View Javadoc

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