View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
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.util.ArrayList;
27  import java.util.Collection;
28  import java.util.Collections;
29  import java.util.HashMap;
30  import java.util.HashSet;
31  import java.util.Iterator;
32  import java.util.List;
33  import java.util.NavigableSet;
34  import java.util.Set;
35  import java.util.concurrent.Callable;
36  import java.util.concurrent.CompletionService;
37  import java.util.concurrent.ConcurrentHashMap;
38  import java.util.concurrent.ExecutionException;
39  import java.util.concurrent.ExecutorCompletionService;
40  import java.util.concurrent.Future;
41  import java.util.concurrent.ThreadPoolExecutor;
42  import java.util.concurrent.atomic.AtomicBoolean;
43  import java.util.concurrent.locks.ReentrantReadWriteLock;
44  
45  import org.apache.commons.logging.Log;
46  import org.apache.commons.logging.LogFactory;
47  import org.apache.hadoop.conf.Configuration;
48  import org.apache.hadoop.fs.FileSystem;
49  import org.apache.hadoop.fs.Path;
50  import org.apache.hadoop.hbase.Cell;
51  import org.apache.hadoop.hbase.CellComparator;
52  import org.apache.hadoop.hbase.CellUtil;
53  import org.apache.hadoop.hbase.CompoundConfiguration;
54  import org.apache.hadoop.hbase.HColumnDescriptor;
55  import org.apache.hadoop.hbase.HConstants;
56  import org.apache.hadoop.hbase.HRegionInfo;
57  import org.apache.hadoop.hbase.KeyValue;
58  import org.apache.hadoop.hbase.TableName;
59  import org.apache.hadoop.hbase.Tag;
60  import org.apache.hadoop.hbase.TagType;
61  import org.apache.hadoop.hbase.classification.InterfaceAudience;
62  import org.apache.hadoop.hbase.client.Scan;
63  import org.apache.hadoop.hbase.conf.ConfigurationManager;
64  import org.apache.hadoop.hbase.io.compress.Compression;
65  import org.apache.hadoop.hbase.io.crypto.Cipher;
66  import org.apache.hadoop.hbase.io.crypto.Encryption;
67  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
68  import org.apache.hadoop.hbase.io.hfile.HFile;
69  import org.apache.hadoop.hbase.io.hfile.HFileContext;
70  import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
71  import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder;
72  import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoderImpl;
73  import org.apache.hadoop.hbase.io.hfile.HFileScanner;
74  import org.apache.hadoop.hbase.io.hfile.InvalidHFileException;
75  import org.apache.hadoop.hbase.monitoring.MonitoredTask;
76  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
77  import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
78  import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext;
79  import org.apache.hadoop.hbase.regionserver.compactions.CompactionProgress;
80  import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest;
81  import org.apache.hadoop.hbase.regionserver.compactions.DefaultCompactor;
82  import org.apache.hadoop.hbase.regionserver.compactions.OffPeakHours;
83  import org.apache.hadoop.hbase.regionserver.compactions.CompactionThroughputController;
84  import org.apache.hadoop.hbase.regionserver.wal.WALUtil;
85  import org.apache.hadoop.hbase.security.EncryptionUtil;
86  import org.apache.hadoop.hbase.security.User;
87  import org.apache.hadoop.hbase.util.Bytes;
88  import org.apache.hadoop.hbase.util.ChecksumType;
89  import org.apache.hadoop.hbase.util.ClassSize;
90  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
91  import org.apache.hadoop.hbase.util.Pair;
92  import org.apache.hadoop.hbase.util.ReflectionUtils;
93  import org.apache.hadoop.ipc.RemoteException;
94  import org.apache.hadoop.util.StringUtils;
95  import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix;
96  
97  import com.google.common.annotations.VisibleForTesting;
98  import com.google.common.base.Preconditions;
99  import com.google.common.collect.ImmutableCollection;
100 import com.google.common.collect.ImmutableList;
101 import com.google.common.collect.Lists;
102 import com.google.common.collect.Sets;
103 
104 /**
105  * A Store holds a column family in a Region.  Its a memstore and a set of zero
106  * or more StoreFiles, which stretch backwards over time.
107  *
108  * <p>There's no reason to consider append-logging at this level; all logging
109  * and locking is handled at the HRegion level.  Store just provides
110  * services to manage sets of StoreFiles.  One of the most important of those
111  * services is compaction services where files are aggregated once they pass
112  * a configurable threshold.
113  *
114  * <p>Locking and transactions are handled at a higher level.  This API should
115  * not be called directly but by an HRegion manager.
116  */
117 @InterfaceAudience.Private
118 public class HStore implements Store {
119   private static final String MEMSTORE_CLASS_NAME = "hbase.regionserver.memstore.class";
120   public static final String COMPACTCHECKER_INTERVAL_MULTIPLIER_KEY =
121       "hbase.server.compactchecker.interval.multiplier";
122   public static final String BLOCKING_STOREFILES_KEY = "hbase.hstore.blockingStoreFiles";
123   public static final int DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER = 1000;
124   public static final int DEFAULT_BLOCKING_STOREFILE_COUNT = 7;
125 
126   private static final Log LOG = LogFactory.getLog(HStore.class);
127 
128   protected final MemStore memstore;
129   // This stores directory in the filesystem.
130   protected final HRegion region;
131   private final HColumnDescriptor family;
132   private final HRegionFileSystem fs;
133   protected Configuration conf;
134   protected CacheConfig cacheConf;
135   private long lastCompactSize = 0;
136   volatile boolean forceMajor = false;
137   /* how many bytes to write between status checks */
138   static int closeCheckInterval = 0;
139   private volatile long storeSize = 0L;
140   private volatile long totalUncompressedBytes = 0L;
141 
142   /**
143    * RWLock for store operations.
144    * Locked in shared mode when the list of component stores is looked at:
145    *   - all reads/writes to table data
146    *   - checking for split
147    * Locked in exclusive mode when the list of component stores is modified:
148    *   - closing
149    *   - completing a compaction
150    */
151   final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
152   private final boolean verifyBulkLoads;
153 
154   private ScanInfo scanInfo;
155 
156   // TODO: ideally, this should be part of storeFileManager, as we keep passing this to it.
157   final List<StoreFile> filesCompacting = Lists.newArrayList();
158 
159   // All access must be synchronized.
160   private final Set<ChangedReadersObserver> changedReaderObservers =
161     Collections.newSetFromMap(new ConcurrentHashMap<ChangedReadersObserver, Boolean>());
162 
163   protected final int blocksize;
164   private HFileDataBlockEncoder dataBlockEncoder;
165 
166   /** Checksum configuration */
167   protected ChecksumType checksumType;
168   protected int bytesPerChecksum;
169 
170   // Comparing KeyValues
171   private final CellComparator comparator;
172 
173   final StoreEngine<?, ?, ?, ?> storeEngine;
174 
175   private static final AtomicBoolean offPeakCompactionTracker = new AtomicBoolean();
176   private volatile OffPeakHours offPeakHours;
177 
178   private static final int DEFAULT_FLUSH_RETRIES_NUMBER = 10;
179   private int flushRetriesNumber;
180   private int pauseTime;
181 
182   private long blockingFileCount;
183   private int compactionCheckMultiplier;
184 
185   protected Encryption.Context cryptoContext = Encryption.Context.NONE;
186 
187   private volatile long flushedCellsCount = 0;
188   private volatile long compactedCellsCount = 0;
189   private volatile long majorCompactedCellsCount = 0;
190   private volatile long flushedCellsSize = 0;
191   private volatile long compactedCellsSize = 0;
192   private volatile long majorCompactedCellsSize = 0;
193 
194   /**
195    * Constructor
196    * @param region
197    * @param family HColumnDescriptor for this column
198    * @param confParam configuration object
199    * failed.  Can be null.
200    * @throws IOException
201    */
202   protected HStore(final HRegion region, final HColumnDescriptor family,
203       final Configuration confParam) throws IOException {
204 
205     this.fs = region.getRegionFileSystem();
206 
207     // Assemble the store's home directory and Ensure it exists.
208     fs.createStoreDir(family.getNameAsString());
209     this.region = region;
210     this.family = family;
211     // 'conf' renamed to 'confParam' b/c we use this.conf in the constructor
212     // CompoundConfiguration will look for keys in reverse order of addition, so we'd
213     // add global config first, then table and cf overrides, then cf metadata.
214     this.conf = new CompoundConfiguration()
215       .add(confParam)
216       .addStringMap(region.getTableDesc().getConfiguration())
217       .addStringMap(family.getConfiguration())
218       .addBytesMap(family.getValues());
219     this.blocksize = family.getBlocksize();
220 
221     this.dataBlockEncoder =
222         new HFileDataBlockEncoderImpl(family.getDataBlockEncoding());
223 
224     this.comparator = region.getCellCompartor();
225     // used by ScanQueryMatcher
226     long timeToPurgeDeletes =
227         Math.max(conf.getLong("hbase.hstore.time.to.purge.deletes", 0), 0);
228     LOG.trace("Time to purge deletes set to " + timeToPurgeDeletes +
229         "ms in store " + this);
230     // Get TTL
231     long ttl = determineTTLFromFamily(family);
232     // Why not just pass a HColumnDescriptor in here altogether?  Even if have
233     // to clone it?
234     scanInfo = new ScanInfo(family, ttl, timeToPurgeDeletes, this.comparator);
235     String className = conf.get(MEMSTORE_CLASS_NAME, DefaultMemStore.class.getName());
236     this.memstore = ReflectionUtils.instantiateWithCustomCtor(className, new Class[] {
237         Configuration.class, CellComparator.class }, new Object[] { conf, this.comparator });
238     this.offPeakHours = OffPeakHours.getInstance(conf);
239 
240     // Setting up cache configuration for this family
241     createCacheConf(family);
242 
243     this.verifyBulkLoads = conf.getBoolean("hbase.hstore.bulkload.verify", false);
244 
245     this.blockingFileCount =
246         conf.getInt(BLOCKING_STOREFILES_KEY, DEFAULT_BLOCKING_STOREFILE_COUNT);
247     this.compactionCheckMultiplier = conf.getInt(
248         COMPACTCHECKER_INTERVAL_MULTIPLIER_KEY, DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER);
249     if (this.compactionCheckMultiplier <= 0) {
250       LOG.error("Compaction check period multiplier must be positive, setting default: "
251           + DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER);
252       this.compactionCheckMultiplier = DEFAULT_COMPACTCHECKER_INTERVAL_MULTIPLIER;
253     }
254 
255     if (HStore.closeCheckInterval == 0) {
256       HStore.closeCheckInterval = conf.getInt(
257           "hbase.hstore.close.check.interval", 10*1000*1000 /* 10 MB */);
258     }
259 
260     this.storeEngine = createStoreEngine(this, this.conf, this.comparator);
261     this.storeEngine.getStoreFileManager().loadFiles(loadStoreFiles());
262 
263     // Initialize checksum type from name. The names are CRC32, CRC32C, etc.
264     this.checksumType = getChecksumType(conf);
265     // initilize bytes per checksum
266     this.bytesPerChecksum = getBytesPerChecksum(conf);
267     flushRetriesNumber = conf.getInt(
268         "hbase.hstore.flush.retries.number", DEFAULT_FLUSH_RETRIES_NUMBER);
269     pauseTime = conf.getInt(HConstants.HBASE_SERVER_PAUSE, HConstants.DEFAULT_HBASE_SERVER_PAUSE);
270     if (flushRetriesNumber <= 0) {
271       throw new IllegalArgumentException(
272           "hbase.hstore.flush.retries.number must be > 0, not "
273               + flushRetriesNumber);
274     }
275 
276     // Crypto context for new store files
277     String cipherName = family.getEncryptionType();
278     if (cipherName != null) {
279       Cipher cipher;
280       Key key;
281       byte[] keyBytes = family.getEncryptionKey();
282       if (keyBytes != null) {
283         // Family provides specific key material
284         String masterKeyName = conf.get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY,
285           User.getCurrent().getShortName());
286         try {
287           // First try the master key
288           key = EncryptionUtil.unwrapKey(conf, masterKeyName, keyBytes);
289         } catch (KeyException e) {
290           // If the current master key fails to unwrap, try the alternate, if
291           // one is configured
292           if (LOG.isDebugEnabled()) {
293             LOG.debug("Unable to unwrap key with current master key '" + masterKeyName + "'");
294           }
295           String alternateKeyName =
296             conf.get(HConstants.CRYPTO_MASTERKEY_ALTERNATE_NAME_CONF_KEY);
297           if (alternateKeyName != null) {
298             try {
299               key = EncryptionUtil.unwrapKey(conf, alternateKeyName, keyBytes);
300             } catch (KeyException ex) {
301               throw new IOException(ex);
302             }
303           } else {
304             throw new IOException(e);
305           }
306         }
307         // Use the algorithm the key wants
308         cipher = Encryption.getCipher(conf, key.getAlgorithm());
309         if (cipher == null) {
310           throw new RuntimeException("Cipher '" + key.getAlgorithm() + "' is not available");
311         }
312         // Fail if misconfigured
313         // We use the encryption type specified in the column schema as a sanity check on
314         // what the wrapped key is telling us
315         if (!cipher.getName().equalsIgnoreCase(cipherName)) {
316           throw new RuntimeException("Encryption for family '" + family.getNameAsString() +
317             "' configured with type '" + cipherName +
318             "' but key specifies algorithm '" + cipher.getName() + "'");
319         }
320       } else {
321         // Family does not provide key material, create a random key
322         cipher = Encryption.getCipher(conf, cipherName);
323         if (cipher == null) {
324           throw new RuntimeException("Cipher '" + cipherName + "' is not available");
325         }
326         key = cipher.getRandomKey();
327       }
328       cryptoContext = Encryption.newContext(conf);
329       cryptoContext.setCipher(cipher);
330       cryptoContext.setKey(key);
331     }
332   }
333 
334   /**
335    * Creates the cache config.
336    * @param family The current column family.
337    */
338   protected void createCacheConf(final HColumnDescriptor family) {
339     this.cacheConf = new CacheConfig(conf, family);
340   }
341 
342   /**
343    * Creates the store engine configured for the given Store.
344    * @param store The store. An unfortunate dependency needed due to it
345    *              being passed to coprocessors via the compactor.
346    * @param conf Store configuration.
347    * @param kvComparator KVComparator for storeFileManager.
348    * @return StoreEngine to use.
349    */
350   protected StoreEngine<?, ?, ?, ?> createStoreEngine(Store store, Configuration conf,
351       CellComparator kvComparator) throws IOException {
352     return StoreEngine.create(store, conf, comparator);
353   }
354 
355   /**
356    * @param family
357    * @return TTL in seconds of the specified family
358    */
359   public static long determineTTLFromFamily(final HColumnDescriptor family) {
360     // HCD.getTimeToLive returns ttl in seconds.  Convert to milliseconds.
361     long ttl = family.getTimeToLive();
362     if (ttl == HConstants.FOREVER) {
363       // Default is unlimited ttl.
364       ttl = Long.MAX_VALUE;
365     } else if (ttl == -1) {
366       ttl = Long.MAX_VALUE;
367     } else {
368       // Second -> ms adjust for user data
369       ttl *= 1000;
370     }
371     return ttl;
372   }
373 
374   @Override
375   public String getColumnFamilyName() {
376     return this.family.getNameAsString();
377   }
378 
379   @Override
380   public TableName getTableName() {
381     return this.getRegionInfo().getTable();
382   }
383 
384   @Override
385   public FileSystem getFileSystem() {
386     return this.fs.getFileSystem();
387   }
388 
389   public HRegionFileSystem getRegionFileSystem() {
390     return this.fs;
391   }
392 
393   /* Implementation of StoreConfigInformation */
394   @Override
395   public long getStoreFileTtl() {
396     // TTL only applies if there's no MIN_VERSIONs setting on the column.
397     return (this.scanInfo.getMinVersions() == 0) ? this.scanInfo.getTtl() : Long.MAX_VALUE;
398   }
399 
400   @Override
401   public long getMemstoreFlushSize() {
402     // TODO: Why is this in here?  The flushsize of the region rather than the store?  St.Ack
403     return this.region.memstoreFlushSize;
404   }
405 
406   @Override
407   public long getFlushableSize() {
408     return this.memstore.getFlushableSize();
409   }
410 
411   @Override
412   public long getSnapshotSize() {
413     return this.memstore.getSnapshotSize();
414   }
415 
416   @Override
417   public long getCompactionCheckMultiplier() {
418     return this.compactionCheckMultiplier;
419   }
420 
421   @Override
422   public long getBlockingFileCount() {
423     return blockingFileCount;
424   }
425   /* End implementation of StoreConfigInformation */
426 
427   /**
428    * Returns the configured bytesPerChecksum value.
429    * @param conf The configuration
430    * @return The bytesPerChecksum that is set in the configuration
431    */
432   public static int getBytesPerChecksum(Configuration conf) {
433     return conf.getInt(HConstants.BYTES_PER_CHECKSUM,
434                        HFile.DEFAULT_BYTES_PER_CHECKSUM);
435   }
436 
437   /**
438    * Returns the configured checksum algorithm.
439    * @param conf The configuration
440    * @return The checksum algorithm that is set in the configuration
441    */
442   public static ChecksumType getChecksumType(Configuration conf) {
443     String checksumName = conf.get(HConstants.CHECKSUM_TYPE_NAME);
444     if (checksumName == null) {
445       return ChecksumType.getDefaultChecksumType();
446     } else {
447       return ChecksumType.nameToType(checksumName);
448     }
449   }
450 
451   /**
452    * @return how many bytes to write between status checks
453    */
454   public static int getCloseCheckInterval() {
455     return closeCheckInterval;
456   }
457 
458   @Override
459   public HColumnDescriptor getFamily() {
460     return this.family;
461   }
462 
463   /**
464    * @return The maximum sequence id in all store files. Used for log replay.
465    */
466   @Override
467   public long getMaxSequenceId() {
468     return StoreFile.getMaxSequenceIdInList(this.getStorefiles());
469   }
470 
471   @Override
472   public long getMaxMemstoreTS() {
473     return StoreFile.getMaxMemstoreTSInList(this.getStorefiles());
474   }
475 
476   /**
477    * @param tabledir {@link Path} to where the table is being stored
478    * @param hri {@link HRegionInfo} for the region.
479    * @param family {@link HColumnDescriptor} describing the column family
480    * @return Path to family/Store home directory.
481    */
482   @Deprecated
483   public static Path getStoreHomedir(final Path tabledir,
484       final HRegionInfo hri, final byte[] family) {
485     return getStoreHomedir(tabledir, hri.getEncodedName(), family);
486   }
487 
488   /**
489    * @param tabledir {@link Path} to where the table is being stored
490    * @param encodedName Encoded region name.
491    * @param family {@link HColumnDescriptor} describing the column family
492    * @return Path to family/Store home directory.
493    */
494   @Deprecated
495   public static Path getStoreHomedir(final Path tabledir,
496       final String encodedName, final byte[] family) {
497     return new Path(tabledir, new Path(encodedName, Bytes.toString(family)));
498   }
499 
500   @Override
501   public HFileDataBlockEncoder getDataBlockEncoder() {
502     return dataBlockEncoder;
503   }
504 
505   /**
506    * Should be used only in tests.
507    * @param blockEncoder the block delta encoder to use
508    */
509   void setDataBlockEncoderInTest(HFileDataBlockEncoder blockEncoder) {
510     this.dataBlockEncoder = blockEncoder;
511   }
512 
513   /**
514    * Creates an unsorted list of StoreFile loaded in parallel
515    * from the given directory.
516    * @throws IOException
517    */
518   private List<StoreFile> loadStoreFiles() throws IOException {
519     Collection<StoreFileInfo> files = fs.getStoreFiles(getColumnFamilyName());
520     return openStoreFiles(files);
521   }
522 
523   private List<StoreFile> openStoreFiles(Collection<StoreFileInfo> files) throws IOException {
524     if (files == null || files.size() == 0) {
525       return new ArrayList<StoreFile>();
526     }
527     // initialize the thread pool for opening store files in parallel..
528     ThreadPoolExecutor storeFileOpenerThreadPool =
529       this.region.getStoreFileOpenAndCloseThreadPool("StoreFileOpenerThread-" +
530           this.getColumnFamilyName());
531     CompletionService<StoreFile> completionService =
532       new ExecutorCompletionService<StoreFile>(storeFileOpenerThreadPool);
533 
534     int totalValidStoreFile = 0;
535     for (final StoreFileInfo storeFileInfo: files) {
536       // open each store file in parallel
537       completionService.submit(new Callable<StoreFile>() {
538         @Override
539         public StoreFile call() throws IOException {
540           StoreFile storeFile = createStoreFileAndReader(storeFileInfo);
541           return storeFile;
542         }
543       });
544       totalValidStoreFile++;
545     }
546 
547     ArrayList<StoreFile> results = new ArrayList<StoreFile>(files.size());
548     IOException ioe = null;
549     try {
550       for (int i = 0; i < totalValidStoreFile; i++) {
551         try {
552           Future<StoreFile> future = completionService.take();
553           StoreFile storeFile = future.get();
554           long length = storeFile.getReader().length();
555           this.storeSize += length;
556           this.totalUncompressedBytes +=
557               storeFile.getReader().getTotalUncompressedBytes();
558           if (LOG.isDebugEnabled()) {
559             LOG.debug("loaded " + storeFile.toStringDetailed());
560           }
561           results.add(storeFile);
562         } catch (InterruptedException e) {
563           if (ioe == null) ioe = new InterruptedIOException(e.getMessage());
564         } catch (ExecutionException e) {
565           if (ioe == null) ioe = new IOException(e.getCause());
566         }
567       }
568     } finally {
569       storeFileOpenerThreadPool.shutdownNow();
570     }
571     if (ioe != null) {
572       // close StoreFile readers
573       for (StoreFile file : results) {
574         try {
575           if (file != null) file.closeReader(true);
576         } catch (IOException e) {
577           LOG.warn(e.getMessage());
578         }
579       }
580       throw ioe;
581     }
582 
583     return results;
584   }
585 
586   /**
587    * Checks the underlying store files, and opens the files that  have not
588    * been opened, and removes the store file readers for store files no longer
589    * available. Mainly used by secondary region replicas to keep up to date with
590    * the primary region files.
591    * @throws IOException
592    */
593   @Override
594   public void refreshStoreFiles() throws IOException {
595     Collection<StoreFileInfo> newFiles = fs.getStoreFiles(getColumnFamilyName());
596     refreshStoreFilesInternal(newFiles);
597   }
598 
599   @Override
600   public void refreshStoreFiles(Collection<String> newFiles) throws IOException {
601     List<StoreFileInfo> storeFiles = new ArrayList<StoreFileInfo>(newFiles.size());
602     for (String file : newFiles) {
603       storeFiles.add(fs.getStoreFileInfo(getColumnFamilyName(), file));
604     }
605     refreshStoreFilesInternal(storeFiles);
606   }
607 
608   /**
609    * Checks the underlying store files, and opens the files that  have not
610    * been opened, and removes the store file readers for store files no longer
611    * available. Mainly used by secondary region replicas to keep up to date with
612    * the primary region files.
613    * @throws IOException
614    */
615   private void refreshStoreFilesInternal(Collection<StoreFileInfo> newFiles) throws IOException {
616     StoreFileManager sfm = storeEngine.getStoreFileManager();
617     Collection<StoreFile> currentFiles = sfm.getStorefiles();
618     if (currentFiles == null) currentFiles = new ArrayList<StoreFile>(0);
619 
620     if (newFiles == null) newFiles = new ArrayList<StoreFileInfo>(0);
621 
622     HashMap<StoreFileInfo, StoreFile> currentFilesSet = new HashMap<StoreFileInfo, StoreFile>(currentFiles.size());
623     for (StoreFile sf : currentFiles) {
624       currentFilesSet.put(sf.getFileInfo(), sf);
625     }
626     HashSet<StoreFileInfo> newFilesSet = new HashSet<StoreFileInfo>(newFiles);
627 
628     Set<StoreFileInfo> toBeAddedFiles = Sets.difference(newFilesSet, currentFilesSet.keySet());
629     Set<StoreFileInfo> toBeRemovedFiles = Sets.difference(currentFilesSet.keySet(), newFilesSet);
630 
631     if (toBeAddedFiles.isEmpty() && toBeRemovedFiles.isEmpty()) {
632       return;
633     }
634 
635     LOG.info("Refreshing store files for region " + this.getRegionInfo().getRegionNameAsString()
636       + " files to add: " + toBeAddedFiles + " files to remove: " + toBeRemovedFiles);
637 
638     Set<StoreFile> toBeRemovedStoreFiles = new HashSet<StoreFile>(toBeRemovedFiles.size());
639     for (StoreFileInfo sfi : toBeRemovedFiles) {
640       toBeRemovedStoreFiles.add(currentFilesSet.get(sfi));
641     }
642 
643     // try to open the files
644     List<StoreFile> openedFiles = openStoreFiles(toBeAddedFiles);
645 
646     // propogate the file changes to the underlying store file manager
647     replaceStoreFiles(toBeRemovedStoreFiles, openedFiles); //won't throw an exception
648 
649     // Advance the memstore read point to be at least the new store files seqIds so that
650     // readers might pick it up. This assumes that the store is not getting any writes (otherwise
651     // in-flight transactions might be made visible)
652     if (!toBeAddedFiles.isEmpty()) {
653       region.getMVCC().advanceMemstoreReadPointIfNeeded(this.getMaxSequenceId());
654     }
655 
656     // notify scanners, close file readers, and recompute store size
657     completeCompaction(toBeRemovedStoreFiles, false);
658   }
659 
660   private StoreFile createStoreFileAndReader(final Path p) throws IOException {
661     StoreFileInfo info = new StoreFileInfo(conf, this.getFileSystem(), p);
662     return createStoreFileAndReader(info);
663   }
664 
665   private StoreFile createStoreFileAndReader(final StoreFileInfo info)
666       throws IOException {
667     info.setRegionCoprocessorHost(this.region.getCoprocessorHost());
668     StoreFile storeFile = new StoreFile(this.getFileSystem(), info, this.conf, this.cacheConf,
669       this.family.getBloomFilterType());
670     storeFile.createReader();
671     return storeFile;
672   }
673 
674   @Override
675   public Pair<Long, Cell> add(final Cell cell) {
676     lock.readLock().lock();
677     try {
678        return this.memstore.add(cell);
679     } finally {
680       lock.readLock().unlock();
681     }
682   }
683 
684   @Override
685   public long timeOfOldestEdit() {
686     return memstore.timeOfOldestEdit();
687   }
688 
689   /**
690    * Adds a value to the memstore
691    *
692    * @param kv
693    * @return memstore size delta
694    */
695   protected long delete(final KeyValue kv) {
696     lock.readLock().lock();
697     try {
698       return this.memstore.delete(kv);
699     } finally {
700       lock.readLock().unlock();
701     }
702   }
703 
704   @Override
705   public void rollback(final Cell cell) {
706     lock.readLock().lock();
707     try {
708       this.memstore.rollback(cell);
709     } finally {
710       lock.readLock().unlock();
711     }
712   }
713 
714   /**
715    * @return All store files.
716    */
717   @Override
718   public Collection<StoreFile> getStorefiles() {
719     return this.storeEngine.getStoreFileManager().getStorefiles();
720   }
721 
722   @Override
723   public void assertBulkLoadHFileOk(Path srcPath) throws IOException {
724     HFile.Reader reader  = null;
725     try {
726       LOG.info("Validating hfile at " + srcPath + " for inclusion in "
727           + "store " + this + " region " + this.getRegionInfo().getRegionNameAsString());
728       reader = HFile.createReader(srcPath.getFileSystem(conf),
729           srcPath, cacheConf, conf);
730       reader.loadFileInfo();
731 
732       byte[] firstKey = reader.getFirstRowKey();
733       Preconditions.checkState(firstKey != null, "First key can not be null");
734       Cell lk = reader.getLastKey();
735       Preconditions.checkState(lk != null, "Last key can not be null");
736       byte[] lastKey =  CellUtil.cloneRow(lk);
737 
738       LOG.debug("HFile bounds: first=" + Bytes.toStringBinary(firstKey) +
739           " last=" + Bytes.toStringBinary(lastKey));
740       LOG.debug("Region bounds: first=" +
741           Bytes.toStringBinary(getRegionInfo().getStartKey()) +
742           " last=" + Bytes.toStringBinary(getRegionInfo().getEndKey()));
743 
744       if (!this.getRegionInfo().containsRange(firstKey, lastKey)) {
745         throw new WrongRegionException(
746             "Bulk load file " + srcPath.toString() + " does not fit inside region "
747             + this.getRegionInfo().getRegionNameAsString());
748       }
749 
750       if(reader.length() > conf.getLong(HConstants.HREGION_MAX_FILESIZE,
751           HConstants.DEFAULT_MAX_FILE_SIZE)) {
752         LOG.warn("Trying to bulk load hfile " + srcPath.toString() + " with size: " +
753             reader.length() + " bytes can be problematic as it may lead to oversplitting.");
754       }
755 
756       if (verifyBulkLoads) {
757         long verificationStartTime = EnvironmentEdgeManager.currentTime();
758         LOG.info("Full verification started for bulk load hfile: " + srcPath.toString());
759         Cell prevCell = null;
760         HFileScanner scanner = reader.getScanner(false, false, false);
761         scanner.seekTo();
762         do {
763           Cell cell = scanner.getCell();
764           if (prevCell != null) {
765             if (comparator.compareRows(prevCell, cell) > 0) {
766               throw new InvalidHFileException("Previous row is greater than"
767                   + " current row: path=" + srcPath + " previous="
768                   + CellUtil.getCellKeyAsString(prevCell) + " current="
769                   + CellUtil.getCellKeyAsString(cell));
770             }
771             if (CellComparator.compareFamilies(prevCell, cell) != 0) {
772               throw new InvalidHFileException("Previous key had different"
773                   + " family compared to current key: path=" + srcPath
774                   + " previous="
775                   + Bytes.toStringBinary(prevCell.getFamilyArray(), prevCell.getFamilyOffset(),
776                       prevCell.getFamilyLength())
777                   + " current="
778                   + Bytes.toStringBinary(cell.getFamilyArray(), cell.getFamilyOffset(),
779                       cell.getFamilyLength()));
780             }
781           }
782           prevCell = cell;
783         } while (scanner.next());
784       LOG.info("Full verification complete for bulk load hfile: " + srcPath.toString()
785          + " took " + (EnvironmentEdgeManager.currentTime() - verificationStartTime)
786          + " ms");
787       }
788     } finally {
789       if (reader != null) reader.close();
790     }
791   }
792 
793   @Override
794   public Path bulkLoadHFile(String srcPathStr, long seqNum) throws IOException {
795     Path srcPath = new Path(srcPathStr);
796     Path dstPath = fs.bulkLoadStoreFile(getColumnFamilyName(), srcPath, seqNum);
797 
798     LOG.info("Loaded HFile " + srcPath + " into store '" + getColumnFamilyName() + "' as "
799         + dstPath + " - updating store file list.");
800 
801     StoreFile sf = createStoreFileAndReader(dstPath);
802     bulkLoadHFile(sf);
803 
804     LOG.info("Successfully loaded store file " + srcPath + " into store " + this
805         + " (new location: " + dstPath + ")");
806 
807     return dstPath;
808   }
809 
810   @Override
811   public void bulkLoadHFile(StoreFileInfo fileInfo) throws IOException {
812     StoreFile sf = createStoreFileAndReader(fileInfo);
813     bulkLoadHFile(sf);
814   }
815 
816   private void bulkLoadHFile(StoreFile sf) throws IOException {
817     StoreFile.Reader r = sf.getReader();
818     this.storeSize += r.length();
819     this.totalUncompressedBytes += r.getTotalUncompressedBytes();
820 
821     // Append the new storefile into the list
822     this.lock.writeLock().lock();
823     try {
824       this.storeEngine.getStoreFileManager().insertNewFiles(Lists.newArrayList(sf));
825     } finally {
826       // We need the lock, as long as we are updating the storeFiles
827       // or changing the memstore. Let us release it before calling
828       // notifyChangeReadersObservers. See HBASE-4485 for a possible
829       // deadlock scenario that could have happened if continue to hold
830       // the lock.
831       this.lock.writeLock().unlock();
832     }
833     notifyChangedReadersObservers();
834     LOG.info("Loaded HFile " + sf.getFileInfo() + " into store '" + getColumnFamilyName());
835     if (LOG.isTraceEnabled()) {
836       String traceMessage = "BULK LOAD time,size,store size,store files ["
837           + EnvironmentEdgeManager.currentTime() + "," + r.length() + "," + storeSize
838           + "," + storeEngine.getStoreFileManager().getStorefileCount() + "]";
839       LOG.trace(traceMessage);
840     }
841   }
842 
843   @Override
844   public ImmutableCollection<StoreFile> close() throws IOException {
845     this.lock.writeLock().lock();
846     try {
847       // Clear so metrics doesn't find them.
848       ImmutableCollection<StoreFile> result = storeEngine.getStoreFileManager().clearFiles();
849 
850       if (!result.isEmpty()) {
851         // initialize the thread pool for closing store files in parallel.
852         ThreadPoolExecutor storeFileCloserThreadPool = this.region
853             .getStoreFileOpenAndCloseThreadPool("StoreFileCloserThread-"
854                 + this.getColumnFamilyName());
855 
856         // close each store file in parallel
857         CompletionService<Void> completionService =
858           new ExecutorCompletionService<Void>(storeFileCloserThreadPool);
859         for (final StoreFile f : result) {
860           completionService.submit(new Callable<Void>() {
861             @Override
862             public Void call() throws IOException {
863               f.closeReader(true);
864               return null;
865             }
866           });
867         }
868 
869         IOException ioe = null;
870         try {
871           for (int i = 0; i < result.size(); i++) {
872             try {
873               Future<Void> future = completionService.take();
874               future.get();
875             } catch (InterruptedException e) {
876               if (ioe == null) {
877                 ioe = new InterruptedIOException();
878                 ioe.initCause(e);
879               }
880             } catch (ExecutionException e) {
881               if (ioe == null) ioe = new IOException(e.getCause());
882             }
883           }
884         } finally {
885           storeFileCloserThreadPool.shutdownNow();
886         }
887         if (ioe != null) throw ioe;
888       }
889       LOG.info("Closed " + this);
890       return result;
891     } finally {
892       this.lock.writeLock().unlock();
893     }
894   }
895 
896   /**
897    * Snapshot this stores memstore. Call before running
898    * {@link #flushCache(long, MemStoreSnapshot, MonitoredTask)}
899    *  so it has some work to do.
900    */
901   void snapshot() {
902     this.lock.writeLock().lock();
903     try {
904       this.memstore.snapshot();
905     } finally {
906       this.lock.writeLock().unlock();
907     }
908   }
909 
910   /**
911    * Write out current snapshot.  Presumes {@link #snapshot()} has been called previously.
912    * @param logCacheFlushId flush sequence number
913    * @param snapshot
914    * @param status
915    * @return The path name of the tmp file to which the store was flushed
916    * @throws IOException
917    */
918   protected List<Path> flushCache(final long logCacheFlushId, MemStoreSnapshot snapshot,
919       MonitoredTask status) throws IOException {
920     // If an exception happens flushing, we let it out without clearing
921     // the memstore snapshot.  The old snapshot will be returned when we say
922     // 'snapshot', the next time flush comes around.
923     // Retry after catching exception when flushing, otherwise server will abort
924     // itself
925     StoreFlusher flusher = storeEngine.getStoreFlusher();
926     IOException lastException = null;
927     for (int i = 0; i < flushRetriesNumber; i++) {
928       try {
929         List<Path> pathNames = flusher.flushSnapshot(snapshot, logCacheFlushId, status);
930         Path lastPathName = null;
931         try {
932           for (Path pathName : pathNames) {
933             lastPathName = pathName;
934             validateStoreFile(pathName);
935           }
936           return pathNames;
937         } catch (Exception e) {
938           LOG.warn("Failed validating store file " + lastPathName + ", retrying num=" + i, e);
939           if (e instanceof IOException) {
940             lastException = (IOException) e;
941           } else {
942             lastException = new IOException(e);
943           }
944         }
945       } catch (IOException e) {
946         LOG.warn("Failed flushing store file, retrying num=" + i, e);
947         lastException = e;
948       }
949       if (lastException != null && i < (flushRetriesNumber - 1)) {
950         try {
951           Thread.sleep(pauseTime);
952         } catch (InterruptedException e) {
953           IOException iie = new InterruptedIOException();
954           iie.initCause(e);
955           throw iie;
956         }
957       }
958     }
959     throw lastException;
960   }
961 
962   /*
963    * @param path The pathname of the tmp file into which the store was flushed
964    * @param logCacheFlushId
965    * @param status
966    * @return StoreFile created.
967    * @throws IOException
968    */
969   private StoreFile commitFile(final Path path, final long logCacheFlushId, MonitoredTask status)
970       throws IOException {
971     // Write-out finished successfully, move into the right spot
972     Path dstPath = fs.commitStoreFile(getColumnFamilyName(), path);
973 
974     status.setStatus("Flushing " + this + ": reopening flushed file");
975     StoreFile sf = createStoreFileAndReader(dstPath);
976 
977     StoreFile.Reader r = sf.getReader();
978     this.storeSize += r.length();
979     this.totalUncompressedBytes += r.getTotalUncompressedBytes();
980 
981     if (LOG.isInfoEnabled()) {
982       LOG.info("Added " + sf + ", entries=" + r.getEntries() +
983         ", sequenceid=" + logCacheFlushId +
984         ", filesize=" + TraditionalBinaryPrefix.long2String(r.length(), "", 1));
985     }
986     return sf;
987   }
988 
989   /*
990    * @param maxKeyCount
991    * @param compression Compression algorithm to use
992    * @param isCompaction whether we are creating a new file in a compaction
993    * @param includesMVCCReadPoint - whether to include MVCC or not
994    * @param includesTag - includesTag or not
995    * @return Writer for a new StoreFile in the tmp dir.
996    */
997   @Override
998   public StoreFile.Writer createWriterInTmp(long maxKeyCount, Compression.Algorithm compression,
999       boolean isCompaction, boolean includeMVCCReadpoint, boolean includesTag)
1000   throws IOException {
1001     final CacheConfig writerCacheConf;
1002     if (isCompaction) {
1003       // Don't cache data on write on compactions.
1004       writerCacheConf = new CacheConfig(cacheConf);
1005       writerCacheConf.setCacheDataOnWrite(false);
1006     } else {
1007       writerCacheConf = cacheConf;
1008     }
1009     InetSocketAddress[] favoredNodes = null;
1010     if (region.getRegionServerServices() != null) {
1011       favoredNodes = region.getRegionServerServices().getFavoredNodesForRegion(
1012           region.getRegionInfo().getEncodedName());
1013     }
1014     HFileContext hFileContext = createFileContext(compression, includeMVCCReadpoint, includesTag,
1015       cryptoContext);
1016     StoreFile.Writer w = new StoreFile.WriterBuilder(conf, writerCacheConf,
1017         this.getFileSystem())
1018             .withFilePath(fs.createTempName())
1019             .withComparator(comparator)
1020             .withBloomType(family.getBloomFilterType())
1021             .withMaxKeyCount(maxKeyCount)
1022             .withFavoredNodes(favoredNodes)
1023             .withFileContext(hFileContext)
1024             .build();
1025     return w;
1026   }
1027 
1028   private HFileContext createFileContext(Compression.Algorithm compression,
1029       boolean includeMVCCReadpoint, boolean includesTag, Encryption.Context cryptoContext) {
1030     if (compression == null) {
1031       compression = HFile.DEFAULT_COMPRESSION_ALGORITHM;
1032     }
1033     HFileContext hFileContext = new HFileContextBuilder()
1034                                 .withIncludesMvcc(includeMVCCReadpoint)
1035                                 .withIncludesTags(includesTag)
1036                                 .withCompression(compression)
1037                                 .withCompressTags(family.isCompressTags())
1038                                 .withChecksumType(checksumType)
1039                                 .withBytesPerCheckSum(bytesPerChecksum)
1040                                 .withBlockSize(blocksize)
1041                                 .withHBaseCheckSum(true)
1042                                 .withDataBlockEncoding(family.getDataBlockEncoding())
1043                                 .withEncryptionContext(cryptoContext)
1044                                 .withCreateTime(EnvironmentEdgeManager.currentTime())
1045                                 .build();
1046     return hFileContext;
1047   }
1048 
1049 
1050   /*
1051    * Change storeFiles adding into place the Reader produced by this new flush.
1052    * @param sfs Store files
1053    * @param snapshotId
1054    * @throws IOException
1055    * @return Whether compaction is required.
1056    */
1057   private boolean updateStorefiles(final List<StoreFile> sfs, final long snapshotId)
1058       throws IOException {
1059     this.lock.writeLock().lock();
1060     try {
1061       this.storeEngine.getStoreFileManager().insertNewFiles(sfs);
1062       if (snapshotId > 0) {
1063         this.memstore.clearSnapshot(snapshotId);
1064       }
1065     } finally {
1066       // We need the lock, as long as we are updating the storeFiles
1067       // or changing the memstore. Let us release it before calling
1068       // notifyChangeReadersObservers. See HBASE-4485 for a possible
1069       // deadlock scenario that could have happened if continue to hold
1070       // the lock.
1071       this.lock.writeLock().unlock();
1072     }
1073 
1074     // Tell listeners of the change in readers.
1075     notifyChangedReadersObservers();
1076 
1077     if (LOG.isTraceEnabled()) {
1078       long totalSize = 0;
1079       for (StoreFile sf : sfs) {
1080         totalSize += sf.getReader().length();
1081       }
1082       String traceMessage = "FLUSH time,count,size,store size,store files ["
1083           + EnvironmentEdgeManager.currentTime() + "," + sfs.size() + "," + totalSize
1084           + "," + storeSize + "," + storeEngine.getStoreFileManager().getStorefileCount() + "]";
1085       LOG.trace(traceMessage);
1086     }
1087     return needsCompaction();
1088   }
1089 
1090   /*
1091    * Notify all observers that set of Readers has changed.
1092    * @throws IOException
1093    */
1094   private void notifyChangedReadersObservers() throws IOException {
1095     for (ChangedReadersObserver o: this.changedReaderObservers) {
1096       o.updateReaders();
1097     }
1098   }
1099 
1100   /**
1101    * Get all scanners with no filtering based on TTL (that happens further down
1102    * the line).
1103    * @return all scanners for this store
1104    */
1105   @Override
1106   public List<KeyValueScanner> getScanners(boolean cacheBlocks, boolean isGet,
1107       boolean usePread, boolean isCompaction, ScanQueryMatcher matcher, byte[] startRow,
1108       byte[] stopRow, long readPt) throws IOException {
1109     Collection<StoreFile> storeFilesToScan;
1110     List<KeyValueScanner> memStoreScanners;
1111     this.lock.readLock().lock();
1112     try {
1113       storeFilesToScan =
1114           this.storeEngine.getStoreFileManager().getFilesForScanOrGet(isGet, startRow, stopRow);
1115       memStoreScanners = this.memstore.getScanners(readPt);
1116     } finally {
1117       this.lock.readLock().unlock();
1118     }
1119 
1120     // First the store file scanners
1121 
1122     // TODO this used to get the store files in descending order,
1123     // but now we get them in ascending order, which I think is
1124     // actually more correct, since memstore get put at the end.
1125     List<StoreFileScanner> sfScanners = StoreFileScanner
1126       .getScannersForStoreFiles(storeFilesToScan, cacheBlocks, usePread, isCompaction, matcher,
1127         readPt);
1128     List<KeyValueScanner> scanners =
1129       new ArrayList<KeyValueScanner>(sfScanners.size()+1);
1130     scanners.addAll(sfScanners);
1131     // Then the memstore scanners
1132     scanners.addAll(memStoreScanners);
1133     return scanners;
1134   }
1135 
1136   @Override
1137   public void addChangedReaderObserver(ChangedReadersObserver o) {
1138     this.changedReaderObservers.add(o);
1139   }
1140 
1141   @Override
1142   public void deleteChangedReaderObserver(ChangedReadersObserver o) {
1143     // We don't check if observer present; it may not be (legitimately)
1144     this.changedReaderObservers.remove(o);
1145   }
1146 
1147   //////////////////////////////////////////////////////////////////////////////
1148   // Compaction
1149   //////////////////////////////////////////////////////////////////////////////
1150 
1151   /**
1152    * Compact the StoreFiles.  This method may take some time, so the calling
1153    * thread must be able to block for long periods.
1154    *
1155    * <p>During this time, the Store can work as usual, getting values from
1156    * StoreFiles and writing new StoreFiles from the memstore.
1157    *
1158    * Existing StoreFiles are not destroyed until the new compacted StoreFile is
1159    * completely written-out to disk.
1160    *
1161    * <p>The compactLock prevents multiple simultaneous compactions.
1162    * The structureLock prevents us from interfering with other write operations.
1163    *
1164    * <p>We don't want to hold the structureLock for the whole time, as a compact()
1165    * can be lengthy and we want to allow cache-flushes during this period.
1166    *
1167    * <p> Compaction event should be idempotent, since there is no IO Fencing for
1168    * the region directory in hdfs. A region server might still try to complete the
1169    * compaction after it lost the region. That is why the following events are carefully
1170    * ordered for a compaction:
1171    *  1. Compaction writes new files under region/.tmp directory (compaction output)
1172    *  2. Compaction atomically moves the temporary file under region directory
1173    *  3. Compaction appends a WAL edit containing the compaction input and output files.
1174    *  Forces sync on WAL.
1175    *  4. Compaction deletes the input files from the region directory.
1176    *
1177    * Failure conditions are handled like this:
1178    *  - If RS fails before 2, compaction wont complete. Even if RS lives on and finishes
1179    *  the compaction later, it will only write the new data file to the region directory.
1180    *  Since we already have this data, this will be idempotent but we will have a redundant
1181    *  copy of the data.
1182    *  - If RS fails between 2 and 3, the region will have a redundant copy of the data. The
1183    *  RS that failed won't be able to finish snyc() for WAL because of lease recovery in WAL.
1184    *  - If RS fails after 3, the region region server who opens the region will pick up the
1185    *  the compaction marker from the WAL and replay it by removing the compaction input files.
1186    *  Failed RS can also attempt to delete those files, but the operation will be idempotent
1187    *
1188    * See HBASE-2231 for details.
1189    *
1190    * @param compaction compaction details obtained from requestCompaction()
1191    * @throws IOException
1192    * @return Storefile we compacted into or null if we failed or opted out early.
1193    */
1194   @Override
1195   public List<StoreFile> compact(CompactionContext compaction,
1196       CompactionThroughputController throughputController) throws IOException {
1197     assert compaction != null;
1198     List<StoreFile> sfs = null;
1199     CompactionRequest cr = compaction.getRequest();;
1200     try {
1201       // Do all sanity checking in here if we have a valid CompactionRequest
1202       // because we need to clean up after it on the way out in a finally
1203       // block below
1204       long compactionStartTime = EnvironmentEdgeManager.currentTime();
1205       assert compaction.hasSelection();
1206       Collection<StoreFile> filesToCompact = cr.getFiles();
1207       assert !filesToCompact.isEmpty();
1208       synchronized (filesCompacting) {
1209         // sanity check: we're compacting files that this store knows about
1210         // TODO: change this to LOG.error() after more debugging
1211         Preconditions.checkArgument(filesCompacting.containsAll(filesToCompact));
1212       }
1213 
1214       // Ready to go. Have list of files to compact.
1215       LOG.info("Starting compaction of " + filesToCompact.size() + " file(s) in "
1216           + this + " of " + this.getRegionInfo().getRegionNameAsString()
1217           + " into tmpdir=" + fs.getTempDir() + ", totalSize="
1218           + TraditionalBinaryPrefix.long2String(cr.getSize(), "", 1));
1219 
1220       // Commence the compaction.
1221       List<Path> newFiles = compaction.compact(throughputController);
1222 
1223       // TODO: get rid of this!
1224       if (!this.conf.getBoolean("hbase.hstore.compaction.complete", true)) {
1225         LOG.warn("hbase.hstore.compaction.complete is set to false");
1226         sfs = new ArrayList<StoreFile>(newFiles.size());
1227         for (Path newFile : newFiles) {
1228           // Create storefile around what we wrote with a reader on it.
1229           StoreFile sf = createStoreFileAndReader(newFile);
1230           sf.closeReader(true);
1231           sfs.add(sf);
1232         }
1233         return sfs;
1234       }
1235       // Do the steps necessary to complete the compaction.
1236       sfs = moveCompatedFilesIntoPlace(cr, newFiles);
1237       writeCompactionWalRecord(filesToCompact, sfs);
1238       replaceStoreFiles(filesToCompact, sfs);
1239       if (cr.isMajor()) {
1240         majorCompactedCellsCount += getCompactionProgress().totalCompactingKVs;
1241         majorCompactedCellsSize += getCompactionProgress().totalCompactedSize;
1242       } else {
1243         compactedCellsCount += getCompactionProgress().totalCompactingKVs;
1244         compactedCellsSize += getCompactionProgress().totalCompactedSize;
1245       }
1246       // At this point the store will use new files for all new scanners.
1247       completeCompaction(filesToCompact, true); // Archive old files & update store size.
1248 
1249       logCompactionEndMessage(cr, sfs, compactionStartTime);
1250       return sfs;
1251     } finally {
1252       finishCompactionRequest(cr);
1253     }
1254   }
1255 
1256   private List<StoreFile> moveCompatedFilesIntoPlace(
1257       CompactionRequest cr, List<Path> newFiles) throws IOException {
1258     List<StoreFile> sfs = new ArrayList<StoreFile>(newFiles.size());
1259     for (Path newFile : newFiles) {
1260       assert newFile != null;
1261       StoreFile sf = moveFileIntoPlace(newFile);
1262       if (this.getCoprocessorHost() != null) {
1263         this.getCoprocessorHost().postCompact(this, sf, cr);
1264       }
1265       assert sf != null;
1266       sfs.add(sf);
1267     }
1268     return sfs;
1269   }
1270 
1271   // Package-visible for tests
1272   StoreFile moveFileIntoPlace(final Path newFile) throws IOException {
1273     validateStoreFile(newFile);
1274     // Move the file into the right spot
1275     Path destPath = fs.commitStoreFile(getColumnFamilyName(), newFile);
1276     return createStoreFileAndReader(destPath);
1277   }
1278 
1279   /**
1280    * Writes the compaction WAL record.
1281    * @param filesCompacted Files compacted (input).
1282    * @param newFiles Files from compaction.
1283    */
1284   private void writeCompactionWalRecord(Collection<StoreFile> filesCompacted,
1285       Collection<StoreFile> newFiles) throws IOException {
1286     if (region.getWAL() == null) return;
1287     List<Path> inputPaths = new ArrayList<Path>(filesCompacted.size());
1288     for (StoreFile f : filesCompacted) {
1289       inputPaths.add(f.getPath());
1290     }
1291     List<Path> outputPaths = new ArrayList<Path>(newFiles.size());
1292     for (StoreFile f : newFiles) {
1293       outputPaths.add(f.getPath());
1294     }
1295     HRegionInfo info = this.region.getRegionInfo();
1296     CompactionDescriptor compactionDescriptor = ProtobufUtil.toCompactionDescriptor(info,
1297         family.getName(), inputPaths, outputPaths, fs.getStoreDir(getFamily().getNameAsString()));
1298     WALUtil.writeCompactionMarker(region.getWAL(), this.region.getTableDesc(),
1299         this.region.getRegionInfo(), compactionDescriptor, this.region.getSequenceId());
1300   }
1301 
1302   @VisibleForTesting
1303   void replaceStoreFiles(final Collection<StoreFile> compactedFiles,
1304       final Collection<StoreFile> result) throws IOException {
1305     this.lock.writeLock().lock();
1306     try {
1307       this.storeEngine.getStoreFileManager().addCompactionResults(compactedFiles, result);
1308       filesCompacting.removeAll(compactedFiles); // safe bc: lock.writeLock();
1309     } finally {
1310       this.lock.writeLock().unlock();
1311     }
1312   }
1313 
1314   /**
1315    * Log a very elaborate compaction completion message.
1316    * @param cr Request.
1317    * @param sfs Resulting files.
1318    * @param compactionStartTime Start time.
1319    */
1320   private void logCompactionEndMessage(
1321       CompactionRequest cr, List<StoreFile> sfs, long compactionStartTime) {
1322     long now = EnvironmentEdgeManager.currentTime();
1323     StringBuilder message = new StringBuilder(
1324       "Completed" + (cr.isMajor() ? " major" : "") + " compaction of "
1325       + cr.getFiles().size() + (cr.isAllFiles() ? " (all)" : "") + " file(s) in "
1326       + this + " of " + this.getRegionInfo().getRegionNameAsString() + " into ");
1327     if (sfs.isEmpty()) {
1328       message.append("none, ");
1329     } else {
1330       for (StoreFile sf: sfs) {
1331         message.append(sf.getPath().getName());
1332         message.append("(size=");
1333         message.append(TraditionalBinaryPrefix.long2String(sf.getReader().length(), "", 1));
1334         message.append("), ");
1335       }
1336     }
1337     message.append("total size for store is ")
1338       .append(StringUtils.TraditionalBinaryPrefix.long2String(storeSize, "", 1))
1339       .append(". This selection was in queue for ")
1340       .append(StringUtils.formatTimeDiff(compactionStartTime, cr.getSelectionTime()))
1341       .append(", and took ").append(StringUtils.formatTimeDiff(now, compactionStartTime))
1342       .append(" to execute.");
1343     LOG.info(message.toString());
1344     if (LOG.isTraceEnabled()) {
1345       int fileCount = storeEngine.getStoreFileManager().getStorefileCount();
1346       long resultSize = 0;
1347       for (StoreFile sf : sfs) {
1348         resultSize += sf.getReader().length();
1349       }
1350       String traceMessage = "COMPACTION start,end,size out,files in,files out,store size,"
1351         + "store files [" + compactionStartTime + "," + now + "," + resultSize + ","
1352           + cr.getFiles().size() + "," + sfs.size() + "," +  storeSize + "," + fileCount + "]";
1353       LOG.trace(traceMessage);
1354     }
1355   }
1356 
1357   /**
1358    * Call to complete a compaction. Its for the case where we find in the WAL a compaction
1359    * that was not finished.  We could find one recovering a WAL after a regionserver crash.
1360    * See HBASE-2231.
1361    * @param compaction
1362    */
1363   @Override
1364   public void replayCompactionMarker(CompactionDescriptor compaction,
1365       boolean pickCompactionFiles, boolean removeFiles)
1366       throws IOException {
1367     LOG.debug("Completing compaction from the WAL marker");
1368     List<String> compactionInputs = compaction.getCompactionInputList();
1369     List<String> compactionOutputs = Lists.newArrayList(compaction.getCompactionOutputList());
1370 
1371     // The Compaction Marker is written after the compaction is completed,
1372     // and the files moved into the region/family folder.
1373     //
1374     // If we crash after the entry is written, we may not have removed the
1375     // input files, but the output file is present.
1376     // (The unremoved input files will be removed by this function)
1377     //
1378     // If we scan the directory and the file is not present, it can mean that:
1379     //   - The file was manually removed by the user
1380     //   - The file was removed as consequence of subsequent compaction
1381     // so, we can't do anything with the "compaction output list" because those
1382     // files have already been loaded when opening the region (by virtue of
1383     // being in the store's folder) or they may be missing due to a compaction.
1384 
1385     String familyName = this.getColumnFamilyName();
1386     List<String> inputFiles = new ArrayList<String>(compactionInputs.size());
1387     for (String compactionInput : compactionInputs) {
1388       Path inputPath = fs.getStoreFilePath(familyName, compactionInput);
1389       inputFiles.add(inputPath.getName());
1390     }
1391 
1392     //some of the input files might already be deleted
1393     List<StoreFile> inputStoreFiles = new ArrayList<StoreFile>(compactionInputs.size());
1394     for (StoreFile sf : this.getStorefiles()) {
1395       if (inputFiles.contains(sf.getPath().getName())) {
1396         inputStoreFiles.add(sf);
1397       }
1398     }
1399 
1400     // check whether we need to pick up the new files
1401     List<StoreFile> outputStoreFiles = new ArrayList<StoreFile>(compactionOutputs.size());
1402 
1403     if (pickCompactionFiles) {
1404       for (StoreFile sf : this.getStorefiles()) {
1405         compactionOutputs.remove(sf.getPath().getName());
1406       }
1407       for (String compactionOutput : compactionOutputs) {
1408         StoreFileInfo storeFileInfo = fs.getStoreFileInfo(getColumnFamilyName(), compactionOutput);
1409         StoreFile storeFile = createStoreFileAndReader(storeFileInfo);
1410         outputStoreFiles.add(storeFile);
1411       }
1412     }
1413 
1414     if (!inputStoreFiles.isEmpty() || !outputStoreFiles.isEmpty()) {
1415       LOG.info("Replaying compaction marker, replacing input files: " +
1416           inputStoreFiles + " with output files : " + outputStoreFiles);
1417       this.replaceStoreFiles(inputStoreFiles, outputStoreFiles);
1418       this.completeCompaction(inputStoreFiles, removeFiles);
1419     }
1420   }
1421 
1422   /**
1423    * This method tries to compact N recent files for testing.
1424    * Note that because compacting "recent" files only makes sense for some policies,
1425    * e.g. the default one, it assumes default policy is used. It doesn't use policy,
1426    * but instead makes a compaction candidate list by itself.
1427    * @param N Number of files.
1428    */
1429   public void compactRecentForTestingAssumingDefaultPolicy(int N) throws IOException {
1430     List<StoreFile> filesToCompact;
1431     boolean isMajor;
1432 
1433     this.lock.readLock().lock();
1434     try {
1435       synchronized (filesCompacting) {
1436         filesToCompact = Lists.newArrayList(storeEngine.getStoreFileManager().getStorefiles());
1437         if (!filesCompacting.isEmpty()) {
1438           // exclude all files older than the newest file we're currently
1439           // compacting. this allows us to preserve contiguity (HBASE-2856)
1440           StoreFile last = filesCompacting.get(filesCompacting.size() - 1);
1441           int idx = filesToCompact.indexOf(last);
1442           Preconditions.checkArgument(idx != -1);
1443           filesToCompact.subList(0, idx + 1).clear();
1444         }
1445         int count = filesToCompact.size();
1446         if (N > count) {
1447           throw new RuntimeException("Not enough files");
1448         }
1449 
1450         filesToCompact = filesToCompact.subList(count - N, count);
1451         isMajor = (filesToCompact.size() == storeEngine.getStoreFileManager().getStorefileCount());
1452         filesCompacting.addAll(filesToCompact);
1453         Collections.sort(filesCompacting, StoreFile.Comparators.SEQ_ID);
1454       }
1455     } finally {
1456       this.lock.readLock().unlock();
1457     }
1458 
1459     try {
1460       // Ready to go. Have list of files to compact.
1461       List<Path> newFiles = ((DefaultCompactor)this.storeEngine.getCompactor())
1462           .compactForTesting(filesToCompact, isMajor);
1463       for (Path newFile: newFiles) {
1464         // Move the compaction into place.
1465         StoreFile sf = moveFileIntoPlace(newFile);
1466         if (this.getCoprocessorHost() != null) {
1467           this.getCoprocessorHost().postCompact(this, sf, null);
1468         }
1469         replaceStoreFiles(filesToCompact, Lists.newArrayList(sf));
1470         completeCompaction(filesToCompact, true);
1471       }
1472     } finally {
1473       synchronized (filesCompacting) {
1474         filesCompacting.removeAll(filesToCompact);
1475       }
1476     }
1477   }
1478 
1479   @Override
1480   public boolean hasReferences() {
1481     return StoreUtils.hasReferences(this.storeEngine.getStoreFileManager().getStorefiles());
1482   }
1483 
1484   @Override
1485   public CompactionProgress getCompactionProgress() {
1486     return this.storeEngine.getCompactor().getProgress();
1487   }
1488 
1489   @Override
1490   public boolean isMajorCompaction() throws IOException {
1491     for (StoreFile sf : this.storeEngine.getStoreFileManager().getStorefiles()) {
1492       // TODO: what are these reader checks all over the place?
1493       if (sf.getReader() == null) {
1494         LOG.debug("StoreFile " + sf + " has null Reader");
1495         return false;
1496       }
1497     }
1498     return storeEngine.getCompactionPolicy().isMajorCompaction(
1499         this.storeEngine.getStoreFileManager().getStorefiles());
1500   }
1501 
1502   @Override
1503   public CompactionContext requestCompaction() throws IOException {
1504     return requestCompaction(Store.NO_PRIORITY, null);
1505   }
1506 
1507   @Override
1508   public CompactionContext requestCompaction(int priority, CompactionRequest baseRequest)
1509       throws IOException {
1510     // don't even select for compaction if writes are disabled
1511     if (!this.areWritesEnabled()) {
1512       return null;
1513     }
1514 
1515     // Before we do compaction, try to get rid of unneeded files to simplify things.
1516     removeUnneededFiles();
1517 
1518     CompactionContext compaction = storeEngine.createCompaction();
1519     CompactionRequest request = null;
1520     this.lock.readLock().lock();
1521     try {
1522       synchronized (filesCompacting) {
1523         // First, see if coprocessor would want to override selection.
1524         if (this.getCoprocessorHost() != null) {
1525           List<StoreFile> candidatesForCoproc = compaction.preSelect(this.filesCompacting);
1526           boolean override = this.getCoprocessorHost().preCompactSelection(
1527               this, candidatesForCoproc, baseRequest);
1528           if (override) {
1529             // Coprocessor is overriding normal file selection.
1530             compaction.forceSelect(new CompactionRequest(candidatesForCoproc));
1531           }
1532         }
1533 
1534         // Normal case - coprocessor is not overriding file selection.
1535         if (!compaction.hasSelection()) {
1536           boolean isUserCompaction = priority == Store.PRIORITY_USER;
1537           boolean mayUseOffPeak = offPeakHours.isOffPeakHour() &&
1538               offPeakCompactionTracker.compareAndSet(false, true);
1539           try {
1540             compaction.select(this.filesCompacting, isUserCompaction,
1541               mayUseOffPeak, forceMajor && filesCompacting.isEmpty());
1542           } catch (IOException e) {
1543             if (mayUseOffPeak) {
1544               offPeakCompactionTracker.set(false);
1545             }
1546             throw e;
1547           }
1548           assert compaction.hasSelection();
1549           if (mayUseOffPeak && !compaction.getRequest().isOffPeak()) {
1550             // Compaction policy doesn't want to take advantage of off-peak.
1551             offPeakCompactionTracker.set(false);
1552           }
1553         }
1554         if (this.getCoprocessorHost() != null) {
1555           this.getCoprocessorHost().postCompactSelection(
1556               this, ImmutableList.copyOf(compaction.getRequest().getFiles()), baseRequest);
1557         }
1558 
1559         // Selected files; see if we have a compaction with some custom base request.
1560         if (baseRequest != null) {
1561           // Update the request with what the system thinks the request should be;
1562           // its up to the request if it wants to listen.
1563           compaction.forceSelect(
1564               baseRequest.combineWith(compaction.getRequest()));
1565         }
1566         // Finally, we have the resulting files list. Check if we have any files at all.
1567         request = compaction.getRequest();
1568         final Collection<StoreFile> selectedFiles = request.getFiles();
1569         if (selectedFiles.isEmpty()) {
1570           return null;
1571         }
1572 
1573         addToCompactingFiles(selectedFiles);
1574 
1575         // If we're enqueuing a major, clear the force flag.
1576         this.forceMajor = this.forceMajor && !request.isMajor();
1577 
1578         // Set common request properties.
1579         // Set priority, either override value supplied by caller or from store.
1580         request.setPriority((priority != Store.NO_PRIORITY) ? priority : getCompactPriority());
1581         request.setDescription(getRegionInfo().getRegionNameAsString(), getColumnFamilyName());
1582       }
1583     } finally {
1584       this.lock.readLock().unlock();
1585     }
1586 
1587     LOG.debug(getRegionInfo().getEncodedName() + " - "  + getColumnFamilyName()
1588         + ": Initiating " + (request.isMajor() ? "major" : "minor") + " compaction"
1589         + (request.isAllFiles() ? " (all files)" : ""));
1590     this.region.reportCompactionRequestStart(request.isMajor());
1591     return compaction;
1592   }
1593 
1594   /** Adds the files to compacting files. filesCompacting must be locked. */
1595   private void addToCompactingFiles(final Collection<StoreFile> filesToAdd) {
1596     if (filesToAdd == null) return;
1597     // Check that we do not try to compact the same StoreFile twice.
1598     if (!Collections.disjoint(filesCompacting, filesToAdd)) {
1599       Preconditions.checkArgument(false, "%s overlaps with %s", filesToAdd, filesCompacting);
1600     }
1601     filesCompacting.addAll(filesToAdd);
1602     Collections.sort(filesCompacting, StoreFile.Comparators.SEQ_ID);
1603   }
1604 
1605   private void removeUnneededFiles() throws IOException {
1606     if (!conf.getBoolean("hbase.store.delete.expired.storefile", true)) return;
1607     if (getFamily().getMinVersions() > 0) {
1608       LOG.debug("Skipping expired store file removal due to min version being " +
1609           getFamily().getMinVersions());
1610       return;
1611     }
1612     this.lock.readLock().lock();
1613     Collection<StoreFile> delSfs = null;
1614     try {
1615       synchronized (filesCompacting) {
1616         long cfTtl = getStoreFileTtl();
1617         if (cfTtl != Long.MAX_VALUE) {
1618           delSfs = storeEngine.getStoreFileManager().getUnneededFiles(
1619               EnvironmentEdgeManager.currentTime() - cfTtl, filesCompacting);
1620           addToCompactingFiles(delSfs);
1621         }
1622       }
1623     } finally {
1624       this.lock.readLock().unlock();
1625     }
1626     if (delSfs == null || delSfs.isEmpty()) return;
1627 
1628     Collection<StoreFile> newFiles = new ArrayList<StoreFile>(); // No new files.
1629     writeCompactionWalRecord(delSfs, newFiles);
1630     replaceStoreFiles(delSfs, newFiles);
1631     completeCompaction(delSfs);
1632     LOG.info("Completed removal of " + delSfs.size() + " unnecessary (expired) file(s) in "
1633         + this + " of " + this.getRegionInfo().getRegionNameAsString()
1634         + "; total size for store is " + TraditionalBinaryPrefix.long2String(storeSize, "", 1));
1635   }
1636 
1637   @Override
1638   public void cancelRequestedCompaction(CompactionContext compaction) {
1639     finishCompactionRequest(compaction.getRequest());
1640   }
1641 
1642   private void finishCompactionRequest(CompactionRequest cr) {
1643     this.region.reportCompactionRequestEnd(cr.isMajor(), cr.getFiles().size(), cr.getSize());
1644     if (cr.isOffPeak()) {
1645       offPeakCompactionTracker.set(false);
1646       cr.setOffPeak(false);
1647     }
1648     synchronized (filesCompacting) {
1649       filesCompacting.removeAll(cr.getFiles());
1650     }
1651   }
1652 
1653   /**
1654    * Validates a store file by opening and closing it. In HFileV2 this should
1655    * not be an expensive operation.
1656    *
1657    * @param path the path to the store file
1658    */
1659   private void validateStoreFile(Path path)
1660       throws IOException {
1661     StoreFile storeFile = null;
1662     try {
1663       storeFile = createStoreFileAndReader(path);
1664     } catch (IOException e) {
1665       LOG.error("Failed to open store file : " + path
1666           + ", keeping it in tmp location", e);
1667       throw e;
1668     } finally {
1669       if (storeFile != null) {
1670         storeFile.closeReader(false);
1671       }
1672     }
1673   }
1674 
1675   /**
1676    * <p>It works by processing a compaction that's been written to disk.
1677    *
1678    * <p>It is usually invoked at the end of a compaction, but might also be
1679    * invoked at HStore startup, if the prior execution died midway through.
1680    *
1681    * <p>Moving the compacted TreeMap into place means:
1682    * <pre>
1683    * 1) Unload all replaced StoreFile, close and collect list to delete.
1684    * 2) Compute new store size
1685    * </pre>
1686    *
1687    * @param compactedFiles list of files that were compacted
1688    */
1689   @VisibleForTesting
1690   protected void completeCompaction(final Collection<StoreFile> compactedFiles)
1691     throws IOException {
1692     completeCompaction(compactedFiles, true);
1693   }
1694 
1695 
1696   /**
1697    * <p>It works by processing a compaction that's been written to disk.
1698    *
1699    * <p>It is usually invoked at the end of a compaction, but might also be
1700    * invoked at HStore startup, if the prior execution died midway through.
1701    *
1702    * <p>Moving the compacted TreeMap into place means:
1703    * <pre>
1704    * 1) Unload all replaced StoreFile, close and collect list to delete.
1705    * 2) Compute new store size
1706    * </pre>
1707    *
1708    * @param compactedFiles list of files that were compacted
1709    */
1710   @VisibleForTesting
1711   protected void completeCompaction(final Collection<StoreFile> compactedFiles, boolean removeFiles)
1712       throws IOException {
1713     try {
1714       // Do not delete old store files until we have sent out notification of
1715       // change in case old files are still being accessed by outstanding scanners.
1716       // Don't do this under writeLock; see HBASE-4485 for a possible deadlock
1717       // scenario that could have happened if continue to hold the lock.
1718       notifyChangedReadersObservers();
1719       // At this point the store will use new files for all scanners.
1720 
1721       // let the archive util decide if we should archive or delete the files
1722       LOG.debug("Removing store files after compaction...");
1723       for (StoreFile compactedFile : compactedFiles) {
1724         compactedFile.closeReader(true);
1725       }
1726       if (removeFiles) {
1727         this.fs.removeStoreFiles(this.getColumnFamilyName(), compactedFiles);
1728       }
1729     } catch (IOException e) {
1730       e = e instanceof RemoteException ?
1731                 ((RemoteException)e).unwrapRemoteException() : e;
1732       LOG.error("Failed removing compacted files in " + this +
1733         ". Files we were trying to remove are " + compactedFiles.toString() +
1734         "; some of them may have been already removed", e);
1735     }
1736 
1737     // 4. Compute new store size
1738     this.storeSize = 0L;
1739     this.totalUncompressedBytes = 0L;
1740     for (StoreFile hsf : this.storeEngine.getStoreFileManager().getStorefiles()) {
1741       StoreFile.Reader r = hsf.getReader();
1742       if (r == null) {
1743         LOG.warn("StoreFile " + hsf + " has a null Reader");
1744         continue;
1745       }
1746       this.storeSize += r.length();
1747       this.totalUncompressedBytes += r.getTotalUncompressedBytes();
1748     }
1749   }
1750 
1751   /*
1752    * @param wantedVersions How many versions were asked for.
1753    * @return wantedVersions or this families' {@link HConstants#VERSIONS}.
1754    */
1755   int versionsToReturn(final int wantedVersions) {
1756     if (wantedVersions <= 0) {
1757       throw new IllegalArgumentException("Number of versions must be > 0");
1758     }
1759     // Make sure we do not return more than maximum versions for this store.
1760     int maxVersions = this.family.getMaxVersions();
1761     return wantedVersions > maxVersions ? maxVersions: wantedVersions;
1762   }
1763 
1764   /**
1765    * @param cell
1766    * @param oldestTimestamp
1767    * @return true if the cell is expired
1768    */
1769   static boolean isCellTTLExpired(final Cell cell, final long oldestTimestamp, final long now) {
1770     // Do not create an Iterator or Tag objects unless the cell actually has tags.
1771     if (cell.getTagsLength() > 0) {
1772       // Look for a TTL tag first. Use it instead of the family setting if
1773       // found. If a cell has multiple TTLs, resolve the conflict by using the
1774       // first tag encountered.
1775       Iterator<Tag> i = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(),
1776         cell.getTagsLength());
1777       while (i.hasNext()) {
1778         Tag t = i.next();
1779         if (TagType.TTL_TAG_TYPE == t.getType()) {
1780           // Unlike in schema cell TTLs are stored in milliseconds, no need
1781           // to convert
1782           long ts = cell.getTimestamp();
1783           assert t.getTagLength() == Bytes.SIZEOF_LONG;
1784           long ttl = Bytes.toLong(t.getBuffer(), t.getTagOffset(), t.getTagLength());
1785           if (ts + ttl < now) {
1786             return true;
1787           }
1788           // Per cell TTLs cannot extend lifetime beyond family settings, so
1789           // fall through to check that
1790           break;
1791         }
1792       }
1793     }
1794     return false;
1795   }
1796 
1797   @Override
1798   public boolean canSplit() {
1799     this.lock.readLock().lock();
1800     try {
1801       // Not split-able if we find a reference store file present in the store.
1802       boolean result = !hasReferences();
1803       if (!result && LOG.isDebugEnabled()) {
1804         LOG.debug("Cannot split region due to reference files being there");
1805       }
1806       return result;
1807     } finally {
1808       this.lock.readLock().unlock();
1809     }
1810   }
1811 
1812   @Override
1813   public byte[] getSplitPoint() {
1814     this.lock.readLock().lock();
1815     try {
1816       // Should already be enforced by the split policy!
1817       assert !this.getRegionInfo().isMetaRegion();
1818       // Not split-able if we find a reference store file present in the store.
1819       if (hasReferences()) {
1820         return null;
1821       }
1822       return this.storeEngine.getStoreFileManager().getSplitPoint();
1823     } catch(IOException e) {
1824       LOG.warn("Failed getting store size for " + this, e);
1825     } finally {
1826       this.lock.readLock().unlock();
1827     }
1828     return null;
1829   }
1830 
1831   @Override
1832   public long getLastCompactSize() {
1833     return this.lastCompactSize;
1834   }
1835 
1836   @Override
1837   public long getSize() {
1838     return storeSize;
1839   }
1840 
1841   @Override
1842   public void triggerMajorCompaction() {
1843     this.forceMajor = true;
1844   }
1845 
1846 
1847   //////////////////////////////////////////////////////////////////////////////
1848   // File administration
1849   //////////////////////////////////////////////////////////////////////////////
1850 
1851   @Override
1852   public KeyValueScanner getScanner(Scan scan,
1853       final NavigableSet<byte []> targetCols, long readPt) throws IOException {
1854     lock.readLock().lock();
1855     try {
1856       KeyValueScanner scanner = null;
1857       if (this.getCoprocessorHost() != null) {
1858         scanner = this.getCoprocessorHost().preStoreScannerOpen(this, scan, targetCols);
1859       }
1860       scanner = createScanner(scan, targetCols, readPt, scanner);
1861       return scanner;
1862     } finally {
1863       lock.readLock().unlock();
1864     }
1865   }
1866 
1867   protected KeyValueScanner createScanner(Scan scan, final NavigableSet<byte[]> targetCols,
1868       long readPt, KeyValueScanner scanner) throws IOException {
1869     if (scanner == null) {
1870       scanner = scan.isReversed() ? new ReversedStoreScanner(this,
1871           getScanInfo(), scan, targetCols, readPt) : new StoreScanner(this,
1872           getScanInfo(), scan, targetCols, readPt);
1873     }
1874     return scanner;
1875   }
1876 
1877   @Override
1878   public String toString() {
1879     return this.getColumnFamilyName();
1880   }
1881 
1882   @Override
1883   public int getStorefilesCount() {
1884     return this.storeEngine.getStoreFileManager().getStorefileCount();
1885   }
1886 
1887   @Override
1888   public long getStoreSizeUncompressed() {
1889     return this.totalUncompressedBytes;
1890   }
1891 
1892   @Override
1893   public long getStorefilesSize() {
1894     long size = 0;
1895     for (StoreFile s: this.storeEngine.getStoreFileManager().getStorefiles()) {
1896       StoreFile.Reader r = s.getReader();
1897       if (r == null) {
1898         LOG.warn("StoreFile " + s + " has a null Reader");
1899         continue;
1900       }
1901       size += r.length();
1902     }
1903     return size;
1904   }
1905 
1906   @Override
1907   public long getStorefilesIndexSize() {
1908     long size = 0;
1909     for (StoreFile s: this.storeEngine.getStoreFileManager().getStorefiles()) {
1910       StoreFile.Reader r = s.getReader();
1911       if (r == null) {
1912         LOG.warn("StoreFile " + s + " has a null Reader");
1913         continue;
1914       }
1915       size += r.indexSize();
1916     }
1917     return size;
1918   }
1919 
1920   @Override
1921   public long getTotalStaticIndexSize() {
1922     long size = 0;
1923     for (StoreFile s : this.storeEngine.getStoreFileManager().getStorefiles()) {
1924       size += s.getReader().getUncompressedDataIndexSize();
1925     }
1926     return size;
1927   }
1928 
1929   @Override
1930   public long getTotalStaticBloomSize() {
1931     long size = 0;
1932     for (StoreFile s : this.storeEngine.getStoreFileManager().getStorefiles()) {
1933       StoreFile.Reader r = s.getReader();
1934       size += r.getTotalBloomSize();
1935     }
1936     return size;
1937   }
1938 
1939   @Override
1940   public long getMemStoreSize() {
1941     return this.memstore.size();
1942   }
1943 
1944   @Override
1945   public int getCompactPriority() {
1946     int priority = this.storeEngine.getStoreFileManager().getStoreCompactionPriority();
1947     if (priority == PRIORITY_USER) {
1948       LOG.warn("Compaction priority is USER despite there being no user compaction");
1949     }
1950     return priority;
1951   }
1952 
1953   @Override
1954   public boolean throttleCompaction(long compactionSize) {
1955     return storeEngine.getCompactionPolicy().throttleCompaction(compactionSize);
1956   }
1957 
1958   public HRegion getHRegion() {
1959     return this.region;
1960   }
1961 
1962   @Override
1963   public RegionCoprocessorHost getCoprocessorHost() {
1964     return this.region.getCoprocessorHost();
1965   }
1966 
1967   @Override
1968   public HRegionInfo getRegionInfo() {
1969     return this.fs.getRegionInfo();
1970   }
1971 
1972   @Override
1973   public boolean areWritesEnabled() {
1974     return this.region.areWritesEnabled();
1975   }
1976 
1977   @Override
1978   public long getSmallestReadPoint() {
1979     return this.region.getSmallestReadPoint();
1980   }
1981 
1982   /**
1983    * Used in tests. TODO: Remove
1984    *
1985    * Updates the value for the given row/family/qualifier. This function will always be seen as
1986    * atomic by other readers because it only puts a single KV to memstore. Thus no read/write
1987    * control necessary.
1988    * @param row row to update
1989    * @param f family to update
1990    * @param qualifier qualifier to update
1991    * @param newValue the new value to set into memstore
1992    * @return memstore size delta
1993    * @throws IOException
1994    */
1995   public long updateColumnValue(byte [] row, byte [] f,
1996                                 byte [] qualifier, long newValue)
1997       throws IOException {
1998 
1999     this.lock.readLock().lock();
2000     try {
2001       long now = EnvironmentEdgeManager.currentTime();
2002 
2003       return this.memstore.updateColumnValue(row,
2004           f,
2005           qualifier,
2006           newValue,
2007           now);
2008 
2009     } finally {
2010       this.lock.readLock().unlock();
2011     }
2012   }
2013 
2014   @Override
2015   public long upsert(Iterable<Cell> cells, long readpoint) throws IOException {
2016     this.lock.readLock().lock();
2017     try {
2018       return this.memstore.upsert(cells, readpoint);
2019     } finally {
2020       this.lock.readLock().unlock();
2021     }
2022   }
2023 
2024   @Override
2025   public StoreFlushContext createFlushContext(long cacheFlushId) {
2026     return new StoreFlusherImpl(cacheFlushId);
2027   }
2028 
2029   private class StoreFlusherImpl implements StoreFlushContext {
2030 
2031     private long cacheFlushSeqNum;
2032     private MemStoreSnapshot snapshot;
2033     private List<Path> tempFiles;
2034     private List<Path> committedFiles;
2035     private long cacheFlushCount;
2036     private long cacheFlushSize;
2037 
2038     private StoreFlusherImpl(long cacheFlushSeqNum) {
2039       this.cacheFlushSeqNum = cacheFlushSeqNum;
2040     }
2041 
2042     /**
2043      * This is not thread safe. The caller should have a lock on the region or the store.
2044      * If necessary, the lock can be added with the patch provided in HBASE-10087
2045      */
2046     @Override
2047     public void prepare() {
2048       this.snapshot = memstore.snapshot();
2049       this.cacheFlushCount = snapshot.getCellsCount();
2050       this.cacheFlushSize = snapshot.getSize();
2051       committedFiles = new ArrayList<Path>(1);
2052     }
2053 
2054     @Override
2055     public void flushCache(MonitoredTask status) throws IOException {
2056       tempFiles = HStore.this.flushCache(cacheFlushSeqNum, snapshot, status);
2057     }
2058 
2059     @Override
2060     public boolean commit(MonitoredTask status) throws IOException {
2061       if (this.tempFiles == null || this.tempFiles.isEmpty()) {
2062         return false;
2063       }
2064       List<StoreFile> storeFiles = new ArrayList<StoreFile>(this.tempFiles.size());
2065       for (Path storeFilePath : tempFiles) {
2066         try {
2067           storeFiles.add(HStore.this.commitFile(storeFilePath, cacheFlushSeqNum, status));
2068         } catch (IOException ex) {
2069           LOG.error("Failed to commit store file " + storeFilePath, ex);
2070           // Try to delete the files we have committed before.
2071           for (StoreFile sf : storeFiles) {
2072             Path pathToDelete = sf.getPath();
2073             try {
2074               sf.deleteReader();
2075             } catch (IOException deleteEx) {
2076               LOG.fatal("Failed to delete store file we committed, halting " + pathToDelete, ex);
2077               Runtime.getRuntime().halt(1);
2078             }
2079           }
2080           throw new IOException("Failed to commit the flush", ex);
2081         }
2082       }
2083 
2084       for (StoreFile sf : storeFiles) {
2085         if (HStore.this.getCoprocessorHost() != null) {
2086           HStore.this.getCoprocessorHost().postFlush(HStore.this, sf);
2087         }
2088         committedFiles.add(sf.getPath());
2089       }
2090 
2091       HStore.this.flushedCellsCount += cacheFlushCount;
2092       HStore.this.flushedCellsSize += cacheFlushSize;
2093 
2094       // Add new file to store files.  Clear snapshot too while we have the Store write lock.
2095       return HStore.this.updateStorefiles(storeFiles, snapshot.getId());
2096     }
2097 
2098     @Override
2099     public List<Path> getCommittedFiles() {
2100       return committedFiles;
2101     }
2102 
2103     /**
2104      * Similar to commit, but called in secondary region replicas for replaying the
2105      * flush cache from primary region. Adds the new files to the store, and drops the
2106      * snapshot depending on dropMemstoreSnapshot argument.
2107      * @param fileNames names of the flushed files
2108      * @param dropMemstoreSnapshot whether to drop the prepared memstore snapshot
2109      * @throws IOException
2110      */
2111     @Override
2112     public void replayFlush(List<String> fileNames, boolean dropMemstoreSnapshot)
2113         throws IOException {
2114       List<StoreFile> storeFiles = new ArrayList<StoreFile>(fileNames.size());
2115       for (String file : fileNames) {
2116         // open the file as a store file (hfile link, etc)
2117         StoreFileInfo storeFileInfo = fs.getStoreFileInfo(getColumnFamilyName(), file);
2118         StoreFile storeFile = createStoreFileAndReader(storeFileInfo);
2119         storeFiles.add(storeFile);
2120         HStore.this.storeSize += storeFile.getReader().length();
2121         HStore.this.totalUncompressedBytes += storeFile.getReader().getTotalUncompressedBytes();
2122         if (LOG.isInfoEnabled()) {
2123           LOG.info("Region: " + HStore.this.getRegionInfo().getEncodedName() +
2124             " added " + storeFile + ", entries=" + storeFile.getReader().getEntries() +
2125             ", sequenceid=" +  + storeFile.getReader().getSequenceID() +
2126             ", filesize=" + StringUtils.humanReadableInt(storeFile.getReader().length()));
2127         }
2128       }
2129 
2130       long snapshotId = -1; // -1 means do not drop
2131       if (dropMemstoreSnapshot && snapshot != null) {
2132         snapshotId = snapshot.getId();
2133       }
2134       HStore.this.updateStorefiles(storeFiles, snapshotId);
2135     }
2136 
2137     /**
2138      * Abort the snapshot preparation. Drops the snapshot if any.
2139      * @throws IOException
2140      */
2141     @Override
2142     public void abort() throws IOException {
2143       if (snapshot == null) {
2144         return;
2145       }
2146       HStore.this.updateStorefiles(new ArrayList<StoreFile>(0), snapshot.getId());
2147     }
2148   }
2149 
2150   @Override
2151   public boolean needsCompaction() {
2152     return this.storeEngine.needsCompaction(this.filesCompacting);
2153   }
2154 
2155   @Override
2156   public CacheConfig getCacheConfig() {
2157     return this.cacheConf;
2158   }
2159 
2160   public static final long FIXED_OVERHEAD =
2161       ClassSize.align(ClassSize.OBJECT + (16 * ClassSize.REFERENCE) + (10 * Bytes.SIZEOF_LONG)
2162               + (5 * Bytes.SIZEOF_INT) + (2 * Bytes.SIZEOF_BOOLEAN));
2163 
2164   public static final long DEEP_OVERHEAD = ClassSize.align(FIXED_OVERHEAD
2165       + ClassSize.OBJECT + ClassSize.REENTRANT_LOCK
2166       + ClassSize.CONCURRENT_SKIPLISTMAP
2167       + ClassSize.CONCURRENT_SKIPLISTMAP_ENTRY + ClassSize.OBJECT
2168       + ScanInfo.FIXED_OVERHEAD);
2169 
2170   @Override
2171   public long heapSize() {
2172     return DEEP_OVERHEAD + this.memstore.heapSize();
2173   }
2174 
2175   @Override
2176   public CellComparator getComparator() {
2177     return comparator;
2178   }
2179 
2180   @Override
2181   public ScanInfo getScanInfo() {
2182     return scanInfo;
2183   }
2184 
2185   /**
2186    * Set scan info, used by test
2187    * @param scanInfo new scan info to use for test
2188    */
2189   void setScanInfo(ScanInfo scanInfo) {
2190     this.scanInfo = scanInfo;
2191   }
2192 
2193   @Override
2194   public boolean hasTooManyStoreFiles() {
2195     return getStorefilesCount() > this.blockingFileCount;
2196   }
2197 
2198   @Override
2199   public long getFlushedCellsCount() {
2200     return flushedCellsCount;
2201   }
2202 
2203   @Override
2204   public long getFlushedCellsSize() {
2205     return flushedCellsSize;
2206   }
2207 
2208   @Override
2209   public long getCompactedCellsCount() {
2210     return compactedCellsCount;
2211   }
2212 
2213   @Override
2214   public long getCompactedCellsSize() {
2215     return compactedCellsSize;
2216   }
2217 
2218   @Override
2219   public long getMajorCompactedCellsCount() {
2220     return majorCompactedCellsCount;
2221   }
2222 
2223   @Override
2224   public long getMajorCompactedCellsSize() {
2225     return majorCompactedCellsSize;
2226   }
2227 
2228   /**
2229    * Returns the StoreEngine that is backing this concrete implementation of Store.
2230    * @return Returns the {@link StoreEngine} object used internally inside this HStore object.
2231    */
2232   @VisibleForTesting
2233   public StoreEngine<?, ?, ?, ?> getStoreEngine() {
2234     return this.storeEngine;
2235   }
2236 
2237   protected OffPeakHours getOffPeakHours() {
2238     return this.offPeakHours;
2239   }
2240 
2241   /**
2242    * {@inheritDoc}
2243    */
2244   @Override
2245   public void onConfigurationChange(Configuration conf) {
2246     this.conf = new CompoundConfiguration()
2247             .add(conf)
2248             .addBytesMap(family.getValues());
2249     this.storeEngine.compactionPolicy.setConf(conf);
2250     this.offPeakHours = OffPeakHours.getInstance(conf);
2251   }
2252 
2253   /**
2254    * {@inheritDoc}
2255    */
2256   @Override
2257   public void registerChildren(ConfigurationManager manager) {
2258     // No children to register
2259   }
2260 
2261   /**
2262    * {@inheritDoc}
2263    */
2264   @Override
2265   public void deregisterChildren(ConfigurationManager manager) {
2266     // No children to deregister
2267   }
2268 
2269   @Override
2270   public double getCompactionPressure() {
2271     return storeEngine.getStoreFileManager().getCompactionPressure();
2272   }
2273 }