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