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.hbase.classification.InterfaceAudience;
29  import org.apache.hadoop.conf.Configuration;
30  import org.apache.hadoop.hbase.Cell;
31  import org.apache.hadoop.hbase.CellUtil;
32  import org.apache.hadoop.hbase.HConstants;
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    /** specify how many days to keep MVCC values during major compaction **/ 
63    protected int keepSeqIdPeriod;
64  
65    //TODO: depending on Store is not good but, realistically, all compactors currently do.
66    Compactor(final Configuration conf, final Store store) {
67      this.conf = conf;
68      this.store = store;
69      this.compactionKVMax =
70        this.conf.getInt(HConstants.COMPACTION_KV_MAX, HConstants.COMPACTION_KV_MAX_DEFAULT);
71      this.compactionCompression = (this.store.getFamily() == null) ?
72          Compression.Algorithm.NONE : this.store.getFamily().getCompactionCompression();
73      this.keepSeqIdPeriod = Math.max(this.conf.getInt(HConstants.KEEP_SEQID_PERIOD, 
74        HConstants.MIN_KEEP_SEQID_PERIOD), HConstants.MIN_KEEP_SEQID_PERIOD);
75    }
76  
77    public interface CellSink {
78      void append(Cell cell) throws IOException;
79    }
80  
81    public CompactionProgress getProgress() {
82      return this.progress;
83    }
84  
85    /** The sole reason this class exists is that java has no ref/out/pointer parameters. */
86    protected static class FileDetails {
87      /** Maximum key count after compaction (for blooms) */
88      public long maxKeyCount = 0;
89      /** Earliest put timestamp if major compaction */
90      public long earliestPutTs = HConstants.LATEST_TIMESTAMP;
91      /** The last key in the files we're compacting. */
92      public long maxSeqId = 0;
93      /** Latest memstore read point found in any of the involved files */
94      public long maxMVCCReadpoint = 0;
95      /** Max tags length**/
96      public int maxTagsLength = 0;
97      /** Min SeqId to keep during a major compaction **/
98      public long minSeqIdToKeep = 0;
99    }
100 
101   /**
102    * Extracts some details about the files to compact that are commonly needed by compactors.
103    * @param filesToCompact Files.
104    * @param allFiles Whether all files are included for compaction
105    * @return The result.
106    */
107   protected FileDetails getFileDetails(
108       Collection<StoreFile> filesToCompact, boolean allFiles) throws IOException {
109     FileDetails fd = new FileDetails();
110     long oldestHFileTimeStampToKeepMVCC = System.currentTimeMillis() - 
111       (1000L * 60 * 60 * 24 * this.keepSeqIdPeriod);  
112 
113     for (StoreFile file : filesToCompact) {
114       if(allFiles && (file.getModificationTimeStamp() < oldestHFileTimeStampToKeepMVCC)) {
115         // when isAllFiles is true, all files are compacted so we can calculate the smallest 
116         // MVCC value to keep
117         if(fd.minSeqIdToKeep < file.getMaxMemstoreTS()) {
118           fd.minSeqIdToKeep = file.getMaxMemstoreTS();
119         }
120       }
121       long seqNum = file.getMaxSequenceId();
122       fd.maxSeqId = Math.max(fd.maxSeqId, seqNum);
123       StoreFile.Reader r = file.getReader();
124       if (r == null) {
125         LOG.warn("Null reader for " + file.getPath());
126         continue;
127       }
128       // NOTE: getFilterEntries could cause under-sized blooms if the user
129       // switches bloom type (e.g. from ROW to ROWCOL)
130       long keyCount = (r.getBloomFilterType() == store.getFamily().getBloomFilterType())
131           ? r.getFilterEntries() : r.getEntries();
132       fd.maxKeyCount += keyCount;
133       // calculate the latest MVCC readpoint in any of the involved store files
134       Map<byte[], byte[]> fileInfo = r.loadFileInfo();
135       byte tmp[] = null;
136       // Get and set the real MVCCReadpoint for bulk loaded files, which is the
137       // SeqId number.
138       if (r.isBulkLoaded()) {
139         fd.maxMVCCReadpoint = Math.max(fd.maxMVCCReadpoint, r.getSequenceID());
140       }
141       else {
142         tmp = fileInfo.get(HFileWriterV2.MAX_MEMSTORE_TS_KEY);
143         if (tmp != null) {
144           fd.maxMVCCReadpoint = Math.max(fd.maxMVCCReadpoint, Bytes.toLong(tmp));
145         }
146       }
147       tmp = fileInfo.get(FileInfo.MAX_TAGS_LEN);
148       if (tmp != null) {
149         fd.maxTagsLength = Math.max(fd.maxTagsLength, Bytes.toInt(tmp));
150       }
151       // If required, calculate the earliest put timestamp of all involved storefiles.
152       // This is used to remove family delete marker during compaction.
153       long earliestPutTs = 0;
154       if (allFiles) {
155         tmp = fileInfo.get(StoreFile.EARLIEST_PUT_TS);
156         if (tmp == null) {
157           // There's a file with no information, must be an old one
158           // assume we have very old puts
159           fd.earliestPutTs = earliestPutTs = HConstants.OLDEST_TIMESTAMP;
160         } else {
161           earliestPutTs = Bytes.toLong(tmp);
162           fd.earliestPutTs = Math.min(fd.earliestPutTs, earliestPutTs);
163         }
164       }
165       if (LOG.isDebugEnabled()) {
166         LOG.debug("Compacting " + file +
167           ", keycount=" + keyCount +
168           ", bloomtype=" + r.getBloomFilterType().toString() +
169           ", size=" + StringUtils.humanReadableInt(r.length()) +
170           ", encoding=" + r.getHFileReader().getDataBlockEncoding() +
171           ", seqNum=" + seqNum +
172           (allFiles ? ", earliestPutTs=" + earliestPutTs: ""));
173       }
174     }
175     return fd;
176   }
177 
178   /**
179    * Creates file scanners for compaction.
180    * @param filesToCompact Files.
181    * @return Scanners.
182    */
183   protected List<StoreFileScanner> createFileScanners(
184       final Collection<StoreFile> filesToCompact, long smallestReadPoint) throws IOException {
185     return StoreFileScanner.getScannersForStoreFiles(filesToCompact, false, false, true,
186       smallestReadPoint);
187   }
188 
189   protected long getSmallestReadPoint() {
190     return store.getSmallestReadPoint();
191   }
192 
193   /**
194    * Calls coprocessor, if any, to create compaction scanner - before normal scanner creation.
195    * @param request Compaction request.
196    * @param scanType Scan type.
197    * @param earliestPutTs Earliest put ts.
198    * @param scanners File scanners for compaction files.
199    * @return Scanner override by coprocessor; null if not overriding.
200    */
201   protected InternalScanner preCreateCoprocScanner(final CompactionRequest request,
202       ScanType scanType, long earliestPutTs,  List<StoreFileScanner> scanners) throws IOException {
203     if (store.getCoprocessorHost() == null) return null;
204     return store.getCoprocessorHost()
205         .preCompactScannerOpen(store, scanners, scanType, earliestPutTs, request);
206   }
207 
208   /**
209    * Calls coprocessor, if any, to create scanners - after normal scanner creation.
210    * @param request Compaction request.
211    * @param scanType Scan type.
212    * @param scanner The default scanner created for compaction.
213    * @return Scanner scanner to use (usually the default); null if compaction should not proceed.
214    */
215    protected InternalScanner postCreateCoprocScanner(final CompactionRequest request,
216       ScanType scanType, InternalScanner scanner) throws IOException {
217     if (store.getCoprocessorHost() == null) return scanner;
218     return store.getCoprocessorHost().preCompact(store, scanner, scanType, request);
219   }
220 
221   /**
222    * Performs the compaction.
223    * @param scanner Where to read from.
224    * @param writer Where to write to.
225    * @param smallestReadPoint Smallest read point.
226    * @param cleanSeqId When true, remove seqId(used to be mvcc) value which is <= smallestReadPoint
227    * @return Whether compaction ended; false if it was interrupted for some reason.
228    */
229   protected boolean performCompaction(InternalScanner scanner,
230       CellSink writer, long smallestReadPoint, boolean cleanSeqId) throws IOException {
231     int bytesWritten = 0;
232     // Since scanner.next() can return 'false' but still be delivering data,
233     // we have to use a do/while loop.
234     List<Cell> cells = new ArrayList<Cell>();
235     int closeCheckInterval = HStore.getCloseCheckInterval();
236     long lastMillis;
237     if (LOG.isDebugEnabled()) {
238       lastMillis = System.currentTimeMillis();
239     } else {
240       lastMillis = 0;
241     }
242     boolean hasMore;
243     do {
244       hasMore = scanner.next(cells, compactionKVMax);
245       // output to writer:
246       for (Cell c : cells) {
247         if (cleanSeqId && c.getSequenceId() <= smallestReadPoint) {
248           CellUtil.setSequenceId(c, 0);
249         }
250         writer.append(c);
251         ++progress.currentCompactedKVs;
252         progress.totalCompactedSize += KeyValueUtil.length(c);
253 
254         // check periodically to see if a system stop is requested
255         if (closeCheckInterval > 0) {
256           bytesWritten += KeyValueUtil.length(c);
257           if (bytesWritten > closeCheckInterval) {
258             // Log the progress of long running compactions every minute if
259             // logging at DEBUG level
260             if (LOG.isDebugEnabled()) {
261               long now = System.currentTimeMillis();
262               if ((now - lastMillis) >= 60 * 1000) {
263                 LOG.debug("Compaction progress: " + progress + String.format(", rate=%.2f kB/sec",
264                   (bytesWritten / 1024.0) / ((now - lastMillis) / 1000.0)));
265                 lastMillis = now;
266               }
267             }
268             bytesWritten = 0;
269             if (!store.areWritesEnabled()) {
270               progress.cancel();
271               return false;
272             }
273           }
274         }
275       }
276       cells.clear();
277     } while (hasMore);
278     progress.complete();
279     return true;
280   }
281 
282   /**
283    * @param store store
284    * @param scanners Store file scanners.
285    * @param scanType Scan type.
286    * @param smallestReadPoint Smallest MVCC read point.
287    * @param earliestPutTs Earliest put across all files.
288    * @return A compaction scanner.
289    */
290   protected InternalScanner createScanner(Store store, List<StoreFileScanner> scanners,
291       ScanType scanType, long smallestReadPoint, long earliestPutTs) throws IOException {
292     Scan scan = new Scan();
293     scan.setMaxVersions(store.getFamily().getMaxVersions());
294     return new StoreScanner(store, store.getScanInfo(), scan, scanners,
295         scanType, smallestReadPoint, earliestPutTs);
296   }
297 
298   /**
299    * @param store The store.
300    * @param scanners Store file scanners.
301    * @param smallestReadPoint Smallest MVCC read point.
302    * @param earliestPutTs Earliest put across all files.
303    * @param dropDeletesFromRow Drop deletes starting with this row, inclusive. Can be null.
304    * @param dropDeletesToRow Drop deletes ending with this row, exclusive. Can be null.
305    * @return A compaction scanner.
306    */
307   protected InternalScanner createScanner(Store store, List<StoreFileScanner> scanners,
308      long smallestReadPoint, long earliestPutTs, byte[] dropDeletesFromRow,
309      byte[] dropDeletesToRow) throws IOException {
310     Scan scan = new Scan();
311     scan.setMaxVersions(store.getFamily().getMaxVersions());
312     return new StoreScanner(store, store.getScanInfo(), scan, scanners, smallestReadPoint,
313         earliestPutTs, dropDeletesFromRow, dropDeletesToRow);
314   }
315 }