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