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.io.InterruptedIOException;
22  import java.security.PrivilegedExceptionAction;
23  import java.util.ArrayList;
24  import java.util.Collection;
25  import java.util.Collections;
26  import java.util.List;
27  import java.util.Map;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.fs.Path;
33  import org.apache.hadoop.hbase.Cell;
34  import org.apache.hadoop.hbase.CellUtil;
35  import org.apache.hadoop.hbase.HConstants;
36  import org.apache.hadoop.hbase.KeyValueUtil;
37  import org.apache.hadoop.hbase.classification.InterfaceAudience;
38  import org.apache.hadoop.hbase.client.Scan;
39  import org.apache.hadoop.hbase.io.compress.Compression;
40  import org.apache.hadoop.hbase.io.hfile.HFile.FileInfo;
41  import org.apache.hadoop.hbase.io.hfile.HFileWriterV2;
42  import org.apache.hadoop.hbase.regionserver.HStore;
43  import org.apache.hadoop.hbase.regionserver.InternalScanner;
44  import org.apache.hadoop.hbase.regionserver.ScanType;
45  import org.apache.hadoop.hbase.regionserver.ScannerContext;
46  import org.apache.hadoop.hbase.regionserver.Store;
47  import org.apache.hadoop.hbase.regionserver.StoreFile;
48  import org.apache.hadoop.hbase.regionserver.StoreFile.Writer;
49  import org.apache.hadoop.hbase.regionserver.StoreFileScanner;
50  import org.apache.hadoop.hbase.regionserver.StoreScanner;
51  import org.apache.hadoop.hbase.regionserver.compactions.Compactor.CellSink;
52  import org.apache.hadoop.hbase.regionserver.throttle.ThroughputControlUtil;
53  import org.apache.hadoop.hbase.regionserver.throttle.ThroughputController;
54  import org.apache.hadoop.hbase.security.User;
55  import org.apache.hadoop.hbase.util.Bytes;
56  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
57  import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix;
58  
59  import com.google.common.io.Closeables;
60  
61  /**
62   * A compactor is a compaction algorithm associated a given policy. Base class also contains
63   * reusable parts for implementing compactors (what is common and what isn't is evolving).
64   */
65  @InterfaceAudience.Private
66  public abstract class Compactor<T extends CellSink> {
67    private static final Log LOG = LogFactory.getLog(Compactor.class);
68  
69    protected volatile CompactionProgress progress;
70  
71    protected final Configuration conf;
72    protected final Store store;
73  
74    protected final int compactionKVMax;
75    protected final Compression.Algorithm compactionCompression;
76  
77    /** specify how many days to keep MVCC values during major compaction **/ 
78    protected int keepSeqIdPeriod;
79  
80    // Configs that drive whether we drop page cache behind compactions
81    protected static final String  MAJOR_COMPACTION_DROP_CACHE =
82        "hbase.regionserver.majorcompaction.pagecache.drop";
83    protected static final String MINOR_COMPACTION_DROP_CACHE =
84        "hbase.regionserver.minorcompaction.pagecache.drop";
85  
86    private boolean dropCacheMajor;
87    private boolean dropCacheMinor;
88  
89    //TODO: depending on Store is not good but, realistically, all compactors currently do.
90    Compactor(final Configuration conf, final Store store) {
91      this.conf = conf;
92      this.store = store;
93      this.compactionKVMax =
94        this.conf.getInt(HConstants.COMPACTION_KV_MAX, HConstants.COMPACTION_KV_MAX_DEFAULT);
95      this.compactionCompression = (this.store.getFamily() == null) ?
96          Compression.Algorithm.NONE : this.store.getFamily().getCompactionCompression();
97      this.keepSeqIdPeriod = Math.max(this.conf.getInt(HConstants.KEEP_SEQID_PERIOD, 
98        HConstants.MIN_KEEP_SEQID_PERIOD), HConstants.MIN_KEEP_SEQID_PERIOD);
99      this.dropCacheMajor = conf.getBoolean(MAJOR_COMPACTION_DROP_CACHE, true);
100     this.dropCacheMinor = conf.getBoolean(MINOR_COMPACTION_DROP_CACHE, true);
101   }
102 
103   public interface CellSink {
104     void append(Cell cell) throws IOException;
105   }
106 
107   protected interface CellSinkFactory<S> {
108     S createWriter(InternalScanner scanner, FileDetails fd, boolean shouldDropBehind)
109         throws IOException;
110   }
111 
112   public CompactionProgress getProgress() {
113     return this.progress;
114   }
115 
116   /** The sole reason this class exists is that java has no ref/out/pointer parameters. */
117   protected static class FileDetails {
118     /** Maximum key count after compaction (for blooms) */
119     public long maxKeyCount = 0;
120     /** Earliest put timestamp if major compaction */
121     public long earliestPutTs = HConstants.LATEST_TIMESTAMP;
122     /** The last key in the files we're compacting. */
123     public long maxSeqId = 0;
124     /** Latest memstore read point found in any of the involved files */
125     public long maxMVCCReadpoint = 0;
126     /** Max tags length**/
127     public int maxTagsLength = 0;
128     /** Min SeqId to keep during a major compaction **/
129     public long minSeqIdToKeep = 0;
130   }
131 
132   /**
133    * Extracts some details about the files to compact that are commonly needed by compactors.
134    * @param filesToCompact Files.
135    * @param allFiles Whether all files are included for compaction
136    * @return The result.
137    */
138   protected FileDetails getFileDetails(
139       Collection<StoreFile> filesToCompact, boolean allFiles) throws IOException {
140     FileDetails fd = new FileDetails();
141     long oldestHFileTimeStampToKeepMVCC = System.currentTimeMillis() - 
142       (1000L * 60 * 60 * 24 * this.keepSeqIdPeriod);  
143 
144     for (StoreFile file : filesToCompact) {
145       if(allFiles && (file.getModificationTimeStamp() < oldestHFileTimeStampToKeepMVCC)) {
146         // when isAllFiles is true, all files are compacted so we can calculate the smallest 
147         // MVCC value to keep
148         if(fd.minSeqIdToKeep < file.getMaxMemstoreTS()) {
149           fd.minSeqIdToKeep = file.getMaxMemstoreTS();
150         }
151       }
152       long seqNum = file.getMaxSequenceId();
153       fd.maxSeqId = Math.max(fd.maxSeqId, seqNum);
154       StoreFile.Reader r = file.getReader();
155       if (r == null) {
156         LOG.warn("Null reader for " + file.getPath());
157         continue;
158       }
159       // NOTE: use getEntries when compacting instead of getFilterEntries, otherwise under-sized
160       // blooms can cause progress to be miscalculated or if the user switches bloom
161       // type (e.g. from ROW to ROWCOL)
162       long keyCount = r.getEntries();
163       fd.maxKeyCount += keyCount;
164       // calculate the latest MVCC readpoint in any of the involved store files
165       Map<byte[], byte[]> fileInfo = r.loadFileInfo();
166       byte[] tmp = null;
167       // Get and set the real MVCCReadpoint for bulk loaded files, which is the
168       // SeqId number.
169       if (r.isBulkLoaded()) {
170         fd.maxMVCCReadpoint = Math.max(fd.maxMVCCReadpoint, r.getSequenceID());
171       }
172       else {
173         tmp = fileInfo.get(HFileWriterV2.MAX_MEMSTORE_TS_KEY);
174         if (tmp != null) {
175           fd.maxMVCCReadpoint = Math.max(fd.maxMVCCReadpoint, Bytes.toLong(tmp));
176         }
177       }
178       tmp = fileInfo.get(FileInfo.MAX_TAGS_LEN);
179       if (tmp != null) {
180         fd.maxTagsLength = Math.max(fd.maxTagsLength, Bytes.toInt(tmp));
181       }
182       // If required, calculate the earliest put timestamp of all involved storefiles.
183       // This is used to remove family delete marker during compaction.
184       long earliestPutTs = 0;
185       if (allFiles) {
186         tmp = fileInfo.get(StoreFile.EARLIEST_PUT_TS);
187         if (tmp == null) {
188           // There's a file with no information, must be an old one
189           // assume we have very old puts
190           fd.earliestPutTs = earliestPutTs = HConstants.OLDEST_TIMESTAMP;
191         } else {
192           earliestPutTs = Bytes.toLong(tmp);
193           fd.earliestPutTs = Math.min(fd.earliestPutTs, earliestPutTs);
194         }
195       }
196       if (LOG.isDebugEnabled()) {
197         LOG.debug("Compacting " + file +
198           ", keycount=" + keyCount +
199           ", bloomtype=" + r.getBloomFilterType().toString() +
200           ", size=" + TraditionalBinaryPrefix.long2String(r.length(), "", 1) +
201           ", encoding=" + r.getHFileReader().getDataBlockEncoding() +
202           ", seqNum=" + seqNum +
203           (allFiles ? ", earliestPutTs=" + earliestPutTs: ""));
204       }
205     }
206     return fd;
207   }
208 
209   /**
210    * Creates file scanners for compaction.
211    * @param filesToCompact Files.
212    * @return Scanners.
213    */
214   protected List<StoreFileScanner> createFileScanners(
215       final Collection<StoreFile> filesToCompact,
216       long smallestReadPoint,
217       boolean useDropBehind) throws IOException {
218     return StoreFileScanner.getScannersForStoreFiles(filesToCompact,
219         /* cache blocks = */ false,
220         /* use pread = */ false,
221         /* is compaction */ true,
222         /* use Drop Behind */ useDropBehind,
223       smallestReadPoint);
224   }
225 
226   protected long getSmallestReadPoint() {
227     return store.getSmallestReadPoint();
228   }
229 
230   protected interface InternalScannerFactory {
231 
232     ScanType getScanType(CompactionRequest request);
233 
234     InternalScanner createScanner(List<StoreFileScanner> scanners, ScanType scanType,
235         FileDetails fd, long smallestReadPoint) throws IOException;
236   }
237 
238   protected final InternalScannerFactory defaultScannerFactory = new InternalScannerFactory() {
239 
240     @Override
241     public ScanType getScanType(CompactionRequest request) {
242       return request.isAllFiles() ? ScanType.COMPACT_DROP_DELETES
243           : ScanType.COMPACT_RETAIN_DELETES;
244     }
245 
246     @Override
247     public InternalScanner createScanner(List<StoreFileScanner> scanners, ScanType scanType,
248         FileDetails fd, long smallestReadPoint) throws IOException {
249       return Compactor.this.createScanner(store, scanners, scanType, smallestReadPoint,
250         fd.earliestPutTs);
251     }
252   };
253 
254   /**
255    * Creates a writer for a new file in a temporary directory.
256    * @param fd The file details.
257    * @return Writer for a new StoreFile in the tmp dir.
258    * @throws IOException if creation failed
259    */
260   protected Writer createTmpWriter(FileDetails fd, boolean shouldDropBehind) throws IOException {
261     // When all MVCC readpoints are 0, don't write them.
262     // See HBASE-8166, HBASE-12600, and HBASE-13389.
263     return store.createWriterInTmp(fd.maxKeyCount, this.compactionCompression,
264     /* isCompaction = */true,
265     /* includeMVCCReadpoint = */fd.maxMVCCReadpoint > 0,
266     /* includesTags = */fd.maxTagsLength > 0, shouldDropBehind);
267   }
268 
269   protected List<Path> compact(final CompactionRequest request,
270       InternalScannerFactory scannerFactory, CellSinkFactory<T> sinkFactory,
271       ThroughputController throughputController, User user) throws IOException {
272     FileDetails fd = getFileDetails(request.getFiles(), request.isAllFiles());
273     this.progress = new CompactionProgress(fd.maxKeyCount);
274 
275     // Find the smallest read point across all the Scanners.
276     long smallestReadPoint = getSmallestReadPoint();
277 
278     List<StoreFileScanner> scanners;
279     Collection<StoreFile> readersToClose;
280     T writer = null;
281     boolean dropCache;
282     if (request.isMajor() || request.isAllFiles()) {
283       dropCache = this.dropCacheMajor;
284     } else {
285       dropCache = this.dropCacheMinor;
286     }
287 
288     if (this.conf.getBoolean("hbase.regionserver.compaction.private.readers", true)) {
289       // clone all StoreFiles, so we'll do the compaction on a independent copy of StoreFiles,
290       // HFiles, and their readers
291       readersToClose = new ArrayList<StoreFile>(request.getFiles().size());
292       for (StoreFile f : request.getFiles()) {
293         readersToClose.add(f.cloneForReader());
294       }
295       scanners = createFileScanners(readersToClose, smallestReadPoint, dropCache);
296     } else {
297       readersToClose = Collections.emptyList();
298       scanners = createFileScanners(request.getFiles(), smallestReadPoint, dropCache);
299     }
300     InternalScanner scanner = null;
301     boolean finished = false;
302     try {
303       /* Include deletes, unless we are doing a major compaction */
304       ScanType scanType = scannerFactory.getScanType(request);
305       scanner = preCreateCoprocScanner(request, scanType, fd.earliestPutTs, scanners);
306       if (scanner == null) {
307         scanner = scannerFactory.createScanner(scanners, scanType, fd, smallestReadPoint);
308       }
309       scanner = postCreateCoprocScanner(request, scanType, scanner, user);
310       if (scanner == null) {
311         // NULL scanner returned from coprocessor hooks means skip normal processing.
312         return new ArrayList<Path>();
313       }
314       boolean cleanSeqId = false;
315       if (fd.minSeqIdToKeep > 0) {
316         smallestReadPoint = Math.min(fd.minSeqIdToKeep, smallestReadPoint);
317         cleanSeqId = true;
318       }
319       writer = sinkFactory.createWriter(scanner, fd, dropCache);
320       finished =
321           performCompaction(scanner, writer, smallestReadPoint, cleanSeqId, throughputController);
322       if (!finished) {
323         throw new InterruptedIOException("Aborting compaction of store " + store + " in region "
324             + store.getRegionInfo().getRegionNameAsString() + " because it was interrupted.");
325       }
326     } finally {
327       Closeables.close(scanner, true);
328       for (StoreFile f : readersToClose) {
329         try {
330           f.closeReader(true);
331         } catch (IOException e) {
332           LOG.warn("Exception closing " + f, e);
333         }
334       }
335       if (!finished && writer != null) {
336         abortWriter(writer);
337       }
338     }
339     assert finished : "We should have exited the method on all error paths";
340     assert writer != null : "Writer should be non-null if no error";
341     return commitWriter(writer, fd, request);
342   }
343 
344   protected abstract List<Path> commitWriter(T writer, FileDetails fd, CompactionRequest request)
345       throws IOException;
346 
347   protected abstract void abortWriter(T writer) throws IOException;
348 
349   /**
350    * Calls coprocessor, if any, to create compaction scanner - before normal scanner creation.
351    * @param request Compaction request.
352    * @param scanType Scan type.
353    * @param earliestPutTs Earliest put ts.
354    * @param scanners File scanners for compaction files.
355    * @return Scanner override by coprocessor; null if not overriding.
356    */
357   protected InternalScanner preCreateCoprocScanner(final CompactionRequest request,
358       ScanType scanType, long earliestPutTs,  List<StoreFileScanner> scanners) throws IOException {
359     return preCreateCoprocScanner(request, scanType, earliestPutTs, scanners, null);
360   }
361 
362   protected InternalScanner preCreateCoprocScanner(final CompactionRequest request,
363       final ScanType scanType, final long earliestPutTs, final List<StoreFileScanner> scanners,
364       User user) throws IOException {
365     if (store.getCoprocessorHost() == null) {
366       return null;
367     }
368     if (user == null) {
369       return store.getCoprocessorHost().preCompactScannerOpen(store, scanners, scanType,
370         earliestPutTs, request);
371     } else {
372       try {
373         return user.getUGI().doAs(new PrivilegedExceptionAction<InternalScanner>() {
374           @Override
375           public InternalScanner run() throws Exception {
376             return store.getCoprocessorHost().preCompactScannerOpen(store, scanners,
377               scanType, earliestPutTs, request);
378           }
379         });
380       } catch (InterruptedException ie) {
381         InterruptedIOException iioe = new InterruptedIOException();
382         iioe.initCause(ie);
383         throw iioe;
384       }
385     }
386   }
387 
388   /**
389    * Calls coprocessor, if any, to create scanners - after normal scanner creation.
390    * @param request Compaction request.
391    * @param scanType Scan type.
392    * @param scanner The default scanner created for compaction.
393    * @return Scanner scanner to use (usually the default); null if compaction should not proceed.
394    */
395   protected InternalScanner postCreateCoprocScanner(final CompactionRequest request,
396       final ScanType scanType, final InternalScanner scanner, User user) throws IOException {
397     if (store.getCoprocessorHost() == null) {
398       return scanner;
399     }
400     if (user == null) {
401       return store.getCoprocessorHost().preCompact(store, scanner, scanType, request);
402     } else {
403       try {
404         return user.getUGI().doAs(new PrivilegedExceptionAction<InternalScanner>() {
405           @Override
406           public InternalScanner run() throws Exception {
407             return store.getCoprocessorHost().preCompact(store, scanner, scanType, request);
408           }
409         });
410       } catch (InterruptedException ie) {
411         InterruptedIOException iioe = new InterruptedIOException();
412         iioe.initCause(ie);
413         throw iioe;
414       }
415     }
416   }
417 
418   /**
419    * Performs the compaction.
420    * @param scanner Where to read from.
421    * @param writer Where to write to.
422    * @param smallestReadPoint Smallest read point.
423    * @param cleanSeqId When true, remove seqId(used to be mvcc) value which is &lt;=
424    *          smallestReadPoint
425    * @return Whether compaction ended; false if it was interrupted for some reason.
426    */
427   protected boolean performCompaction(InternalScanner scanner, CellSink writer,
428       long smallestReadPoint, boolean cleanSeqId,
429       ThroughputController throughputController) throws IOException {
430     long bytesWritten = 0;
431     long bytesWrittenProgress = 0;
432     // Since scanner.next() can return 'false' but still be delivering data,
433     // we have to use a do/while loop.
434     List<Cell> cells = new ArrayList<Cell>();
435     long closeCheckInterval = HStore.getCloseCheckInterval();
436     long lastMillis = 0;
437     if (LOG.isDebugEnabled()) {
438       lastMillis = EnvironmentEdgeManager.currentTime();
439     }
440     String compactionName = ThroughputControlUtil.getNameForThrottling(store, "compaction");
441     long now = 0;
442     boolean hasMore;
443     ScannerContext scannerContext =
444         ScannerContext.newBuilder().setBatchLimit(compactionKVMax).build();
445 
446     throughputController.start(compactionName);
447     try {
448       do {
449         hasMore = scanner.next(cells, scannerContext);
450         if (LOG.isDebugEnabled()) {
451           now = EnvironmentEdgeManager.currentTime();
452         }
453         // output to writer:
454         Cell lastCleanCell = null;
455         long lastCleanCellSeqId = 0;
456         for (Cell c : cells) {
457           if (cleanSeqId && c.getSequenceId() <= smallestReadPoint) {
458             lastCleanCell = c;
459             lastCleanCellSeqId = c.getSequenceId();
460             CellUtil.setSequenceId(c, 0);
461           } else {
462             lastCleanCell = null;
463             lastCleanCellSeqId = 0;
464           }
465           writer.append(c);
466           int len = KeyValueUtil.length(c);
467           ++progress.currentCompactedKVs;
468           progress.totalCompactedSize += len;
469           if (LOG.isDebugEnabled()) {
470             bytesWrittenProgress += len;
471           }
472           throughputController.control(compactionName, len);
473           // check periodically to see if a system stop is requested
474           if (closeCheckInterval > 0) {
475             bytesWritten += len;
476             if (bytesWritten > closeCheckInterval) {
477               bytesWritten = 0;
478               if (!store.areWritesEnabled()) {
479                 progress.cancel();
480                 return false;
481               }
482             }
483           }
484         }
485         if (lastCleanCell != null) {
486           // HBASE-16931, set back sequence id to avoid affecting scan order unexpectedly
487           CellUtil.setSequenceId(lastCleanCell, lastCleanCellSeqId);
488         }
489         // Log the progress of long running compactions every minute if
490         // logging at DEBUG level
491         if (LOG.isDebugEnabled()) {
492           if ((now - lastMillis) >= 60 * 1000) {
493             LOG.debug("Compaction progress: "
494                 + compactionName
495                 + " "
496                 + progress
497                 + String.format(", rate=%.2f kB/sec", (bytesWrittenProgress / 1024.0)
498                     / ((now - lastMillis) / 1000.0)) + ", throughputController is "
499                 + throughputController);
500             lastMillis = now;
501             bytesWrittenProgress = 0;
502           }
503         }
504         cells.clear();
505       } while (hasMore);
506     } catch (InterruptedException e) {
507       progress.cancel();
508       throw new InterruptedIOException("Interrupted while control throughput of compacting "
509           + compactionName);
510     } finally {
511       throughputController.finish(compactionName);
512     }
513     progress.complete();
514     return true;
515   }
516 
517   /**
518    * @param store store
519    * @param scanners Store file scanners.
520    * @param scanType Scan type.
521    * @param smallestReadPoint Smallest MVCC read point.
522    * @param earliestPutTs Earliest put across all files.
523    * @return A compaction scanner.
524    */
525   protected InternalScanner createScanner(Store store, List<StoreFileScanner> scanners,
526       ScanType scanType, long smallestReadPoint, long earliestPutTs) throws IOException {
527     Scan scan = new Scan();
528     scan.setMaxVersions(store.getFamily().getMaxVersions());
529     return new StoreScanner(store, store.getScanInfo(), scan, scanners,
530         scanType, smallestReadPoint, earliestPutTs);
531   }
532 
533   /**
534    * @param store The store.
535    * @param scanners Store file scanners.
536    * @param smallestReadPoint Smallest MVCC read point.
537    * @param earliestPutTs Earliest put across all files.
538    * @param dropDeletesFromRow Drop deletes starting with this row, inclusive. Can be null.
539    * @param dropDeletesToRow Drop deletes ending with this row, exclusive. Can be null.
540    * @return A compaction scanner.
541    */
542   protected InternalScanner createScanner(Store store, List<StoreFileScanner> scanners,
543      long smallestReadPoint, long earliestPutTs, byte[] dropDeletesFromRow,
544      byte[] dropDeletesToRow) throws IOException {
545     Scan scan = new Scan();
546     scan.setMaxVersions(store.getFamily().getMaxVersions());
547     return new StoreScanner(store, store.getScanInfo(), scan, scanners, smallestReadPoint,
548         earliestPutTs, dropDeletesFromRow, dropDeletesToRow);
549   }
550 }