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