View Javadoc

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