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