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