View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.regionserver;
20  
21  import java.io.IOException;
22  import java.io.InterruptedIOException;
23  import java.util.ArrayList;
24  import java.util.List;
25  import java.util.ListIterator;
26  import java.util.Map;
27  import java.util.concurrent.Callable;
28  import java.util.concurrent.ExecutionException;
29  import java.util.concurrent.Executors;
30  import java.util.concurrent.Future;
31  import java.util.concurrent.ThreadFactory;
32  import java.util.concurrent.ThreadPoolExecutor;
33  import java.util.concurrent.TimeUnit;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.hadoop.fs.Path;
38  import org.apache.hadoop.hbase.classification.InterfaceAudience;
39  import org.apache.hadoop.hbase.HConstants;
40  import org.apache.hadoop.hbase.HRegionInfo;
41  import org.apache.hadoop.hbase.Server;
42  import org.apache.hadoop.hbase.ServerName;
43  import org.apache.hadoop.hbase.MetaTableAccessor;
44  import org.apache.hadoop.hbase.client.HConnection;
45  import org.apache.hadoop.hbase.client.Mutation;
46  import org.apache.hadoop.hbase.client.Put;
47  import org.apache.hadoop.hbase.coordination.BaseCoordinatedStateManager;
48  import org.apache.hadoop.hbase.coordination.SplitTransactionCoordination;
49  import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionStateTransition.TransitionCode;
50  import org.apache.hadoop.hbase.util.Bytes;
51  import org.apache.hadoop.hbase.util.CancelableProgressable;
52  import org.apache.hadoop.hbase.util.ConfigUtil;
53  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
54  import org.apache.hadoop.hbase.util.FSUtils;
55  import org.apache.hadoop.hbase.util.HasThread;
56  import org.apache.hadoop.hbase.util.Pair;
57  import org.apache.hadoop.hbase.util.PairOfSameType;
58  import org.apache.zookeeper.KeeperException;
59  
60  import com.google.common.util.concurrent.ThreadFactoryBuilder;
61  
62  @InterfaceAudience.Private
63  public class SplitTransactionImpl implements SplitTransaction {
64    private static final Log LOG = LogFactory.getLog(SplitTransaction.class);
65  
66    /*
67     * Region to split
68     */
69    private final HRegion parent;
70    private HRegionInfo hri_a;
71    private HRegionInfo hri_b;
72    private long fileSplitTimeout = 30000;
73    public SplitTransactionCoordination.SplitTransactionDetails std;
74    boolean useZKForAssignment;
75  
76    /*
77     * Row to split around
78     */
79    private final byte [] splitrow;
80  
81    /*
82     * Transaction state for listener, only valid during execute and
83     * rollback
84     */
85    private SplitTransactionPhase currentPhase = SplitTransactionPhase.STARTED;
86    private Server server;
87    private RegionServerServices rsServices;
88  
89    public static class JournalEntryImpl implements JournalEntry {
90      private SplitTransactionPhase type;
91      private long timestamp;
92  
93      public JournalEntryImpl(SplitTransactionPhase type) {
94        this(type, EnvironmentEdgeManager.currentTime());
95      }
96  
97      public JournalEntryImpl(SplitTransactionPhase type, long timestamp) {
98        this.type = type;
99        this.timestamp = timestamp;
100     }
101 
102     @Override
103     public String toString() {
104       StringBuilder sb = new StringBuilder();
105       sb.append(type);
106       sb.append(" at ");
107       sb.append(timestamp);
108       return sb.toString();
109     }
110 
111     @Override
112     public SplitTransactionPhase getPhase() {
113       return type;
114     }
115 
116     @Override
117     public long getTimeStamp() {
118       return timestamp;
119     }
120   }
121 
122   /*
123    * Journal of how far the split transaction has progressed.
124    */
125   private final List<JournalEntry> journal = new ArrayList<JournalEntry>();
126 
127   /**
128    * Listeners
129    */
130   private final ArrayList<TransactionListener> listeners = new ArrayList<TransactionListener>();
131 
132   /**
133    * Constructor
134    * @param r Region to split
135    * @param splitrow Row to split around
136    */
137   public SplitTransactionImpl(final Region r, final byte [] splitrow) {
138     this.parent = (HRegion)r;
139     this.splitrow = splitrow;
140     this.journal.add(new JournalEntryImpl(SplitTransactionPhase.STARTED));
141     useZKForAssignment = ConfigUtil.useZKForAssignment(parent.getBaseConf());
142   }
143 
144   private void transition(SplitTransactionPhase nextPhase) throws IOException {
145     transition(nextPhase, false);
146   }
147 
148   private void transition(SplitTransactionPhase nextPhase, boolean isRollback)
149       throws IOException {
150     if (!isRollback) {
151       // Add to the journal first, because if the listener throws an exception
152       // we need to roll back starting at 'nextPhase'
153       this.journal.add(new JournalEntryImpl(nextPhase));
154     }
155     for (int i = 0; i < listeners.size(); i++) {
156       TransactionListener listener = listeners.get(i);
157       if (!isRollback) {
158         listener.transition(this, currentPhase, nextPhase);
159       } else {
160         listener.rollback(this, currentPhase, nextPhase);
161       }
162     }
163     currentPhase = nextPhase;
164   }
165 
166   /**
167    * Does checks on split inputs.
168    * @return <code>true</code> if the region is splittable else
169    * <code>false</code> if it is not (e.g. its already closed, etc.).
170    */
171   public boolean prepare() throws IOException {
172     if (!this.parent.isSplittable()) return false;
173     // Split key can be null if this region is unsplittable; i.e. has refs.
174     if (this.splitrow == null) return false;
175     HRegionInfo hri = this.parent.getRegionInfo();
176     parent.prepareToSplit();
177     // Check splitrow.
178     byte [] startKey = hri.getStartKey();
179     byte [] endKey = hri.getEndKey();
180     if (Bytes.equals(startKey, splitrow) ||
181         !this.parent.getRegionInfo().containsRow(splitrow)) {
182       LOG.info("Split row is not inside region key range or is equal to " +
183           "startkey: " + Bytes.toStringBinary(this.splitrow));
184       return false;
185     }
186     long rid = getDaughterRegionIdTimestamp(hri);
187     this.hri_a = new HRegionInfo(hri.getTable(), startKey, this.splitrow, false, rid);
188     this.hri_b = new HRegionInfo(hri.getTable(), this.splitrow, endKey, false, rid);
189 
190     transition(SplitTransactionPhase.PREPARED);
191 
192     return true;
193   }
194 
195   /**
196    * Calculate daughter regionid to use.
197    * @param hri Parent {@link HRegionInfo}
198    * @return Daughter region id (timestamp) to use.
199    */
200   private static long getDaughterRegionIdTimestamp(final HRegionInfo hri) {
201     long rid = EnvironmentEdgeManager.currentTime();
202     // Regionid is timestamp.  Can't be less than that of parent else will insert
203     // at wrong location in hbase:meta (See HBASE-710).
204     if (rid < hri.getRegionId()) {
205       LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() +
206         " but current time here is " + rid);
207       rid = hri.getRegionId() + 1;
208     }
209     return rid;
210   }
211 
212   private static IOException closedByOtherException = new IOException(
213       "Failed to close region: already closed by another thread");
214 
215   /**
216    * Prepare the regions and region files.
217    * @param server Hosting server instance.  Can be null when testing (won't try
218    * and update in zk if a null server)
219    * @param services Used to online/offline regions.
220    * @throws IOException If thrown, transaction failed.
221    *    Call {@link #rollback(Server, RegionServerServices)}
222    * @return Regions created
223    */
224   /* package */PairOfSameType<Region> createDaughters(final Server server,
225       final RegionServerServices services) throws IOException {
226     LOG.info("Starting split of region " + this.parent);
227     if ((server != null && server.isStopped()) ||
228         (services != null && services.isStopping())) {
229       throw new IOException("Server is stopped or stopping");
230     }
231     assert !this.parent.lock.writeLock().isHeldByCurrentThread():
232       "Unsafe to hold write lock while performing RPCs";
233 
234     transition(SplitTransactionPhase.BEFORE_PRE_SPLIT_HOOK);
235 
236     // Coprocessor callback
237     if (this.parent.getCoprocessorHost() != null) {
238       // TODO: Remove one of these
239       this.parent.getCoprocessorHost().preSplit();
240       this.parent.getCoprocessorHost().preSplit(this.splitrow);
241     }
242 
243     transition(SplitTransactionPhase.AFTER_PRE_SPLIT_HOOK);
244 
245     // If true, no cluster to write meta edits to or to update znodes in.
246     boolean testing = server == null? true:
247         server.getConfiguration().getBoolean("hbase.testing.nocluster", false);
248     this.fileSplitTimeout = testing ? this.fileSplitTimeout :
249         server.getConfiguration().getLong("hbase.regionserver.fileSplitTimeout",
250           this.fileSplitTimeout);
251 
252     PairOfSameType<Region> daughterRegions = stepsBeforePONR(server, services, testing);
253 
254     List<Mutation> metaEntries = new ArrayList<Mutation>();
255     if (this.parent.getCoprocessorHost() != null) {
256       if (this.parent.getCoprocessorHost().
257           preSplitBeforePONR(this.splitrow, metaEntries)) {
258         throw new IOException("Coprocessor bypassing region "
259             + this.parent.getRegionInfo().getRegionNameAsString() + " split.");
260       }
261       try {
262         for (Mutation p : metaEntries) {
263           HRegionInfo.parseRegionName(p.getRow());
264         }
265       } catch (IOException e) {
266         LOG.error("Row key of mutation from coprossor is not parsable as region name."
267             + "Mutations from coprocessor should only for hbase:meta table.");
268         throw e;
269       }
270     }
271 
272     // This is the point of no return.  Adding subsequent edits to .META. as we
273     // do below when we do the daughter opens adding each to .META. can fail in
274     // various interesting ways the most interesting of which is a timeout
275     // BUT the edits all go through (See HBASE-3872).  IF we reach the PONR
276     // then subsequent failures need to crash out this regionserver; the
277     // server shutdown processing should be able to fix-up the incomplete split.
278     // The offlined parent will have the daughters as extra columns.  If
279     // we leave the daughter regions in place and do not remove them when we
280     // crash out, then they will have their references to the parent in place
281     // still and the server shutdown fixup of .META. will point to these
282     // regions.
283     // We should add PONR JournalEntry before offlineParentInMeta,so even if
284     // OfflineParentInMeta timeout,this will cause regionserver exit,and then
285     // master ServerShutdownHandler will fix daughter & avoid data loss. (See
286     // HBase-4562).
287     transition(SplitTransactionPhase.PONR);
288 
289     // Edit parent in meta.  Offlines parent region and adds splita and splitb
290     // as an atomic update. See HBASE-7721. This update to META makes the region
291     // will determine whether the region is split or not in case of failures.
292     // If it is successful, master will roll-forward, if not, master will rollback
293     // and assign the parent region.
294     if (!testing && useZKForAssignment) {
295       if (metaEntries == null || metaEntries.isEmpty()) {
296         MetaTableAccessor.splitRegion(server.getConnection(),
297           parent.getRegionInfo(), daughterRegions.getFirst().getRegionInfo(),
298           daughterRegions.getSecond().getRegionInfo(), server.getServerName(),
299           parent.getTableDesc().getRegionReplication());
300       } else {
301         offlineParentInMetaAndputMetaEntries(server.getConnection(),
302           parent.getRegionInfo(), daughterRegions.getFirst().getRegionInfo(), daughterRegions
303               .getSecond().getRegionInfo(), server.getServerName(), metaEntries,
304               parent.getTableDesc().getRegionReplication());
305       }
306     } else if (services != null && !useZKForAssignment) {
307       if (!services.reportRegionStateTransition(TransitionCode.SPLIT_PONR,
308           parent.getRegionInfo(), hri_a, hri_b)) {
309         // Passed PONR, let SSH clean it up
310         throw new IOException("Failed to notify master that split passed PONR: "
311           + parent.getRegionInfo().getRegionNameAsString());
312       }
313     }
314     return daughterRegions;
315   }
316 
317   public PairOfSameType<Region> stepsBeforePONR(final Server server,
318       final RegionServerServices services, boolean testing) throws IOException {
319 
320     if (useCoordinatedStateManager(server)) {
321       if (std == null) {
322         std =
323             ((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
324                 .getSplitTransactionCoordination().getDefaultDetails();
325       }
326       ((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
327           .getSplitTransactionCoordination().startSplitTransaction(parent, server.getServerName(),
328             hri_a, hri_b);
329     } else if (services != null && !useZKForAssignment) {
330       if (!services.reportRegionStateTransition(TransitionCode.READY_TO_SPLIT,
331           parent.getRegionInfo(), hri_a, hri_b)) {
332         throw new IOException("Failed to get ok from master to split "
333           + parent.getRegionInfo().getRegionNameAsString());
334       }
335     }
336 
337     transition(SplitTransactionPhase.SET_SPLITTING);
338 
339     if (useCoordinatedStateManager(server)) {
340       ((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
341           .getSplitTransactionCoordination().waitForSplitTransaction(services, parent, hri_a,
342             hri_b, std);
343     }
344 
345     this.parent.getRegionFileSystem().createSplitsDir();
346 
347     transition(SplitTransactionPhase.CREATE_SPLIT_DIR);
348 
349     Map<byte[], List<StoreFile>> hstoreFilesToSplit = null;
350     Exception exceptionToThrow = null;
351     try{
352       hstoreFilesToSplit = this.parent.close(false);
353     } catch (Exception e) {
354       exceptionToThrow = e;
355     }
356     if (exceptionToThrow == null && hstoreFilesToSplit == null) {
357       // The region was closed by a concurrent thread.  We can't continue
358       // with the split, instead we must just abandon the split.  If we
359       // reopen or split this could cause problems because the region has
360       // probably already been moved to a different server, or is in the
361       // process of moving to a different server.
362       exceptionToThrow = closedByOtherException;
363     }
364     if (exceptionToThrow != closedByOtherException) {
365       transition(SplitTransactionPhase.CLOSED_PARENT_REGION);
366     }
367     if (exceptionToThrow != null) {
368       if (exceptionToThrow instanceof IOException) throw (IOException)exceptionToThrow;
369       throw new IOException(exceptionToThrow);
370     }
371     if (!testing) {
372       services.removeFromOnlineRegions(this.parent, null);
373     }
374 
375     transition(SplitTransactionPhase.OFFLINED_PARENT);
376 
377     // TODO: If splitStoreFiles were multithreaded would we complete steps in
378     // less elapsed time?  St.Ack 20100920
379     //
380     // splitStoreFiles creates daughter region dirs under the parent splits dir
381     // Nothing to unroll here if failure -- clean up of CREATE_SPLIT_DIR will
382     // clean this up.
383     Pair<Integer, Integer> expectedReferences = splitStoreFiles(hstoreFilesToSplit);
384 
385     // Log to the journal that we are creating region A, the first daughter
386     // region.  We could fail halfway through.  If we do, we could have left
387     // stuff in fs that needs cleanup -- a storefile or two.  Thats why we
388     // add entry to journal BEFORE rather than AFTER the change.
389     transition(SplitTransactionPhase.STARTED_REGION_A_CREATION);
390 
391     assertReferenceFileCount(expectedReferences.getFirst(),
392         this.parent.getRegionFileSystem().getSplitsDir(this.hri_a));
393     Region a = this.parent.createDaughterRegionFromSplits(this.hri_a);
394     assertReferenceFileCount(expectedReferences.getFirst(),
395         new Path(this.parent.getRegionFileSystem().getTableDir(), this.hri_a.getEncodedName()));
396 
397     // Ditto
398     transition(SplitTransactionPhase.STARTED_REGION_B_CREATION);
399 
400     assertReferenceFileCount(expectedReferences.getSecond(),
401         this.parent.getRegionFileSystem().getSplitsDir(this.hri_b));
402     Region b = this.parent.createDaughterRegionFromSplits(this.hri_b);
403     assertReferenceFileCount(expectedReferences.getSecond(),
404         new Path(this.parent.getRegionFileSystem().getTableDir(), this.hri_b.getEncodedName()));
405 
406     return new PairOfSameType<Region>(a, b);
407   }
408 
409   void assertReferenceFileCount(int expectedReferenceFileCount, Path dir)
410       throws IOException {
411     if (expectedReferenceFileCount != 0 &&
412         expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(parent.getFilesystem(),
413           dir)) {
414       throw new IOException("Failing split. Expected reference file count isn't equal.");
415     }
416   }
417 
418   /**
419    * Perform time consuming opening of the daughter regions.
420    * @param server Hosting server instance.  Can be null when testing
421    * @param services Used to online/offline regions.
422    * @param a first daughter region
423    * @param a second daughter region
424    * @throws IOException If thrown, transaction failed.
425    *          Call {@link #rollback(Server, RegionServerServices)}
426    */
427   /* package */void openDaughters(final Server server,
428       final RegionServerServices services, Region a, Region b)
429       throws IOException {
430     boolean stopped = server != null && server.isStopped();
431     boolean stopping = services != null && services.isStopping();
432     // TODO: Is this check needed here?
433     if (stopped || stopping) {
434       LOG.info("Not opening daughters " +
435           b.getRegionInfo().getRegionNameAsString() +
436           " and " +
437           a.getRegionInfo().getRegionNameAsString() +
438           " because stopping=" + stopping + ", stopped=" + stopped);
439     } else {
440       // Open daughters in parallel.
441       DaughterOpener aOpener = new DaughterOpener(server, (HRegion)a);
442       DaughterOpener bOpener = new DaughterOpener(server, (HRegion)b);
443       aOpener.start();
444       bOpener.start();
445       try {
446         aOpener.join();
447         if (aOpener.getException() == null) {
448           transition(SplitTransactionPhase.OPENED_REGION_A);
449         }
450         bOpener.join();
451         if (bOpener.getException() == null) {
452           transition(SplitTransactionPhase.OPENED_REGION_B);
453         }
454       } catch (InterruptedException e) {
455         throw (InterruptedIOException)new InterruptedIOException().initCause(e);
456       }
457       if (aOpener.getException() != null) {
458         throw new IOException("Failed " +
459           aOpener.getName(), aOpener.getException());
460       }
461       if (bOpener.getException() != null) {
462         throw new IOException("Failed " +
463           bOpener.getName(), bOpener.getException());
464       }
465       if (services != null) {
466         try {
467           if (useZKForAssignment) {
468             // add 2nd daughter first (see HBASE-4335)
469             services.postOpenDeployTasks(b);
470           } else if (!services.reportRegionStateTransition(TransitionCode.SPLIT,
471               parent.getRegionInfo(), hri_a, hri_b)) {
472             throw new IOException("Failed to report split region to master: "
473               + parent.getRegionInfo().getShortNameToLog());
474           }
475           // Should add it to OnlineRegions
476           services.addToOnlineRegions(b);
477           if (useZKForAssignment) {
478             services.postOpenDeployTasks(a);
479           }
480           services.addToOnlineRegions(a);
481         } catch (KeeperException ke) {
482           throw new IOException(ke);
483         }
484       }
485     }
486   }
487 
488   /**
489    * Run the transaction.
490    * @param server Hosting server instance.  Can be null when testing
491    * @param services Used to online/offline regions.
492    * @throws IOException If thrown, transaction failed.
493    *          Call {@link #rollback(Server, RegionServerServices)}
494    * @return Regions created
495    * @throws IOException
496    * @see #rollback(Server, RegionServerServices)
497    */
498   public PairOfSameType<Region> execute(final Server server,
499       final RegionServerServices services) throws IOException {
500     this.server = server;
501     this.rsServices = services;
502     useZKForAssignment = server == null ? true :
503       ConfigUtil.useZKForAssignment(server.getConfiguration());
504     if (useCoordinatedStateManager(server)) {
505       std =
506           ((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
507               .getSplitTransactionCoordination().getDefaultDetails();
508     }
509     PairOfSameType<Region> regions = createDaughters(server, services);
510     if (this.parent.getCoprocessorHost() != null) {
511       this.parent.getCoprocessorHost().preSplitAfterPONR();
512     }
513     regions = stepsAfterPONR(server, services, regions);
514 
515     transition(SplitTransactionPhase.COMPLETED);
516 
517     return regions;
518   }
519 
520   public PairOfSameType<Region> stepsAfterPONR(final Server server,
521       final RegionServerServices services, PairOfSameType<Region> regions)
522       throws IOException {
523     openDaughters(server, services, regions.getFirst(), regions.getSecond());
524     if (useCoordinatedStateManager(server)) {
525       ((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
526           .getSplitTransactionCoordination().completeSplitTransaction(services, regions.getFirst(),
527             regions.getSecond(), std, parent);
528     }
529 
530     transition(SplitTransactionPhase.BEFORE_POST_SPLIT_HOOK);
531 
532     // Coprocessor callback
533     if (parent.getCoprocessorHost() != null) {
534       parent.getCoprocessorHost().postSplit(regions.getFirst(), regions.getSecond());
535     }
536 
537     transition(SplitTransactionPhase.AFTER_POST_SPLIT_HOOK);
538 
539     return regions;
540   }
541 
542   private void offlineParentInMetaAndputMetaEntries(HConnection hConnection,
543       HRegionInfo parent, HRegionInfo splitA, HRegionInfo splitB,
544       ServerName serverName, List<Mutation> metaEntries, int regionReplication)
545           throws IOException {
546     List<Mutation> mutations = metaEntries;
547     HRegionInfo copyOfParent = new HRegionInfo(parent);
548     copyOfParent.setOffline(true);
549     copyOfParent.setSplit(true);
550 
551     //Put for parent
552     Put putParent = MetaTableAccessor.makePutFromRegionInfo(copyOfParent);
553     MetaTableAccessor.addDaughtersToPut(putParent, splitA, splitB);
554     mutations.add(putParent);
555     
556     //Puts for daughters
557     Put putA = MetaTableAccessor.makePutFromRegionInfo(splitA);
558     Put putB = MetaTableAccessor.makePutFromRegionInfo(splitB);
559 
560     addLocation(putA, serverName, 1); //these are new regions, openSeqNum = 1 is fine.
561     addLocation(putB, serverName, 1);
562     mutations.add(putA);
563     mutations.add(putB);
564 
565     // Add empty locations for region replicas of daughters so that number of replicas can be
566     // cached whenever the primary region is looked up from meta
567     for (int i = 1; i < regionReplication; i++) {
568       addEmptyLocation(putA, i);
569       addEmptyLocation(putB, i);
570     }
571 
572     MetaTableAccessor.mutateMetaTable(hConnection, mutations);
573   }
574 
575   private static Put addEmptyLocation(final Put p, int replicaId){
576     p.addImmutable(HConstants.CATALOG_FAMILY, MetaTableAccessor.getServerColumn(replicaId), null);
577     p.addImmutable(HConstants.CATALOG_FAMILY, MetaTableAccessor.getStartCodeColumn(replicaId),
578       null);
579     p.addImmutable(HConstants.CATALOG_FAMILY, MetaTableAccessor.getSeqNumColumn(replicaId), null);
580     return p;
581   }
582 
583   public Put addLocation(final Put p, final ServerName sn, long openSeqNum) {
584     p.addImmutable(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER,
585       Bytes.toBytes(sn.getHostAndPort()));
586     p.addImmutable(HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER,
587       Bytes.toBytes(sn.getStartcode()));
588     p.addImmutable(HConstants.CATALOG_FAMILY, HConstants.SEQNUM_QUALIFIER,
589         Bytes.toBytes(openSeqNum));
590     return p;
591   }
592 
593   /*
594    * Open daughter region in its own thread.
595    * If we fail, abort this hosting server.
596    */
597   class DaughterOpener extends HasThread {
598     private final Server server;
599     private final HRegion r;
600     private Throwable t = null;
601 
602     DaughterOpener(final Server s, final HRegion r) {
603       super((s == null? "null-services": s.getServerName()) +
604         "-daughterOpener=" + r.getRegionInfo().getEncodedName());
605       setDaemon(true);
606       this.server = s;
607       this.r = r;
608     }
609 
610     /**
611      * @return Null if open succeeded else exception that causes us fail open.
612      * Call it after this thread exits else you may get wrong view on result.
613      */
614     Throwable getException() {
615       return this.t;
616     }
617 
618     @Override
619     public void run() {
620       try {
621         openDaughterRegion(this.server, r);
622       } catch (Throwable t) {
623         this.t = t;
624       }
625     }
626   }
627 
628   /**
629    * Open daughter regions, add them to online list and update meta.
630    * @param server
631    * @param daughter
632    * @throws IOException
633    * @throws KeeperException
634    */
635   void openDaughterRegion(final Server server, final HRegion daughter)
636   throws IOException, KeeperException {
637     HRegionInfo hri = daughter.getRegionInfo();
638     LoggingProgressable reporter = server == null ? null
639         : new LoggingProgressable(hri, server.getConfiguration().getLong(
640             "hbase.regionserver.split.daughter.open.log.interval", 10000));
641     daughter.openHRegion(reporter);
642   }
643 
644   static class LoggingProgressable implements CancelableProgressable {
645     private final HRegionInfo hri;
646     private long lastLog = -1;
647     private final long interval;
648 
649     LoggingProgressable(final HRegionInfo hri, final long interval) {
650       this.hri = hri;
651       this.interval = interval;
652     }
653 
654     @Override
655     public boolean progress() {
656       long now = EnvironmentEdgeManager.currentTime();
657       if (now - lastLog > this.interval) {
658         LOG.info("Opening " + this.hri.getRegionNameAsString());
659         this.lastLog = now;
660       }
661       return true;
662     }
663   }
664 
665   private boolean useCoordinatedStateManager(final Server server) {
666     return server != null && useZKForAssignment && server.getCoordinatedStateManager() != null;
667   }
668 
669   /**
670    * Creates reference files for top and bottom half of the
671    * @param hstoreFilesToSplit map of store files to create half file references for.
672    * @return the number of reference files that were created.
673    * @throws IOException
674    */
675   private Pair<Integer, Integer> splitStoreFiles(
676       final Map<byte[], List<StoreFile>> hstoreFilesToSplit)
677       throws IOException {
678     if (hstoreFilesToSplit == null) {
679       // Could be null because close didn't succeed -- for now consider it fatal
680       throw new IOException("Close returned empty list of StoreFiles");
681     }
682     // The following code sets up a thread pool executor with as many slots as
683     // there's files to split. It then fires up everything, waits for
684     // completion and finally checks for any exception
685     int nbFiles = hstoreFilesToSplit.size();
686     if (nbFiles == 0) {
687       // no file needs to be splitted.
688       return new Pair<Integer, Integer>(0,0);
689     }
690     LOG.info("Preparing to split " + nbFiles + " storefiles for region " + this.parent);
691     ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
692     builder.setNameFormat("StoreFileSplitter-%1$d");
693     ThreadFactory factory = builder.build();
694     ThreadPoolExecutor threadPool =
695       (ThreadPoolExecutor) Executors.newFixedThreadPool(nbFiles, factory);
696     List<Future<Pair<Path,Path>>> futures = new ArrayList<Future<Pair<Path,Path>>> (nbFiles);
697 
698     // Split each store file.
699     for (Map.Entry<byte[], List<StoreFile>> entry: hstoreFilesToSplit.entrySet()) {
700       for (StoreFile sf: entry.getValue()) {
701         StoreFileSplitter sfs = new StoreFileSplitter(entry.getKey(), sf);
702         futures.add(threadPool.submit(sfs));
703       }
704     }
705     // Shutdown the pool
706     threadPool.shutdown();
707 
708     // Wait for all the tasks to finish
709     try {
710       boolean stillRunning = !threadPool.awaitTermination(
711           this.fileSplitTimeout, TimeUnit.MILLISECONDS);
712       if (stillRunning) {
713         threadPool.shutdownNow();
714         // wait for the thread to shutdown completely.
715         while (!threadPool.isTerminated()) {
716           Thread.sleep(50);
717         }
718         throw new IOException("Took too long to split the" +
719             " files and create the references, aborting split");
720       }
721     } catch (InterruptedException e) {
722       throw (InterruptedIOException)new InterruptedIOException().initCause(e);
723     }
724 
725     int created_a = 0;
726     int created_b = 0;
727     // Look for any exception
728     for (Future<Pair<Path, Path>> future : futures) {
729       try {
730         Pair<Path, Path> p = future.get();
731         created_a += p.getFirst() != null ? 1 : 0;
732         created_b += p.getSecond() != null ? 1 : 0;
733       } catch (InterruptedException e) {
734         throw (InterruptedIOException) new InterruptedIOException().initCause(e);
735       } catch (ExecutionException e) {
736         throw new IOException(e);
737       }
738     }
739 
740     if (LOG.isDebugEnabled()) {
741       LOG.debug("Split storefiles for region " + this.parent + " Daugther A: " + created_a
742           + " storefiles, Daugther B: " + created_b + " storefiles.");
743     }
744     return new Pair<Integer, Integer>(created_a, created_b);
745   }
746 
747   private Pair<Path, Path> splitStoreFile(final byte[] family, final StoreFile sf)
748       throws IOException {
749     HRegionFileSystem fs = this.parent.getRegionFileSystem();
750     String familyName = Bytes.toString(family);
751 
752     Path path_a =
753         fs.splitStoreFile(this.hri_a, familyName, sf, this.splitrow, false,
754           this.parent.getSplitPolicy());
755     Path path_b =
756         fs.splitStoreFile(this.hri_b, familyName, sf, this.splitrow, true,
757           this.parent.getSplitPolicy());
758     return new Pair<Path,Path>(path_a, path_b);
759   }
760 
761   /**
762    * Utility class used to do the file splitting / reference writing
763    * in parallel instead of sequentially.
764    */
765   class StoreFileSplitter implements Callable<Pair<Path,Path>> {
766     private final byte[] family;
767     private final StoreFile sf;
768 
769     /**
770      * Constructor that takes what it needs to split
771      * @param family Family that contains the store file
772      * @param sf which file
773      */
774     public StoreFileSplitter(final byte[] family, final StoreFile sf) {
775       this.sf = sf;
776       this.family = family;
777     }
778 
779     public Pair<Path,Path> call() throws IOException {
780       return splitStoreFile(family, sf);
781     }
782   }
783 
784   /**
785    * @param server Hosting server instance (May be null when testing).
786    * @param services
787    * @throws IOException If thrown, rollback failed.  Take drastic action.
788    * @return True if we successfully rolled back, false if we got to the point
789    * of no return and so now need to abort the server to minimize damage.
790    */
791   @SuppressWarnings("deprecation")
792   public boolean rollback(final Server server, final RegionServerServices services)
793   throws IOException {
794     // Coprocessor callback
795     if (this.parent.getCoprocessorHost() != null) {
796       this.parent.getCoprocessorHost().preRollBackSplit();
797     }
798 
799     boolean result = true;
800     ListIterator<JournalEntry> iterator =
801       this.journal.listIterator(this.journal.size());
802     // Iterate in reverse.
803     while (iterator.hasPrevious()) {
804       JournalEntry je = iterator.previous();
805 
806       transition(je.getPhase(), true);
807 
808       switch(je.getPhase()) {
809 
810       case SET_SPLITTING:
811         if (useCoordinatedStateManager(server) && server instanceof HRegionServer) {
812           ((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
813               .getSplitTransactionCoordination().clean(this.parent.getRegionInfo());
814         } else if (services != null && !useZKForAssignment
815             && !services.reportRegionStateTransition(TransitionCode.SPLIT_REVERTED,
816                 parent.getRegionInfo(), hri_a, hri_b)) {
817           return false;
818         }
819         break;
820 
821       case CREATE_SPLIT_DIR:
822         this.parent.writestate.writesEnabled = true;
823         this.parent.getRegionFileSystem().cleanupSplitsDir();
824         break;
825 
826       case CLOSED_PARENT_REGION:
827         try {
828           // So, this returns a seqid but if we just closed and then reopened, we
829           // should be ok. On close, we flushed using sequenceid obtained from
830           // hosting regionserver so no need to propagate the sequenceid returned
831           // out of initialize below up into regionserver as we normally do.
832           // TODO: Verify.
833           this.parent.initialize();
834         } catch (IOException e) {
835           LOG.error("Failed rollbacking CLOSED_PARENT_REGION of region " +
836             this.parent.getRegionInfo().getRegionNameAsString(), e);
837           throw new RuntimeException(e);
838         }
839         break;
840 
841       case STARTED_REGION_A_CREATION:
842         this.parent.getRegionFileSystem().cleanupDaughterRegion(this.hri_a);
843         break;
844 
845       case STARTED_REGION_B_CREATION:
846         this.parent.getRegionFileSystem().cleanupDaughterRegion(this.hri_b);
847         break;
848 
849       case OFFLINED_PARENT:
850         if (services != null) services.addToOnlineRegions(this.parent);
851         break;
852 
853       case PONR:
854         // We got to the point-of-no-return so we need to just abort. Return
855         // immediately.  Do not clean up created daughter regions.  They need
856         // to be in place so we don't delete the parent region mistakenly.
857         // See HBASE-3872.
858         return false;
859 
860       // Informational only cases
861       case STARTED:
862       case PREPARED:
863       case BEFORE_PRE_SPLIT_HOOK:
864       case AFTER_PRE_SPLIT_HOOK:
865       case BEFORE_POST_SPLIT_HOOK:
866       case AFTER_POST_SPLIT_HOOK:
867       case OPENED_REGION_A:
868       case OPENED_REGION_B:
869       case COMPLETED:
870         break;
871 
872       default:
873         throw new RuntimeException("Unhandled journal entry: " + je);
874       }
875     }
876     // Coprocessor callback
877     if (this.parent.getCoprocessorHost() != null) {
878       this.parent.getCoprocessorHost().postRollBackSplit();
879     }
880     return result;
881   }
882 
883   HRegionInfo getFirstDaughter() {
884     return hri_a;
885   }
886 
887   HRegionInfo getSecondDaughter() {
888     return hri_b;
889   }
890 
891   @Override
892   public List<JournalEntry> getJournal() {
893     return journal;
894   }
895 
896   @Override
897   public SplitTransaction registerTransactionListener(TransactionListener listener) {
898     listeners.add(listener);
899     return this;
900   }
901 
902   @Override
903   public Server getServer() {
904     return server;
905   }
906 
907   @Override
908   public RegionServerServices getRegionServerServices() {
909     return rsServices;
910   }
911 }