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