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 */
018package org.apache.hadoop.hbase.master.snapshot;
019
020import java.io.FileNotFoundException;
021import java.io.IOException;
022import java.util.HashSet;
023import java.util.List;
024import java.util.Set;
025import java.util.concurrent.CancellationException;
026import org.apache.hadoop.conf.Configuration;
027import org.apache.hadoop.fs.FileSystem;
028import org.apache.hadoop.fs.Path;
029import org.apache.hadoop.hbase.MetaTableAccessor;
030import org.apache.hadoop.hbase.ServerName;
031import org.apache.hadoop.hbase.TableName;
032import org.apache.hadoop.hbase.client.RegionInfo;
033import org.apache.hadoop.hbase.client.TableDescriptor;
034import org.apache.hadoop.hbase.errorhandling.ForeignException;
035import org.apache.hadoop.hbase.errorhandling.ForeignExceptionDispatcher;
036import org.apache.hadoop.hbase.errorhandling.ForeignExceptionSnare;
037import org.apache.hadoop.hbase.executor.EventHandler;
038import org.apache.hadoop.hbase.executor.EventType;
039import org.apache.hadoop.hbase.master.MasterServices;
040import org.apache.hadoop.hbase.master.MetricsSnapshot;
041import org.apache.hadoop.hbase.master.SnapshotSentinel;
042import org.apache.hadoop.hbase.master.locking.LockManager;
043import org.apache.hadoop.hbase.master.locking.LockManager.MasterLock;
044import org.apache.hadoop.hbase.monitoring.MonitoredTask;
045import org.apache.hadoop.hbase.monitoring.TaskMonitor;
046import org.apache.hadoop.hbase.procedure2.LockType;
047import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
048import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
049import org.apache.hadoop.hbase.snapshot.SnapshotManifest;
050import org.apache.hadoop.hbase.util.CommonFSUtils;
051import org.apache.hadoop.hbase.util.Pair;
052import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
053import org.apache.yetus.audience.InterfaceAudience;
054import org.apache.zookeeper.KeeperException;
055import org.slf4j.Logger;
056import org.slf4j.LoggerFactory;
057
058import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
059
060import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
061import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos.SnapshotDescription;
062
063/**
064 * A handler for taking snapshots from the master.
065 *
066 * This is not a subclass of TableEventHandler because using that would incur an extra hbase:meta scan.
067 *
068 * The {@link #snapshotRegions(List)} call should get implemented for each snapshot flavor.
069 */
070@InterfaceAudience.Private
071public abstract class TakeSnapshotHandler extends EventHandler implements SnapshotSentinel,
072    ForeignExceptionSnare {
073  private static final Logger LOG = LoggerFactory.getLogger(TakeSnapshotHandler.class);
074
075  private volatile boolean finished;
076
077  // none of these should ever be null
078  protected final MasterServices master;
079  protected final MetricsSnapshot metricsSnapshot = new MetricsSnapshot();
080  protected final SnapshotDescription snapshot;
081  protected final Configuration conf;
082  protected final FileSystem rootFs;
083  protected final FileSystem workingDirFs;
084  protected final Path rootDir;
085  private final Path snapshotDir;
086  protected final Path workingDir;
087  private final MasterSnapshotVerifier verifier;
088  protected final ForeignExceptionDispatcher monitor;
089  private final LockManager.MasterLock tableLock;
090  protected final MonitoredTask status;
091  protected final TableName snapshotTable;
092  protected final SnapshotManifest snapshotManifest;
093  protected final SnapshotManager snapshotManager;
094
095  protected TableDescriptor htd;
096
097  /**
098   * @param snapshot descriptor of the snapshot to take
099   * @param masterServices master services provider
100   * @throws IllegalArgumentException if the working snapshot directory set from the
101   *   configuration is the same as the completed snapshot directory
102   * @throws IOException if the file system of the working snapshot directory cannot be
103   *   determined
104   */
105  public TakeSnapshotHandler(SnapshotDescription snapshot, final MasterServices masterServices,
106                             final SnapshotManager snapshotManager) throws IOException {
107    super(masterServices, EventType.C_M_SNAPSHOT_TABLE);
108    assert snapshot != null : "SnapshotDescription must not be nul1";
109    assert masterServices != null : "MasterServices must not be nul1";
110    this.master = masterServices;
111    this.conf = this.master.getConfiguration();
112    this.rootDir = this.master.getMasterFileSystem().getRootDir();
113    this.workingDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(snapshot, rootDir, conf);
114    Preconditions.checkArgument(!SnapshotDescriptionUtils.isSubDirectoryOf(workingDir, rootDir) ||
115            SnapshotDescriptionUtils.isWithinDefaultWorkingDir(workingDir, conf),
116        "The working directory " + workingDir + " cannot be in the root directory unless it is "
117            + "within the default working directory");
118
119    this.snapshot = snapshot;
120    this.snapshotManager = snapshotManager;
121    this.snapshotTable = TableName.valueOf(snapshot.getTable());
122    this.rootFs = this.master.getMasterFileSystem().getFileSystem();
123    this.snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshot, rootDir);
124    this.workingDirFs = this.workingDir.getFileSystem(this.conf);
125    this.monitor = new ForeignExceptionDispatcher(snapshot.getName());
126
127    this.tableLock = master.getLockManager().createMasterLock(
128        snapshotTable, LockType.EXCLUSIVE,
129        this.getClass().getName() + ": take snapshot " + snapshot.getName());
130
131    // prepare the verify
132    this.verifier = new MasterSnapshotVerifier(masterServices, snapshot, workingDirFs);
133    // update the running tasks
134    this.status = TaskMonitor.get().createStatus(
135      "Taking " + snapshot.getType() + " snapshot on table: " + snapshotTable);
136    this.status.enableStatusJournal(true);
137    this.snapshotManifest =
138        SnapshotManifest.create(conf, rootFs, workingDir, snapshot, monitor, status);
139  }
140
141  private TableDescriptor loadTableDescriptor()
142      throws FileNotFoundException, IOException {
143    TableDescriptor htd =
144      this.master.getTableDescriptors().get(snapshotTable);
145    if (htd == null) {
146      throw new IOException("TableDescriptor missing for " + snapshotTable);
147    }
148    return htd;
149  }
150
151  @Override
152  public TakeSnapshotHandler prepare() throws Exception {
153    super.prepare();
154    // after this, you should ensure to release this lock in case of exceptions
155    this.tableLock.acquire();
156    try {
157      this.htd = loadTableDescriptor(); // check that .tableinfo is present
158    } catch (Exception e) {
159      this.tableLock.release();
160      throw e;
161    }
162    return this;
163  }
164
165  /**
166   * Execute the core common portions of taking a snapshot. The {@link #snapshotRegions(List)}
167   * call should get implemented for each snapshot flavor.
168   */
169  @Override
170  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="REC_CATCH_EXCEPTION",
171    justification="Intentional")
172  public void process() {
173    String msg = "Running " + snapshot.getType() + " table snapshot " + snapshot.getName() + " "
174        + eventType + " on table " + snapshotTable;
175    LOG.info(msg);
176    MasterLock tableLockToRelease = this.tableLock;
177    status.setStatus(msg);
178    try {
179      if (downgradeToSharedTableLock()) {
180        // release the exclusive lock and hold the shared lock instead
181        tableLockToRelease = master.getLockManager().createMasterLock(snapshotTable,
182          LockType.SHARED, this.getClass().getName() + ": take snapshot " + snapshot.getName());
183        tableLock.release();
184        tableLockToRelease.acquire();
185      }
186      // If regions move after this meta scan, the region specific snapshot should fail, triggering
187      // an external exception that gets captured here.
188
189      // write down the snapshot info in the working directory
190      SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, workingDir, workingDirFs);
191      snapshotManifest.addTableDescriptor(this.htd);
192      monitor.rethrowException();
193
194      List<Pair<RegionInfo, ServerName>> regionsAndLocations;
195      if (TableName.META_TABLE_NAME.equals(snapshotTable)) {
196        regionsAndLocations = MetaTableLocator.getMetaRegionsAndLocations(
197          server.getZooKeeper());
198      } else {
199        regionsAndLocations = MetaTableAccessor.getTableRegionsAndLocations(
200          server.getConnection(), snapshotTable, false);
201      }
202
203      // run the snapshot
204      snapshotRegions(regionsAndLocations);
205      monitor.rethrowException();
206
207      // extract each pair to separate lists
208      Set<String> serverNames = new HashSet<>();
209      for (Pair<RegionInfo, ServerName> p : regionsAndLocations) {
210        if (p != null && p.getFirst() != null && p.getSecond() != null) {
211          RegionInfo hri = p.getFirst();
212          if (hri.isOffline() && (hri.isSplit() || hri.isSplitParent())) continue;
213          serverNames.add(p.getSecond().toString());
214        }
215      }
216
217      // flush the in-memory state, and write the single manifest
218      status.setStatus("Consolidate snapshot: " + snapshot.getName());
219      snapshotManifest.consolidate();
220
221      // verify the snapshot is valid
222      status.setStatus("Verifying snapshot: " + snapshot.getName());
223      verifier.verifySnapshot(this.workingDir, serverNames);
224
225      // complete the snapshot, atomically moving from tmp to .snapshot dir.
226      SnapshotDescriptionUtils.completeSnapshot(this.snapshotDir, this.workingDir, this.rootFs,
227        this.workingDirFs, this.conf);
228      finished = true;
229      msg = "Snapshot " + snapshot.getName() + " of table " + snapshotTable + " completed";
230      status.markComplete(msg);
231      LOG.info(msg);
232      metricsSnapshot.addSnapshot(status.getCompletionTimestamp() - status.getStartTime());
233      if (master.getMasterCoprocessorHost() != null) {
234        master.getMasterCoprocessorHost()
235            .postCompletedSnapshotAction(ProtobufUtil.createSnapshotDesc(snapshot), this.htd);
236      }
237    } catch (Exception e) { // FindBugs: REC_CATCH_EXCEPTION
238      status.abort("Failed to complete snapshot " + snapshot.getName() + " on table " +
239          snapshotTable + " because " + e.getMessage());
240      String reason = "Failed taking snapshot " + ClientSnapshotDescriptionUtils.toString(snapshot)
241          + " due to exception:" + e.getMessage();
242      LOG.error(reason, e);
243      ForeignException ee = new ForeignException(reason, e);
244      monitor.receive(ee);
245      // need to mark this completed to close off and allow cleanup to happen.
246      cancel(reason);
247    } finally {
248      LOG.debug("Launching cleanup of working dir:" + workingDir);
249      try {
250        // if the working dir is still present, the snapshot has failed.  it is present we delete
251        // it.
252        if (!workingDirFs.delete(workingDir, true)) {
253          LOG.error("Couldn't delete snapshot working directory:" + workingDir);
254        }
255      } catch (IOException e) {
256        LOG.error("Couldn't delete snapshot working directory:" + workingDir);
257      }
258      if (LOG.isDebugEnabled()) {
259        LOG.debug("Table snapshot journal : \n" + status.prettyPrintJournal());
260      }
261      tableLockToRelease.release();
262    }
263  }
264
265  /**
266   * When taking snapshot, first we must acquire the exclusive table lock to confirm that there are
267   * no ongoing merge/split procedures. But later, we should try our best to release the exclusive
268   * lock as this may hurt the availability, because we need to hold the shared lock when assigning
269   * regions.
270   * <p/>
271   * See HBASE-21480 for more details.
272   */
273  protected abstract boolean downgradeToSharedTableLock();
274
275  /**
276   * Snapshot the specified regions
277   */
278  protected abstract void snapshotRegions(List<Pair<RegionInfo, ServerName>> regions)
279      throws IOException, KeeperException;
280
281  /**
282   * Take a snapshot of the specified disabled region
283   */
284  protected void snapshotDisabledRegion(final RegionInfo regionInfo)
285      throws IOException {
286    snapshotManifest.addRegion(CommonFSUtils.getTableDir(rootDir, snapshotTable), regionInfo);
287    monitor.rethrowException();
288    status.setStatus("Completed referencing HFiles for offline region " + regionInfo.toString() +
289        " of table: " + snapshotTable);
290  }
291
292  @Override
293  public void cancel(String why) {
294    if (finished) return;
295
296    this.finished = true;
297    LOG.info("Stop taking snapshot=" + ClientSnapshotDescriptionUtils.toString(snapshot) +
298        " because: " + why);
299    CancellationException ce = new CancellationException(why);
300    monitor.receive(new ForeignException(master.getServerName().toString(), ce));
301  }
302
303  @Override
304  public boolean isFinished() {
305    return finished;
306  }
307
308  @Override
309  public long getCompletionTimestamp() {
310    return this.status.getCompletionTimestamp();
311  }
312
313  @Override
314  public SnapshotDescription getSnapshot() {
315    return snapshot;
316  }
317
318  @Override
319  public ForeignException getExceptionIfFailed() {
320    return monitor.getException();
321  }
322
323  @Override
324  public void rethrowExceptionIfFailed() throws ForeignException {
325    monitor.rethrowException();
326  }
327
328  @Override
329  public void rethrowException() throws ForeignException {
330    monitor.rethrowException();
331  }
332
333  @Override
334  public boolean hasException() {
335    return monitor.hasException();
336  }
337
338  @Override
339  public ForeignException getException() {
340    return monitor.getException();
341  }
342}