View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.regionserver.compactions;
19  
20  import java.io.IOException;
21  import java.util.ArrayList;
22  import java.util.Collection;
23  import java.util.List;
24  import java.util.Map;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.apache.hadoop.classification.InterfaceAudience;
29  import org.apache.hadoop.conf.Configuration;
30  import org.apache.hadoop.hbase.Cell;
31  import org.apache.hadoop.hbase.HConstants;
32  import org.apache.hadoop.hbase.KeyValue;
33  import org.apache.hadoop.hbase.KeyValueUtil;
34  import org.apache.hadoop.hbase.client.Scan;
35  import org.apache.hadoop.hbase.io.compress.Compression;
36  import org.apache.hadoop.hbase.io.hfile.HFile.FileInfo;
37  import org.apache.hadoop.hbase.io.hfile.HFileWriterV2;
38  import org.apache.hadoop.hbase.regionserver.HStore;
39  import org.apache.hadoop.hbase.regionserver.InternalScanner;
40  import org.apache.hadoop.hbase.regionserver.ScanType;
41  import org.apache.hadoop.hbase.regionserver.Store;
42  import org.apache.hadoop.hbase.regionserver.StoreFile;
43  import org.apache.hadoop.hbase.regionserver.StoreFileScanner;
44  import org.apache.hadoop.hbase.regionserver.StoreScanner;
45  import org.apache.hadoop.hbase.util.Bytes;
46  import org.apache.hadoop.util.StringUtils;
47  
48  /**
49   * A compactor is a compaction algorithm associated a given policy. Base class also contains
50   * reusable parts for implementing compactors (what is common and what isn't is evolving).
51   */
52  @InterfaceAudience.Private
53  public abstract class Compactor {
54    private static final Log LOG = LogFactory.getLog(Compactor.class);
55    protected CompactionProgress progress;
56    protected Configuration conf;
57    protected Store store;
58  
59    private int compactionKVMax;
60    protected Compression.Algorithm compactionCompression;
61  
62    //TODO: depending on Store is not good but, realistically, all compactors currently do.
63    Compactor(final Configuration conf, final Store store) {
64      this.conf = conf;
65      this.store = store;
66      this.compactionKVMax =
67        this.conf.getInt(HConstants.COMPACTION_KV_MAX, HConstants.COMPACTION_KV_MAX_DEFAULT);
68      this.compactionCompression = (this.store.getFamily() == null) ?
69          Compression.Algorithm.NONE : this.store.getFamily().getCompactionCompression();
70    }
71  
72    /**
73     * TODO: Replace this with CellOutputStream when StoreFile.Writer uses cells.
74     */
75    public interface CellSink {
76      void append(KeyValue kv) throws IOException;
77    }
78  
79    public CompactionProgress getProgress() {
80      return this.progress;
81    }
82  
83    /** The sole reason this class exists is that java has no ref/out/pointer parameters. */
84    protected static class FileDetails {
85      /** Maximum key count after compaction (for blooms) */
86      public long maxKeyCount = 0;
87      /** Earliest put timestamp if major compaction */
88      public long earliestPutTs = HConstants.LATEST_TIMESTAMP;
89      /** The last key in the files we're compacting. */
90      public long maxSeqId = 0;
91      /** Latest memstore read point found in any of the involved files */
92      public long maxMVCCReadpoint = 0;
93      /** Max tags length**/
94      public int maxTagsLength = 0;
95    }
96  
97    /**
98     * Extracts some details about the files to compact that are commonly needed by compactors.
99     * @param filesToCompact Files.
100    * @param calculatePutTs Whether earliest put TS is needed.
101    * @return The result.
102    */
103   protected FileDetails getFileDetails(
104       Collection<StoreFile> filesToCompact, boolean calculatePutTs) throws IOException {
105     FileDetails fd = new FileDetails();
106 
107     for (StoreFile file : filesToCompact) {
108       long seqNum = file.getMaxSequenceId();
109       fd.maxSeqId = Math.max(fd.maxSeqId, seqNum);
110       StoreFile.Reader r = file.getReader();
111       if (r == null) {
112         LOG.warn("Null reader for " + file.getPath());
113         continue;
114       }
115       // NOTE: getFilterEntries could cause under-sized blooms if the user
116       // switches bloom type (e.g. from ROW to ROWCOL)
117       long keyCount = (r.getBloomFilterType() == store.getFamily().getBloomFilterType())
118           ? r.getFilterEntries() : r.getEntries();
119       fd.maxKeyCount += keyCount;
120       // calculate the latest MVCC readpoint in any of the involved store files
121       Map<byte[], byte[]> fileInfo = r.loadFileInfo();
122       byte tmp[] = fileInfo.get(HFileWriterV2.MAX_MEMSTORE_TS_KEY);
123       if (tmp != null) {
124         fd.maxMVCCReadpoint = Math.max(fd.maxMVCCReadpoint, Bytes.toLong(tmp));
125       }
126       tmp = fileInfo.get(FileInfo.MAX_TAGS_LEN);
127       if (tmp != null) {
128         fd.maxTagsLength = Math.max(fd.maxTagsLength, Bytes.toInt(tmp));
129       }
130       // If required, calculate the earliest put timestamp of all involved storefiles.
131       // This is used to remove family delete marker during compaction.
132       long earliestPutTs = 0;
133       if (calculatePutTs) {
134         tmp = fileInfo.get(StoreFile.EARLIEST_PUT_TS);
135         if (tmp == null) {
136           // There's a file with no information, must be an old one
137           // assume we have very old puts
138           fd.earliestPutTs = earliestPutTs = HConstants.OLDEST_TIMESTAMP;
139         } else {
140           earliestPutTs = Bytes.toLong(tmp);
141           fd.earliestPutTs = Math.min(fd.earliestPutTs, earliestPutTs);
142         }
143       }
144       if (LOG.isDebugEnabled()) {
145         LOG.debug("Compacting " + file +
146           ", keycount=" + keyCount +
147           ", bloomtype=" + r.getBloomFilterType().toString() +
148           ", size=" + StringUtils.humanReadableInt(r.length()) +
149           ", encoding=" + r.getHFileReader().getDataBlockEncoding() +
150           ", seqNum=" + seqNum +
151           (calculatePutTs ? ", earliestPutTs=" + earliestPutTs: ""));
152       }
153     }
154     return fd;
155   }
156 
157   /**
158    * Creates file scanners for compaction.
159    * @param filesToCompact Files.
160    * @return Scanners.
161    */
162   protected List<StoreFileScanner> createFileScanners(
163       final Collection<StoreFile> filesToCompact, long smallestReadPoint) throws IOException {
164     return StoreFileScanner.getScannersForStoreFiles(filesToCompact, false, false, true,
165       smallestReadPoint);
166   }
167 
168   protected long getSmallestReadPoint() {
169     return store.getSmallestReadPoint();
170   }
171 
172   /**
173    * Calls coprocessor, if any, to create compaction scanner - before normal scanner creation.
174    * @param request Compaction request.
175    * @param scanType Scan type.
176    * @param earliestPutTs Earliest put ts.
177    * @param scanners File scanners for compaction files.
178    * @return Scanner override by coprocessor; null if not overriding.
179    */
180   protected InternalScanner preCreateCoprocScanner(final CompactionRequest request,
181       ScanType scanType, long earliestPutTs,  List<StoreFileScanner> scanners) throws IOException {
182     if (store.getCoprocessorHost() == null) return null;
183     return store.getCoprocessorHost()
184         .preCompactScannerOpen(store, scanners, scanType, earliestPutTs, request);
185   }
186 
187   /**
188    * Calls coprocessor, if any, to create scanners - after normal scanner creation.
189    * @param request Compaction request.
190    * @param scanType Scan type.
191    * @param scanner The default scanner created for compaction.
192    * @return Scanner scanner to use (usually the default); null if compaction should not proceed.
193    */
194    protected InternalScanner postCreateCoprocScanner(final CompactionRequest request,
195       ScanType scanType, InternalScanner scanner) throws IOException {
196     if (store.getCoprocessorHost() == null) return scanner;
197     return store.getCoprocessorHost().preCompact(store, scanner, scanType, request);
198   }
199 
200   /**
201    * Performs the compaction.
202    * @param scanner Where to read from.
203    * @param writer Where to write to.
204    * @param smallestReadPoint Smallest read point.
205    * @return Whether compaction ended; false if it was interrupted for some reason.
206    */
207   protected boolean performCompaction(InternalScanner scanner,
208       CellSink writer, long smallestReadPoint) throws IOException {
209     int bytesWritten = 0;
210     // Since scanner.next() can return 'false' but still be delivering data,
211     // we have to use a do/while loop.
212     List<Cell> kvs = new ArrayList<Cell>();
213     // Limit to "hbase.hstore.compaction.kv.max" (default 10) to avoid OOME
214     int closeCheckInterval = HStore.getCloseCheckInterval();
215     boolean hasMore;
216     do {
217       hasMore = scanner.next(kvs, compactionKVMax);
218       // output to writer:
219       for (Cell c : kvs) {
220         KeyValue kv = KeyValueUtil.ensureKeyValue(c);
221         if (kv.getMvccVersion() <= smallestReadPoint) {
222           kv.setMvccVersion(0);
223         }
224         writer.append(kv);
225         ++progress.currentCompactedKVs;
226 
227         // check periodically to see if a system stop is requested
228         if (closeCheckInterval > 0) {
229           bytesWritten += kv.getLength();
230           if (bytesWritten > closeCheckInterval) {
231             bytesWritten = 0;
232             if (!store.areWritesEnabled()) {
233               progress.cancel();
234               return false;
235             }
236           }
237         }
238       }
239       kvs.clear();
240     } while (hasMore);
241     progress.complete();
242     return true;
243   }
244 
245   /**
246    * @param store store
247    * @param scanners Store file scanners.
248    * @param scanType Scan type.
249    * @param smallestReadPoint Smallest MVCC read point.
250    * @param earliestPutTs Earliest put across all files.
251    * @return A compaction scanner.
252    */
253   protected InternalScanner createScanner(Store store, List<StoreFileScanner> scanners,
254       ScanType scanType, long smallestReadPoint, long earliestPutTs) throws IOException {
255     Scan scan = new Scan();
256     scan.setMaxVersions(store.getFamily().getMaxVersions());
257     return new StoreScanner(store, store.getScanInfo(), scan, scanners,
258         scanType, smallestReadPoint, earliestPutTs);
259   }
260 
261   /**
262    * @param store The store.
263    * @param scanners Store file scanners.
264    * @param smallestReadPoint Smallest MVCC read point.
265    * @param earliestPutTs Earliest put across all files.
266    * @param dropDeletesFromRow Drop deletes starting with this row, inclusive. Can be null.
267    * @param dropDeletesToRow Drop deletes ending with this row, exclusive. Can be null.
268    * @return A compaction scanner.
269    */
270   protected InternalScanner createScanner(Store store, List<StoreFileScanner> scanners,
271      long smallestReadPoint, long earliestPutTs, byte[] dropDeletesFromRow,
272      byte[] dropDeletesToRow) throws IOException {
273     Scan scan = new Scan();
274     scan.setMaxVersions(store.getFamily().getMaxVersions());
275     return new StoreScanner(store, store.getScanInfo(), scan, scanners, smallestReadPoint,
276         earliestPutTs, dropDeletesFromRow, dropDeletesToRow);
277   }
278 }