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