001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.hbase.snapshot;
020
021import java.io.IOException;
022import java.io.InterruptedIOException;
023import java.util.ArrayList;
024import java.util.List;
025import java.util.concurrent.Callable;
026import java.util.concurrent.ExecutionException;
027import java.util.concurrent.Executor;
028import java.util.concurrent.ExecutorCompletionService;
029import org.apache.hadoop.conf.Configuration;
030import org.apache.hadoop.fs.FSDataInputStream;
031import org.apache.hadoop.fs.FSDataOutputStream;
032import org.apache.hadoop.fs.FileStatus;
033import org.apache.hadoop.fs.FileSystem;
034import org.apache.hadoop.fs.Path;
035import org.apache.hadoop.fs.PathFilter;
036import org.apache.hadoop.hbase.client.RegionInfo;
037import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
038import org.apache.hadoop.hbase.util.CommonFSUtils;
039import org.apache.yetus.audience.InterfaceAudience;
040import org.slf4j.Logger;
041import org.slf4j.LoggerFactory;
042
043import org.apache.hbase.thirdparty.com.google.protobuf.CodedInputStream;
044import org.apache.hbase.thirdparty.com.google.protobuf.InvalidProtocolBufferException;
045import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
046
047import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
048import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos.SnapshotDescription;
049import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos.SnapshotRegionManifest;
050
051/**
052 * DO NOT USE DIRECTLY. USE {@link SnapshotManifest}.
053 *
054 * Snapshot v2 layout format
055 *  - Single Manifest file containing all the information of regions
056 *  - In the online-snapshot case each region will write a "region manifest"
057 *      /snapshotName/manifest.regionName
058 */
059@InterfaceAudience.Private
060public final class SnapshotManifestV2 {
061  private static final Logger LOG = LoggerFactory.getLogger(SnapshotManifestV2.class);
062
063  public static final int DESCRIPTOR_VERSION = 2;
064
065  public static final String SNAPSHOT_MANIFEST_PREFIX = "region-manifest.";
066
067  private SnapshotManifestV2() {}
068
069  static class ManifestBuilder implements SnapshotManifest.RegionVisitor<
070                    SnapshotRegionManifest.Builder, SnapshotRegionManifest.FamilyFiles.Builder> {
071    private final Configuration conf;
072    private final Path snapshotDir;
073    private final FileSystem rootFs;
074
075    public ManifestBuilder(final Configuration conf, final FileSystem rootFs,
076        final Path snapshotDir) {
077      this.snapshotDir = snapshotDir;
078      this.conf = conf;
079      this.rootFs = rootFs;
080    }
081
082    @Override
083    public SnapshotRegionManifest.Builder regionOpen(final RegionInfo regionInfo) {
084      SnapshotRegionManifest.Builder manifest = SnapshotRegionManifest.newBuilder();
085      manifest.setRegionInfo(ProtobufUtil.toRegionInfo(regionInfo));
086      return manifest;
087    }
088
089    @Override
090    public void regionClose(final SnapshotRegionManifest.Builder region) throws IOException {
091      // we should ensure the snapshot dir exist, maybe it has been deleted by master
092      // see HBASE-16464
093      FileSystem workingDirFs = snapshotDir.getFileSystem(this.conf);
094      if (workingDirFs.exists(snapshotDir)) {
095        SnapshotRegionManifest manifest = region.build();
096        try (FSDataOutputStream stream = workingDirFs.create(
097            getRegionManifestPath(snapshotDir, manifest))) {
098          manifest.writeTo(stream);
099        }
100      } else {
101        LOG.warn("can't write manifest without parent dir, maybe it has been deleted by master?");
102      }
103    }
104
105    @Override
106    public SnapshotRegionManifest.FamilyFiles.Builder familyOpen(
107        final SnapshotRegionManifest.Builder region, final byte[] familyName) {
108      SnapshotRegionManifest.FamilyFiles.Builder family =
109          SnapshotRegionManifest.FamilyFiles.newBuilder();
110      family.setFamilyName(UnsafeByteOperations.unsafeWrap(familyName));
111      return family;
112    }
113
114    @Override
115    public void familyClose(final SnapshotRegionManifest.Builder region,
116        final SnapshotRegionManifest.FamilyFiles.Builder family) {
117      region.addFamilyFiles(family.build());
118    }
119
120    @Override
121    public void storeFile(final SnapshotRegionManifest.Builder region,
122        final SnapshotRegionManifest.FamilyFiles.Builder family, final StoreFileInfo storeFile)
123        throws IOException {
124      SnapshotRegionManifest.StoreFile.Builder sfManifest =
125            SnapshotRegionManifest.StoreFile.newBuilder();
126      sfManifest.setName(storeFile.getPath().getName());
127      if (storeFile.isReference()) {
128        sfManifest.setReference(storeFile.getReference().convert());
129      }
130      if (!storeFile.isReference() && !storeFile.isLink()) {
131        sfManifest.setFileSize(storeFile.getSize());
132      } else {
133        sfManifest.setFileSize(storeFile.getReferencedFileStatus(rootFs).getLen());
134      }
135      family.addStoreFiles(sfManifest.build());
136    }
137  }
138
139  static List<SnapshotRegionManifest> loadRegionManifests(final Configuration conf,
140      final Executor executor, final FileSystem fs, final Path snapshotDir,
141      final SnapshotDescription desc, final int manifestSizeLimit) throws IOException {
142    FileStatus[] manifestFiles = CommonFSUtils.listStatus(fs, snapshotDir, new PathFilter() {
143      @Override
144      public boolean accept(Path path) {
145        return path.getName().startsWith(SNAPSHOT_MANIFEST_PREFIX);
146      }
147    });
148
149    if (manifestFiles == null || manifestFiles.length == 0) return null;
150
151    final ExecutorCompletionService<SnapshotRegionManifest> completionService =
152      new ExecutorCompletionService<>(executor);
153    for (final FileStatus st: manifestFiles) {
154      completionService.submit(new Callable<SnapshotRegionManifest>() {
155        @Override
156        public SnapshotRegionManifest call() throws IOException {
157          try (FSDataInputStream stream = fs.open(st.getPath())) {
158            CodedInputStream cin = CodedInputStream.newInstance(stream);
159            cin.setSizeLimit(manifestSizeLimit);
160            return SnapshotRegionManifest.parseFrom(cin);
161          }
162        }
163      });
164    }
165
166    ArrayList<SnapshotRegionManifest> regionsManifest = new ArrayList<>(manifestFiles.length);
167    try {
168      for (int i = 0; i < manifestFiles.length; ++i) {
169        regionsManifest.add(completionService.take().get());
170      }
171    } catch (InterruptedException e) {
172      throw new InterruptedIOException(e.getMessage());
173    } catch (ExecutionException e) {
174      Throwable t = e.getCause();
175
176      if(t instanceof InvalidProtocolBufferException) {
177        throw (InvalidProtocolBufferException)t;
178      } else {
179        throw new IOException("ExecutionException", e.getCause());
180      }
181    }
182    return regionsManifest;
183  }
184
185  static void deleteRegionManifest(final FileSystem fs, final Path snapshotDir,
186      final SnapshotRegionManifest manifest) throws IOException {
187    fs.delete(getRegionManifestPath(snapshotDir, manifest), true);
188  }
189
190  private static Path getRegionManifestPath(final Path snapshotDir,
191      final SnapshotRegionManifest manifest) {
192    String regionName = SnapshotManifest.getRegionNameFromManifest(manifest);
193    return new Path(snapshotDir, SNAPSHOT_MANIFEST_PREFIX + regionName);
194  }
195}