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