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