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.DataInput;
22  import java.io.IOException;
23  import java.io.UnsupportedEncodingException;
24  import java.net.InetSocketAddress;
25  import java.net.URLEncoder;
26  import java.nio.ByteBuffer;
27  import java.util.Arrays;
28  import java.util.Collection;
29  import java.util.Collections;
30  import java.util.Comparator;
31  import java.util.HashSet;
32  import java.util.Map;
33  import java.util.Set;
34  import java.util.SortedSet;
35  import java.util.UUID;
36  import java.util.concurrent.atomic.AtomicBoolean;
37  import java.util.concurrent.atomic.AtomicInteger;
38  
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  import org.apache.hadoop.conf.Configuration;
42  import org.apache.hadoop.fs.FileSystem;
43  import org.apache.hadoop.fs.Path;
44  import org.apache.hadoop.hbase.Cell;
45  import org.apache.hadoop.hbase.CellUtil;
46  import org.apache.hadoop.hbase.HConstants;
47  import org.apache.hadoop.hbase.HDFSBlocksDistribution;
48  import org.apache.hadoop.hbase.KeyValue;
49  import org.apache.hadoop.hbase.KeyValue.KVComparator;
50  import org.apache.hadoop.hbase.KeyValueUtil;
51  import org.apache.hadoop.hbase.classification.InterfaceAudience;
52  import org.apache.hadoop.hbase.client.Scan;
53  import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
54  import org.apache.hadoop.hbase.io.TimeRange;
55  import org.apache.hadoop.hbase.io.hfile.BlockType;
56  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
57  import org.apache.hadoop.hbase.io.hfile.HFile;
58  import org.apache.hadoop.hbase.io.hfile.HFileContext;
59  import org.apache.hadoop.hbase.io.hfile.HFileScanner;
60  import org.apache.hadoop.hbase.io.hfile.HFileWriterV2;
61  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
62  import org.apache.hadoop.hbase.regionserver.compactions.Compactor;
63  import org.apache.hadoop.hbase.util.BloomFilter;
64  import org.apache.hadoop.hbase.util.BloomFilterFactory;
65  import org.apache.hadoop.hbase.util.BloomFilterWriter;
66  import org.apache.hadoop.hbase.util.Bytes;
67  import org.apache.hadoop.io.WritableUtils;
68  
69  import com.google.common.annotations.VisibleForTesting;
70  import com.google.common.base.Function;
71  import com.google.common.base.Preconditions;
72  import com.google.common.collect.ImmutableList;
73  import com.google.common.collect.Ordering;
74  
75  /**
76   * A Store data file.  Stores usually have one or more of these files.  They
77   * are produced by flushing the memstore to disk.  To
78   * create, instantiate a writer using {@link StoreFile.WriterBuilder}
79   * and append data. Be sure to add any metadata before calling close on the
80   * Writer (Use the appendMetadata convenience methods). On close, a StoreFile
81   * is sitting in the Filesystem.  To refer to it, create a StoreFile instance
82   * passing filesystem and path.  To read, call {@link #createReader()}.
83   * <p>StoreFiles may also reference store files in another Store.
84   *
85   * The reason for this weird pattern where you use a different instance for the
86   * writer and a reader is that we write once but read a lot more.
87   */
88  @InterfaceAudience.LimitedPrivate("Coprocessor")
89  public class StoreFile {
90    private static final Log LOG = LogFactory.getLog(StoreFile.class.getName());
91  
92    // Keys for fileinfo values in HFile
93  
94    /** Max Sequence ID in FileInfo */
95    public static final byte [] MAX_SEQ_ID_KEY = Bytes.toBytes("MAX_SEQ_ID_KEY");
96  
97    /** Major compaction flag in FileInfo */
98    public static final byte[] MAJOR_COMPACTION_KEY =
99        Bytes.toBytes("MAJOR_COMPACTION_KEY");
100 
101   /** Minor compaction flag in FileInfo */
102   public static final byte[] EXCLUDE_FROM_MINOR_COMPACTION_KEY =
103       Bytes.toBytes("EXCLUDE_FROM_MINOR_COMPACTION");
104 
105   /** Bloom filter Type in FileInfo */
106   public static final byte[] BLOOM_FILTER_TYPE_KEY =
107       Bytes.toBytes("BLOOM_FILTER_TYPE");
108 
109   /** Delete Family Count in FileInfo */
110   public static final byte[] DELETE_FAMILY_COUNT =
111       Bytes.toBytes("DELETE_FAMILY_COUNT");
112 
113   /** Last Bloom filter key in FileInfo */
114   private static final byte[] LAST_BLOOM_KEY = Bytes.toBytes("LAST_BLOOM_KEY");
115 
116   /** Key for Timerange information in metadata*/
117   public static final byte[] TIMERANGE_KEY = Bytes.toBytes("TIMERANGE");
118 
119   /** Key for timestamp of earliest-put in metadata*/
120   public static final byte[] EARLIEST_PUT_TS = Bytes.toBytes("EARLIEST_PUT_TS");
121 
122   /**
123    * Key for compaction event which contains the compacted storefiles in FileInfo
124    */
125   public static final byte[] COMPACTION_EVENT_KEY = Bytes.toBytes("COMPACTION_EVENT_KEY");
126 
127   private final StoreFileInfo fileInfo;
128   private final FileSystem fs;
129 
130   // Block cache configuration and reference.
131   private final CacheConfig cacheConf;
132 
133   // Keys for metadata stored in backing HFile.
134   // Set when we obtain a Reader.
135   private long sequenceid = -1;
136 
137   // max of the MemstoreTS in the KV's in this store
138   // Set when we obtain a Reader.
139   private long maxMemstoreTS = -1;
140 
141   // firstKey, lastkey and cellComparator will be set when openReader.
142   private byte[] firstKey;
143 
144   private byte[] lastKey;
145 
146   private KVComparator comparator;
147 
148   CacheConfig getCacheConf() {
149     return cacheConf;
150   }
151 
152   public byte[] getFirstKey() {
153     return firstKey;
154   }
155 
156   public byte[] getLastKey() {
157     return lastKey;
158   }
159 
160   public KVComparator getComparator() {
161     return comparator;
162   }
163 
164   public long getMaxMemstoreTS() {
165     return maxMemstoreTS;
166   }
167 
168   public void setMaxMemstoreTS(long maxMemstoreTS) {
169     this.maxMemstoreTS = maxMemstoreTS;
170   }
171 
172   // If true, this file was product of a major compaction.  Its then set
173   // whenever you get a Reader.
174   private AtomicBoolean majorCompaction = null;
175 
176   // If true, this file should not be included in minor compactions.
177   // It's set whenever you get a Reader.
178   private boolean excludeFromMinorCompaction = false;
179 
180   // This file was product of these compacted store files
181   private final Set<String> compactedStoreFiles = new HashSet<>();
182 
183   /** Meta key set when store file is a result of a bulk load */
184   public static final byte[] BULKLOAD_TASK_KEY =
185     Bytes.toBytes("BULKLOAD_SOURCE_TASK");
186   public static final byte[] BULKLOAD_TIME_KEY =
187     Bytes.toBytes("BULKLOAD_TIMESTAMP");
188 
189   /**
190    * Map of the metadata entries in the corresponding HFile
191    */
192   private Map<byte[], byte[]> metadataMap;
193 
194   // StoreFile.Reader
195   private volatile Reader reader;
196 
197   /**
198    * Bloom filter type specified in column family configuration. Does not
199    * necessarily correspond to the Bloom filter type present in the HFile.
200    */
201   private final BloomType cfBloomType;
202 
203   /**
204    * Constructor, loads a reader and it's indices, etc. May allocate a
205    * substantial amount of ram depending on the underlying files (10-20MB?).
206    *
207    * @param fs  The current file system to use.
208    * @param p  The path of the file.
209    * @param conf  The current configuration.
210    * @param cacheConf  The cache configuration and block cache reference.
211    * @param cfBloomType The bloom type to use for this store file as specified
212    *          by column family configuration. This may or may not be the same
213    *          as the Bloom filter type actually present in the HFile, because
214    *          column family configuration might change. If this is
215    *          {@link BloomType#NONE}, the existing Bloom filter is ignored.
216    * @throws IOException When opening the reader fails.
217    */
218   public StoreFile(final FileSystem fs, final Path p, final Configuration conf,
219         final CacheConfig cacheConf, final BloomType cfBloomType) throws IOException {
220     this(fs, new StoreFileInfo(conf, fs, p), conf, cacheConf, cfBloomType);
221   }
222 
223 
224   /**
225    * Constructor, loads a reader and it's indices, etc. May allocate a
226    * substantial amount of ram depending on the underlying files (10-20MB?).
227    *
228    * @param fs  The current file system to use.
229    * @param fileInfo  The store file information.
230    * @param conf  The current configuration.
231    * @param cacheConf  The cache configuration and block cache reference.
232    * @param cfBloomType The bloom type to use for this store file as specified
233    *          by column family configuration. This may or may not be the same
234    *          as the Bloom filter type actually present in the HFile, because
235    *          column family configuration might change. If this is
236    *          {@link BloomType#NONE}, the existing Bloom filter is ignored.
237    * @throws IOException When opening the reader fails.
238    */
239   public StoreFile(final FileSystem fs, final StoreFileInfo fileInfo, final Configuration conf,
240       final CacheConfig cacheConf,  final BloomType cfBloomType) throws IOException {
241     this.fs = fs;
242     this.fileInfo = fileInfo;
243     this.cacheConf = cacheConf;
244 
245     if (BloomFilterFactory.isGeneralBloomEnabled(conf)) {
246       this.cfBloomType = cfBloomType;
247     } else {
248       LOG.info("Ignoring bloom filter check for file " + this.getPath() + ": " +
249           "cfBloomType=" + cfBloomType + " (disabled in config)");
250       this.cfBloomType = BloomType.NONE;
251     }
252   }
253 
254   /**
255    * Clone
256    * @param other The StoreFile to clone from
257    */
258   public StoreFile(final StoreFile other) {
259     this.fs = other.fs;
260     this.fileInfo = other.fileInfo;
261     this.cacheConf = other.cacheConf;
262     this.cfBloomType = other.cfBloomType;
263   }
264 
265   /**
266    * Clone a StoreFile for opening private reader.
267    */
268   public StoreFile cloneForReader() {
269     return new StoreFile(this);
270   }
271 
272   /**
273    * @return the StoreFile object associated to this StoreFile.
274    *         null if the StoreFile is not a reference.
275    */
276   public StoreFileInfo getFileInfo() {
277     return this.fileInfo;
278   }
279 
280   /**
281    * @return Path or null if this StoreFile was made with a Stream.
282    */
283   public Path getPath() {
284     return this.fileInfo.getPath();
285   }
286 
287   /**
288    * @return Encoded Path if this StoreFile was made with a Stream.
289    */
290   public Path getEncodedPath() {
291     try {
292       return new Path(URLEncoder.encode(fileInfo.getPath().toString(), HConstants.UTF8_ENCODING));
293     } catch (UnsupportedEncodingException ex) {
294       throw new RuntimeException("URLEncoder doesn't support UTF-8", ex);
295     }
296   }
297 
298   /**
299    * @return Returns the qualified path of this StoreFile
300    */
301   public Path getQualifiedPath() {
302     return this.fileInfo.getPath().makeQualified(fs);
303   }
304 
305   /**
306    * @return True if this is a StoreFile Reference; call
307    * after {@link #open(boolean canUseDropBehind)} else may get wrong answer.
308    */
309   public boolean isReference() {
310     return this.fileInfo.isReference();
311   }
312 
313   /**
314    * @return True if this is HFile.
315    */
316   public boolean isHFile() {
317     return StoreFileInfo.isHFile(this.fileInfo.getPath());
318   }
319 
320   /**
321    * @return True if this file was made by a major compaction.
322    */
323   public boolean isMajorCompaction() {
324     if (this.majorCompaction == null) {
325       throw new NullPointerException("This has not been set yet");
326     }
327     return this.majorCompaction.get();
328   }
329 
330   /**
331    * @return True if this file should not be part of a minor compaction.
332    */
333   public boolean excludeFromMinorCompaction() {
334     return this.excludeFromMinorCompaction;
335   }
336 
337   /**
338    * @return This files maximum edit sequence id.
339    */
340   public long getMaxSequenceId() {
341     return this.sequenceid;
342   }
343 
344   public long getModificationTimeStamp() throws IOException {
345     return (fileInfo == null) ? 0 : fileInfo.getModificationTime();
346   }
347 
348   /**
349    * Only used by the Striped Compaction Policy
350    * @param key
351    * @return value associated with the metadata key
352    */
353   public byte[] getMetadataValue(byte[] key) {
354     return metadataMap.get(key);
355   }
356 
357   /**
358    * Return the largest memstoreTS found across all storefiles in
359    * the given list. Store files that were created by a mapreduce
360    * bulk load are ignored, as they do not correspond to any specific
361    * put operation, and thus do not have a memstoreTS associated with them.
362    * @return 0 if no non-bulk-load files are provided or, this is Store that
363    * does not yet have any store files.
364    */
365   public static long getMaxMemstoreTSInList(Collection<StoreFile> sfs) {
366     long max = 0;
367     for (StoreFile sf : sfs) {
368       if (!sf.isBulkLoadResult()) {
369         max = Math.max(max, sf.getMaxMemstoreTS());
370       }
371     }
372     return max;
373   }
374 
375   /**
376    * Return the highest sequence ID found across all storefiles in
377    * the given list.
378    * @param sfs
379    * @return 0 if no non-bulk-load files are provided or, this is Store that
380    * does not yet have any store files.
381    */
382   public static long getMaxSequenceIdInList(Collection<StoreFile> sfs) {
383     long max = 0;
384     for (StoreFile sf : sfs) {
385       max = Math.max(max, sf.getMaxSequenceId());
386     }
387     return max;
388   }
389 
390   /**
391    * Check if this storefile was created by bulk load.
392    * When a hfile is bulk loaded into HBase, we append
393    * '_SeqId_&lt;id-when-loaded&gt;' to the hfile name, unless
394    * "hbase.mapreduce.bulkload.assign.sequenceNumbers" is
395    * explicitly turned off.
396    * If "hbase.mapreduce.bulkload.assign.sequenceNumbers"
397    * is turned off, fall back to BULKLOAD_TIME_KEY.
398    * @return true if this storefile was created by bulk load.
399    */
400   public boolean isBulkLoadResult() {
401     boolean bulkLoadedHFile = false;
402     String fileName = this.getPath().getName();
403     int startPos = fileName.indexOf("SeqId_");
404     if (startPos != -1) {
405       bulkLoadedHFile = true;
406     }
407     return bulkLoadedHFile || metadataMap.containsKey(BULKLOAD_TIME_KEY);
408   }
409 
410   @VisibleForTesting
411   public boolean isCompactedAway() {
412     if (this.reader != null) {
413       return this.reader.isCompactedAway();
414     }
415     return true;
416   }
417 
418   @VisibleForTesting
419   public int getRefCount() {
420     return this.reader.refCount.get();
421   }
422 
423   /**
424    * Return the timestamp at which this bulk load file was generated.
425    */
426   public long getBulkLoadTimestamp() {
427     byte[] bulkLoadTimestamp = metadataMap.get(BULKLOAD_TIME_KEY);
428     return (bulkLoadTimestamp == null) ? 0 : Bytes.toLong(bulkLoadTimestamp);
429   }
430 
431   /**
432    * @return the cached value of HDFS blocks distribution. The cached value is
433    * calculated when store file is opened.
434    */
435   public HDFSBlocksDistribution getHDFSBlockDistribution() {
436     return this.fileInfo.getHDFSBlockDistribution();
437   }
438 
439   /**
440    * Opens reader on this store file.  Called by Constructor.
441    * @return Reader for the store file.
442    * @throws IOException
443    * @see #closeReader(boolean)
444    */
445   private Reader open(boolean canUseDropBehind) throws IOException {
446     if (this.reader != null) {
447       throw new IllegalAccessError("Already open");
448     }
449 
450     // Open the StoreFile.Reader
451     this.reader = fileInfo.open(this.fs, this.cacheConf, canUseDropBehind);
452 
453     // Load up indices and fileinfo. This also loads Bloom filter type.
454     metadataMap = Collections.unmodifiableMap(this.reader.loadFileInfo());
455 
456     // Read in our metadata.
457     byte [] b = metadataMap.get(MAX_SEQ_ID_KEY);
458     if (b != null) {
459       // By convention, if halfhfile, top half has a sequence number > bottom
460       // half. Thats why we add one in below. Its done for case the two halves
461       // are ever merged back together --rare.  Without it, on open of store,
462       // since store files are distinguished by sequence id, the one half would
463       // subsume the other.
464       this.sequenceid = Bytes.toLong(b);
465       if (fileInfo.isTopReference()) {
466         this.sequenceid += 1;
467       }
468     }
469 
470     if (isBulkLoadResult()){
471       // generate the sequenceId from the fileName
472       // fileName is of the form <randomName>_SeqId_<id-when-loaded>_
473       String fileName = this.getPath().getName();
474       // Use lastIndexOf() to get the last, most recent bulk load seqId.
475       int startPos = fileName.lastIndexOf("SeqId_");
476       if (startPos != -1) {
477         this.sequenceid = Long.parseLong(fileName.substring(startPos + 6,
478             fileName.indexOf('_', startPos + 6)));
479         // Handle reference files as done above.
480         if (fileInfo.isTopReference()) {
481           this.sequenceid += 1;
482         }
483       }
484       this.reader.setBulkLoaded(true);
485     }
486     this.reader.setSequenceID(this.sequenceid);
487 
488     b = metadataMap.get(HFileWriterV2.MAX_MEMSTORE_TS_KEY);
489     if (b != null) {
490       this.maxMemstoreTS = Bytes.toLong(b);
491     }
492 
493     b = metadataMap.get(MAJOR_COMPACTION_KEY);
494     if (b != null) {
495       boolean mc = Bytes.toBoolean(b);
496       if (this.majorCompaction == null) {
497         this.majorCompaction = new AtomicBoolean(mc);
498       } else {
499         this.majorCompaction.set(mc);
500       }
501     } else {
502       // Presume it is not major compacted if it doesn't explicity say so
503       // HFileOutputFormat explicitly sets the major compacted key.
504       this.majorCompaction = new AtomicBoolean(false);
505     }
506 
507     b = metadataMap.get(EXCLUDE_FROM_MINOR_COMPACTION_KEY);
508     this.excludeFromMinorCompaction = (b != null && Bytes.toBoolean(b));
509 
510     BloomType hfileBloomType = reader.getBloomFilterType();
511     if (cfBloomType != BloomType.NONE) {
512       reader.loadBloomfilter(BlockType.GENERAL_BLOOM_META);
513       if (hfileBloomType != cfBloomType) {
514         LOG.info("HFile Bloom filter type for "
515             + reader.getHFileReader().getName() + ": " + hfileBloomType
516             + ", but " + cfBloomType + " specified in column family "
517             + "configuration");
518       }
519     } else if (hfileBloomType != BloomType.NONE) {
520       LOG.info("Bloom filter turned off by CF config for "
521           + reader.getHFileReader().getName());
522     }
523 
524     // load delete family bloom filter
525     reader.loadBloomfilter(BlockType.DELETE_FAMILY_BLOOM_META);
526 
527     try {
528       this.reader.timeRange = TimeRangeTracker.getTimeRange(metadataMap.get(TIMERANGE_KEY));
529     } catch (IllegalArgumentException e) {
530       LOG.error("Error reading timestamp range data from meta -- " +
531           "proceeding without", e);
532       this.reader.timeRange = null;
533     }
534 
535     try {
536       byte[] data = metadataMap.get(COMPACTION_EVENT_KEY);
537       this.compactedStoreFiles.addAll(ProtobufUtil.toCompactedStoreFiles(data));
538     } catch (IOException e) {
539       LOG.error("Error reading compacted storefiles from meta data", e);
540     }
541 
542     // initialize so we can reuse them after reader closed.
543     firstKey = reader.getFirstKey();
544     lastKey = reader.getLastKey();
545     comparator = reader.getComparator();
546     return this.reader;
547   }
548 
549   public Reader createReader() throws IOException {
550     return createReader(false);
551   }
552 
553   /**
554    * @return Reader for StoreFile. creates if necessary
555    * @throws IOException
556    */
557   public Reader createReader(boolean canUseDropBehind) throws IOException {
558     if (this.reader == null) {
559       try {
560         this.reader = open(canUseDropBehind);
561       } catch (IOException e) {
562         try {
563           boolean evictOnClose =
564               cacheConf != null? cacheConf.shouldEvictOnClose(): true;
565           this.closeReader(evictOnClose);
566         } catch (IOException ee) {
567         }
568         throw e;
569       }
570 
571     }
572     return this.reader;
573   }
574 
575   /**
576    * @return Current reader.  Must call createReader first else returns null.
577    * @see #createReader()
578    */
579   public Reader getReader() {
580     return this.reader;
581   }
582 
583   /**
584    * @param evictOnClose whether to evict blocks belonging to this file
585    * @throws IOException
586    */
587   public synchronized void closeReader(boolean evictOnClose)
588       throws IOException {
589     if (this.reader != null) {
590       this.reader.close(evictOnClose);
591       this.reader = null;
592     }
593   }
594 
595   /**
596    * Marks the status of the file as compactedAway.
597    */
598   public void markCompactedAway() {
599     if (this.reader != null) {
600       this.reader.markCompactedAway();
601     }
602   }
603 
604   /**
605    * Delete this file
606    * @throws IOException
607    */
608   public void deleteReader() throws IOException {
609     boolean evictOnClose =
610         cacheConf != null? cacheConf.shouldEvictOnClose(): true;
611     closeReader(evictOnClose);
612     this.fs.delete(getPath(), true);
613   }
614 
615   @Override
616   public String toString() {
617     return this.fileInfo.toString();
618   }
619 
620   /**
621    * @return a length description of this StoreFile, suitable for debug output
622    */
623   public String toStringDetailed() {
624     StringBuilder sb = new StringBuilder();
625     sb.append(this.getPath().toString());
626     sb.append(", isReference=").append(isReference());
627     sb.append(", isBulkLoadResult=").append(isBulkLoadResult());
628     if (isBulkLoadResult()) {
629       sb.append(", bulkLoadTS=").append(getBulkLoadTimestamp());
630     } else {
631       sb.append(", seqid=").append(getMaxSequenceId());
632     }
633     sb.append(", majorCompaction=").append(isMajorCompaction());
634 
635     return sb.toString();
636   }
637 
638   @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="ICAST_INTEGER_MULTIPLY_CAST_TO_LONG",
639       justification="Will not overflow")
640   public static class WriterBuilder {
641     private final Configuration conf;
642     private final CacheConfig cacheConf;
643     private final FileSystem fs;
644 
645     private KeyValue.KVComparator comparator = KeyValue.COMPARATOR;
646     private BloomType bloomType = BloomType.NONE;
647     private long maxKeyCount = 0;
648     private Path dir;
649     private Path filePath;
650     private InetSocketAddress[] favoredNodes;
651     private HFileContext fileContext;
652     private TimeRangeTracker trt;
653     private boolean shouldDropCacheBehind;
654     private Collection<StoreFile> compactedFiles = Collections.emptySet();
655 
656     public WriterBuilder(Configuration conf, CacheConfig cacheConf,
657         FileSystem fs) {
658       this.conf = conf;
659       this.cacheConf = cacheConf;
660       this.fs = fs;
661     }
662 
663     /**
664      * @param trt A premade TimeRangeTracker to use rather than build one per append (building one
665      * of these is expensive so good to pass one in if you have one).
666      * @return this (for chained invocation)
667      */
668     public WriterBuilder withTimeRangeTracker(final TimeRangeTracker trt) {
669       Preconditions.checkNotNull(trt);
670       this.trt = trt;
671       return this;
672     }
673 
674     /**
675      * Use either this method or {@link #withFilePath}, but not both.
676      * @param dir Path to column family directory. The directory is created if
677      *          does not exist. The file is given a unique name within this
678      *          directory.
679      * @return this (for chained invocation)
680      */
681     public WriterBuilder withOutputDir(Path dir) {
682       Preconditions.checkNotNull(dir);
683       this.dir = dir;
684       return this;
685     }
686 
687     /**
688      * Use either this method or {@link #withOutputDir}, but not both.
689      * @param filePath the StoreFile path to write
690      * @return this (for chained invocation)
691      */
692     public WriterBuilder withFilePath(Path filePath) {
693       Preconditions.checkNotNull(filePath);
694       this.filePath = filePath;
695       return this;
696     }
697 
698     /**
699      * @param favoredNodes an array of favored nodes or possibly null
700      * @return this (for chained invocation)
701      */
702     public WriterBuilder withFavoredNodes(InetSocketAddress[] favoredNodes) {
703       this.favoredNodes = favoredNodes;
704       return this;
705     }
706 
707     public WriterBuilder withComparator(KeyValue.KVComparator comparator) {
708       Preconditions.checkNotNull(comparator);
709       this.comparator = comparator;
710       return this;
711     }
712 
713     public WriterBuilder withBloomType(BloomType bloomType) {
714       Preconditions.checkNotNull(bloomType);
715       this.bloomType = bloomType;
716       return this;
717     }
718 
719     /**
720      * @param maxKeyCount estimated maximum number of keys we expect to add
721      * @return this (for chained invocation)
722      */
723     public WriterBuilder withMaxKeyCount(long maxKeyCount) {
724       this.maxKeyCount = maxKeyCount;
725       return this;
726     }
727 
728     public WriterBuilder withFileContext(HFileContext fileContext) {
729       this.fileContext = fileContext;
730       return this;
731     }
732 
733     public WriterBuilder withShouldDropCacheBehind(boolean shouldDropCacheBehind) {
734       this.shouldDropCacheBehind = shouldDropCacheBehind;
735       return this;
736     }
737 
738     public WriterBuilder withCompactedFiles(Collection<StoreFile> compactedFiles) {
739       this.compactedFiles = compactedFiles;
740       return this;
741     }
742 
743     /**
744      * Create a store file writer. Client is responsible for closing file when
745      * done. If metadata, add BEFORE closing using
746      * {@link Writer#appendMetadata}.
747      */
748     public Writer build() throws IOException {
749       if ((dir == null ? 0 : 1) + (filePath == null ? 0 : 1) != 1) {
750         throw new IllegalArgumentException("Either specify parent directory " +
751             "or file path");
752       }
753 
754       if (dir == null) {
755         dir = filePath.getParent();
756       }
757 
758       if (!fs.exists(dir)) {
759         fs.mkdirs(dir);
760       }
761 
762       if (filePath == null) {
763         filePath = getUniqueFile(fs, dir);
764         if (!BloomFilterFactory.isGeneralBloomEnabled(conf)) {
765           bloomType = BloomType.NONE;
766         }
767       }
768 
769       if (comparator == null) {
770         comparator = KeyValue.COMPARATOR;
771       }
772       return new Writer(fs, filePath,
773           conf, cacheConf, comparator, bloomType, maxKeyCount, favoredNodes, fileContext,
774           shouldDropCacheBehind, trt, compactedFiles);
775     }
776   }
777 
778   /**
779    * @param fs
780    * @param dir Directory to create file in.
781    * @return random filename inside passed <code>dir</code>
782    */
783   public static Path getUniqueFile(final FileSystem fs, final Path dir)
784       throws IOException {
785     if (!fs.getFileStatus(dir).isDirectory()) {
786       throw new IOException("Expecting " + dir.toString() +
787         " to be a directory");
788     }
789     return new Path(dir, UUID.randomUUID().toString().replaceAll("-", ""));
790   }
791 
792   public Long getMinimumTimestamp() {
793     return getReader().timeRange == null? null: getReader().timeRange.getMin();
794   }
795 
796   public Long getMaximumTimestamp() {
797     return getReader().timeRange == null? null: getReader().timeRange.getMax();
798   }
799 
800 
801   /**
802    * Gets the approximate mid-point of this file that is optimal for use in splitting it.
803    * @param comparator Comparator used to compare KVs.
804    * @return The split point row, or null if splitting is not possible, or reader is null.
805    */
806   @SuppressWarnings("deprecation")
807   byte[] getFileSplitPoint(KVComparator comparator) throws IOException {
808     if (this.reader == null) {
809       LOG.warn("Storefile " + this + " Reader is null; cannot get split point");
810       return null;
811     }
812     // Get first, last, and mid keys.  Midkey is the key that starts block
813     // in middle of hfile.  Has column and timestamp.  Need to return just
814     // the row we want to split on as midkey.
815     byte [] midkey = this.reader.midkey();
816     if (midkey != null) {
817       KeyValue mk = KeyValue.createKeyValueFromKey(midkey, 0, midkey.length);
818       byte [] fk = this.reader.getFirstKey();
819       KeyValue firstKey = KeyValue.createKeyValueFromKey(fk, 0, fk.length);
820       byte [] lk = this.reader.getLastKey();
821       KeyValue lastKey = KeyValue.createKeyValueFromKey(lk, 0, lk.length);
822       // if the midkey is the same as the first or last keys, we cannot (ever) split this region.
823       if (comparator.compareRows(mk, firstKey) == 0 || comparator.compareRows(mk, lastKey) == 0) {
824         if (LOG.isDebugEnabled()) {
825           LOG.debug("cannot split because midkey is the same as first or last row");
826         }
827         return null;
828       }
829       return mk.getRow();
830     }
831     return null;
832   }
833 
834   Set<String> getCompactedStoreFiles() {
835     return Collections.unmodifiableSet(this.compactedStoreFiles);
836   }
837 
838   /**
839    * A StoreFile writer.  Use this to read/write HBase Store Files. It is package
840    * local because it is an implementation detail of the HBase regionserver.
841    */
842   public static class Writer implements Compactor.CellSink {
843     private final BloomFilterWriter generalBloomFilterWriter;
844     private final BloomFilterWriter deleteFamilyBloomFilterWriter;
845     private final BloomType bloomType;
846     private byte[] lastBloomKey;
847     private int lastBloomKeyOffset, lastBloomKeyLen;
848     private KVComparator kvComparator;
849     private Cell lastCell = null;
850     private long earliestPutTs = HConstants.LATEST_TIMESTAMP;
851     private Cell lastDeleteFamilyCell = null;
852     private long deleteFamilyCnt = 0;
853 
854     /**
855      * timeRangeTrackerSet is used to figure if we were passed a filled-out TimeRangeTracker or not.
856      * When flushing a memstore, we set the TimeRangeTracker that it accumulated during updates to
857      * memstore in here into this Writer and use this variable to indicate that we do not need to
858      * recalculate the timeRangeTracker bounds; it was done already as part of add-to-memstore.
859      * A completed TimeRangeTracker is not set in cases of compactions when it is recalculated.
860      */
861     private final boolean timeRangeTrackerSet;
862     final TimeRangeTracker timeRangeTracker;
863 
864     protected HFile.Writer writer;
865     private final Collection<StoreFile> compactedFiles;
866 
867     /**
868      * Creates an HFile.Writer that also write helpful meta data.
869      * @param fs file system to write to
870      * @param path file name to create
871      * @param conf user configuration
872      * @param comparator key comparator
873      * @param bloomType bloom filter setting
874      * @param maxKeys the expected maximum number of keys to be added. Was used
875      *        for Bloom filter size in {@link HFile} format version 1.
876      * @param favoredNodes
877      * @param fileContext - The HFile context
878      * @param shouldDropCacheBehind Drop pages written to page cache after writing the store file.
879      * @throws IOException problem writing to FS
880      */
881     private Writer(FileSystem fs, Path path,
882         final Configuration conf,
883         CacheConfig cacheConf,
884         final KVComparator comparator, BloomType bloomType, long maxKeys,
885         InetSocketAddress[] favoredNodes, HFileContext fileContext, boolean shouldDropCacheBehind)
886             throws IOException {
887       this(fs, path, conf, cacheConf, comparator, bloomType, maxKeys, favoredNodes, fileContext,
888           shouldDropCacheBehind, null, Collections.<StoreFile>emptySet());
889     }
890 
891     /**
892      * Creates an HFile.Writer that also write helpful meta data.
893      * @param fs file system to write to
894      * @param path file name to create
895      * @param conf user configuration
896      * @param comparator key comparator
897      * @param bloomType bloom filter setting
898      * @param maxKeys the expected maximum number of keys to be added. Was used
899      *        for Bloom filter size in {@link HFile} format version 1.
900      * @param favoredNodes
901      * @param fileContext - The HFile context
902      * @param shouldDropCacheBehind Drop pages written to page cache after writing the store file.
903      * @param trt Ready-made timetracker to use.
904      * @param compactedFilesSupplier Compacted files which not archived
905      * @throws IOException problem writing to FS
906      */
907     private Writer(FileSystem fs, Path path,
908         final Configuration conf,
909         CacheConfig cacheConf,
910         final KVComparator comparator, BloomType bloomType, long maxKeys,
911         InetSocketAddress[] favoredNodes, HFileContext fileContext,
912         boolean shouldDropCacheBehind, final TimeRangeTracker trt,
913         Collection<StoreFile> compactedFiles)
914         throws IOException {
915       this.compactedFiles =
916           (compactedFiles == null ? Collections.<StoreFile> emptySet() : compactedFiles);
917       // If passed a TimeRangeTracker, use it. Set timeRangeTrackerSet so we don't destroy it.
918       // TODO: put the state of the TRT on the TRT; i.e. make a read-only version (TimeRange) when
919       // it no longer writable.
920       this.timeRangeTrackerSet = trt != null;
921       this.timeRangeTracker = this.timeRangeTrackerSet? trt: new TimeRangeTracker();
922       writer = HFile.getWriterFactory(conf, cacheConf)
923           .withPath(fs, path)
924           .withComparator(comparator)
925           .withFavoredNodes(favoredNodes)
926           .withFileContext(fileContext)
927           .withShouldDropCacheBehind(shouldDropCacheBehind)
928           .create();
929 
930       this.kvComparator = comparator;
931 
932       generalBloomFilterWriter = BloomFilterFactory.createGeneralBloomAtWrite(
933           conf, cacheConf, bloomType,
934           (int) Math.min(maxKeys, Integer.MAX_VALUE), writer);
935 
936       if (generalBloomFilterWriter != null) {
937         this.bloomType = bloomType;
938         if (LOG.isTraceEnabled()) LOG.trace("Bloom filter type for " + path + ": " +
939           this.bloomType + ", " + generalBloomFilterWriter.getClass().getSimpleName());
940       } else {
941         // Not using Bloom filters.
942         this.bloomType = BloomType.NONE;
943       }
944 
945       // initialize delete family Bloom filter when there is NO RowCol Bloom
946       // filter
947       if (this.bloomType != BloomType.ROWCOL) {
948         this.deleteFamilyBloomFilterWriter = BloomFilterFactory
949             .createDeleteBloomAtWrite(conf, cacheConf,
950                 (int) Math.min(maxKeys, Integer.MAX_VALUE), writer);
951       } else {
952         deleteFamilyBloomFilterWriter = null;
953       }
954       if (deleteFamilyBloomFilterWriter != null) {
955         if (LOG.isTraceEnabled()) LOG.trace("Delete Family Bloom filter type for " + path + ": "
956             + deleteFamilyBloomFilterWriter.getClass().getSimpleName());
957       }
958     }
959 
960     /**
961      * Writes meta data. Call before {@link #close()} since its written as meta data to this file.
962      * @param maxSequenceId Maximum sequence id.
963      * @param majorCompaction True if this file is product of a major compaction
964      * @throws IOException problem writing to FS
965      */
966     public void appendMetadata(final long maxSequenceId, final boolean majorCompaction)
967         throws IOException {
968       appendMetadata(maxSequenceId, majorCompaction, Collections.<StoreFile> emptySet());
969     }
970 
971     /**
972      * Writes meta data. Call before {@link #close()} since its written as meta data to this file.
973      * @param maxSequenceId Maximum sequence id.
974      * @param majorCompaction True if this file is product of a major compaction
975      * @param storeFiles The compacted store files to generate this new file
976      * @throws IOException problem writing to FS
977      */
978     public void appendMetadata(final long maxSequenceId, final boolean majorCompaction,
979         final Collection<StoreFile> storeFiles) throws IOException {
980       writer.appendFileInfo(MAX_SEQ_ID_KEY, Bytes.toBytes(maxSequenceId));
981       writer.appendFileInfo(MAJOR_COMPACTION_KEY, Bytes.toBytes(majorCompaction));
982       writer.appendFileInfo(COMPACTION_EVENT_KEY, toCompactionEventTrackerBytes(storeFiles));
983       appendTrackedTimestampsToMetadata();
984     }
985 
986     /**
987      * Used when write {@link HStoreFile#COMPACTION_EVENT_KEY} to new file's file info. The
988      * compacted store files's name is needed. But if the compacted store file is a result of
989      * compaction, it's compacted files which still not archived is needed, too. And don't need to
990      * add compacted files recursively. If file A, B, C compacted to new file D, and file D
991      * compacted to new file E, will write A, B, C, D to file E's compacted files. So if file E
992      * compacted to new file F, will add E to F's compacted files first, then add E's compacted
993      * files: A, B, C, D to it. And no need to add D's compacted file, as D's compacted files has
994      * been in E's compacted files, too. See HBASE-20724 for more details.
995      * @param storeFiles The compacted store files to generate this new file
996      * @return bytes of CompactionEventTracker
997      */
998     private byte[] toCompactionEventTrackerBytes(Collection<StoreFile> storeFiles) {
999       Set<String> notArchivedCompactedStoreFiles = new HashSet<>();
1000       for (StoreFile sf : this.compactedFiles) {
1001         notArchivedCompactedStoreFiles.add(sf.getPath().getName());
1002       }
1003       Set<String> compactedStoreFiles = new HashSet<>();
1004       for (StoreFile storeFile : storeFiles) {
1005         compactedStoreFiles.add(storeFile.getFileInfo().getPath().getName());
1006         for (String csf : storeFile.getCompactedStoreFiles()) {
1007           if (notArchivedCompactedStoreFiles.contains(csf)) {
1008             compactedStoreFiles.add(csf);
1009           }
1010         }
1011       }
1012       return ProtobufUtil.toCompactionEventTrackerBytes(compactedStoreFiles);
1013     }
1014 
1015     /**
1016      * Add TimestampRange and earliest put timestamp to Metadata
1017      */
1018     public void appendTrackedTimestampsToMetadata() throws IOException {
1019       appendFileInfo(TIMERANGE_KEY,WritableUtils.toByteArray(timeRangeTracker));
1020       appendFileInfo(EARLIEST_PUT_TS, Bytes.toBytes(earliestPutTs));
1021     }
1022 
1023     /**
1024      * Record the earlest Put timestamp.
1025      *
1026      * If the timeRangeTracker is not set,
1027      * update TimeRangeTracker to include the timestamp of this key
1028      * @param cell
1029      */
1030     public void trackTimestamps(final Cell cell) {
1031       if (KeyValue.Type.Put.getCode() == cell.getTypeByte()) {
1032         earliestPutTs = Math.min(earliestPutTs, cell.getTimestamp());
1033       }
1034       if (!timeRangeTrackerSet) {
1035         timeRangeTracker.includeTimestamp(cell);
1036       }
1037     }
1038 
1039     private void appendGeneralBloomfilter(final Cell cell) throws IOException {
1040       if (this.generalBloomFilterWriter != null) {
1041         // only add to the bloom filter on a new, unique key
1042         boolean newKey = true;
1043         if (this.lastCell != null) {
1044           switch(bloomType) {
1045           case ROW:
1046             newKey = ! kvComparator.matchingRows(cell, lastCell);
1047             break;
1048           case ROWCOL:
1049             newKey = ! kvComparator.matchingRowColumn(cell, lastCell);
1050             break;
1051           case NONE:
1052             newKey = false;
1053             break;
1054           default:
1055             throw new IOException("Invalid Bloom filter type: " + bloomType +
1056                 " (ROW or ROWCOL expected)");
1057           }
1058         }
1059         if (newKey) {
1060           /*
1061            * http://2.bp.blogspot.com/_Cib_A77V54U/StZMrzaKufI/AAAAAAAAADo/ZhK7bGoJdMQ/s400/KeyValue.png
1062            * Key = RowLen + Row + FamilyLen + Column [Family + Qualifier] + TimeStamp
1063            *
1064            * 2 Types of Filtering:
1065            *  1. Row = Row
1066            *  2. RowCol = Row + Qualifier
1067            */
1068           byte[] bloomKey;
1069           int bloomKeyOffset, bloomKeyLen;
1070 
1071           switch (bloomType) {
1072           case ROW:
1073             bloomKey = cell.getRowArray();
1074             bloomKeyOffset = cell.getRowOffset();
1075             bloomKeyLen = cell.getRowLength();
1076             break;
1077           case ROWCOL:
1078             // merge(row, qualifier)
1079             // TODO: could save one buffer copy in case of compound Bloom
1080             // filters when this involves creating a KeyValue
1081             bloomKey = generalBloomFilterWriter.createBloomKey(cell.getRowArray(),
1082                 cell.getRowOffset(), cell.getRowLength(), cell.getQualifierArray(),
1083                 cell.getQualifierOffset(), cell.getQualifierLength());
1084             bloomKeyOffset = 0;
1085             bloomKeyLen = bloomKey.length;
1086             break;
1087           default:
1088             throw new IOException("Invalid Bloom filter type: " + bloomType +
1089                 " (ROW or ROWCOL expected)");
1090           }
1091           generalBloomFilterWriter.add(bloomKey, bloomKeyOffset, bloomKeyLen);
1092           if (lastBloomKey != null
1093               && generalBloomFilterWriter.getComparator().compareFlatKey(bloomKey,
1094                   bloomKeyOffset, bloomKeyLen, lastBloomKey,
1095                   lastBloomKeyOffset, lastBloomKeyLen) <= 0) {
1096             throw new IOException("Non-increasing Bloom keys: "
1097                 + Bytes.toStringBinary(bloomKey, bloomKeyOffset, bloomKeyLen)
1098                 + " after "
1099                 + Bytes.toStringBinary(lastBloomKey, lastBloomKeyOffset,
1100                     lastBloomKeyLen));
1101           }
1102           lastBloomKey = bloomKey;
1103           lastBloomKeyOffset = bloomKeyOffset;
1104           lastBloomKeyLen = bloomKeyLen;
1105           this.lastCell = cell;
1106         }
1107       }
1108     }
1109 
1110     private void appendDeleteFamilyBloomFilter(final Cell cell)
1111         throws IOException {
1112       if (!CellUtil.isDeleteFamily(cell) && !CellUtil.isDeleteFamilyVersion(cell)) {
1113         return;
1114       }
1115 
1116       // increase the number of delete family in the store file
1117       deleteFamilyCnt++;
1118       if (null != this.deleteFamilyBloomFilterWriter) {
1119         boolean newKey = true;
1120         if (lastDeleteFamilyCell != null) {
1121           newKey = !kvComparator.matchingRows(cell, lastDeleteFamilyCell);
1122         }
1123         if (newKey) {
1124           this.deleteFamilyBloomFilterWriter.add(cell.getRowArray(),
1125               cell.getRowOffset(), cell.getRowLength());
1126           this.lastDeleteFamilyCell = cell;
1127         }
1128       }
1129     }
1130 
1131     public void append(final Cell cell) throws IOException {
1132       appendGeneralBloomfilter(cell);
1133       appendDeleteFamilyBloomFilter(cell);
1134       writer.append(cell);
1135       trackTimestamps(cell);
1136     }
1137 
1138     public Path getPath() {
1139       return this.writer.getPath();
1140     }
1141 
1142     boolean hasGeneralBloom() {
1143       return this.generalBloomFilterWriter != null;
1144     }
1145 
1146     /**
1147      * For unit testing only.
1148      *
1149      * @return the Bloom filter used by this writer.
1150      */
1151     BloomFilterWriter getGeneralBloomWriter() {
1152       return generalBloomFilterWriter;
1153     }
1154 
1155     private boolean closeBloomFilter(BloomFilterWriter bfw) throws IOException {
1156       boolean haveBloom = (bfw != null && bfw.getKeyCount() > 0);
1157       if (haveBloom) {
1158         bfw.compactBloom();
1159       }
1160       return haveBloom;
1161     }
1162 
1163     private boolean closeGeneralBloomFilter() throws IOException {
1164       boolean hasGeneralBloom = closeBloomFilter(generalBloomFilterWriter);
1165 
1166       // add the general Bloom filter writer and append file info
1167       if (hasGeneralBloom) {
1168         writer.addGeneralBloomFilter(generalBloomFilterWriter);
1169         writer.appendFileInfo(BLOOM_FILTER_TYPE_KEY,
1170             Bytes.toBytes(bloomType.toString()));
1171         if (lastBloomKey != null) {
1172           writer.appendFileInfo(LAST_BLOOM_KEY, Arrays.copyOfRange(
1173               lastBloomKey, lastBloomKeyOffset, lastBloomKeyOffset
1174                   + lastBloomKeyLen));
1175         }
1176       }
1177       return hasGeneralBloom;
1178     }
1179 
1180     private boolean closeDeleteFamilyBloomFilter() throws IOException {
1181       boolean hasDeleteFamilyBloom = closeBloomFilter(deleteFamilyBloomFilterWriter);
1182 
1183       // add the delete family Bloom filter writer
1184       if (hasDeleteFamilyBloom) {
1185         writer.addDeleteFamilyBloomFilter(deleteFamilyBloomFilterWriter);
1186       }
1187 
1188       // append file info about the number of delete family kvs
1189       // even if there is no delete family Bloom.
1190       writer.appendFileInfo(DELETE_FAMILY_COUNT,
1191           Bytes.toBytes(this.deleteFamilyCnt));
1192 
1193       return hasDeleteFamilyBloom;
1194     }
1195 
1196     public void close() throws IOException {
1197       boolean hasGeneralBloom = this.closeGeneralBloomFilter();
1198       boolean hasDeleteFamilyBloom = this.closeDeleteFamilyBloomFilter();
1199 
1200       writer.close();
1201 
1202       // Log final Bloom filter statistics. This needs to be done after close()
1203       // because compound Bloom filters might be finalized as part of closing.
1204       if (StoreFile.LOG.isTraceEnabled()) {
1205         StoreFile.LOG.trace((hasGeneralBloom ? "" : "NO ") + "General Bloom and " +
1206           (hasDeleteFamilyBloom ? "" : "NO ") + "DeleteFamily" + " was added to HFile " +
1207           getPath());
1208       }
1209 
1210     }
1211 
1212     public void appendFileInfo(byte[] key, byte[] value) throws IOException {
1213       writer.appendFileInfo(key, value);
1214     }
1215 
1216     /** For use in testing, e.g. {@link org.apache.hadoop.hbase.regionserver.CreateRandomStoreFile}
1217      */
1218     HFile.Writer getHFileWriter() {
1219       return writer;
1220     }
1221   }
1222 
1223   /**
1224    * Reader for a StoreFile.
1225    */
1226   public static class Reader {
1227     private static final Log LOG = LogFactory.getLog(Reader.class.getName());
1228 
1229     protected BloomFilter generalBloomFilter = null;
1230     protected BloomFilter deleteFamilyBloomFilter = null;
1231     protected BloomType bloomFilterType;
1232     private final HFile.Reader reader;
1233     protected TimeRange timeRange;
1234     protected long sequenceID = -1;
1235     private byte[] lastBloomKey;
1236     private long deleteFamilyCnt = -1;
1237     private boolean bulkLoadResult = false;
1238     // Counter that is incremented every time a scanner is created on the
1239     // store file. It is decremented when the scan on the store file is
1240     // done.
1241     private AtomicInteger refCount = new AtomicInteger(0);
1242     // Indicates if the file got compacted
1243     private volatile boolean compactedAway = false;
1244 
1245     public Reader(FileSystem fs, Path path, CacheConfig cacheConf, Configuration conf)
1246         throws IOException {
1247       reader = HFile.createReader(fs, path, cacheConf, conf);
1248       bloomFilterType = BloomType.NONE;
1249     }
1250 
1251     void markCompactedAway() {
1252       this.compactedAway = true;
1253     }
1254 
1255     public Reader(FileSystem fs, Path path, FSDataInputStreamWrapper in, long size,
1256         CacheConfig cacheConf, Configuration conf) throws IOException {
1257       reader = HFile.createReader(fs, path, in, size, cacheConf, conf);
1258       bloomFilterType = BloomType.NONE;
1259     }
1260 
1261     public void setReplicaStoreFile(boolean isPrimaryReplicaStoreFile) {
1262       reader.setPrimaryReplicaReader(isPrimaryReplicaStoreFile);
1263     }
1264     public boolean isPrimaryReplicaReader() {
1265       return reader.isPrimaryReplicaReader();
1266     }
1267 
1268     /**
1269      * ONLY USE DEFAULT CONSTRUCTOR FOR UNIT TESTS
1270      */
1271     Reader() {
1272       this.reader = null;
1273     }
1274 
1275     public KVComparator getComparator() {
1276       return reader.getComparator();
1277     }
1278 
1279     /**
1280      * Get a scanner to scan over this StoreFile. Do not use
1281      * this overload if using this scanner for compactions.
1282      *
1283      * @param cacheBlocks should this scanner cache blocks?
1284      * @param pread use pread (for highly concurrent small readers)
1285      * @return a scanner
1286      */
1287     public StoreFileScanner getStoreFileScanner(boolean cacheBlocks,
1288                                                boolean pread) {
1289       return getStoreFileScanner(cacheBlocks, pread, false,
1290         // 0 is passed as readpoint because this method is only used by test
1291         // where StoreFile is directly operated upon
1292         0);
1293     }
1294 
1295     /**
1296      * Get a scanner to scan over this StoreFile.
1297      *
1298      * @param cacheBlocks should this scanner cache blocks?
1299      * @param pread use pread (for highly concurrent small readers)
1300      * @param isCompaction is scanner being used for compaction?
1301      * @return a scanner
1302      */
1303     public StoreFileScanner getStoreFileScanner(boolean cacheBlocks, boolean pread,
1304         boolean isCompaction, long readPt) {
1305       return new StoreFileScanner(this, getScanner(cacheBlocks, pread, isCompaction),
1306         !isCompaction, reader.hasMVCCInfo(), readPt);
1307     }
1308 
1309     /**
1310      * Return the ref count associated with the reader whenever a scanner associated with the
1311      * reader is opened.
1312      */
1313     int getRefCount() {
1314       return refCount.get();
1315     }
1316 
1317     /**
1318      * Increment the ref count associated with the reader when ever a scanner associated with the
1319      * reader is opened
1320      */
1321     void incrementRefCount() {
1322       refCount.incrementAndGet();
1323     }
1324 
1325     /**
1326      * Decrement the ref count associated with the reader when ever a scanner associated
1327      * with the reader is closed
1328      */
1329     void decrementRefCount() {
1330       refCount.decrementAndGet();
1331     }
1332 
1333     /**
1334      * @return true if the file is still used in reads
1335      */
1336     public boolean isReferencedInReads() {
1337       return refCount.get() != 0;
1338     }
1339 
1340     /**
1341      * @return true if the file is compacted
1342      */
1343     public boolean isCompactedAway() {
1344       return this.compactedAway;
1345     }
1346 
1347     /**
1348      * @deprecated Do not write further code which depends on this call. Instead
1349      * use getStoreFileScanner() which uses the StoreFileScanner class/interface
1350      * which is the preferred way to scan a store with higher level concepts.
1351      *
1352      * @param cacheBlocks should we cache the blocks?
1353      * @param pread use pread (for concurrent small readers)
1354      * @return the underlying HFileScanner
1355      */
1356     @Deprecated
1357     public HFileScanner getScanner(boolean cacheBlocks, boolean pread) {
1358       return getScanner(cacheBlocks, pread, false);
1359     }
1360 
1361     /**
1362      * @deprecated Do not write further code which depends on this call. Instead
1363      * use getStoreFileScanner() which uses the StoreFileScanner class/interface
1364      * which is the preferred way to scan a store with higher level concepts.
1365      *
1366      * @param cacheBlocks
1367      *          should we cache the blocks?
1368      * @param pread
1369      *          use pread (for concurrent small readers)
1370      * @param isCompaction
1371      *          is scanner being used for compaction?
1372      * @return the underlying HFileScanner
1373      */
1374     @Deprecated
1375     public HFileScanner getScanner(boolean cacheBlocks, boolean pread,
1376         boolean isCompaction) {
1377       return reader.getScanner(cacheBlocks, pread, isCompaction);
1378     }
1379 
1380     public void close(boolean evictOnClose) throws IOException {
1381       reader.close(evictOnClose);
1382     }
1383 
1384     /**
1385      * Check if this storeFile may contain keys within the TimeRange that
1386      * have not expired (i.e. not older than oldestUnexpiredTS).
1387      * @param timeRange the timeRange to restrict
1388      * @param oldestUnexpiredTS the oldest timestamp that is not expired, as
1389      *          determined by the column family's TTL
1390      * @return false if queried keys definitely don't exist in this StoreFile
1391      */
1392     boolean passesTimerangeFilter(TimeRange tr, long oldestUnexpiredTS) {
1393       return this.timeRange == null? true:
1394         this.timeRange.includesTimeRange(tr) && this.timeRange.getMax() >= oldestUnexpiredTS;
1395     }
1396 
1397     /**
1398      * Checks whether the given scan passes the Bloom filter (if present). Only
1399      * checks Bloom filters for single-row or single-row-column scans. Bloom
1400      * filter checking for multi-gets is implemented as part of the store
1401      * scanner system (see {@link StoreFileScanner#seekExactly}) and uses
1402      * the lower-level API {@link #passesGeneralBloomFilter(byte[], int, int, byte[],
1403      * int, int)}.
1404      *
1405      * @param scan the scan specification. Used to determine the row, and to
1406      *          check whether this is a single-row ("get") scan.
1407      * @param columns the set of columns. Only used for row-column Bloom
1408      *          filters.
1409      * @return true if the scan with the given column set passes the Bloom
1410      *         filter, or if the Bloom filter is not applicable for the scan.
1411      *         False if the Bloom filter is applicable and the scan fails it.
1412      */
1413      boolean passesBloomFilter(Scan scan,
1414         final SortedSet<byte[]> columns) {
1415       // Multi-column non-get scans will use Bloom filters through the
1416       // lower-level API function that this function calls.
1417       if (!scan.isGetScan()) {
1418         return true;
1419       }
1420 
1421       byte[] row = scan.getStartRow();
1422       switch (this.bloomFilterType) {
1423         case ROW:
1424           return passesGeneralBloomFilter(row, 0, row.length, null, 0, 0);
1425 
1426         case ROWCOL:
1427           if (columns != null && columns.size() == 1) {
1428             byte[] column = columns.first();
1429             return passesGeneralBloomFilter(row, 0, row.length, column, 0,
1430                 column.length);
1431           }
1432 
1433           // For multi-column queries the Bloom filter is checked from the
1434           // seekExact operation.
1435           return true;
1436 
1437         default:
1438           return true;
1439       }
1440     }
1441 
1442     public boolean passesDeleteFamilyBloomFilter(byte[] row, int rowOffset,
1443         int rowLen) {
1444       // Cache Bloom filter as a local variable in case it is set to null by
1445       // another thread on an IO error.
1446       BloomFilter bloomFilter = this.deleteFamilyBloomFilter;
1447 
1448       // Empty file or there is no delete family at all
1449       if (reader.getTrailer().getEntryCount() == 0 || deleteFamilyCnt == 0) {
1450         return false;
1451       }
1452 
1453       if (bloomFilter == null) {
1454         return true;
1455       }
1456 
1457       try {
1458         if (!bloomFilter.supportsAutoLoading()) {
1459           return true;
1460         }
1461         return bloomFilter.contains(row, rowOffset, rowLen, null);
1462       } catch (IllegalArgumentException e) {
1463         LOG.error("Bad Delete Family bloom filter data -- proceeding without",
1464             e);
1465         setDeleteFamilyBloomFilterFaulty();
1466       }
1467 
1468       return true;
1469     }
1470 
1471     /**
1472      * A method for checking Bloom filters. Called directly from
1473      * StoreFileScanner in case of a multi-column query.
1474      *
1475      * @param row
1476      * @param rowOffset
1477      * @param rowLen
1478      * @param col
1479      * @param colOffset
1480      * @param colLen
1481      * @return True if passes
1482      */
1483     public boolean passesGeneralBloomFilter(byte[] row, int rowOffset,
1484         int rowLen, byte[] col, int colOffset, int colLen) {
1485       // Cache Bloom filter as a local variable in case it is set to null by
1486       // another thread on an IO error.
1487       BloomFilter bloomFilter = this.generalBloomFilter;
1488       if (bloomFilter == null) {
1489         return true;
1490       }
1491 
1492       byte[] key;
1493       switch (bloomFilterType) {
1494         case ROW:
1495           if (col != null) {
1496             throw new RuntimeException("Row-only Bloom filter called with " +
1497                 "column specified");
1498           }
1499           if (rowOffset != 0 || rowLen != row.length) {
1500               throw new AssertionError("For row-only Bloom filters the row "
1501                   + "must occupy the whole array");
1502           }
1503           key = row;
1504           break;
1505 
1506         case ROWCOL:
1507           key = bloomFilter.createBloomKey(row, rowOffset, rowLen, col,
1508               colOffset, colLen);
1509 
1510           break;
1511 
1512         default:
1513           return true;
1514       }
1515 
1516       // Empty file
1517       if (reader.getTrailer().getEntryCount() == 0)
1518         return false;
1519 
1520       try {
1521         boolean shouldCheckBloom;
1522         ByteBuffer bloom;
1523         if (bloomFilter.supportsAutoLoading()) {
1524           bloom = null;
1525           shouldCheckBloom = true;
1526         } else {
1527           bloom = reader.getMetaBlock(HFile.BLOOM_FILTER_DATA_KEY,
1528               true);
1529           shouldCheckBloom = bloom != null;
1530         }
1531 
1532         if (shouldCheckBloom) {
1533           boolean exists;
1534 
1535           // Whether the primary Bloom key is greater than the last Bloom key
1536           // from the file info. For row-column Bloom filters this is not yet
1537           // a sufficient condition to return false.
1538           boolean keyIsAfterLast = lastBloomKey != null
1539               && bloomFilter.getComparator().compareFlatKey(key, lastBloomKey) > 0;
1540 
1541           if (bloomFilterType == BloomType.ROWCOL) {
1542             // Since a Row Delete is essentially a DeleteFamily applied to all
1543             // columns, a file might be skipped if using row+col Bloom filter.
1544             // In order to ensure this file is included an additional check is
1545             // required looking only for a row bloom.
1546             byte[] rowBloomKey = bloomFilter.createBloomKey(row, rowOffset, rowLen,
1547                 null, 0, 0);
1548 
1549             if (keyIsAfterLast
1550                 && bloomFilter.getComparator().compareFlatKey(rowBloomKey,
1551                     lastBloomKey) > 0) {
1552               exists = false;
1553             } else {
1554               exists =
1555                   bloomFilter.contains(key, 0, key.length, bloom) ||
1556                   bloomFilter.contains(rowBloomKey, 0, rowBloomKey.length,
1557                       bloom);
1558             }
1559           } else {
1560             exists = !keyIsAfterLast
1561                 && bloomFilter.contains(key, 0, key.length, bloom);
1562           }
1563 
1564           return exists;
1565         }
1566       } catch (IOException e) {
1567         LOG.error("Error reading bloom filter data -- proceeding without",
1568             e);
1569         setGeneralBloomFilterFaulty();
1570       } catch (IllegalArgumentException e) {
1571         LOG.error("Bad bloom filter data -- proceeding without", e);
1572         setGeneralBloomFilterFaulty();
1573       }
1574 
1575       return true;
1576     }
1577 
1578     /**
1579      * Checks whether the given scan rowkey range overlaps with the current storefile's
1580      * @param scan the scan specification. Used to determine the rowkey range.
1581      * @return true if there is overlap, false otherwise
1582      */
1583     public boolean passesKeyRangeFilter(Scan scan) {
1584       if (this.getFirstKey() == null || this.getLastKey() == null) {
1585         // the file is empty
1586         return false;
1587       }
1588       if (Bytes.equals(scan.getStartRow(), HConstants.EMPTY_START_ROW)
1589           && Bytes.equals(scan.getStopRow(), HConstants.EMPTY_END_ROW)) {
1590         return true;
1591       }
1592       KeyValue smallestScanKeyValue = scan.isReversed() ? KeyValueUtil
1593           .createFirstOnRow(scan.getStopRow()) : KeyValueUtil.createFirstOnRow(scan
1594           .getStartRow());
1595       KeyValue largestScanKeyValue = scan.isReversed() ? KeyValueUtil
1596           .createLastOnRow(scan.getStartRow()) : KeyValueUtil.createLastOnRow(scan
1597           .getStopRow());
1598       boolean nonOverLapping = (getComparator().compareFlatKey(
1599           this.getFirstKey(), largestScanKeyValue.getKey()) > 0 && !Bytes
1600           .equals(scan.isReversed() ? scan.getStartRow() : scan.getStopRow(),
1601               HConstants.EMPTY_END_ROW))
1602           || getComparator().compareFlatKey(this.getLastKey(),
1603               smallestScanKeyValue.getKey()) < 0;
1604       return !nonOverLapping;
1605     }
1606 
1607     public Map<byte[], byte[]> loadFileInfo() throws IOException {
1608       Map<byte [], byte []> fi = reader.loadFileInfo();
1609 
1610       byte[] b = fi.get(BLOOM_FILTER_TYPE_KEY);
1611       if (b != null) {
1612         bloomFilterType = BloomType.valueOf(Bytes.toString(b));
1613       }
1614 
1615       lastBloomKey = fi.get(LAST_BLOOM_KEY);
1616       byte[] cnt = fi.get(DELETE_FAMILY_COUNT);
1617       if (cnt != null) {
1618         deleteFamilyCnt = Bytes.toLong(cnt);
1619       }
1620 
1621       return fi;
1622     }
1623 
1624     public void loadBloomfilter() {
1625       this.loadBloomfilter(BlockType.GENERAL_BLOOM_META);
1626       this.loadBloomfilter(BlockType.DELETE_FAMILY_BLOOM_META);
1627     }
1628 
1629     private void loadBloomfilter(BlockType blockType) {
1630       try {
1631         if (blockType == BlockType.GENERAL_BLOOM_META) {
1632           if (this.generalBloomFilter != null)
1633             return; // Bloom has been loaded
1634 
1635           DataInput bloomMeta = reader.getGeneralBloomFilterMetadata();
1636           if (bloomMeta != null) {
1637             // sanity check for NONE Bloom filter
1638             if (bloomFilterType == BloomType.NONE) {
1639               throw new IOException(
1640                   "valid bloom filter type not found in FileInfo");
1641             } else {
1642               generalBloomFilter = BloomFilterFactory.createFromMeta(bloomMeta,
1643                   reader);
1644               if (LOG.isTraceEnabled()) {
1645                 LOG.trace("Loaded " + bloomFilterType.toString() + " "
1646                   + generalBloomFilter.getClass().getSimpleName()
1647                   + " metadata for " + reader.getName());
1648               }
1649             }
1650           }
1651         } else if (blockType == BlockType.DELETE_FAMILY_BLOOM_META) {
1652           if (this.deleteFamilyBloomFilter != null)
1653             return; // Bloom has been loaded
1654 
1655           DataInput bloomMeta = reader.getDeleteBloomFilterMetadata();
1656           if (bloomMeta != null) {
1657             deleteFamilyBloomFilter = BloomFilterFactory.createFromMeta(
1658                 bloomMeta, reader);
1659             LOG.info("Loaded Delete Family Bloom ("
1660                 + deleteFamilyBloomFilter.getClass().getSimpleName()
1661                 + ") metadata for " + reader.getName());
1662           }
1663         } else {
1664           throw new RuntimeException("Block Type: " + blockType.toString()
1665               + "is not supported for Bloom filter");
1666         }
1667       } catch (IOException e) {
1668         LOG.error("Error reading bloom filter meta for " + blockType
1669             + " -- proceeding without", e);
1670         setBloomFilterFaulty(blockType);
1671       } catch (IllegalArgumentException e) {
1672         LOG.error("Bad bloom filter meta " + blockType
1673             + " -- proceeding without", e);
1674         setBloomFilterFaulty(blockType);
1675       }
1676     }
1677 
1678     private void setBloomFilterFaulty(BlockType blockType) {
1679       if (blockType == BlockType.GENERAL_BLOOM_META) {
1680         setGeneralBloomFilterFaulty();
1681       } else if (blockType == BlockType.DELETE_FAMILY_BLOOM_META) {
1682         setDeleteFamilyBloomFilterFaulty();
1683       }
1684     }
1685 
1686     /**
1687      * The number of Bloom filter entries in this store file, or an estimate
1688      * thereof, if the Bloom filter is not loaded. This always returns an upper
1689      * bound of the number of Bloom filter entries.
1690      *
1691      * @return an estimate of the number of Bloom filter entries in this file
1692      */
1693     public long getFilterEntries() {
1694       return generalBloomFilter != null ? generalBloomFilter.getKeyCount()
1695           : reader.getEntries();
1696     }
1697 
1698     public void setGeneralBloomFilterFaulty() {
1699       generalBloomFilter = null;
1700     }
1701 
1702     public void setDeleteFamilyBloomFilterFaulty() {
1703       this.deleteFamilyBloomFilter = null;
1704     }
1705 
1706     public byte[] getLastKey() {
1707       return reader.getLastKey();
1708     }
1709 
1710     public byte[] getLastRowKey() {
1711       return reader.getLastRowKey();
1712     }
1713 
1714     public byte[] midkey() throws IOException {
1715       return reader.midkey();
1716     }
1717 
1718     public long length() {
1719       return reader.length();
1720     }
1721 
1722     public long getTotalUncompressedBytes() {
1723       return reader.getTrailer().getTotalUncompressedBytes();
1724     }
1725 
1726     public long getEntries() {
1727       return reader.getEntries();
1728     }
1729 
1730     public long getDeleteFamilyCnt() {
1731       return deleteFamilyCnt;
1732     }
1733 
1734     public byte[] getFirstKey() {
1735       return reader.getFirstKey();
1736     }
1737 
1738     public long indexSize() {
1739       return reader.indexSize();
1740     }
1741 
1742     public BloomType getBloomFilterType() {
1743       return this.bloomFilterType;
1744     }
1745 
1746     public long getSequenceID() {
1747       return sequenceID;
1748     }
1749 
1750     public void setSequenceID(long sequenceID) {
1751       this.sequenceID = sequenceID;
1752     }
1753 
1754     public void setBulkLoaded(boolean bulkLoadResult) {
1755       this.bulkLoadResult = bulkLoadResult;
1756     }
1757 
1758     public boolean isBulkLoaded() {
1759       return this.bulkLoadResult;
1760     }
1761 
1762     BloomFilter getGeneralBloomFilter() {
1763       return generalBloomFilter;
1764     }
1765 
1766     long getUncompressedDataIndexSize() {
1767       return reader.getTrailer().getUncompressedDataIndexSize();
1768     }
1769 
1770     public long getTotalBloomSize() {
1771       if (generalBloomFilter == null)
1772         return 0;
1773       return generalBloomFilter.getByteSize();
1774     }
1775 
1776     public int getHFileVersion() {
1777       return reader.getTrailer().getMajorVersion();
1778     }
1779 
1780     public int getHFileMinorVersion() {
1781       return reader.getTrailer().getMinorVersion();
1782     }
1783 
1784     public HFile.Reader getHFileReader() {
1785       return reader;
1786     }
1787 
1788     void disableBloomFilterForTesting() {
1789       generalBloomFilter = null;
1790       this.deleteFamilyBloomFilter = null;
1791     }
1792 
1793     public long getMaxTimestamp() {
1794       return timeRange == null ? TimeRange.INITIAL_MAX_TIMESTAMP: timeRange.getMax();
1795     }
1796   }
1797 
1798   /**
1799    * Useful comparators for comparing StoreFiles.
1800    */
1801   public abstract static class Comparators {
1802     /**
1803      * Comparator that compares based on the Sequence Ids of the
1804      * the StoreFiles. Bulk loads that did not request a seq ID
1805      * are given a seq id of -1; thus, they are placed before all non-
1806      * bulk loads, and bulk loads with sequence Id. Among these files,
1807      * the size is used to determine the ordering, then bulkLoadTime.
1808      * If there are ties, the path name is used as a tie-breaker.
1809      */
1810     public static final Comparator<StoreFile> SEQ_ID =
1811       Ordering.compound(ImmutableList.of(
1812           Ordering.natural().onResultOf(new GetSeqId()),
1813           Ordering.natural().onResultOf(new GetFileSize()).reverse(),
1814           Ordering.natural().onResultOf(new GetBulkTime()),
1815           Ordering.natural().onResultOf(new GetPathName())
1816       ));
1817 
1818     /**
1819      * Comparator for time-aware compaction. SeqId is still the first
1820      *   ordering criterion to maintain MVCC.
1821      */
1822     public static final Comparator<StoreFile> SEQ_ID_MAX_TIMESTAMP =
1823       Ordering.compound(ImmutableList.of(
1824         Ordering.natural().onResultOf(new GetSeqId()),
1825         Ordering.natural().onResultOf(new GetMaxTimestamp()),
1826         Ordering.natural().onResultOf(new GetFileSize()).reverse(),
1827         Ordering.natural().onResultOf(new GetBulkTime()),
1828         Ordering.natural().onResultOf(new GetPathName())
1829       ));
1830 
1831     private static class GetSeqId implements Function<StoreFile, Long> {
1832       @Override
1833       public Long apply(StoreFile sf) {
1834         return sf.getMaxSequenceId();
1835       }
1836     }
1837 
1838     private static class GetFileSize implements Function<StoreFile, Long> {
1839       @Override
1840       public Long apply(StoreFile sf) {
1841         if (sf.getReader() != null) {
1842           return sf.getReader().length();
1843         } else {
1844           // the reader may be null for the compacted files and if the archiving
1845           // had failed.
1846           return -1L;
1847         }
1848       }
1849     }
1850 
1851     private static class GetBulkTime implements Function<StoreFile, Long> {
1852       @Override
1853       public Long apply(StoreFile sf) {
1854         if (!sf.isBulkLoadResult()) return Long.MAX_VALUE;
1855         return sf.getBulkLoadTimestamp();
1856       }
1857     }
1858 
1859     private static class GetPathName implements Function<StoreFile, String> {
1860       @Override
1861       public String apply(StoreFile sf) {
1862         return sf.getPath().getName();
1863       }
1864     }
1865 
1866     private static class GetMaxTimestamp implements Function<StoreFile, Long> {
1867       @Override
1868       public Long apply(StoreFile sf) {
1869         return sf.getMaximumTimestamp() == null? (Long)Long.MAX_VALUE : sf.getMaximumTimestamp();
1870       }
1871     }
1872   }
1873 }