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.EOFException;
22  import java.io.FileNotFoundException;
23  import java.io.IOException;
24  import java.io.InterruptedIOException;
25  import java.io.UnsupportedEncodingException;
26  import java.lang.reflect.Constructor;
27  import java.text.ParseException;
28  import java.util.AbstractList;
29  import java.util.ArrayList;
30  import java.util.Arrays;
31  import java.util.Collection;
32  import java.util.Collections;
33  import java.util.HashMap;
34  import java.util.HashSet;
35  import java.util.Iterator;
36  import java.util.List;
37  import java.util.Map;
38  import java.util.Map.Entry;
39  import java.util.NavigableMap;
40  import java.util.NavigableSet;
41  import java.util.RandomAccess;
42  import java.util.Set;
43  import java.util.TreeMap;
44  import java.util.concurrent.Callable;
45  import java.util.concurrent.CompletionService;
46  import java.util.concurrent.ConcurrentHashMap;
47  import java.util.concurrent.ConcurrentMap;
48  import java.util.concurrent.ConcurrentSkipListMap;
49  import java.util.concurrent.CountDownLatch;
50  import java.util.concurrent.ExecutionException;
51  import java.util.concurrent.ExecutorCompletionService;
52  import java.util.concurrent.ExecutorService;
53  import java.util.concurrent.Executors;
54  import java.util.concurrent.Future;
55  import java.util.concurrent.FutureTask;
56  import java.util.concurrent.ThreadFactory;
57  import java.util.concurrent.ThreadPoolExecutor;
58  import java.util.concurrent.TimeUnit;
59  import java.util.concurrent.TimeoutException;
60  import java.util.concurrent.atomic.AtomicBoolean;
61  import java.util.concurrent.atomic.AtomicInteger;
62  import java.util.concurrent.atomic.AtomicLong;
63  import java.util.concurrent.locks.Lock;
64  import java.util.concurrent.locks.ReentrantReadWriteLock;
65  
66  import org.apache.commons.lang.RandomStringUtils;
67  import org.apache.commons.logging.Log;
68  import org.apache.commons.logging.LogFactory;
69  import org.apache.hadoop.conf.Configuration;
70  import org.apache.hadoop.fs.FileStatus;
71  import org.apache.hadoop.fs.FileSystem;
72  import org.apache.hadoop.fs.Path;
73  import org.apache.hadoop.hbase.Cell;
74  import org.apache.hadoop.hbase.CellScanner;
75  import org.apache.hadoop.hbase.CellUtil;
76  import org.apache.hadoop.hbase.CompoundConfiguration;
77  import org.apache.hadoop.hbase.DroppedSnapshotException;
78  import org.apache.hadoop.hbase.HBaseConfiguration;
79  import org.apache.hadoop.hbase.HColumnDescriptor;
80  import org.apache.hadoop.hbase.HConstants;
81  import org.apache.hadoop.hbase.HConstants.OperationStatusCode;
82  import org.apache.hadoop.hbase.HDFSBlocksDistribution;
83  import org.apache.hadoop.hbase.HRegionInfo;
84  import org.apache.hadoop.hbase.HTableDescriptor;
85  import org.apache.hadoop.hbase.KeyValue;
86  import org.apache.hadoop.hbase.KeyValueUtil;
87  import org.apache.hadoop.hbase.NamespaceDescriptor;
88  import org.apache.hadoop.hbase.NotServingRegionException;
89  import org.apache.hadoop.hbase.RegionTooBusyException;
90  import org.apache.hadoop.hbase.TableName;
91  import org.apache.hadoop.hbase.Tag;
92  import org.apache.hadoop.hbase.TagType;
93  import org.apache.hadoop.hbase.UnknownScannerException;
94  import org.apache.hadoop.hbase.backup.HFileArchiver;
95  import org.apache.hadoop.hbase.classification.InterfaceAudience;
96  import org.apache.hadoop.hbase.client.Append;
97  import org.apache.hadoop.hbase.client.Delete;
98  import org.apache.hadoop.hbase.client.Durability;
99  import org.apache.hadoop.hbase.client.Get;
100 import org.apache.hadoop.hbase.client.Increment;
101 import org.apache.hadoop.hbase.client.IsolationLevel;
102 import org.apache.hadoop.hbase.client.Mutation;
103 import org.apache.hadoop.hbase.client.Put;
104 import org.apache.hadoop.hbase.client.RegionReplicaUtil;
105 import org.apache.hadoop.hbase.client.Result;
106 import org.apache.hadoop.hbase.client.RowMutations;
107 import org.apache.hadoop.hbase.client.Scan;
108 import org.apache.hadoop.hbase.conf.ConfigurationManager;
109 import org.apache.hadoop.hbase.conf.PropagatingConfigurationObserver;
110 import org.apache.hadoop.hbase.coprocessor.RegionObserver;
111 import org.apache.hadoop.hbase.errorhandling.ForeignExceptionSnare;
112 import org.apache.hadoop.hbase.exceptions.FailedSanityCheckException;
113 import org.apache.hadoop.hbase.exceptions.RegionInRecoveryException;
114 import org.apache.hadoop.hbase.exceptions.UnknownProtocolException;
115 import org.apache.hadoop.hbase.filter.ByteArrayComparable;
116 import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
117 import org.apache.hadoop.hbase.filter.FilterWrapper;
118 import org.apache.hadoop.hbase.filter.IncompatibleFilterException;
119 import org.apache.hadoop.hbase.io.HeapSize;
120 import org.apache.hadoop.hbase.io.TimeRange;
121 import org.apache.hadoop.hbase.io.hfile.BlockCache;
122 import org.apache.hadoop.hbase.io.hfile.CacheConfig;
123 import org.apache.hadoop.hbase.io.hfile.HFile;
124 import org.apache.hadoop.hbase.ipc.CallerDisconnectedException;
125 import org.apache.hadoop.hbase.ipc.RpcCallContext;
126 import org.apache.hadoop.hbase.ipc.RpcServer;
127 import org.apache.hadoop.hbase.monitoring.MonitoredTask;
128 import org.apache.hadoop.hbase.monitoring.TaskMonitor;
129 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
130 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse.CompactionState;
131 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
132 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceCall;
133 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionLoad;
134 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.StoreSequenceId;
135 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
136 import org.apache.hadoop.hbase.protobuf.generated.WALProtos;
137 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
138 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.FlushDescriptor;
139 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.FlushDescriptor.FlushAction;
140 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.FlushDescriptor.StoreFlushDescriptor;
141 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.RegionEventDescriptor;
142 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.RegionEventDescriptor.EventType;
143 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.StoreDescriptor;
144 import org.apache.hadoop.hbase.regionserver.MultiVersionConsistencyControl.WriteEntry;
145 import org.apache.hadoop.hbase.regionserver.ScannerContext.LimitScope;
146 import org.apache.hadoop.hbase.regionserver.ScannerContext.NextState;
147 import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext;
148 import org.apache.hadoop.hbase.regionserver.compactions.CompactionThroughputController;
149 import org.apache.hadoop.hbase.regionserver.compactions.CompactionThroughputControllerFactory;
150 import org.apache.hadoop.hbase.regionserver.compactions.NoLimitCompactionThroughputController;
151 import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
152 import org.apache.hadoop.hbase.regionserver.wal.MetricsWAL;
153 import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
154 import org.apache.hadoop.hbase.regionserver.wal.ReplayHLogKey;
155 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
156 import org.apache.hadoop.hbase.regionserver.wal.WALUtil;
157 import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
158 import org.apache.hadoop.hbase.snapshot.SnapshotManifest;
159 import org.apache.hadoop.hbase.util.ByteStringer;
160 import org.apache.hadoop.hbase.util.Bytes;
161 import org.apache.hadoop.hbase.util.CancelableProgressable;
162 import org.apache.hadoop.hbase.util.ClassSize;
163 import org.apache.hadoop.hbase.util.CompressionTest;
164 import org.apache.hadoop.hbase.util.Counter;
165 import org.apache.hadoop.hbase.util.EncryptionTest;
166 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
167 import org.apache.hadoop.hbase.util.FSTableDescriptors;
168 import org.apache.hadoop.hbase.util.FSUtils;
169 import org.apache.hadoop.hbase.util.HashedBytes;
170 import org.apache.hadoop.hbase.util.Pair;
171 import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
172 import org.apache.hadoop.hbase.util.Threads;
173 import org.apache.hadoop.hbase.wal.WAL;
174 import org.apache.hadoop.hbase.wal.WALFactory;
175 import org.apache.hadoop.hbase.wal.WALKey;
176 import org.apache.hadoop.hbase.wal.WALSplitter;
177 import org.apache.hadoop.hbase.wal.WALSplitter.MutationReplay;
178 import org.apache.hadoop.io.MultipleIOException;
179 import org.apache.hadoop.util.StringUtils;
180 import org.apache.htrace.Trace;
181 import org.apache.htrace.TraceScope;
182 
183 import com.google.common.annotations.VisibleForTesting;
184 import com.google.common.base.Optional;
185 import com.google.common.base.Preconditions;
186 import com.google.common.collect.Lists;
187 import com.google.common.collect.Maps;
188 import com.google.common.io.Closeables;
189 import com.google.protobuf.ByteString;
190 import com.google.protobuf.Descriptors;
191 import com.google.protobuf.Message;
192 import com.google.protobuf.RpcCallback;
193 import com.google.protobuf.RpcController;
194 import com.google.protobuf.Service;
195 import com.google.protobuf.TextFormat;
196 
197 @InterfaceAudience.Private
198 public class HRegion implements HeapSize, PropagatingConfigurationObserver, Region {
199   public static final Log LOG = LogFactory.getLog(HRegion.class);
200 
201   public static final String LOAD_CFS_ON_DEMAND_CONFIG_KEY =
202       "hbase.hregion.scan.loadColumnFamiliesOnDemand";
203 
204   /**
205    * This is the global default value for durability. All tables/mutations not
206    * defining a durability or using USE_DEFAULT will default to this value.
207    */
208   private static final Durability DEFAULT_DURABILITY = Durability.SYNC_WAL;
209 
210   final AtomicBoolean closed = new AtomicBoolean(false);
211   /* Closing can take some time; use the closing flag if there is stuff we don't
212    * want to do while in closing state; e.g. like offer this region up to the
213    * master as a region to close if the carrying regionserver is overloaded.
214    * Once set, it is never cleared.
215    */
216   final AtomicBoolean closing = new AtomicBoolean(false);
217 
218   /**
219    * The max sequence id of flushed data on this region.  Used doing some rough calculations on
220    * whether time to flush or not.
221    */
222   private volatile long maxFlushedSeqId = HConstants.NO_SEQNUM;
223 
224   /**
225    * Record the sequence id of last flush operation.
226    */
227   private volatile long lastFlushOpSeqId = HConstants.NO_SEQNUM;
228   /**
229    * Region scoped edit sequence Id. Edits to this region are GUARANTEED to appear in the WAL
230    * file in this sequence id's order; i.e. edit #2 will be in the WAL after edit #1.
231    * Its default value is -1L. This default is used as a marker to indicate
232    * that the region hasn't opened yet. Once it is opened, it is set to the derived
233    * {@link #openSeqNum}, the largest sequence id of all hfiles opened under this Region.
234    *
235    * <p>Control of this sequence is handed off to the WAL implementation.  It is responsible
236    * for tagging edits with the correct sequence id since it is responsible for getting the
237    * edits into the WAL files. It controls updating the sequence id value.  DO NOT UPDATE IT
238    * OUTSIDE OF THE WAL.  The value you get will not be what you think it is.
239    */
240   private final AtomicLong sequenceId = new AtomicLong(-1L);
241 
242   /**
243    * The sequence id of the last replayed open region event from the primary region. This is used
244    * to skip entries before this due to the possibility of replay edits coming out of order from
245    * replication.
246    */
247   protected volatile long lastReplayedOpenRegionSeqId = -1L;
248   protected volatile long lastReplayedCompactionSeqId = -1L;
249 
250   //////////////////////////////////////////////////////////////////////////////
251   // Members
252   //////////////////////////////////////////////////////////////////////////////
253 
254   // map from a locked row to the context for that lock including:
255   // - CountDownLatch for threads waiting on that row
256   // - the thread that owns the lock (allow reentrancy)
257   // - reference count of (reentrant) locks held by the thread
258   // - the row itself
259   private final ConcurrentHashMap<HashedBytes, RowLockContext> lockedRows =
260       new ConcurrentHashMap<HashedBytes, RowLockContext>();
261 
262   protected final Map<byte[], Store> stores = new ConcurrentSkipListMap<byte[], Store>(
263       Bytes.BYTES_RAWCOMPARATOR);
264 
265   // TODO: account for each registered handler in HeapSize computation
266   private Map<String, Service> coprocessorServiceHandlers = Maps.newHashMap();
267 
268   public final AtomicLong memstoreSize = new AtomicLong(0);
269 
270   // Debug possible data loss due to WAL off
271   final Counter numMutationsWithoutWAL = new Counter();
272   final Counter dataInMemoryWithoutWAL = new Counter();
273 
274   // Debug why CAS operations are taking a while.
275   final Counter checkAndMutateChecksPassed = new Counter();
276   final Counter checkAndMutateChecksFailed = new Counter();
277 
278   //Number of requests
279   final Counter readRequestsCount = new Counter();
280   final Counter writeRequestsCount = new Counter();
281 
282   // Number of requests blocked by memstore size.
283   private final Counter blockedRequestsCount = new Counter();
284 
285   // Compaction counters
286   final AtomicLong compactionsFinished = new AtomicLong(0L);
287   final AtomicLong compactionNumFilesCompacted = new AtomicLong(0L);
288   final AtomicLong compactionNumBytesCompacted = new AtomicLong(0L);
289 
290   private final WAL wal;
291   private final HRegionFileSystem fs;
292   protected final Configuration conf;
293   private final Configuration baseConf;
294   private final KeyValue.KVComparator comparator;
295   private final int rowLockWaitDuration;
296   static final int DEFAULT_ROWLOCK_WAIT_DURATION = 30000;
297 
298   // The internal wait duration to acquire a lock before read/update
299   // from the region. It is not per row. The purpose of this wait time
300   // is to avoid waiting a long time while the region is busy, so that
301   // we can release the IPC handler soon enough to improve the
302   // availability of the region server. It can be adjusted by
303   // tuning configuration "hbase.busy.wait.duration".
304   final long busyWaitDuration;
305   static final long DEFAULT_BUSY_WAIT_DURATION = HConstants.DEFAULT_HBASE_RPC_TIMEOUT;
306 
307   // If updating multiple rows in one call, wait longer,
308   // i.e. waiting for busyWaitDuration * # of rows. However,
309   // we can limit the max multiplier.
310   final int maxBusyWaitMultiplier;
311 
312   // Max busy wait duration. There is no point to wait longer than the RPC
313   // purge timeout, when a RPC call will be terminated by the RPC engine.
314   final long maxBusyWaitDuration;
315 
316   // negative number indicates infinite timeout
317   static final long DEFAULT_ROW_PROCESSOR_TIMEOUT = 60 * 1000L;
318   final ExecutorService rowProcessorExecutor = Executors.newCachedThreadPool();
319 
320   private final ConcurrentHashMap<RegionScanner, Long> scannerReadPoints;
321 
322   /**
323    * The sequence ID that was encountered when this region was opened.
324    */
325   private long openSeqNum = HConstants.NO_SEQNUM;
326 
327   /**
328    * The default setting for whether to enable on-demand CF loading for
329    * scan requests to this region. Requests can override it.
330    */
331   private boolean isLoadingCfsOnDemandDefault = false;
332 
333   private final AtomicInteger majorInProgress = new AtomicInteger(0);
334   private final AtomicInteger minorInProgress = new AtomicInteger(0);
335 
336   //
337   // Context: During replay we want to ensure that we do not lose any data. So, we
338   // have to be conservative in how we replay wals. For each store, we calculate
339   // the maxSeqId up to which the store was flushed. And, skip the edits which
340   // are equal to or lower than maxSeqId for each store.
341   // The following map is populated when opening the region
342   Map<byte[], Long> maxSeqIdInStores = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
343 
344   /** Saved state from replaying prepare flush cache */
345   private PrepareFlushResult prepareFlushResult = null;
346 
347   /**
348    * Config setting for whether to allow writes when a region is in recovering or not.
349    */
350   private boolean disallowWritesInRecovering = false;
351 
352   // when a region is in recovering state, it can only accept writes not reads
353   private volatile boolean isRecovering = false;
354 
355   private volatile Optional<ConfigurationManager> configurationManager;
356 
357   /**
358    * @return The smallest mvcc readPoint across all the scanners in this
359    * region. Writes older than this readPoint, are included  in every
360    * read operation.
361    */
362   public long getSmallestReadPoint() {
363     long minimumReadPoint;
364     // We need to ensure that while we are calculating the smallestReadPoint
365     // no new RegionScanners can grab a readPoint that we are unaware of.
366     // We achieve this by synchronizing on the scannerReadPoints object.
367     synchronized(scannerReadPoints) {
368       minimumReadPoint = mvcc.memstoreReadPoint();
369 
370       for (Long readPoint: this.scannerReadPoints.values()) {
371         if (readPoint < minimumReadPoint) {
372           minimumReadPoint = readPoint;
373         }
374       }
375     }
376     return minimumReadPoint;
377   }
378 
379   /*
380    * Data structure of write state flags used coordinating flushes,
381    * compactions and closes.
382    */
383   static class WriteState {
384     // Set while a memstore flush is happening.
385     volatile boolean flushing = false;
386     // Set when a flush has been requested.
387     volatile boolean flushRequested = false;
388     // Number of compactions running.
389     volatile int compacting = 0;
390     // Gets set in close. If set, cannot compact or flush again.
391     volatile boolean writesEnabled = true;
392     // Set if region is read-only
393     volatile boolean readOnly = false;
394     // whether the reads are enabled. This is different than readOnly, because readOnly is
395     // static in the lifetime of the region, while readsEnabled is dynamic
396     volatile boolean readsEnabled = true;
397 
398     /**
399      * Set flags that make this region read-only.
400      *
401      * @param onOff flip value for region r/o setting
402      */
403     synchronized void setReadOnly(final boolean onOff) {
404       this.writesEnabled = !onOff;
405       this.readOnly = onOff;
406     }
407 
408     boolean isReadOnly() {
409       return this.readOnly;
410     }
411 
412     boolean isFlushRequested() {
413       return this.flushRequested;
414     }
415 
416     void setReadsEnabled(boolean readsEnabled) {
417       this.readsEnabled = readsEnabled;
418     }
419 
420     static final long HEAP_SIZE = ClassSize.align(
421         ClassSize.OBJECT + 5 * Bytes.SIZEOF_BOOLEAN);
422   }
423 
424   /**
425    * Objects from this class are created when flushing to describe all the different states that
426    * that method ends up in. The Result enum describes those states. The sequence id should only
427    * be specified if the flush was successful, and the failure message should only be specified
428    * if it didn't flush.
429    */
430   public static class FlushResultImpl implements FlushResult {
431     final Result result;
432     final String failureReason;
433     final long flushSequenceId;
434     final boolean wroteFlushWalMarker;
435 
436     /**
437      * Convenience constructor to use when the flush is successful, the failure message is set to
438      * null.
439      * @param result Expecting FLUSHED_NO_COMPACTION_NEEDED or FLUSHED_COMPACTION_NEEDED.
440      * @param flushSequenceId Generated sequence id that comes right after the edits in the
441      *                        memstores.
442      */
443     FlushResultImpl(Result result, long flushSequenceId) {
444       this(result, flushSequenceId, null, false);
445       assert result == Result.FLUSHED_NO_COMPACTION_NEEDED || result == Result
446           .FLUSHED_COMPACTION_NEEDED;
447     }
448 
449     /**
450      * Convenience constructor to use when we cannot flush.
451      * @param result Expecting CANNOT_FLUSH_MEMSTORE_EMPTY or CANNOT_FLUSH.
452      * @param failureReason Reason why we couldn't flush.
453      */
454     FlushResultImpl(Result result, String failureReason, boolean wroteFlushMarker) {
455       this(result, -1, failureReason, wroteFlushMarker);
456       assert result == Result.CANNOT_FLUSH_MEMSTORE_EMPTY || result == Result.CANNOT_FLUSH;
457     }
458 
459     /**
460      * Constructor with all the parameters.
461      * @param result Any of the Result.
462      * @param flushSequenceId Generated sequence id if the memstores were flushed else -1.
463      * @param failureReason Reason why we couldn't flush, or null.
464      */
465     FlushResultImpl(Result result, long flushSequenceId, String failureReason,
466       boolean wroteFlushMarker) {
467       this.result = result;
468       this.flushSequenceId = flushSequenceId;
469       this.failureReason = failureReason;
470       this.wroteFlushWalMarker = wroteFlushMarker;
471     }
472 
473     /**
474      * Convenience method, the equivalent of checking if result is
475      * FLUSHED_NO_COMPACTION_NEEDED or FLUSHED_NO_COMPACTION_NEEDED.
476      * @return true if the memstores were flushed, else false.
477      */
478     public boolean isFlushSucceeded() {
479       return result == Result.FLUSHED_NO_COMPACTION_NEEDED || result == Result
480           .FLUSHED_COMPACTION_NEEDED;
481     }
482 
483     /**
484      * Convenience method, the equivalent of checking if result is FLUSHED_COMPACTION_NEEDED.
485      * @return True if the flush requested a compaction, else false (doesn't even mean it flushed).
486      */
487     public boolean isCompactionNeeded() {
488       return result == Result.FLUSHED_COMPACTION_NEEDED;
489     }
490 
491     @Override
492     public String toString() {
493       return new StringBuilder()
494         .append("flush result:").append(result).append(", ")
495         .append("failureReason:").append(failureReason).append(",")
496         .append("flush seq id").append(flushSequenceId).toString();
497     }
498 
499     @Override
500     public Result getResult() {
501       return result;
502     }
503   }
504 
505   /** A result object from prepare flush cache stage */
506   @VisibleForTesting
507   static class PrepareFlushResult {
508     final FlushResult result; // indicating a failure result from prepare
509     final TreeMap<byte[], StoreFlushContext> storeFlushCtxs;
510     final TreeMap<byte[], List<Path>> committedFiles;
511     final long startTime;
512     final long flushOpSeqId;
513     final long flushedSeqId;
514     final long totalFlushableSize;
515 
516     /** Constructs an early exit case */
517     PrepareFlushResult(FlushResult result, long flushSeqId) {
518       this(result, null, null, Math.max(0, flushSeqId), 0, 0, 0);
519     }
520 
521     /** Constructs a successful prepare flush result */
522     PrepareFlushResult(
523       TreeMap<byte[], StoreFlushContext> storeFlushCtxs,
524       TreeMap<byte[], List<Path>> committedFiles, long startTime, long flushSeqId,
525       long flushedSeqId, long totalFlushableSize) {
526       this(null, storeFlushCtxs, committedFiles, startTime,
527         flushSeqId, flushedSeqId, totalFlushableSize);
528     }
529 
530     private PrepareFlushResult(
531       FlushResult result,
532       TreeMap<byte[], StoreFlushContext> storeFlushCtxs,
533       TreeMap<byte[], List<Path>> committedFiles, long startTime, long flushSeqId,
534       long flushedSeqId, long totalFlushableSize) {
535       this.result = result;
536       this.storeFlushCtxs = storeFlushCtxs;
537       this.committedFiles = committedFiles;
538       this.startTime = startTime;
539       this.flushOpSeqId = flushSeqId;
540       this.flushedSeqId = flushedSeqId;
541       this.totalFlushableSize = totalFlushableSize;
542     }
543 
544     public FlushResult getResult() {
545       return this.result;
546     }
547   }
548 
549   final WriteState writestate = new WriteState();
550 
551   long memstoreFlushSize;
552   final long timestampSlop;
553   final long rowProcessorTimeout;
554 
555   // Last flush time for each Store. Useful when we are flushing for each column
556   private final ConcurrentMap<Store, Long> lastStoreFlushTimeMap =
557       new ConcurrentHashMap<Store, Long>();
558 
559   final RegionServerServices rsServices;
560   private RegionServerAccounting rsAccounting;
561   private long flushCheckInterval;
562   // flushPerChanges is to prevent too many changes in memstore
563   private long flushPerChanges;
564   private long blockingMemStoreSize;
565   final long threadWakeFrequency;
566   // Used to guard closes
567   final ReentrantReadWriteLock lock =
568     new ReentrantReadWriteLock();
569 
570   // Stop updates lock
571   private final ReentrantReadWriteLock updatesLock =
572     new ReentrantReadWriteLock();
573   private boolean splitRequest;
574   private byte[] explicitSplitPoint = null;
575 
576   private final MultiVersionConsistencyControl mvcc =
577       new MultiVersionConsistencyControl();
578 
579   // Coprocessor host
580   private RegionCoprocessorHost coprocessorHost;
581 
582   private HTableDescriptor htableDescriptor = null;
583   private RegionSplitPolicy splitPolicy;
584   private FlushPolicy flushPolicy;
585 
586   private final MetricsRegion metricsRegion;
587   private final MetricsRegionWrapperImpl metricsRegionWrapper;
588   private final Durability durability;
589   private final boolean regionStatsEnabled;
590 
591   /**
592    * HRegion constructor. This constructor should only be used for testing and
593    * extensions.  Instances of HRegion should be instantiated with the
594    * {@link HRegion#createHRegion} or {@link HRegion#openHRegion} method.
595    *
596    * @param tableDir qualified path of directory where region should be located,
597    * usually the table directory.
598    * @param wal The WAL is the outbound log for any updates to the HRegion
599    * The wal file is a logfile from the previous execution that's
600    * custom-computed for this HRegion. The HRegionServer computes and sorts the
601    * appropriate wal info for this HRegion. If there is a previous wal file
602    * (implying that the HRegion has been written-to before), then read it from
603    * the supplied path.
604    * @param fs is the filesystem.
605    * @param confParam is global configuration settings.
606    * @param regionInfo - HRegionInfo that describes the region
607    * is new), then read them from the supplied path.
608    * @param htd the table descriptor
609    * @param rsServices reference to {@link RegionServerServices} or null
610    */
611   @Deprecated
612   public HRegion(final Path tableDir, final WAL wal, final FileSystem fs,
613       final Configuration confParam, final HRegionInfo regionInfo,
614       final HTableDescriptor htd, final RegionServerServices rsServices) {
615     this(new HRegionFileSystem(confParam, fs, tableDir, regionInfo),
616       wal, confParam, htd, rsServices);
617   }
618 
619   /**
620    * HRegion constructor. This constructor should only be used for testing and
621    * extensions.  Instances of HRegion should be instantiated with the
622    * {@link HRegion#createHRegion} or {@link HRegion#openHRegion} method.
623    *
624    * @param fs is the filesystem.
625    * @param wal The WAL is the outbound log for any updates to the HRegion
626    * The wal file is a logfile from the previous execution that's
627    * custom-computed for this HRegion. The HRegionServer computes and sorts the
628    * appropriate wal info for this HRegion. If there is a previous wal file
629    * (implying that the HRegion has been written-to before), then read it from
630    * the supplied path.
631    * @param confParam is global configuration settings.
632    * @param htd the table descriptor
633    * @param rsServices reference to {@link RegionServerServices} or null
634    */
635   public HRegion(final HRegionFileSystem fs, final WAL wal, final Configuration confParam,
636       final HTableDescriptor htd, final RegionServerServices rsServices) {
637     if (htd == null) {
638       throw new IllegalArgumentException("Need table descriptor");
639     }
640 
641     if (confParam instanceof CompoundConfiguration) {
642       throw new IllegalArgumentException("Need original base configuration");
643     }
644 
645     this.comparator = fs.getRegionInfo().getComparator();
646     this.wal = wal;
647     this.fs = fs;
648 
649     // 'conf' renamed to 'confParam' b/c we use this.conf in the constructor
650     this.baseConf = confParam;
651     this.conf = new CompoundConfiguration()
652       .add(confParam)
653       .addStringMap(htd.getConfiguration())
654       .addWritableMap(htd.getValues());
655     this.flushCheckInterval = conf.getInt(MEMSTORE_PERIODIC_FLUSH_INTERVAL,
656         DEFAULT_CACHE_FLUSH_INTERVAL);
657     this.flushPerChanges = conf.getLong(MEMSTORE_FLUSH_PER_CHANGES, DEFAULT_FLUSH_PER_CHANGES);
658     if (this.flushPerChanges > MAX_FLUSH_PER_CHANGES) {
659       throw new IllegalArgumentException(MEMSTORE_FLUSH_PER_CHANGES + " can not exceed "
660           + MAX_FLUSH_PER_CHANGES);
661     }
662     this.rowLockWaitDuration = conf.getInt("hbase.rowlock.wait.duration",
663                     DEFAULT_ROWLOCK_WAIT_DURATION);
664 
665     this.isLoadingCfsOnDemandDefault = conf.getBoolean(LOAD_CFS_ON_DEMAND_CONFIG_KEY, true);
666     this.htableDescriptor = htd;
667     this.rsServices = rsServices;
668     this.threadWakeFrequency = conf.getLong(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000);
669     setHTableSpecificConf();
670     this.scannerReadPoints = new ConcurrentHashMap<RegionScanner, Long>();
671 
672     this.busyWaitDuration = conf.getLong(
673       "hbase.busy.wait.duration", DEFAULT_BUSY_WAIT_DURATION);
674     this.maxBusyWaitMultiplier = conf.getInt("hbase.busy.wait.multiplier.max", 2);
675     if (busyWaitDuration * maxBusyWaitMultiplier <= 0L) {
676       throw new IllegalArgumentException("Invalid hbase.busy.wait.duration ("
677         + busyWaitDuration + ") or hbase.busy.wait.multiplier.max ("
678         + maxBusyWaitMultiplier + "). Their product should be positive");
679     }
680     this.maxBusyWaitDuration = conf.getLong("hbase.ipc.client.call.purge.timeout",
681       2 * HConstants.DEFAULT_HBASE_RPC_TIMEOUT);
682 
683     /*
684      * timestamp.slop provides a server-side constraint on the timestamp. This
685      * assumes that you base your TS around currentTimeMillis(). In this case,
686      * throw an error to the user if the user-specified TS is newer than now +
687      * slop. LATEST_TIMESTAMP == don't use this functionality
688      */
689     this.timestampSlop = conf.getLong(
690         "hbase.hregion.keyvalue.timestamp.slop.millisecs",
691         HConstants.LATEST_TIMESTAMP);
692 
693     /**
694      * Timeout for the process time in processRowsWithLocks().
695      * Use -1 to switch off time bound.
696      */
697     this.rowProcessorTimeout = conf.getLong(
698         "hbase.hregion.row.processor.timeout", DEFAULT_ROW_PROCESSOR_TIMEOUT);
699     this.durability = htd.getDurability() == Durability.USE_DEFAULT
700         ? DEFAULT_DURABILITY
701         : htd.getDurability();
702     if (rsServices != null) {
703       this.rsAccounting = this.rsServices.getRegionServerAccounting();
704       // don't initialize coprocessors if not running within a regionserver
705       // TODO: revisit if coprocessors should load in other cases
706       this.coprocessorHost = new RegionCoprocessorHost(this, rsServices, conf);
707       this.metricsRegionWrapper = new MetricsRegionWrapperImpl(this);
708       this.metricsRegion = new MetricsRegion(this.metricsRegionWrapper);
709 
710       Map<String, Region> recoveringRegions = rsServices.getRecoveringRegions();
711       String encodedName = getRegionInfo().getEncodedName();
712       if (recoveringRegions != null && recoveringRegions.containsKey(encodedName)) {
713         this.isRecovering = true;
714         recoveringRegions.put(encodedName, this);
715       }
716     } else {
717       this.metricsRegionWrapper = null;
718       this.metricsRegion = null;
719     }
720     if (LOG.isDebugEnabled()) {
721       // Write out region name as string and its encoded name.
722       LOG.debug("Instantiated " + this);
723     }
724 
725     // by default, we allow writes against a region when it's in recovering
726     this.disallowWritesInRecovering =
727         conf.getBoolean(HConstants.DISALLOW_WRITES_IN_RECOVERING,
728           HConstants.DEFAULT_DISALLOW_WRITES_IN_RECOVERING_CONFIG);
729     configurationManager = Optional.absent();
730 
731     // disable stats tracking system tables, but check the config for everything else
732     this.regionStatsEnabled = htd.getTableName().getNamespaceAsString().equals(
733         NamespaceDescriptor.SYSTEM_NAMESPACE_NAME_STR) ?
734           false :
735           conf.getBoolean(HConstants.ENABLE_CLIENT_BACKPRESSURE,
736               HConstants.DEFAULT_ENABLE_CLIENT_BACKPRESSURE);
737   }
738 
739   void setHTableSpecificConf() {
740     if (this.htableDescriptor == null) return;
741     long flushSize = this.htableDescriptor.getMemStoreFlushSize();
742 
743     if (flushSize <= 0) {
744       flushSize = conf.getLong(HConstants.HREGION_MEMSTORE_FLUSH_SIZE,
745         HTableDescriptor.DEFAULT_MEMSTORE_FLUSH_SIZE);
746     }
747     this.memstoreFlushSize = flushSize;
748     this.blockingMemStoreSize = this.memstoreFlushSize *
749         conf.getLong("hbase.hregion.memstore.block.multiplier", 2);
750   }
751 
752   /**
753    * Initialize this region.
754    * Used only by tests and SplitTransaction to reopen the region.
755    * You should use createHRegion() or openHRegion()
756    * @return What the next sequence (edit) id should be.
757    * @throws IOException e
758    * @deprecated use HRegion.createHRegion() or HRegion.openHRegion()
759    */
760   @Deprecated
761   public long initialize() throws IOException {
762     return initialize(null);
763   }
764 
765   /**
766    * Initialize this region.
767    *
768    * @param reporter Tickle every so often if initialize is taking a while.
769    * @return What the next sequence (edit) id should be.
770    * @throws IOException e
771    */
772   private long initialize(final CancelableProgressable reporter) throws IOException {
773     MonitoredTask status = TaskMonitor.get().createStatus("Initializing region " + this);
774     long nextSeqId = -1;
775     try {
776       nextSeqId = initializeRegionInternals(reporter, status);
777       return nextSeqId;
778     } finally {
779       // nextSeqid will be -1 if the initialization fails.
780       // At least it will be 0 otherwise.
781       if (nextSeqId == -1) {
782         status.abort("Exception during region " + getRegionInfo().getRegionNameAsString() +
783           " initialization.");
784       }
785     }
786   }
787 
788   private long initializeRegionInternals(final CancelableProgressable reporter,
789       final MonitoredTask status) throws IOException {
790     if (coprocessorHost != null) {
791       status.setStatus("Running coprocessor pre-open hook");
792       coprocessorHost.preOpen();
793     }
794 
795     // Write HRI to a file in case we need to recover hbase:meta
796     status.setStatus("Writing region info on filesystem");
797     fs.checkRegionInfoOnFilesystem();
798 
799     // Initialize all the HStores
800     status.setStatus("Initializing all the Stores");
801     long maxSeqId = initializeRegionStores(reporter, status, false);
802     this.lastReplayedOpenRegionSeqId = maxSeqId;
803 
804     this.writestate.setReadOnly(ServerRegionReplicaUtil.isReadOnly(this));
805     this.writestate.flushRequested = false;
806     this.writestate.compacting = 0;
807 
808     if (this.writestate.writesEnabled) {
809       // Remove temporary data left over from old regions
810       status.setStatus("Cleaning up temporary data from old regions");
811       fs.cleanupTempDir();
812     }
813 
814     if (this.writestate.writesEnabled) {
815       status.setStatus("Cleaning up detritus from prior splits");
816       // Get rid of any splits or merges that were lost in-progress.  Clean out
817       // these directories here on open.  We may be opening a region that was
818       // being split but we crashed in the middle of it all.
819       fs.cleanupAnySplitDetritus();
820       fs.cleanupMergesDir();
821     }
822 
823     // Initialize split policy
824     this.splitPolicy = RegionSplitPolicy.create(this, conf);
825 
826     // Initialize flush policy
827     this.flushPolicy = FlushPolicyFactory.create(this, conf);
828 
829     long lastFlushTime = EnvironmentEdgeManager.currentTime();
830     for (Store store: stores.values()) {
831       this.lastStoreFlushTimeMap.put(store, lastFlushTime);
832     }
833 
834     // Use maximum of log sequenceid or that which was found in stores
835     // (particularly if no recovered edits, seqid will be -1).
836     long nextSeqid = maxSeqId;
837 
838     // In distributedLogReplay mode, we don't know the last change sequence number because region
839     // is opened before recovery completes. So we add a safety bumper to avoid new sequence number
840     // overlaps used sequence numbers
841     if (this.writestate.writesEnabled) {
842       nextSeqid = WALSplitter.writeRegionSequenceIdFile(this.fs.getFileSystem(), this.fs
843           .getRegionDir(), nextSeqid, (this.isRecovering ? (this.flushPerChanges + 10000000) : 1));
844     } else {
845       nextSeqid++;
846     }
847 
848     LOG.info("Onlined " + this.getRegionInfo().getShortNameToLog() +
849       "; next sequenceid=" + nextSeqid);
850 
851     // A region can be reopened if failed a split; reset flags
852     this.closing.set(false);
853     this.closed.set(false);
854 
855     if (coprocessorHost != null) {
856       status.setStatus("Running coprocessor post-open hooks");
857       coprocessorHost.postOpen();
858     }
859 
860     status.markComplete("Region opened successfully");
861     return nextSeqid;
862   }
863 
864   private long initializeRegionStores(final CancelableProgressable reporter, MonitoredTask status,
865       boolean warmupOnly)
866       throws IOException {
867 
868     // Load in all the HStores.
869 
870     long maxSeqId = -1;
871     // initialized to -1 so that we pick up MemstoreTS from column families
872     long maxMemstoreTS = -1;
873 
874     if (!htableDescriptor.getFamilies().isEmpty()) {
875       // initialize the thread pool for opening stores in parallel.
876       ThreadPoolExecutor storeOpenerThreadPool =
877         getStoreOpenAndCloseThreadPool("StoreOpener-" + this.getRegionInfo().getShortNameToLog());
878       CompletionService<HStore> completionService =
879         new ExecutorCompletionService<HStore>(storeOpenerThreadPool);
880 
881       // initialize each store in parallel
882       for (final HColumnDescriptor family : htableDescriptor.getFamilies()) {
883         status.setStatus("Instantiating store for column family " + family);
884         completionService.submit(new Callable<HStore>() {
885           @Override
886           public HStore call() throws IOException {
887             return instantiateHStore(family);
888           }
889         });
890       }
891       boolean allStoresOpened = false;
892       try {
893         for (int i = 0; i < htableDescriptor.getFamilies().size(); i++) {
894           Future<HStore> future = completionService.take();
895           HStore store = future.get();
896           this.stores.put(store.getFamily().getName(), store);
897 
898           long storeMaxSequenceId = store.getMaxSequenceId();
899           maxSeqIdInStores.put(store.getColumnFamilyName().getBytes(),
900               storeMaxSequenceId);
901           if (maxSeqId == -1 || storeMaxSequenceId > maxSeqId) {
902             maxSeqId = storeMaxSequenceId;
903           }
904           long maxStoreMemstoreTS = store.getMaxMemstoreTS();
905           if (maxStoreMemstoreTS > maxMemstoreTS) {
906             maxMemstoreTS = maxStoreMemstoreTS;
907           }
908         }
909         allStoresOpened = true;
910       } catch (InterruptedException e) {
911         throw (InterruptedIOException)new InterruptedIOException().initCause(e);
912       } catch (ExecutionException e) {
913         throw new IOException(e.getCause());
914       } finally {
915         storeOpenerThreadPool.shutdownNow();
916         if (!allStoresOpened) {
917           // something went wrong, close all opened stores
918           LOG.error("Could not initialize all stores for the region=" + this);
919           for (Store store : this.stores.values()) {
920             try {
921               store.close();
922             } catch (IOException e) {
923               LOG.warn(e.getMessage());
924             }
925           }
926         }
927       }
928     }
929     if (ServerRegionReplicaUtil.shouldReplayRecoveredEdits(this) && !warmupOnly) {
930       // Recover any edits if available.
931       maxSeqId = Math.max(maxSeqId, replayRecoveredEditsIfAny(
932           this.fs.getRegionDir(), maxSeqIdInStores, reporter, status));
933     }
934     maxSeqId = Math.max(maxSeqId, maxMemstoreTS + 1);
935     mvcc.initialize(maxSeqId);
936     return maxSeqId;
937   }
938 
939   private void initializeWarmup(final CancelableProgressable reporter) throws IOException {
940     MonitoredTask status = TaskMonitor.get().createStatus("Initializing region " + this);
941 
942     // Initialize all the HStores
943     status.setStatus("Warming up all the Stores");
944     initializeRegionStores(reporter, status, true);
945   }
946 
947   private void writeRegionOpenMarker(WAL wal, long openSeqId) throws IOException {
948     Map<byte[], List<Path>> storeFiles = new TreeMap<byte[], List<Path>>(Bytes.BYTES_COMPARATOR);
949     for (Store store: getStores()) {
950       ArrayList<Path> storeFileNames = new ArrayList<Path>();
951       for (StoreFile storeFile: store.getStorefiles()) {
952         storeFileNames.add(storeFile.getPath());
953       }
954       storeFiles.put(store.getFamily().getName(), storeFileNames);
955     }
956 
957     RegionEventDescriptor regionOpenDesc = ProtobufUtil.toRegionEventDescriptor(
958       RegionEventDescriptor.EventType.REGION_OPEN, getRegionInfo(), openSeqId,
959       getRegionServerServices().getServerName(), storeFiles);
960     WALUtil.writeRegionEventMarker(wal, getTableDesc(), getRegionInfo(), regionOpenDesc,
961       getSequenceId());
962   }
963 
964   private void writeRegionCloseMarker(WAL wal) throws IOException {
965     Map<byte[], List<Path>> storeFiles = new TreeMap<byte[], List<Path>>(Bytes.BYTES_COMPARATOR);
966     for (Store store: getStores()) {
967       ArrayList<Path> storeFileNames = new ArrayList<Path>();
968       for (StoreFile storeFile: store.getStorefiles()) {
969         storeFileNames.add(storeFile.getPath());
970       }
971       storeFiles.put(store.getFamily().getName(), storeFileNames);
972     }
973 
974     RegionEventDescriptor regionEventDesc = ProtobufUtil.toRegionEventDescriptor(
975       RegionEventDescriptor.EventType.REGION_CLOSE, getRegionInfo(), getSequenceId().get(),
976       getRegionServerServices().getServerName(), storeFiles);
977     WALUtil.writeRegionEventMarker(wal, getTableDesc(), getRegionInfo(), regionEventDesc,
978       getSequenceId());
979 
980     // Store SeqId in HDFS when a region closes
981     // checking region folder exists is due to many tests which delete the table folder while a
982     // table is still online
983     if (this.fs.getFileSystem().exists(this.fs.getRegionDir())) {
984       WALSplitter.writeRegionSequenceIdFile(this.fs.getFileSystem(), this.fs.getRegionDir(),
985         getSequenceId().get(), 0);
986     }
987   }
988 
989   /**
990    * @return True if this region has references.
991    */
992   public boolean hasReferences() {
993     for (Store store : this.stores.values()) {
994       if (store.hasReferences()) return true;
995     }
996     return false;
997   }
998 
999   @Override
1000   public HDFSBlocksDistribution getHDFSBlocksDistribution() {
1001     HDFSBlocksDistribution hdfsBlocksDistribution =
1002       new HDFSBlocksDistribution();
1003     synchronized (this.stores) {
1004       for (Store store : this.stores.values()) {
1005         for (StoreFile sf : store.getStorefiles()) {
1006           HDFSBlocksDistribution storeFileBlocksDistribution =
1007             sf.getHDFSBlockDistribution();
1008           hdfsBlocksDistribution.add(storeFileBlocksDistribution);
1009         }
1010       }
1011     }
1012     return hdfsBlocksDistribution;
1013   }
1014 
1015   /**
1016    * This is a helper function to compute HDFS block distribution on demand
1017    * @param conf configuration
1018    * @param tableDescriptor HTableDescriptor of the table
1019    * @param regionInfo encoded name of the region
1020    * @return The HDFS blocks distribution for the given region.
1021    * @throws IOException
1022    */
1023   public static HDFSBlocksDistribution computeHDFSBlocksDistribution(final Configuration conf,
1024       final HTableDescriptor tableDescriptor, final HRegionInfo regionInfo) throws IOException {
1025     Path tablePath = FSUtils.getTableDir(FSUtils.getRootDir(conf), tableDescriptor.getTableName());
1026     return computeHDFSBlocksDistribution(conf, tableDescriptor, regionInfo, tablePath);
1027   }
1028 
1029   /**
1030    * This is a helper function to compute HDFS block distribution on demand
1031    * @param conf configuration
1032    * @param tableDescriptor HTableDescriptor of the table
1033    * @param regionInfo encoded name of the region
1034    * @param tablePath the table directory
1035    * @return The HDFS blocks distribution for the given region.
1036    * @throws IOException
1037    */
1038   public static HDFSBlocksDistribution computeHDFSBlocksDistribution(final Configuration conf,
1039       final HTableDescriptor tableDescriptor, final HRegionInfo regionInfo,  Path tablePath)
1040       throws IOException {
1041     HDFSBlocksDistribution hdfsBlocksDistribution = new HDFSBlocksDistribution();
1042     FileSystem fs = tablePath.getFileSystem(conf);
1043 
1044     HRegionFileSystem regionFs = new HRegionFileSystem(conf, fs, tablePath, regionInfo);
1045     for (HColumnDescriptor family: tableDescriptor.getFamilies()) {
1046       Collection<StoreFileInfo> storeFiles = regionFs.getStoreFiles(family.getNameAsString());
1047       if (storeFiles == null) continue;
1048 
1049       for (StoreFileInfo storeFileInfo : storeFiles) {
1050         hdfsBlocksDistribution.add(storeFileInfo.computeHDFSBlocksDistribution(fs));
1051       }
1052     }
1053     return hdfsBlocksDistribution;
1054   }
1055 
1056   /**
1057    * Increase the size of mem store in this region and the size of global mem
1058    * store
1059    * @return the size of memstore in this region
1060    */
1061   public long addAndGetGlobalMemstoreSize(long memStoreSize) {
1062     if (this.rsAccounting != null) {
1063       rsAccounting.addAndGetGlobalMemstoreSize(memStoreSize);
1064     }
1065     return this.memstoreSize.addAndGet(memStoreSize);
1066   }
1067 
1068   @Override
1069   public HRegionInfo getRegionInfo() {
1070     return this.fs.getRegionInfo();
1071   }
1072 
1073   /**
1074    * @return Instance of {@link RegionServerServices} used by this HRegion.
1075    * Can be null.
1076    */
1077   RegionServerServices getRegionServerServices() {
1078     return this.rsServices;
1079   }
1080 
1081   @Override
1082   public long getReadRequestsCount() {
1083     return readRequestsCount.get();
1084   }
1085 
1086   @Override
1087   public void updateReadRequestsCount(long i) {
1088     readRequestsCount.add(i);
1089   }
1090 
1091   @Override
1092   public long getWriteRequestsCount() {
1093     return writeRequestsCount.get();
1094   }
1095 
1096   @Override
1097   public void updateWriteRequestsCount(long i) {
1098     writeRequestsCount.add(i);
1099   }
1100 
1101   @Override
1102   public long getMemstoreSize() {
1103     return memstoreSize.get();
1104   }
1105 
1106   @Override
1107   public long getNumMutationsWithoutWAL() {
1108     return numMutationsWithoutWAL.get();
1109   }
1110   
1111   @Override
1112   public long getDataInMemoryWithoutWAL() {
1113     return dataInMemoryWithoutWAL.get();
1114   }
1115 
1116   @Override
1117   public long getBlockedRequestsCount() {
1118     return blockedRequestsCount.get();
1119   }
1120 
1121   @Override
1122   public long getCheckAndMutateChecksPassed() {
1123     return checkAndMutateChecksPassed.get();
1124   }
1125 
1126   @Override
1127   public long getCheckAndMutateChecksFailed() {
1128     return checkAndMutateChecksFailed.get();
1129   }
1130 
1131   @Override
1132   public MetricsRegion getMetrics() {
1133     return metricsRegion;
1134   }
1135 
1136   @Override
1137   public boolean isClosed() {
1138     return this.closed.get();
1139   }
1140 
1141   @Override
1142   public boolean isClosing() {
1143     return this.closing.get();
1144   }
1145 
1146   @Override
1147   public boolean isReadOnly() {
1148     return this.writestate.isReadOnly();
1149   }
1150 
1151   /**
1152    * Reset recovering state of current region
1153    */
1154   public void setRecovering(boolean newState) {
1155     boolean wasRecovering = this.isRecovering;
1156     // before we flip the recovering switch (enabling reads) we should write the region open
1157     // event to WAL if needed
1158     if (wal != null && getRegionServerServices() != null && !writestate.readOnly
1159         && wasRecovering && !newState) {
1160 
1161       // force a flush only if region replication is set up for this region. Otherwise no need.
1162       boolean forceFlush = getTableDesc().getRegionReplication() > 1;
1163 
1164       // force a flush first
1165       MonitoredTask status = TaskMonitor.get().createStatus(
1166         "Flushing region " + this + " because recovery is finished");
1167       try {
1168         if (forceFlush) {
1169           internalFlushcache(status);
1170         }
1171 
1172         status.setStatus("Writing region open event marker to WAL because recovery is finished");
1173         try {
1174           long seqId = openSeqNum;
1175           // obtain a new seqId because we possibly have writes and flushes on top of openSeqNum
1176           if (wal != null) {
1177             seqId = getNextSequenceId(wal);
1178           }
1179           writeRegionOpenMarker(wal, seqId);
1180         } catch (IOException e) {
1181           // We cannot rethrow this exception since we are being called from the zk thread. The
1182           // region has already opened. In this case we log the error, but continue
1183           LOG.warn(getRegionInfo().getEncodedName() + " : was not able to write region opening "
1184               + "event to WAL, continueing", e);
1185         }
1186       } catch (IOException ioe) {
1187         // Distributed log replay semantics does not necessarily require a flush, since the replayed
1188         // data is already written again in the WAL. So failed flush should be fine.
1189         LOG.warn(getRegionInfo().getEncodedName() + " : was not able to flush "
1190             + "event to WAL, continueing", ioe);
1191       } finally {
1192         status.cleanup();
1193       }
1194     }
1195 
1196     this.isRecovering = newState;
1197     if (wasRecovering && !isRecovering) {
1198       // Call only when wal replay is over.
1199       coprocessorHost.postLogReplay();
1200     }
1201   }
1202 
1203   @Override
1204   public boolean isRecovering() {
1205     return this.isRecovering;
1206   }
1207 
1208   @Override
1209   public boolean isAvailable() {
1210     return !isClosed() && !isClosing();
1211   }
1212 
1213   /** @return true if region is splittable */
1214   public boolean isSplittable() {
1215     return isAvailable() && !hasReferences();
1216   }
1217 
1218   /**
1219    * @return true if region is mergeable
1220    */
1221   public boolean isMergeable() {
1222     if (!isAvailable()) {
1223       LOG.debug("Region " + getRegionInfo().getRegionNameAsString()
1224           + " is not mergeable because it is closing or closed");
1225       return false;
1226     }
1227     if (hasReferences()) {
1228       LOG.debug("Region " + getRegionInfo().getRegionNameAsString()
1229           + " is not mergeable because it has references");
1230       return false;
1231     }
1232 
1233     return true;
1234   }
1235 
1236   public boolean areWritesEnabled() {
1237     synchronized(this.writestate) {
1238       return this.writestate.writesEnabled;
1239     }
1240   }
1241 
1242    public MultiVersionConsistencyControl getMVCC() {
1243      return mvcc;
1244    }
1245 
1246    @Override
1247    public long getMaxFlushedSeqId() {
1248      return maxFlushedSeqId;
1249    }
1250 
1251    @Override
1252    public long getReadpoint(IsolationLevel isolationLevel) {
1253      if (isolationLevel == IsolationLevel.READ_UNCOMMITTED) {
1254        // This scan can read even uncommitted transactions
1255        return Long.MAX_VALUE;
1256      }
1257      return mvcc.memstoreReadPoint();
1258    }
1259 
1260    @Override
1261    public boolean isLoadingCfsOnDemandDefault() {
1262      return this.isLoadingCfsOnDemandDefault;
1263    }
1264 
1265   /**
1266    * Close down this HRegion.  Flush the cache, shut down each HStore, don't
1267    * service any more calls.
1268    *
1269    * <p>This method could take some time to execute, so don't call it from a
1270    * time-sensitive thread.
1271    *
1272    * @return Vector of all the storage files that the HRegion's component
1273    * HStores make use of.  It's a list of all HStoreFile objects. Returns empty
1274    * vector if already closed and null if judged that it should not close.
1275    *
1276    * @throws IOException e
1277    */
1278   public Map<byte[], List<StoreFile>> close() throws IOException {
1279     return close(false);
1280   }
1281 
1282   private final Object closeLock = new Object();
1283 
1284   /** Conf key for the periodic flush interval */
1285   public static final String MEMSTORE_PERIODIC_FLUSH_INTERVAL =
1286       "hbase.regionserver.optionalcacheflushinterval";
1287   /** Default interval for the memstore flush */
1288   public static final int DEFAULT_CACHE_FLUSH_INTERVAL = 3600000;
1289   public static final int META_CACHE_FLUSH_INTERVAL = 300000; // 5 minutes
1290 
1291   /** Conf key to force a flush if there are already enough changes for one region in memstore */
1292   public static final String MEMSTORE_FLUSH_PER_CHANGES =
1293       "hbase.regionserver.flush.per.changes";
1294   public static final long DEFAULT_FLUSH_PER_CHANGES = 30000000; // 30 millions
1295   /**
1296    * The following MAX_FLUSH_PER_CHANGES is large enough because each KeyValue has 20+ bytes
1297    * overhead. Therefore, even 1G empty KVs occupy at least 20GB memstore size for a single region
1298    */
1299   public static final long MAX_FLUSH_PER_CHANGES = 1000000000; // 1G
1300 
1301   /**
1302    * Close down this HRegion.  Flush the cache unless abort parameter is true,
1303    * Shut down each HStore, don't service any more calls.
1304    *
1305    * This method could take some time to execute, so don't call it from a
1306    * time-sensitive thread.
1307    *
1308    * @param abort true if server is aborting (only during testing)
1309    * @return Vector of all the storage files that the HRegion's component
1310    * HStores make use of.  It's a list of HStoreFile objects.  Can be null if
1311    * we are not to close at this time or we are already closed.
1312    *
1313    * @throws IOException e
1314    */
1315   public Map<byte[], List<StoreFile>> close(final boolean abort) throws IOException {
1316     // Only allow one thread to close at a time. Serialize them so dual
1317     // threads attempting to close will run up against each other.
1318     MonitoredTask status = TaskMonitor.get().createStatus(
1319         "Closing region " + this +
1320         (abort ? " due to abort" : ""));
1321 
1322     status.setStatus("Waiting for close lock");
1323     try {
1324       synchronized (closeLock) {
1325         return doClose(abort, status);
1326       }
1327     } finally {
1328       status.cleanup();
1329     }
1330   }
1331 
1332   private Map<byte[], List<StoreFile>> doClose(final boolean abort, MonitoredTask status)
1333       throws IOException {
1334     if (isClosed()) {
1335       LOG.warn("Region " + this + " already closed");
1336       return null;
1337     }
1338 
1339     if (coprocessorHost != null) {
1340       status.setStatus("Running coprocessor pre-close hooks");
1341       this.coprocessorHost.preClose(abort);
1342     }
1343 
1344     status.setStatus("Disabling compacts and flushes for region");
1345     boolean canFlush = true;
1346     synchronized (writestate) {
1347       // Disable compacting and flushing by background threads for this
1348       // region.
1349       canFlush = !writestate.readOnly;
1350       writestate.writesEnabled = false;
1351       LOG.debug("Closing " + this + ": disabling compactions & flushes");
1352       waitForFlushesAndCompactions();
1353     }
1354     // If we were not just flushing, is it worth doing a preflush...one
1355     // that will clear out of the bulk of the memstore before we put up
1356     // the close flag?
1357     if (!abort && worthPreFlushing() && canFlush) {
1358       status.setStatus("Pre-flushing region before close");
1359       LOG.info("Running close preflush of " + getRegionInfo().getRegionNameAsString());
1360       try {
1361         internalFlushcache(status);
1362       } catch (IOException ioe) {
1363         // Failed to flush the region. Keep going.
1364         status.setStatus("Failed pre-flush " + this + "; " + ioe.getMessage());
1365       }
1366     }
1367 
1368     this.closing.set(true);
1369     status.setStatus("Disabling writes for close");
1370     // block waiting for the lock for closing
1371     lock.writeLock().lock();
1372     try {
1373       if (this.isClosed()) {
1374         status.abort("Already got closed by another process");
1375         // SplitTransaction handles the null
1376         return null;
1377       }
1378       LOG.debug("Updates disabled for region " + this);
1379       // Don't flush the cache if we are aborting
1380       if (!abort && canFlush) {
1381         int flushCount = 0;
1382         while (this.memstoreSize.get() > 0) {
1383           try {
1384             if (flushCount++ > 0) {
1385               int actualFlushes = flushCount - 1;
1386               if (actualFlushes > 5) {
1387                 // If we tried 5 times and are unable to clear memory, abort
1388                 // so we do not lose data
1389                 throw new DroppedSnapshotException("Failed clearing memory after " +
1390                   actualFlushes + " attempts on region: " +
1391                     Bytes.toStringBinary(getRegionInfo().getRegionName()));
1392               }
1393               LOG.info("Running extra flush, " + actualFlushes +
1394                 " (carrying snapshot?) " + this);
1395             }
1396             internalFlushcache(status);
1397           } catch (IOException ioe) {
1398             status.setStatus("Failed flush " + this + ", putting online again");
1399             synchronized (writestate) {
1400               writestate.writesEnabled = true;
1401             }
1402             // Have to throw to upper layers.  I can't abort server from here.
1403             throw ioe;
1404           }
1405         }
1406       }
1407 
1408       Map<byte[], List<StoreFile>> result =
1409         new TreeMap<byte[], List<StoreFile>>(Bytes.BYTES_COMPARATOR);
1410       if (!stores.isEmpty()) {
1411         // initialize the thread pool for closing stores in parallel.
1412         ThreadPoolExecutor storeCloserThreadPool =
1413           getStoreOpenAndCloseThreadPool("StoreCloserThread-" +
1414             getRegionInfo().getRegionNameAsString());
1415         CompletionService<Pair<byte[], Collection<StoreFile>>> completionService =
1416           new ExecutorCompletionService<Pair<byte[], Collection<StoreFile>>>(storeCloserThreadPool);
1417 
1418         // close each store in parallel
1419         for (final Store store : stores.values()) {
1420           assert abort || store.getFlushableSize() == 0 || writestate.readOnly;
1421           completionService
1422               .submit(new Callable<Pair<byte[], Collection<StoreFile>>>() {
1423                 @Override
1424                 public Pair<byte[], Collection<StoreFile>> call() throws IOException {
1425                   return new Pair<byte[], Collection<StoreFile>>(
1426                     store.getFamily().getName(), store.close());
1427                 }
1428               });
1429         }
1430         try {
1431           for (int i = 0; i < stores.size(); i++) {
1432             Future<Pair<byte[], Collection<StoreFile>>> future = completionService.take();
1433             Pair<byte[], Collection<StoreFile>> storeFiles = future.get();
1434             List<StoreFile> familyFiles = result.get(storeFiles.getFirst());
1435             if (familyFiles == null) {
1436               familyFiles = new ArrayList<StoreFile>();
1437               result.put(storeFiles.getFirst(), familyFiles);
1438             }
1439             familyFiles.addAll(storeFiles.getSecond());
1440           }
1441         } catch (InterruptedException e) {
1442           throw (InterruptedIOException)new InterruptedIOException().initCause(e);
1443         } catch (ExecutionException e) {
1444           throw new IOException(e.getCause());
1445         } finally {
1446           storeCloserThreadPool.shutdownNow();
1447         }
1448       }
1449 
1450       status.setStatus("Writing region close event to WAL");
1451       if (!abort && wal != null && getRegionServerServices() != null && !writestate.readOnly) {
1452         writeRegionCloseMarker(wal);
1453       }
1454 
1455       this.closed.set(true);
1456       if (!canFlush) {
1457         addAndGetGlobalMemstoreSize(-memstoreSize.get());
1458       } else if (memstoreSize.get() != 0) {
1459         LOG.error("Memstore size is " + memstoreSize.get());
1460       }
1461       if (coprocessorHost != null) {
1462         status.setStatus("Running coprocessor post-close hooks");
1463         this.coprocessorHost.postClose(abort);
1464       }
1465       if (this.metricsRegion != null) {
1466         this.metricsRegion.close();
1467       }
1468       if (this.metricsRegionWrapper != null) {
1469         Closeables.closeQuietly(this.metricsRegionWrapper);
1470       }
1471       status.markComplete("Closed");
1472       LOG.info("Closed " + this);
1473       return result;
1474     } finally {
1475       lock.writeLock().unlock();
1476     }
1477   }
1478 
1479   @Override
1480   public void waitForFlushesAndCompactions() {
1481     synchronized (writestate) {
1482       if (this.writestate.readOnly) {
1483         // we should not wait for replayed flushed if we are read only (for example in case the
1484         // region is a secondary replica).
1485         return;
1486       }
1487       boolean interrupted = false;
1488       try {
1489         while (writestate.compacting > 0 || writestate.flushing) {
1490           LOG.debug("waiting for " + writestate.compacting + " compactions"
1491             + (writestate.flushing ? " & cache flush" : "") + " to complete for region " + this);
1492           try {
1493             writestate.wait();
1494           } catch (InterruptedException iex) {
1495             // essentially ignore and propagate the interrupt back up
1496             LOG.warn("Interrupted while waiting");
1497             interrupted = true;
1498           }
1499         }
1500       } finally {
1501         if (interrupted) {
1502           Thread.currentThread().interrupt();
1503         }
1504       }
1505     }
1506   }
1507 
1508   protected ThreadPoolExecutor getStoreOpenAndCloseThreadPool(
1509       final String threadNamePrefix) {
1510     int numStores = Math.max(1, this.htableDescriptor.getFamilies().size());
1511     int maxThreads = Math.min(numStores,
1512         conf.getInt(HConstants.HSTORE_OPEN_AND_CLOSE_THREADS_MAX,
1513             HConstants.DEFAULT_HSTORE_OPEN_AND_CLOSE_THREADS_MAX));
1514     return getOpenAndCloseThreadPool(maxThreads, threadNamePrefix);
1515   }
1516 
1517   protected ThreadPoolExecutor getStoreFileOpenAndCloseThreadPool(
1518       final String threadNamePrefix) {
1519     int numStores = Math.max(1, this.htableDescriptor.getFamilies().size());
1520     int maxThreads = Math.max(1,
1521         conf.getInt(HConstants.HSTORE_OPEN_AND_CLOSE_THREADS_MAX,
1522             HConstants.DEFAULT_HSTORE_OPEN_AND_CLOSE_THREADS_MAX)
1523             / numStores);
1524     return getOpenAndCloseThreadPool(maxThreads, threadNamePrefix);
1525   }
1526 
1527   static ThreadPoolExecutor getOpenAndCloseThreadPool(int maxThreads,
1528       final String threadNamePrefix) {
1529     return Threads.getBoundedCachedThreadPool(maxThreads, 30L, TimeUnit.SECONDS,
1530       new ThreadFactory() {
1531         private int count = 1;
1532 
1533         @Override
1534         public Thread newThread(Runnable r) {
1535           return new Thread(r, threadNamePrefix + "-" + count++);
1536         }
1537       });
1538   }
1539 
1540    /**
1541     * @return True if its worth doing a flush before we put up the close flag.
1542     */
1543   private boolean worthPreFlushing() {
1544     return this.memstoreSize.get() >
1545       this.conf.getLong("hbase.hregion.preclose.flush.size", 1024 * 1024 * 5);
1546   }
1547 
1548   //////////////////////////////////////////////////////////////////////////////
1549   // HRegion accessors
1550   //////////////////////////////////////////////////////////////////////////////
1551 
1552   @Override
1553   public HTableDescriptor getTableDesc() {
1554     return this.htableDescriptor;
1555   }
1556 
1557   /** @return WAL in use for this region */
1558   public WAL getWAL() {
1559     return this.wal;
1560   }
1561 
1562   /**
1563    * A split takes the config from the parent region & passes it to the daughter
1564    * region's constructor. If 'conf' was passed, you would end up using the HTD
1565    * of the parent region in addition to the new daughter HTD. Pass 'baseConf'
1566    * to the daughter regions to avoid this tricky dedupe problem.
1567    * @return Configuration object
1568    */
1569   Configuration getBaseConf() {
1570     return this.baseConf;
1571   }
1572 
1573   /** @return {@link FileSystem} being used by this region */
1574   public FileSystem getFilesystem() {
1575     return fs.getFileSystem();
1576   }
1577 
1578   /** @return the {@link HRegionFileSystem} used by this region */
1579   public HRegionFileSystem getRegionFileSystem() {
1580     return this.fs;
1581   }
1582 
1583   @Override
1584   public long getEarliestFlushTimeForAllStores() {
1585     return lastStoreFlushTimeMap.isEmpty() ? Long.MAX_VALUE : Collections.min(lastStoreFlushTimeMap
1586         .values());
1587   }
1588 
1589   @Override
1590   public long getOldestHfileTs(boolean majorCompactioOnly) throws IOException {
1591     long result = Long.MAX_VALUE;
1592     for (Store store : getStores()) {
1593       for (StoreFile file : store.getStorefiles()) {
1594         HFile.Reader reader = file.getReader().getHFileReader();
1595         if (majorCompactioOnly) {
1596           byte[] val = reader.loadFileInfo().get(StoreFile.MAJOR_COMPACTION_KEY);
1597           if (val == null || !Bytes.toBoolean(val)) {
1598             continue;
1599           }
1600         }
1601         result = Math.min(result, reader.getFileContext().getFileCreateTime());
1602       }
1603     }
1604     return result == Long.MAX_VALUE ? 0 : result;
1605   }
1606 
1607   RegionLoad.Builder setCompleteSequenceId(RegionLoad.Builder regionLoadBldr) {
1608     long lastFlushOpSeqIdLocal = this.lastFlushOpSeqId;
1609     byte[] encodedRegionName = this.getRegionInfo().getEncodedNameAsBytes();
1610     regionLoadBldr.clearStoreCompleteSequenceId();
1611     for (byte[] familyName : this.stores.keySet()) {
1612       long oldestUnflushedSeqId = this.wal.getEarliestMemstoreSeqNum(encodedRegionName, familyName);
1613       // no oldestUnflushedSeqId means no data has written to the store after last flush, so we use
1614       // lastFlushOpSeqId as complete sequence id for the store.
1615       regionLoadBldr.addStoreCompleteSequenceId(StoreSequenceId
1616           .newBuilder()
1617           .setFamilyName(ByteString.copyFrom(familyName))
1618           .setSequenceId(
1619             oldestUnflushedSeqId < 0 ? lastFlushOpSeqIdLocal : oldestUnflushedSeqId - 1).build());
1620     }
1621     return regionLoadBldr.setCompleteSequenceId(this.maxFlushedSeqId);
1622   }
1623 
1624   //////////////////////////////////////////////////////////////////////////////
1625   // HRegion maintenance.
1626   //
1627   // These methods are meant to be called periodically by the HRegionServer for
1628   // upkeep.
1629   //////////////////////////////////////////////////////////////////////////////
1630 
1631   /** @return returns size of largest HStore. */
1632   public long getLargestHStoreSize() {
1633     long size = 0;
1634     for (Store h : stores.values()) {
1635       long storeSize = h.getSize();
1636       if (storeSize > size) {
1637         size = storeSize;
1638       }
1639     }
1640     return size;
1641   }
1642 
1643   /**
1644    * @return KeyValue Comparator
1645    */
1646   public KeyValue.KVComparator getComparator() {
1647     return this.comparator;
1648   }
1649 
1650   /*
1651    * Do preparation for pending compaction.
1652    * @throws IOException
1653    */
1654   protected void doRegionCompactionPrep() throws IOException {
1655   }
1656 
1657   @Override
1658   public void triggerMajorCompaction() throws IOException {
1659     for (Store s : getStores()) {
1660       s.triggerMajorCompaction();
1661     }
1662   }
1663 
1664   @Override
1665   public void compact(final boolean majorCompaction) throws IOException {
1666     if (majorCompaction) {
1667       triggerMajorCompaction();
1668     }
1669     for (Store s : getStores()) {
1670       CompactionContext compaction = s.requestCompaction();
1671       if (compaction != null) {
1672         CompactionThroughputController controller = null;
1673         if (rsServices != null) {
1674           controller = CompactionThroughputControllerFactory.create(rsServices, conf);
1675         }
1676         if (controller == null) {
1677           controller = NoLimitCompactionThroughputController.INSTANCE;
1678         }
1679         compact(compaction, s, controller);
1680       }
1681     }
1682   }
1683 
1684   /**
1685    * This is a helper function that compact all the stores synchronously
1686    * It is used by utilities and testing
1687    *
1688    * @throws IOException e
1689    */
1690   public void compactStores() throws IOException {
1691     for (Store s : getStores()) {
1692       CompactionContext compaction = s.requestCompaction();
1693       if (compaction != null) {
1694         compact(compaction, s, NoLimitCompactionThroughputController.INSTANCE);
1695       }
1696     }
1697   }
1698 
1699   /**
1700    * This is a helper function that compact the given store
1701    * It is used by utilities and testing
1702    *
1703    * @throws IOException e
1704    */
1705   @VisibleForTesting
1706   void compactStore(byte[] family, CompactionThroughputController throughputController)
1707       throws IOException {
1708     Store s = getStore(family);
1709     CompactionContext compaction = s.requestCompaction();
1710     if (compaction != null) {
1711       compact(compaction, s, throughputController);
1712     }
1713   }
1714 
1715   /*
1716    * Called by compaction thread and after region is opened to compact the
1717    * HStores if necessary.
1718    *
1719    * <p>This operation could block for a long time, so don't call it from a
1720    * time-sensitive thread.
1721    *
1722    * Note that no locking is necessary at this level because compaction only
1723    * conflicts with a region split, and that cannot happen because the region
1724    * server does them sequentially and not in parallel.
1725    *
1726    * @param compaction Compaction details, obtained by requestCompaction()
1727    * @return whether the compaction completed
1728    */
1729   public boolean compact(CompactionContext compaction, Store store,
1730       CompactionThroughputController throughputController) throws IOException {
1731     assert compaction != null && compaction.hasSelection();
1732     assert !compaction.getRequest().getFiles().isEmpty();
1733     if (this.closing.get() || this.closed.get()) {
1734       LOG.debug("Skipping compaction on " + this + " because closing/closed");
1735       store.cancelRequestedCompaction(compaction);
1736       return false;
1737     }
1738     MonitoredTask status = null;
1739     boolean requestNeedsCancellation = true;
1740     // block waiting for the lock for compaction
1741     lock.readLock().lock();
1742     try {
1743       byte[] cf = Bytes.toBytes(store.getColumnFamilyName());
1744       if (stores.get(cf) != store) {
1745         LOG.warn("Store " + store.getColumnFamilyName() + " on region " + this
1746             + " has been re-instantiated, cancel this compaction request. "
1747             + " It may be caused by the roll back of split transaction");
1748         return false;
1749       }
1750 
1751       status = TaskMonitor.get().createStatus("Compacting " + store + " in " + this);
1752       if (this.closed.get()) {
1753         String msg = "Skipping compaction on " + this + " because closed";
1754         LOG.debug(msg);
1755         status.abort(msg);
1756         return false;
1757       }
1758       boolean wasStateSet = false;
1759       try {
1760         synchronized (writestate) {
1761           if (writestate.writesEnabled) {
1762             wasStateSet = true;
1763             ++writestate.compacting;
1764           } else {
1765             String msg = "NOT compacting region " + this + ". Writes disabled.";
1766             LOG.info(msg);
1767             status.abort(msg);
1768             return false;
1769           }
1770         }
1771         LOG.info("Starting compaction on " + store + " in region " + this
1772             + (compaction.getRequest().isOffPeak()?" as an off-peak compaction":""));
1773         doRegionCompactionPrep();
1774         try {
1775           status.setStatus("Compacting store " + store);
1776           // We no longer need to cancel the request on the way out of this
1777           // method because Store#compact will clean up unconditionally
1778           requestNeedsCancellation = false;
1779           store.compact(compaction, throughputController);
1780         } catch (InterruptedIOException iioe) {
1781           String msg = "compaction interrupted";
1782           LOG.info(msg, iioe);
1783           status.abort(msg);
1784           return false;
1785         }
1786       } finally {
1787         if (wasStateSet) {
1788           synchronized (writestate) {
1789             --writestate.compacting;
1790             if (writestate.compacting <= 0) {
1791               writestate.notifyAll();
1792             }
1793           }
1794         }
1795       }
1796       status.markComplete("Compaction complete");
1797       return true;
1798     } finally {
1799       try {
1800         if (requestNeedsCancellation) store.cancelRequestedCompaction(compaction);
1801         if (status != null) status.cleanup();
1802       } finally {
1803         lock.readLock().unlock();
1804       }
1805     }
1806   }
1807 
1808   @Override
1809   public FlushResult flush(boolean force) throws IOException {
1810     return flushcache(force, false);
1811   }
1812 
1813   /**
1814    * Flush the cache.
1815    *
1816    * When this method is called the cache will be flushed unless:
1817    * <ol>
1818    *   <li>the cache is empty</li>
1819    *   <li>the region is closed.</li>
1820    *   <li>a flush is already in progress</li>
1821    *   <li>writes are disabled</li>
1822    * </ol>
1823    *
1824    * <p>This method may block for some time, so it should not be called from a
1825    * time-sensitive thread.
1826    * @param forceFlushAllStores whether we want to flush all stores
1827    * @param writeFlushRequestWalMarker whether to write the flush request marker to WAL
1828    * @return whether the flush is success and whether the region needs compacting
1829    *
1830    * @throws IOException general io exceptions
1831    * @throws DroppedSnapshotException Thrown when replay of wal is required
1832    * because a Snapshot was not properly persisted.
1833    */
1834   public FlushResult flushcache(boolean forceFlushAllStores, boolean writeFlushRequestWalMarker)
1835       throws IOException {
1836     // fail-fast instead of waiting on the lock
1837     if (this.closing.get()) {
1838       String msg = "Skipping flush on " + this + " because closing";
1839       LOG.debug(msg);
1840       return new FlushResultImpl(FlushResult.Result.CANNOT_FLUSH, msg, false);
1841     }
1842     MonitoredTask status = TaskMonitor.get().createStatus("Flushing " + this);
1843     status.setStatus("Acquiring readlock on region");
1844     // block waiting for the lock for flushing cache
1845     lock.readLock().lock();
1846     try {
1847       if (this.closed.get()) {
1848         String msg = "Skipping flush on " + this + " because closed";
1849         LOG.debug(msg);
1850         status.abort(msg);
1851         return new FlushResultImpl(FlushResult.Result.CANNOT_FLUSH, msg, false);
1852       }
1853       if (coprocessorHost != null) {
1854         status.setStatus("Running coprocessor pre-flush hooks");
1855         coprocessorHost.preFlush();
1856       }
1857       // TODO: this should be managed within memstore with the snapshot, updated only after flush
1858       // successful
1859       if (numMutationsWithoutWAL.get() > 0) {
1860         numMutationsWithoutWAL.set(0);
1861         dataInMemoryWithoutWAL.set(0);
1862       }
1863       synchronized (writestate) {
1864         if (!writestate.flushing && writestate.writesEnabled) {
1865           this.writestate.flushing = true;
1866         } else {
1867           if (LOG.isDebugEnabled()) {
1868             LOG.debug("NOT flushing memstore for region " + this
1869                 + ", flushing=" + writestate.flushing + ", writesEnabled="
1870                 + writestate.writesEnabled);
1871           }
1872           String msg = "Not flushing since "
1873               + (writestate.flushing ? "already flushing"
1874               : "writes not enabled");
1875           status.abort(msg);
1876           return new FlushResultImpl(FlushResult.Result.CANNOT_FLUSH, msg, false);
1877         }
1878       }
1879 
1880       try {
1881         Collection<Store> specificStoresToFlush =
1882             forceFlushAllStores ? stores.values() : flushPolicy.selectStoresToFlush();
1883         FlushResult fs = internalFlushcache(specificStoresToFlush,
1884           status, writeFlushRequestWalMarker);
1885 
1886         if (coprocessorHost != null) {
1887           status.setStatus("Running post-flush coprocessor hooks");
1888           coprocessorHost.postFlush();
1889         }
1890 
1891         status.markComplete("Flush successful");
1892         return fs;
1893       } finally {
1894         synchronized (writestate) {
1895           writestate.flushing = false;
1896           this.writestate.flushRequested = false;
1897           writestate.notifyAll();
1898         }
1899       }
1900     } finally {
1901       lock.readLock().unlock();
1902       status.cleanup();
1903     }
1904   }
1905 
1906   /**
1907    * Should the store be flushed because it is old enough.
1908    * <p>
1909    * Every FlushPolicy should call this to determine whether a store is old enough to flush(except
1910    * that you always flush all stores). Otherwise the {@link #shouldFlush()} method will always
1911    * returns true which will make a lot of flush requests.
1912    */
1913   boolean shouldFlushStore(Store store) {
1914     long maxFlushedSeqId =
1915         this.wal.getEarliestMemstoreSeqNum(getRegionInfo().getEncodedNameAsBytes(), store
1916             .getFamily().getName()) - 1;
1917     if (maxFlushedSeqId > 0 && maxFlushedSeqId + flushPerChanges < sequenceId.get()) {
1918       if (LOG.isDebugEnabled()) {
1919         LOG.debug("Column Family: " + store.getColumnFamilyName() + " of region " + this
1920             + " will be flushed because its max flushed seqId(" + maxFlushedSeqId
1921             + ") is far away from current(" + sequenceId.get() + "), max allowed is "
1922             + flushPerChanges);
1923       }
1924       return true;
1925     }
1926     if (flushCheckInterval <= 0) {
1927       return false;
1928     }
1929     long now = EnvironmentEdgeManager.currentTime();
1930     if (store.timeOfOldestEdit() < now - flushCheckInterval) {
1931       if (LOG.isDebugEnabled()) {
1932         LOG.debug("Column Family: " + store.getColumnFamilyName() + " of region " + this
1933             + " will be flushed because time of its oldest edit (" + store.timeOfOldestEdit()
1934             + ") is far away from now(" + now + "), max allowed is " + flushCheckInterval);
1935       }
1936       return true;
1937     }
1938     return false;
1939   }
1940 
1941   /**
1942    * Should the memstore be flushed now
1943    */
1944   boolean shouldFlush() {
1945     // This is a rough measure.
1946     if (this.maxFlushedSeqId > 0
1947           && (this.maxFlushedSeqId + this.flushPerChanges < this.sequenceId.get())) {
1948       return true;
1949     }
1950     long modifiedFlushCheckInterval = flushCheckInterval;
1951     if (getRegionInfo().isMetaRegion() &&
1952         getRegionInfo().getReplicaId() == HRegionInfo.DEFAULT_REPLICA_ID) {
1953       modifiedFlushCheckInterval = META_CACHE_FLUSH_INTERVAL;
1954     }
1955     if (modifiedFlushCheckInterval <= 0) { //disabled
1956       return false;
1957     }
1958     long now = EnvironmentEdgeManager.currentTime();
1959     //if we flushed in the recent past, we don't need to do again now
1960     if ((now - getEarliestFlushTimeForAllStores() < modifiedFlushCheckInterval)) {
1961       return false;
1962     }
1963     //since we didn't flush in the recent past, flush now if certain conditions
1964     //are met. Return true on first such memstore hit.
1965     for (Store s : getStores()) {
1966       if (s.timeOfOldestEdit() < now - modifiedFlushCheckInterval) {
1967         // we have an old enough edit in the memstore, flush
1968         return true;
1969       }
1970     }
1971     return false;
1972   }
1973 
1974   /**
1975    * Flushing all stores.
1976    *
1977    * @see #internalFlushcache(Collection, MonitoredTask, boolean)
1978    */
1979   private FlushResult internalFlushcache(MonitoredTask status)
1980       throws IOException {
1981     return internalFlushcache(stores.values(), status, false);
1982   }
1983 
1984   /**
1985    * Flushing given stores.
1986    *
1987    * @see #internalFlushcache(WAL, long, Collection, MonitoredTask, boolean)
1988    */
1989   private FlushResult internalFlushcache(final Collection<Store> storesToFlush,
1990       MonitoredTask status, boolean writeFlushWalMarker) throws IOException {
1991     return internalFlushcache(this.wal, HConstants.NO_SEQNUM, storesToFlush,
1992         status, writeFlushWalMarker);
1993   }
1994 
1995   /**
1996    * Flush the memstore. Flushing the memstore is a little tricky. We have a lot
1997    * of updates in the memstore, all of which have also been written to the wal.
1998    * We need to write those updates in the memstore out to disk, while being
1999    * able to process reads/writes as much as possible during the flush
2000    * operation.
2001    * <p>
2002    * This method may block for some time. Every time you call it, we up the
2003    * regions sequence id even if we don't flush; i.e. the returned region id
2004    * will be at least one larger than the last edit applied to this region. The
2005    * returned id does not refer to an actual edit. The returned id can be used
2006    * for say installing a bulk loaded file just ahead of the last hfile that was
2007    * the result of this flush, etc.
2008    *
2009    * @param wal
2010    *          Null if we're NOT to go via wal.
2011    * @param myseqid
2012    *          The seqid to use if <code>wal</code> is null writing out flush
2013    *          file.
2014    * @param storesToFlush
2015    *          The list of stores to flush.
2016    * @return object describing the flush's state
2017    * @throws IOException
2018    *           general io exceptions
2019    * @throws DroppedSnapshotException
2020    *           Thrown when replay of wal is required because a Snapshot was not
2021    *           properly persisted.
2022    */
2023   protected FlushResult internalFlushcache(final WAL wal, final long myseqid,
2024       final Collection<Store> storesToFlush, MonitoredTask status, boolean writeFlushWalMarker)
2025           throws IOException {
2026     PrepareFlushResult result
2027       = internalPrepareFlushCache(wal, myseqid, storesToFlush, status, writeFlushWalMarker);
2028     if (result.result == null) {
2029       return internalFlushCacheAndCommit(wal, status, result, storesToFlush);
2030     } else {
2031       return result.result; // early exit due to failure from prepare stage
2032     }
2033   }
2034 
2035   protected PrepareFlushResult internalPrepareFlushCache(
2036       final WAL wal, final long myseqid, final Collection<Store> storesToFlush,
2037       MonitoredTask status, boolean writeFlushWalMarker)
2038           throws IOException {
2039 
2040     if (this.rsServices != null && this.rsServices.isAborted()) {
2041       // Don't flush when server aborting, it's unsafe
2042       throw new IOException("Aborting flush because server is aborted...");
2043     }
2044     final long startTime = EnvironmentEdgeManager.currentTime();
2045     // If nothing to flush, return, but we need to safely update the region sequence id
2046     if (this.memstoreSize.get() <= 0) {
2047       // Take an update lock because am about to change the sequence id and we want the sequence id
2048       // to be at the border of the empty memstore.
2049       MultiVersionConsistencyControl.WriteEntry w = null;
2050       this.updatesLock.writeLock().lock();
2051       try {
2052         if (this.memstoreSize.get() <= 0) {
2053           // Presume that if there are still no edits in the memstore, then there are no edits for
2054           // this region out in the WAL subsystem so no need to do any trickery clearing out
2055           // edits in the WAL system. Up the sequence number so the resulting flush id is for
2056           // sure just beyond the last appended region edit (useful as a marker when bulk loading,
2057           // etc.)
2058           // wal can be null replaying edits.
2059           if (wal != null) {
2060             w = mvcc.beginMemstoreInsert();
2061             long flushOpSeqId = getNextSequenceId(wal);
2062             FlushResult flushResult = new FlushResultImpl(
2063               FlushResult.Result.CANNOT_FLUSH_MEMSTORE_EMPTY, flushOpSeqId, "Nothing to flush",
2064               writeFlushRequestMarkerToWAL(wal, writeFlushWalMarker));
2065             w.setWriteNumber(flushOpSeqId);
2066             mvcc.waitForPreviousTransactionsComplete(w);
2067             w = null;
2068             return new PrepareFlushResult(flushResult, myseqid);
2069           } else {
2070             return new PrepareFlushResult(
2071               new FlushResultImpl(FlushResult.Result.CANNOT_FLUSH_MEMSTORE_EMPTY,
2072                 "Nothing to flush", false),
2073               myseqid);
2074           }
2075         }
2076       } finally {
2077         this.updatesLock.writeLock().unlock();
2078         if (w != null) {
2079           mvcc.advanceMemstore(w);
2080         }
2081       }
2082     }
2083 
2084     if (LOG.isInfoEnabled()) {
2085       LOG.info("Started memstore flush for " + this + ", current region memstore size "
2086           + StringUtils.byteDesc(this.memstoreSize.get()) + ", and " + storesToFlush.size() + "/"
2087           + stores.size() + " column families' memstores are being flushed."
2088           + ((wal != null) ? "" : "; wal is null, using passed sequenceid=" + myseqid));
2089       // only log when we are not flushing all stores.
2090       if (this.stores.size() > storesToFlush.size()) {
2091         for (Store store: storesToFlush) {
2092           LOG.info("Flushing Column Family: " + store.getColumnFamilyName()
2093               + " which was occupying "
2094               + StringUtils.byteDesc(store.getMemStoreSize()) + " of memstore.");
2095         }
2096       }
2097     }
2098     // Stop updates while we snapshot the memstore of all of these regions' stores. We only have
2099     // to do this for a moment.  It is quick. We also set the memstore size to zero here before we
2100     // allow updates again so its value will represent the size of the updates received
2101     // during flush
2102     MultiVersionConsistencyControl.WriteEntry w = null;
2103     // We have to take an update lock during snapshot, or else a write could end up in both snapshot
2104     // and memstore (makes it difficult to do atomic rows then)
2105     status.setStatus("Obtaining lock to block concurrent updates");
2106     // block waiting for the lock for internal flush
2107     this.updatesLock.writeLock().lock();
2108     status.setStatus("Preparing to flush by snapshotting stores in " +
2109       getRegionInfo().getEncodedName());
2110     long totalFlushableSizeOfFlushableStores = 0;
2111 
2112     Set<byte[]> flushedFamilyNames = new HashSet<byte[]>();
2113     for (Store store: storesToFlush) {
2114       flushedFamilyNames.add(store.getFamily().getName());
2115     }
2116 
2117     TreeMap<byte[], StoreFlushContext> storeFlushCtxs
2118       = new TreeMap<byte[], StoreFlushContext>(Bytes.BYTES_COMPARATOR);
2119     TreeMap<byte[], List<Path>> committedFiles = new TreeMap<byte[], List<Path>>(
2120         Bytes.BYTES_COMPARATOR);
2121     // The sequence id of this flush operation which is used to log FlushMarker and pass to
2122     // createFlushContext to use as the store file's sequence id.
2123     long flushOpSeqId = HConstants.NO_SEQNUM;
2124     // The max flushed sequence id after this flush operation. Used as completeSequenceId which is
2125     // passed to HMaster.
2126     long flushedSeqId = HConstants.NO_SEQNUM;
2127     byte[] encodedRegionName = getRegionInfo().getEncodedNameAsBytes();
2128 
2129     long trxId = 0;
2130     try {
2131       try {
2132         w = mvcc.beginMemstoreInsert();
2133         if (wal != null) {
2134           if (!wal.startCacheFlush(encodedRegionName, flushedFamilyNames)) {
2135             // This should never happen.
2136             String msg = "Flush will not be started for ["
2137                 + this.getRegionInfo().getEncodedName() + "] - because the WAL is closing.";
2138             status.setStatus(msg);
2139             return new PrepareFlushResult(
2140               new FlushResultImpl(FlushResult.Result.CANNOT_FLUSH, msg, false),
2141               myseqid);
2142           }
2143           flushOpSeqId = getNextSequenceId(wal);
2144           long oldestUnflushedSeqId = wal.getEarliestMemstoreSeqNum(encodedRegionName);
2145           // no oldestUnflushedSeqId means we flushed all stores.
2146           // or the unflushed stores are all empty.
2147           flushedSeqId = (oldestUnflushedSeqId == HConstants.NO_SEQNUM) ? flushOpSeqId
2148               : oldestUnflushedSeqId - 1;
2149         } else {
2150           // use the provided sequence Id as WAL is not being used for this flush.
2151           flushedSeqId = flushOpSeqId = myseqid;
2152         }
2153 
2154         for (Store s : storesToFlush) {
2155           totalFlushableSizeOfFlushableStores += s.getFlushableSize();
2156           storeFlushCtxs.put(s.getFamily().getName(), s.createFlushContext(flushOpSeqId));
2157           committedFiles.put(s.getFamily().getName(), null); // for writing stores to WAL
2158         }
2159 
2160         // write the snapshot start to WAL
2161         if (wal != null && !writestate.readOnly) {
2162           FlushDescriptor desc = ProtobufUtil.toFlushDescriptor(FlushAction.START_FLUSH,
2163             getRegionInfo(), flushOpSeqId, committedFiles);
2164           // no sync. Sync is below where we do not hold the updates lock
2165           trxId = WALUtil.writeFlushMarker(wal, this.htableDescriptor, getRegionInfo(),
2166             desc, sequenceId, false);
2167         }
2168 
2169         // Prepare flush (take a snapshot)
2170         for (StoreFlushContext flush : storeFlushCtxs.values()) {
2171           flush.prepare();
2172         }
2173       } catch (IOException ex) {
2174         if (wal != null) {
2175           if (trxId > 0) { // check whether we have already written START_FLUSH to WAL
2176             try {
2177               FlushDescriptor desc = ProtobufUtil.toFlushDescriptor(FlushAction.ABORT_FLUSH,
2178                 getRegionInfo(), flushOpSeqId, committedFiles);
2179               WALUtil.writeFlushMarker(wal, this.htableDescriptor, getRegionInfo(),
2180                 desc, sequenceId, false);
2181             } catch (Throwable t) {
2182               LOG.warn("Received unexpected exception trying to write ABORT_FLUSH marker to WAL:" +
2183                   StringUtils.stringifyException(t));
2184               // ignore this since we will be aborting the RS with DSE.
2185             }
2186           }
2187           // we have called wal.startCacheFlush(), now we have to abort it
2188           wal.abortCacheFlush(this.getRegionInfo().getEncodedNameAsBytes());
2189           throw ex; // let upper layers deal with it.
2190         }
2191       } finally {
2192         this.updatesLock.writeLock().unlock();
2193       }
2194       String s = "Finished memstore snapshotting " + this +
2195         ", syncing WAL and waiting on mvcc, flushsize=" + totalFlushableSizeOfFlushableStores;
2196       status.setStatus(s);
2197       if (LOG.isTraceEnabled()) LOG.trace(s);
2198       // sync unflushed WAL changes
2199       // see HBASE-8208 for details
2200       if (wal != null) {
2201         try {
2202           wal.sync(); // ensure that flush marker is sync'ed
2203         } catch (IOException ioe) {
2204           LOG.warn("Unexpected exception while wal.sync(), ignoring. Exception: "
2205               + StringUtils.stringifyException(ioe));
2206         }
2207       }
2208 
2209       // wait for all in-progress transactions to commit to WAL before
2210       // we can start the flush. This prevents
2211       // uncommitted transactions from being written into HFiles.
2212       // We have to block before we start the flush, otherwise keys that
2213       // were removed via a rollbackMemstore could be written to Hfiles.
2214       w.setWriteNumber(flushOpSeqId);
2215       mvcc.waitForPreviousTransactionsComplete(w);
2216       // set w to null to prevent mvcc.advanceMemstore from being called again inside finally block
2217       w = null;
2218     } finally {
2219       if (w != null) {
2220         // in case of failure just mark current w as complete
2221         mvcc.advanceMemstore(w);
2222       }
2223     }
2224     return new PrepareFlushResult(storeFlushCtxs, committedFiles, startTime, flushOpSeqId,
2225       flushedSeqId, totalFlushableSizeOfFlushableStores);
2226   }
2227 
2228   /**
2229    * Writes a marker to WAL indicating a flush is requested but cannot be complete due to various
2230    * reasons. Ignores exceptions from WAL. Returns whether the write succeeded.
2231    * @param wal
2232    * @return whether WAL write was successful
2233    */
2234   private boolean writeFlushRequestMarkerToWAL(WAL wal, boolean writeFlushWalMarker) {
2235     if (writeFlushWalMarker && wal != null && !writestate.readOnly) {
2236       FlushDescriptor desc = ProtobufUtil.toFlushDescriptor(FlushAction.CANNOT_FLUSH,
2237         getRegionInfo(), -1, new TreeMap<byte[], List<Path>>());
2238       try {
2239         WALUtil.writeFlushMarker(wal, this.htableDescriptor, getRegionInfo(),
2240           desc, sequenceId, true);
2241         return true;
2242       } catch (IOException e) {
2243         LOG.warn(getRegionInfo().getEncodedName() + " : "
2244             + "Received exception while trying to write the flush request to wal", e);
2245       }
2246     }
2247     return false;
2248   }
2249 
2250   protected FlushResult internalFlushCacheAndCommit(
2251         final WAL wal, MonitoredTask status, final PrepareFlushResult prepareResult,
2252         final Collection<Store> storesToFlush)
2253     throws IOException {
2254 
2255     // prepare flush context is carried via PrepareFlushResult
2256     TreeMap<byte[], StoreFlushContext> storeFlushCtxs = prepareResult.storeFlushCtxs;
2257     TreeMap<byte[], List<Path>> committedFiles = prepareResult.committedFiles;
2258     long startTime = prepareResult.startTime;
2259     long flushOpSeqId = prepareResult.flushOpSeqId;
2260     long flushedSeqId = prepareResult.flushedSeqId;
2261     long totalFlushableSizeOfFlushableStores = prepareResult.totalFlushableSize;
2262 
2263     String s = "Flushing stores of " + this;
2264     status.setStatus(s);
2265     if (LOG.isTraceEnabled()) LOG.trace(s);
2266 
2267     // Any failure from here on out will be catastrophic requiring server
2268     // restart so wal content can be replayed and put back into the memstore.
2269     // Otherwise, the snapshot content while backed up in the wal, it will not
2270     // be part of the current running servers state.
2271     boolean compactionRequested = false;
2272     try {
2273       // A.  Flush memstore to all the HStores.
2274       // Keep running vector of all store files that includes both old and the
2275       // just-made new flush store file. The new flushed file is still in the
2276       // tmp directory.
2277 
2278       for (StoreFlushContext flush : storeFlushCtxs.values()) {
2279         flush.flushCache(status);
2280       }
2281 
2282       // Switch snapshot (in memstore) -> new hfile (thus causing
2283       // all the store scanners to reset/reseek).
2284       Iterator<Store> it = storesToFlush.iterator();
2285       // stores.values() and storeFlushCtxs have same order
2286       for (StoreFlushContext flush : storeFlushCtxs.values()) {
2287         boolean needsCompaction = flush.commit(status);
2288         if (needsCompaction) {
2289           compactionRequested = true;
2290         }
2291         committedFiles.put(it.next().getFamily().getName(), flush.getCommittedFiles());
2292       }
2293       storeFlushCtxs.clear();
2294 
2295       // Set down the memstore size by amount of flush.
2296       this.addAndGetGlobalMemstoreSize(-totalFlushableSizeOfFlushableStores);
2297 
2298       if (wal != null) {
2299         // write flush marker to WAL. If fail, we should throw DroppedSnapshotException
2300         FlushDescriptor desc = ProtobufUtil.toFlushDescriptor(FlushAction.COMMIT_FLUSH,
2301           getRegionInfo(), flushOpSeqId, committedFiles);
2302         WALUtil.writeFlushMarker(wal, this.htableDescriptor, getRegionInfo(),
2303           desc, sequenceId, true);
2304       }
2305     } catch (Throwable t) {
2306       // An exception here means that the snapshot was not persisted.
2307       // The wal needs to be replayed so its content is restored to memstore.
2308       // Currently, only a server restart will do this.
2309       // We used to only catch IOEs but its possible that we'd get other
2310       // exceptions -- e.g. HBASE-659 was about an NPE -- so now we catch
2311       // all and sundry.
2312       if (wal != null) {
2313         try {
2314           FlushDescriptor desc = ProtobufUtil.toFlushDescriptor(FlushAction.ABORT_FLUSH,
2315             getRegionInfo(), flushOpSeqId, committedFiles);
2316           WALUtil.writeFlushMarker(wal, this.htableDescriptor, getRegionInfo(),
2317             desc, sequenceId, false);
2318         } catch (Throwable ex) {
2319           LOG.warn(getRegionInfo().getEncodedName() + " : "
2320               + "Received unexpected exception trying to write ABORT_FLUSH marker to WAL:"
2321               + StringUtils.stringifyException(ex));
2322           // ignore this since we will be aborting the RS with DSE.
2323         }
2324         wal.abortCacheFlush(this.getRegionInfo().getEncodedNameAsBytes());
2325       }
2326       DroppedSnapshotException dse = new DroppedSnapshotException("region: " +
2327           Bytes.toStringBinary(getRegionInfo().getRegionName()));
2328       dse.initCause(t);
2329       status.abort("Flush failed: " + StringUtils.stringifyException(t));
2330       throw dse;
2331     }
2332 
2333     // If we get to here, the HStores have been written.
2334     if (wal != null) {
2335       wal.completeCacheFlush(this.getRegionInfo().getEncodedNameAsBytes());
2336     }
2337 
2338     // Record latest flush time
2339     for (Store store: storesToFlush) {
2340       this.lastStoreFlushTimeMap.put(store, startTime);
2341     }
2342 
2343     // Update the oldest unflushed sequence id for region.
2344     this.maxFlushedSeqId = flushedSeqId;
2345 
2346     // Record flush operation sequence id.
2347     this.lastFlushOpSeqId = flushOpSeqId;
2348 
2349     // C. Finally notify anyone waiting on memstore to clear:
2350     // e.g. checkResources().
2351     synchronized (this) {
2352       notifyAll(); // FindBugs NN_NAKED_NOTIFY
2353     }
2354 
2355     long time = EnvironmentEdgeManager.currentTime() - startTime;
2356     long memstoresize = this.memstoreSize.get();
2357     String msg = "Finished memstore flush of ~"
2358         + StringUtils.byteDesc(totalFlushableSizeOfFlushableStores) + "/"
2359         + totalFlushableSizeOfFlushableStores + ", currentsize="
2360         + StringUtils.byteDesc(memstoresize) + "/" + memstoresize
2361         + " for region " + this + " in " + time + "ms, sequenceid="
2362         + flushOpSeqId +  ", compaction requested=" + compactionRequested
2363         + ((wal == null) ? "; wal=null" : "");
2364     LOG.info(msg);
2365     status.setStatus(msg);
2366 
2367     return new FlushResultImpl(compactionRequested ? 
2368         FlushResult.Result.FLUSHED_COMPACTION_NEEDED :
2369           FlushResult.Result.FLUSHED_NO_COMPACTION_NEEDED,
2370         flushOpSeqId);
2371   }
2372 
2373   /**
2374    * Method to safely get the next sequence number.
2375    * @return Next sequence number unassociated with any actual edit.
2376    * @throws IOException
2377    */
2378   @VisibleForTesting
2379   protected long getNextSequenceId(final WAL wal) throws IOException {
2380     WALKey key = this.appendEmptyEdit(wal, null);
2381     return key.getSequenceId();
2382   }
2383 
2384   //////////////////////////////////////////////////////////////////////////////
2385   // get() methods for client use.
2386   //////////////////////////////////////////////////////////////////////////////
2387 
2388   @Override
2389   public Result getClosestRowBefore(final byte [] row, final byte [] family) throws IOException {
2390     if (coprocessorHost != null) {
2391       Result result = new Result();
2392       if (coprocessorHost.preGetClosestRowBefore(row, family, result)) {
2393         return result;
2394       }
2395     }
2396     // look across all the HStores for this region and determine what the
2397     // closest key is across all column families, since the data may be sparse
2398     checkRow(row, "getClosestRowBefore");
2399     startRegionOperation(Operation.GET);
2400     this.readRequestsCount.increment();
2401     try {
2402       Store store = getStore(family);
2403       // get the closest key. (HStore.getRowKeyAtOrBefore can return null)
2404       Cell key = store.getRowKeyAtOrBefore(row);
2405       Result result = null;
2406       if (key != null) {
2407         Get get = new Get(CellUtil.cloneRow(key));
2408         get.addFamily(family);
2409         result = get(get);
2410       }
2411       if (coprocessorHost != null) {
2412         coprocessorHost.postGetClosestRowBefore(row, family, result);
2413       }
2414       return result;
2415     } finally {
2416       closeRegionOperation(Operation.GET);
2417     }
2418   }
2419 
2420   @Override
2421   public RegionScanner getScanner(Scan scan) throws IOException {
2422    return getScanner(scan, null);
2423   }
2424 
2425   protected RegionScanner getScanner(Scan scan,
2426       List<KeyValueScanner> additionalScanners) throws IOException {
2427     startRegionOperation(Operation.SCAN);
2428     try {
2429       // Verify families are all valid
2430       if (!scan.hasFamilies()) {
2431         // Adding all families to scanner
2432         for (byte[] family: this.htableDescriptor.getFamiliesKeys()) {
2433           scan.addFamily(family);
2434         }
2435       } else {
2436         for (byte [] family : scan.getFamilyMap().keySet()) {
2437           checkFamily(family);
2438         }
2439       }
2440       return instantiateRegionScanner(scan, additionalScanners);
2441     } finally {
2442       closeRegionOperation(Operation.SCAN);
2443     }
2444   }
2445 
2446   protected RegionScanner instantiateRegionScanner(Scan scan,
2447       List<KeyValueScanner> additionalScanners) throws IOException {
2448     if (scan.isReversed()) {
2449       if (scan.getFilter() != null) {
2450         scan.getFilter().setReversed(true);
2451       }
2452       return new ReversedRegionScannerImpl(scan, additionalScanners, this);
2453     }
2454     return new RegionScannerImpl(scan, additionalScanners, this);
2455   }
2456 
2457   @Override
2458   public void prepareDelete(Delete delete) throws IOException {
2459     // Check to see if this is a deleteRow insert
2460     if(delete.getFamilyCellMap().isEmpty()){
2461       for(byte [] family : this.htableDescriptor.getFamiliesKeys()){
2462         // Don't eat the timestamp
2463         delete.addFamily(family, delete.getTimeStamp());
2464       }
2465     } else {
2466       for(byte [] family : delete.getFamilyCellMap().keySet()) {
2467         if(family == null) {
2468           throw new NoSuchColumnFamilyException("Empty family is invalid");
2469         }
2470         checkFamily(family);
2471       }
2472     }
2473   }
2474 
2475   @Override
2476   public void delete(Delete delete) throws IOException {
2477     checkReadOnly();
2478     checkResources();
2479     startRegionOperation(Operation.DELETE);
2480     try {
2481       delete.getRow();
2482       // All edits for the given row (across all column families) must happen atomically.
2483       doBatchMutate(delete);
2484     } finally {
2485       closeRegionOperation(Operation.DELETE);
2486     }
2487   }
2488 
2489   /**
2490    * Row needed by below method.
2491    */
2492   private static final byte [] FOR_UNIT_TESTS_ONLY = Bytes.toBytes("ForUnitTestsOnly");
2493 
2494   /**
2495    * This is used only by unit tests. Not required to be a public API.
2496    * @param familyMap map of family to edits for the given family.
2497    * @throws IOException
2498    */
2499   void delete(NavigableMap<byte[], List<Cell>> familyMap,
2500       Durability durability) throws IOException {
2501     Delete delete = new Delete(FOR_UNIT_TESTS_ONLY);
2502     delete.setFamilyCellMap(familyMap);
2503     delete.setDurability(durability);
2504     doBatchMutate(delete);
2505   }
2506 
2507   @Override
2508   public void prepareDeleteTimestamps(Mutation mutation, Map<byte[], List<Cell>> familyMap,
2509       byte[] byteNow) throws IOException {
2510     for (Map.Entry<byte[], List<Cell>> e : familyMap.entrySet()) {
2511 
2512       byte[] family = e.getKey();
2513       List<Cell> cells = e.getValue();
2514       assert cells instanceof RandomAccess;
2515 
2516       Map<byte[], Integer> kvCount = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR);
2517       int listSize = cells.size();
2518       for (int i=0; i < listSize; i++) {
2519         Cell cell = cells.get(i);
2520         //  Check if time is LATEST, change to time of most recent addition if so
2521         //  This is expensive.
2522         if (cell.getTimestamp() == HConstants.LATEST_TIMESTAMP && CellUtil.isDeleteType(cell)) {
2523           byte[] qual = CellUtil.cloneQualifier(cell);
2524           if (qual == null) qual = HConstants.EMPTY_BYTE_ARRAY;
2525 
2526           Integer count = kvCount.get(qual);
2527           if (count == null) {
2528             kvCount.put(qual, 1);
2529           } else {
2530             kvCount.put(qual, count + 1);
2531           }
2532           count = kvCount.get(qual);
2533 
2534           Get get = new Get(CellUtil.cloneRow(cell));
2535           get.setMaxVersions(count);
2536           get.addColumn(family, qual);
2537           if (coprocessorHost != null) {
2538             if (!coprocessorHost.prePrepareTimeStampForDeleteVersion(mutation, cell,
2539                 byteNow, get)) {
2540               updateDeleteLatestVersionTimeStamp(cell, get, count, byteNow);
2541             }
2542           } else {
2543             updateDeleteLatestVersionTimeStamp(cell, get, count, byteNow);
2544           }
2545         } else {
2546           CellUtil.updateLatestStamp(cell, byteNow, 0);
2547         }
2548       }
2549     }
2550   }
2551 
2552   void updateDeleteLatestVersionTimeStamp(Cell cell, Get get, int count, byte[] byteNow)
2553       throws IOException {
2554     List<Cell> result = get(get, false);
2555 
2556     if (result.size() < count) {
2557       // Nothing to delete
2558       CellUtil.updateLatestStamp(cell, byteNow, 0);
2559       return;
2560     }
2561     if (result.size() > count) {
2562       throw new RuntimeException("Unexpected size: " + result.size());
2563     }
2564     Cell getCell = result.get(count - 1);
2565     CellUtil.setTimestamp(cell, getCell.getTimestamp());
2566   }
2567 
2568   @Override
2569   public void put(Put put) throws IOException {
2570     checkReadOnly();
2571 
2572     // Do a rough check that we have resources to accept a write.  The check is
2573     // 'rough' in that between the resource check and the call to obtain a
2574     // read lock, resources may run out.  For now, the thought is that this
2575     // will be extremely rare; we'll deal with it when it happens.
2576     checkResources();
2577     startRegionOperation(Operation.PUT);
2578     try {
2579       // All edits for the given row (across all column families) must happen atomically.
2580       doBatchMutate(put);
2581     } finally {
2582       closeRegionOperation(Operation.PUT);
2583     }
2584   }
2585 
2586   /**
2587    * Struct-like class that tracks the progress of a batch operation,
2588    * accumulating status codes and tracking the index at which processing
2589    * is proceeding.
2590    */
2591   private abstract static class BatchOperationInProgress<T> {
2592     T[] operations;
2593     int nextIndexToProcess = 0;
2594     OperationStatus[] retCodeDetails;
2595     WALEdit[] walEditsFromCoprocessors;
2596 
2597     public BatchOperationInProgress(T[] operations) {
2598       this.operations = operations;
2599       this.retCodeDetails = new OperationStatus[operations.length];
2600       this.walEditsFromCoprocessors = new WALEdit[operations.length];
2601       Arrays.fill(this.retCodeDetails, OperationStatus.NOT_RUN);
2602     }
2603 
2604     public abstract Mutation getMutation(int index);
2605     public abstract long getNonceGroup(int index);
2606     public abstract long getNonce(int index);
2607     /** This method is potentially expensive and should only be used for non-replay CP path. */
2608     public abstract Mutation[] getMutationsForCoprocs();
2609     public abstract boolean isInReplay();
2610     public abstract long getReplaySequenceId();
2611 
2612     public boolean isDone() {
2613       return nextIndexToProcess == operations.length;
2614     }
2615   }
2616 
2617   private static class MutationBatch extends BatchOperationInProgress<Mutation> {
2618     private long nonceGroup;
2619     private long nonce;
2620     public MutationBatch(Mutation[] operations, long nonceGroup, long nonce) {
2621       super(operations);
2622       this.nonceGroup = nonceGroup;
2623       this.nonce = nonce;
2624     }
2625 
2626     @Override
2627     public Mutation getMutation(int index) {
2628       return this.operations[index];
2629     }
2630 
2631     @Override
2632     public long getNonceGroup(int index) {
2633       return nonceGroup;
2634     }
2635 
2636     @Override
2637     public long getNonce(int index) {
2638       return nonce;
2639     }
2640 
2641     @Override
2642     public Mutation[] getMutationsForCoprocs() {
2643       return this.operations;
2644     }
2645 
2646     @Override
2647     public boolean isInReplay() {
2648       return false;
2649     }
2650 
2651     @Override
2652     public long getReplaySequenceId() {
2653       return 0;
2654     }
2655   }
2656 
2657   private static class ReplayBatch extends BatchOperationInProgress<MutationReplay> {
2658     private long replaySeqId = 0;
2659     public ReplayBatch(MutationReplay[] operations, long seqId) {
2660       super(operations);
2661       this.replaySeqId = seqId;
2662     }
2663 
2664     @Override
2665     public Mutation getMutation(int index) {
2666       return this.operations[index].mutation;
2667     }
2668 
2669     @Override
2670     public long getNonceGroup(int index) {
2671       return this.operations[index].nonceGroup;
2672     }
2673 
2674     @Override
2675     public long getNonce(int index) {
2676       return this.operations[index].nonce;
2677     }
2678 
2679     @Override
2680     public Mutation[] getMutationsForCoprocs() {
2681       assert false;
2682       throw new RuntimeException("Should not be called for replay batch");
2683     }
2684 
2685     @Override
2686     public boolean isInReplay() {
2687       return true;
2688     }
2689 
2690     @Override
2691     public long getReplaySequenceId() {
2692       return this.replaySeqId;
2693     }
2694   }
2695 
2696   @Override
2697   public OperationStatus[] batchMutate(Mutation[] mutations, long nonceGroup, long nonce)
2698       throws IOException {
2699     // As it stands, this is used for 3 things
2700     //  * batchMutate with single mutation - put/delete, separate or from checkAndMutate.
2701     //  * coprocessor calls (see ex. BulkDeleteEndpoint).
2702     // So nonces are not really ever used by HBase. They could be by coprocs, and checkAnd...
2703     return batchMutate(new MutationBatch(mutations, nonceGroup, nonce));
2704   }
2705 
2706   public OperationStatus[] batchMutate(Mutation[] mutations) throws IOException {
2707     return batchMutate(mutations, HConstants.NO_NONCE, HConstants.NO_NONCE);
2708   }
2709 
2710   @Override
2711   public OperationStatus[] batchReplay(MutationReplay[] mutations, long replaySeqId)
2712       throws IOException {
2713     if (!RegionReplicaUtil.isDefaultReplica(getRegionInfo())
2714         && replaySeqId < lastReplayedOpenRegionSeqId) {
2715       // if it is a secondary replica we should ignore these entries silently
2716       // since they are coming out of order
2717       if (LOG.isTraceEnabled()) {
2718         LOG.trace(getRegionInfo().getEncodedName() + " : "
2719           + "Skipping " + mutations.length + " mutations with replaySeqId=" + replaySeqId
2720           + " which is < than lastReplayedOpenRegionSeqId=" + lastReplayedOpenRegionSeqId);
2721         for (MutationReplay mut : mutations) {
2722           LOG.trace(getRegionInfo().getEncodedName() + " : Skipping : " + mut.mutation);
2723         }
2724       }
2725 
2726       OperationStatus[] statuses = new OperationStatus[mutations.length];
2727       for (int i = 0; i < statuses.length; i++) {
2728         statuses[i] = OperationStatus.SUCCESS;
2729       }
2730       return statuses;
2731     }
2732     return batchMutate(new ReplayBatch(mutations, replaySeqId));
2733   }
2734 
2735   /**
2736    * Perform a batch of mutations.
2737    * It supports only Put and Delete mutations and will ignore other types passed.
2738    * @param batchOp contains the list of mutations
2739    * @return an array of OperationStatus which internally contains the
2740    *         OperationStatusCode and the exceptionMessage if any.
2741    * @throws IOException
2742    */
2743   OperationStatus[] batchMutate(BatchOperationInProgress<?> batchOp) throws IOException {
2744     boolean initialized = false;
2745     Operation op = batchOp.isInReplay() ? Operation.REPLAY_BATCH_MUTATE : Operation.BATCH_MUTATE;
2746     startRegionOperation(op);
2747     try {
2748       while (!batchOp.isDone()) {
2749         if (!batchOp.isInReplay()) {
2750           checkReadOnly();
2751         }
2752         checkResources();
2753 
2754         if (!initialized) {
2755           this.writeRequestsCount.add(batchOp.operations.length);
2756           if (!batchOp.isInReplay()) {
2757             doPreMutationHook(batchOp);
2758           }
2759           initialized = true;
2760         }
2761         long addedSize = doMiniBatchMutation(batchOp);
2762         long newSize = this.addAndGetGlobalMemstoreSize(addedSize);
2763         if (isFlushSize(newSize)) {
2764           requestFlush();
2765         }
2766       }
2767     } finally {
2768       closeRegionOperation(op);
2769     }
2770     return batchOp.retCodeDetails;
2771   }
2772 
2773 
2774   private void doPreMutationHook(BatchOperationInProgress<?> batchOp)
2775       throws IOException {
2776     /* Run coprocessor pre hook outside of locks to avoid deadlock */
2777     WALEdit walEdit = new WALEdit();
2778     if (coprocessorHost != null) {
2779       for (int i = 0 ; i < batchOp.operations.length; i++) {
2780         Mutation m = batchOp.getMutation(i);
2781         if (m instanceof Put) {
2782           if (coprocessorHost.prePut((Put) m, walEdit, m.getDurability())) {
2783             // pre hook says skip this Put
2784             // mark as success and skip in doMiniBatchMutation
2785             batchOp.retCodeDetails[i] = OperationStatus.SUCCESS;
2786           }
2787         } else if (m instanceof Delete) {
2788           Delete curDel = (Delete) m;
2789           if (curDel.getFamilyCellMap().isEmpty()) {
2790             // handle deleting a row case
2791             prepareDelete(curDel);
2792           }
2793           if (coprocessorHost.preDelete(curDel, walEdit, m.getDurability())) {
2794             // pre hook says skip this Delete
2795             // mark as success and skip in doMiniBatchMutation
2796             batchOp.retCodeDetails[i] = OperationStatus.SUCCESS;
2797           }
2798         } else {
2799           // In case of passing Append mutations along with the Puts and Deletes in batchMutate
2800           // mark the operation return code as failure so that it will not be considered in
2801           // the doMiniBatchMutation
2802           batchOp.retCodeDetails[i] = new OperationStatus(OperationStatusCode.FAILURE,
2803               "Put/Delete mutations only supported in batchMutate() now");
2804         }
2805         if (!walEdit.isEmpty()) {
2806           batchOp.walEditsFromCoprocessors[i] = walEdit;
2807           walEdit = new WALEdit();
2808         }
2809       }
2810     }
2811   }
2812 
2813   @SuppressWarnings("unchecked")
2814   private long doMiniBatchMutation(BatchOperationInProgress<?> batchOp) throws IOException {
2815     boolean isInReplay = batchOp.isInReplay();
2816     // variable to note if all Put items are for the same CF -- metrics related
2817     boolean putsCfSetConsistent = true;
2818     //The set of columnFamilies first seen for Put.
2819     Set<byte[]> putsCfSet = null;
2820     // variable to note if all Delete items are for the same CF -- metrics related
2821     boolean deletesCfSetConsistent = true;
2822     //The set of columnFamilies first seen for Delete.
2823     Set<byte[]> deletesCfSet = null;
2824 
2825     long currentNonceGroup = HConstants.NO_NONCE, currentNonce = HConstants.NO_NONCE;
2826     WALEdit walEdit = new WALEdit(isInReplay);
2827     MultiVersionConsistencyControl.WriteEntry w = null;
2828     long txid = 0;
2829     boolean doRollBackMemstore = false;
2830     boolean locked = false;
2831 
2832     /** Keep track of the locks we hold so we can release them in finally clause */
2833     List<RowLock> acquiredRowLocks = Lists.newArrayListWithCapacity(batchOp.operations.length);
2834     // reference family maps directly so coprocessors can mutate them if desired
2835     Map<byte[], List<Cell>>[] familyMaps = new Map[batchOp.operations.length];
2836     List<Cell> memstoreCells = new ArrayList<Cell>();
2837     // We try to set up a batch in the range [firstIndex,lastIndexExclusive)
2838     int firstIndex = batchOp.nextIndexToProcess;
2839     int lastIndexExclusive = firstIndex;
2840     boolean success = false;
2841     int noOfPuts = 0, noOfDeletes = 0;
2842     WALKey walKey = null;
2843     long mvccNum = 0;
2844     try {
2845       // ------------------------------------
2846       // STEP 1. Try to acquire as many locks as we can, and ensure
2847       // we acquire at least one.
2848       // ----------------------------------
2849       int numReadyToWrite = 0;
2850       long now = EnvironmentEdgeManager.currentTime();
2851       while (lastIndexExclusive < batchOp.operations.length) {
2852         Mutation mutation = batchOp.getMutation(lastIndexExclusive);
2853         boolean isPutMutation = mutation instanceof Put;
2854 
2855         Map<byte[], List<Cell>> familyMap = mutation.getFamilyCellMap();
2856         // store the family map reference to allow for mutations
2857         familyMaps[lastIndexExclusive] = familyMap;
2858 
2859         // skip anything that "ran" already
2860         if (batchOp.retCodeDetails[lastIndexExclusive].getOperationStatusCode()
2861             != OperationStatusCode.NOT_RUN) {
2862           lastIndexExclusive++;
2863           continue;
2864         }
2865 
2866         try {
2867           if (isPutMutation) {
2868             // Check the families in the put. If bad, skip this one.
2869             if (isInReplay) {
2870               removeNonExistentColumnFamilyForReplay(familyMap);
2871             } else {
2872               checkFamilies(familyMap.keySet());
2873             }
2874             checkTimestamps(mutation.getFamilyCellMap(), now);
2875           } else {
2876             prepareDelete((Delete) mutation);
2877           }
2878           checkRow(mutation.getRow(), "doMiniBatchMutation");
2879         } catch (NoSuchColumnFamilyException nscf) {
2880           LOG.warn("No such column family in batch mutation", nscf);
2881           batchOp.retCodeDetails[lastIndexExclusive] = new OperationStatus(
2882               OperationStatusCode.BAD_FAMILY, nscf.getMessage());
2883           lastIndexExclusive++;
2884           continue;
2885         } catch (FailedSanityCheckException fsce) {
2886           LOG.warn("Batch Mutation did not pass sanity check", fsce);
2887           batchOp.retCodeDetails[lastIndexExclusive] = new OperationStatus(
2888               OperationStatusCode.SANITY_CHECK_FAILURE, fsce.getMessage());
2889           lastIndexExclusive++;
2890           continue;
2891         } catch (WrongRegionException we) {
2892           LOG.warn("Batch mutation had a row that does not belong to this region", we);
2893           batchOp.retCodeDetails[lastIndexExclusive] = new OperationStatus(
2894               OperationStatusCode.SANITY_CHECK_FAILURE, we.getMessage());
2895           lastIndexExclusive++;
2896           continue;
2897         }
2898 
2899         // If we haven't got any rows in our batch, we should block to
2900         // get the next one.
2901         boolean shouldBlock = numReadyToWrite == 0;
2902         RowLock rowLock = null;
2903         try {
2904           rowLock = getRowLockInternal(mutation.getRow(), shouldBlock);
2905         } catch (IOException ioe) {
2906           LOG.warn("Failed getting lock in batch put, row="
2907             + Bytes.toStringBinary(mutation.getRow()), ioe);
2908         }
2909         if (rowLock == null) {
2910           // We failed to grab another lock
2911           assert !shouldBlock : "Should never fail to get lock when blocking";
2912           break; // stop acquiring more rows for this batch
2913         } else {
2914           acquiredRowLocks.add(rowLock);
2915         }
2916 
2917         lastIndexExclusive++;
2918         numReadyToWrite++;
2919 
2920         if (isPutMutation) {
2921           // If Column Families stay consistent through out all of the
2922           // individual puts then metrics can be reported as a mutliput across
2923           // column families in the first put.
2924           if (putsCfSet == null) {
2925             putsCfSet = mutation.getFamilyCellMap().keySet();
2926           } else {
2927             putsCfSetConsistent = putsCfSetConsistent
2928                 && mutation.getFamilyCellMap().keySet().equals(putsCfSet);
2929           }
2930         } else {
2931           if (deletesCfSet == null) {
2932             deletesCfSet = mutation.getFamilyCellMap().keySet();
2933           } else {
2934             deletesCfSetConsistent = deletesCfSetConsistent
2935                 && mutation.getFamilyCellMap().keySet().equals(deletesCfSet);
2936           }
2937         }
2938       }
2939 
2940       // we should record the timestamp only after we have acquired the rowLock,
2941       // otherwise, newer puts/deletes are not guaranteed to have a newer timestamp
2942       now = EnvironmentEdgeManager.currentTime();
2943       byte[] byteNow = Bytes.toBytes(now);
2944 
2945       // Nothing to put/delete -- an exception in the above such as NoSuchColumnFamily?
2946       if (numReadyToWrite <= 0) return 0L;
2947 
2948       // We've now grabbed as many mutations off the list as we can
2949 
2950       // ------------------------------------
2951       // STEP 2. Update any LATEST_TIMESTAMP timestamps
2952       // ----------------------------------
2953       for (int i = firstIndex; !isInReplay && i < lastIndexExclusive; i++) {
2954         // skip invalid
2955         if (batchOp.retCodeDetails[i].getOperationStatusCode()
2956             != OperationStatusCode.NOT_RUN) continue;
2957 
2958         Mutation mutation = batchOp.getMutation(i);
2959         if (mutation instanceof Put) {
2960           updateCellTimestamps(familyMaps[i].values(), byteNow);
2961           noOfPuts++;
2962         } else {
2963           prepareDeleteTimestamps(mutation, familyMaps[i], byteNow);
2964           noOfDeletes++;
2965         }
2966         rewriteCellTags(familyMaps[i], mutation);
2967       }
2968 
2969       lock(this.updatesLock.readLock(), numReadyToWrite);
2970       locked = true;
2971       if(isInReplay) {
2972         mvccNum = batchOp.getReplaySequenceId();
2973       } else {
2974         mvccNum = MultiVersionConsistencyControl.getPreAssignedWriteNumber(this.sequenceId);
2975       }
2976       //
2977       // ------------------------------------
2978       // Acquire the latest mvcc number
2979       // ----------------------------------
2980       w = mvcc.beginMemstoreInsertWithSeqNum(mvccNum);
2981 
2982       // calling the pre CP hook for batch mutation
2983       if (!isInReplay && coprocessorHost != null) {
2984         MiniBatchOperationInProgress<Mutation> miniBatchOp =
2985           new MiniBatchOperationInProgress<Mutation>(batchOp.getMutationsForCoprocs(),
2986           batchOp.retCodeDetails, batchOp.walEditsFromCoprocessors, firstIndex, lastIndexExclusive);
2987         if (coprocessorHost.preBatchMutate(miniBatchOp)) return 0L;
2988       }
2989 
2990       // ------------------------------------
2991       // STEP 3. Write back to memstore
2992       // Write to memstore. It is ok to write to memstore
2993       // first without updating the WAL because we do not roll
2994       // forward the memstore MVCC. The MVCC will be moved up when
2995       // the complete operation is done. These changes are not yet
2996       // visible to scanners till we update the MVCC. The MVCC is
2997       // moved only when the sync is complete.
2998       // ----------------------------------
2999       long addedSize = 0;
3000       for (int i = firstIndex; i < lastIndexExclusive; i++) {
3001         if (batchOp.retCodeDetails[i].getOperationStatusCode()
3002             != OperationStatusCode.NOT_RUN) {
3003           continue;
3004         }
3005         doRollBackMemstore = true; // If we have a failure, we need to clean what we wrote
3006         addedSize += applyFamilyMapToMemstore(familyMaps[i], mvccNum, memstoreCells, isInReplay);
3007       }
3008 
3009       // ------------------------------------
3010       // STEP 4. Build WAL edit
3011       // ----------------------------------
3012       Durability durability = Durability.USE_DEFAULT;
3013       for (int i = firstIndex; i < lastIndexExclusive; i++) {
3014         // Skip puts that were determined to be invalid during preprocessing
3015         if (batchOp.retCodeDetails[i].getOperationStatusCode()
3016             != OperationStatusCode.NOT_RUN) {
3017           continue;
3018         }
3019         batchOp.retCodeDetails[i] = OperationStatus.SUCCESS;
3020 
3021         Mutation m = batchOp.getMutation(i);
3022         Durability tmpDur = getEffectiveDurability(m.getDurability());
3023         if (tmpDur.ordinal() > durability.ordinal()) {
3024           durability = tmpDur;
3025         }
3026         if (tmpDur == Durability.SKIP_WAL) {
3027           recordMutationWithoutWal(m.getFamilyCellMap());
3028           continue;
3029         }
3030 
3031         long nonceGroup = batchOp.getNonceGroup(i), nonce = batchOp.getNonce(i);
3032         // In replay, the batch may contain multiple nonces. If so, write WALEdit for each.
3033         // Given how nonces are originally written, these should be contiguous.
3034         // They don't have to be, it will still work, just write more WALEdits than needed.
3035         if (nonceGroup != currentNonceGroup || nonce != currentNonce) {
3036           if (walEdit.size() > 0) {
3037             assert isInReplay;
3038             if (!isInReplay) {
3039               throw new IOException("Multiple nonces per batch and not in replay");
3040             }
3041             // txid should always increase, so having the one from the last call is ok.
3042             // we use HLogKey here instead of WALKey directly to support legacy coprocessors.
3043             walKey = new ReplayHLogKey(this.getRegionInfo().getEncodedNameAsBytes(),
3044               this.htableDescriptor.getTableName(), now, m.getClusterIds(),
3045               currentNonceGroup, currentNonce);
3046             txid = this.wal.append(this.htableDescriptor,  this.getRegionInfo(),  walKey,
3047               walEdit, getSequenceId(), true, null);
3048             walEdit = new WALEdit(isInReplay);
3049             walKey = null;
3050           }
3051           currentNonceGroup = nonceGroup;
3052           currentNonce = nonce;
3053         }
3054 
3055         // Add WAL edits by CP
3056         WALEdit fromCP = batchOp.walEditsFromCoprocessors[i];
3057         if (fromCP != null) {
3058           for (Cell cell : fromCP.getCells()) {
3059             walEdit.add(cell);
3060           }
3061         }
3062         addFamilyMapToWALEdit(familyMaps[i], walEdit);
3063       }
3064 
3065       // -------------------------
3066       // STEP 5. Append the final edit to WAL. Do not sync wal.
3067       // -------------------------
3068       Mutation mutation = batchOp.getMutation(firstIndex);
3069       if (isInReplay) {
3070         // use wal key from the original
3071         walKey = new ReplayHLogKey(this.getRegionInfo().getEncodedNameAsBytes(),
3072           this.htableDescriptor.getTableName(), WALKey.NO_SEQUENCE_ID, now,
3073           mutation.getClusterIds(), currentNonceGroup, currentNonce);
3074         long replaySeqId = batchOp.getReplaySequenceId();
3075         walKey.setOrigLogSeqNum(replaySeqId);
3076 
3077         // ensure that the sequence id of the region is at least as big as orig log seq id
3078         while (true) {
3079           long seqId = getSequenceId().get();
3080           if (seqId >= replaySeqId) break;
3081           if (getSequenceId().compareAndSet(seqId, replaySeqId)) break;
3082         }
3083       }
3084       if (walEdit.size() > 0) {
3085         if (!isInReplay) {
3086         // we use HLogKey here instead of WALKey directly to support legacy coprocessors.
3087         walKey = new HLogKey(this.getRegionInfo().getEncodedNameAsBytes(),
3088             this.htableDescriptor.getTableName(), WALKey.NO_SEQUENCE_ID, now,
3089             mutation.getClusterIds(), currentNonceGroup, currentNonce);
3090         }
3091 
3092         txid = this.wal.append(this.htableDescriptor, this.getRegionInfo(), walKey, walEdit,
3093           getSequenceId(), true, memstoreCells);
3094       }
3095       if(walKey == null){
3096         // Append a faked WALEdit in order for SKIP_WAL updates to get mvcc assigned
3097         walKey = this.appendEmptyEdit(this.wal, memstoreCells);
3098       }
3099 
3100       // -------------------------------
3101       // STEP 6. Release row locks, etc.
3102       // -------------------------------
3103       if (locked) {
3104         this.updatesLock.readLock().unlock();
3105         locked = false;
3106       }
3107       releaseRowLocks(acquiredRowLocks);
3108 
3109       // -------------------------
3110       // STEP 7. Sync wal.
3111       // -------------------------
3112       if (txid != 0) {
3113         syncOrDefer(txid, durability);
3114       }
3115 
3116       doRollBackMemstore = false;
3117       // calling the post CP hook for batch mutation
3118       if (!isInReplay && coprocessorHost != null) {
3119         MiniBatchOperationInProgress<Mutation> miniBatchOp =
3120           new MiniBatchOperationInProgress<Mutation>(batchOp.getMutationsForCoprocs(),
3121           batchOp.retCodeDetails, batchOp.walEditsFromCoprocessors, firstIndex, lastIndexExclusive);
3122         coprocessorHost.postBatchMutate(miniBatchOp);
3123       }
3124 
3125 
3126       // ------------------------------------------------------------------
3127       // STEP 8. Advance mvcc. This will make this put visible to scanners and getters.
3128       // ------------------------------------------------------------------
3129       if (w != null) {
3130         mvcc.completeMemstoreInsertWithSeqNum(w, walKey);
3131         w = null;
3132       }
3133 
3134       // ------------------------------------
3135       // STEP 9. Run coprocessor post hooks. This should be done after the wal is
3136       // synced so that the coprocessor contract is adhered to.
3137       // ------------------------------------
3138       if (!isInReplay && coprocessorHost != null) {
3139         for (int i = firstIndex; i < lastIndexExclusive; i++) {
3140           // only for successful puts
3141           if (batchOp.retCodeDetails[i].getOperationStatusCode()
3142               != OperationStatusCode.SUCCESS) {
3143             continue;
3144           }
3145           Mutation m = batchOp.getMutation(i);
3146           if (m instanceof Put) {
3147             coprocessorHost.postPut((Put) m, walEdit, m.getDurability());
3148           } else {
3149             coprocessorHost.postDelete((Delete) m, walEdit, m.getDurability());
3150           }
3151         }
3152       }
3153 
3154       success = true;
3155       return addedSize;
3156     } finally {
3157       // if the wal sync was unsuccessful, remove keys from memstore
3158       if (doRollBackMemstore) {
3159         rollbackMemstore(memstoreCells);
3160       }
3161       if (w != null) {
3162         mvcc.completeMemstoreInsertWithSeqNum(w, walKey);
3163       }
3164 
3165       if (locked) {
3166         this.updatesLock.readLock().unlock();
3167       }
3168       releaseRowLocks(acquiredRowLocks);
3169 
3170       // See if the column families were consistent through the whole thing.
3171       // if they were then keep them. If they were not then pass a null.
3172       // null will be treated as unknown.
3173       // Total time taken might be involving Puts and Deletes.
3174       // Split the time for puts and deletes based on the total number of Puts and Deletes.
3175 
3176       if (noOfPuts > 0) {
3177         // There were some Puts in the batch.
3178         if (this.metricsRegion != null) {
3179           this.metricsRegion.updatePut();
3180         }
3181       }
3182       if (noOfDeletes > 0) {
3183         // There were some Deletes in the batch.
3184         if (this.metricsRegion != null) {
3185           this.metricsRegion.updateDelete();
3186         }
3187       }
3188       if (!success) {
3189         for (int i = firstIndex; i < lastIndexExclusive; i++) {
3190           if (batchOp.retCodeDetails[i].getOperationStatusCode() == OperationStatusCode.NOT_RUN) {
3191             batchOp.retCodeDetails[i] = OperationStatus.FAILURE;
3192           }
3193         }
3194       }
3195       if (coprocessorHost != null && !batchOp.isInReplay()) {
3196         // call the coprocessor hook to do any finalization steps
3197         // after the put is done
3198         MiniBatchOperationInProgress<Mutation> miniBatchOp =
3199             new MiniBatchOperationInProgress<Mutation>(batchOp.getMutationsForCoprocs(),
3200                 batchOp.retCodeDetails, batchOp.walEditsFromCoprocessors, firstIndex,
3201                 lastIndexExclusive);
3202         coprocessorHost.postBatchMutateIndispensably(miniBatchOp, success);
3203       }
3204 
3205       batchOp.nextIndexToProcess = lastIndexExclusive;
3206     }
3207   }
3208 
3209   /**
3210    * Returns effective durability from the passed durability and
3211    * the table descriptor.
3212    */
3213   protected Durability getEffectiveDurability(Durability d) {
3214     return d == Durability.USE_DEFAULT ? this.durability : d;
3215   }
3216 
3217   //TODO, Think that gets/puts and deletes should be refactored a bit so that
3218   //the getting of the lock happens before, so that you would just pass it into
3219   //the methods. So in the case of checkAndMutate you could just do lockRow,
3220   //get, put, unlockRow or something
3221 
3222   @Override
3223   public boolean checkAndMutate(byte [] row, byte [] family, byte [] qualifier,
3224       CompareOp compareOp, ByteArrayComparable comparator, Mutation w,
3225       boolean writeToWAL)
3226   throws IOException{
3227     checkReadOnly();
3228     //TODO, add check for value length or maybe even better move this to the
3229     //client if this becomes a global setting
3230     checkResources();
3231     boolean isPut = w instanceof Put;
3232     if (!isPut && !(w instanceof Delete))
3233       throw new org.apache.hadoop.hbase.DoNotRetryIOException("Action must " +
3234           "be Put or Delete");
3235     if (!Bytes.equals(row, w.getRow())) {
3236       throw new org.apache.hadoop.hbase.DoNotRetryIOException("Action's " +
3237           "getRow must match the passed row");
3238     }
3239 
3240     startRegionOperation();
3241     try {
3242       Get get = new Get(row);
3243       checkFamily(family);
3244       get.addColumn(family, qualifier);
3245 
3246       // Lock row - note that doBatchMutate will relock this row if called
3247       RowLock rowLock = getRowLock(get.getRow());
3248       // wait for all previous transactions to complete (with lock held)
3249       mvcc.waitForPreviousTransactionsComplete();
3250       try {
3251         if (this.getCoprocessorHost() != null) {
3252           Boolean processed = null;
3253           if (w instanceof Put) {
3254             processed = this.getCoprocessorHost().preCheckAndPutAfterRowLock(row, family,
3255                 qualifier, compareOp, comparator, (Put) w);
3256           } else if (w instanceof Delete) {
3257             processed = this.getCoprocessorHost().preCheckAndDeleteAfterRowLock(row, family,
3258                 qualifier, compareOp, comparator, (Delete) w);
3259           }
3260           if (processed != null) {
3261             return processed;
3262           }
3263         }
3264         List<Cell> result = get(get, false);
3265 
3266         boolean valueIsNull = comparator.getValue() == null ||
3267           comparator.getValue().length == 0;
3268         boolean matches = false;
3269         if (result.size() == 0 && valueIsNull) {
3270           matches = true;
3271         } else if (result.size() > 0 && result.get(0).getValueLength() == 0 &&
3272             valueIsNull) {
3273           matches = true;
3274         } else if (result.size() == 1 && !valueIsNull) {
3275           Cell kv = result.get(0);
3276           int compareResult = comparator.compareTo(kv.getValueArray(),
3277               kv.getValueOffset(), kv.getValueLength());
3278           switch (compareOp) {
3279           case LESS:
3280             matches = compareResult < 0;
3281             break;
3282           case LESS_OR_EQUAL:
3283             matches = compareResult <= 0;
3284             break;
3285           case EQUAL:
3286             matches = compareResult == 0;
3287             break;
3288           case NOT_EQUAL:
3289             matches = compareResult != 0;
3290             break;
3291           case GREATER_OR_EQUAL:
3292             matches = compareResult >= 0;
3293             break;
3294           case GREATER:
3295             matches = compareResult > 0;
3296             break;
3297           default:
3298             throw new RuntimeException("Unknown Compare op " + compareOp.name());
3299           }
3300         }
3301         //If matches put the new put or delete the new delete
3302         if (matches) {
3303           // All edits for the given row (across all column families) must
3304           // happen atomically.
3305           doBatchMutate(w);
3306           this.checkAndMutateChecksPassed.increment();
3307           return true;
3308         }
3309         this.checkAndMutateChecksFailed.increment();
3310         return false;
3311       } finally {
3312         rowLock.release();
3313       }
3314     } finally {
3315       closeRegionOperation();
3316     }
3317   }
3318 
3319   //TODO, Think that gets/puts and deletes should be refactored a bit so that
3320   //the getting of the lock happens before, so that you would just pass it into
3321   //the methods. So in the case of checkAndMutate you could just do lockRow,
3322   //get, put, unlockRow or something
3323 
3324   @Override
3325   public boolean checkAndRowMutate(byte [] row, byte [] family, byte [] qualifier,
3326       CompareOp compareOp, ByteArrayComparable comparator, RowMutations rm,
3327       boolean writeToWAL) throws IOException {
3328     checkReadOnly();
3329     //TODO, add check for value length or maybe even better move this to the
3330     //client if this becomes a global setting
3331     checkResources();
3332 
3333     startRegionOperation();
3334     try {
3335       Get get = new Get(row);
3336       checkFamily(family);
3337       get.addColumn(family, qualifier);
3338 
3339       // Lock row - note that doBatchMutate will relock this row if called
3340       RowLock rowLock = getRowLock(get.getRow());
3341       // wait for all previous transactions to complete (with lock held)
3342       mvcc.waitForPreviousTransactionsComplete();
3343       try {
3344         List<Cell> result = get(get, false);
3345 
3346         boolean valueIsNull = comparator.getValue() == null ||
3347             comparator.getValue().length == 0;
3348         boolean matches = false;
3349         if (result.size() == 0 && valueIsNull) {
3350           matches = true;
3351         } else if (result.size() > 0 && result.get(0).getValueLength() == 0 &&
3352             valueIsNull) {
3353           matches = true;
3354         } else if (result.size() == 1 && !valueIsNull) {
3355           Cell kv = result.get(0);
3356           int compareResult = comparator.compareTo(kv.getValueArray(),
3357               kv.getValueOffset(), kv.getValueLength());
3358           switch (compareOp) {
3359           case LESS:
3360             matches = compareResult < 0;
3361             break;
3362           case LESS_OR_EQUAL:
3363             matches = compareResult <= 0;
3364             break;
3365           case EQUAL:
3366             matches = compareResult == 0;
3367             break;
3368           case NOT_EQUAL:
3369             matches = compareResult != 0;
3370             break;
3371           case GREATER_OR_EQUAL:
3372             matches = compareResult >= 0;
3373             break;
3374           case GREATER:
3375             matches = compareResult > 0;
3376             break;
3377           default:
3378             throw new RuntimeException("Unknown Compare op " + compareOp.name());
3379           }
3380         }
3381         //If matches put the new put or delete the new delete
3382         if (matches) {
3383           // All edits for the given row (across all column families) must
3384           // happen atomically.
3385           mutateRow(rm);
3386           this.checkAndMutateChecksPassed.increment();
3387           return true;
3388         }
3389         this.checkAndMutateChecksFailed.increment();
3390         return false;
3391       } finally {
3392         rowLock.release();
3393       }
3394     } finally {
3395       closeRegionOperation();
3396     }
3397   }
3398 
3399   private void doBatchMutate(Mutation mutation) throws IOException {
3400     // Currently this is only called for puts and deletes, so no nonces.
3401     OperationStatus[] batchMutate = this.batchMutate(new Mutation[] { mutation });
3402     if (batchMutate[0].getOperationStatusCode().equals(OperationStatusCode.SANITY_CHECK_FAILURE)) {
3403       throw new FailedSanityCheckException(batchMutate[0].getExceptionMsg());
3404     } else if (batchMutate[0].getOperationStatusCode().equals(OperationStatusCode.BAD_FAMILY)) {
3405       throw new NoSuchColumnFamilyException(batchMutate[0].getExceptionMsg());
3406     }
3407   }
3408 
3409   /**
3410    * Complete taking the snapshot on the region. Writes the region info and adds references to the
3411    * working snapshot directory.
3412    *
3413    * TODO for api consistency, consider adding another version with no {@link ForeignExceptionSnare}
3414    * arg.  (In the future other cancellable HRegion methods could eventually add a
3415    * {@link ForeignExceptionSnare}, or we could do something fancier).
3416    *
3417    * @param desc snapshot description object
3418    * @param exnSnare ForeignExceptionSnare that captures external exceptions in case we need to
3419    *   bail out.  This is allowed to be null and will just be ignored in that case.
3420    * @throws IOException if there is an external or internal error causing the snapshot to fail
3421    */
3422   public void addRegionToSnapshot(SnapshotDescription desc,
3423       ForeignExceptionSnare exnSnare) throws IOException {
3424     Path rootDir = FSUtils.getRootDir(conf);
3425     Path snapshotDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(desc, rootDir);
3426 
3427     SnapshotManifest manifest = SnapshotManifest.create(conf, getFilesystem(),
3428                                                         snapshotDir, desc, exnSnare);
3429     manifest.addRegion(this);
3430   }
3431 
3432   @Override
3433   public void updateCellTimestamps(final Iterable<List<Cell>> cellItr, final byte[] now)
3434       throws IOException {
3435     for (List<Cell> cells: cellItr) {
3436       if (cells == null) continue;
3437       assert cells instanceof RandomAccess;
3438       int listSize = cells.size();
3439       for (int i = 0; i < listSize; i++) {
3440         CellUtil.updateLatestStamp(cells.get(i), now, 0);
3441       }
3442     }
3443   }
3444 
3445   /**
3446    * Possibly rewrite incoming cell tags.
3447    */
3448   void rewriteCellTags(Map<byte[], List<Cell>> familyMap, final Mutation m) {
3449     // Check if we have any work to do and early out otherwise
3450     // Update these checks as more logic is added here
3451 
3452     if (m.getTTL() == Long.MAX_VALUE) {
3453       return;
3454     }
3455 
3456     // From this point we know we have some work to do
3457 
3458     for (Map.Entry<byte[], List<Cell>> e: familyMap.entrySet()) {
3459       List<Cell> cells = e.getValue();
3460       assert cells instanceof RandomAccess;
3461       int listSize = cells.size();
3462       for (int i = 0; i < listSize; i++) {
3463         Cell cell = cells.get(i);
3464         List<Tag> newTags = new ArrayList<Tag>();
3465         Iterator<Tag> tagIterator = CellUtil.tagsIterator(cell.getTagsArray(),
3466           cell.getTagsOffset(), cell.getTagsLength());
3467 
3468         // Carry forward existing tags
3469 
3470         while (tagIterator.hasNext()) {
3471 
3472           // Add any filters or tag specific rewrites here
3473 
3474           newTags.add(tagIterator.next());
3475         }
3476 
3477         // Cell TTL handling
3478 
3479         // Check again if we need to add a cell TTL because early out logic
3480         // above may change when there are more tag based features in core.
3481         if (m.getTTL() != Long.MAX_VALUE) {
3482           // Add a cell TTL tag
3483           newTags.add(new Tag(TagType.TTL_TAG_TYPE, Bytes.toBytes(m.getTTL())));
3484         }
3485 
3486         // Rewrite the cell with the updated set of tags
3487 
3488         cells.set(i, new KeyValue(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(),
3489           cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
3490           cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(),
3491           cell.getTimestamp(), KeyValue.Type.codeToType(cell.getTypeByte()),
3492           cell.getValueArray(), cell.getValueOffset(), cell.getValueLength(),
3493           newTags));
3494       }
3495     }
3496   }
3497 
3498   /*
3499    * Check if resources to support an update.
3500    *
3501    * We throw RegionTooBusyException if above memstore limit
3502    * and expect client to retry using some kind of backoff
3503   */
3504   private void checkResources() throws RegionTooBusyException {
3505     // If catalog region, do not impose resource constraints or block updates.
3506     if (this.getRegionInfo().isMetaRegion()) return;
3507 
3508     if (this.memstoreSize.get() > this.blockingMemStoreSize) {
3509       blockedRequestsCount.increment();
3510       requestFlush();
3511       throw new RegionTooBusyException("Above memstore limit, " +
3512           "regionName=" + (this.getRegionInfo() == null ? "unknown" :
3513           this.getRegionInfo().getRegionNameAsString()) +
3514           ", server=" + (this.getRegionServerServices() == null ? "unknown" :
3515           this.getRegionServerServices().getServerName()) +
3516           ", memstoreSize=" + memstoreSize.get() +
3517           ", blockingMemStoreSize=" + blockingMemStoreSize);
3518     }
3519   }
3520 
3521   /**
3522    * @throws IOException Throws exception if region is in read-only mode.
3523    */
3524   protected void checkReadOnly() throws IOException {
3525     if (isReadOnly()) {
3526       throw new IOException("region is read only");
3527     }
3528   }
3529 
3530   protected void checkReadsEnabled() throws IOException {
3531     if (!this.writestate.readsEnabled) {
3532       throw new IOException(getRegionInfo().getEncodedName()
3533         + ": The region's reads are disabled. Cannot serve the request");
3534     }
3535   }
3536 
3537   public void setReadsEnabled(boolean readsEnabled) {
3538    if (readsEnabled && !this.writestate.readsEnabled) {
3539      LOG.info(getRegionInfo().getEncodedName() + " : Enabling reads for region.");
3540     }
3541     this.writestate.setReadsEnabled(readsEnabled);
3542   }
3543 
3544   /**
3545    * Add updates first to the wal and then add values to memstore.
3546    * Warning: Assumption is caller has lock on passed in row.
3547    * @param edits Cell updates by column
3548    * @throws IOException
3549    */
3550   private void put(final byte [] row, byte [] family, List<Cell> edits)
3551   throws IOException {
3552     NavigableMap<byte[], List<Cell>> familyMap;
3553     familyMap = new TreeMap<byte[], List<Cell>>(Bytes.BYTES_COMPARATOR);
3554 
3555     familyMap.put(family, edits);
3556     Put p = new Put(row);
3557     p.setFamilyCellMap(familyMap);
3558     doBatchMutate(p);
3559   }
3560 
3561   /**
3562    * Atomically apply the given map of family->edits to the memstore.
3563    * This handles the consistency control on its own, but the caller
3564    * should already have locked updatesLock.readLock(). This also does
3565    * <b>not</b> check the families for validity.
3566    *
3567    * @param familyMap Map of kvs per family
3568    * @param localizedWriteEntry The WriteEntry of the MVCC for this transaction.
3569    *        If null, then this method internally creates a mvcc transaction.
3570    * @param output newly added KVs into memstore
3571    * @param isInReplay true when adding replayed KVs into memstore
3572    * @return the additional memory usage of the memstore caused by the
3573    * new entries.
3574    * @throws IOException
3575    */
3576   private long applyFamilyMapToMemstore(Map<byte[], List<Cell>> familyMap,
3577     long mvccNum, List<Cell> memstoreCells, boolean isInReplay) throws IOException {
3578     long size = 0;
3579 
3580     for (Map.Entry<byte[], List<Cell>> e : familyMap.entrySet()) {
3581       byte[] family = e.getKey();
3582       List<Cell> cells = e.getValue();
3583       assert cells instanceof RandomAccess;
3584       Store store = getStore(family);
3585       int listSize = cells.size();
3586       for (int i=0; i < listSize; i++) {
3587         Cell cell = cells.get(i);
3588         CellUtil.setSequenceId(cell, mvccNum);
3589         Pair<Long, Cell> ret = store.add(cell);
3590         size += ret.getFirst();
3591         memstoreCells.add(ret.getSecond());
3592         if(isInReplay) {
3593           // set memstore newly added cells with replay mvcc number
3594           CellUtil.setSequenceId(ret.getSecond(), mvccNum);
3595         }
3596       }
3597     }
3598 
3599      return size;
3600    }
3601 
3602   /**
3603    * Remove all the keys listed in the map from the memstore. This method is
3604    * called when a Put/Delete has updated memstore but subsequently fails to update
3605    * the wal. This method is then invoked to rollback the memstore.
3606    */
3607   private void rollbackMemstore(List<Cell> memstoreCells) {
3608     int kvsRolledback = 0;
3609 
3610     for (Cell cell : memstoreCells) {
3611       byte[] family = CellUtil.cloneFamily(cell);
3612       Store store = getStore(family);
3613       store.rollback(cell);
3614       kvsRolledback++;
3615     }
3616     LOG.debug("rollbackMemstore rolled back " + kvsRolledback);
3617   }
3618 
3619   @Override
3620   public void checkFamilies(Collection<byte[]> families) throws NoSuchColumnFamilyException {
3621     for (byte[] family : families) {
3622       checkFamily(family);
3623     }
3624   }
3625 
3626   /**
3627    * During replay, there could exist column families which are removed between region server
3628    * failure and replay
3629    */
3630   private void removeNonExistentColumnFamilyForReplay(
3631       final Map<byte[], List<Cell>> familyMap) {
3632     List<byte[]> nonExistentList = null;
3633     for (byte[] family : familyMap.keySet()) {
3634       if (!this.htableDescriptor.hasFamily(family)) {
3635         if (nonExistentList == null) {
3636           nonExistentList = new ArrayList<byte[]>();
3637         }
3638         nonExistentList.add(family);
3639       }
3640     }
3641     if (nonExistentList != null) {
3642       for (byte[] family : nonExistentList) {
3643         // Perhaps schema was changed between crash and replay
3644         LOG.info("No family for " + Bytes.toString(family) + " omit from reply.");
3645         familyMap.remove(family);
3646       }
3647     }
3648   }
3649 
3650   @Override
3651   public void checkTimestamps(final Map<byte[], List<Cell>> familyMap, long now)
3652       throws FailedSanityCheckException {
3653     if (timestampSlop == HConstants.LATEST_TIMESTAMP) {
3654       return;
3655     }
3656     long maxTs = now + timestampSlop;
3657     for (List<Cell> kvs : familyMap.values()) {
3658       assert kvs instanceof RandomAccess;
3659       int listSize  = kvs.size();
3660       for (int i=0; i < listSize; i++) {
3661         Cell cell = kvs.get(i);
3662         // see if the user-side TS is out of range. latest = server-side
3663         long ts = cell.getTimestamp();
3664         if (ts != HConstants.LATEST_TIMESTAMP && ts > maxTs) {
3665           throw new FailedSanityCheckException("Timestamp for KV out of range "
3666               + cell + " (too.new=" + timestampSlop + ")");
3667         }
3668       }
3669     }
3670   }
3671 
3672   /**
3673    * Append the given map of family->edits to a WALEdit data structure.
3674    * This does not write to the WAL itself.
3675    * @param familyMap map of family->edits
3676    * @param walEdit the destination entry to append into
3677    */
3678   private void addFamilyMapToWALEdit(Map<byte[], List<Cell>> familyMap,
3679       WALEdit walEdit) {
3680     for (List<Cell> edits : familyMap.values()) {
3681       assert edits instanceof RandomAccess;
3682       int listSize = edits.size();
3683       for (int i=0; i < listSize; i++) {
3684         Cell cell = edits.get(i);
3685         walEdit.add(cell);
3686       }
3687     }
3688   }
3689 
3690   private void requestFlush() {
3691     if (this.rsServices == null) {
3692       return;
3693     }
3694     synchronized (writestate) {
3695       if (this.writestate.isFlushRequested()) {
3696         return;
3697       }
3698       writestate.flushRequested = true;
3699     }
3700     // Make request outside of synchronize block; HBASE-818.
3701     this.rsServices.getFlushRequester().requestFlush(this, false);
3702     if (LOG.isDebugEnabled()) {
3703       LOG.debug("Flush requested on " + this);
3704     }
3705   }
3706 
3707   /*
3708    * @param size
3709    * @return True if size is over the flush threshold
3710    */
3711   private boolean isFlushSize(final long size) {
3712     return size > this.memstoreFlushSize;
3713   }
3714 
3715   /**
3716    * Read the edits put under this region by wal splitting process.  Put
3717    * the recovered edits back up into this region.
3718    *
3719    * <p>We can ignore any wal message that has a sequence ID that's equal to or
3720    * lower than minSeqId.  (Because we know such messages are already
3721    * reflected in the HFiles.)
3722    *
3723    * <p>While this is running we are putting pressure on memory yet we are
3724    * outside of our usual accounting because we are not yet an onlined region
3725    * (this stuff is being run as part of Region initialization).  This means
3726    * that if we're up against global memory limits, we'll not be flagged to flush
3727    * because we are not online. We can't be flushed by usual mechanisms anyways;
3728    * we're not yet online so our relative sequenceids are not yet aligned with
3729    * WAL sequenceids -- not till we come up online, post processing of split
3730    * edits.
3731    *
3732    * <p>But to help relieve memory pressure, at least manage our own heap size
3733    * flushing if are in excess of per-region limits.  Flushing, though, we have
3734    * to be careful and avoid using the regionserver/wal sequenceid.  Its running
3735    * on a different line to whats going on in here in this region context so if we
3736    * crashed replaying these edits, but in the midst had a flush that used the
3737    * regionserver wal with a sequenceid in excess of whats going on in here
3738    * in this region and with its split editlogs, then we could miss edits the
3739    * next time we go to recover. So, we have to flush inline, using seqids that
3740    * make sense in a this single region context only -- until we online.
3741    *
3742    * @param maxSeqIdInStores Any edit found in split editlogs needs to be in excess of
3743    * the maxSeqId for the store to be applied, else its skipped.
3744    * @return the sequence id of the last edit added to this region out of the
3745    * recovered edits log or <code>minSeqId</code> if nothing added from editlogs.
3746    * @throws UnsupportedEncodingException
3747    * @throws IOException
3748    */
3749   protected long replayRecoveredEditsIfAny(final Path regiondir,
3750       Map<byte[], Long> maxSeqIdInStores,
3751       final CancelableProgressable reporter, final MonitoredTask status)
3752       throws IOException {
3753     long minSeqIdForTheRegion = -1;
3754     for (Long maxSeqIdInStore : maxSeqIdInStores.values()) {
3755       if (maxSeqIdInStore < minSeqIdForTheRegion || minSeqIdForTheRegion == -1) {
3756         minSeqIdForTheRegion = maxSeqIdInStore;
3757       }
3758     }
3759     long seqid = minSeqIdForTheRegion;
3760 
3761     FileSystem fs = this.fs.getFileSystem();
3762     NavigableSet<Path> files = WALSplitter.getSplitEditFilesSorted(fs, regiondir);
3763     if (LOG.isDebugEnabled()) {
3764       LOG.debug("Found " + (files == null ? 0 : files.size())
3765         + " recovered edits file(s) under " + regiondir);
3766     }
3767 
3768     if (files == null || files.isEmpty()) return seqid;
3769 
3770     for (Path edits: files) {
3771       if (edits == null || !fs.exists(edits)) {
3772         LOG.warn("Null or non-existent edits file: " + edits);
3773         continue;
3774       }
3775       if (isZeroLengthThenDelete(fs, edits)) continue;
3776 
3777       long maxSeqId;
3778       String fileName = edits.getName();
3779       maxSeqId = Math.abs(Long.parseLong(fileName));
3780       if (maxSeqId <= minSeqIdForTheRegion) {
3781         if (LOG.isDebugEnabled()) {
3782           String msg = "Maximum sequenceid for this wal is " + maxSeqId
3783             + " and minimum sequenceid for the region is " + minSeqIdForTheRegion
3784             + ", skipped the whole file, path=" + edits;
3785           LOG.debug(msg);
3786         }
3787         continue;
3788       }
3789 
3790       try {
3791         // replay the edits. Replay can return -1 if everything is skipped, only update
3792         // if seqId is greater
3793         seqid = Math.max(seqid, replayRecoveredEdits(edits, maxSeqIdInStores, reporter));
3794       } catch (IOException e) {
3795         boolean skipErrors = conf.getBoolean(
3796             HConstants.HREGION_EDITS_REPLAY_SKIP_ERRORS,
3797             conf.getBoolean(
3798                 "hbase.skip.errors",
3799                 HConstants.DEFAULT_HREGION_EDITS_REPLAY_SKIP_ERRORS));
3800         if (conf.get("hbase.skip.errors") != null) {
3801           LOG.warn(
3802               "The property 'hbase.skip.errors' has been deprecated. Please use " +
3803               HConstants.HREGION_EDITS_REPLAY_SKIP_ERRORS + " instead.");
3804         }
3805         if (skipErrors) {
3806           Path p = WALSplitter.moveAsideBadEditsFile(fs, edits);
3807           LOG.error(HConstants.HREGION_EDITS_REPLAY_SKIP_ERRORS
3808               + "=true so continuing. Renamed " + edits +
3809               " as " + p, e);
3810         } else {
3811           throw e;
3812         }
3813       }
3814     }
3815     // The edits size added into rsAccounting during this replaying will not
3816     // be required any more. So just clear it.
3817     if (this.rsAccounting != null) {
3818       this.rsAccounting.clearRegionReplayEditsSize(getRegionInfo().getRegionName());
3819     }
3820     if (seqid > minSeqIdForTheRegion) {
3821       // Then we added some edits to memory. Flush and cleanup split edit files.
3822       internalFlushcache(null, seqid, stores.values(), status, false);
3823     }
3824     // Now delete the content of recovered edits.  We're done w/ them.
3825     if (files.size() > 0 && this.conf.getBoolean("hbase.region.archive.recovered.edits", false)) {
3826       // For debugging data loss issues!
3827       // If this flag is set, make use of the hfile archiving by making recovered.edits a fake
3828       // column family. Have to fake out file type too by casting our recovered.edits as storefiles
3829       String fakeFamilyName = WALSplitter.getRegionDirRecoveredEditsDir(regiondir).getName();
3830       Set<StoreFile> fakeStoreFiles = new HashSet<StoreFile>(files.size());
3831       for (Path file: files) {
3832         fakeStoreFiles.add(new StoreFile(getRegionFileSystem().getFileSystem(), file, this.conf,
3833           null, null));
3834       }
3835       getRegionFileSystem().removeStoreFiles(fakeFamilyName, fakeStoreFiles);
3836     } else {
3837       for (Path file: files) {
3838         if (!fs.delete(file, false)) {
3839           LOG.error("Failed delete of " + file);
3840         } else {
3841           LOG.debug("Deleted recovered.edits file=" + file);
3842         }
3843       }
3844     }
3845     return seqid;
3846   }
3847 
3848   /*
3849    * @param edits File of recovered edits.
3850    * @param maxSeqIdInStores Maximum sequenceid found in each store.  Edits in wal
3851    * must be larger than this to be replayed for each store.
3852    * @param reporter
3853    * @return the sequence id of the last edit added to this region out of the
3854    * recovered edits log or <code>minSeqId</code> if nothing added from editlogs.
3855    * @throws IOException
3856    */
3857   private long replayRecoveredEdits(final Path edits,
3858       Map<byte[], Long> maxSeqIdInStores, final CancelableProgressable reporter)
3859     throws IOException {
3860     String msg = "Replaying edits from " + edits;
3861     LOG.info(msg);
3862     MonitoredTask status = TaskMonitor.get().createStatus(msg);
3863     FileSystem fs = this.fs.getFileSystem();
3864 
3865     status.setStatus("Opening recovered edits");
3866     WAL.Reader reader = null;
3867     try {
3868       reader = WALFactory.createReader(fs, edits, conf);
3869       long currentEditSeqId = -1;
3870       long currentReplaySeqId = -1;
3871       long firstSeqIdInLog = -1;
3872       long skippedEdits = 0;
3873       long editsCount = 0;
3874       long intervalEdits = 0;
3875       WAL.Entry entry;
3876       Store store = null;
3877       boolean reported_once = false;
3878       ServerNonceManager ng = this.rsServices == null ? null : this.rsServices.getNonceManager();
3879 
3880       try {
3881         // How many edits seen before we check elapsed time
3882         int interval = this.conf.getInt("hbase.hstore.report.interval.edits", 2000);
3883         // How often to send a progress report (default 1/2 master timeout)
3884         int period = this.conf.getInt("hbase.hstore.report.period", 300000);
3885         long lastReport = EnvironmentEdgeManager.currentTime();
3886 
3887         while ((entry = reader.next()) != null) {
3888           WALKey key = entry.getKey();
3889           WALEdit val = entry.getEdit();
3890 
3891           if (ng != null) { // some test, or nonces disabled
3892             ng.reportOperationFromWal(key.getNonceGroup(), key.getNonce(), key.getWriteTime());
3893           }
3894 
3895           if (reporter != null) {
3896             intervalEdits += val.size();
3897             if (intervalEdits >= interval) {
3898               // Number of edits interval reached
3899               intervalEdits = 0;
3900               long cur = EnvironmentEdgeManager.currentTime();
3901               if (lastReport + period <= cur) {
3902                 status.setStatus("Replaying edits..." +
3903                     " skipped=" + skippedEdits +
3904                     " edits=" + editsCount);
3905                 // Timeout reached
3906                 if(!reporter.progress()) {
3907                   msg = "Progressable reporter failed, stopping replay";
3908                   LOG.warn(msg);
3909                   status.abort(msg);
3910                   throw new IOException(msg);
3911                 }
3912                 reported_once = true;
3913                 lastReport = cur;
3914               }
3915             }
3916           }
3917 
3918           if (firstSeqIdInLog == -1) {
3919             firstSeqIdInLog = key.getLogSeqNum();
3920           }
3921           if (currentEditSeqId > key.getLogSeqNum()) {
3922             // when this condition is true, it means we have a serious defect because we need to
3923             // maintain increasing SeqId for WAL edits per region
3924             LOG.error(getRegionInfo().getEncodedName() + " : "
3925                  + "Found decreasing SeqId. PreId=" + currentEditSeqId + " key=" + key
3926                 + "; edit=" + val);
3927           } else {
3928             currentEditSeqId = key.getLogSeqNum();
3929           }
3930           currentReplaySeqId = (key.getOrigLogSeqNum() > 0) ?
3931             key.getOrigLogSeqNum() : currentEditSeqId;
3932 
3933           // Start coprocessor replay here. The coprocessor is for each WALEdit
3934           // instead of a KeyValue.
3935           if (coprocessorHost != null) {
3936             status.setStatus("Running pre-WAL-restore hook in coprocessors");
3937             if (coprocessorHost.preWALRestore(this.getRegionInfo(), key, val)) {
3938               // if bypass this wal entry, ignore it ...
3939               continue;
3940             }
3941           }
3942           // Check this edit is for this region.
3943           if (!Bytes.equals(key.getEncodedRegionName(),
3944               this.getRegionInfo().getEncodedNameAsBytes())) {
3945             skippedEdits++;
3946             continue;
3947           }
3948 
3949           boolean flush = false;
3950           for (Cell cell: val.getCells()) {
3951             // Check this edit is for me. Also, guard against writing the special
3952             // METACOLUMN info such as HBASE::CACHEFLUSH entries
3953             if (CellUtil.matchingFamily(cell, WALEdit.METAFAMILY)) {
3954               //this is a special edit, we should handle it
3955               CompactionDescriptor compaction = WALEdit.getCompaction(cell);
3956               if (compaction != null) {
3957                 //replay the compaction
3958                 replayWALCompactionMarker(compaction, false, true, Long.MAX_VALUE);
3959               }
3960               skippedEdits++;
3961               continue;
3962             }
3963             // Figure which store the edit is meant for.
3964             if (store == null || !CellUtil.matchingFamily(cell, store.getFamily().getName())) {
3965               store = getStore(cell);
3966             }
3967             if (store == null) {
3968               // This should never happen.  Perhaps schema was changed between
3969               // crash and redeploy?
3970               LOG.warn("No family for " + cell);
3971               skippedEdits++;
3972               continue;
3973             }
3974             // Now, figure if we should skip this edit.
3975             if (key.getLogSeqNum() <= maxSeqIdInStores.get(store.getFamily()
3976                 .getName())) {
3977               skippedEdits++;
3978               continue;
3979             }
3980             CellUtil.setSequenceId(cell, currentReplaySeqId);
3981 
3982             // Once we are over the limit, restoreEdit will keep returning true to
3983             // flush -- but don't flush until we've played all the kvs that make up
3984             // the WALEdit.
3985             flush |= restoreEdit(store, cell);
3986             editsCount++;
3987           }
3988           if (flush) {
3989             internalFlushcache(null, currentEditSeqId, stores.values(), status, false);
3990           }
3991 
3992           if (coprocessorHost != null) {
3993             coprocessorHost.postWALRestore(this.getRegionInfo(), key, val);
3994           }
3995         }
3996       } catch (EOFException eof) {
3997         Path p = WALSplitter.moveAsideBadEditsFile(fs, edits);
3998         msg = "Encountered EOF. Most likely due to Master failure during " +
3999             "wal splitting, so we have this data in another edit.  " +
4000             "Continuing, but renaming " + edits + " as " + p;
4001         LOG.warn(msg, eof);
4002         status.abort(msg);
4003       } catch (IOException ioe) {
4004         // If the IOE resulted from bad file format,
4005         // then this problem is idempotent and retrying won't help
4006         if (ioe.getCause() instanceof ParseException) {
4007           Path p = WALSplitter.moveAsideBadEditsFile(fs, edits);
4008           msg = "File corruption encountered!  " +
4009               "Continuing, but renaming " + edits + " as " + p;
4010           LOG.warn(msg, ioe);
4011           status.setStatus(msg);
4012         } else {
4013           status.abort(StringUtils.stringifyException(ioe));
4014           // other IO errors may be transient (bad network connection,
4015           // checksum exception on one datanode, etc).  throw & retry
4016           throw ioe;
4017         }
4018       }
4019       if (reporter != null && !reported_once) {
4020         reporter.progress();
4021       }
4022       msg = "Applied " + editsCount + ", skipped " + skippedEdits +
4023         ", firstSequenceIdInLog=" + firstSeqIdInLog +
4024         ", maxSequenceIdInLog=" + currentEditSeqId + ", path=" + edits;
4025       status.markComplete(msg);
4026       LOG.debug(msg);
4027       return currentEditSeqId;
4028     } finally {
4029       status.cleanup();
4030       if (reader != null) {
4031          reader.close();
4032       }
4033     }
4034   }
4035 
4036   /**
4037    * Call to complete a compaction. Its for the case where we find in the WAL a compaction
4038    * that was not finished.  We could find one recovering a WAL after a regionserver crash.
4039    * See HBASE-2331.
4040    */
4041   void replayWALCompactionMarker(CompactionDescriptor compaction, boolean pickCompactionFiles,
4042       boolean removeFiles, long replaySeqId)
4043       throws IOException {
4044     checkTargetRegion(compaction.getEncodedRegionName().toByteArray(),
4045       "Compaction marker from WAL ", compaction);
4046 
4047     synchronized (writestate) {
4048       if (replaySeqId < lastReplayedOpenRegionSeqId) {
4049         LOG.warn(getRegionInfo().getEncodedName() + " : "
4050             + "Skipping replaying compaction event :" + TextFormat.shortDebugString(compaction)
4051             + " because its sequence id " + replaySeqId + " is smaller than this regions "
4052             + "lastReplayedOpenRegionSeqId of " + lastReplayedOpenRegionSeqId);
4053         return;
4054       }
4055       if (replaySeqId < lastReplayedCompactionSeqId) {
4056         LOG.warn(getRegionInfo().getEncodedName() + " : "
4057             + "Skipping replaying compaction event :" + TextFormat.shortDebugString(compaction)
4058             + " because its sequence id " + replaySeqId + " is smaller than this regions "
4059             + "lastReplayedCompactionSeqId of " + lastReplayedCompactionSeqId);
4060         return;
4061       } else {
4062         lastReplayedCompactionSeqId = replaySeqId;
4063       }
4064 
4065       if (LOG.isDebugEnabled()) {
4066         LOG.debug(getRegionInfo().getEncodedName() + " : "
4067             + "Replaying compaction marker " + TextFormat.shortDebugString(compaction)
4068             + " with seqId=" + replaySeqId + " and lastReplayedOpenRegionSeqId="
4069             + lastReplayedOpenRegionSeqId);
4070       }
4071 
4072       startRegionOperation(Operation.REPLAY_EVENT);
4073       try {
4074         Store store = this.getStore(compaction.getFamilyName().toByteArray());
4075         if (store == null) {
4076           LOG.warn(getRegionInfo().getEncodedName() + " : "
4077               + "Found Compaction WAL edit for deleted family:"
4078               + Bytes.toString(compaction.getFamilyName().toByteArray()));
4079           return;
4080         }
4081         store.replayCompactionMarker(compaction, pickCompactionFiles, removeFiles);
4082         logRegionFiles();
4083       } catch (FileNotFoundException ex) {
4084         LOG.warn(getRegionInfo().getEncodedName() + " : "
4085             + "At least one of the store files in compaction: "
4086             + TextFormat.shortDebugString(compaction)
4087             + " doesn't exist any more. Skip loading the file(s)", ex);
4088       } finally {
4089         closeRegionOperation(Operation.REPLAY_EVENT);
4090       }
4091     }
4092   }
4093 
4094   void replayWALFlushMarker(FlushDescriptor flush, long replaySeqId) throws IOException {
4095     checkTargetRegion(flush.getEncodedRegionName().toByteArray(),
4096       "Flush marker from WAL ", flush);
4097 
4098     if (ServerRegionReplicaUtil.isDefaultReplica(this.getRegionInfo())) {
4099       return; // if primary nothing to do
4100     }
4101 
4102     if (LOG.isDebugEnabled()) {
4103       LOG.debug(getRegionInfo().getEncodedName() + " : "
4104           + "Replaying flush marker " + TextFormat.shortDebugString(flush));
4105     }
4106 
4107     startRegionOperation(Operation.REPLAY_EVENT); // use region close lock to guard against close
4108     try {
4109       FlushAction action = flush.getAction();
4110       switch (action) {
4111       case START_FLUSH:
4112         replayWALFlushStartMarker(flush);
4113         break;
4114       case COMMIT_FLUSH:
4115         replayWALFlushCommitMarker(flush);
4116         break;
4117       case ABORT_FLUSH:
4118         replayWALFlushAbortMarker(flush);
4119         break;
4120       case CANNOT_FLUSH:
4121         replayWALFlushCannotFlushMarker(flush, replaySeqId);
4122         break;
4123       default:
4124         LOG.warn(getRegionInfo().getEncodedName() + " : " +
4125           "Received a flush event with unknown action, ignoring. " +
4126           TextFormat.shortDebugString(flush));
4127         break;
4128       }
4129 
4130       logRegionFiles();
4131     } finally {
4132       closeRegionOperation(Operation.REPLAY_EVENT);
4133     }
4134   }
4135 
4136   /** Replay the flush marker from primary region by creating a corresponding snapshot of
4137    * the store memstores, only if the memstores do not have a higher seqId from an earlier wal
4138    * edit (because the events may be coming out of order).
4139    */
4140   @VisibleForTesting
4141   PrepareFlushResult replayWALFlushStartMarker(FlushDescriptor flush) throws IOException {
4142     long flushSeqId = flush.getFlushSequenceNumber();
4143 
4144     HashSet<Store> storesToFlush = new HashSet<Store>();
4145     for (StoreFlushDescriptor storeFlush : flush.getStoreFlushesList()) {
4146       byte[] family = storeFlush.getFamilyName().toByteArray();
4147       Store store = getStore(family);
4148       if (store == null) {
4149         LOG.warn(getRegionInfo().getEncodedName() + " : "
4150           + "Received a flush start marker from primary, but the family is not found. Ignoring"
4151           + " StoreFlushDescriptor:" + TextFormat.shortDebugString(storeFlush));
4152         continue;
4153       }
4154       storesToFlush.add(store);
4155     }
4156 
4157     MonitoredTask status = TaskMonitor.get().createStatus("Preparing flush " + this);
4158 
4159     // we will use writestate as a coarse-grain lock for all the replay events
4160     // (flush, compaction, region open etc)
4161     synchronized (writestate) {
4162       try {
4163         if (flush.getFlushSequenceNumber() < lastReplayedOpenRegionSeqId) {
4164           LOG.warn(getRegionInfo().getEncodedName() + " : "
4165               + "Skipping replaying flush event :" + TextFormat.shortDebugString(flush)
4166               + " because its sequence id is smaller than this regions lastReplayedOpenRegionSeqId "
4167               + " of " + lastReplayedOpenRegionSeqId);
4168           return null;
4169         }
4170         if (numMutationsWithoutWAL.get() > 0) {
4171           numMutationsWithoutWAL.set(0);
4172           dataInMemoryWithoutWAL.set(0);
4173         }
4174 
4175         if (!writestate.flushing) {
4176           // we do not have an active snapshot and corresponding this.prepareResult. This means
4177           // we can just snapshot our memstores and continue as normal.
4178 
4179           // invoke prepareFlushCache. Send null as wal since we do not want the flush events in wal
4180           PrepareFlushResult prepareResult = internalPrepareFlushCache(null,
4181             flushSeqId, storesToFlush, status, false);
4182           if (prepareResult.result == null) {
4183             // save the PrepareFlushResult so that we can use it later from commit flush
4184             this.writestate.flushing = true;
4185             this.prepareFlushResult = prepareResult;
4186             status.markComplete("Flush prepare successful");
4187             if (LOG.isDebugEnabled()) {
4188               LOG.debug(getRegionInfo().getEncodedName() + " : "
4189                   + " Prepared flush with seqId:" + flush.getFlushSequenceNumber());
4190             }
4191           } else {
4192             // special case empty memstore. We will still save the flush result in this case, since
4193             // our memstore ie empty, but the primary is still flushing
4194             if (prepareResult.getResult().getResult() ==
4195                   FlushResult.Result.CANNOT_FLUSH_MEMSTORE_EMPTY) {
4196               this.writestate.flushing = true;
4197               this.prepareFlushResult = prepareResult;
4198               if (LOG.isDebugEnabled()) {
4199                 LOG.debug(getRegionInfo().getEncodedName() + " : "
4200                   + " Prepared empty flush with seqId:" + flush.getFlushSequenceNumber());
4201               }
4202             }
4203             status.abort("Flush prepare failed with " + prepareResult.result);
4204             // nothing much to do. prepare flush failed because of some reason.
4205           }
4206           return prepareResult;
4207         } else {
4208           // we already have an active snapshot.
4209           if (flush.getFlushSequenceNumber() == this.prepareFlushResult.flushOpSeqId) {
4210             // They define the same flush. Log and continue.
4211             LOG.warn(getRegionInfo().getEncodedName() + " : "
4212                 + "Received a flush prepare marker with the same seqId: " +
4213                 + flush.getFlushSequenceNumber() + " before clearing the previous one with seqId: "
4214                 + prepareFlushResult.flushOpSeqId + ". Ignoring");
4215             // ignore
4216           } else if (flush.getFlushSequenceNumber() < this.prepareFlushResult.flushOpSeqId) {
4217             // We received a flush with a smaller seqNum than what we have prepared. We can only
4218             // ignore this prepare flush request.
4219             LOG.warn(getRegionInfo().getEncodedName() + " : "
4220                 + "Received a flush prepare marker with a smaller seqId: " +
4221                 + flush.getFlushSequenceNumber() + " before clearing the previous one with seqId: "
4222                 + prepareFlushResult.flushOpSeqId + ". Ignoring");
4223             // ignore
4224           } else {
4225             // We received a flush with a larger seqNum than what we have prepared
4226             LOG.warn(getRegionInfo().getEncodedName() + " : "
4227                 + "Received a flush prepare marker with a larger seqId: " +
4228                 + flush.getFlushSequenceNumber() + " before clearing the previous one with seqId: "
4229                 + prepareFlushResult.flushOpSeqId + ". Ignoring");
4230             // We do not have multiple active snapshots in the memstore or a way to merge current
4231             // memstore snapshot with the contents and resnapshot for now. We cannot take
4232             // another snapshot and drop the previous one because that will cause temporary
4233             // data loss in the secondary. So we ignore this for now, deferring the resolution
4234             // to happen when we see the corresponding flush commit marker. If we have a memstore
4235             // snapshot with x, and later received another prepare snapshot with y (where x < y),
4236             // when we see flush commit for y, we will drop snapshot for x, and can also drop all
4237             // the memstore edits if everything in memstore is < y. This is the usual case for
4238             // RS crash + recovery where we might see consequtive prepare flush wal markers.
4239             // Otherwise, this will cause more memory to be used in secondary replica until a
4240             // further prapare + commit flush is seen and replayed.
4241           }
4242         }
4243       } finally {
4244         status.cleanup();
4245         writestate.notifyAll();
4246       }
4247     }
4248     return null;
4249   }
4250 
4251   @VisibleForTesting
4252   void replayWALFlushCommitMarker(FlushDescriptor flush) throws IOException {
4253     MonitoredTask status = TaskMonitor.get().createStatus("Committing flush " + this);
4254 
4255     // check whether we have the memstore snapshot with the corresponding seqId. Replay to
4256     // secondary region replicas are in order, except for when the region moves or then the
4257     // region server crashes. In those cases, we may receive replay requests out of order from
4258     // the original seqIds.
4259     synchronized (writestate) {
4260       try {
4261         if (flush.getFlushSequenceNumber() < lastReplayedOpenRegionSeqId) {
4262           LOG.warn(getRegionInfo().getEncodedName() + " : "
4263             + "Skipping replaying flush event :" + TextFormat.shortDebugString(flush)
4264             + " because its sequence id is smaller than this regions lastReplayedOpenRegionSeqId "
4265             + " of " + lastReplayedOpenRegionSeqId);
4266           return;
4267         }
4268 
4269         if (writestate.flushing) {
4270           PrepareFlushResult prepareFlushResult = this.prepareFlushResult;
4271           if (flush.getFlushSequenceNumber() == prepareFlushResult.flushOpSeqId) {
4272             if (LOG.isDebugEnabled()) {
4273               LOG.debug(getRegionInfo().getEncodedName() + " : "
4274                   + "Received a flush commit marker with seqId:" + flush.getFlushSequenceNumber()
4275                   + " and a previous prepared snapshot was found");
4276             }
4277             // This is the regular case where we received commit flush after prepare flush
4278             // corresponding to the same seqId.
4279             replayFlushInStores(flush, prepareFlushResult, true);
4280 
4281             // Set down the memstore size by amount of flush.
4282             this.addAndGetGlobalMemstoreSize(-prepareFlushResult.totalFlushableSize);
4283 
4284             this.prepareFlushResult = null;
4285             writestate.flushing = false;
4286           } else if (flush.getFlushSequenceNumber() < prepareFlushResult.flushOpSeqId) {
4287             // This should not happen normally. However, lets be safe and guard against these cases
4288             // we received a flush commit with a smaller seqId than what we have prepared
4289             // we will pick the flush file up from this commit (if we have not seen it), but we
4290             // will not drop the memstore
4291             LOG.warn(getRegionInfo().getEncodedName() + " : "
4292                 + "Received a flush commit marker with smaller seqId: "
4293                 + flush.getFlushSequenceNumber() + " than what we have prepared with seqId: "
4294                 + prepareFlushResult.flushOpSeqId + ". Picking up new file, but not dropping"
4295                 +"  prepared memstore snapshot");
4296             replayFlushInStores(flush, prepareFlushResult, false);
4297 
4298             // snapshot is not dropped, so memstore sizes should not be decremented
4299             // we still have the prepared snapshot, flushing should still be true
4300           } else {
4301             // This should not happen normally. However, lets be safe and guard against these cases
4302             // we received a flush commit with a larger seqId than what we have prepared
4303             // we will pick the flush file for this. We will also obtain the updates lock and
4304             // look for contents of the memstore to see whether we have edits after this seqId.
4305             // If not, we will drop all the memstore edits and the snapshot as well.
4306             LOG.warn(getRegionInfo().getEncodedName() + " : "
4307                 + "Received a flush commit marker with larger seqId: "
4308                 + flush.getFlushSequenceNumber() + " than what we have prepared with seqId: " +
4309                 prepareFlushResult.flushOpSeqId + ". Picking up new file and dropping prepared"
4310                 +" memstore snapshot");
4311 
4312             replayFlushInStores(flush, prepareFlushResult, true);
4313 
4314             // Set down the memstore size by amount of flush.
4315             this.addAndGetGlobalMemstoreSize(-prepareFlushResult.totalFlushableSize);
4316 
4317             // Inspect the memstore contents to see whether the memstore contains only edits
4318             // with seqId smaller than the flush seqId. If so, we can discard those edits.
4319             dropMemstoreContentsForSeqId(flush.getFlushSequenceNumber(), null);
4320 
4321             this.prepareFlushResult = null;
4322             writestate.flushing = false;
4323           }
4324           // If we were waiting for observing a flush or region opening event for not showing
4325           // partial data after a secondary region crash, we can allow reads now. We can only make
4326           // sure that we are not showing partial data (for example skipping some previous edits)
4327           // until we observe a full flush start and flush commit. So if we were not able to find
4328           // a previous flush we will not enable reads now.
4329           this.setReadsEnabled(true);
4330         } else {
4331           LOG.warn(getRegionInfo().getEncodedName() + " : "
4332               + "Received a flush commit marker with seqId:" + flush.getFlushSequenceNumber()
4333               + ", but no previous prepared snapshot was found");
4334           // There is no corresponding prepare snapshot from before.
4335           // We will pick up the new flushed file
4336           replayFlushInStores(flush, null, false);
4337 
4338           // Inspect the memstore contents to see whether the memstore contains only edits
4339           // with seqId smaller than the flush seqId. If so, we can discard those edits.
4340           dropMemstoreContentsForSeqId(flush.getFlushSequenceNumber(), null);
4341         }
4342 
4343         status.markComplete("Flush commit successful");
4344 
4345         // Update the last flushed sequence id for region.
4346         this.maxFlushedSeqId = flush.getFlushSequenceNumber();
4347 
4348         // advance the mvcc read point so that the new flushed file is visible.
4349         // there may be some in-flight transactions, but they won't be made visible since they are
4350         // either greater than flush seq number or they were already dropped via flush.
4351         // TODO: If we are using FlushAllStoresPolicy, then this can make edits visible from other
4352         // stores while they are still in flight because the flush commit marker will not contain
4353         // flushes from ALL stores.
4354         getMVCC().advanceMemstoreReadPointIfNeeded(flush.getFlushSequenceNumber());
4355 
4356       } catch (FileNotFoundException ex) {
4357         LOG.warn(getRegionInfo().getEncodedName() + " : "
4358             + "At least one of the store files in flush: " + TextFormat.shortDebugString(flush)
4359             + " doesn't exist any more. Skip loading the file(s)", ex);
4360       }
4361       finally {
4362         status.cleanup();
4363         writestate.notifyAll();
4364       }
4365     }
4366 
4367     // C. Finally notify anyone waiting on memstore to clear:
4368     // e.g. checkResources().
4369     synchronized (this) {
4370       notifyAll(); // FindBugs NN_NAKED_NOTIFY
4371     }
4372   }
4373 
4374   /**
4375    * Replays the given flush descriptor by opening the flush files in stores and dropping the
4376    * memstore snapshots if requested.
4377    * @param flush
4378    * @param prepareFlushResult
4379    * @param dropMemstoreSnapshot
4380    * @throws IOException
4381    */
4382   private void replayFlushInStores(FlushDescriptor flush, PrepareFlushResult prepareFlushResult,
4383       boolean dropMemstoreSnapshot)
4384       throws IOException {
4385     for (StoreFlushDescriptor storeFlush : flush.getStoreFlushesList()) {
4386       byte[] family = storeFlush.getFamilyName().toByteArray();
4387       Store store = getStore(family);
4388       if (store == null) {
4389         LOG.warn(getRegionInfo().getEncodedName() + " : "
4390             + "Received a flush commit marker from primary, but the family is not found."
4391             + "Ignoring StoreFlushDescriptor:" + storeFlush);
4392         continue;
4393       }
4394       List<String> flushFiles = storeFlush.getFlushOutputList();
4395       StoreFlushContext ctx = null;
4396       long startTime = EnvironmentEdgeManager.currentTime();
4397       if (prepareFlushResult == null || prepareFlushResult.storeFlushCtxs == null) {
4398         ctx = store.createFlushContext(flush.getFlushSequenceNumber());
4399       } else {
4400         ctx = prepareFlushResult.storeFlushCtxs.get(family);
4401         startTime = prepareFlushResult.startTime;
4402       }
4403 
4404       if (ctx == null) {
4405         LOG.warn(getRegionInfo().getEncodedName() + " : "
4406             + "Unexpected: flush commit marker received from store "
4407             + Bytes.toString(family) + " but no associated flush context. Ignoring");
4408         continue;
4409       }
4410 
4411       ctx.replayFlush(flushFiles, dropMemstoreSnapshot); // replay the flush
4412 
4413       // Record latest flush time
4414       this.lastStoreFlushTimeMap.put(store, startTime);
4415     }
4416   }
4417 
4418   /**
4419    * Drops the memstore contents after replaying a flush descriptor or region open event replay
4420    * if the memstore edits have seqNums smaller than the given seq id
4421    * @param flush the flush descriptor
4422    * @throws IOException
4423    */
4424   private long dropMemstoreContentsForSeqId(long seqId, Store store) throws IOException {
4425     long totalFreedSize = 0;
4426     this.updatesLock.writeLock().lock();
4427     try {
4428       mvcc.waitForPreviousTransactionsComplete();
4429       long currentSeqId = getSequenceId().get();
4430       if (seqId >= currentSeqId) {
4431         // then we can drop the memstore contents since everything is below this seqId
4432         LOG.info(getRegionInfo().getEncodedName() + " : "
4433             + "Dropping memstore contents as well since replayed flush seqId: "
4434             + seqId + " is greater than current seqId:" + currentSeqId);
4435 
4436         // Prepare flush (take a snapshot) and then abort (drop the snapshot)
4437         if (store == null ) {
4438           for (Store s : stores.values()) {
4439             totalFreedSize += doDropStoreMemstoreContentsForSeqId(s, currentSeqId);
4440           }
4441         } else {
4442           totalFreedSize += doDropStoreMemstoreContentsForSeqId(store, currentSeqId);
4443         }
4444       } else {
4445         LOG.info(getRegionInfo().getEncodedName() + " : "
4446             + "Not dropping memstore contents since replayed flush seqId: "
4447             + seqId + " is smaller than current seqId:" + currentSeqId);
4448       }
4449     } finally {
4450       this.updatesLock.writeLock().unlock();
4451     }
4452     return totalFreedSize;
4453   }
4454 
4455   private long doDropStoreMemstoreContentsForSeqId(Store s, long currentSeqId) throws IOException {
4456     long snapshotSize = s.getFlushableSize();
4457     this.addAndGetGlobalMemstoreSize(-snapshotSize);
4458     StoreFlushContext ctx = s.createFlushContext(currentSeqId);
4459     ctx.prepare();
4460     ctx.abort();
4461     return snapshotSize;
4462   }
4463 
4464   private void replayWALFlushAbortMarker(FlushDescriptor flush) {
4465     // nothing to do for now. A flush abort will cause a RS abort which means that the region
4466     // will be opened somewhere else later. We will see the region open event soon, and replaying
4467     // that will drop the snapshot
4468   }
4469 
4470   private void replayWALFlushCannotFlushMarker(FlushDescriptor flush, long replaySeqId) {
4471     synchronized (writestate) {
4472       if (this.lastReplayedOpenRegionSeqId > replaySeqId) {
4473         LOG.warn(getRegionInfo().getEncodedName() + " : "
4474           + "Skipping replaying flush event :" + TextFormat.shortDebugString(flush)
4475           + " because its sequence id " + replaySeqId + " is smaller than this regions "
4476           + "lastReplayedOpenRegionSeqId of " + lastReplayedOpenRegionSeqId);
4477         return;
4478       }
4479 
4480       // If we were waiting for observing a flush or region opening event for not showing partial
4481       // data after a secondary region crash, we can allow reads now. This event means that the
4482       // primary was not able to flush because memstore is empty when we requested flush. By the
4483       // time we observe this, we are guaranteed to have up to date seqId with our previous
4484       // assignment.
4485       this.setReadsEnabled(true);
4486     }
4487   }
4488 
4489   @VisibleForTesting
4490   PrepareFlushResult getPrepareFlushResult() {
4491     return prepareFlushResult;
4492   }
4493 
4494   void replayWALRegionEventMarker(RegionEventDescriptor regionEvent) throws IOException {
4495     checkTargetRegion(regionEvent.getEncodedRegionName().toByteArray(),
4496       "RegionEvent marker from WAL ", regionEvent);
4497 
4498     startRegionOperation(Operation.REPLAY_EVENT);
4499     try {
4500       if (ServerRegionReplicaUtil.isDefaultReplica(this.getRegionInfo())) {
4501         return; // if primary nothing to do
4502       }
4503 
4504       if (regionEvent.getEventType() == EventType.REGION_CLOSE) {
4505         // nothing to do on REGION_CLOSE for now.
4506         return;
4507       }
4508       if (regionEvent.getEventType() != EventType.REGION_OPEN) {
4509         LOG.warn(getRegionInfo().getEncodedName() + " : "
4510             + "Unknown region event received, ignoring :"
4511             + TextFormat.shortDebugString(regionEvent));
4512         return;
4513       }
4514 
4515       if (LOG.isDebugEnabled()) {
4516         LOG.debug(getRegionInfo().getEncodedName() + " : "
4517           + "Replaying region open event marker " + TextFormat.shortDebugString(regionEvent));
4518       }
4519 
4520       // we will use writestate as a coarse-grain lock for all the replay events
4521       synchronized (writestate) {
4522         // Replication can deliver events out of order when primary region moves or the region
4523         // server crashes, since there is no coordination between replication of different wal files
4524         // belonging to different region servers. We have to safe guard against this case by using
4525         // region open event's seqid. Since this is the first event that the region puts (after
4526         // possibly flushing recovered.edits), after seeing this event, we can ignore every edit
4527         // smaller than this seqId
4528         if (this.lastReplayedOpenRegionSeqId <= regionEvent.getLogSequenceNumber()) {
4529           this.lastReplayedOpenRegionSeqId = regionEvent.getLogSequenceNumber();
4530         } else {
4531           LOG.warn(getRegionInfo().getEncodedName() + " : "
4532             + "Skipping replaying region event :" + TextFormat.shortDebugString(regionEvent)
4533             + " because its sequence id is smaller than this regions lastReplayedOpenRegionSeqId "
4534             + " of " + lastReplayedOpenRegionSeqId);
4535           return;
4536         }
4537 
4538         // region open lists all the files that the region has at the time of the opening. Just pick
4539         // all the files and drop prepared flushes and empty memstores
4540         for (StoreDescriptor storeDescriptor : regionEvent.getStoresList()) {
4541           // stores of primary may be different now
4542           byte[] family = storeDescriptor.getFamilyName().toByteArray();
4543           Store store = getStore(family);
4544           if (store == null) {
4545             LOG.warn(getRegionInfo().getEncodedName() + " : "
4546                 + "Received a region open marker from primary, but the family is not found. "
4547                 + "Ignoring. StoreDescriptor:" + storeDescriptor);
4548             continue;
4549           }
4550 
4551           long storeSeqId = store.getMaxSequenceId();
4552           List<String> storeFiles = storeDescriptor.getStoreFileList();
4553           try {
4554             store.refreshStoreFiles(storeFiles); // replace the files with the new ones
4555           } catch (FileNotFoundException ex) {
4556             LOG.warn(getRegionInfo().getEncodedName() + " : "
4557                     + "At least one of the store files: " + storeFiles
4558                     + " doesn't exist any more. Skip loading the file(s)", ex);
4559             continue;
4560           }
4561           if (store.getMaxSequenceId() != storeSeqId) {
4562             // Record latest flush time if we picked up new files
4563             lastStoreFlushTimeMap.put(store, EnvironmentEdgeManager.currentTime());
4564           }
4565 
4566           if (writestate.flushing) {
4567             // only drop memstore snapshots if they are smaller than last flush for the store
4568             if (this.prepareFlushResult.flushOpSeqId <= regionEvent.getLogSequenceNumber()) {
4569               StoreFlushContext ctx = this.prepareFlushResult.storeFlushCtxs == null ?
4570                   null : this.prepareFlushResult.storeFlushCtxs.get(family);
4571               if (ctx != null) {
4572                 long snapshotSize = store.getFlushableSize();
4573                 ctx.abort();
4574                 this.addAndGetGlobalMemstoreSize(-snapshotSize);
4575                 this.prepareFlushResult.storeFlushCtxs.remove(family);
4576               }
4577             }
4578           }
4579 
4580           // Drop the memstore contents if they are now smaller than the latest seen flushed file
4581           dropMemstoreContentsForSeqId(regionEvent.getLogSequenceNumber(), store);
4582           if (storeSeqId > this.maxFlushedSeqId) {
4583             this.maxFlushedSeqId = storeSeqId;
4584           }
4585         }
4586 
4587         // if all stores ended up dropping their snapshots, we can safely drop the
4588         // prepareFlushResult
4589         dropPrepareFlushIfPossible();
4590 
4591         // advance the mvcc read point so that the new flushed file is visible.
4592         // there may be some in-flight transactions, but they won't be made visible since they are
4593         // either greater than flush seq number or they were already dropped via flush.
4594         getMVCC().advanceMemstoreReadPointIfNeeded(this.maxFlushedSeqId);
4595 
4596         // If we were waiting for observing a flush or region opening event for not showing partial
4597         // data after a secondary region crash, we can allow reads now.
4598         this.setReadsEnabled(true);
4599 
4600         // C. Finally notify anyone waiting on memstore to clear:
4601         // e.g. checkResources().
4602         synchronized (this) {
4603           notifyAll(); // FindBugs NN_NAKED_NOTIFY
4604         }
4605       }
4606       logRegionFiles();
4607     } finally {
4608       closeRegionOperation(Operation.REPLAY_EVENT);
4609     }
4610   }
4611 
4612   void replayWALBulkLoadEventMarker(WALProtos.BulkLoadDescriptor bulkLoadEvent) throws IOException {
4613     checkTargetRegion(bulkLoadEvent.getEncodedRegionName().toByteArray(),
4614       "BulkLoad marker from WAL ", bulkLoadEvent);
4615 
4616     if (ServerRegionReplicaUtil.isDefaultReplica(this.getRegionInfo())) {
4617       return; // if primary nothing to do
4618     }
4619 
4620     if (LOG.isDebugEnabled()) {
4621       LOG.debug(getRegionInfo().getEncodedName() + " : "
4622               +  "Replaying bulkload event marker " + TextFormat.shortDebugString(bulkLoadEvent));
4623     }
4624     // check if multiple families involved
4625     boolean multipleFamilies = false;
4626     byte[] family = null;
4627     for (StoreDescriptor storeDescriptor : bulkLoadEvent.getStoresList()) {
4628       byte[] fam = storeDescriptor.getFamilyName().toByteArray();
4629       if (family == null) {
4630         family = fam;
4631       } else if (!Bytes.equals(family, fam)) {
4632         multipleFamilies = true;
4633         break;
4634       }
4635     }
4636 
4637     startBulkRegionOperation(multipleFamilies);
4638     try {
4639       // we will use writestate as a coarse-grain lock for all the replay events
4640       synchronized (writestate) {
4641         // Replication can deliver events out of order when primary region moves or the region
4642         // server crashes, since there is no coordination between replication of different wal files
4643         // belonging to different region servers. We have to safe guard against this case by using
4644         // region open event's seqid. Since this is the first event that the region puts (after
4645         // possibly flushing recovered.edits), after seeing this event, we can ignore every edit
4646         // smaller than this seqId
4647         if (bulkLoadEvent.getBulkloadSeqNum() >= 0
4648             && this.lastReplayedOpenRegionSeqId >= bulkLoadEvent.getBulkloadSeqNum()) {
4649           LOG.warn(getRegionInfo().getEncodedName() + " : "
4650               + "Skipping replaying bulkload event :"
4651               + TextFormat.shortDebugString(bulkLoadEvent)
4652               + " because its sequence id is smaller than this region's lastReplayedOpenRegionSeqId"
4653               + " =" + lastReplayedOpenRegionSeqId);
4654 
4655           return;
4656         }
4657 
4658         for (StoreDescriptor storeDescriptor : bulkLoadEvent.getStoresList()) {
4659           // stores of primary may be different now
4660           family = storeDescriptor.getFamilyName().toByteArray();
4661           Store store = getStore(family);
4662           if (store == null) {
4663             LOG.warn(getRegionInfo().getEncodedName() + " : "
4664                     + "Received a bulk load marker from primary, but the family is not found. "
4665                     + "Ignoring. StoreDescriptor:" + storeDescriptor);
4666             continue;
4667           }
4668 
4669           List<String> storeFiles = storeDescriptor.getStoreFileList();
4670           for (String storeFile : storeFiles) {
4671             StoreFileInfo storeFileInfo = null;
4672             try {
4673               storeFileInfo = fs.getStoreFileInfo(Bytes.toString(family), storeFile);
4674               store.bulkLoadHFile(storeFileInfo);
4675             } catch(FileNotFoundException ex) {
4676               LOG.warn(getRegionInfo().getEncodedName() + " : "
4677                       + ((storeFileInfo != null) ? storeFileInfo.toString() :
4678                             (new Path(Bytes.toString(family), storeFile)).toString())
4679                       + " doesn't exist any more. Skip loading the file");
4680             }
4681           }
4682         }
4683       }
4684       if (bulkLoadEvent.getBulkloadSeqNum() > 0) {
4685         getMVCC().advanceMemstoreReadPointIfNeeded(bulkLoadEvent.getBulkloadSeqNum());
4686       }
4687     } finally {
4688       closeBulkRegionOperation();
4689     }
4690   }
4691 
4692   /**
4693    * If all stores ended up dropping their snapshots, we can safely drop the prepareFlushResult
4694    */
4695   private void dropPrepareFlushIfPossible() {
4696     if (writestate.flushing) {
4697       boolean canDrop = true;
4698       if (prepareFlushResult.storeFlushCtxs != null) {
4699         for (Entry<byte[], StoreFlushContext> entry
4700             : prepareFlushResult.storeFlushCtxs.entrySet()) {
4701           Store store = getStore(entry.getKey());
4702           if (store == null) {
4703             continue;
4704           }
4705           if (store.getSnapshotSize() > 0) {
4706             canDrop = false;
4707             break;
4708           }
4709         }
4710       }
4711 
4712       // this means that all the stores in the region has finished flushing, but the WAL marker
4713       // may not have been written or we did not receive it yet.
4714       if (canDrop) {
4715         writestate.flushing = false;
4716         this.prepareFlushResult = null;
4717       }
4718     }
4719   }
4720 
4721   @Override
4722   public boolean refreshStoreFiles() throws IOException {
4723     if (ServerRegionReplicaUtil.isDefaultReplica(this.getRegionInfo())) {
4724       return false; // if primary nothing to do
4725     }
4726 
4727     if (LOG.isDebugEnabled()) {
4728       LOG.debug(getRegionInfo().getEncodedName() + " : "
4729           + "Refreshing store files to see whether we can free up memstore");
4730     }
4731 
4732     long totalFreedSize = 0;
4733 
4734     long smallestSeqIdInStores = Long.MAX_VALUE;
4735 
4736     startRegionOperation(); // obtain region close lock
4737     try {
4738       synchronized (writestate) {
4739         for (Store store : getStores()) {
4740           // TODO: some stores might see new data from flush, while others do not which
4741           // MIGHT break atomic edits across column families.
4742           long maxSeqIdBefore = store.getMaxSequenceId();
4743 
4744           // refresh the store files. This is similar to observing a region open wal marker.
4745           store.refreshStoreFiles();
4746 
4747           long storeSeqId = store.getMaxSequenceId();
4748           if (storeSeqId < smallestSeqIdInStores) {
4749             smallestSeqIdInStores = storeSeqId;
4750           }
4751 
4752           // see whether we can drop the memstore or the snapshot
4753           if (storeSeqId > maxSeqIdBefore) {
4754 
4755             if (writestate.flushing) {
4756               // only drop memstore snapshots if they are smaller than last flush for the store
4757               if (this.prepareFlushResult.flushOpSeqId <= storeSeqId) {
4758                 StoreFlushContext ctx = this.prepareFlushResult.storeFlushCtxs == null ?
4759                     null : this.prepareFlushResult.storeFlushCtxs.get(store.getFamily().getName());
4760                 if (ctx != null) {
4761                   long snapshotSize = store.getFlushableSize();
4762                   ctx.abort();
4763                   this.addAndGetGlobalMemstoreSize(-snapshotSize);
4764                   this.prepareFlushResult.storeFlushCtxs.remove(store.getFamily().getName());
4765                   totalFreedSize += snapshotSize;
4766                 }
4767               }
4768             }
4769 
4770             // Drop the memstore contents if they are now smaller than the latest seen flushed file
4771             totalFreedSize += dropMemstoreContentsForSeqId(storeSeqId, store);
4772           }
4773         }
4774 
4775         // if all stores ended up dropping their snapshots, we can safely drop the
4776         // prepareFlushResult
4777         dropPrepareFlushIfPossible();
4778 
4779         // advance the mvcc read point so that the new flushed files are visible.
4780         // there may be some in-flight transactions, but they won't be made visible since they are
4781         // either greater than flush seq number or they were already picked up via flush.
4782         for (Store s : getStores()) {
4783           getMVCC().advanceMemstoreReadPointIfNeeded(s.getMaxMemstoreTS());
4784         }
4785 
4786         // smallestSeqIdInStores is the seqId that we have a corresponding hfile for. We can safely
4787         // skip all edits that are to be replayed in the future with that has a smaller seqId
4788         // than this. We are updating lastReplayedOpenRegionSeqId so that we can skip all edits
4789         // that we have picked the flush files for
4790         if (this.lastReplayedOpenRegionSeqId < smallestSeqIdInStores) {
4791           this.lastReplayedOpenRegionSeqId = smallestSeqIdInStores;
4792         }
4793       }
4794       // C. Finally notify anyone waiting on memstore to clear:
4795       // e.g. checkResources().
4796       synchronized (this) {
4797         notifyAll(); // FindBugs NN_NAKED_NOTIFY
4798       }
4799       return totalFreedSize > 0;
4800     } finally {
4801       closeRegionOperation();
4802     }
4803   }
4804 
4805   private void logRegionFiles() {
4806     if (LOG.isTraceEnabled()) {
4807       LOG.trace(getRegionInfo().getEncodedName() + " : Store files for region: ");
4808       for (Store s : stores.values()) {
4809         for (StoreFile sf : s.getStorefiles()) {
4810           LOG.trace(getRegionInfo().getEncodedName() + " : " + sf);
4811         }
4812       }
4813     }
4814   }
4815 
4816   /** Checks whether the given regionName is either equal to our region, or that
4817    * the regionName is the primary region to our corresponding range for the secondary replica.
4818    */
4819   private void checkTargetRegion(byte[] encodedRegionName, String exceptionMsg, Object payload)
4820       throws WrongRegionException {
4821     if (Bytes.equals(this.getRegionInfo().getEncodedNameAsBytes(), encodedRegionName)) {
4822       return;
4823     }
4824 
4825     if (!RegionReplicaUtil.isDefaultReplica(this.getRegionInfo()) &&
4826         Bytes.equals(encodedRegionName,
4827           this.fs.getRegionInfoForFS().getEncodedNameAsBytes())) {
4828       return;
4829     }
4830 
4831     throw new WrongRegionException(exceptionMsg + payload
4832       + " targetted for region " + Bytes.toStringBinary(encodedRegionName)
4833       + " does not match this region: " + this.getRegionInfo());
4834   }
4835 
4836   /**
4837    * Used by tests
4838    * @param s Store to add edit too.
4839    * @param cell Cell to add.
4840    * @return True if we should flush.
4841    */
4842   protected boolean restoreEdit(final Store s, final Cell cell) {
4843     long kvSize = s.add(cell).getFirst();
4844     if (this.rsAccounting != null) {
4845       rsAccounting.addAndGetRegionReplayEditsSize(getRegionInfo().getRegionName(), kvSize);
4846     }
4847     return isFlushSize(this.addAndGetGlobalMemstoreSize(kvSize));
4848   }
4849 
4850   /*
4851    * @param fs
4852    * @param p File to check.
4853    * @return True if file was zero-length (and if so, we'll delete it in here).
4854    * @throws IOException
4855    */
4856   private static boolean isZeroLengthThenDelete(final FileSystem fs, final Path p)
4857       throws IOException {
4858     FileStatus stat = fs.getFileStatus(p);
4859     if (stat.getLen() > 0) return false;
4860     LOG.warn("File " + p + " is zero-length, deleting.");
4861     fs.delete(p, false);
4862     return true;
4863   }
4864 
4865   protected HStore instantiateHStore(final HColumnDescriptor family) throws IOException {
4866     return new HStore(this, family, this.conf);
4867   }
4868 
4869   @Override
4870   public Store getStore(final byte[] column) {
4871     return this.stores.get(column);
4872   }
4873 
4874   /**
4875    * Return HStore instance. Does not do any copy: as the number of store is limited, we
4876    *  iterate on the list.
4877    */
4878   private Store getStore(Cell cell) {
4879     for (Map.Entry<byte[], Store> famStore : stores.entrySet()) {
4880       if (Bytes.equals(
4881           cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
4882           famStore.getKey(), 0, famStore.getKey().length)) {
4883         return famStore.getValue();
4884       }
4885     }
4886 
4887     return null;
4888   }
4889 
4890   @Override
4891   public List<Store> getStores() {
4892     List<Store> list = new ArrayList<Store>(stores.size());
4893     list.addAll(stores.values());
4894     return list;
4895   }
4896 
4897   @Override
4898   public List<String> getStoreFileList(final byte [][] columns)
4899     throws IllegalArgumentException {
4900     List<String> storeFileNames = new ArrayList<String>();
4901     synchronized(closeLock) {
4902       for(byte[] column : columns) {
4903         Store store = this.stores.get(column);
4904         if (store == null) {
4905           throw new IllegalArgumentException("No column family : " +
4906               new String(column) + " available");
4907         }
4908         for (StoreFile storeFile: store.getStorefiles()) {
4909           storeFileNames.add(storeFile.getPath().toString());
4910         }
4911 
4912         logRegionFiles();
4913       }
4914     }
4915     return storeFileNames;
4916   }
4917 
4918   //////////////////////////////////////////////////////////////////////////////
4919   // Support code
4920   //////////////////////////////////////////////////////////////////////////////
4921 
4922   /** Make sure this is a valid row for the HRegion */
4923   void checkRow(final byte [] row, String op) throws IOException {
4924     if (!rowIsInRange(getRegionInfo(), row)) {
4925       throw new WrongRegionException("Requested row out of range for " +
4926           op + " on HRegion " + this + ", startKey='" +
4927           Bytes.toStringBinary(getRegionInfo().getStartKey()) + "', getEndKey()='" +
4928           Bytes.toStringBinary(getRegionInfo().getEndKey()) + "', row='" +
4929           Bytes.toStringBinary(row) + "'");
4930     }
4931   }
4932 
4933   @Override
4934   public RowLock getRowLock(byte[] row, boolean waitForLock) throws IOException {
4935     startRegionOperation();
4936     try {
4937       return getRowLockInternal(row, waitForLock);
4938     } finally {
4939       closeRegionOperation();
4940     }
4941   }
4942 
4943   /**
4944    * A version of getRowLock(byte[], boolean) to use when a region operation has already been
4945    * started (the calling thread has already acquired the region-close-guard lock).
4946    */
4947   protected RowLock getRowLockInternal(byte[] row, boolean waitForLock) throws IOException {
4948     HashedBytes rowKey = new HashedBytes(row);
4949     RowLockContext rowLockContext = new RowLockContext(rowKey);
4950 
4951     // loop until we acquire the row lock (unless !waitForLock)
4952     while (true) {
4953       RowLockContext existingContext = lockedRows.putIfAbsent(rowKey, rowLockContext);
4954       if (existingContext == null) {
4955         // Row is not already locked by any thread, use newly created context.
4956         break;
4957       } else if (existingContext.ownedByCurrentThread()) {
4958         // Row is already locked by current thread, reuse existing context instead.
4959         rowLockContext = existingContext;
4960         break;
4961       } else {
4962         if (!waitForLock) {
4963           return null;
4964         }
4965         TraceScope traceScope = null;
4966         try {
4967           if (Trace.isTracing()) {
4968             traceScope = Trace.startSpan("HRegion.getRowLockInternal");
4969           }
4970           // Row is already locked by some other thread, give up or wait for it
4971           if (!existingContext.latch.await(this.rowLockWaitDuration, TimeUnit.MILLISECONDS)) {
4972             if(traceScope != null) {
4973               traceScope.getSpan().addTimelineAnnotation("Failed to get row lock");
4974             }
4975             throw new IOException("Timed out waiting for lock for row: " + rowKey);
4976           }
4977           if (traceScope != null) traceScope.close();
4978           traceScope = null;
4979         } catch (InterruptedException ie) {
4980           LOG.warn("Thread interrupted waiting for lock on row: " + rowKey);
4981           InterruptedIOException iie = new InterruptedIOException();
4982           iie.initCause(ie);
4983           throw iie;
4984         } finally {
4985           if (traceScope != null) traceScope.close();
4986         }
4987       }
4988     }
4989 
4990     // allocate new lock for this thread
4991     return rowLockContext.newLock();
4992   }
4993 
4994   /**
4995    * Acquires a lock on the given row.
4996    * The same thread may acquire multiple locks on the same row.
4997    * @return the acquired row lock
4998    * @throws IOException if the lock could not be acquired after waiting
4999    */
5000   public RowLock getRowLock(byte[] row) throws IOException {
5001     return getRowLock(row, true);
5002   }
5003 
5004   @Override
5005   public void releaseRowLocks(List<RowLock> rowLocks) {
5006     if (rowLocks != null) {
5007       for (RowLock rowLock : rowLocks) {
5008         rowLock.release();
5009       }
5010       rowLocks.clear();
5011     }
5012   }
5013 
5014   /**
5015    * Determines whether multiple column families are present
5016    * Precondition: familyPaths is not null
5017    *
5018    * @param familyPaths List of Pair<byte[] column family, String hfilePath>
5019    */
5020   private static boolean hasMultipleColumnFamilies(Collection<Pair<byte[], String>> familyPaths) {
5021     boolean multipleFamilies = false;
5022     byte[] family = null;
5023     for (Pair<byte[], String> pair : familyPaths) {
5024       byte[] fam = pair.getFirst();
5025       if (family == null) {
5026         family = fam;
5027       } else if (!Bytes.equals(family, fam)) {
5028         multipleFamilies = true;
5029         break;
5030       }
5031     }
5032     return multipleFamilies;
5033   }
5034 
5035   @Override
5036   public boolean bulkLoadHFiles(Collection<Pair<byte[], String>> familyPaths, boolean assignSeqId,
5037       BulkLoadListener bulkLoadListener) throws IOException {
5038     long seqId = -1;
5039     Map<byte[], List<Path>> storeFiles = new TreeMap<byte[], List<Path>>(Bytes.BYTES_COMPARATOR);
5040     Preconditions.checkNotNull(familyPaths);
5041     // we need writeLock for multi-family bulk load
5042     startBulkRegionOperation(hasMultipleColumnFamilies(familyPaths));
5043     try {
5044       this.writeRequestsCount.increment();
5045 
5046       // There possibly was a split that happened between when the split keys
5047       // were gathered and before the HRegion's write lock was taken.  We need
5048       // to validate the HFile region before attempting to bulk load all of them
5049       List<IOException> ioes = new ArrayList<IOException>();
5050       List<Pair<byte[], String>> failures = new ArrayList<Pair<byte[], String>>();
5051       for (Pair<byte[], String> p : familyPaths) {
5052         byte[] familyName = p.getFirst();
5053         String path = p.getSecond();
5054 
5055         Store store = getStore(familyName);
5056         if (store == null) {
5057           IOException ioe = new org.apache.hadoop.hbase.DoNotRetryIOException(
5058               "No such column family " + Bytes.toStringBinary(familyName));
5059           ioes.add(ioe);
5060         } else {
5061           try {
5062             store.assertBulkLoadHFileOk(new Path(path));
5063           } catch (WrongRegionException wre) {
5064             // recoverable (file doesn't fit in region)
5065             failures.add(p);
5066           } catch (IOException ioe) {
5067             // unrecoverable (hdfs problem)
5068             ioes.add(ioe);
5069           }
5070         }
5071       }
5072 
5073       // validation failed because of some sort of IO problem.
5074       if (ioes.size() != 0) {
5075         IOException e = MultipleIOException.createIOException(ioes);
5076         LOG.error("There were one or more IO errors when checking if the bulk load is ok.", e);
5077         throw e;
5078       }
5079 
5080       // validation failed, bail out before doing anything permanent.
5081       if (failures.size() != 0) {
5082         StringBuilder list = new StringBuilder();
5083         for (Pair<byte[], String> p : failures) {
5084           list.append("\n").append(Bytes.toString(p.getFirst())).append(" : ")
5085               .append(p.getSecond());
5086         }
5087         // problem when validating
5088         LOG.warn("There was a recoverable bulk load failure likely due to a" +
5089             " split.  These (family, HFile) pairs were not loaded: " + list);
5090         return false;
5091       }
5092 
5093       // We need to assign a sequential ID that's in between two memstores in order to preserve
5094       // the guarantee that all the edits lower than the highest sequential ID from all the
5095       // HFiles are flushed on disk. See HBASE-10958.  The sequence id returned when we flush is
5096       // guaranteed to be one beyond the file made when we flushed (or if nothing to flush, it is
5097       // a sequence id that we can be sure is beyond the last hfile written).
5098       if (assignSeqId) {
5099         FlushResult fs = flushcache(true, false);
5100         if (fs.isFlushSucceeded()) {
5101           seqId = ((FlushResultImpl)fs).flushSequenceId;
5102         } else if (fs.getResult() == FlushResult.Result.CANNOT_FLUSH_MEMSTORE_EMPTY) {
5103           seqId = ((FlushResultImpl)fs).flushSequenceId;
5104         } else {
5105           throw new IOException("Could not bulk load with an assigned sequential ID because the "+
5106             "flush didn't run. Reason for not flushing: " + ((FlushResultImpl)fs).failureReason);
5107         }
5108       }
5109 
5110       for (Pair<byte[], String> p : familyPaths) {
5111         byte[] familyName = p.getFirst();
5112         String path = p.getSecond();
5113         Store store = getStore(familyName);
5114         try {
5115           String finalPath = path;
5116           if (bulkLoadListener != null) {
5117             finalPath = bulkLoadListener.prepareBulkLoad(familyName, path);
5118           }
5119           Path commitedStoreFile = store.bulkLoadHFile(finalPath, seqId);
5120 
5121           if(storeFiles.containsKey(familyName)) {
5122             storeFiles.get(familyName).add(commitedStoreFile);
5123           } else {
5124             List<Path> storeFileNames = new ArrayList<Path>();
5125             storeFileNames.add(commitedStoreFile);
5126             storeFiles.put(familyName, storeFileNames);
5127           }
5128           if (bulkLoadListener != null) {
5129             bulkLoadListener.doneBulkLoad(familyName, path);
5130           }
5131         } catch (IOException ioe) {
5132           // A failure here can cause an atomicity violation that we currently
5133           // cannot recover from since it is likely a failed HDFS operation.
5134 
5135           // TODO Need a better story for reverting partial failures due to HDFS.
5136           LOG.error("There was a partial failure due to IO when attempting to" +
5137               " load " + Bytes.toString(p.getFirst()) + " : " + p.getSecond(), ioe);
5138           if (bulkLoadListener != null) {
5139             try {
5140               bulkLoadListener.failedBulkLoad(familyName, path);
5141             } catch (Exception ex) {
5142               LOG.error("Error while calling failedBulkLoad for family " +
5143                   Bytes.toString(familyName) + " with path " + path, ex);
5144             }
5145           }
5146           throw ioe;
5147         }
5148       }
5149 
5150       return true;
5151     } finally {
5152       if (wal != null && !storeFiles.isEmpty()) {
5153         // write a bulk load event when not all hfiles are loaded
5154         try {
5155           WALProtos.BulkLoadDescriptor loadDescriptor = ProtobufUtil.toBulkLoadDescriptor(
5156               this.getRegionInfo().getTable(),
5157               ByteStringer.wrap(this.getRegionInfo().getEncodedNameAsBytes()), storeFiles, seqId);
5158           WALUtil.writeBulkLoadMarkerAndSync(wal, this.htableDescriptor, getRegionInfo(),
5159               loadDescriptor, sequenceId);
5160         } catch (IOException ioe) {
5161           if (this.rsServices != null) {
5162             // Have to abort region server because some hfiles has been loaded but we can't write
5163             // the event into WAL
5164             this.rsServices.abort("Failed to write bulk load event into WAL.", ioe);
5165           }
5166         }
5167       }
5168 
5169       closeBulkRegionOperation();
5170     }
5171   }
5172 
5173   @Override
5174   public boolean equals(Object o) {
5175     return o instanceof HRegion && Bytes.equals(getRegionInfo().getRegionName(),
5176                                                 ((HRegion) o).getRegionInfo().getRegionName());
5177   }
5178 
5179   @Override
5180   public int hashCode() {
5181     return Bytes.hashCode(getRegionInfo().getRegionName());
5182   }
5183 
5184   @Override
5185   public String toString() {
5186     return getRegionInfo().getRegionNameAsString();
5187   }
5188 
5189   /**
5190    * RegionScannerImpl is used to combine scanners from multiple Stores (aka column families).
5191    */
5192   class RegionScannerImpl implements RegionScanner {
5193     // Package local for testability
5194     KeyValueHeap storeHeap = null;
5195     /** Heap of key-values that are not essential for the provided filters and are thus read
5196      * on demand, if on-demand column family loading is enabled.*/
5197     KeyValueHeap joinedHeap = null;
5198     /**
5199      * If the joined heap data gathering is interrupted due to scan limits, this will
5200      * contain the row for which we are populating the values.*/
5201     protected Cell joinedContinuationRow = null;
5202     protected final byte[] stopRow;
5203     private final FilterWrapper filter;
5204     private ScannerContext defaultScannerContext;
5205     protected int isScan;
5206     private boolean filterClosed = false;
5207     private long readPt;
5208     private long maxResultSize;
5209     protected HRegion region;
5210 
5211     @Override
5212     public HRegionInfo getRegionInfo() {
5213       return region.getRegionInfo();
5214     }
5215 
5216     RegionScannerImpl(Scan scan, List<KeyValueScanner> additionalScanners, HRegion region)
5217         throws IOException {
5218 
5219       this.region = region;
5220       this.maxResultSize = scan.getMaxResultSize();
5221       if (scan.hasFilter()) {
5222         this.filter = new FilterWrapper(scan.getFilter());
5223       } else {
5224         this.filter = null;
5225       }
5226 
5227       /**
5228        * By default, calls to next/nextRaw must enforce the batch limit. Thus, construct a default
5229        * scanner context that can be used to enforce the batch limit in the event that a
5230        * ScannerContext is not specified during an invocation of next/nextRaw
5231        */
5232       defaultScannerContext = ScannerContext.newBuilder().setBatchLimit(scan.getBatch()).build();
5233 
5234       if (Bytes.equals(scan.getStopRow(), HConstants.EMPTY_END_ROW) && !scan.isGetScan()) {
5235         this.stopRow = null;
5236       } else {
5237         this.stopRow = scan.getStopRow();
5238       }
5239       // If we are doing a get, we want to be [startRow,endRow] normally
5240       // it is [startRow,endRow) and if startRow=endRow we get nothing.
5241       this.isScan = scan.isGetScan() ? -1 : 0;
5242 
5243       // synchronize on scannerReadPoints so that nobody calculates
5244       // getSmallestReadPoint, before scannerReadPoints is updated.
5245       IsolationLevel isolationLevel = scan.getIsolationLevel();
5246       synchronized(scannerReadPoints) {
5247         this.readPt = getReadpoint(isolationLevel);
5248         scannerReadPoints.put(this, this.readPt);
5249       }
5250 
5251       // Here we separate all scanners into two lists - scanner that provide data required
5252       // by the filter to operate (scanners list) and all others (joinedScanners list).
5253       List<KeyValueScanner> scanners = new ArrayList<KeyValueScanner>();
5254       List<KeyValueScanner> joinedScanners = new ArrayList<KeyValueScanner>();
5255       if (additionalScanners != null) {
5256         scanners.addAll(additionalScanners);
5257       }
5258 
5259       for (Map.Entry<byte[], NavigableSet<byte[]>> entry :
5260           scan.getFamilyMap().entrySet()) {
5261         Store store = stores.get(entry.getKey());
5262         KeyValueScanner scanner = store.getScanner(scan, entry.getValue(), this.readPt);
5263         if (this.filter == null || !scan.doLoadColumnFamiliesOnDemand()
5264           || this.filter.isFamilyEssential(entry.getKey())) {
5265           scanners.add(scanner);
5266         } else {
5267           joinedScanners.add(scanner);
5268         }
5269       }
5270       initializeKVHeap(scanners, joinedScanners, region);
5271     }
5272 
5273     protected void initializeKVHeap(List<KeyValueScanner> scanners,
5274         List<KeyValueScanner> joinedScanners, HRegion region)
5275         throws IOException {
5276       this.storeHeap = new KeyValueHeap(scanners, region.comparator);
5277       if (!joinedScanners.isEmpty()) {
5278         this.joinedHeap = new KeyValueHeap(joinedScanners, region.comparator);
5279       }
5280     }
5281 
5282     @Override
5283     public long getMaxResultSize() {
5284       return maxResultSize;
5285     }
5286 
5287     @Override
5288     public long getMvccReadPoint() {
5289       return this.readPt;
5290     }
5291 
5292     @Override
5293     public int getBatch() {
5294       return this.defaultScannerContext.getBatchLimit();
5295     }
5296 
5297     /**
5298      * Reset both the filter and the old filter.
5299      *
5300      * @throws IOException in case a filter raises an I/O exception.
5301      */
5302     protected void resetFilters() throws IOException {
5303       if (filter != null) {
5304         filter.reset();
5305       }
5306     }
5307 
5308     @Override
5309     public boolean next(List<Cell> outResults)
5310         throws IOException {
5311       // apply the batching limit by default
5312       return next(outResults, defaultScannerContext);
5313     }
5314 
5315     @Override
5316     public synchronized boolean next(List<Cell> outResults, ScannerContext scannerContext) throws IOException {
5317       if (this.filterClosed) {
5318         throw new UnknownScannerException("Scanner was closed (timed out?) " +
5319             "after we renewed it. Could be caused by a very slow scanner " +
5320             "or a lengthy garbage collection");
5321       }
5322       startRegionOperation(Operation.SCAN);
5323       readRequestsCount.increment();
5324       try {
5325         return nextRaw(outResults, scannerContext);
5326       } finally {
5327         closeRegionOperation(Operation.SCAN);
5328       }
5329     }
5330 
5331     @Override
5332     public boolean nextRaw(List<Cell> outResults) throws IOException {
5333       // Use the RegionScanner's context by default
5334       return nextRaw(outResults, defaultScannerContext);
5335     }
5336 
5337     @Override
5338     public boolean nextRaw(List<Cell> outResults, ScannerContext scannerContext)
5339         throws IOException {
5340       if (storeHeap == null) {
5341         // scanner is closed
5342         throw new UnknownScannerException("Scanner was closed");
5343       }
5344       boolean moreValues;
5345       if (outResults.isEmpty()) {
5346         // Usually outResults is empty. This is true when next is called
5347         // to handle scan or get operation.
5348         moreValues = nextInternal(outResults, scannerContext);
5349       } else {
5350         List<Cell> tmpList = new ArrayList<Cell>();
5351         moreValues = nextInternal(tmpList, scannerContext);
5352         outResults.addAll(tmpList);
5353       }
5354       
5355       // If the size limit was reached it means a partial Result is being returned. Returning a
5356       // partial Result means that we should not reset the filters; filters should only be reset in
5357       // between rows
5358       if (!scannerContext.partialResultFormed()) resetFilters();
5359 
5360       if (isFilterDoneInternal()) {
5361         moreValues = false;
5362       }
5363       return moreValues;
5364     }
5365 
5366     /**
5367      * @return true if more cells exist after this batch, false if scanner is done
5368      */
5369     private boolean populateFromJoinedHeap(List<Cell> results, ScannerContext scannerContext)
5370             throws IOException {
5371       assert joinedContinuationRow != null;
5372       boolean moreValues =
5373           populateResult(results, this.joinedHeap, scannerContext,
5374           joinedContinuationRow.getRowArray(), joinedContinuationRow.getRowOffset(),
5375           joinedContinuationRow.getRowLength());
5376 
5377       if (!scannerContext.checkAnyLimitReached(LimitScope.BETWEEN_CELLS)) {
5378         // We are done with this row, reset the continuation.
5379         joinedContinuationRow = null;
5380       }
5381       // As the data is obtained from two independent heaps, we need to
5382       // ensure that result list is sorted, because Result relies on that.
5383       Collections.sort(results, comparator);
5384       return moreValues;
5385     }
5386 
5387     /**
5388      * Fetches records with currentRow into results list, until next row, batchLimit (if not -1) is
5389      * reached, or remainingResultSize (if not -1) is reaced
5390      * @param heap KeyValueHeap to fetch data from.It must be positioned on correct row before call.
5391      * @param scannerContext
5392      * @param currentRow Byte array with key we are fetching.
5393      * @param offset offset for currentRow
5394      * @param length length for currentRow
5395      * @return state of last call to {@link KeyValueHeap#next()}
5396      */
5397     private boolean populateResult(List<Cell> results, KeyValueHeap heap,
5398         ScannerContext scannerContext, byte[] currentRow, int offset, short length)
5399         throws IOException {
5400       Cell nextKv;
5401       boolean moreCellsInRow = false;
5402       boolean tmpKeepProgress = scannerContext.getKeepProgress();
5403       // Scanning between column families and thus the scope is between cells
5404       LimitScope limitScope = LimitScope.BETWEEN_CELLS;
5405       do {
5406         // We want to maintain any progress that is made towards the limits while scanning across
5407         // different column families. To do this, we toggle the keep progress flag on during calls
5408         // to the StoreScanner to ensure that any progress made thus far is not wiped away.
5409         scannerContext.setKeepProgress(true);
5410         heap.next(results, scannerContext);
5411         scannerContext.setKeepProgress(tmpKeepProgress);
5412 
5413         nextKv = heap.peek();
5414         moreCellsInRow = moreCellsInRow(nextKv, currentRow, offset, length);
5415 
5416         if (scannerContext.checkBatchLimit(limitScope)) {
5417           return scannerContext.setScannerState(NextState.BATCH_LIMIT_REACHED).hasMoreValues();
5418         } else if (scannerContext.checkSizeLimit(limitScope)) {
5419           ScannerContext.NextState state =
5420               moreCellsInRow ? NextState.SIZE_LIMIT_REACHED_MID_ROW : NextState.SIZE_LIMIT_REACHED;
5421           return scannerContext.setScannerState(state).hasMoreValues();
5422         } else if (scannerContext.checkTimeLimit(limitScope)) {
5423           ScannerContext.NextState state =
5424               moreCellsInRow ? NextState.TIME_LIMIT_REACHED_MID_ROW : NextState.TIME_LIMIT_REACHED;
5425           return scannerContext.setScannerState(state).hasMoreValues();
5426         }
5427       } while (moreCellsInRow);
5428 
5429       return nextKv != null;
5430     }
5431 
5432     /**
5433      * Based on the nextKv in the heap, and the current row, decide whether or not there are more
5434      * cells to be read in the heap. If the row of the nextKv in the heap matches the current row
5435      * then there are more cells to be read in the row.
5436      * @param nextKv
5437      * @param currentRow
5438      * @param offset
5439      * @param length
5440      * @return true When there are more cells in the row to be read
5441      */
5442     private boolean moreCellsInRow(final Cell nextKv, byte[] currentRow, int offset,
5443         short length) {
5444       return nextKv != null && CellUtil.matchingRow(nextKv, currentRow, offset, length);
5445     }
5446 
5447     /*
5448      * @return True if a filter rules the scanner is over, done.
5449      */
5450     @Override
5451     public synchronized boolean isFilterDone() throws IOException {
5452       return isFilterDoneInternal();
5453     }
5454 
5455     private boolean isFilterDoneInternal() throws IOException {
5456       return this.filter != null && this.filter.filterAllRemaining();
5457     }
5458 
5459     private boolean nextInternal(List<Cell> results, ScannerContext scannerContext)
5460         throws IOException {
5461       if (!results.isEmpty()) {
5462         throw new IllegalArgumentException("First parameter should be an empty list");
5463       }
5464       if (scannerContext == null) {
5465         throw new IllegalArgumentException("Scanner context cannot be null");
5466       }
5467       RpcCallContext rpcCall = RpcServer.getCurrentCall();
5468 
5469       // Save the initial progress from the Scanner context in these local variables. The progress
5470       // may need to be reset a few times if rows are being filtered out so we save the initial
5471       // progress.
5472       int initialBatchProgress = scannerContext.getBatchProgress();
5473       long initialSizeProgress = scannerContext.getSizeProgress();
5474       long initialTimeProgress = scannerContext.getTimeProgress();
5475 
5476       // The loop here is used only when at some point during the next we determine
5477       // that due to effects of filters or otherwise, we have an empty row in the result.
5478       // Then we loop and try again. Otherwise, we must get out on the first iteration via return,
5479       // "true" if there's more data to read, "false" if there isn't (storeHeap is at a stop row,
5480       // and joinedHeap has no more data to read for the last row (if set, joinedContinuationRow).
5481       while (true) {
5482         // Starting to scan a new row. Reset the scanner progress according to whether or not
5483         // progress should be kept.
5484         if (scannerContext.getKeepProgress()) {
5485           // Progress should be kept. Reset to initial values seen at start of method invocation.
5486           scannerContext
5487               .setProgress(initialBatchProgress, initialSizeProgress, initialTimeProgress);
5488         } else {
5489           scannerContext.clearProgress();
5490         }
5491 
5492         if (rpcCall != null) {
5493           // If a user specifies a too-restrictive or too-slow scanner, the
5494           // client might time out and disconnect while the server side
5495           // is still processing the request. We should abort aggressively
5496           // in that case.
5497           long afterTime = rpcCall.disconnectSince();
5498           if (afterTime >= 0) {
5499             throw new CallerDisconnectedException(
5500                 "Aborting on region " + getRegionInfo().getRegionNameAsString() + ", call " +
5501                     this + " after " + afterTime + " ms, since " +
5502                     "caller disconnected");
5503           }
5504         }
5505 
5506         // Let's see what we have in the storeHeap.
5507         Cell current = this.storeHeap.peek();
5508 
5509         byte[] currentRow = null;
5510         int offset = 0;
5511         short length = 0;
5512         if (current != null) {
5513           currentRow = current.getRowArray();
5514           offset = current.getRowOffset();
5515           length = current.getRowLength();
5516         }
5517 
5518         boolean stopRow = isStopRow(currentRow, offset, length);
5519         // When has filter row is true it means that the all the cells for a particular row must be
5520         // read before a filtering decision can be made. This means that filters where hasFilterRow
5521         // run the risk of encountering out of memory errors in the case that they are applied to a
5522         // table that has very large rows.
5523         boolean hasFilterRow = this.filter != null && this.filter.hasFilterRow();
5524 
5525         // If filter#hasFilterRow is true, partial results are not allowed since allowing them
5526         // would prevent the filters from being evaluated. Thus, if it is true, change the
5527         // scope of any limits that could potentially create partial results to
5528         // LimitScope.BETWEEN_ROWS so that those limits are not reached mid-row
5529         if (hasFilterRow) {
5530           if (LOG.isTraceEnabled()) {
5531             LOG.trace("filter#hasFilterRow is true which prevents partial results from being "
5532                 + " formed. Changing scope of limits that may create partials");
5533           }
5534           scannerContext.setSizeLimitScope(LimitScope.BETWEEN_ROWS);
5535           scannerContext.setTimeLimitScope(LimitScope.BETWEEN_ROWS);
5536         }
5537 
5538         // Check if we were getting data from the joinedHeap and hit the limit.
5539         // If not, then it's main path - getting results from storeHeap.
5540         if (joinedContinuationRow == null) {
5541           // First, check if we are at a stop row. If so, there are no more results.
5542           if (stopRow) {
5543             if (hasFilterRow) {
5544               filter.filterRowCells(results);
5545             }
5546             return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
5547           }
5548 
5549           // Check if rowkey filter wants to exclude this row. If so, loop to next.
5550           // Technically, if we hit limits before on this row, we don't need this call.
5551           if (filterRowKey(currentRow, offset, length)) {
5552             boolean moreRows = nextRow(currentRow, offset, length);
5553             if (!moreRows) {
5554               return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
5555             }
5556             results.clear();
5557             continue;
5558           }
5559 
5560           // Ok, we are good, let's try to get some results from the main heap.
5561           populateResult(results, this.storeHeap, scannerContext, currentRow, offset, length);
5562 
5563           if (scannerContext.checkAnyLimitReached(LimitScope.BETWEEN_CELLS)) {
5564             if (hasFilterRow) {
5565               throw new IncompatibleFilterException(
5566                   "Filter whose hasFilterRow() returns true is incompatible with scans that must "
5567                       + " stop mid-row because of a limit. ScannerContext:" + scannerContext);
5568             }
5569             return true;
5570           }
5571 
5572           Cell nextKv = this.storeHeap.peek();
5573           stopRow = nextKv == null ||
5574               isStopRow(nextKv.getRowArray(), nextKv.getRowOffset(), nextKv.getRowLength());
5575           // save that the row was empty before filters applied to it.
5576           final boolean isEmptyRow = results.isEmpty();
5577 
5578           // We have the part of the row necessary for filtering (all of it, usually).
5579           // First filter with the filterRow(List).
5580           FilterWrapper.FilterRowRetCode ret = FilterWrapper.FilterRowRetCode.NOT_CALLED;
5581           if (hasFilterRow) {
5582             ret = filter.filterRowCellsWithRet(results);
5583 
5584             // We don't know how the results have changed after being filtered. Must set progress
5585             // according to contents of results now. However, a change in the results should not
5586             // affect the time progress. Thus preserve whatever time progress has been made
5587             long timeProgress = scannerContext.getTimeProgress();
5588             if (scannerContext.getKeepProgress()) {
5589               scannerContext.setProgress(initialBatchProgress, initialSizeProgress,
5590                 initialTimeProgress);
5591             } else {
5592               scannerContext.clearProgress();
5593             }
5594             scannerContext.setTimeProgress(timeProgress);
5595             scannerContext.incrementBatchProgress(results.size());
5596             for (Cell cell : results) {
5597               scannerContext.incrementSizeProgress(CellUtil.estimatedHeapSizeOfWithoutTags(cell));
5598             }
5599           }
5600 
5601           if ((isEmptyRow || ret == FilterWrapper.FilterRowRetCode.EXCLUDE) || filterRow()) {
5602             results.clear();
5603             boolean moreRows = nextRow(currentRow, offset, length);
5604             if (!moreRows) {
5605               return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
5606             }
5607 
5608             // This row was totally filtered out, if this is NOT the last row,
5609             // we should continue on. Otherwise, nothing else to do.
5610             if (!stopRow) continue;
5611             return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
5612           }
5613 
5614           // Ok, we are done with storeHeap for this row.
5615           // Now we may need to fetch additional, non-essential data into row.
5616           // These values are not needed for filter to work, so we postpone their
5617           // fetch to (possibly) reduce amount of data loads from disk.
5618           if (this.joinedHeap != null) {
5619             boolean mayHaveData = joinedHeapMayHaveData(currentRow, offset, length);
5620             if (mayHaveData) {
5621               joinedContinuationRow = current;
5622               populateFromJoinedHeap(results, scannerContext);
5623 
5624               if (scannerContext.checkAnyLimitReached(LimitScope.BETWEEN_CELLS)) {
5625                 return true;
5626               }
5627             }
5628           }
5629         } else {
5630           // Populating from the joined heap was stopped by limits, populate some more.
5631           populateFromJoinedHeap(results, scannerContext);
5632           if (scannerContext.checkAnyLimitReached(LimitScope.BETWEEN_CELLS)) {
5633             return true;
5634           }
5635         }
5636         // We may have just called populateFromJoinedMap and hit the limits. If that is
5637         // the case, we need to call it again on the next next() invocation.
5638         if (joinedContinuationRow != null) {
5639           return scannerContext.setScannerState(NextState.MORE_VALUES).hasMoreValues();
5640         }
5641 
5642         // Finally, we are done with both joinedHeap and storeHeap.
5643         // Double check to prevent empty rows from appearing in result. It could be
5644         // the case when SingleColumnValueExcludeFilter is used.
5645         if (results.isEmpty()) {
5646           boolean moreRows = nextRow(currentRow, offset, length);
5647           if (!moreRows) {
5648             return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
5649           }
5650           if (!stopRow) continue;
5651         }
5652 
5653         // We are done. Return the result.
5654         if (stopRow) {
5655           return scannerContext.setScannerState(NextState.NO_MORE_VALUES).hasMoreValues();
5656         } else {
5657           return scannerContext.setScannerState(NextState.MORE_VALUES).hasMoreValues();
5658         }
5659       }
5660     }
5661 
5662     /**
5663      * @param currentRow
5664      * @param offset
5665      * @param length
5666      * @return true when the joined heap may have data for the current row
5667      * @throws IOException
5668      */
5669     private boolean joinedHeapMayHaveData(byte[] currentRow, int offset, short length)
5670         throws IOException {
5671       Cell nextJoinedKv = joinedHeap.peek();
5672       boolean matchCurrentRow =
5673           nextJoinedKv != null && CellUtil.matchingRow(nextJoinedKv, currentRow, offset, length);
5674       boolean matchAfterSeek = false;
5675 
5676       // If the next value in the joined heap does not match the current row, try to seek to the
5677       // correct row
5678       if (!matchCurrentRow) {
5679         Cell firstOnCurrentRow = KeyValueUtil.createFirstOnRow(currentRow, offset, length);
5680         boolean seekSuccessful = this.joinedHeap.requestSeek(firstOnCurrentRow, true, true);
5681         matchAfterSeek =
5682             seekSuccessful && joinedHeap.peek() != null
5683                 && CellUtil.matchingRow(joinedHeap.peek(), currentRow, offset, length);
5684       }
5685 
5686       return matchCurrentRow || matchAfterSeek;
5687     }
5688 
5689     /**
5690      * This function is to maintain backward compatibility for 0.94 filters. HBASE-6429 combines
5691      * both filterRow & filterRow(List<KeyValue> kvs) functions. While 0.94 code or older, it may
5692      * not implement hasFilterRow as HBase-6429 expects because 0.94 hasFilterRow() only returns
5693      * true when filterRow(List<KeyValue> kvs) is overridden not the filterRow(). Therefore, the
5694      * filterRow() will be skipped.
5695      */
5696     private boolean filterRow() throws IOException {
5697       // when hasFilterRow returns true, filter.filterRow() will be called automatically inside
5698       // filterRowCells(List<Cell> kvs) so we skip that scenario here.
5699       return filter != null && (!filter.hasFilterRow())
5700           && filter.filterRow();
5701     }
5702 
5703     private boolean filterRowKey(byte[] row, int offset, short length) throws IOException {
5704       return filter != null
5705           && filter.filterRowKey(row, offset, length);
5706     }
5707 
5708     protected boolean nextRow(byte [] currentRow, int offset, short length) throws IOException {
5709       assert this.joinedContinuationRow == null: "Trying to go to next row during joinedHeap read.";
5710       Cell next;
5711       while ((next = this.storeHeap.peek()) != null &&
5712              CellUtil.matchingRow(next, currentRow, offset, length)) {
5713         this.storeHeap.next(MOCKED_LIST);
5714       }
5715       resetFilters();
5716       // Calling the hook in CP which allows it to do a fast forward
5717       return this.region.getCoprocessorHost() == null
5718           || this.region.getCoprocessorHost()
5719               .postScannerFilterRow(this, currentRow, offset, length);
5720     }
5721 
5722     protected boolean isStopRow(byte[] currentRow, int offset, short length) {
5723       return currentRow == null ||
5724           (stopRow != null &&
5725           comparator.compareRows(stopRow, 0, stopRow.length,
5726             currentRow, offset, length) <= isScan);
5727     }
5728 
5729     @Override
5730     public synchronized void close() {
5731       if (storeHeap != null) {
5732         storeHeap.close();
5733         storeHeap = null;
5734       }
5735       if (joinedHeap != null) {
5736         joinedHeap.close();
5737         joinedHeap = null;
5738       }
5739       // no need to synchronize here.
5740       scannerReadPoints.remove(this);
5741       this.filterClosed = true;
5742     }
5743 
5744     KeyValueHeap getStoreHeapForTesting() {
5745       return storeHeap;
5746     }
5747 
5748     @Override
5749     public synchronized boolean reseek(byte[] row) throws IOException {
5750       if (row == null) {
5751         throw new IllegalArgumentException("Row cannot be null.");
5752       }
5753       boolean result = false;
5754       startRegionOperation();
5755       try {
5756         KeyValue kv = KeyValueUtil.createFirstOnRow(row);
5757         // use request seek to make use of the lazy seek option. See HBASE-5520
5758         result = this.storeHeap.requestSeek(kv, true, true);
5759         if (this.joinedHeap != null) {
5760           result = this.joinedHeap.requestSeek(kv, true, true) || result;
5761         }
5762       } finally {
5763         closeRegionOperation();
5764       }
5765       return result;
5766     }
5767   }
5768 
5769   // Utility methods
5770   /**
5771    * A utility method to create new instances of HRegion based on the
5772    * {@link HConstants#REGION_IMPL} configuration property.
5773    * @param tableDir qualified path of directory where region should be located,
5774    * usually the table directory.
5775    * @param wal The WAL is the outbound log for any updates to the HRegion
5776    * The wal file is a logfile from the previous execution that's
5777    * custom-computed for this HRegion. The HRegionServer computes and sorts the
5778    * appropriate wal info for this HRegion. If there is a previous file
5779    * (implying that the HRegion has been written-to before), then read it from
5780    * the supplied path.
5781    * @param fs is the filesystem.
5782    * @param conf is global configuration settings.
5783    * @param regionInfo - HRegionInfo that describes the region
5784    * is new), then read them from the supplied path.
5785    * @param htd the table descriptor
5786    * @return the new instance
5787    */
5788   static HRegion newHRegion(Path tableDir, WAL wal, FileSystem fs,
5789       Configuration conf, HRegionInfo regionInfo, final HTableDescriptor htd,
5790       RegionServerServices rsServices) {
5791     try {
5792       @SuppressWarnings("unchecked")
5793       Class<? extends HRegion> regionClass =
5794           (Class<? extends HRegion>) conf.getClass(HConstants.REGION_IMPL, HRegion.class);
5795 
5796       Constructor<? extends HRegion> c =
5797           regionClass.getConstructor(Path.class, WAL.class, FileSystem.class,
5798               Configuration.class, HRegionInfo.class, HTableDescriptor.class,
5799               RegionServerServices.class);
5800 
5801       return c.newInstance(tableDir, wal, fs, conf, regionInfo, htd, rsServices);
5802     } catch (Throwable e) {
5803       // todo: what should I throw here?
5804       throw new IllegalStateException("Could not instantiate a region instance.", e);
5805     }
5806   }
5807 
5808   /**
5809    * Convenience method creating new HRegions. Used by createTable and by the
5810    * bootstrap code in the HMaster constructor.
5811    * Note, this method creates an {@link WAL} for the created region. It
5812    * needs to be closed explicitly.  Use {@link HRegion#getWAL()} to get
5813    * access.  <b>When done with a region created using this method, you will
5814    * need to explicitly close the {@link WAL} it created too; it will not be
5815    * done for you.  Not closing the wal will leave at least a daemon thread
5816    * running.</b>  Call {@link #closeHRegion(HRegion)} and it will do
5817    * necessary cleanup for you.
5818    * @param info Info for region to create.
5819    * @param rootDir Root directory for HBase instance
5820    * @return new HRegion
5821    *
5822    * @throws IOException
5823    */
5824   public static HRegion createHRegion(final HRegionInfo info, final Path rootDir,
5825       final Configuration conf, final HTableDescriptor hTableDescriptor)
5826   throws IOException {
5827     return createHRegion(info, rootDir, conf, hTableDescriptor, null);
5828   }
5829 
5830   /**
5831    * This will do the necessary cleanup a call to
5832    * {@link #createHRegion(HRegionInfo, Path, Configuration, HTableDescriptor)}
5833    * requires.  This method will close the region and then close its
5834    * associated {@link WAL} file.  You can still use it if you call the other createHRegion,
5835    * the one that takes an {@link WAL} instance but don't be surprised by the
5836    * call to the {@link WAL#close()} on the {@link WAL} the
5837    * HRegion was carrying.
5838    * @throws IOException
5839    */
5840   public static void closeHRegion(final HRegion r) throws IOException {
5841     if (r == null) return;
5842     r.close();
5843     if (r.getWAL() == null) return;
5844     r.getWAL().close();
5845   }
5846 
5847   /**
5848    * Convenience method creating new HRegions. Used by createTable.
5849    * The {@link WAL} for the created region needs to be closed explicitly.
5850    * Use {@link HRegion#getWAL()} to get access.
5851    *
5852    * @param info Info for region to create.
5853    * @param rootDir Root directory for HBase instance
5854    * @param wal shared WAL
5855    * @param initialize - true to initialize the region
5856    * @return new HRegion
5857    *
5858    * @throws IOException
5859    */
5860   public static HRegion createHRegion(final HRegionInfo info, final Path rootDir,
5861                                       final Configuration conf,
5862                                       final HTableDescriptor hTableDescriptor,
5863                                       final WAL wal,
5864                                       final boolean initialize)
5865       throws IOException {
5866     return createHRegion(info, rootDir, conf, hTableDescriptor,
5867         wal, initialize, false);
5868   }
5869 
5870   /**
5871    * Convenience method creating new HRegions. Used by createTable.
5872    * The {@link WAL} for the created region needs to be closed
5873    * explicitly, if it is not null.
5874    * Use {@link HRegion#getWAL()} to get access.
5875    *
5876    * @param info Info for region to create.
5877    * @param rootDir Root directory for HBase instance
5878    * @param wal shared WAL
5879    * @param initialize - true to initialize the region
5880    * @param ignoreWAL - true to skip generate new wal if it is null, mostly for createTable
5881    * @return new HRegion
5882    * @throws IOException
5883    */
5884   public static HRegion createHRegion(final HRegionInfo info, final Path rootDir,
5885                                       final Configuration conf,
5886                                       final HTableDescriptor hTableDescriptor,
5887                                       final WAL wal,
5888                                       final boolean initialize, final boolean ignoreWAL)
5889       throws IOException {
5890       Path tableDir = FSUtils.getTableDir(rootDir, info.getTable());
5891       return createHRegion(info, rootDir, tableDir, conf, hTableDescriptor, wal, initialize,
5892           ignoreWAL);
5893   }
5894 
5895   /**
5896    * Convenience method creating new HRegions. Used by createTable.
5897    * The {@link WAL} for the created region needs to be closed
5898    * explicitly, if it is not null.
5899    * Use {@link HRegion#getWAL()} to get access.
5900    *
5901    * @param info Info for region to create.
5902    * @param rootDir Root directory for HBase instance
5903    * @param tableDir table directory
5904    * @param wal shared WAL
5905    * @param initialize - true to initialize the region
5906    * @param ignoreWAL - true to skip generate new wal if it is null, mostly for createTable
5907    * @return new HRegion
5908    * @throws IOException
5909    */
5910   public static HRegion createHRegion(final HRegionInfo info, final Path rootDir, final Path tableDir,
5911                                       final Configuration conf,
5912                                       final HTableDescriptor hTableDescriptor,
5913                                       final WAL wal,
5914                                       final boolean initialize, final boolean ignoreWAL)
5915       throws IOException {
5916     LOG.info("creating HRegion " + info.getTable().getNameAsString()
5917         + " HTD == " + hTableDescriptor + " RootDir = " + rootDir +
5918         " Table name == " + info.getTable().getNameAsString());
5919     FileSystem fs = FileSystem.get(conf);
5920     HRegionFileSystem.createRegionOnFileSystem(conf, fs, tableDir, info);
5921     WAL effectiveWAL = wal;
5922     if (wal == null && !ignoreWAL) {
5923       // TODO HBASE-11983 There'll be no roller for this wal?
5924       // The WAL subsystem will use the default rootDir rather than the passed in rootDir
5925       // unless I pass along via the conf.
5926       Configuration confForWAL = new Configuration(conf);
5927       confForWAL.set(HConstants.HBASE_DIR, rootDir.toString());
5928       effectiveWAL = (new WALFactory(confForWAL,
5929           Collections.<WALActionsListener>singletonList(new MetricsWAL()),
5930           "hregion-" + RandomStringUtils.randomNumeric(8))).
5931             getWAL(info.getEncodedNameAsBytes());
5932     }
5933     HRegion region = HRegion.newHRegion(tableDir,
5934         effectiveWAL, fs, conf, info, hTableDescriptor, null);
5935     if (initialize) {
5936       // If initializing, set the sequenceId. It is also required by WALPerformanceEvaluation when
5937       // verifying the WALEdits.
5938       region.setSequenceId(region.initialize(null));
5939     }
5940     return region;
5941   }
5942 
5943   public static HRegion createHRegion(final HRegionInfo info, final Path rootDir,
5944                                       final Configuration conf,
5945                                       final HTableDescriptor hTableDescriptor,
5946                                       final WAL wal)
5947     throws IOException {
5948     return createHRegion(info, rootDir, conf, hTableDescriptor, wal, true);
5949   }
5950 
5951 
5952   /**
5953    * Open a Region.
5954    * @param info Info for region to be opened.
5955    * @param wal WAL for region to use. This method will call
5956    * WAL#setSequenceNumber(long) passing the result of the call to
5957    * HRegion#getMinSequenceId() to ensure the wal id is properly kept
5958    * up.  HRegionStore does this every time it opens a new region.
5959    * @return new HRegion
5960    *
5961    * @throws IOException
5962    */
5963   public static HRegion openHRegion(final HRegionInfo info,
5964       final HTableDescriptor htd, final WAL wal,
5965       final Configuration conf)
5966   throws IOException {
5967     return openHRegion(info, htd, wal, conf, null, null);
5968   }
5969 
5970   /**
5971    * Open a Region.
5972    * @param info Info for region to be opened
5973    * @param htd the table descriptor
5974    * @param wal WAL for region to use. This method will call
5975    * WAL#setSequenceNumber(long) passing the result of the call to
5976    * HRegion#getMinSequenceId() to ensure the wal id is properly kept
5977    * up.  HRegionStore does this every time it opens a new region.
5978    * @param conf The Configuration object to use.
5979    * @param rsServices An interface we can request flushes against.
5980    * @param reporter An interface we can report progress against.
5981    * @return new HRegion
5982    *
5983    * @throws IOException
5984    */
5985   public static HRegion openHRegion(final HRegionInfo info,
5986     final HTableDescriptor htd, final WAL wal, final Configuration conf,
5987     final RegionServerServices rsServices,
5988     final CancelableProgressable reporter)
5989   throws IOException {
5990     return openHRegion(FSUtils.getRootDir(conf), info, htd, wal, conf, rsServices, reporter);
5991   }
5992 
5993   /**
5994    * Open a Region.
5995    * @param rootDir Root directory for HBase instance
5996    * @param info Info for region to be opened.
5997    * @param htd the table descriptor
5998    * @param wal WAL for region to use. This method will call
5999    * WAL#setSequenceNumber(long) passing the result of the call to
6000    * HRegion#getMinSequenceId() to ensure the wal id is properly kept
6001    * up.  HRegionStore does this every time it opens a new region.
6002    * @param conf The Configuration object to use.
6003    * @return new HRegion
6004    * @throws IOException
6005    */
6006   public static HRegion openHRegion(Path rootDir, final HRegionInfo info,
6007       final HTableDescriptor htd, final WAL wal, final Configuration conf)
6008   throws IOException {
6009     return openHRegion(rootDir, info, htd, wal, conf, null, null);
6010   }
6011 
6012   /**
6013    * Open a Region.
6014    * @param rootDir Root directory for HBase instance
6015    * @param info Info for region to be opened.
6016    * @param htd the table descriptor
6017    * @param wal WAL for region to use. This method will call
6018    * WAL#setSequenceNumber(long) passing the result of the call to
6019    * HRegion#getMinSequenceId() to ensure the wal id is properly kept
6020    * up.  HRegionStore does this every time it opens a new region.
6021    * @param conf The Configuration object to use.
6022    * @param rsServices An interface we can request flushes against.
6023    * @param reporter An interface we can report progress against.
6024    * @return new HRegion
6025    * @throws IOException
6026    */
6027   public static HRegion openHRegion(final Path rootDir, final HRegionInfo info,
6028       final HTableDescriptor htd, final WAL wal, final Configuration conf,
6029       final RegionServerServices rsServices,
6030       final CancelableProgressable reporter)
6031   throws IOException {
6032     FileSystem fs = null;
6033     if (rsServices != null) {
6034       fs = rsServices.getFileSystem();
6035     }
6036     if (fs == null) {
6037       fs = FileSystem.get(conf);
6038     }
6039     return openHRegion(conf, fs, rootDir, info, htd, wal, rsServices, reporter);
6040   }
6041 
6042   /**
6043    * Open a Region.
6044    * @param conf The Configuration object to use.
6045    * @param fs Filesystem to use
6046    * @param rootDir Root directory for HBase instance
6047    * @param info Info for region to be opened.
6048    * @param htd the table descriptor
6049    * @param wal WAL for region to use. This method will call
6050    * WAL#setSequenceNumber(long) passing the result of the call to
6051    * HRegion#getMinSequenceId() to ensure the wal id is properly kept
6052    * up.  HRegionStore does this every time it opens a new region.
6053    * @return new HRegion
6054    * @throws IOException
6055    */
6056   public static HRegion openHRegion(final Configuration conf, final FileSystem fs,
6057       final Path rootDir, final HRegionInfo info, final HTableDescriptor htd, final WAL wal)
6058       throws IOException {
6059     return openHRegion(conf, fs, rootDir, info, htd, wal, null, null);
6060   }
6061 
6062   /**
6063    * Open a Region.
6064    * @param conf The Configuration object to use.
6065    * @param fs Filesystem to use
6066    * @param rootDir Root directory for HBase instance
6067    * @param info Info for region to be opened.
6068    * @param htd the table descriptor
6069    * @param wal WAL for region to use. This method will call
6070    * WAL#setSequenceNumber(long) passing the result of the call to
6071    * HRegion#getMinSequenceId() to ensure the wal id is properly kept
6072    * up.  HRegionStore does this every time it opens a new region.
6073    * @param rsServices An interface we can request flushes against.
6074    * @param reporter An interface we can report progress against.
6075    * @return new HRegion
6076    * @throws IOException
6077    */
6078   public static HRegion openHRegion(final Configuration conf, final FileSystem fs,
6079       final Path rootDir, final HRegionInfo info, final HTableDescriptor htd, final WAL wal,
6080       final RegionServerServices rsServices, final CancelableProgressable reporter)
6081       throws IOException {
6082     Path tableDir = FSUtils.getTableDir(rootDir, info.getTable());
6083     return openHRegion(conf, fs, rootDir, tableDir, info, htd, wal, rsServices, reporter);
6084   }
6085 
6086   /**
6087    * Open a Region.
6088    * @param conf The Configuration object to use.
6089    * @param fs Filesystem to use
6090    * @param rootDir Root directory for HBase instance
6091    * @param info Info for region to be opened.
6092    * @param htd the table descriptor
6093    * @param wal WAL for region to use. This method will call
6094    * WAL#setSequenceNumber(long) passing the result of the call to
6095    * HRegion#getMinSequenceId() to ensure the wal id is properly kept
6096    * up.  HRegionStore does this every time it opens a new region.
6097    * @param rsServices An interface we can request flushes against.
6098    * @param reporter An interface we can report progress against.
6099    * @return new HRegion
6100    * @throws IOException
6101    */
6102   public static HRegion openHRegion(final Configuration conf, final FileSystem fs,
6103       final Path rootDir, final Path tableDir, final HRegionInfo info, final HTableDescriptor htd,
6104       final WAL wal, final RegionServerServices rsServices,
6105       final CancelableProgressable reporter)
6106       throws IOException {
6107     if (info == null) throw new NullPointerException("Passed region info is null");
6108     if (LOG.isDebugEnabled()) {
6109       LOG.debug("Opening region: " + info);
6110     }
6111     HRegion r = HRegion.newHRegion(tableDir, wal, fs, conf, info, htd, rsServices);
6112     return r.openHRegion(reporter);
6113   }
6114 
6115 
6116   /**
6117    * Useful when reopening a closed region (normally for unit tests)
6118    * @param other original object
6119    * @param reporter An interface we can report progress against.
6120    * @return new HRegion
6121    * @throws IOException
6122    */
6123   public static HRegion openHRegion(final HRegion other, final CancelableProgressable reporter)
6124       throws IOException {
6125     HRegionFileSystem regionFs = other.getRegionFileSystem();
6126     HRegion r = newHRegion(regionFs.getTableDir(), other.getWAL(), regionFs.getFileSystem(),
6127         other.baseConf, other.getRegionInfo(), other.getTableDesc(), null);
6128     return r.openHRegion(reporter);
6129   }
6130 
6131   public static Region openHRegion(final Region other, final CancelableProgressable reporter)
6132         throws IOException {
6133     return openHRegion((HRegion)other, reporter);
6134   }
6135 
6136   /**
6137    * Open HRegion.
6138    * Calls initialize and sets sequenceId.
6139    * @return Returns <code>this</code>
6140    * @throws IOException
6141    */
6142   protected HRegion openHRegion(final CancelableProgressable reporter)
6143   throws IOException {
6144     // Refuse to open the region if we are missing local compression support
6145     checkCompressionCodecs();
6146     // Refuse to open the region if encryption configuration is incorrect or
6147     // codec support is missing
6148     checkEncryption();
6149     // Refuse to open the region if a required class cannot be loaded
6150     checkClassLoading();
6151     this.openSeqNum = initialize(reporter);
6152     this.setSequenceId(openSeqNum);
6153     if (wal != null && getRegionServerServices() != null && !writestate.readOnly
6154         && !isRecovering) {
6155       // Only write the region open event marker to WAL if (1) we are not read-only
6156       // (2) dist log replay is off or we are not recovering. In case region is
6157       // recovering, the open event will be written at setRecovering(false)
6158       writeRegionOpenMarker(wal, openSeqNum);
6159     }
6160     return this;
6161   }
6162 
6163   public static void warmupHRegion(final HRegionInfo info,
6164       final HTableDescriptor htd, final WAL wal, final Configuration conf,
6165       final RegionServerServices rsServices,
6166       final CancelableProgressable reporter)
6167       throws IOException {
6168 
6169     if (info == null) throw new NullPointerException("Passed region info is null");
6170 
6171     if (LOG.isDebugEnabled()) {
6172       LOG.debug("HRegion.Warming up region: " + info);
6173     }
6174 
6175     Path rootDir = FSUtils.getRootDir(conf);
6176     Path tableDir = FSUtils.getTableDir(rootDir, info.getTable());
6177 
6178     FileSystem fs = null;
6179     if (rsServices != null) {
6180       fs = rsServices.getFileSystem();
6181     }
6182     if (fs == null) {
6183       fs = FileSystem.get(conf);
6184     }
6185 
6186     HRegion r = HRegion.newHRegion(tableDir, wal, fs, conf, info, htd, rsServices);
6187     r.initializeWarmup(reporter);
6188     r.close();
6189   }
6190 
6191 
6192   private void checkCompressionCodecs() throws IOException {
6193     for (HColumnDescriptor fam: this.htableDescriptor.getColumnFamilies()) {
6194       CompressionTest.testCompression(fam.getCompression());
6195       CompressionTest.testCompression(fam.getCompactionCompression());
6196     }
6197   }
6198 
6199   private void checkEncryption() throws IOException {
6200     for (HColumnDescriptor fam: this.htableDescriptor.getColumnFamilies()) {
6201       EncryptionTest.testEncryption(conf, fam.getEncryptionType(), fam.getEncryptionKey());
6202     }
6203   }
6204 
6205   private void checkClassLoading() throws IOException {
6206     RegionSplitPolicy.getSplitPolicyClass(this.htableDescriptor, conf);
6207     RegionCoprocessorHost.testTableCoprocessorAttrs(conf, this.htableDescriptor);
6208   }
6209 
6210   /**
6211    * Create a daughter region from given a temp directory with the region data.
6212    * @param hri Spec. for daughter region to open.
6213    * @throws IOException
6214    */
6215   HRegion createDaughterRegionFromSplits(final HRegionInfo hri) throws IOException {
6216     // Move the files from the temporary .splits to the final /table/region directory
6217     fs.commitDaughterRegion(hri);
6218 
6219     // Create the daughter HRegion instance
6220     HRegion r = HRegion.newHRegion(this.fs.getTableDir(), this.getWAL(), fs.getFileSystem(),
6221         this.getBaseConf(), hri, this.getTableDesc(), rsServices);
6222     r.readRequestsCount.set(this.getReadRequestsCount() / 2);
6223     r.writeRequestsCount.set(this.getWriteRequestsCount() / 2);
6224     return r;
6225   }
6226 
6227   /**
6228    * Create a merged region given a temp directory with the region data.
6229    * @param region_b another merging region
6230    * @return merged HRegion
6231    * @throws IOException
6232    */
6233   HRegion createMergedRegionFromMerges(final HRegionInfo mergedRegionInfo,
6234       final HRegion region_b) throws IOException {
6235     HRegion r = HRegion.newHRegion(this.fs.getTableDir(), this.getWAL(),
6236         fs.getFileSystem(), this.getBaseConf(), mergedRegionInfo,
6237         this.getTableDesc(), this.rsServices);
6238     r.readRequestsCount.set(this.getReadRequestsCount()
6239         + region_b.getReadRequestsCount());
6240     r.writeRequestsCount.set(this.getWriteRequestsCount()
6241 
6242         + region_b.getWriteRequestsCount());
6243     this.fs.commitMergedRegion(mergedRegionInfo);
6244     return r;
6245   }
6246 
6247   /**
6248    * Inserts a new region's meta information into the passed
6249    * <code>meta</code> region. Used by the HMaster bootstrap code adding
6250    * new table to hbase:meta table.
6251    *
6252    * @param meta hbase:meta HRegion to be updated
6253    * @param r HRegion to add to <code>meta</code>
6254    *
6255    * @throws IOException
6256    */
6257   // TODO remove since only test and merge use this
6258   public static void addRegionToMETA(final HRegion meta, final HRegion r) throws IOException {
6259     meta.checkResources();
6260     // The row key is the region name
6261     byte[] row = r.getRegionInfo().getRegionName();
6262     final long now = EnvironmentEdgeManager.currentTime();
6263     final List<Cell> cells = new ArrayList<Cell>(2);
6264     cells.add(new KeyValue(row, HConstants.CATALOG_FAMILY,
6265       HConstants.REGIONINFO_QUALIFIER, now,
6266       r.getRegionInfo().toByteArray()));
6267     // Set into the root table the version of the meta table.
6268     cells.add(new KeyValue(row, HConstants.CATALOG_FAMILY,
6269       HConstants.META_VERSION_QUALIFIER, now,
6270       Bytes.toBytes(HConstants.META_VERSION)));
6271     meta.put(row, HConstants.CATALOG_FAMILY, cells);
6272   }
6273 
6274   /**
6275    * Computes the Path of the HRegion
6276    *
6277    * @param tabledir qualified path for table
6278    * @param name ENCODED region name
6279    * @return Path of HRegion directory
6280    */
6281   @Deprecated
6282   public static Path getRegionDir(final Path tabledir, final String name) {
6283     return new Path(tabledir, name);
6284   }
6285 
6286   /**
6287    * Computes the Path of the HRegion
6288    *
6289    * @param rootdir qualified path of HBase root directory
6290    * @param info HRegionInfo for the region
6291    * @return qualified path of region directory
6292    */
6293   @Deprecated
6294   @VisibleForTesting
6295   public static Path getRegionDir(final Path rootdir, final HRegionInfo info) {
6296     return new Path(
6297       FSUtils.getTableDir(rootdir, info.getTable()), info.getEncodedName());
6298   }
6299 
6300   /**
6301    * Determines if the specified row is within the row range specified by the
6302    * specified HRegionInfo
6303    *
6304    * @param info HRegionInfo that specifies the row range
6305    * @param row row to be checked
6306    * @return true if the row is within the range specified by the HRegionInfo
6307    */
6308   public static boolean rowIsInRange(HRegionInfo info, final byte [] row) {
6309     return ((info.getStartKey().length == 0) ||
6310         (Bytes.compareTo(info.getStartKey(), row) <= 0)) &&
6311         ((info.getEndKey().length == 0) ||
6312             (Bytes.compareTo(info.getEndKey(), row) > 0));
6313   }
6314 
6315   /**
6316    * Merge two HRegions.  The regions must be adjacent and must not overlap.
6317    *
6318    * @return new merged HRegion
6319    * @throws IOException
6320    */
6321   public static HRegion mergeAdjacent(final HRegion srcA, final HRegion srcB)
6322   throws IOException {
6323     HRegion a = srcA;
6324     HRegion b = srcB;
6325 
6326     // Make sure that srcA comes first; important for key-ordering during
6327     // write of the merged file.
6328     if (srcA.getRegionInfo().getStartKey() == null) {
6329       if (srcB.getRegionInfo().getStartKey() == null) {
6330         throw new IOException("Cannot merge two regions with null start key");
6331       }
6332       // A's start key is null but B's isn't. Assume A comes before B
6333     } else if ((srcB.getRegionInfo().getStartKey() == null) ||
6334       (Bytes.compareTo(srcA.getRegionInfo().getStartKey(),
6335         srcB.getRegionInfo().getStartKey()) > 0)) {
6336       a = srcB;
6337       b = srcA;
6338     }
6339 
6340     if (!(Bytes.compareTo(a.getRegionInfo().getEndKey(),
6341         b.getRegionInfo().getStartKey()) == 0)) {
6342       throw new IOException("Cannot merge non-adjacent regions");
6343     }
6344     return merge(a, b);
6345   }
6346 
6347   /**
6348    * Merge two regions whether they are adjacent or not.
6349    *
6350    * @param a region a
6351    * @param b region b
6352    * @return new merged region
6353    * @throws IOException
6354    */
6355   public static HRegion merge(final HRegion a, final HRegion b) throws IOException {
6356     if (!a.getRegionInfo().getTable().equals(b.getRegionInfo().getTable())) {
6357       throw new IOException("Regions do not belong to the same table");
6358     }
6359 
6360     FileSystem fs = a.getRegionFileSystem().getFileSystem();
6361     // Make sure each region's cache is empty
6362     a.flush(true);
6363     b.flush(true);
6364 
6365     // Compact each region so we only have one store file per family
6366     a.compact(true);
6367     if (LOG.isDebugEnabled()) {
6368       LOG.debug("Files for region: " + a);
6369       a.getRegionFileSystem().logFileSystemState(LOG);
6370     }
6371     b.compact(true);
6372     if (LOG.isDebugEnabled()) {
6373       LOG.debug("Files for region: " + b);
6374       b.getRegionFileSystem().logFileSystemState(LOG);
6375     }
6376 
6377     RegionMergeTransactionImpl rmt = new RegionMergeTransactionImpl(a, b, true);
6378     if (!rmt.prepare(null)) {
6379       throw new IOException("Unable to merge regions " + a + " and " + b);
6380     }
6381     HRegionInfo mergedRegionInfo = rmt.getMergedRegionInfo();
6382     LOG.info("starting merge of regions: " + a + " and " + b
6383         + " into new region " + mergedRegionInfo.getRegionNameAsString()
6384         + " with start key <"
6385         + Bytes.toStringBinary(mergedRegionInfo.getStartKey())
6386         + "> and end key <"
6387         + Bytes.toStringBinary(mergedRegionInfo.getEndKey()) + ">");
6388     HRegion dstRegion;
6389     try {
6390       dstRegion = (HRegion)rmt.execute(null, null);
6391     } catch (IOException ioe) {
6392       rmt.rollback(null, null);
6393       throw new IOException("Failed merging region " + a + " and " + b
6394           + ", and successfully rolled back");
6395     }
6396     dstRegion.compact(true);
6397 
6398     if (LOG.isDebugEnabled()) {
6399       LOG.debug("Files for new region");
6400       dstRegion.getRegionFileSystem().logFileSystemState(LOG);
6401     }
6402 
6403     if (dstRegion.getRegionFileSystem().hasReferences(dstRegion.getTableDesc())) {
6404       throw new IOException("Merged region " + dstRegion
6405           + " still has references after the compaction, is compaction canceled?");
6406     }
6407 
6408     // Archiving the 'A' region
6409     HFileArchiver.archiveRegion(a.getBaseConf(), fs, a.getRegionInfo());
6410     // Archiving the 'B' region
6411     HFileArchiver.archiveRegion(b.getBaseConf(), fs, b.getRegionInfo());
6412 
6413     LOG.info("merge completed. New region is " + dstRegion);
6414     return dstRegion;
6415   }
6416 
6417   @Override
6418   public Result get(final Get get) throws IOException {
6419     checkRow(get.getRow(), "Get");
6420     // Verify families are all valid
6421     if (get.hasFamilies()) {
6422       for (byte [] family: get.familySet()) {
6423         checkFamily(family);
6424       }
6425     } else { // Adding all families to scanner
6426       for (byte[] family: this.htableDescriptor.getFamiliesKeys()) {
6427         get.addFamily(family);
6428       }
6429     }
6430     List<Cell> results = get(get, true);
6431     boolean stale = this.getRegionInfo().getReplicaId() != 0;
6432     return Result.create(results, get.isCheckExistenceOnly() ? !results.isEmpty() : null, stale);
6433   }
6434 
6435   @Override
6436   public List<Cell> get(Get get, boolean withCoprocessor) throws IOException {
6437 
6438     List<Cell> results = new ArrayList<Cell>();
6439 
6440     // pre-get CP hook
6441     if (withCoprocessor && (coprocessorHost != null)) {
6442        if (coprocessorHost.preGet(get, results)) {
6443          return results;
6444        }
6445     }
6446 
6447     Scan scan = new Scan(get);
6448 
6449     RegionScanner scanner = null;
6450     try {
6451       scanner = getScanner(scan);
6452       scanner.next(results);
6453     } finally {
6454       if (scanner != null)
6455         scanner.close();
6456     }
6457 
6458     // post-get CP hook
6459     if (withCoprocessor && (coprocessorHost != null)) {
6460       coprocessorHost.postGet(get, results);
6461     }
6462 
6463     // do after lock
6464     if (this.metricsRegion != null) {
6465       long totalSize = 0L;
6466       for (Cell cell : results) {
6467         totalSize += CellUtil.estimatedSerializedSizeOf(cell);
6468       }
6469       this.metricsRegion.updateGet(totalSize);
6470     }
6471 
6472     return results;
6473   }
6474 
6475   public void mutateRow(RowMutations rm) throws IOException {
6476     // Don't need nonces here - RowMutations only supports puts and deletes
6477     mutateRowsWithLocks(rm.getMutations(), Collections.singleton(rm.getRow()));
6478   }
6479 
6480   /**
6481    * Perform atomic mutations within the region w/o nonces.
6482    * See {@link #mutateRowsWithLocks(Collection, Collection, long, long)}
6483    */
6484   public void mutateRowsWithLocks(Collection<Mutation> mutations,
6485       Collection<byte[]> rowsToLock) throws IOException {
6486     mutateRowsWithLocks(mutations, rowsToLock, HConstants.NO_NONCE, HConstants.NO_NONCE);
6487   }
6488 
6489   /**
6490    * Perform atomic mutations within the region.
6491    * @param mutations The list of mutations to perform.
6492    * <code>mutations</code> can contain operations for multiple rows.
6493    * Caller has to ensure that all rows are contained in this region.
6494    * @param rowsToLock Rows to lock
6495    * @param nonceGroup Optional nonce group of the operation (client Id)
6496    * @param nonce Optional nonce of the operation (unique random id to ensure "more idempotence")
6497    * If multiple rows are locked care should be taken that
6498    * <code>rowsToLock</code> is sorted in order to avoid deadlocks.
6499    * @throws IOException
6500    */
6501   public void mutateRowsWithLocks(Collection<Mutation> mutations,
6502       Collection<byte[]> rowsToLock, long nonceGroup, long nonce) throws IOException {
6503     MultiRowMutationProcessor proc = new MultiRowMutationProcessor(mutations, rowsToLock);
6504     processRowsWithLocks(proc, -1, nonceGroup, nonce);
6505   }
6506 
6507   /**
6508    * @return the current load statistics for the the region
6509    */
6510   public ClientProtos.RegionLoadStats getRegionStats() {
6511     if (!regionStatsEnabled) {
6512       return null;
6513     }
6514     ClientProtos.RegionLoadStats.Builder stats = ClientProtos.RegionLoadStats.newBuilder();
6515     stats.setMemstoreLoad((int) (Math.min(100, (this.memstoreSize.get() * 100) / this
6516         .memstoreFlushSize)));
6517     stats.setHeapOccupancy((int)rsServices.getHeapMemoryManager().getHeapOccupancyPercent()*100);
6518     return stats.build();
6519   }
6520 
6521   @Override
6522   public void processRowsWithLocks(RowProcessor<?,?> processor) throws IOException {
6523     processRowsWithLocks(processor, rowProcessorTimeout, HConstants.NO_NONCE,
6524       HConstants.NO_NONCE);
6525   }
6526 
6527   @Override
6528   public void processRowsWithLocks(RowProcessor<?,?> processor, long nonceGroup, long nonce)
6529       throws IOException {
6530     processRowsWithLocks(processor, rowProcessorTimeout, nonceGroup, nonce);
6531   }
6532 
6533   @Override
6534   public void processRowsWithLocks(RowProcessor<?,?> processor, long timeout,
6535       long nonceGroup, long nonce) throws IOException {
6536 
6537     for (byte[] row : processor.getRowsToLock()) {
6538       checkRow(row, "processRowsWithLocks");
6539     }
6540     if (!processor.readOnly()) {
6541       checkReadOnly();
6542     }
6543     checkResources();
6544 
6545     startRegionOperation();
6546     WALEdit walEdit = new WALEdit();
6547 
6548     // 1. Run pre-process hook
6549     try {
6550       processor.preProcess(this, walEdit);
6551     } catch (IOException e) {
6552       closeRegionOperation();
6553       throw e;
6554     }
6555     // Short circuit the read only case
6556     if (processor.readOnly()) {
6557       try {
6558         long now = EnvironmentEdgeManager.currentTime();
6559         doProcessRowWithTimeout(
6560             processor, now, this, null, null, timeout);
6561         processor.postProcess(this, walEdit, true);
6562       } finally {
6563         closeRegionOperation();
6564       }
6565       return;
6566     }
6567 
6568     MultiVersionConsistencyControl.WriteEntry writeEntry = null;
6569     boolean locked;
6570     boolean walSyncSuccessful = false;
6571     List<RowLock> acquiredRowLocks;
6572     long addedSize = 0;
6573     List<Mutation> mutations = new ArrayList<Mutation>();
6574     List<Cell> memstoreCells = new ArrayList<Cell>();
6575     Collection<byte[]> rowsToLock = processor.getRowsToLock();
6576     long mvccNum = 0;
6577     WALKey walKey = null;
6578     try {
6579       // 2. Acquire the row lock(s)
6580       acquiredRowLocks = new ArrayList<RowLock>(rowsToLock.size());
6581       for (byte[] row : rowsToLock) {
6582         // Attempt to lock all involved rows, throw if any lock times out
6583         acquiredRowLocks.add(getRowLock(row));
6584       }
6585       // 3. Region lock
6586       lock(this.updatesLock.readLock(), acquiredRowLocks.size() == 0 ? 1 : acquiredRowLocks.size());
6587       locked = true;
6588       // Get a mvcc write number
6589       mvccNum = MultiVersionConsistencyControl.getPreAssignedWriteNumber(this.sequenceId);
6590 
6591       long now = EnvironmentEdgeManager.currentTime();
6592       try {
6593         // 4. Let the processor scan the rows, generate mutations and add
6594         //    waledits
6595         doProcessRowWithTimeout(
6596             processor, now, this, mutations, walEdit, timeout);
6597 
6598         if (!mutations.isEmpty()) {
6599           // 5. Start mvcc transaction
6600           writeEntry = mvcc.beginMemstoreInsertWithSeqNum(mvccNum);
6601           // 6. Call the preBatchMutate hook
6602           processor.preBatchMutate(this, walEdit);
6603           // 7. Apply to memstore
6604           for (Mutation m : mutations) {
6605             // Handle any tag based cell features
6606             rewriteCellTags(m.getFamilyCellMap(), m);
6607 
6608             for (CellScanner cellScanner = m.cellScanner(); cellScanner.advance();) {
6609               Cell cell = cellScanner.current();
6610               CellUtil.setSequenceId(cell, mvccNum);
6611               Store store = getStore(cell);
6612               if (store == null) {
6613                 checkFamily(CellUtil.cloneFamily(cell));
6614                 // unreachable
6615               }
6616               Pair<Long, Cell> ret = store.add(cell);
6617               addedSize += ret.getFirst();
6618               memstoreCells.add(ret.getSecond());
6619             }
6620           }
6621 
6622           long txid = 0;
6623           // 8. Append no sync
6624           if (!walEdit.isEmpty()) {
6625             // we use HLogKey here instead of WALKey directly to support legacy coprocessors.
6626             walKey = new HLogKey(this.getRegionInfo().getEncodedNameAsBytes(),
6627               this.htableDescriptor.getTableName(), WALKey.NO_SEQUENCE_ID, now,
6628               processor.getClusterIds(), nonceGroup, nonce);
6629             txid = this.wal.append(this.htableDescriptor, this.getRegionInfo(),
6630               walKey, walEdit, getSequenceId(), true, memstoreCells);
6631           }
6632           if(walKey == null){
6633             // since we use wal sequence Id as mvcc, for SKIP_WAL changes we need a "faked" WALEdit
6634             // to get a sequence id assigned which is done by FSWALEntry#stampRegionSequenceId
6635             walKey = this.appendEmptyEdit(this.wal, memstoreCells);
6636           }
6637           // 9. Release region lock
6638           if (locked) {
6639             this.updatesLock.readLock().unlock();
6640             locked = false;
6641           }
6642 
6643           // 10. Release row lock(s)
6644           releaseRowLocks(acquiredRowLocks);
6645 
6646           // 11. Sync edit log
6647           if (txid != 0) {
6648             syncOrDefer(txid, getEffectiveDurability(processor.useDurability()));
6649           }
6650           walSyncSuccessful = true;
6651           // 12. call postBatchMutate hook
6652           processor.postBatchMutate(this);
6653         }
6654       } finally {
6655         if (!mutations.isEmpty() && !walSyncSuccessful) {
6656           LOG.warn("Wal sync failed. Roll back " + mutations.size() +
6657               " memstore keyvalues for row(s):" + StringUtils.byteToHexString(
6658               processor.getRowsToLock().iterator().next()) + "...");
6659           for (Mutation m : mutations) {
6660             for (CellScanner cellScanner = m.cellScanner(); cellScanner.advance();) {
6661               Cell cell = cellScanner.current();
6662               getStore(cell).rollback(cell);
6663             }
6664           }
6665         }
6666         // 13. Roll mvcc forward
6667         if (writeEntry != null) {
6668           mvcc.completeMemstoreInsertWithSeqNum(writeEntry, walKey);
6669         }
6670         if (locked) {
6671           this.updatesLock.readLock().unlock();
6672         }
6673         // release locks if some were acquired but another timed out
6674         releaseRowLocks(acquiredRowLocks);
6675       }
6676 
6677       // 14. Run post-process hook
6678       processor.postProcess(this, walEdit, walSyncSuccessful);
6679 
6680     } finally {
6681       closeRegionOperation();
6682       if (!mutations.isEmpty() &&
6683           isFlushSize(this.addAndGetGlobalMemstoreSize(addedSize))) {
6684         requestFlush();
6685       }
6686     }
6687   }
6688 
6689   private void doProcessRowWithTimeout(final RowProcessor<?,?> processor,
6690                                        final long now,
6691                                        final HRegion region,
6692                                        final List<Mutation> mutations,
6693                                        final WALEdit walEdit,
6694                                        final long timeout) throws IOException {
6695     // Short circuit the no time bound case.
6696     if (timeout < 0) {
6697       try {
6698         processor.process(now, region, mutations, walEdit);
6699       } catch (IOException e) {
6700         LOG.warn("RowProcessor:" + processor.getClass().getName() +
6701             " throws Exception on row(s):" +
6702             Bytes.toStringBinary(
6703               processor.getRowsToLock().iterator().next()) + "...", e);
6704         throw e;
6705       }
6706       return;
6707     }
6708 
6709     // Case with time bound
6710     FutureTask<Void> task =
6711       new FutureTask<Void>(new Callable<Void>() {
6712         @Override
6713         public Void call() throws IOException {
6714           try {
6715             processor.process(now, region, mutations, walEdit);
6716             return null;
6717           } catch (IOException e) {
6718             LOG.warn("RowProcessor:" + processor.getClass().getName() +
6719                 " throws Exception on row(s):" +
6720                 Bytes.toStringBinary(
6721                     processor.getRowsToLock().iterator().next()) + "...", e);
6722             throw e;
6723           }
6724         }
6725       });
6726     rowProcessorExecutor.execute(task);
6727     try {
6728       task.get(timeout, TimeUnit.MILLISECONDS);
6729     } catch (TimeoutException te) {
6730       LOG.error("RowProcessor timeout:" + timeout + " ms on row(s):" +
6731           Bytes.toStringBinary(processor.getRowsToLock().iterator().next()) +
6732           "...");
6733       throw new IOException(te);
6734     } catch (Exception e) {
6735       throw new IOException(e);
6736     }
6737   }
6738 
6739   public Result append(Append append) throws IOException {
6740     return append(append, HConstants.NO_NONCE, HConstants.NO_NONCE);
6741   }
6742 
6743   // TODO: There's a lot of boiler plate code identical to increment.
6744   // We should refactor append and increment as local get-mutate-put
6745   // transactions, so all stores only go through one code path for puts.
6746 
6747   @Override
6748   public Result append(Append append, long nonceGroup, long nonce) throws IOException {
6749     byte[] row = append.getRow();
6750     checkRow(row, "append");
6751     boolean flush = false;
6752     Durability durability = getEffectiveDurability(append.getDurability());
6753     boolean writeToWAL = durability != Durability.SKIP_WAL;
6754     WALEdit walEdits = null;
6755     List<Cell> allKVs = new ArrayList<Cell>(append.size());
6756     Map<Store, List<Cell>> tempMemstore = new HashMap<Store, List<Cell>>();
6757     long size = 0;
6758     long txid = 0;
6759 
6760     checkReadOnly();
6761     checkResources();
6762     // Lock row
6763     startRegionOperation(Operation.APPEND);
6764     this.writeRequestsCount.increment();
6765     long mvccNum = 0;
6766     WriteEntry w = null;
6767     WALKey walKey = null;
6768     RowLock rowLock = null;
6769     List<Cell> memstoreCells = new ArrayList<Cell>();
6770     boolean doRollBackMemstore = false;
6771     try {
6772       rowLock = getRowLock(row);
6773       try {
6774         lock(this.updatesLock.readLock());
6775         try {
6776           // wait for all prior MVCC transactions to finish - while we hold the row lock
6777           // (so that we are guaranteed to see the latest state)
6778           mvcc.waitForPreviousTransactionsComplete();
6779           if (this.coprocessorHost != null) {
6780             Result r = this.coprocessorHost.preAppendAfterRowLock(append);
6781             if(r!= null) {
6782               return r;
6783             }
6784           }
6785           // now start my own transaction
6786           mvccNum = MultiVersionConsistencyControl.getPreAssignedWriteNumber(this.sequenceId);
6787           w = mvcc.beginMemstoreInsertWithSeqNum(mvccNum);
6788           long now = EnvironmentEdgeManager.currentTime();
6789           // Process each family
6790           for (Map.Entry<byte[], List<Cell>> family : append.getFamilyCellMap().entrySet()) {
6791 
6792             Store store = stores.get(family.getKey());
6793             List<Cell> kvs = new ArrayList<Cell>(family.getValue().size());
6794 
6795             // Sort the cells so that they match the order that they
6796             // appear in the Get results. Otherwise, we won't be able to
6797             // find the existing values if the cells are not specified
6798             // in order by the client since cells are in an array list.
6799             Collections.sort(family.getValue(), store.getComparator());
6800             // Get previous values for all columns in this family
6801             Get get = new Get(row);
6802             for (Cell cell : family.getValue()) {
6803               get.addColumn(family.getKey(), CellUtil.cloneQualifier(cell));
6804             }
6805             List<Cell> results = get(get, false);
6806 
6807             // Iterate the input columns and update existing values if they were
6808             // found, otherwise add new column initialized to the append value
6809 
6810             // Avoid as much copying as possible. We may need to rewrite and
6811             // consolidate tags. Bytes are only copied once.
6812             // Would be nice if KeyValue had scatter/gather logic
6813             int idx = 0;
6814             for (Cell cell : family.getValue()) {
6815               Cell newCell;
6816               Cell oldCell = null;
6817               if (idx < results.size()
6818                   && CellUtil.matchingQualifier(results.get(idx), cell)) {
6819                 oldCell = results.get(idx);
6820                 long ts = Math.max(now, oldCell.getTimestamp());
6821 
6822                 // Process cell tags
6823                 List<Tag> newTags = new ArrayList<Tag>();
6824 
6825                 // Make a union of the set of tags in the old and new KVs
6826 
6827                 if (oldCell.getTagsLength() > 0) {
6828                   Iterator<Tag> i = CellUtil.tagsIterator(oldCell.getTagsArray(),
6829                     oldCell.getTagsOffset(), oldCell.getTagsLength());
6830                   while (i.hasNext()) {
6831                     newTags.add(i.next());
6832                   }
6833                 }
6834                 if (cell.getTagsLength() > 0) {
6835                   Iterator<Tag> i  = CellUtil.tagsIterator(cell.getTagsArray(),
6836                     cell.getTagsOffset(), cell.getTagsLength());
6837                   while (i.hasNext()) {
6838                     newTags.add(i.next());
6839                   }
6840                 }
6841 
6842                 // Cell TTL handling
6843 
6844                 if (append.getTTL() != Long.MAX_VALUE) {
6845                   // Add the new TTL tag
6846                   newTags.add(new Tag(TagType.TTL_TAG_TYPE, Bytes.toBytes(append.getTTL())));
6847                 }
6848 
6849                 // Rebuild tags
6850                 byte[] tagBytes = Tag.fromList(newTags);
6851 
6852                 // allocate an empty cell once
6853                 newCell = new KeyValue(row.length, cell.getFamilyLength(),
6854                     cell.getQualifierLength(), ts, KeyValue.Type.Put,
6855                     oldCell.getValueLength() + cell.getValueLength(),
6856                     tagBytes.length);
6857                 // copy in row, family, and qualifier
6858                 System.arraycopy(cell.getRowArray(), cell.getRowOffset(),
6859                   newCell.getRowArray(), newCell.getRowOffset(), cell.getRowLength());
6860                 System.arraycopy(cell.getFamilyArray(), cell.getFamilyOffset(),
6861                   newCell.getFamilyArray(), newCell.getFamilyOffset(),
6862                   cell.getFamilyLength());
6863                 System.arraycopy(cell.getQualifierArray(), cell.getQualifierOffset(),
6864                   newCell.getQualifierArray(), newCell.getQualifierOffset(),
6865                   cell.getQualifierLength());
6866                 // copy in the value
6867                 System.arraycopy(oldCell.getValueArray(), oldCell.getValueOffset(),
6868                   newCell.getValueArray(), newCell.getValueOffset(),
6869                   oldCell.getValueLength());
6870                 System.arraycopy(cell.getValueArray(), cell.getValueOffset(),
6871                   newCell.getValueArray(),
6872                   newCell.getValueOffset() + oldCell.getValueLength(),
6873                   cell.getValueLength());
6874                 // Copy in tag data
6875                 System.arraycopy(tagBytes, 0, newCell.getTagsArray(), newCell.getTagsOffset(),
6876                   tagBytes.length);
6877                 idx++;
6878               } else {
6879                 // Append's KeyValue.Type==Put and ts==HConstants.LATEST_TIMESTAMP
6880                 CellUtil.updateLatestStamp(cell, now);
6881 
6882                 // Cell TTL handling
6883 
6884                 if (append.getTTL() != Long.MAX_VALUE) {
6885                   List<Tag> newTags = new ArrayList<Tag>(1);
6886                   newTags.add(new Tag(TagType.TTL_TAG_TYPE, Bytes.toBytes(append.getTTL())));
6887                   // Add the new TTL tag
6888                   newCell = new KeyValue(cell.getRowArray(), cell.getRowOffset(),
6889                       cell.getRowLength(),
6890                     cell.getFamilyArray(), cell.getFamilyOffset(),
6891                       cell.getFamilyLength(),
6892                     cell.getQualifierArray(), cell.getQualifierOffset(),
6893                       cell.getQualifierLength(),
6894                     cell.getTimestamp(), KeyValue.Type.codeToType(cell.getTypeByte()),
6895                     cell.getValueArray(), cell.getValueOffset(), cell.getValueLength(),
6896                     newTags);
6897                 } else {
6898                   newCell = cell;
6899                 }
6900               }
6901 
6902               CellUtil.setSequenceId(newCell, mvccNum);
6903               // Give coprocessors a chance to update the new cell
6904               if (coprocessorHost != null) {
6905                 newCell = coprocessorHost.postMutationBeforeWAL(RegionObserver.MutationType.APPEND,
6906                     append, oldCell, newCell);
6907               }
6908               kvs.add(newCell);
6909 
6910               // Append update to WAL
6911               if (writeToWAL) {
6912                 if (walEdits == null) {
6913                   walEdits = new WALEdit();
6914                 }
6915                 walEdits.add(newCell);
6916               }
6917             }
6918 
6919             //store the kvs to the temporary memstore before writing WAL
6920             tempMemstore.put(store, kvs);
6921           }
6922 
6923           //Actually write to Memstore now
6924           for (Map.Entry<Store, List<Cell>> entry : tempMemstore.entrySet()) {
6925             Store store = entry.getKey();
6926             if (store.getFamily().getMaxVersions() == 1) {
6927               // upsert if VERSIONS for this CF == 1
6928               size += store.upsert(entry.getValue(), getSmallestReadPoint());
6929               memstoreCells.addAll(entry.getValue());
6930             } else {
6931               // otherwise keep older versions around
6932               for (Cell cell: entry.getValue()) {
6933                 Pair<Long, Cell> ret = store.add(cell);
6934                 size += ret.getFirst();
6935                 memstoreCells.add(ret.getSecond());
6936                 doRollBackMemstore = true;
6937               }
6938             }
6939             allKVs.addAll(entry.getValue());
6940           }
6941 
6942           // Actually write to WAL now
6943           if (writeToWAL) {
6944             // Using default cluster id, as this can only happen in the originating
6945             // cluster. A slave cluster receives the final value (not the delta)
6946             // as a Put.
6947             // we use HLogKey here instead of WALKey directly to support legacy coprocessors.
6948             walKey = new HLogKey(getRegionInfo().getEncodedNameAsBytes(),
6949               this.htableDescriptor.getTableName(), WALKey.NO_SEQUENCE_ID, nonceGroup, nonce);
6950             txid = this.wal.append(this.htableDescriptor, getRegionInfo(), walKey, walEdits,
6951               this.sequenceId, true, memstoreCells);
6952           } else {
6953             recordMutationWithoutWal(append.getFamilyCellMap());
6954           }
6955           if (walKey == null) {
6956             // Append a faked WALEdit in order for SKIP_WAL updates to get mvcc assigned
6957             walKey = this.appendEmptyEdit(this.wal, memstoreCells);
6958           }
6959           size = this.addAndGetGlobalMemstoreSize(size);
6960           flush = isFlushSize(size);
6961         } finally {
6962           this.updatesLock.readLock().unlock();
6963         }
6964       } finally {
6965         rowLock.release();
6966         rowLock = null;
6967       }
6968       // sync the transaction log outside the rowlock
6969       if(txid != 0){
6970         syncOrDefer(txid, durability);
6971       }
6972       doRollBackMemstore = false;
6973     } finally {
6974       if (rowLock != null) {
6975         rowLock.release();
6976       }
6977       // if the wal sync was unsuccessful, remove keys from memstore
6978       if (doRollBackMemstore) {
6979         rollbackMemstore(memstoreCells);
6980       }
6981       if (w != null) {
6982         mvcc.completeMemstoreInsertWithSeqNum(w, walKey);
6983       }
6984       closeRegionOperation(Operation.APPEND);
6985     }
6986 
6987     if (this.metricsRegion != null) {
6988       this.metricsRegion.updateAppend();
6989     }
6990 
6991     if (flush) {
6992       // Request a cache flush. Do it outside update lock.
6993       requestFlush();
6994     }
6995 
6996 
6997     return append.isReturnResults() ? Result.create(allKVs) : null;
6998   }
6999 
7000   public Result increment(Increment increment) throws IOException {
7001     return increment(increment, HConstants.NO_NONCE, HConstants.NO_NONCE);
7002   }
7003 
7004   // TODO: There's a lot of boiler plate code identical to append.
7005   // We should refactor append and increment as local get-mutate-put
7006   // transactions, so all stores only go through one code path for puts.
7007 
7008   @Override
7009   public Result increment(Increment increment, long nonceGroup, long nonce)
7010   throws IOException {
7011     byte [] row = increment.getRow();
7012     checkRow(row, "increment");
7013     TimeRange tr = increment.getTimeRange();
7014     boolean flush = false;
7015     Durability durability = getEffectiveDurability(increment.getDurability());
7016     boolean writeToWAL = durability != Durability.SKIP_WAL;
7017     WALEdit walEdits = null;
7018     List<Cell> allKVs = new ArrayList<Cell>(increment.size());
7019     Map<Store, List<Cell>> tempMemstore = new HashMap<Store, List<Cell>>();
7020 
7021     long size = 0;
7022     long txid = 0;
7023 
7024     checkReadOnly();
7025     checkResources();
7026     // Lock row
7027     startRegionOperation(Operation.INCREMENT);
7028     this.writeRequestsCount.increment();
7029     RowLock rowLock = null;
7030     WriteEntry w = null;
7031     WALKey walKey = null;
7032     long mvccNum = 0;
7033     List<Cell> memstoreCells = new ArrayList<Cell>();
7034     boolean doRollBackMemstore = false;
7035     try {
7036       rowLock = getRowLock(row);
7037       try {
7038         lock(this.updatesLock.readLock());
7039         try {
7040           // wait for all prior MVCC transactions to finish - while we hold the row lock
7041           // (so that we are guaranteed to see the latest state)
7042           mvcc.waitForPreviousTransactionsComplete();
7043           if (this.coprocessorHost != null) {
7044             Result r = this.coprocessorHost.preIncrementAfterRowLock(increment);
7045             if (r != null) {
7046               return r;
7047             }
7048           }
7049           // now start my own transaction
7050           mvccNum = MultiVersionConsistencyControl.getPreAssignedWriteNumber(this.sequenceId);
7051           w = mvcc.beginMemstoreInsertWithSeqNum(mvccNum);
7052           long now = EnvironmentEdgeManager.currentTime();
7053           // Process each family
7054           for (Map.Entry<byte [], List<Cell>> family:
7055               increment.getFamilyCellMap().entrySet()) {
7056 
7057             Store store = stores.get(family.getKey());
7058             List<Cell> kvs = new ArrayList<Cell>(family.getValue().size());
7059 
7060             // Sort the cells so that they match the order that they
7061             // appear in the Get results. Otherwise, we won't be able to
7062             // find the existing values if the cells are not specified
7063             // in order by the client since cells are in an array list.
7064             Collections.sort(family.getValue(), store.getComparator());
7065             // Get previous values for all columns in this family
7066             Get get = new Get(row);
7067             for (Cell cell: family.getValue()) {
7068               get.addColumn(family.getKey(),  CellUtil.cloneQualifier(cell));
7069             }
7070             get.setTimeRange(tr.getMin(), tr.getMax());
7071             List<Cell> results = get(get, false);
7072 
7073             // Iterate the input columns and update existing values if they were
7074             // found, otherwise add new column initialized to the increment amount
7075             int idx = 0;
7076             List<Cell> edits = family.getValue();
7077             for (int i = 0; i < edits.size(); i++) {
7078               Cell cell = edits.get(i);
7079               long amount = Bytes.toLong(CellUtil.cloneValue(cell));
7080               boolean noWriteBack = (amount == 0);
7081               List<Tag> newTags = new ArrayList<Tag>();
7082 
7083               // Carry forward any tags that might have been added by a coprocessor
7084               if (cell.getTagsLength() > 0) {
7085                 Iterator<Tag> itr = CellUtil.tagsIterator(cell.getTagsArray(),
7086                   cell.getTagsOffset(), cell.getTagsLength());
7087                 while (itr.hasNext()) {
7088                   newTags.add(itr.next());
7089                 }
7090               }
7091 
7092               Cell c = null;
7093               long ts = now;
7094               if (idx < results.size() && CellUtil.matchingQualifier(results.get(idx), cell)) {
7095                 c = results.get(idx);
7096                 ts = Math.max(now, c.getTimestamp());
7097                 if(c.getValueLength() == Bytes.SIZEOF_LONG) {
7098                   amount += Bytes.toLong(c.getValueArray(), c.getValueOffset(), Bytes.SIZEOF_LONG);
7099                 } else {
7100                   // throw DoNotRetryIOException instead of IllegalArgumentException
7101                   throw new org.apache.hadoop.hbase.DoNotRetryIOException(
7102                       "Attempted to increment field that isn't 64 bits wide");
7103                 }
7104                 // Carry tags forward from previous version
7105                 if (c.getTagsLength() > 0) {
7106                   Iterator<Tag> itr = CellUtil.tagsIterator(c.getTagsArray(),
7107                     c.getTagsOffset(), c.getTagsLength());
7108                   while (itr.hasNext()) {
7109                     newTags.add(itr.next());
7110                   }
7111                 }
7112                 if (i < ( edits.size() - 1) && !CellUtil.matchingQualifier(cell, edits.get(i + 1)))
7113                   idx++;
7114               }
7115 
7116               // Append new incremented KeyValue to list
7117               byte[] q = CellUtil.cloneQualifier(cell);
7118               byte[] val = Bytes.toBytes(amount);
7119 
7120               // Add the TTL tag if the mutation carried one
7121               if (increment.getTTL() != Long.MAX_VALUE) {
7122                 newTags.add(new Tag(TagType.TTL_TAG_TYPE, Bytes.toBytes(increment.getTTL())));
7123               }
7124 
7125               Cell newKV = new KeyValue(row, 0, row.length,
7126                 family.getKey(), 0, family.getKey().length,
7127                 q, 0, q.length,
7128                 ts,
7129                 KeyValue.Type.Put,
7130                 val, 0, val.length,
7131                 newTags);
7132 
7133               CellUtil.setSequenceId(newKV, mvccNum);
7134 
7135               // Give coprocessors a chance to update the new cell
7136               if (coprocessorHost != null) {
7137                 newKV = coprocessorHost.postMutationBeforeWAL(
7138                     RegionObserver.MutationType.INCREMENT, increment, c, newKV);
7139               }
7140               allKVs.add(newKV);
7141 
7142               if (!noWriteBack) {
7143                 kvs.add(newKV);
7144 
7145                 // Prepare WAL updates
7146                 if (writeToWAL) {
7147                   if (walEdits == null) {
7148                     walEdits = new WALEdit();
7149                   }
7150                   walEdits.add(newKV);
7151                 }
7152               }
7153             }
7154 
7155             //store the kvs to the temporary memstore before writing WAL
7156             if (!kvs.isEmpty()) {
7157               tempMemstore.put(store, kvs);
7158             }
7159           }
7160 
7161           //Actually write to Memstore now
7162           if (!tempMemstore.isEmpty()) {
7163             for (Map.Entry<Store, List<Cell>> entry : tempMemstore.entrySet()) {
7164               Store store = entry.getKey();
7165               if (store.getFamily().getMaxVersions() == 1) {
7166                 // upsert if VERSIONS for this CF == 1
7167                 size += store.upsert(entry.getValue(), getSmallestReadPoint());
7168                 memstoreCells.addAll(entry.getValue());
7169               } else {
7170                 // otherwise keep older versions around
7171                 for (Cell cell : entry.getValue()) {
7172                   Pair<Long, Cell> ret = store.add(cell);
7173                   size += ret.getFirst();
7174                   memstoreCells.add(ret.getSecond());
7175                   doRollBackMemstore = true;
7176                 }
7177               }
7178             }
7179             size = this.addAndGetGlobalMemstoreSize(size);
7180             flush = isFlushSize(size);
7181           }
7182 
7183           // Actually write to WAL now
7184           if (walEdits != null && !walEdits.isEmpty()) {
7185             if (writeToWAL) {
7186               // Using default cluster id, as this can only happen in the originating
7187               // cluster. A slave cluster receives the final value (not the delta)
7188               // as a Put.
7189               // we use HLogKey here instead of WALKey directly to support legacy coprocessors.
7190               walKey = new HLogKey(this.getRegionInfo().getEncodedNameAsBytes(),
7191                 this.htableDescriptor.getTableName(), WALKey.NO_SEQUENCE_ID, nonceGroup, nonce);
7192               txid = this.wal.append(this.htableDescriptor, this.getRegionInfo(),
7193                 walKey, walEdits, getSequenceId(), true, memstoreCells);
7194             } else {
7195               recordMutationWithoutWal(increment.getFamilyCellMap());
7196             }
7197           }
7198           if(walKey == null){
7199             // Append a faked WALEdit in order for SKIP_WAL updates to get mvccNum assigned
7200             walKey = this.appendEmptyEdit(this.wal, memstoreCells);
7201           }
7202         } finally {
7203           this.updatesLock.readLock().unlock();
7204         }
7205       } finally {
7206         rowLock.release();
7207         rowLock = null;
7208       }
7209       // sync the transaction log outside the rowlock
7210       if(txid != 0){
7211         syncOrDefer(txid, durability);
7212       }
7213       doRollBackMemstore = false;
7214     } finally {
7215       if (rowLock != null) {
7216         rowLock.release();
7217       }
7218       // if the wal sync was unsuccessful, remove keys from memstore
7219       if (doRollBackMemstore) {
7220         rollbackMemstore(memstoreCells);
7221       }
7222       if (w != null) {
7223         mvcc.completeMemstoreInsertWithSeqNum(w, walKey);
7224       }
7225       closeRegionOperation(Operation.INCREMENT);
7226       if (this.metricsRegion != null) {
7227         this.metricsRegion.updateIncrement();
7228       }
7229     }
7230 
7231     if (flush) {
7232       // Request a cache flush.  Do it outside update lock.
7233       requestFlush();
7234     }
7235     return increment.isReturnResults() ? Result.create(allKVs) : null;
7236   }
7237 
7238   //
7239   // New HBASE-880 Helpers
7240   //
7241 
7242   private void checkFamily(final byte [] family)
7243   throws NoSuchColumnFamilyException {
7244     if (!this.htableDescriptor.hasFamily(family)) {
7245       throw new NoSuchColumnFamilyException("Column family " +
7246           Bytes.toString(family) + " does not exist in region " + this
7247           + " in table " + this.htableDescriptor);
7248     }
7249   }
7250 
7251   public static final long FIXED_OVERHEAD = ClassSize.align(
7252       ClassSize.OBJECT +
7253       ClassSize.ARRAY +
7254       45 * ClassSize.REFERENCE + 2 * Bytes.SIZEOF_INT +
7255       (14 * Bytes.SIZEOF_LONG) +
7256       5 * Bytes.SIZEOF_BOOLEAN);
7257 
7258   // woefully out of date - currently missing:
7259   // 1 x HashMap - coprocessorServiceHandlers
7260   // 6 x Counter - numMutationsWithoutWAL, dataInMemoryWithoutWAL,
7261   //   checkAndMutateChecksPassed, checkAndMutateChecksFailed, readRequestsCount,
7262   //   writeRequestsCount
7263   // 1 x HRegion$WriteState - writestate
7264   // 1 x RegionCoprocessorHost - coprocessorHost
7265   // 1 x RegionSplitPolicy - splitPolicy
7266   // 1 x MetricsRegion - metricsRegion
7267   // 1 x MetricsRegionWrapperImpl - metricsRegionWrapper
7268   public static final long DEEP_OVERHEAD = FIXED_OVERHEAD +
7269       ClassSize.OBJECT + // closeLock
7270       (2 * ClassSize.ATOMIC_BOOLEAN) + // closed, closing
7271       (3 * ClassSize.ATOMIC_LONG) + // memStoreSize, numPutsWithoutWAL, dataInMemoryWithoutWAL
7272       (2 * ClassSize.CONCURRENT_HASHMAP) +  // lockedRows, scannerReadPoints
7273       WriteState.HEAP_SIZE + // writestate
7274       ClassSize.CONCURRENT_SKIPLISTMAP + ClassSize.CONCURRENT_SKIPLISTMAP_ENTRY + // stores
7275       (2 * ClassSize.REENTRANT_LOCK) + // lock, updatesLock
7276       MultiVersionConsistencyControl.FIXED_SIZE // mvcc
7277       + ClassSize.TREEMAP // maxSeqIdInStores
7278       + 2 * ClassSize.ATOMIC_INTEGER // majorInProgress, minorInProgress
7279       ;
7280 
7281   @Override
7282   public long heapSize() {
7283     long heapSize = DEEP_OVERHEAD;
7284     for (Store store : this.stores.values()) {
7285       heapSize += store.heapSize();
7286     }
7287     // this does not take into account row locks, recent flushes, mvcc entries, and more
7288     return heapSize;
7289   }
7290 
7291   /*
7292    * This method calls System.exit.
7293    * @param message Message to print out.  May be null.
7294    */
7295   private static void printUsageAndExit(final String message) {
7296     if (message != null && message.length() > 0) System.out.println(message);
7297     System.out.println("Usage: HRegion CATALOG_TABLE_DIR [major_compact]");
7298     System.out.println("Options:");
7299     System.out.println(" major_compact  Pass this option to major compact " +
7300       "passed region.");
7301     System.out.println("Default outputs scan of passed region.");
7302     System.exit(1);
7303   }
7304 
7305   @Override
7306   public boolean registerService(Service instance) {
7307     /*
7308      * No stacking of instances is allowed for a single service name
7309      */
7310     Descriptors.ServiceDescriptor serviceDesc = instance.getDescriptorForType();
7311     if (coprocessorServiceHandlers.containsKey(serviceDesc.getFullName())) {
7312       LOG.error("Coprocessor service "+serviceDesc.getFullName()+
7313           " already registered, rejecting request from "+instance
7314       );
7315       return false;
7316     }
7317 
7318     coprocessorServiceHandlers.put(serviceDesc.getFullName(), instance);
7319     if (LOG.isDebugEnabled()) {
7320       LOG.debug("Registered coprocessor service: region=" +
7321           Bytes.toStringBinary(getRegionInfo().getRegionName()) +
7322           " service=" + serviceDesc.getFullName());
7323     }
7324     return true;
7325   }
7326 
7327   @Override
7328   public Message execService(RpcController controller, CoprocessorServiceCall call)
7329       throws IOException {
7330     String serviceName = call.getServiceName();
7331     String methodName = call.getMethodName();
7332     if (!coprocessorServiceHandlers.containsKey(serviceName)) {
7333       throw new UnknownProtocolException(null,
7334           "No registered coprocessor service found for name "+serviceName+
7335           " in region "+Bytes.toStringBinary(getRegionInfo().getRegionName()));
7336     }
7337 
7338     Service service = coprocessorServiceHandlers.get(serviceName);
7339     Descriptors.ServiceDescriptor serviceDesc = service.getDescriptorForType();
7340     Descriptors.MethodDescriptor methodDesc = serviceDesc.findMethodByName(methodName);
7341     if (methodDesc == null) {
7342       throw new UnknownProtocolException(service.getClass(),
7343           "Unknown method "+methodName+" called on service "+serviceName+
7344               " in region "+Bytes.toStringBinary(getRegionInfo().getRegionName()));
7345     }
7346 
7347     Message request = service.getRequestPrototype(methodDesc).newBuilderForType()
7348         .mergeFrom(call.getRequest()).build();
7349 
7350     if (coprocessorHost != null) {
7351       request = coprocessorHost.preEndpointInvocation(service, methodName, request);
7352     }
7353 
7354     final Message.Builder responseBuilder =
7355         service.getResponsePrototype(methodDesc).newBuilderForType();
7356     service.callMethod(methodDesc, controller, request, new RpcCallback<Message>() {
7357       @Override
7358       public void run(Message message) {
7359         if (message != null) {
7360           responseBuilder.mergeFrom(message);
7361         }
7362       }
7363     });
7364 
7365     if (coprocessorHost != null) {
7366       coprocessorHost.postEndpointInvocation(service, methodName, request, responseBuilder);
7367     }
7368 
7369     return responseBuilder.build();
7370   }
7371 
7372   /*
7373    * Process table.
7374    * Do major compaction or list content.
7375    * @throws IOException
7376    */
7377   private static void processTable(final FileSystem fs, final Path p,
7378       final WALFactory walFactory, final Configuration c,
7379       final boolean majorCompact)
7380   throws IOException {
7381     HRegion region;
7382     FSTableDescriptors fst = new FSTableDescriptors(c);
7383     // Currently expects tables have one region only.
7384     if (FSUtils.getTableName(p).equals(TableName.META_TABLE_NAME)) {
7385       final WAL wal = walFactory.getMetaWAL(
7386           HRegionInfo.FIRST_META_REGIONINFO.getEncodedNameAsBytes());
7387       region = HRegion.newHRegion(p, wal, fs, c,
7388         HRegionInfo.FIRST_META_REGIONINFO, fst.get(TableName.META_TABLE_NAME), null);
7389     } else {
7390       throw new IOException("Not a known catalog table: " + p.toString());
7391     }
7392     try {
7393       region.initialize(null);
7394       if (majorCompact) {
7395         region.compact(true);
7396       } else {
7397         // Default behavior
7398         Scan scan = new Scan();
7399         // scan.addFamily(HConstants.CATALOG_FAMILY);
7400         RegionScanner scanner = region.getScanner(scan);
7401         try {
7402           List<Cell> kvs = new ArrayList<Cell>();
7403           boolean done;
7404           do {
7405             kvs.clear();
7406             done = scanner.next(kvs);
7407             if (kvs.size() > 0) LOG.info(kvs);
7408           } while (done);
7409         } finally {
7410           scanner.close();
7411         }
7412       }
7413     } finally {
7414       region.close();
7415     }
7416   }
7417 
7418   boolean shouldForceSplit() {
7419     return this.splitRequest;
7420   }
7421 
7422   byte[] getExplicitSplitPoint() {
7423     return this.explicitSplitPoint;
7424   }
7425 
7426   void forceSplit(byte[] sp) {
7427     // This HRegion will go away after the forced split is successful
7428     // But if a forced split fails, we need to clear forced split.
7429     this.splitRequest = true;
7430     if (sp != null) {
7431       this.explicitSplitPoint = sp;
7432     }
7433   }
7434 
7435   void clearSplit() {
7436     this.splitRequest = false;
7437     this.explicitSplitPoint = null;
7438   }
7439 
7440   /**
7441    * Give the region a chance to prepare before it is split.
7442    */
7443   protected void prepareToSplit() {
7444     // nothing
7445   }
7446 
7447   /**
7448    * Return the splitpoint. null indicates the region isn't splittable
7449    * If the splitpoint isn't explicitly specified, it will go over the stores
7450    * to find the best splitpoint. Currently the criteria of best splitpoint
7451    * is based on the size of the store.
7452    */
7453   public byte[] checkSplit() {
7454     // Can't split META
7455     if (this.getRegionInfo().isMetaTable() ||
7456         TableName.NAMESPACE_TABLE_NAME.equals(this.getRegionInfo().getTable())) {
7457       if (shouldForceSplit()) {
7458         LOG.warn("Cannot split meta region in HBase 0.20 and above");
7459       }
7460       return null;
7461     }
7462 
7463     // Can't split region which is in recovering state
7464     if (this.isRecovering()) {
7465       LOG.info("Cannot split region " + this.getRegionInfo().getEncodedName() + " in recovery.");
7466       return null;
7467     }
7468 
7469     if (!splitPolicy.shouldSplit()) {
7470       return null;
7471     }
7472 
7473     byte[] ret = splitPolicy.getSplitPoint();
7474 
7475     if (ret != null) {
7476       try {
7477         checkRow(ret, "calculated split");
7478       } catch (IOException e) {
7479         LOG.error("Ignoring invalid split", e);
7480         return null;
7481       }
7482     }
7483     return ret;
7484   }
7485 
7486   /**
7487    * @return The priority that this region should have in the compaction queue
7488    */
7489   public int getCompactPriority() {
7490     int count = Integer.MAX_VALUE;
7491     for (Store store : stores.values()) {
7492       count = Math.min(count, store.getCompactPriority());
7493     }
7494     return count;
7495   }
7496 
7497 
7498   /** @return the coprocessor host */
7499   public RegionCoprocessorHost getCoprocessorHost() {
7500     return coprocessorHost;
7501   }
7502 
7503   /** @param coprocessorHost the new coprocessor host */
7504   public void setCoprocessorHost(final RegionCoprocessorHost coprocessorHost) {
7505     this.coprocessorHost = coprocessorHost;
7506   }
7507 
7508   @Override
7509   public void startRegionOperation() throws IOException {
7510     startRegionOperation(Operation.ANY);
7511   }
7512 
7513   @Override
7514   public void startRegionOperation(Operation op) throws IOException {
7515     switch (op) {
7516     case GET:  // read operations
7517     case SCAN:
7518       checkReadsEnabled();
7519     case INCREMENT: // write operations
7520     case APPEND:
7521     case SPLIT_REGION:
7522     case MERGE_REGION:
7523     case PUT:
7524     case DELETE:
7525     case BATCH_MUTATE:
7526     case COMPACT_REGION:
7527       // when a region is in recovering state, no read, split or merge is allowed
7528       if (isRecovering() && (this.disallowWritesInRecovering ||
7529               (op != Operation.PUT && op != Operation.DELETE && op != Operation.BATCH_MUTATE))) {
7530         throw new RegionInRecoveryException(getRegionInfo().getRegionNameAsString() +
7531           " is recovering; cannot take reads");
7532       }
7533       break;
7534     default:
7535       break;
7536     }
7537     if (op == Operation.MERGE_REGION || op == Operation.SPLIT_REGION
7538         || op == Operation.COMPACT_REGION) {
7539       // split, merge or compact region doesn't need to check the closing/closed state or lock the
7540       // region
7541       return;
7542     }
7543     if (this.closing.get()) {
7544       throw new NotServingRegionException(getRegionInfo().getRegionNameAsString() + " is closing");
7545     }
7546     lock(lock.readLock());
7547     if (this.closed.get()) {
7548       lock.readLock().unlock();
7549       throw new NotServingRegionException(getRegionInfo().getRegionNameAsString() + " is closed");
7550     }
7551     try {
7552       if (coprocessorHost != null) {
7553         coprocessorHost.postStartRegionOperation(op);
7554       }
7555     } catch (Exception e) {
7556       lock.readLock().unlock();
7557       throw new IOException(e);
7558     }
7559   }
7560 
7561   @Override
7562   public void closeRegionOperation() throws IOException {
7563     closeRegionOperation(Operation.ANY);
7564   }
7565 
7566   /**
7567    * Closes the lock. This needs to be called in the finally block corresponding
7568    * to the try block of {@link #startRegionOperation(Operation)}
7569    * @throws IOException
7570    */
7571   public void closeRegionOperation(Operation operation) throws IOException {
7572     lock.readLock().unlock();
7573     if (coprocessorHost != null) {
7574       coprocessorHost.postCloseRegionOperation(operation);
7575     }
7576   }
7577 
7578   /**
7579    * This method needs to be called before any public call that reads or
7580    * modifies stores in bulk. It has to be called just before a try.
7581    * #closeBulkRegionOperation needs to be called in the try's finally block
7582    * Acquires a writelock and checks if the region is closing or closed.
7583    * @throws NotServingRegionException when the region is closing or closed
7584    * @throws RegionTooBusyException if failed to get the lock in time
7585    * @throws InterruptedIOException if interrupted while waiting for a lock
7586    */
7587   private void startBulkRegionOperation(boolean writeLockNeeded)
7588       throws NotServingRegionException, RegionTooBusyException, InterruptedIOException {
7589     if (this.closing.get()) {
7590       throw new NotServingRegionException(getRegionInfo().getRegionNameAsString() + " is closing");
7591     }
7592     if (writeLockNeeded) lock(lock.writeLock());
7593     else lock(lock.readLock());
7594     if (this.closed.get()) {
7595       if (writeLockNeeded) lock.writeLock().unlock();
7596       else lock.readLock().unlock();
7597       throw new NotServingRegionException(getRegionInfo().getRegionNameAsString() + " is closed");
7598     }
7599   }
7600 
7601   /**
7602    * Closes the lock. This needs to be called in the finally block corresponding
7603    * to the try block of #startRegionOperation
7604    */
7605   private void closeBulkRegionOperation(){
7606     if (lock.writeLock().isHeldByCurrentThread()) lock.writeLock().unlock();
7607     else lock.readLock().unlock();
7608   }
7609 
7610   /**
7611    * Update counters for numer of puts without wal and the size of possible data loss.
7612    * These information are exposed by the region server metrics.
7613    */
7614   private void recordMutationWithoutWal(final Map<byte [], List<Cell>> familyMap) {
7615     numMutationsWithoutWAL.increment();
7616     if (numMutationsWithoutWAL.get() <= 1) {
7617       LOG.info("writing data to region " + this +
7618                " with WAL disabled. Data may be lost in the event of a crash.");
7619     }
7620 
7621     long mutationSize = 0;
7622     for (List<Cell> cells: familyMap.values()) {
7623       assert cells instanceof RandomAccess;
7624       int listSize = cells.size();
7625       for (int i=0; i < listSize; i++) {
7626         Cell cell = cells.get(i);
7627         // TODO we need include tags length also here.
7628         mutationSize += KeyValueUtil.keyLength(cell) + cell.getValueLength();
7629       }
7630     }
7631 
7632     dataInMemoryWithoutWAL.add(mutationSize);
7633   }
7634 
7635   private void lock(final Lock lock)
7636       throws RegionTooBusyException, InterruptedIOException {
7637     lock(lock, 1);
7638   }
7639 
7640   /**
7641    * Try to acquire a lock.  Throw RegionTooBusyException
7642    * if failed to get the lock in time. Throw InterruptedIOException
7643    * if interrupted while waiting for the lock.
7644    */
7645   private void lock(final Lock lock, final int multiplier)
7646       throws RegionTooBusyException, InterruptedIOException {
7647     try {
7648       final long waitTime = Math.min(maxBusyWaitDuration,
7649           busyWaitDuration * Math.min(multiplier, maxBusyWaitMultiplier));
7650       if (!lock.tryLock(waitTime, TimeUnit.MILLISECONDS)) {
7651         throw new RegionTooBusyException(
7652             "failed to get a lock in " + waitTime + " ms. " +
7653                 "regionName=" + (this.getRegionInfo() == null ? "unknown" :
7654                 this.getRegionInfo().getRegionNameAsString()) +
7655                 ", server=" + (this.getRegionServerServices() == null ? "unknown" :
7656                 this.getRegionServerServices().getServerName()));
7657       }
7658     } catch (InterruptedException ie) {
7659       LOG.info("Interrupted while waiting for a lock");
7660       InterruptedIOException iie = new InterruptedIOException();
7661       iie.initCause(ie);
7662       throw iie;
7663     }
7664   }
7665 
7666   /**
7667    * Calls sync with the given transaction ID if the region's table is not
7668    * deferring it.
7669    * @param txid should sync up to which transaction
7670    * @throws IOException If anything goes wrong with DFS
7671    */
7672   private void syncOrDefer(long txid, Durability durability) throws IOException {
7673     if (this.getRegionInfo().isMetaRegion()) {
7674       this.wal.sync(txid);
7675     } else {
7676       switch(durability) {
7677       case USE_DEFAULT:
7678         // do what table defaults to
7679         if (shouldSyncWAL()) {
7680           this.wal.sync(txid);
7681         }
7682         break;
7683       case SKIP_WAL:
7684         // nothing do to
7685         break;
7686       case ASYNC_WAL:
7687         // nothing do to
7688         break;
7689       case SYNC_WAL:
7690       case FSYNC_WAL:
7691         // sync the WAL edit (SYNC and FSYNC treated the same for now)
7692         this.wal.sync(txid);
7693         break;
7694       }
7695     }
7696   }
7697 
7698   /**
7699    * Check whether we should sync the wal from the table's durability settings
7700    */
7701   private boolean shouldSyncWAL() {
7702     return durability.ordinal() >  Durability.ASYNC_WAL.ordinal();
7703   }
7704 
7705   /**
7706    * A mocked list implementation - discards all updates.
7707    */
7708   private static final List<Cell> MOCKED_LIST = new AbstractList<Cell>() {
7709 
7710     @Override
7711     public void add(int index, Cell element) {
7712       // do nothing
7713     }
7714 
7715     @Override
7716     public boolean addAll(int index, Collection<? extends Cell> c) {
7717       return false; // this list is never changed as a result of an update
7718     }
7719 
7720     @Override
7721     public KeyValue get(int index) {
7722       throw new UnsupportedOperationException();
7723     }
7724 
7725     @Override
7726     public int size() {
7727       return 0;
7728     }
7729   };
7730 
7731   /**
7732    * Facility for dumping and compacting catalog tables.
7733    * Only does catalog tables since these are only tables we for sure know
7734    * schema on.  For usage run:
7735    * <pre>
7736    *   ./bin/hbase org.apache.hadoop.hbase.regionserver.HRegion
7737    * </pre>
7738    * @throws IOException
7739    */
7740   public static void main(String[] args) throws IOException {
7741     if (args.length < 1) {
7742       printUsageAndExit(null);
7743     }
7744     boolean majorCompact = false;
7745     if (args.length > 1) {
7746       if (!args[1].toLowerCase().startsWith("major")) {
7747         printUsageAndExit("ERROR: Unrecognized option <" + args[1] + ">");
7748       }
7749       majorCompact = true;
7750     }
7751     final Path tableDir = new Path(args[0]);
7752     final Configuration c = HBaseConfiguration.create();
7753     final FileSystem fs = FileSystem.get(c);
7754     final Path logdir = new Path(c.get("hbase.tmp.dir"));
7755     final String logname = "wal" + FSUtils.getTableName(tableDir) + System.currentTimeMillis();
7756 
7757     final Configuration walConf = new Configuration(c);
7758     FSUtils.setRootDir(walConf, logdir);
7759     final WALFactory wals = new WALFactory(walConf, null, logname);
7760     try {
7761       processTable(fs, tableDir, wals, c, majorCompact);
7762     } finally {
7763        wals.close();
7764        // TODO: is this still right?
7765        BlockCache bc = new CacheConfig(c).getBlockCache();
7766        if (bc != null) bc.shutdown();
7767     }
7768   }
7769 
7770   @Override
7771   public long getOpenSeqNum() {
7772     return this.openSeqNum;
7773   }
7774 
7775   @Override
7776   public Map<byte[], Long> getMaxStoreSeqId() {
7777     return this.maxSeqIdInStores;
7778   }
7779 
7780   @Override
7781   public long getOldestSeqIdOfStore(byte[] familyName) {
7782     return wal.getEarliestMemstoreSeqNum(getRegionInfo()
7783         .getEncodedNameAsBytes(), familyName);
7784   }
7785 
7786   @Override
7787   public CompactionState getCompactionState() {
7788     boolean hasMajor = majorInProgress.get() > 0, hasMinor = minorInProgress.get() > 0;
7789     return (hasMajor ? (hasMinor ? CompactionState.MAJOR_AND_MINOR : CompactionState.MAJOR)
7790         : (hasMinor ? CompactionState.MINOR : CompactionState.NONE));
7791   }
7792 
7793   public void reportCompactionRequestStart(boolean isMajor){
7794     (isMajor ? majorInProgress : minorInProgress).incrementAndGet();
7795   }
7796 
7797   public void reportCompactionRequestEnd(boolean isMajor, int numFiles, long filesSizeCompacted) {
7798     int newValue = (isMajor ? majorInProgress : minorInProgress).decrementAndGet();
7799 
7800     // metrics
7801     compactionsFinished.incrementAndGet();
7802     compactionNumFilesCompacted.addAndGet(numFiles);
7803     compactionNumBytesCompacted.addAndGet(filesSizeCompacted);
7804 
7805     assert newValue >= 0;
7806   }
7807 
7808   /**
7809    * Do not change this sequence id. See {@link #sequenceId} comment.
7810    * @return sequenceId
7811    */
7812   @VisibleForTesting
7813   public AtomicLong getSequenceId() {
7814     return this.sequenceId;
7815   }
7816 
7817   /**
7818    * sets this region's sequenceId.
7819    * @param value new value
7820    */
7821   private void setSequenceId(long value) {
7822     this.sequenceId.set(value);
7823   }
7824 
7825   @VisibleForTesting class RowLockContext {
7826     private final HashedBytes row;
7827     private final CountDownLatch latch = new CountDownLatch(1);
7828     private final Thread thread;
7829     private int lockCount = 0;
7830 
7831     RowLockContext(HashedBytes row) {
7832       this.row = row;
7833       this.thread = Thread.currentThread();
7834     }
7835 
7836     boolean ownedByCurrentThread() {
7837       return thread == Thread.currentThread();
7838     }
7839 
7840     RowLock newLock() {
7841       lockCount++;
7842       RowLockImpl rl = new RowLockImpl();
7843       rl.setContext(this);
7844       return rl;
7845     }
7846 
7847     void releaseLock() {
7848       if (!ownedByCurrentThread()) {
7849         throw new IllegalArgumentException("Lock held by thread: " + thread
7850           + " cannot be released by different thread: " + Thread.currentThread());
7851       }
7852       lockCount--;
7853       if (lockCount == 0) {
7854         // no remaining locks by the thread, unlock and allow other threads to access
7855         RowLockContext existingContext = lockedRows.remove(row);
7856         if (existingContext != this) {
7857           throw new RuntimeException(
7858               "Internal row lock state inconsistent, should not happen, row: " + row);
7859         }
7860         latch.countDown();
7861       }
7862     }
7863   }
7864 
7865   public static class RowLockImpl implements RowLock {
7866     private RowLockContext context;
7867     private boolean released = false;
7868 
7869     @VisibleForTesting
7870     public RowLockContext getContext() {
7871       return context;
7872     }
7873 
7874     @VisibleForTesting
7875     public void setContext(RowLockContext context) {
7876       this.context = context;
7877     }
7878 
7879     @Override
7880     public void release() {
7881       if (!released) {
7882         context.releaseLock();
7883       }
7884       released = true;
7885     }
7886   }
7887 
7888   /**
7889    * Append a faked WALEdit in order to get a long sequence number and wal syncer will just ignore
7890    * the WALEdit append later.
7891    * @param wal
7892    * @param cells list of Cells inserted into memstore. Those Cells are passed in order to
7893    *        be updated with right mvcc values(their wal sequence number)
7894    * @return Return the key used appending with no sync and no append.
7895    * @throws IOException
7896    */
7897   private WALKey appendEmptyEdit(final WAL wal, List<Cell> cells) throws IOException {
7898     // we use HLogKey here instead of WALKey directly to support legacy coprocessors.
7899     WALKey key = new HLogKey(getRegionInfo().getEncodedNameAsBytes(), getRegionInfo().getTable(),
7900       WALKey.NO_SEQUENCE_ID, 0, null, HConstants.NO_NONCE, HConstants.NO_NONCE);
7901     // Call append but with an empty WALEdit.  The returned seqeunce id will not be associated
7902     // with any edit and we can be sure it went in after all outstanding appends.
7903     wal.append(getTableDesc(), getRegionInfo(), key,
7904       WALEdit.EMPTY_WALEDIT, this.sequenceId, false, cells);
7905     return key;
7906   }
7907 
7908   /**
7909    * {@inheritDoc}
7910    */
7911   @Override
7912   public void onConfigurationChange(Configuration conf) {
7913     // Do nothing for now.
7914   }
7915 
7916   /**
7917    * {@inheritDoc}
7918    */
7919   @Override
7920   public void registerChildren(ConfigurationManager manager) {
7921     configurationManager = Optional.of(manager);
7922     for (Store s : this.stores.values()) {
7923       configurationManager.get().registerObserver(s);
7924     }
7925   }
7926 
7927   /**
7928    * {@inheritDoc}
7929    */
7930   @Override
7931   public void deregisterChildren(ConfigurationManager manager) {
7932     for (Store s : this.stores.values()) {
7933       configurationManager.get().deregisterObserver(s);
7934     }
7935   }
7936 
7937   /**
7938    * @return split policy for this region.
7939    */
7940   public RegionSplitPolicy getSplitPolicy() {
7941     return this.splitPolicy;
7942   }
7943 }