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