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