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.IOException;
22 import java.io.InterruptedIOException;
23 import java.net.InetSocketAddress;
24 import java.security.Key;
25 import java.security.KeyException;
26 import java.security.PrivilegedExceptionAction;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.NavigableSet;
35 import java.util.Set;
36 import java.util.concurrent.Callable;
37 import java.util.concurrent.CompletionService;
38 import java.util.concurrent.ConcurrentHashMap;
39 import java.util.concurrent.ExecutionException;
40 import java.util.concurrent.ExecutorCompletionService;
41 import java.util.concurrent.Future;
42 import java.util.concurrent.ThreadPoolExecutor;
43 import java.util.concurrent.atomic.AtomicBoolean;
44 import java.util.concurrent.atomic.AtomicLong;
45 import java.util.concurrent.locks.ReentrantLock;
46 import java.util.concurrent.locks.ReentrantReadWriteLock;
47
48 import org.apache.commons.logging.Log;
49 import org.apache.commons.logging.LogFactory;
50 import org.apache.hadoop.conf.Configuration;
51 import org.apache.hadoop.fs.FileSystem;
52 import org.apache.hadoop.fs.Path;
53 import org.apache.hadoop.hbase.Cell;
54 import org.apache.hadoop.hbase.CellComparator;
55 import org.apache.hadoop.hbase.CellUtil;
56 import org.apache.hadoop.hbase.CompoundConfiguration;
57 import org.apache.hadoop.hbase.HColumnDescriptor;
58 import org.apache.hadoop.hbase.HConstants;
59 import org.apache.hadoop.hbase.HRegionInfo;
60 import org.apache.hadoop.hbase.KeyValue;
61 import org.apache.hadoop.hbase.TableName;
62 import org.apache.hadoop.hbase.Tag;
63 import org.apache.hadoop.hbase.TagType;
64 import org.apache.hadoop.hbase.backup.FailedArchiveException;
65 import org.apache.hadoop.hbase.classification.InterfaceAudience;
66 import org.apache.hadoop.hbase.client.Scan;
67 import org.apache.hadoop.hbase.conf.ConfigurationManager;
68 import org.apache.hadoop.hbase.io.compress.Compression;
69 import org.apache.hadoop.hbase.io.crypto.Cipher;
70 import org.apache.hadoop.hbase.io.crypto.Encryption;
71 import org.apache.hadoop.hbase.io.hfile.CacheConfig;
72 import org.apache.hadoop.hbase.io.hfile.HFile;
73 import org.apache.hadoop.hbase.io.hfile.HFileContext;
74 import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
75 import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder;
76 import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoderImpl;
77 import org.apache.hadoop.hbase.io.hfile.HFileScanner;
78 import org.apache.hadoop.hbase.io.hfile.InvalidHFileException;
79 import org.apache.hadoop.hbase.monitoring.MonitoredTask;
80 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
81 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
82 import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext;
83 import org.apache.hadoop.hbase.regionserver.compactions.CompactionProgress;
84 import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest;
85 import org.apache.hadoop.hbase.regionserver.compactions.DefaultCompactor;
86 import org.apache.hadoop.hbase.regionserver.compactions.OffPeakHours;
87 import org.apache.hadoop.hbase.regionserver.querymatcher.ScanQueryMatcher;
88 import org.apache.hadoop.hbase.regionserver.throttle.ThroughputController;
89 import org.apache.hadoop.hbase.regionserver.wal.WALUtil;
90 import org.apache.hadoop.hbase.security.EncryptionUtil;
91 import org.apache.hadoop.hbase.security.User;
92 import org.apache.hadoop.hbase.util.Bytes;
93 import org.apache.hadoop.hbase.util.ChecksumType;
94 import org.apache.hadoop.hbase.util.ClassSize;
95 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
96 import org.apache.hadoop.hbase.util.Pair;
97 import org.apache.hadoop.hbase.util.ReflectionUtils;
98 import org.apache.hadoop.util.StringUtils;
99 import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix;
100
101 import com.google.common.annotations.VisibleForTesting;
102 import com.google.common.base.Preconditions;
103 import com.google.common.collect.ImmutableCollection;
104 import com.google.common.collect.ImmutableList;
105 import com.google.common.collect.Lists;
106 import com.google.common.collect.Sets;
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121 @InterfaceAudience.Private
122 public class HStore implements Store {
123 private static final String MEMSTORE_CLASS_NAME = "hbase.regionserver.memstore.class";
124 public static final String COMPACTCHECKER_INTERVAL_MULTIPLIER_KEY =
125 "hbase.server.compactchecker.interval.multiplier";
126 public static final String BLOCKING_STOREFILES_KEY = "hbase.hstore.blockingStoreFiles";
127 public static final int DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER = 1000;
128 public static final int DEFAULT_BLOCKING_STOREFILE_COUNT = 7;
129
130 private static final Log LOG = LogFactory.getLog(HStore.class);
131
132 protected final MemStore memstore;
133
134 private final HRegion region;
135 private final HColumnDescriptor family;
136 private final HRegionFileSystem fs;
137 private Configuration conf;
138 private final CacheConfig cacheConf;
139 private long lastCompactSize = 0;
140 volatile boolean forceMajor = false;
141
142 static int closeCheckInterval = 0;
143 private AtomicLong storeSize = new AtomicLong();
144 private AtomicLong totalUncompressedBytes = new AtomicLong();
145
146
147
148
149
150
151
152
153
154
155 final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
156
157
158
159
160
161
162
163
164
165
166
167 final ReentrantLock archiveLock = new ReentrantLock();
168
169 private final boolean verifyBulkLoads;
170
171 private ScanInfo scanInfo;
172
173
174
175 private final List<StoreFile> filesCompacting = Lists.newArrayList();
176
177
178 private final Set<ChangedReadersObserver> changedReaderObservers =
179 Collections.newSetFromMap(new ConcurrentHashMap<ChangedReadersObserver, Boolean>());
180
181 private final int blocksize;
182 private HFileDataBlockEncoder dataBlockEncoder;
183
184
185 private ChecksumType checksumType;
186 private int bytesPerChecksum;
187
188
189 private final KeyValue.KVComparator comparator;
190
191 final StoreEngine<?, ?, ?, ?> storeEngine;
192
193 private static final AtomicBoolean offPeakCompactionTracker = new AtomicBoolean();
194 private volatile OffPeakHours offPeakHours;
195
196 private static final int DEFAULT_FLUSH_RETRIES_NUMBER = 10;
197 private int flushRetriesNumber;
198 private int pauseTime;
199
200 private long blockingFileCount;
201 private int compactionCheckMultiplier;
202
203 private Encryption.Context cryptoContext = Encryption.Context.NONE;
204
205 private AtomicLong flushedCellsCount = new AtomicLong();
206 private AtomicLong compactedCellsCount = new AtomicLong();
207 private AtomicLong majorCompactedCellsCount = new AtomicLong();
208 private AtomicLong flushedCellsSize = new AtomicLong();
209 private AtomicLong flushedOutputFileSize = new AtomicLong();
210 private AtomicLong compactedCellsSize = new AtomicLong();
211 private AtomicLong majorCompactedCellsSize = new AtomicLong();
212
213
214
215
216
217
218
219
220
221 protected HStore(final HRegion region, final HColumnDescriptor family,
222 final Configuration confParam) throws IOException {
223
224 HRegionInfo info = region.getRegionInfo();
225 this.fs = region.getRegionFileSystem();
226
227
228 fs.createStoreDir(family.getNameAsString());
229 this.region = region;
230 this.family = family;
231
232
233
234 this.conf = new CompoundConfiguration()
235 .add(confParam)
236 .addStringMap(region.getTableDesc().getConfiguration())
237 .addStringMap(family.getConfiguration())
238 .addWritableMap(family.getValues());
239 this.blocksize = family.getBlocksize();
240
241 this.dataBlockEncoder =
242 new HFileDataBlockEncoderImpl(family.getDataBlockEncoding());
243
244 this.comparator = info.getComparator();
245
246 long timeToPurgeDeletes =
247 Math.max(conf.getLong("hbase.hstore.time.to.purge.deletes", 0), 0);
248 LOG.trace("Time to purge deletes set to " + timeToPurgeDeletes +
249 "ms in store " + this);
250
251 long ttl = determineTTLFromFamily(family);
252
253
254 scanInfo = new ScanInfo(conf, family, ttl, timeToPurgeDeletes, this.comparator);
255 String className = conf.get(MEMSTORE_CLASS_NAME, DefaultMemStore.class.getName());
256 this.memstore = ReflectionUtils.instantiateWithCustomCtor(className, new Class[] {
257 Configuration.class, KeyValue.KVComparator.class }, new Object[] { conf, this.comparator });
258 this.offPeakHours = OffPeakHours.getInstance(conf);
259
260
261 this.cacheConf = new CacheConfig(conf, family);
262
263 this.verifyBulkLoads = conf.getBoolean("hbase.hstore.bulkload.verify", false);
264
265 this.blockingFileCount =
266 conf.getInt(BLOCKING_STOREFILES_KEY, DEFAULT_BLOCKING_STOREFILE_COUNT);
267 this.compactionCheckMultiplier = conf.getInt(
268 COMPACTCHECKER_INTERVAL_MULTIPLIER_KEY, DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER);
269 if (this.compactionCheckMultiplier <= 0) {
270 LOG.error("Compaction check period multiplier must be positive, setting default: "
271 + DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER);
272 this.compactionCheckMultiplier = DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER;
273 }
274
275 if (HStore.closeCheckInterval == 0) {
276 HStore.closeCheckInterval = conf.getInt(
277 "hbase.hstore.close.check.interval", 10*1000*1000
278 }
279
280 this.storeEngine = StoreEngine.create(this, this.conf, this.comparator);
281 List<StoreFile> storeFiles = loadStoreFiles();
282
283
284
285
286 this.storeSize.addAndGet(getStorefilesSize(storeFiles));
287 this.totalUncompressedBytes.addAndGet(getTotalUmcompressedBytes(storeFiles));
288 this.storeEngine.getStoreFileManager().loadFiles(storeFiles);
289
290
291 this.checksumType = getChecksumType(conf);
292
293 this.bytesPerChecksum = getBytesPerChecksum(conf);
294 flushRetriesNumber = conf.getInt(
295 "hbase.hstore.flush.retries.number", DEFAULT_FLUSH_RETRIES_NUMBER);
296 pauseTime = conf.getInt(HConstants.HBASE_SERVER_PAUSE, HConstants.DEFAULT_HBASE_SERVER_PAUSE);
297 if (flushRetriesNumber <= 0) {
298 throw new IllegalArgumentException(
299 "hbase.hstore.flush.retries.number must be > 0, not "
300 + flushRetriesNumber);
301 }
302
303
304 String cipherName = family.getEncryptionType();
305 if (cipherName != null) {
306 Cipher cipher;
307 Key key;
308 byte[] keyBytes = family.getEncryptionKey();
309 if (keyBytes != null) {
310
311 String masterKeyName = conf.get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY,
312 User.getCurrent().getShortName());
313 try {
314
315 key = EncryptionUtil.unwrapKey(conf, masterKeyName, keyBytes);
316 } catch (KeyException e) {
317
318
319 if (LOG.isDebugEnabled()) {
320 LOG.debug("Unable to unwrap key with current master key '" + masterKeyName + "'");
321 }
322 String alternateKeyName =
323 conf.get(HConstants.CRYPTO_MASTERKEY_ALTERNATE_NAME_CONF_KEY);
324 if (alternateKeyName != null) {
325 try {
326 key = EncryptionUtil.unwrapKey(conf, alternateKeyName, keyBytes);
327 } catch (KeyException ex) {
328 throw new IOException(ex);
329 }
330 } else {
331 throw new IOException(e);
332 }
333 }
334
335 cipher = Encryption.getCipher(conf, key.getAlgorithm());
336 if (cipher == null) {
337 throw new RuntimeException("Cipher '" + key.getAlgorithm() + "' is not available");
338 }
339
340
341
342 if (!cipher.getName().equalsIgnoreCase(cipherName)) {
343 throw new RuntimeException("Encryption for family '" + family.getNameAsString() +
344 "' configured with type '" + cipherName +
345 "' but key specifies algorithm '" + cipher.getName() + "'");
346 }
347 } else {
348
349 cipher = Encryption.getCipher(conf, cipherName);
350 if (cipher == null) {
351 throw new RuntimeException("Cipher '" + cipherName + "' is not available");
352 }
353 key = cipher.getRandomKey();
354 }
355 cryptoContext = Encryption.newContext(conf);
356 cryptoContext.setCipher(cipher);
357 cryptoContext.setKey(key);
358 }
359
360 LOG.info("Store=" + getColumnFamilyName() +
361 ", memstore type=" + this.memstore.getClass().getSimpleName() +
362 ", verifyBulkLoads=" + verifyBulkLoads +
363 ", encoding=" + family.getDataBlockEncoding() +
364 ", compression=" + family.getCompressionType());
365 }
366
367
368
369
370
371 private static long determineTTLFromFamily(final HColumnDescriptor family) {
372
373 long ttl = family.getTimeToLive();
374 if (ttl == HConstants.FOREVER) {
375
376 ttl = Long.MAX_VALUE;
377 } else if (ttl == -1) {
378 ttl = Long.MAX_VALUE;
379 } else {
380
381 ttl *= 1000;
382 }
383 return ttl;
384 }
385
386 @Override
387 public String getColumnFamilyName() {
388 return this.family.getNameAsString();
389 }
390
391 @Override
392 public TableName getTableName() {
393 return this.getRegionInfo().getTable();
394 }
395
396 @Override
397 public FileSystem getFileSystem() {
398 return this.fs.getFileSystem();
399 }
400
401 public HRegionFileSystem getRegionFileSystem() {
402 return this.fs;
403 }
404
405
406 @Override
407 public long getStoreFileTtl() {
408
409 return (this.scanInfo.getMinVersions() == 0) ? this.scanInfo.getTtl() : Long.MAX_VALUE;
410 }
411
412 @Override
413 public long getMemstoreFlushSize() {
414
415 return this.region.memstoreFlushSize;
416 }
417
418 @Override
419 public long getFlushableSize() {
420 return this.memstore.getFlushableSize();
421 }
422
423 @Override
424 public long getSnapshotSize() {
425 return this.memstore.getSnapshotSize();
426 }
427
428 @Override
429 public long getCompactionCheckMultiplier() {
430 return this.compactionCheckMultiplier;
431 }
432
433 @Override
434 public long getBlockingFileCount() {
435 return blockingFileCount;
436 }
437
438
439
440
441
442
443
444 public static int getBytesPerChecksum(Configuration conf) {
445 return conf.getInt(HConstants.BYTES_PER_CHECKSUM,
446 HFile.DEFAULT_BYTES_PER_CHECKSUM);
447 }
448
449
450
451
452
453
454 public static ChecksumType getChecksumType(Configuration conf) {
455 String checksumName = conf.get(HConstants.CHECKSUM_TYPE_NAME);
456 if (checksumName == null) {
457 return ChecksumType.getDefaultChecksumType();
458 } else {
459 return ChecksumType.nameToType(checksumName);
460 }
461 }
462
463
464
465
466 public static int getCloseCheckInterval() {
467 return closeCheckInterval;
468 }
469
470 @Override
471 public HColumnDescriptor getFamily() {
472 return this.family;
473 }
474
475
476
477
478 @Override
479 public long getMaxSequenceId() {
480 return StoreFile.getMaxSequenceIdInList(this.getStorefiles());
481 }
482
483 @Override
484 public long getMaxMemstoreTS() {
485 return StoreFile.getMaxMemstoreTSInList(this.getStorefiles());
486 }
487
488
489
490
491
492
493
494 @Deprecated
495 public static Path getStoreHomedir(final Path tabledir,
496 final HRegionInfo hri, final byte[] family) {
497 return getStoreHomedir(tabledir, hri.getEncodedName(), family);
498 }
499
500
501
502
503
504
505
506 @Deprecated
507 public static Path getStoreHomedir(final Path tabledir,
508 final String encodedName, final byte[] family) {
509 return new Path(tabledir, new Path(encodedName, Bytes.toString(family)));
510 }
511
512 @Override
513 public HFileDataBlockEncoder getDataBlockEncoder() {
514 return dataBlockEncoder;
515 }
516
517
518
519
520
521 void setDataBlockEncoderInTest(HFileDataBlockEncoder blockEncoder) {
522 this.dataBlockEncoder = blockEncoder;
523 }
524
525
526
527
528
529
530 private List<StoreFile> loadStoreFiles() throws IOException {
531 Collection<StoreFileInfo> files = fs.getStoreFiles(getColumnFamilyName());
532 return openStoreFiles(files);
533 }
534
535 private List<StoreFile> openStoreFiles(Collection<StoreFileInfo> files) throws IOException {
536 if (files == null || files.size() == 0) {
537 return new ArrayList<StoreFile>();
538 }
539
540 ThreadPoolExecutor storeFileOpenerThreadPool =
541 this.region.getStoreFileOpenAndCloseThreadPool("StoreFileOpenerThread-" +
542 this.getColumnFamilyName());
543 CompletionService<StoreFile> completionService =
544 new ExecutorCompletionService<StoreFile>(storeFileOpenerThreadPool);
545
546 int totalValidStoreFile = 0;
547 for (final StoreFileInfo storeFileInfo: files) {
548
549 completionService.submit(new Callable<StoreFile>() {
550 @Override
551 public StoreFile call() throws IOException {
552 StoreFile storeFile = createStoreFileAndReader(storeFileInfo);
553 return storeFile;
554 }
555 });
556 totalValidStoreFile++;
557 }
558
559 Set<String> compactedStoreFiles = new HashSet<>();
560 ArrayList<StoreFile> results = new ArrayList<StoreFile>(files.size());
561 IOException ioe = null;
562 try {
563 for (int i = 0; i < totalValidStoreFile; i++) {
564 try {
565 Future<StoreFile> future = completionService.take();
566 StoreFile storeFile = future.get();
567 if (storeFile != null) {
568 if (LOG.isDebugEnabled()) {
569 LOG.debug("loaded " + storeFile.toStringDetailed());
570 }
571 results.add(storeFile);
572 compactedStoreFiles.addAll(storeFile.getCompactedStoreFiles());
573 }
574 } catch (InterruptedException e) {
575 if (ioe == null) ioe = new InterruptedIOException(e.getMessage());
576 } catch (ExecutionException e) {
577 if (ioe == null) ioe = new IOException(e.getCause());
578 }
579 }
580 } finally {
581 storeFileOpenerThreadPool.shutdownNow();
582 }
583 if (ioe != null) {
584
585 boolean evictOnClose =
586 cacheConf != null? cacheConf.shouldEvictOnClose(): true;
587 for (StoreFile file : results) {
588 try {
589 if (file != null) file.closeReader(evictOnClose);
590 } catch (IOException e) {
591 LOG.warn(e.getMessage());
592 }
593 }
594 throw ioe;
595 }
596
597
598 List<StoreFile> filesToRemove = new ArrayList<>(compactedStoreFiles.size());
599 for (StoreFile storeFile : results) {
600 if (compactedStoreFiles.contains(storeFile.getPath().getName())) {
601 LOG.warn("Clearing the compacted storefile " + storeFile + " from this store");
602 storeFile.getReader().close(true);
603 filesToRemove.add(storeFile);
604 }
605 }
606 results.removeAll(filesToRemove);
607 if (!filesToRemove.isEmpty() && this.isPrimaryReplicaStore()) {
608 LOG.debug("Moving the files " + filesToRemove + " to archive");
609 this.fs.removeStoreFiles(this.getColumnFamilyName(), filesToRemove);
610 }
611
612 return results;
613 }
614
615
616
617
618
619
620
621
622 @Override
623 public void refreshStoreFiles() throws IOException {
624 Collection<StoreFileInfo> newFiles = fs.getStoreFiles(getColumnFamilyName());
625 refreshStoreFilesInternal(newFiles);
626 }
627
628 @Override
629 public void refreshStoreFiles(Collection<String> newFiles) throws IOException {
630 List<StoreFileInfo> storeFiles = new ArrayList<StoreFileInfo>(newFiles.size());
631 for (String file : newFiles) {
632 storeFiles.add(fs.getStoreFileInfo(getColumnFamilyName(), file));
633 }
634 refreshStoreFilesInternal(storeFiles);
635 }
636
637
638
639
640
641
642
643
644 private void refreshStoreFilesInternal(Collection<StoreFileInfo> newFiles) throws IOException {
645 StoreFileManager sfm = storeEngine.getStoreFileManager();
646 Collection<StoreFile> currentFiles = sfm.getStorefiles();
647 Collection<StoreFile> compactedFiles = sfm.getCompactedfiles();
648 if (currentFiles == null) currentFiles = Collections.emptySet();
649 if (newFiles == null) newFiles = Collections.emptySet();
650 if (compactedFiles == null) compactedFiles = Collections.emptySet();
651
652 HashMap<StoreFileInfo, StoreFile> currentFilesSet =
653 new HashMap<StoreFileInfo, StoreFile>(currentFiles.size());
654 for (StoreFile sf : currentFiles) {
655 currentFilesSet.put(sf.getFileInfo(), sf);
656 }
657 HashMap<StoreFileInfo, StoreFile> compactedFilesSet =
658 new HashMap<StoreFileInfo, StoreFile>(compactedFiles.size());
659 for (StoreFile sf : compactedFiles) {
660 compactedFilesSet.put(sf.getFileInfo(), sf);
661 }
662
663 Set<StoreFileInfo> newFilesSet = new HashSet<StoreFileInfo>(newFiles);
664
665 newFilesSet = Sets.difference(newFilesSet, compactedFilesSet.keySet());
666 Set<StoreFileInfo> toBeAddedFiles = Sets.difference(newFilesSet, currentFilesSet.keySet());
667 Set<StoreFileInfo> toBeRemovedFiles = Sets.difference(currentFilesSet.keySet(), newFilesSet);
668
669 if (toBeAddedFiles.isEmpty() && toBeRemovedFiles.isEmpty()) {
670 return;
671 }
672
673 LOG.info("Refreshing store files for region " + this.getRegionInfo().getRegionNameAsString()
674 + " files to add: " + toBeAddedFiles + " files to remove: " + toBeRemovedFiles);
675
676 Set<StoreFile> toBeRemovedStoreFiles = new HashSet<StoreFile>(toBeRemovedFiles.size());
677 for (StoreFileInfo sfi : toBeRemovedFiles) {
678 toBeRemovedStoreFiles.add(currentFilesSet.get(sfi));
679 }
680
681
682 List<StoreFile> openedFiles = openStoreFiles(toBeAddedFiles);
683
684
685 replaceStoreFiles(toBeRemovedStoreFiles, openedFiles);
686
687
688
689
690 if (!toBeAddedFiles.isEmpty()) {
691 region.getMVCC().advanceTo(this.getMaxSequenceId());
692 }
693
694 completeCompaction(toBeRemovedStoreFiles);
695 }
696
697 private StoreFile createStoreFileAndReader(final Path p) throws IOException {
698 StoreFileInfo info = new StoreFileInfo(conf, this.getFileSystem(), p);
699 return createStoreFileAndReader(info);
700 }
701
702 private StoreFile createStoreFileAndReader(final StoreFileInfo info)
703 throws IOException {
704 info.setRegionCoprocessorHost(this.region.getCoprocessorHost());
705 StoreFile storeFile = new StoreFile(this.getFileSystem(), info, this.conf, this.cacheConf,
706 this.family.getBloomFilterType());
707 StoreFile.Reader r = storeFile.createReader();
708 r.setReplicaStoreFile(isPrimaryReplicaStore());
709 return storeFile;
710 }
711
712 @Override
713 public long add(final Cell cell) {
714 lock.readLock().lock();
715 try {
716 return this.memstore.add(cell);
717 } finally {
718 lock.readLock().unlock();
719 }
720 }
721
722 @Override
723 public long add(Iterable<Cell> cells) {
724 lock.readLock().lock();
725 try {
726 return this.memstore.add(cells);
727 } finally {
728 lock.readLock().unlock();
729 }
730 }
731
732 @Override
733 public long timeOfOldestEdit() {
734 return memstore.timeOfOldestEdit();
735 }
736
737
738
739
740
741
742
743 protected long delete(final KeyValue kv) {
744 lock.readLock().lock();
745 try {
746 return this.memstore.delete(kv);
747 } finally {
748 lock.readLock().unlock();
749 }
750 }
751
752 @Override
753 public void rollback(final Cell cell) {
754 lock.readLock().lock();
755 try {
756 this.memstore.rollback(cell);
757 } finally {
758 lock.readLock().unlock();
759 }
760 }
761
762
763
764
765 @Override
766 public Collection<StoreFile> getStorefiles() {
767 return this.storeEngine.getStoreFileManager().getStorefiles();
768 }
769
770 public Collection<StoreFile> getCompactedfiles() {
771 Collection<StoreFile> compactedFiles =
772 this.storeEngine.getStoreFileManager().getCompactedfiles();
773 return compactedFiles == null ? new ArrayList<StoreFile>() : compactedFiles;
774 }
775
776 @Override
777 public void assertBulkLoadHFileOk(Path srcPath) throws IOException {
778 HFile.Reader reader = null;
779 try {
780 LOG.info("Validating hfile at " + srcPath + " for inclusion in "
781 + "store " + this + " region " + this.getRegionInfo().getRegionNameAsString());
782 reader = HFile.createReader(srcPath.getFileSystem(conf),
783 srcPath, cacheConf, conf);
784 reader.loadFileInfo();
785
786 byte[] firstKey = reader.getFirstRowKey();
787 Preconditions.checkState(firstKey != null, "First key can not be null");
788 byte[] lk = reader.getLastKey();
789 Preconditions.checkState(lk != null, "Last key can not be null");
790 byte[] lastKey = KeyValue.createKeyValueFromKey(lk).getRow();
791
792 LOG.debug("HFile bounds: first=" + Bytes.toStringBinary(firstKey) +
793 " last=" + Bytes.toStringBinary(lastKey));
794 LOG.debug("Region bounds: first=" +
795 Bytes.toStringBinary(getRegionInfo().getStartKey()) +
796 " last=" + Bytes.toStringBinary(getRegionInfo().getEndKey()));
797
798 if (!this.getRegionInfo().containsRange(firstKey, lastKey)) {
799 throw new WrongRegionException(
800 "Bulk load file " + srcPath.toString() + " does not fit inside region "
801 + this.getRegionInfo().getRegionNameAsString());
802 }
803
804 if(reader.length() > conf.getLong(HConstants.HREGION_MAX_FILESIZE,
805 HConstants.DEFAULT_MAX_FILE_SIZE)) {
806 LOG.warn("Trying to bulk load hfile " + srcPath.toString() + " with size: " +
807 reader.length() + " bytes can be problematic as it may lead to oversplitting.");
808 }
809
810 if (verifyBulkLoads) {
811 long verificationStartTime = EnvironmentEdgeManager.currentTime();
812 LOG.info("Full verification started for bulk load hfile: " + srcPath.toString());
813 Cell prevCell = null;
814 HFileScanner scanner = reader.getScanner(false, false, false);
815 scanner.seekTo();
816 do {
817 Cell cell = scanner.getKeyValue();
818 if (prevCell != null) {
819 if (CellComparator.compareRows(prevCell, cell) > 0) {
820 throw new InvalidHFileException("Previous row is greater than"
821 + " current row: path=" + srcPath + " previous="
822 + CellUtil.getCellKeyAsString(prevCell) + " current="
823 + CellUtil.getCellKeyAsString(cell));
824 }
825 if (CellComparator.compareFamilies(prevCell, cell) != 0) {
826 throw new InvalidHFileException("Previous key had different"
827 + " family compared to current key: path=" + srcPath
828 + " previous="
829 + Bytes.toStringBinary(prevCell.getFamilyArray(), prevCell.getFamilyOffset(),
830 prevCell.getFamilyLength())
831 + " current="
832 + Bytes.toStringBinary(cell.getFamilyArray(), cell.getFamilyOffset(),
833 cell.getFamilyLength()));
834 }
835 }
836 prevCell = cell;
837 } while (scanner.next());
838 LOG.info("Full verification complete for bulk load hfile: " + srcPath.toString()
839 + " took " + (EnvironmentEdgeManager.currentTime() - verificationStartTime)
840 + " ms");
841 }
842 } finally {
843 if (reader != null) reader.close();
844 }
845 }
846
847 public Pair<Path, Path> preBulkLoadHFile(String srcPathStr, long seqNum) throws IOException {
848 Path srcPath = new Path(srcPathStr);
849 return fs.bulkLoadStoreFile(getColumnFamilyName(), srcPath, seqNum);
850 }
851
852 @Override
853 public Path bulkLoadHFile(byte[] family, String srcPathStr, Path dstPath) throws IOException {
854 Path srcPath = new Path(srcPathStr);
855 try {
856 fs.commitStoreFile(srcPath, dstPath);
857 } finally {
858 if (this.getCoprocessorHost() != null) {
859 this.getCoprocessorHost().postCommitStoreFile(family, srcPath, dstPath);
860 }
861 }
862
863 LOG.info("Loaded HFile " + srcPath + " into store '" + getColumnFamilyName() + "' as "
864 + dstPath + " - updating store file list.");
865
866 StoreFile sf = createStoreFileAndReader(dstPath);
867 bulkLoadHFile(sf);
868
869 LOG.info("Successfully loaded store file " + srcPath + " into store " + this
870 + " (new location: " + dstPath + ")");
871
872 return dstPath;
873 }
874
875 @Override
876 public void bulkLoadHFile(StoreFileInfo fileInfo) throws IOException {
877 StoreFile sf = createStoreFileAndReader(fileInfo);
878 bulkLoadHFile(sf);
879 }
880
881 private void bulkLoadHFile(StoreFile sf) throws IOException {
882 StoreFile.Reader r = sf.getReader();
883 this.storeSize.addAndGet(r.length());
884 this.totalUncompressedBytes.addAndGet(r.getTotalUncompressedBytes());
885
886
887 this.lock.writeLock().lock();
888 try {
889 this.storeEngine.getStoreFileManager().insertNewFiles(Lists.newArrayList(sf));
890 } finally {
891
892
893
894
895
896 this.lock.writeLock().unlock();
897 }
898 LOG.info("Loaded HFile " + sf.getFileInfo() + " into store '" + getColumnFamilyName());
899 if (LOG.isTraceEnabled()) {
900 String traceMessage = "BULK LOAD time,size,store size,store files ["
901 + EnvironmentEdgeManager.currentTime() + "," + r.length() + "," + storeSize
902 + "," + storeEngine.getStoreFileManager().getStorefileCount() + "]";
903 LOG.trace(traceMessage);
904 }
905 }
906
907 @Override
908 public ImmutableCollection<StoreFile> close() throws IOException {
909 this.archiveLock.lock();
910 this.lock.writeLock().lock();
911 try {
912
913 ImmutableCollection<StoreFile> result = storeEngine.getStoreFileManager().clearFiles();
914 Collection<StoreFile> compactedfiles =
915 storeEngine.getStoreFileManager().clearCompactedFiles();
916
917 if (compactedfiles != null && !compactedfiles.isEmpty()) {
918 removeCompactedfiles(compactedfiles);
919 }
920 if (!result.isEmpty()) {
921
922 ThreadPoolExecutor storeFileCloserThreadPool = this.region
923 .getStoreFileOpenAndCloseThreadPool("StoreFileCloserThread-"
924 + this.getColumnFamilyName());
925
926
927 CompletionService<Void> completionService =
928 new ExecutorCompletionService<Void>(storeFileCloserThreadPool);
929 for (final StoreFile f : result) {
930 completionService.submit(new Callable<Void>() {
931 @Override
932 public Void call() throws IOException {
933 boolean evictOnClose =
934 cacheConf != null? cacheConf.shouldEvictOnClose(): true;
935 f.closeReader(evictOnClose);
936 return null;
937 }
938 });
939 }
940
941 IOException ioe = null;
942 try {
943 for (int i = 0; i < result.size(); i++) {
944 try {
945 Future<Void> future = completionService.take();
946 future.get();
947 } catch (InterruptedException e) {
948 if (ioe == null) {
949 ioe = new InterruptedIOException();
950 ioe.initCause(e);
951 }
952 } catch (ExecutionException e) {
953 if (ioe == null) ioe = new IOException(e.getCause());
954 }
955 }
956 } finally {
957 storeFileCloserThreadPool.shutdownNow();
958 }
959 if (ioe != null) throw ioe;
960 }
961 LOG.info("Closed " + this);
962 return result;
963 } finally {
964 this.lock.writeLock().unlock();
965 this.archiveLock.unlock();
966 }
967 }
968
969
970
971
972
973
974 void snapshot() {
975 this.lock.writeLock().lock();
976 try {
977 this.memstore.snapshot();
978 } finally {
979 this.lock.writeLock().unlock();
980 }
981 }
982
983
984
985
986
987
988
989
990
991
992 protected List<Path> flushCache(final long logCacheFlushId, MemStoreSnapshot snapshot,
993 MonitoredTask status, ThroughputController throughputController) throws IOException {
994
995
996
997
998
999 StoreFlusher flusher = storeEngine.getStoreFlusher();
1000 IOException lastException = null;
1001 for (int i = 0; i < flushRetriesNumber; i++) {
1002 try {
1003 List<Path> pathNames =
1004 flusher.flushSnapshot(snapshot, logCacheFlushId, status, throughputController);
1005 Path lastPathName = null;
1006 try {
1007 for (Path pathName : pathNames) {
1008 lastPathName = pathName;
1009 validateStoreFile(pathName);
1010 }
1011 return pathNames;
1012 } catch (Exception e) {
1013 LOG.warn("Failed validating store file " + lastPathName + ", retrying num=" + i, e);
1014 if (e instanceof IOException) {
1015 lastException = (IOException) e;
1016 } else {
1017 lastException = new IOException(e);
1018 }
1019 }
1020 } catch (IOException e) {
1021 LOG.warn("Failed flushing store file, retrying num=" + i, e);
1022 lastException = e;
1023 }
1024 if (lastException != null && i < (flushRetriesNumber - 1)) {
1025 try {
1026 Thread.sleep(pauseTime);
1027 } catch (InterruptedException e) {
1028 IOException iie = new InterruptedIOException();
1029 iie.initCause(e);
1030 throw iie;
1031 }
1032 }
1033 }
1034 throw lastException;
1035 }
1036
1037
1038
1039
1040
1041
1042
1043
1044 private StoreFile commitFile(final Path path, final long logCacheFlushId, MonitoredTask status)
1045 throws IOException {
1046
1047 Path dstPath = fs.commitStoreFile(getColumnFamilyName(), path);
1048
1049 status.setStatus("Flushing " + this + ": reopening flushed file");
1050 StoreFile sf = createStoreFileAndReader(dstPath);
1051
1052 StoreFile.Reader r = sf.getReader();
1053 this.storeSize.addAndGet(r.length());
1054 this.totalUncompressedBytes.addAndGet(r.getTotalUncompressedBytes());
1055
1056 if (LOG.isInfoEnabled()) {
1057 LOG.info("Added " + sf + ", entries=" + r.getEntries() +
1058 ", sequenceid=" + logCacheFlushId +
1059 ", filesize=" + TraditionalBinaryPrefix.long2String(r.length(), "", 1));
1060 }
1061 return sf;
1062 }
1063
1064 @Override
1065 public StoreFile.Writer createWriterInTmp(long maxKeyCount, Compression.Algorithm compression,
1066 boolean isCompaction, boolean includeMVCCReadpoint,
1067 boolean includesTag)
1068 throws IOException {
1069 return createWriterInTmp(maxKeyCount, compression, isCompaction, includeMVCCReadpoint,
1070 includesTag, false);
1071 }
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081 @Override
1082 public StoreFile.Writer createWriterInTmp(long maxKeyCount, Compression.Algorithm compression,
1083 boolean isCompaction, boolean includeMVCCReadpoint, boolean includesTag,
1084 boolean shouldDropBehind)
1085 throws IOException {
1086 return createWriterInTmp(maxKeyCount, compression, isCompaction, includeMVCCReadpoint,
1087 includesTag, shouldDropBehind, null);
1088 }
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098 @Override
1099 public StoreFile.Writer createWriterInTmp(long maxKeyCount, Compression.Algorithm compression,
1100 boolean isCompaction, boolean includeMVCCReadpoint, boolean includesTag,
1101 boolean shouldDropBehind, final TimeRangeTracker trt)
1102 throws IOException {
1103 final CacheConfig writerCacheConf;
1104 if (isCompaction) {
1105
1106 writerCacheConf = new CacheConfig(cacheConf);
1107 writerCacheConf.setCacheDataOnWrite(false);
1108 } else {
1109 writerCacheConf = cacheConf;
1110 }
1111 InetSocketAddress[] favoredNodes = null;
1112 if (region.getRegionServerServices() != null) {
1113 favoredNodes = region.getRegionServerServices().getFavoredNodesForRegion(
1114 region.getRegionInfo().getEncodedName());
1115 }
1116 HFileContext hFileContext = createFileContext(compression, includeMVCCReadpoint, includesTag,
1117 cryptoContext);
1118 StoreFile.WriterBuilder builder = new StoreFile.WriterBuilder(conf, writerCacheConf,
1119 this.getFileSystem())
1120 .withFilePath(fs.createTempName())
1121 .withComparator(comparator)
1122 .withBloomType(family.getBloomFilterType())
1123 .withMaxKeyCount(maxKeyCount)
1124 .withFavoredNodes(favoredNodes)
1125 .withFileContext(hFileContext)
1126 .withShouldDropCacheBehind(shouldDropBehind)
1127 .withCompactedFiles(this.getCompactedfiles());
1128 if (trt != null) {
1129 builder.withTimeRangeTracker(trt);
1130 }
1131 return builder.build();
1132 }
1133
1134 private HFileContext createFileContext(Compression.Algorithm compression,
1135 boolean includeMVCCReadpoint, boolean includesTag, Encryption.Context cryptoContext) {
1136 if (compression == null) {
1137 compression = HFile.DEFAULT_COMPRESSION_ALGORITHM;
1138 }
1139 HFileContext hFileContext = new HFileContextBuilder()
1140 .withIncludesMvcc(includeMVCCReadpoint)
1141 .withIncludesTags(includesTag)
1142 .withCompression(compression)
1143 .withCompressTags(family.isCompressTags())
1144 .withChecksumType(checksumType)
1145 .withBytesPerCheckSum(bytesPerChecksum)
1146 .withBlockSize(blocksize)
1147 .withHBaseCheckSum(true)
1148 .withDataBlockEncoding(family.getDataBlockEncoding())
1149 .withEncryptionContext(cryptoContext)
1150 .withCreateTime(EnvironmentEdgeManager.currentTime())
1151 .build();
1152 return hFileContext;
1153 }
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163 private boolean updateStorefiles(final List<StoreFile> sfs, final long snapshotId)
1164 throws IOException {
1165 this.lock.writeLock().lock();
1166 try {
1167 this.storeEngine.getStoreFileManager().insertNewFiles(sfs);
1168 if (snapshotId > 0) {
1169 this.memstore.clearSnapshot(snapshotId);
1170 }
1171 } finally {
1172
1173
1174
1175
1176
1177 this.lock.writeLock().unlock();
1178 }
1179
1180 notifyChangedReadersObservers(sfs);
1181 if (LOG.isTraceEnabled()) {
1182 long totalSize = 0;
1183 for (StoreFile sf : sfs) {
1184 totalSize += sf.getReader().length();
1185 }
1186 String traceMessage = "FLUSH time,count,size,store size,store files ["
1187 + EnvironmentEdgeManager.currentTime() + "," + sfs.size() + "," + totalSize
1188 + "," + storeSize + "," + storeEngine.getStoreFileManager().getStorefileCount() + "]";
1189 LOG.trace(traceMessage);
1190 }
1191 return needsCompaction();
1192 }
1193
1194
1195
1196
1197
1198 private void notifyChangedReadersObservers(List<StoreFile> sfs) throws IOException {
1199 for (ChangedReadersObserver o : this.changedReaderObservers) {
1200 List<KeyValueScanner> memStoreScanners;
1201 this.lock.readLock().lock();
1202 try {
1203 memStoreScanners = this.memstore.getScanners(o.getReadPoint());
1204 } finally {
1205 this.lock.readLock().unlock();
1206 }
1207 o.updateReaders(sfs, memStoreScanners);
1208 }
1209 }
1210
1211
1212
1213
1214
1215
1216 @Override
1217 public List<KeyValueScanner> getScanners(boolean cacheBlocks, boolean isGet,
1218 boolean usePread, boolean isCompaction, ScanQueryMatcher matcher, byte[] startRow,
1219 byte[] stopRow, long readPt) throws IOException {
1220 Collection<StoreFile> storeFilesToScan;
1221 List<KeyValueScanner> memStoreScanners;
1222 this.lock.readLock().lock();
1223 try {
1224
1225
1226
1227
1228
1229 storeFilesToScan = this.storeEngine.getStoreFileManager().getFilesForScanOrGet(startRow, true,
1230 stopRow, true);
1231 memStoreScanners = this.memstore.getScanners(readPt);
1232 } finally {
1233 this.lock.readLock().unlock();
1234 }
1235
1236
1237
1238
1239
1240
1241 List<StoreFileScanner> sfScanners = StoreFileScanner.getScannersForStoreFiles(storeFilesToScan,
1242 cacheBlocks, usePread, isCompaction, false, matcher, readPt, isPrimaryReplicaStore());
1243 List<KeyValueScanner> scanners =
1244 new ArrayList<KeyValueScanner>(sfScanners.size()+1);
1245 scanners.addAll(sfScanners);
1246
1247 if (memStoreScanners != null) {
1248 scanners.addAll(memStoreScanners);
1249 }
1250 return scanners;
1251 }
1252
1253 @Override
1254 public List<KeyValueScanner> getScanners(List<StoreFile> files, boolean cacheBlocks,
1255 boolean isGet, boolean usePread, boolean isCompaction, ScanQueryMatcher matcher,
1256 byte[] startRow, byte[] stopRow, long readPt, boolean includeMemstoreScanner) throws IOException {
1257 List<KeyValueScanner> memStoreScanners = null;
1258 if (includeMemstoreScanner) {
1259 this.lock.readLock().lock();
1260 try {
1261 memStoreScanners = this.memstore.getScanners(readPt);
1262 } finally {
1263 this.lock.readLock().unlock();
1264 }
1265 }
1266 List<StoreFileScanner> sfScanners = StoreFileScanner.getScannersForStoreFiles(files,
1267 cacheBlocks, usePread, isCompaction, false, matcher, readPt, isPrimaryReplicaStore());
1268 List<KeyValueScanner> scanners = new ArrayList<KeyValueScanner>(sfScanners.size() + 1);
1269 scanners.addAll(sfScanners);
1270
1271 if (memStoreScanners != null) {
1272 scanners.addAll(memStoreScanners);
1273 }
1274 return scanners;
1275 }
1276
1277 @Override
1278 public void addChangedReaderObserver(ChangedReadersObserver o) {
1279 this.changedReaderObservers.add(o);
1280 }
1281
1282 @Override
1283 public void deleteChangedReaderObserver(ChangedReadersObserver o) {
1284
1285 this.changedReaderObservers.remove(o);
1286 }
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335 @Override
1336 public List<StoreFile> compact(CompactionContext compaction,
1337 ThroughputController throughputController) throws IOException {
1338 return compact(compaction, throughputController, null);
1339 }
1340
1341 @Override
1342 public List<StoreFile> compact(CompactionContext compaction,
1343 ThroughputController throughputController, User user) throws IOException {
1344 assert compaction != null;
1345 List<StoreFile> sfs = null;
1346 CompactionRequest cr = compaction.getRequest();
1347 try {
1348
1349
1350
1351 long compactionStartTime = EnvironmentEdgeManager.currentTime();
1352 assert compaction.hasSelection();
1353 Collection<StoreFile> filesToCompact = cr.getFiles();
1354 assert !filesToCompact.isEmpty();
1355 synchronized (filesCompacting) {
1356
1357
1358 Preconditions.checkArgument(filesCompacting.containsAll(filesToCompact));
1359 }
1360
1361
1362 LOG.info("Starting compaction of " + filesToCompact.size() + " file(s) in "
1363 + this + " of " + this.getRegionInfo().getRegionNameAsString()
1364 + " into tmpdir=" + fs.getTempDir() + ", totalSize="
1365 + TraditionalBinaryPrefix.long2String(cr.getSize(), "", 1));
1366
1367
1368 List<Path> newFiles = compaction.compact(throughputController, user);
1369
1370 long outputBytes = 0L;
1371
1372 if (!this.conf.getBoolean("hbase.hstore.compaction.complete", true)) {
1373 LOG.warn("hbase.hstore.compaction.complete is set to false");
1374 sfs = new ArrayList<StoreFile>(newFiles.size());
1375 final boolean evictOnClose =
1376 cacheConf != null? cacheConf.shouldEvictOnClose(): true;
1377 for (Path newFile : newFiles) {
1378
1379 StoreFile sf = createStoreFileAndReader(newFile);
1380 sf.closeReader(evictOnClose);
1381 sfs.add(sf);
1382 }
1383 return sfs;
1384 }
1385
1386 sfs = moveCompatedFilesIntoPlace(cr, newFiles, user);
1387 writeCompactionWalRecord(filesToCompact, sfs);
1388 replaceStoreFiles(filesToCompact, sfs);
1389 if (cr.isMajor()) {
1390 majorCompactedCellsCount.addAndGet(getCompactionProgress().totalCompactingKVs);
1391 majorCompactedCellsSize.addAndGet(getCompactionProgress().totalCompactedSize);
1392 } else {
1393 compactedCellsCount.addAndGet(getCompactionProgress().totalCompactingKVs);
1394 compactedCellsSize.addAndGet(getCompactionProgress().totalCompactedSize);
1395 }
1396
1397 for (StoreFile sf : sfs) {
1398 outputBytes += sf.getReader().length();
1399 }
1400
1401
1402 completeCompaction(filesToCompact);
1403
1404 long now = EnvironmentEdgeManager.currentTime();
1405 if (region.getRegionServerServices() != null
1406 && region.getRegionServerServices().getMetrics() != null) {
1407 region.getRegionServerServices().getMetrics().updateCompaction(cr.isMajor(),
1408 now - compactionStartTime, cr.getFiles().size(), newFiles.size(), cr.getSize(),
1409 outputBytes);
1410 }
1411
1412 logCompactionEndMessage(cr, sfs, now, compactionStartTime);
1413 return sfs;
1414 } finally {
1415 finishCompactionRequest(cr);
1416 }
1417 }
1418
1419 private List<StoreFile> moveCompatedFilesIntoPlace(
1420 final CompactionRequest cr, List<Path> newFiles, User user) throws IOException {
1421 List<StoreFile> sfs = new ArrayList<StoreFile>(newFiles.size());
1422 for (Path newFile : newFiles) {
1423 assert newFile != null;
1424 final StoreFile sf = moveFileIntoPlace(newFile);
1425 if (this.getCoprocessorHost() != null) {
1426 final Store thisStore = this;
1427 if (user == null) {
1428 getCoprocessorHost().postCompact(thisStore, sf, cr);
1429 } else {
1430 try {
1431 user.getUGI().doAs(new PrivilegedExceptionAction<Void>() {
1432 @Override
1433 public Void run() throws Exception {
1434 getCoprocessorHost().postCompact(thisStore, sf, cr);
1435 return null;
1436 }
1437 });
1438 } catch (InterruptedException ie) {
1439 InterruptedIOException iioe = new InterruptedIOException();
1440 iioe.initCause(ie);
1441 throw iioe;
1442 }
1443 }
1444 }
1445 assert sf != null;
1446 sfs.add(sf);
1447 }
1448 return sfs;
1449 }
1450
1451
1452 StoreFile moveFileIntoPlace(final Path newFile) throws IOException {
1453 validateStoreFile(newFile);
1454
1455 Path destPath = fs.commitStoreFile(getColumnFamilyName(), newFile);
1456 return createStoreFileAndReader(destPath);
1457 }
1458
1459
1460
1461
1462
1463
1464 private void writeCompactionWalRecord(Collection<StoreFile> filesCompacted,
1465 Collection<StoreFile> newFiles) throws IOException {
1466 if (region.getWAL() == null) return;
1467 List<Path> inputPaths = new ArrayList<Path>(filesCompacted.size());
1468 for (StoreFile f : filesCompacted) {
1469 inputPaths.add(f.getPath());
1470 }
1471 List<Path> outputPaths = new ArrayList<Path>(newFiles.size());
1472 for (StoreFile f : newFiles) {
1473 outputPaths.add(f.getPath());
1474 }
1475 HRegionInfo info = this.region.getRegionInfo();
1476 CompactionDescriptor compactionDescriptor = ProtobufUtil.toCompactionDescriptor(info,
1477 family.getName(), inputPaths, outputPaths, fs.getStoreDir(getFamily().getNameAsString()));
1478 WALUtil.writeCompactionMarker(region.getWAL(), this.region.getTableDesc(),
1479 this.region.getRegionInfo(), compactionDescriptor, region.getMVCC());
1480 }
1481
1482 @VisibleForTesting
1483 void replaceStoreFiles(final Collection<StoreFile> compactedFiles,
1484 final Collection<StoreFile> result) throws IOException {
1485 this.lock.writeLock().lock();
1486 try {
1487 this.storeEngine.getStoreFileManager().addCompactionResults(compactedFiles, result);
1488 synchronized (filesCompacting) {
1489 filesCompacting.removeAll(compactedFiles);
1490 }
1491 } finally {
1492 this.lock.writeLock().unlock();
1493 }
1494 }
1495
1496
1497
1498
1499
1500
1501
1502 private void logCompactionEndMessage(
1503 CompactionRequest cr, List<StoreFile> sfs, long now, long compactionStartTime) {
1504 StringBuilder message = new StringBuilder(
1505 "Completed" + (cr.isMajor() ? " major" : "") + " compaction of "
1506 + cr.getFiles().size() + (cr.isAllFiles() ? " (all)" : "") + " file(s) in "
1507 + this + " of " + this.getRegionInfo().getRegionNameAsString() + " into ");
1508 if (sfs.isEmpty()) {
1509 message.append("none, ");
1510 } else {
1511 for (StoreFile sf: sfs) {
1512 message.append(sf.getPath().getName());
1513 message.append("(size=");
1514 message.append(TraditionalBinaryPrefix.long2String(sf.getReader().length(), "", 1));
1515 message.append("), ");
1516 }
1517 }
1518 message.append("total size for store is ")
1519 .append(StringUtils.TraditionalBinaryPrefix.long2String(storeSize.get(), "", 1))
1520 .append(". This selection was in queue for ")
1521 .append(StringUtils.formatTimeDiff(compactionStartTime, cr.getSelectionTime()))
1522 .append(", and took ").append(StringUtils.formatTimeDiff(now, compactionStartTime))
1523 .append(" to execute.");
1524 LOG.info(message.toString());
1525 if (LOG.isTraceEnabled()) {
1526 int fileCount = storeEngine.getStoreFileManager().getStorefileCount();
1527 long resultSize = 0;
1528 for (StoreFile sf : sfs) {
1529 resultSize += sf.getReader().length();
1530 }
1531 String traceMessage = "COMPACTION start,end,size out,files in,files out,store size,"
1532 + "store files [" + compactionStartTime + "," + now + "," + resultSize + ","
1533 + cr.getFiles().size() + "," + sfs.size() + "," + storeSize + "," + fileCount + "]";
1534 LOG.trace(traceMessage);
1535 }
1536 }
1537
1538
1539
1540
1541
1542
1543
1544 @Override
1545 public void replayCompactionMarker(CompactionDescriptor compaction,
1546 boolean pickCompactionFiles, boolean removeFiles)
1547 throws IOException {
1548 LOG.debug("Completing compaction from the WAL marker");
1549 List<String> compactionInputs = compaction.getCompactionInputList();
1550 List<String> compactionOutputs = Lists.newArrayList(compaction.getCompactionOutputList());
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566 String familyName = this.getColumnFamilyName();
1567 List<String> inputFiles = new ArrayList<String>(compactionInputs.size());
1568 for (String compactionInput : compactionInputs) {
1569 Path inputPath = fs.getStoreFilePath(familyName, compactionInput);
1570 inputFiles.add(inputPath.getName());
1571 }
1572
1573
1574 List<StoreFile> inputStoreFiles = new ArrayList<StoreFile>(compactionInputs.size());
1575 for (StoreFile sf : this.getStorefiles()) {
1576 if (inputFiles.contains(sf.getPath().getName())) {
1577 inputStoreFiles.add(sf);
1578 }
1579 }
1580
1581
1582 List<StoreFile> outputStoreFiles = new ArrayList<StoreFile>(compactionOutputs.size());
1583
1584 if (pickCompactionFiles) {
1585 for (StoreFile sf : this.getStorefiles()) {
1586 compactionOutputs.remove(sf.getPath().getName());
1587 }
1588 for (String compactionOutput : compactionOutputs) {
1589 StoreFileInfo storeFileInfo = fs.getStoreFileInfo(getColumnFamilyName(), compactionOutput);
1590 StoreFile storeFile = createStoreFileAndReader(storeFileInfo);
1591 outputStoreFiles.add(storeFile);
1592 }
1593 }
1594
1595 if (!inputStoreFiles.isEmpty() || !outputStoreFiles.isEmpty()) {
1596 LOG.info("Replaying compaction marker, replacing input files: " +
1597 inputStoreFiles + " with output files : " + outputStoreFiles);
1598 this.replaceStoreFiles(inputStoreFiles, outputStoreFiles);
1599 this.completeCompaction(inputStoreFiles);
1600 }
1601 }
1602
1603
1604
1605
1606
1607
1608
1609
1610 public void compactRecentForTestingAssumingDefaultPolicy(int N) throws IOException {
1611 List<StoreFile> filesToCompact;
1612 boolean isMajor;
1613
1614 this.lock.readLock().lock();
1615 try {
1616 synchronized (filesCompacting) {
1617 filesToCompact = Lists.newArrayList(storeEngine.getStoreFileManager().getStorefiles());
1618 if (!filesCompacting.isEmpty()) {
1619
1620
1621 StoreFile last = filesCompacting.get(filesCompacting.size() - 1);
1622 int idx = filesToCompact.indexOf(last);
1623 Preconditions.checkArgument(idx != -1);
1624 filesToCompact.subList(0, idx + 1).clear();
1625 }
1626 int count = filesToCompact.size();
1627 if (N > count) {
1628 throw new RuntimeException("Not enough files");
1629 }
1630
1631 filesToCompact = filesToCompact.subList(count - N, count);
1632 isMajor = (filesToCompact.size() == storeEngine.getStoreFileManager().getStorefileCount());
1633 filesCompacting.addAll(filesToCompact);
1634 Collections.sort(filesCompacting, storeEngine.getStoreFileManager()
1635 .getStoreFileComparator());
1636 }
1637 } finally {
1638 this.lock.readLock().unlock();
1639 }
1640
1641 try {
1642
1643 List<Path> newFiles = ((DefaultCompactor)this.storeEngine.getCompactor())
1644 .compactForTesting(filesToCompact, isMajor);
1645 for (Path newFile: newFiles) {
1646
1647 StoreFile sf = moveFileIntoPlace(newFile);
1648 if (this.getCoprocessorHost() != null) {
1649 this.getCoprocessorHost().postCompact(this, sf, null);
1650 }
1651 replaceStoreFiles(filesToCompact, Lists.newArrayList(sf));
1652 completeCompaction(filesToCompact);
1653 }
1654 } finally {
1655 synchronized (filesCompacting) {
1656 filesCompacting.removeAll(filesToCompact);
1657 }
1658 }
1659 }
1660
1661 @Override
1662 public boolean hasReferences() {
1663
1664
1665 this.lock.readLock().lock();
1666 try {
1667
1668 Collection<StoreFile> allStoreFiles = new ArrayList<>(getStorefiles());
1669 allStoreFiles.addAll(getCompactedfiles());
1670 return StoreUtils.hasReferences(allStoreFiles);
1671 } finally {
1672 this.lock.readLock().unlock();
1673 }
1674 }
1675
1676 @Override
1677 public CompactionProgress getCompactionProgress() {
1678 return this.storeEngine.getCompactor().getProgress();
1679 }
1680
1681 @Override
1682 public boolean isMajorCompaction() throws IOException {
1683 for (StoreFile sf : this.storeEngine.getStoreFileManager().getStorefiles()) {
1684
1685 if (sf.getReader() == null) {
1686 LOG.debug("StoreFile " + sf + " has null Reader");
1687 return false;
1688 }
1689 }
1690 return storeEngine.getCompactionPolicy().shouldPerformMajorCompaction(
1691 this.storeEngine.getStoreFileManager().getStorefiles());
1692 }
1693
1694 @Override
1695 public CompactionContext requestCompaction() throws IOException {
1696 return requestCompaction(Store.NO_PRIORITY, null);
1697 }
1698
1699 @Override
1700 public CompactionContext requestCompaction(int priority, CompactionRequest baseRequest)
1701 throws IOException {
1702 return requestCompaction(priority, baseRequest, null);
1703 }
1704 @Override
1705 public CompactionContext requestCompaction(int priority, final CompactionRequest baseRequest,
1706 User user) throws IOException {
1707
1708 if (!this.areWritesEnabled()) {
1709 return null;
1710 }
1711
1712
1713 removeUnneededFiles();
1714
1715 final CompactionContext compaction = storeEngine.createCompaction();
1716 CompactionRequest request = null;
1717 this.lock.readLock().lock();
1718 try {
1719 synchronized (filesCompacting) {
1720 final Store thisStore = this;
1721
1722 if (this.getCoprocessorHost() != null) {
1723 final List<StoreFile> candidatesForCoproc = compaction.preSelect(this.filesCompacting);
1724 boolean override = false;
1725 if (user == null) {
1726 override = getCoprocessorHost().preCompactSelection(this, candidatesForCoproc,
1727 baseRequest);
1728 } else {
1729 try {
1730 override = user.getUGI().doAs(new PrivilegedExceptionAction<Boolean>() {
1731 @Override
1732 public Boolean run() throws Exception {
1733 return getCoprocessorHost().preCompactSelection(thisStore, candidatesForCoproc,
1734 baseRequest);
1735 }
1736 });
1737 } catch (InterruptedException ie) {
1738 InterruptedIOException iioe = new InterruptedIOException();
1739 iioe.initCause(ie);
1740 throw iioe;
1741 }
1742 }
1743 if (override) {
1744
1745 compaction.forceSelect(new CompactionRequest(candidatesForCoproc));
1746 }
1747 }
1748
1749
1750 if (!compaction.hasSelection()) {
1751 boolean isUserCompaction = priority == Store.PRIORITY_USER;
1752 boolean mayUseOffPeak = offPeakHours.isOffPeakHour() &&
1753 offPeakCompactionTracker.compareAndSet(false, true);
1754 try {
1755 compaction.select(this.filesCompacting, isUserCompaction,
1756 mayUseOffPeak, forceMajor && filesCompacting.isEmpty());
1757 } catch (IOException e) {
1758 if (mayUseOffPeak) {
1759 offPeakCompactionTracker.set(false);
1760 }
1761 throw e;
1762 }
1763 assert compaction.hasSelection();
1764 if (mayUseOffPeak && !compaction.getRequest().isOffPeak()) {
1765
1766 offPeakCompactionTracker.set(false);
1767 }
1768 }
1769 if (this.getCoprocessorHost() != null) {
1770 if (user == null) {
1771 this.getCoprocessorHost().postCompactSelection(
1772 this, ImmutableList.copyOf(compaction.getRequest().getFiles()), baseRequest);
1773 } else {
1774 try {
1775 user.getUGI().doAs(new PrivilegedExceptionAction<Void>() {
1776 @Override
1777 public Void run() throws Exception {
1778 getCoprocessorHost().postCompactSelection(
1779 thisStore,ImmutableList.copyOf(compaction.getRequest().getFiles()),baseRequest);
1780 return null;
1781 }
1782 });
1783 } catch (InterruptedException ie) {
1784 InterruptedIOException iioe = new InterruptedIOException();
1785 iioe.initCause(ie);
1786 throw iioe;
1787 }
1788 }
1789 }
1790
1791
1792 if (baseRequest != null) {
1793
1794
1795 compaction.forceSelect(
1796 baseRequest.combineWith(compaction.getRequest()));
1797 }
1798
1799 request = compaction.getRequest();
1800 final Collection<StoreFile> selectedFiles = request.getFiles();
1801 if (selectedFiles.isEmpty()) {
1802 return null;
1803 }
1804
1805 addToCompactingFiles(selectedFiles);
1806
1807
1808 this.forceMajor = this.forceMajor && !request.isMajor();
1809
1810
1811
1812 request.setPriority((priority != Store.NO_PRIORITY) ? priority : getCompactPriority());
1813 request.setDescription(getRegionInfo().getRegionNameAsString(), getColumnFamilyName());
1814 }
1815 } finally {
1816 this.lock.readLock().unlock();
1817 }
1818
1819 LOG.debug(getRegionInfo().getEncodedName() + " - " + getColumnFamilyName()
1820 + ": Initiating " + (request.isMajor() ? "major" : "minor") + " compaction"
1821 + (request.isAllFiles() ? " (all files)" : ""));
1822 this.region.reportCompactionRequestStart(request.isMajor());
1823 return compaction;
1824 }
1825
1826
1827 private void addToCompactingFiles(final Collection<StoreFile> filesToAdd) {
1828 if (filesToAdd == null) return;
1829
1830 if (!Collections.disjoint(filesCompacting, filesToAdd)) {
1831 Preconditions.checkArgument(false, "%s overlaps with %s", filesToAdd, filesCompacting);
1832 }
1833 filesCompacting.addAll(filesToAdd);
1834 Collections.sort(filesCompacting, storeEngine.getStoreFileManager().getStoreFileComparator());
1835 }
1836
1837 private void removeUnneededFiles() throws IOException {
1838 if (!conf.getBoolean("hbase.store.delete.expired.storefile", true)) return;
1839 if (getFamily().getMinVersions() > 0) {
1840 LOG.debug("Skipping expired store file removal due to min version being " +
1841 getFamily().getMinVersions());
1842 return;
1843 }
1844 this.lock.readLock().lock();
1845 Collection<StoreFile> delSfs = null;
1846 try {
1847 synchronized (filesCompacting) {
1848 long cfTtl = getStoreFileTtl();
1849 if (cfTtl != Long.MAX_VALUE) {
1850 delSfs = storeEngine.getStoreFileManager().getUnneededFiles(
1851 EnvironmentEdgeManager.currentTime() - cfTtl, filesCompacting);
1852 addToCompactingFiles(delSfs);
1853 }
1854 }
1855 } finally {
1856 this.lock.readLock().unlock();
1857 }
1858 if (delSfs == null || delSfs.isEmpty()) return;
1859
1860 Collection<StoreFile> newFiles = new ArrayList<StoreFile>();
1861 writeCompactionWalRecord(delSfs, newFiles);
1862 replaceStoreFiles(delSfs, newFiles);
1863 completeCompaction(delSfs);
1864 LOG.info("Completed removal of " + delSfs.size() + " unnecessary (expired) file(s) in "
1865 + this + " of " + this.getRegionInfo().getRegionNameAsString()
1866 + "; total size for store is " + TraditionalBinaryPrefix.long2String(storeSize.get(), "", 1));
1867 }
1868
1869 @Override
1870 public void cancelRequestedCompaction(CompactionContext compaction) {
1871 finishCompactionRequest(compaction.getRequest());
1872 }
1873
1874 private void finishCompactionRequest(CompactionRequest cr) {
1875 this.region.reportCompactionRequestEnd(cr.isMajor(), cr.getFiles().size(), cr.getSize());
1876 if (cr.isOffPeak()) {
1877 offPeakCompactionTracker.set(false);
1878 cr.setOffPeak(false);
1879 }
1880 synchronized (filesCompacting) {
1881 filesCompacting.removeAll(cr.getFiles());
1882 }
1883 }
1884
1885
1886
1887
1888
1889
1890
1891 private void validateStoreFile(Path path)
1892 throws IOException {
1893 StoreFile storeFile = null;
1894 try {
1895 storeFile = createStoreFileAndReader(path);
1896 } catch (IOException e) {
1897 LOG.error("Failed to open store file : " + path
1898 + ", keeping it in tmp location", e);
1899 throw e;
1900 } finally {
1901 if (storeFile != null) {
1902 storeFile.closeReader(false);
1903 }
1904 }
1905 }
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921 @VisibleForTesting
1922 protected void completeCompaction(final Collection<StoreFile> compactedFiles)
1923 throws IOException {
1924 completeCompaction(compactedFiles, true);
1925 }
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942 @VisibleForTesting
1943 protected void completeCompaction(final Collection<StoreFile> compactedFiles, boolean removeFiles)
1944 throws IOException {
1945 LOG.debug("Completing compaction...");
1946 this.storeSize.set(0L);
1947 this.totalUncompressedBytes.set(0L);
1948 for (StoreFile hsf : this.storeEngine.getStoreFileManager().getStorefiles()) {
1949 StoreFile.Reader r = hsf.getReader();
1950 if (r == null) {
1951 LOG.warn("StoreFile " + hsf + " has a null Reader");
1952 continue;
1953 }
1954 this.storeSize.addAndGet(r.length());
1955 this.totalUncompressedBytes.addAndGet(r.getTotalUncompressedBytes());
1956 }
1957 }
1958
1959
1960
1961
1962
1963 int versionsToReturn(final int wantedVersions) {
1964 if (wantedVersions <= 0) {
1965 throw new IllegalArgumentException("Number of versions must be > 0");
1966 }
1967
1968 int maxVersions = this.family.getMaxVersions();
1969 return wantedVersions > maxVersions ? maxVersions: wantedVersions;
1970 }
1971
1972
1973
1974
1975
1976
1977 public static boolean isCellTTLExpired(final Cell cell, final long oldestTimestamp, final long now) {
1978
1979
1980 if (cell.getTagsLength() > 0) {
1981
1982
1983
1984 Iterator<Tag> i = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(),
1985 cell.getTagsLength());
1986 while (i.hasNext()) {
1987 Tag t = i.next();
1988 if (TagType.TTL_TAG_TYPE == t.getType()) {
1989
1990
1991 long ts = cell.getTimestamp();
1992 assert t.getTagLength() == Bytes.SIZEOF_LONG;
1993 long ttl = Bytes.toLong(t.getBuffer(), t.getTagOffset(), t.getTagLength());
1994 if (ts + ttl < now) {
1995 return true;
1996 }
1997
1998
1999 break;
2000 }
2001 }
2002 }
2003 return false;
2004 }
2005
2006 @Override
2007 public Cell getRowKeyAtOrBefore(final byte[] row) throws IOException {
2008
2009
2010
2011
2012
2013
2014 long ttlToUse = scanInfo.getMinVersions() > 0 ? Long.MAX_VALUE : this.scanInfo.getTtl();
2015
2016 KeyValue kv = new KeyValue(row, HConstants.LATEST_TIMESTAMP);
2017
2018 GetClosestRowBeforeTracker state = new GetClosestRowBeforeTracker(
2019 this.comparator, kv, ttlToUse, this.getRegionInfo().isMetaRegion());
2020 this.lock.readLock().lock();
2021 try {
2022
2023 this.memstore.getRowKeyAtOrBefore(state);
2024
2025
2026 Iterator<StoreFile> sfIterator = this.storeEngine.getStoreFileManager()
2027 .getCandidateFilesForRowKeyBefore(state.getTargetKey());
2028 while (sfIterator.hasNext()) {
2029 StoreFile sf = sfIterator.next();
2030 sfIterator.remove();
2031 boolean haveNewCandidate = rowAtOrBeforeFromStoreFile(sf, state);
2032 Cell candidate = state.getCandidate();
2033
2034 if (candidate != null && CellUtil.matchingRow(candidate, row)) {
2035 return candidate;
2036 }
2037 if (haveNewCandidate) {
2038 sfIterator = this.storeEngine.getStoreFileManager().updateCandidateFilesForRowKeyBefore(
2039 sfIterator, state.getTargetKey(), candidate);
2040 }
2041 }
2042 return state.getCandidate();
2043 } finally {
2044 this.lock.readLock().unlock();
2045 }
2046 }
2047
2048
2049
2050
2051
2052
2053
2054
2055 private boolean rowAtOrBeforeFromStoreFile(final StoreFile f,
2056 final GetClosestRowBeforeTracker state)
2057 throws IOException {
2058 StoreFile.Reader r = f.getReader();
2059 if (r == null) {
2060 LOG.warn("StoreFile " + f + " has a null Reader");
2061 return false;
2062 }
2063 if (r.getEntries() == 0) {
2064 LOG.warn("StoreFile " + f + " is a empty store file");
2065 return false;
2066 }
2067
2068 byte [] fk = r.getFirstKey();
2069 if (fk == null) return false;
2070 KeyValue firstKV = KeyValue.createKeyValueFromKey(fk, 0, fk.length);
2071 byte [] lk = r.getLastKey();
2072 KeyValue lastKV = KeyValue.createKeyValueFromKey(lk, 0, lk.length);
2073 KeyValue firstOnRow = state.getTargetKey();
2074 if (this.comparator.compareRows(lastKV, firstOnRow) < 0) {
2075
2076
2077 if (!state.isTargetTable(lastKV)) return false;
2078
2079
2080 firstOnRow = new KeyValue(lastKV.getRow(), HConstants.LATEST_TIMESTAMP);
2081 }
2082
2083 HFileScanner scanner = r.getScanner(true, true, false);
2084
2085 if (!seekToScanner(scanner, firstOnRow, firstKV)) return false;
2086
2087
2088 if (walkForwardInSingleRow(scanner, firstOnRow, state)) return true;
2089
2090 while (scanner.seekBefore(firstOnRow.getBuffer(), firstOnRow.getKeyOffset(),
2091 firstOnRow.getKeyLength())) {
2092 Cell kv = scanner.getKeyValue();
2093 if (!state.isTargetTable(kv)) break;
2094 if (!state.isBetterCandidate(kv)) break;
2095
2096 firstOnRow = new KeyValue(kv.getRow(), HConstants.LATEST_TIMESTAMP);
2097
2098 if (!seekToScanner(scanner, firstOnRow, firstKV)) return false;
2099
2100 if (walkForwardInSingleRow(scanner, firstOnRow, state)) return true;
2101 }
2102 return false;
2103 }
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113 private boolean seekToScanner(final HFileScanner scanner,
2114 final KeyValue firstOnRow,
2115 final KeyValue firstKV)
2116 throws IOException {
2117 KeyValue kv = firstOnRow;
2118
2119 if (this.comparator.compareRows(firstKV, firstOnRow) == 0) kv = firstKV;
2120 int result = scanner.seekTo(kv);
2121 return result != -1;
2122 }
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134 private boolean walkForwardInSingleRow(final HFileScanner scanner,
2135 final KeyValue firstOnRow,
2136 final GetClosestRowBeforeTracker state)
2137 throws IOException {
2138 boolean foundCandidate = false;
2139 do {
2140 Cell kv = scanner.getKeyValue();
2141
2142 if (this.comparator.compareRows(kv, firstOnRow) < 0) continue;
2143
2144 if (state.isTooFar(kv, firstOnRow)) break;
2145 if (state.isExpired(kv)) {
2146 continue;
2147 }
2148
2149 if (state.handle(kv)) {
2150 foundCandidate = true;
2151 break;
2152 }
2153 } while(scanner.next());
2154 return foundCandidate;
2155 }
2156
2157 @Override
2158 public boolean canSplit() {
2159 this.lock.readLock().lock();
2160 try {
2161
2162 boolean result = !hasReferences();
2163 if (!result && LOG.isDebugEnabled()) {
2164 LOG.debug("Cannot split region due to reference files being there");
2165 }
2166 return result;
2167 } finally {
2168 this.lock.readLock().unlock();
2169 }
2170 }
2171
2172 @Override
2173 public byte[] getSplitPoint() {
2174 this.lock.readLock().lock();
2175 try {
2176
2177 assert !this.getRegionInfo().isMetaRegion();
2178
2179 if (hasReferences()) {
2180 if (LOG.isTraceEnabled()) {
2181 LOG.trace("Not splittable; has references: " + this);
2182 }
2183 return null;
2184 }
2185 return this.storeEngine.getStoreFileManager().getSplitPoint();
2186 } catch(IOException e) {
2187 LOG.warn("Failed getting store size for " + this, e);
2188 } finally {
2189 this.lock.readLock().unlock();
2190 }
2191 return null;
2192 }
2193
2194 @Override
2195 public long getLastCompactSize() {
2196 return this.lastCompactSize;
2197 }
2198
2199 @Override
2200 public long getSize() {
2201 return storeSize.get();
2202 }
2203
2204 @Override
2205 public void triggerMajorCompaction() {
2206 this.forceMajor = true;
2207 }
2208
2209
2210
2211
2212
2213
2214 @Override
2215 public KeyValueScanner getScanner(Scan scan,
2216 final NavigableSet<byte []> targetCols, long readPt) throws IOException {
2217 lock.readLock().lock();
2218 try {
2219 KeyValueScanner scanner = null;
2220 if (this.getCoprocessorHost() != null) {
2221 scanner = this.getCoprocessorHost().preStoreScannerOpen(this, scan, targetCols);
2222 }
2223 if (scanner == null) {
2224 scanner = scan.isReversed() ? new ReversedStoreScanner(this,
2225 getScanInfo(), scan, targetCols, readPt) : new StoreScanner(this,
2226 getScanInfo(), scan, targetCols, readPt);
2227 }
2228 return scanner;
2229 } finally {
2230 lock.readLock().unlock();
2231 }
2232 }
2233
2234 @Override
2235 public String toString() {
2236 return this.getColumnFamilyName();
2237 }
2238
2239 @Override
2240 public int getStorefilesCount() {
2241 return this.storeEngine.getStoreFileManager().getStorefileCount();
2242 }
2243
2244 @Override
2245 public long getMaxStoreFileAge() {
2246 long earliestTS = Long.MAX_VALUE;
2247 for (StoreFile s: this.storeEngine.getStoreFileManager().getStorefiles()) {
2248 StoreFile.Reader r = s.getReader();
2249 if (r == null) {
2250 LOG.warn("StoreFile " + s + " has a null Reader");
2251 continue;
2252 }
2253 if (!s.isHFile()) {
2254 continue;
2255 }
2256 long createdTS = s.getFileInfo().getCreatedTimestamp();
2257 earliestTS = (createdTS < earliestTS) ? createdTS : earliestTS;
2258 }
2259 long now = EnvironmentEdgeManager.currentTime();
2260 return now - earliestTS;
2261 }
2262
2263 @Override
2264 public long getMinStoreFileAge() {
2265 long latestTS = 0;
2266 for (StoreFile s: this.storeEngine.getStoreFileManager().getStorefiles()) {
2267 StoreFile.Reader r = s.getReader();
2268 if (r == null) {
2269 LOG.warn("StoreFile " + s + " has a null Reader");
2270 continue;
2271 }
2272 if (!s.isHFile()) {
2273 continue;
2274 }
2275 long createdTS = s.getFileInfo().getCreatedTimestamp();
2276 latestTS = (createdTS > latestTS) ? createdTS : latestTS;
2277 }
2278 long now = EnvironmentEdgeManager.currentTime();
2279 return now - latestTS;
2280 }
2281
2282 @Override
2283 public long getAvgStoreFileAge() {
2284 long sum = 0, count = 0;
2285 for (StoreFile s: this.storeEngine.getStoreFileManager().getStorefiles()) {
2286 StoreFile.Reader r = s.getReader();
2287 if (r == null) {
2288 LOG.warn("StoreFile " + s + " has a null Reader");
2289 continue;
2290 }
2291 if (!s.isHFile()) {
2292 continue;
2293 }
2294 sum += s.getFileInfo().getCreatedTimestamp();
2295 count++;
2296 }
2297 if (count == 0) {
2298 return 0;
2299 }
2300 long avgTS = sum / count;
2301 long now = EnvironmentEdgeManager.currentTime();
2302 return now - avgTS;
2303 }
2304
2305 @Override
2306 public long getNumReferenceFiles() {
2307 long numRefFiles = 0;
2308 for (StoreFile s : this.storeEngine.getStoreFileManager().getStorefiles()) {
2309 if (s.isReference()) {
2310 numRefFiles++;
2311 }
2312 }
2313 return numRefFiles;
2314 }
2315
2316 @Override
2317 public long getNumHFiles() {
2318 long numHFiles = 0;
2319 for (StoreFile s : this.storeEngine.getStoreFileManager().getStorefiles()) {
2320 if (s.isHFile()) {
2321 numHFiles++;
2322 }
2323 }
2324 return numHFiles;
2325 }
2326
2327 @Override
2328 public long getStoreSizeUncompressed() {
2329 return this.totalUncompressedBytes.get();
2330 }
2331
2332 private long getTotalUmcompressedBytes(Collection<StoreFile> files) {
2333 long size = 0;
2334 for (StoreFile sf : files) {
2335 if (sf != null && sf.getReader() != null) {
2336 size += sf.getReader().getTotalUncompressedBytes();
2337 }
2338 }
2339 return size;
2340 }
2341
2342 private long getStorefilesSize(Collection<StoreFile> files) {
2343 long size = 0;
2344 for (StoreFile sf : files) {
2345 if (sf != null) {
2346 if (sf.getReader() == null) {
2347 LOG.warn("StoreFile " + sf + " has a null Reader");
2348 continue;
2349 }
2350 size += sf.getReader().length();
2351 }
2352 }
2353 return size;
2354 }
2355
2356 @Override
2357 public long getStorefilesSize() {
2358 return getStorefilesSize(storeEngine.getStoreFileManager().getStorefiles());
2359 }
2360
2361 @Override
2362 public long getStorefilesIndexSize() {
2363 long size = 0;
2364 for (StoreFile s: this.storeEngine.getStoreFileManager().getStorefiles()) {
2365 StoreFile.Reader r = s.getReader();
2366 if (r == null) {
2367 LOG.warn("StoreFile " + s + " has a null Reader");
2368 continue;
2369 }
2370 size += r.indexSize();
2371 }
2372 return size;
2373 }
2374
2375 @Override
2376 public long getTotalStaticIndexSize() {
2377 long size = 0;
2378 for (StoreFile s : this.storeEngine.getStoreFileManager().getStorefiles()) {
2379 StoreFile.Reader r = s.getReader();
2380 if (r == null) {
2381 continue;
2382 }
2383 size += r.getUncompressedDataIndexSize();
2384 }
2385 return size;
2386 }
2387
2388 @Override
2389 public long getTotalStaticBloomSize() {
2390 long size = 0;
2391 for (StoreFile s : this.storeEngine.getStoreFileManager().getStorefiles()) {
2392 StoreFile.Reader r = s.getReader();
2393 if (r == null) {
2394 continue;
2395 }
2396 size += r.getTotalBloomSize();
2397 }
2398 return size;
2399 }
2400
2401 @Override
2402 public long getMemStoreSize() {
2403 return this.memstore.size();
2404 }
2405
2406 @Override
2407 public int getCompactPriority() {
2408 int priority = this.storeEngine.getStoreFileManager().getStoreCompactionPriority();
2409 if (priority == PRIORITY_USER) {
2410 LOG.warn("Compaction priority is USER despite there being no user compaction");
2411 }
2412 return priority;
2413 }
2414
2415 @Override
2416 public boolean throttleCompaction(long compactionSize) {
2417 return storeEngine.getCompactionPolicy().throttleCompaction(compactionSize);
2418 }
2419
2420 public HRegion getHRegion() {
2421 return this.region;
2422 }
2423
2424 @Override
2425 public RegionCoprocessorHost getCoprocessorHost() {
2426 return this.region.getCoprocessorHost();
2427 }
2428
2429 @Override
2430 public HRegionInfo getRegionInfo() {
2431 return this.fs.getRegionInfo();
2432 }
2433
2434 @Override
2435 public boolean areWritesEnabled() {
2436 return this.region.areWritesEnabled();
2437 }
2438
2439 @Override
2440 public long getSmallestReadPoint() {
2441 return this.region.getSmallestReadPoint();
2442 }
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457 public long updateColumnValue(byte [] row, byte [] f,
2458 byte [] qualifier, long newValue)
2459 throws IOException {
2460
2461 this.lock.readLock().lock();
2462 try {
2463 long now = EnvironmentEdgeManager.currentTime();
2464
2465 return this.memstore.updateColumnValue(row,
2466 f,
2467 qualifier,
2468 newValue,
2469 now);
2470
2471 } finally {
2472 this.lock.readLock().unlock();
2473 }
2474 }
2475
2476 @Override
2477 public long upsert(Iterable<Cell> cells, long readpoint,
2478 List<Cell> removedCells) throws IOException {
2479 this.lock.readLock().lock();
2480 try {
2481 return this.memstore.upsert(cells, readpoint, removedCells);
2482 } finally {
2483 this.lock.readLock().unlock();
2484 }
2485 }
2486
2487 @Override
2488 public StoreFlushContext createFlushContext(long cacheFlushId) {
2489 return new StoreFlusherImpl(cacheFlushId);
2490 }
2491
2492 private final class StoreFlusherImpl implements StoreFlushContext {
2493
2494 private long cacheFlushSeqNum;
2495 private MemStoreSnapshot snapshot;
2496 private List<Path> tempFiles;
2497 private List<Path> committedFiles;
2498 private long cacheFlushCount;
2499 private long cacheFlushSize;
2500 private long outputFileSize;
2501
2502 private StoreFlusherImpl(long cacheFlushSeqNum) {
2503 this.cacheFlushSeqNum = cacheFlushSeqNum;
2504 }
2505
2506
2507
2508
2509
2510 @Override
2511 public void prepare() {
2512 this.snapshot = memstore.snapshot();
2513 this.cacheFlushCount = snapshot.getCellsCount();
2514 this.cacheFlushSize = snapshot.getSize();
2515 committedFiles = new ArrayList<Path>(1);
2516 }
2517
2518 @Override
2519 public void flushCache(MonitoredTask status) throws IOException {
2520 RegionServerServices rsService = region.getRegionServerServices();
2521 ThroughputController throughputController =
2522 rsService == null ? null : rsService.getFlushThroughputController();
2523 tempFiles = HStore.this.flushCache(cacheFlushSeqNum, snapshot, status, throughputController);
2524 }
2525
2526 @Override
2527 public boolean commit(MonitoredTask status) throws IOException {
2528 if (this.tempFiles == null || this.tempFiles.isEmpty()) {
2529 return false;
2530 }
2531 List<StoreFile> storeFiles = new ArrayList<StoreFile>(this.tempFiles.size());
2532 for (Path storeFilePath : tempFiles) {
2533 try {
2534 StoreFile sf = HStore.this.commitFile(storeFilePath, cacheFlushSeqNum, status);
2535 outputFileSize += sf.getReader().length();
2536 storeFiles.add(sf);
2537 } catch (IOException ex) {
2538 LOG.error("Failed to commit store file " + storeFilePath, ex);
2539
2540 for (StoreFile sf : storeFiles) {
2541 Path pathToDelete = sf.getPath();
2542 try {
2543 sf.deleteReader();
2544 } catch (IOException deleteEx) {
2545 LOG.fatal("Failed to delete store file we committed, halting " + pathToDelete, ex);
2546 Runtime.getRuntime().halt(1);
2547 }
2548 }
2549 throw new IOException("Failed to commit the flush", ex);
2550 }
2551 }
2552
2553 for (StoreFile sf : storeFiles) {
2554 if (HStore.this.getCoprocessorHost() != null) {
2555 HStore.this.getCoprocessorHost().postFlush(HStore.this, sf);
2556 }
2557 committedFiles.add(sf.getPath());
2558 }
2559
2560 HStore.this.flushedCellsCount.addAndGet(cacheFlushCount);
2561 HStore.this.flushedCellsSize.addAndGet(cacheFlushSize);
2562 HStore.this.flushedOutputFileSize.addAndGet(outputFileSize);
2563
2564
2565 return HStore.this.updateStorefiles(storeFiles, snapshot.getId());
2566 }
2567
2568 @Override
2569 public long getOutputFileSize() {
2570 return outputFileSize;
2571 }
2572
2573 @Override
2574 public List<Path> getCommittedFiles() {
2575 return committedFiles;
2576 }
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586 @Override
2587 public void replayFlush(List<String> fileNames, boolean dropMemstoreSnapshot)
2588 throws IOException {
2589 List<StoreFile> storeFiles = new ArrayList<StoreFile>(fileNames.size());
2590 for (String file : fileNames) {
2591
2592 StoreFileInfo storeFileInfo = fs.getStoreFileInfo(getColumnFamilyName(), file);
2593 StoreFile storeFile = createStoreFileAndReader(storeFileInfo);
2594 storeFiles.add(storeFile);
2595 HStore.this.storeSize.addAndGet(storeFile.getReader().length());
2596 HStore.this.totalUncompressedBytes.addAndGet(
2597 storeFile.getReader().getTotalUncompressedBytes());
2598 if (LOG.isInfoEnabled()) {
2599 LOG.info("Region: " + HStore.this.getRegionInfo().getEncodedName() +
2600 " added " + storeFile + ", entries=" + storeFile.getReader().getEntries() +
2601 ", sequenceid=" + storeFile.getReader().getSequenceID() +
2602 ", filesize=" + StringUtils.humanReadableInt(storeFile.getReader().length()));
2603 }
2604 }
2605
2606 long snapshotId = -1;
2607 if (dropMemstoreSnapshot && snapshot != null) {
2608 snapshotId = snapshot.getId();
2609 }
2610 HStore.this.updateStorefiles(storeFiles, snapshotId);
2611 }
2612
2613
2614
2615
2616
2617 @Override
2618 public void abort() throws IOException {
2619 if (snapshot == null) {
2620 return;
2621 }
2622 HStore.this.updateStorefiles(new ArrayList<StoreFile>(0), snapshot.getId());
2623 }
2624 }
2625
2626 @Override
2627 public boolean needsCompaction() {
2628 List<StoreFile> filesCompactingClone = null;
2629 synchronized (filesCompacting) {
2630 filesCompactingClone = Lists.newArrayList(filesCompacting);
2631 }
2632 return this.storeEngine.needsCompaction(filesCompactingClone);
2633 }
2634
2635 @Override
2636 public CacheConfig getCacheConfig() {
2637 return this.cacheConf;
2638 }
2639
2640 public static final long FIXED_OVERHEAD =
2641 ClassSize.align(ClassSize.OBJECT + (26 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG)
2642 + (5 * Bytes.SIZEOF_INT) + (2 * Bytes.SIZEOF_BOOLEAN));
2643
2644 public static final long DEEP_OVERHEAD = ClassSize.align(FIXED_OVERHEAD
2645 + ClassSize.OBJECT + ClassSize.REENTRANT_LOCK
2646 + ClassSize.CONCURRENT_SKIPLISTMAP
2647 + ClassSize.CONCURRENT_SKIPLISTMAP_ENTRY + ClassSize.OBJECT
2648 + ScanInfo.FIXED_OVERHEAD);
2649
2650 @Override
2651 public long heapSize() {
2652 return DEEP_OVERHEAD + this.memstore.heapSize();
2653 }
2654
2655 @Override
2656 public KeyValue.KVComparator getComparator() {
2657 return comparator;
2658 }
2659
2660 @Override
2661 public ScanInfo getScanInfo() {
2662 return scanInfo;
2663 }
2664
2665
2666
2667
2668
2669 void setScanInfo(ScanInfo scanInfo) {
2670 this.scanInfo = scanInfo;
2671 }
2672
2673 @Override
2674 public boolean hasTooManyStoreFiles() {
2675 return getStorefilesCount() > this.blockingFileCount;
2676 }
2677
2678 @Override
2679 public long getFlushedCellsCount() {
2680 return flushedCellsCount.get();
2681 }
2682
2683 @Override
2684 public long getFlushedCellsSize() {
2685 return flushedCellsSize.get();
2686 }
2687
2688 @Override
2689 public long getFlushedOutputFileSize() {
2690 return flushedOutputFileSize.get();
2691 }
2692
2693 @Override
2694 public long getCompactedCellsCount() {
2695 return compactedCellsCount.get();
2696 }
2697
2698 @Override
2699 public long getCompactedCellsSize() {
2700 return compactedCellsSize.get();
2701 }
2702
2703 @Override
2704 public long getMajorCompactedCellsCount() {
2705 return majorCompactedCellsCount.get();
2706 }
2707
2708 @Override
2709 public long getMajorCompactedCellsSize() {
2710 return majorCompactedCellsSize.get();
2711 }
2712
2713
2714
2715
2716
2717 @VisibleForTesting
2718 public StoreEngine<?, ?, ?, ?> getStoreEngine() {
2719 return this.storeEngine;
2720 }
2721
2722 protected OffPeakHours getOffPeakHours() {
2723 return this.offPeakHours;
2724 }
2725
2726
2727
2728
2729 @Override
2730 public void onConfigurationChange(Configuration conf) {
2731 this.conf = new CompoundConfiguration()
2732 .add(conf)
2733 .addWritableMap(family.getValues());
2734 this.storeEngine.compactionPolicy.setConf(conf);
2735 this.offPeakHours = OffPeakHours.getInstance(conf);
2736 }
2737
2738
2739
2740
2741 @Override
2742 public void registerChildren(ConfigurationManager manager) {
2743
2744 }
2745
2746
2747
2748
2749 @Override
2750 public void deregisterChildren(ConfigurationManager manager) {
2751
2752 }
2753
2754 @Override
2755 public double getCompactionPressure() {
2756 return storeEngine.getStoreFileManager().getCompactionPressure();
2757 }
2758
2759 @Override
2760 public boolean isPrimaryReplicaStore() {
2761 return getRegionInfo().getReplicaId() == HRegionInfo.DEFAULT_REPLICA_ID;
2762 }
2763
2764
2765
2766
2767
2768 public void preSnapshotOperation() {
2769 archiveLock.lock();
2770 }
2771
2772
2773
2774
2775
2776 public void postSnapshotOperation() {
2777 archiveLock.unlock();
2778 }
2779
2780 @Override
2781 public synchronized void closeAndArchiveCompactedFiles() throws IOException {
2782
2783 archiveLock.lock();
2784 try {
2785 lock.readLock().lock();
2786 Collection<StoreFile> copyCompactedfiles = null;
2787 try {
2788 Collection<StoreFile> compactedfiles = getCompactedfiles();
2789 if (compactedfiles != null && compactedfiles.size() != 0) {
2790
2791 copyCompactedfiles = new ArrayList<StoreFile>(compactedfiles);
2792 } else {
2793 if (LOG.isTraceEnabled()) {
2794 LOG.trace("No compacted files to archive");
2795 return;
2796 }
2797 }
2798 } finally {
2799 lock.readLock().unlock();
2800 }
2801 if (copyCompactedfiles != null && !copyCompactedfiles.isEmpty()) {
2802 removeCompactedfiles(copyCompactedfiles);
2803 }
2804 } finally {
2805 archiveLock.unlock();
2806 }
2807 }
2808
2809
2810
2811
2812
2813
2814 private void removeCompactedfiles(Collection<StoreFile> compactedfiles)
2815 throws IOException {
2816 final List<StoreFile> filesToRemove = new ArrayList<StoreFile>(compactedfiles.size());
2817 for (final StoreFile file : compactedfiles) {
2818 synchronized (file) {
2819 try {
2820 StoreFile.Reader r = file.getReader();
2821
2822 if (r == null) {
2823 if (LOG.isDebugEnabled()) {
2824 LOG.debug("The file " + file + " was closed but still not archived.");
2825 }
2826 filesToRemove.add(file);
2827 }
2828
2829 if (r != null && r.isCompactedAway() && !r.isReferencedInReads()) {
2830
2831
2832 if (LOG.isTraceEnabled()) {
2833 LOG.trace("Closing and archiving the file " + file.getPath());
2834 }
2835 r.close(true);
2836
2837 filesToRemove.add(file);
2838 } else {
2839 if (r != null) {
2840 LOG.info("Can't archive compacted file " + file.getPath()
2841 + " because of either isCompactedAway=" + r.isCompactedAway()
2842 + " or file has reference, isReferencedInReads=" + r.isReferencedInReads()
2843 + ", refCount=" + r.getRefCount() + ", skipping for now.");
2844 } else {
2845 LOG.info("Can't archive compacted file " + file.getPath() + ", skipping for now.");
2846 }
2847 }
2848 } catch (Exception e) {
2849 LOG.error(
2850 "Exception while trying to close the compacted store file " + file.getPath().getName());
2851 }
2852 }
2853 }
2854 if (this.isPrimaryReplicaStore()) {
2855
2856
2857
2858 if (!filesToRemove.isEmpty()) {
2859 if (LOG.isDebugEnabled()) {
2860 LOG.debug("Moving the files " + filesToRemove + " to archive");
2861 }
2862
2863 try {
2864 this.fs.removeStoreFiles(this.getFamily().getNameAsString(), filesToRemove);
2865 } catch (FailedArchiveException fae) {
2866
2867
2868
2869 Collection<Path> failedFiles = fae.getFailedFiles();
2870 Iterator<StoreFile> iter = filesToRemove.iterator();
2871 while (iter.hasNext()) {
2872 if (failedFiles.contains(iter.next().getPath())) {
2873 iter.remove();
2874 }
2875 }
2876 if (!filesToRemove.isEmpty()) {
2877 clearCompactedfiles(filesToRemove);
2878 }
2879 throw fae;
2880 }
2881 }
2882 }
2883 if (!filesToRemove.isEmpty()) {
2884
2885 clearCompactedfiles(filesToRemove);
2886 }
2887 }
2888
2889 private void clearCompactedfiles(final List<StoreFile> filesToRemove) throws IOException {
2890 if (LOG.isTraceEnabled()) {
2891 LOG.trace("Clearing the compacted file " + filesToRemove + " from this store");
2892 }
2893 try {
2894 lock.writeLock().lock();
2895 this.getStoreEngine().getStoreFileManager().removeCompactedFiles(filesToRemove);
2896 } finally {
2897 lock.writeLock().unlock();
2898 }
2899 }
2900 }