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