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  
19  package org.apache.hadoop.hbase.snapshot;
20  
21  import com.google.protobuf.CodedInputStream;
22  import com.google.protobuf.InvalidProtocolBufferException;
23  
24  import java.io.FileNotFoundException;
25  import java.io.IOException;
26  import java.util.ArrayList;
27  import java.util.Collection;
28  import java.util.HashMap;
29  import java.util.List;
30  import java.util.Map;
31  import java.util.concurrent.ThreadPoolExecutor;
32  import java.util.concurrent.TimeUnit;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.fs.FSDataInputStream;
38  import org.apache.hadoop.fs.FSDataOutputStream;
39  import org.apache.hadoop.fs.FileStatus;
40  import org.apache.hadoop.fs.FileSystem;
41  import org.apache.hadoop.fs.Path;
42  import org.apache.hadoop.hbase.HColumnDescriptor;
43  import org.apache.hadoop.hbase.HRegionInfo;
44  import org.apache.hadoop.hbase.HTableDescriptor;
45  import org.apache.hadoop.hbase.classification.InterfaceAudience;
46  import org.apache.hadoop.hbase.errorhandling.ForeignExceptionSnare;
47  import org.apache.hadoop.hbase.mob.MobUtils;
48  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
49  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
50  import org.apache.hadoop.hbase.protobuf.generated.SnapshotProtos.SnapshotDataManifest;
51  import org.apache.hadoop.hbase.protobuf.generated.SnapshotProtos.SnapshotRegionManifest;
52  import org.apache.hadoop.hbase.regionserver.HRegion;
53  import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
54  import org.apache.hadoop.hbase.regionserver.Store;
55  import org.apache.hadoop.hbase.regionserver.StoreFile;
56  import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
57  import org.apache.hadoop.hbase.util.Bytes;
58  import org.apache.hadoop.hbase.util.FSTableDescriptors;
59  import org.apache.hadoop.hbase.util.FSUtils;
60  import org.apache.hadoop.hbase.util.Threads;
61
62  /**
63   * Utility class to help read/write the Snapshot Manifest.
64   *
65   * The snapshot format is transparent for the users of this class,
66   * once the snapshot is written, it will never be modified.
67   * On open() the snapshot will be loaded to the current in-memory format.
68   */
69  @InterfaceAudience.Private
70  public final class SnapshotManifest {
71    private static final Log LOG = LogFactory.getLog(SnapshotManifest.class);
72
73    public static final String SNAPSHOT_MANIFEST_SIZE_LIMIT_CONF_KEY = "snapshot.manifest.size.limit";
74
75    public static final String DATA_MANIFEST_NAME = "data.manifest";
76
77    private List<SnapshotRegionManifest> regionManifests;
78    private SnapshotDescription desc;
79    private HTableDescriptor htd;
80
81    private final ForeignExceptionSnare monitor;
82    private final Configuration conf;
83    private final Path workingDir;
84    private final FileSystem fs;
85    private int manifestSizeLimit;
86
87    private SnapshotManifest(final Configuration conf, final FileSystem fs,
88        final Path workingDir, final SnapshotDescription desc,
89        final ForeignExceptionSnare monitor) {
90      this.monitor = monitor;
91      this.desc = desc;
92      this.workingDir = workingDir;
93      this.conf = conf;
94      this.fs = fs;
95
96      this.manifestSizeLimit = conf.getInt(SNAPSHOT_MANIFEST_SIZE_LIMIT_CONF_KEY, 64 * 1024 * 1024);
97    }
98
99    /**
100    * Return a SnapshotManifest instance, used for writing a snapshot.
101    *
102    * There are two usage pattern:
103    *  - The Master will create a manifest, add the descriptor, offline regions
104    *    and consolidate the snapshot by writing all the pending stuff on-disk.
105    *      manifest = SnapshotManifest.create(...)
106    *      manifest.addRegion(tableDir, hri)
107    *      manifest.consolidate()
108    *  - The RegionServer will create a single region manifest
109    *      manifest = SnapshotManifest.create(...)
110    *      manifest.addRegion(region)
111    */
112   public static SnapshotManifest create(final Configuration conf, final FileSystem fs,
113       final Path workingDir, final SnapshotDescription desc,
114       final ForeignExceptionSnare monitor) {
115     return new SnapshotManifest(conf, fs, workingDir, desc, monitor);
116   }
117
118   /**
119    * Return a SnapshotManifest instance with the information already loaded in-memory.
120    *    SnapshotManifest manifest = SnapshotManifest.open(...)
121    *    HTableDescriptor htd = manifest.getTableDescriptor()
122    *    for (SnapshotRegionManifest regionManifest: manifest.getRegionManifests())
123    *      hri = regionManifest.getRegionInfo()
124    *      for (regionManifest.getFamilyFiles())
125    *        ...
126    */
127   public static SnapshotManifest open(final Configuration conf, final FileSystem fs,
128       final Path workingDir, final SnapshotDescription desc) throws IOException {
129     SnapshotManifest manifest = new SnapshotManifest(conf, fs, workingDir, desc, null);
130     manifest.load();
131     return manifest;
132   }
133
134 
135   /**
136    * Add the table descriptor to the snapshot manifest
137    */
138   public void addTableDescriptor(final HTableDescriptor htd) throws IOException {
139     this.htd = htd;
140   }
141
142   interface RegionVisitor<TRegion, TFamily> {
143     TRegion regionOpen(final HRegionInfo regionInfo) throws IOException;
144     void regionClose(final TRegion region) throws IOException;
145
146     TFamily familyOpen(final TRegion region, final byte[] familyName) throws IOException;
147     void familyClose(final TRegion region, final TFamily family) throws IOException;
148
149     void storeFile(final TRegion region, final TFamily family, final StoreFileInfo storeFile)
150       throws IOException;
151   }
152
153   private RegionVisitor createRegionVisitor(final SnapshotDescription desc) throws IOException {
154     switch (getSnapshotFormat(desc)) {
155       case SnapshotManifestV1.DESCRIPTOR_VERSION:
156         return new SnapshotManifestV1.ManifestBuilder(conf, fs, workingDir);
157       case SnapshotManifestV2.DESCRIPTOR_VERSION:
158         return new SnapshotManifestV2.ManifestBuilder(conf, fs, workingDir);
159       default:
160       throw new CorruptedSnapshotException("Invalid Snapshot version: " + desc.getVersion(),
161         ProtobufUtil.createSnapshotDesc(desc));
162     }
163   }
164
165   public void addMobRegion(HRegionInfo regionInfo, HColumnDescriptor[] hcds) throws IOException {
166     // 0. Get the ManifestBuilder/RegionVisitor
167     RegionVisitor visitor = createRegionVisitor(desc);
168
169     // 1. dump region meta info into the snapshot directory
170     LOG.debug("Storing mob region '" + regionInfo + "' region-info for snapshot.");
171     Object regionData = visitor.regionOpen(regionInfo);
172     monitor.rethrowException();
173
174     // 2. iterate through all the stores in the region
175     LOG.debug("Creating references for mob files");
176
177     Path mobRegionPath = MobUtils.getMobRegionPath(conf, regionInfo.getTable());
178     for (HColumnDescriptor hcd : hcds) {
179       // 2.1. build the snapshot reference for the store if it's a mob store
180       if (!hcd.isMobEnabled()) {
181         continue;
182       }
183       Object familyData = visitor.familyOpen(regionData, hcd.getName());
184       monitor.rethrowException();
185
186       Path storePath = MobUtils.getMobFamilyPath(mobRegionPath, hcd.getNameAsString());
187       List<StoreFileInfo> storeFiles = getStoreFiles(storePath);
188       if (storeFiles == null) {
189         if (LOG.isDebugEnabled()) {
190           LOG.debug("No mob files under family: " + hcd.getNameAsString());
191         }
192         continue;
193       }
194
195       addReferenceFiles(visitor, regionData, familyData, storeFiles, true);
196
197       visitor.familyClose(regionData, familyData);
198     }
199     visitor.regionClose(regionData);
200   }
201
202   /**
203    * Creates a 'manifest' for the specified region, by reading directly from the HRegion object.
204    * This is used by the "online snapshot" when the table is enabled.
205    */
206   public void addRegion(final HRegion region) throws IOException {
207     // 0. Get the ManifestBuilder/RegionVisitor
208     RegionVisitor visitor = createRegionVisitor(desc);
209
210     // 1. dump region meta info into the snapshot directory
211     LOG.debug("Storing '" + region + "' region-info for snapshot.");
212     Object regionData = visitor.regionOpen(region.getRegionInfo());
213     monitor.rethrowException();
214
215     // 2. iterate through all the stores in the region
216     LOG.debug("Creating references for hfiles");
217
218     for (Store store : region.getStores()) {
219       // 2.1. build the snapshot reference for the store
220       Object familyData = visitor.familyOpen(regionData, store.getFamily().getName());
221       monitor.rethrowException();
222
223       List<StoreFile> storeFiles = new ArrayList<StoreFile>(store.getStorefiles());
224       if (LOG.isDebugEnabled()) {
225         LOG.debug("Adding snapshot references for " + storeFiles  + " hfiles");
226       }
227
228       // 2.2. iterate through all the store's files and create "references".
229       for (int i = 0, sz = storeFiles.size(); i < sz; i++) {
230         StoreFile storeFile = storeFiles.get(i);
231         monitor.rethrowException();
232
233         // create "reference" to this store file.
234         LOG.debug("Adding reference for file (" + (i+1) + "/" + sz + "): " + storeFile.getPath());
235         visitor.storeFile(regionData, familyData, storeFile.getFileInfo());
236       }
237       visitor.familyClose(regionData, familyData);
238     }
239     visitor.regionClose(regionData);
240   }
241
242   /**
243    * Creates a 'manifest' for the specified region, by reading directly from the disk.
244    * This is used by the "offline snapshot" when the table is disabled.
245    */
246   public void addRegion(final Path tableDir, final HRegionInfo regionInfo) throws IOException {
247     // 0. Get the ManifestBuilder/RegionVisitor
248     RegionVisitor visitor = createRegionVisitor(desc);
249
250     boolean isMobRegion = MobUtils.isMobRegionInfo(regionInfo);
251     try {
252       // Open the RegionFS
253       HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem(conf, fs,
254             tableDir, regionInfo, true);
255       monitor.rethrowException();
256
257       // 1. dump region meta info into the snapshot directory
258       LOG.debug("Storing region-info for snapshot.");
259       Object regionData = visitor.regionOpen(regionInfo);
260       monitor.rethrowException();
261
262       // 2. iterate through all the stores in the region
263       LOG.debug("Creating references for hfiles");
264
265       // This ensures that we have an atomic view of the directory as long as we have < ls limit
266       // (batch size of the files in a directory) on the namenode. Otherwise, we get back the files
267       // in batches and may miss files being added/deleted. This could be more robust (iteratively
268       // checking to see if we have all the files until we are sure), but the limit is currently
269       // 1000 files/batch, far more than the number of store files under a single column family.
270       Collection<String> familyNames = regionFs.getFamilies();
271       if (familyNames != null) {
272         for (String familyName: familyNames) {
273           Object familyData = visitor.familyOpen(regionData, Bytes.toBytes(familyName));
274           monitor.rethrowException();
275
276           Collection<StoreFileInfo> storeFiles = null;
277           if (isMobRegion) {
278             Path regionPath = MobUtils.getMobRegionPath(conf, regionInfo.getTable());
279             Path storePath = MobUtils.getMobFamilyPath(regionPath, familyName);
280             storeFiles = getStoreFiles(storePath);
281           } else {
282             storeFiles = regionFs.getStoreFiles(familyName);
283           }
284
285           if (storeFiles == null) {
286             if (LOG.isDebugEnabled()) {
287               LOG.debug("No files under family: " + familyName);
288             }
289             continue;
290           }
291
292           // 2.1. build the snapshot reference for the store
293           // iterate through all the store's files and create "references".
294           addReferenceFiles(visitor, regionData, familyData, storeFiles, false);
295
296           visitor.familyClose(regionData, familyData);
297         }
298       }
299       visitor.regionClose(regionData);
300     } catch (IOException e) {
301       // the mob directory might not be created yet, so do nothing when it is a mob region
302       if (!isMobRegion) {
303         throw e;
304       }
305     }
306   }
307
308   private List<StoreFileInfo> getStoreFiles(Path storeDir) throws IOException {
309     FileStatus[] stats = FSUtils.listStatus(fs, storeDir);
310     if (stats == null) return null;
311
312     ArrayList<StoreFileInfo> storeFiles = new ArrayList<StoreFileInfo>(stats.length);
313     for (int i = 0; i < stats.length; ++i) {
314       storeFiles.add(new StoreFileInfo(conf, fs, stats[i]));
315     }
316     return storeFiles;
317   }
318
319   private void addReferenceFiles(RegionVisitor visitor, Object regionData, Object familyData,
320       Collection<StoreFileInfo> storeFiles, boolean isMob) throws IOException {
321     final String fileType = isMob ? "mob file" : "hfile";
322
323     if (LOG.isDebugEnabled()) {
324       LOG.debug(String.format("Adding snapshot references for %s %ss", storeFiles, fileType));
325     }
326
327     int i = 0;
328     int sz = storeFiles.size();
329     for (StoreFileInfo storeFile: storeFiles) {
330       monitor.rethrowException();
331
332       LOG.debug(String.format("Adding reference for %s (%d/%d): %s",
333           fileType, ++i, sz, storeFile.getPath()));
334
335       // create "reference" to this store file.
336       visitor.storeFile(regionData, familyData, storeFile);
337     }
338   }
339
340   /**
341    * Load the information in the SnapshotManifest. Called by SnapshotManifest.open()
342    *
343    * If the format is v2 and there is no data-manifest, means that we are loading an
344    * in-progress snapshot. Since we support rolling-upgrades, we loook for v1 and v2
345    * regions format.
346    */
347   private void load() throws IOException {
348     switch (getSnapshotFormat(desc)) {
349       case SnapshotManifestV1.DESCRIPTOR_VERSION: {
350         this.htd = FSTableDescriptors.getTableDescriptorFromFs(fs, workingDir);
351         ThreadPoolExecutor tpool = createExecutor("SnapshotManifestLoader");
352         try {
353           this.regionManifests =
354             SnapshotManifestV1.loadRegionManifests(conf, tpool, fs, workingDir, desc);
355         } finally {
356           tpool.shutdown();
357         }
358         break;
359       }
360       case SnapshotManifestV2.DESCRIPTOR_VERSION: {
361         SnapshotDataManifest dataManifest = readDataManifest();
362         if (dataManifest != null) {
363           htd = ProtobufUtil.convertToHTableDesc(dataManifest.getTableSchema());
364           regionManifests = dataManifest.getRegionManifestsList();
365         } else {
366           // Compatibility, load the v1 regions
367           // This happens only when the snapshot is in-progress and the cache wants to refresh.
368           List<SnapshotRegionManifest> v1Regions, v2Regions;
369           ThreadPoolExecutor tpool = createExecutor("SnapshotManifestLoader");
370           try {
371             v1Regions = SnapshotManifestV1.loadRegionManifests(conf, tpool, fs, workingDir, desc);
372             v2Regions = SnapshotManifestV2.loadRegionManifests(conf, tpool, fs, workingDir, desc);
373           } catch (InvalidProtocolBufferException e) {
374             throw new CorruptedSnapshotException("unable to parse region manifest " +
375                 e.getMessage(), e);
376           } finally {
377             tpool.shutdown();
378           }
379           if (v1Regions != null && v2Regions != null) {
380             regionManifests =
381               new ArrayList<SnapshotRegionManifest>(v1Regions.size() + v2Regions.size());
382             regionManifests.addAll(v1Regions);
383             regionManifests.addAll(v2Regions);
384           } else if (v1Regions != null) {
385             regionManifests = v1Regions;
386           } else /* if (v2Regions != null) */ {
387             regionManifests = v2Regions;
388           }
389         }
390         break;
391       }
392       default:
393       throw new CorruptedSnapshotException("Invalid Snapshot version: " + desc.getVersion(),
394         ProtobufUtil.createSnapshotDesc(desc));
395     }
396   }
397
398   /**
399    * Get the current snapshot working dir
400    */
401   public Path getSnapshotDir() {
402     return this.workingDir;
403   }
404
405   /**
406    * Get the SnapshotDescription
407    */
408   public SnapshotDescription getSnapshotDescription() {
409     return this.desc;
410   }
411
412   /**
413    * Get the table descriptor from the Snapshot
414    */
415   public HTableDescriptor getTableDescriptor() {
416     return this.htd;
417   }
418
419   /**
420    * Get all the Region Manifest from the snapshot
421    */
422   public List<SnapshotRegionManifest> getRegionManifests() {
423     return this.regionManifests;
424   }
425
426   /**
427    * Get all the Region Manifest from the snapshot.
428    * This is an helper to get a map with the region encoded name
429    */
430   public Map<String, SnapshotRegionManifest> getRegionManifestsMap() {
431     if (regionManifests == null || regionManifests.size() == 0) return null;
432
433     HashMap<String, SnapshotRegionManifest> regionsMap =
434         new HashMap<String, SnapshotRegionManifest>(regionManifests.size());
435     for (SnapshotRegionManifest manifest: regionManifests) {
436       String regionName = getRegionNameFromManifest(manifest);
437       regionsMap.put(regionName, manifest);
438     }
439     return regionsMap;
440   }
441
442   public void consolidate() throws IOException {
443     if (getSnapshotFormat(desc) == SnapshotManifestV1.DESCRIPTOR_VERSION) {
444       Path rootDir = FSUtils.getRootDir(conf);
445       LOG.info("Using old Snapshot Format");
446       // write a copy of descriptor to the snapshot directory
447       new FSTableDescriptors(conf, fs, rootDir)
448         .createTableDescriptorForTableDirectory(workingDir, htd, false);
449     } else {
450       LOG.debug("Convert to Single Snapshot Manifest");
451       convertToV2SingleManifest();
452     }
453   }
454
455   /*
456    * In case of rolling-upgrade, we try to read all the formats and build
457    * the snapshot with the latest format.
458    */
459   private void convertToV2SingleManifest() throws IOException {
460     // Try to load v1 and v2 regions
461     List<SnapshotRegionManifest> v1Regions, v2Regions;
462     ThreadPoolExecutor tpool = createExecutor("SnapshotManifestLoader");
463     try {
464       v1Regions = SnapshotManifestV1.loadRegionManifests(conf, tpool, fs, workingDir, desc);
465       v2Regions = SnapshotManifestV2.loadRegionManifests(conf, tpool, fs, workingDir, desc);
466     } finally {
467       tpool.shutdown();
468     }
469
470     SnapshotDataManifest.Builder dataManifestBuilder = SnapshotDataManifest.newBuilder();
471     dataManifestBuilder.setTableSchema(ProtobufUtil.convertToTableSchema(htd));
472
473     if (v1Regions != null && v1Regions.size() > 0) {
474       dataManifestBuilder.addAllRegionManifests(v1Regions);
475     }
476     if (v2Regions != null && v2Regions.size() > 0) {
477       dataManifestBuilder.addAllRegionManifests(v2Regions);
478     }
479
480     // Write the v2 Data Manifest.
481     // Once the data-manifest is written, the snapshot can be considered complete.
482     // Currently snapshots are written in a "temporary" directory and later
483     // moved to the "complated" snapshot directory.
484     SnapshotDataManifest dataManifest = dataManifestBuilder.build();
485     writeDataManifest(dataManifest);
486     this.regionManifests = dataManifest.getRegionManifestsList();
487
488     // Remove the region manifests. Everything is now in the data-manifest.
489     // The delete operation is "relaxed", unless we get an exception we keep going.
490     // The extra files in the snapshot directory will not give any problem,
491     // since they have the same content as the data manifest, and even by re-reading
492     // them we will get the same information.
493     if (v1Regions != null && v1Regions.size() > 0) {
494       for (SnapshotRegionManifest regionManifest: v1Regions) {
495         SnapshotManifestV1.deleteRegionManifest(fs, workingDir, regionManifest);
496       }
497     }
498     if (v2Regions != null && v2Regions.size() > 0) {
499       for (SnapshotRegionManifest regionManifest: v2Regions) {
500         SnapshotManifestV2.deleteRegionManifest(fs, workingDir, regionManifest);
501       }
502     }
503   }
504
505   /*
506    * Write the SnapshotDataManifest file
507    */
508   private void writeDataManifest(final SnapshotDataManifest manifest)
509       throws IOException {
510     FSDataOutputStream stream = fs.create(new Path(workingDir, DATA_MANIFEST_NAME));
511     try {
512       manifest.writeTo(stream);
513     } finally {
514       stream.close();
515     }
516   }
517
518   /*
519    * Read the SnapshotDataManifest file
520    */
521   private SnapshotDataManifest readDataManifest() throws IOException {
522     FSDataInputStream in = null;
523     try {
524       in = fs.open(new Path(workingDir, DATA_MANIFEST_NAME));
525       CodedInputStream cin = CodedInputStream.newInstance(in);
526       cin.setSizeLimit(manifestSizeLimit);
527       return SnapshotDataManifest.parseFrom(cin);
528     } catch (FileNotFoundException e) {
529       return null;
530     } catch (InvalidProtocolBufferException e) {
531       throw new CorruptedSnapshotException("unable to parse data manifest " + e.getMessage(), e);
532     } finally {
533       if (in != null) in.close();
534     }
535   }
536
537   private ThreadPoolExecutor createExecutor(final String name) {
538     return createExecutor(conf, name);
539   }
540
541   public static ThreadPoolExecutor createExecutor(final Configuration conf, final String name) {
542     int maxThreads = conf.getInt("hbase.snapshot.thread.pool.max", 8);
543     return Threads.getBoundedCachedThreadPool(maxThreads, 30L, TimeUnit.SECONDS,
544               Threads.getNamedThreadFactory(name));
545   }
546
547   /**
548    * Extract the region encoded name from the region manifest
549    */
550   static String getRegionNameFromManifest(final SnapshotRegionManifest manifest) {
551     byte[] regionName = HRegionInfo.createRegionName(
552             ProtobufUtil.toTableName(manifest.getRegionInfo().getTableName()),
553             manifest.getRegionInfo().getStartKey().toByteArray(),
554             manifest.getRegionInfo().getRegionId(), true);
555     return HRegionInfo.encodeRegionName(regionName);
556   }
557
558   /*
559    * Return the snapshot format
560    */
561   private static int getSnapshotFormat(final SnapshotDescription desc) {
562     return desc.hasVersion() ? desc.getVersion() : SnapshotManifestV1.DESCRIPTOR_VERSION;
563   }
564 }