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