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.master.snapshot;
19  
20  import java.io.FileNotFoundException;
21  import java.io.IOException;
22  import java.util.HashSet;
23  import java.util.List;
24  import java.util.Set;
25  import java.util.concurrent.CancellationException;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.classification.InterfaceAudience;
30  import org.apache.hadoop.conf.Configuration;
31  import org.apache.hadoop.fs.FileSystem;
32  import org.apache.hadoop.fs.Path;
33  import org.apache.hadoop.hbase.HRegionInfo;
34  import org.apache.hadoop.hbase.HTableDescriptor;
35  import org.apache.hadoop.hbase.ServerName;
36  import org.apache.hadoop.hbase.catalog.MetaReader;
37  import org.apache.hadoop.hbase.errorhandling.ForeignException;
38  import org.apache.hadoop.hbase.errorhandling.ForeignExceptionDispatcher;
39  import org.apache.hadoop.hbase.errorhandling.ForeignExceptionSnare;
40  import org.apache.hadoop.hbase.executor.EventHandler;
41  import org.apache.hadoop.hbase.master.MasterServices;
42  import org.apache.hadoop.hbase.master.SnapshotSentinel;
43  import org.apache.hadoop.hbase.master.metrics.MasterMetrics;
44  import org.apache.hadoop.hbase.monitoring.MonitoredTask;
45  import org.apache.hadoop.hbase.monitoring.TaskMonitor;
46  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
47  import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
48  import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
49  import org.apache.hadoop.hbase.snapshot.TableInfoCopyTask;
50  import org.apache.hadoop.hbase.util.Bytes;
51  import org.apache.hadoop.hbase.util.Pair;
52  import org.apache.zookeeper.KeeperException;
53  
54  /**
55   * A handler for taking snapshots from the master.
56   *
57   * This is not a subclass of TableEventHandler because using that would incur an extra META scan.
58   *
59   * The {@link #snapshotRegions(List)} call should get implemented for each snapshot flavor.
60   */
61  @InterfaceAudience.Private
62  public abstract class TakeSnapshotHandler extends EventHandler implements SnapshotSentinel,
63      ForeignExceptionSnare {
64    private static final Log LOG = LogFactory.getLog(TakeSnapshotHandler.class);
65  
66    private volatile boolean finished;
67  
68    // none of these should ever be null
69    protected final MasterServices master;
70    protected final MasterMetrics metricsMaster;
71    protected final SnapshotDescription snapshot;
72    protected final Configuration conf;
73    protected final FileSystem fs;
74    protected final Path rootDir;
75    private final Path snapshotDir;
76    protected final Path workingDir;
77    private final MasterSnapshotVerifier verifier;
78    protected final ForeignExceptionDispatcher monitor;
79    protected final MonitoredTask status;
80  
81    /**
82     * @param snapshot descriptor of the snapshot to take
83     * @param masterServices master services provider
84     * @throws IOException on unexpected error
85     */
86    public TakeSnapshotHandler(SnapshotDescription snapshot, final MasterServices masterServices,
87        final MasterMetrics metricsMaster) {
88      super(masterServices, EventType.C_M_SNAPSHOT_TABLE);
89      assert snapshot != null : "SnapshotDescription must not be nul1";
90      assert masterServices != null : "MasterServices must not be nul1";
91  
92      this.master = masterServices;
93      this.metricsMaster = metricsMaster;
94      this.snapshot = snapshot;
95      this.conf = this.master.getConfiguration();
96      this.fs = this.master.getMasterFileSystem().getFileSystem();
97      this.rootDir = this.master.getMasterFileSystem().getRootDir();
98      this.snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshot, rootDir);
99      this.workingDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(snapshot, rootDir);
100     this.monitor =  new ForeignExceptionDispatcher();
101 
102     // prepare the verify
103     this.verifier = new MasterSnapshotVerifier(masterServices, snapshot, rootDir);
104     // update the running tasks
105     this.status = TaskMonitor.get().createStatus(
106       "Taking " + snapshot.getType() + " snapshot on table: " + snapshot.getTable());
107   }
108 
109   private HTableDescriptor loadTableDescriptor()
110       throws FileNotFoundException, IOException {
111     final String name = snapshot.getTable();
112     HTableDescriptor htd =
113       this.master.getTableDescriptors().get(name);
114     if (htd == null) {
115       throw new IOException("HTableDescriptor missing for " + name);
116     }
117     return htd;
118   }
119 
120   public TakeSnapshotHandler prepare() throws Exception {
121     loadTableDescriptor(); // check that .tableinfo is present
122     return this;
123   }
124 
125   /**
126    * Execute the core common portions of taking a snapshot. The {@link #snapshotRegions(List)}
127    * call should get implemented for each snapshot flavor.
128    */
129   @Override
130   public void process() {
131     String msg = "Running " + snapshot.getType() + " table snapshot " + snapshot.getName() + " "
132         + eventType + " on table " + snapshot.getTable();
133     LOG.info(msg);
134     status.setStatus(msg);
135     try {
136       // If regions move after this meta scan, the region specific snapshot should fail, triggering
137       // an external exception that gets captured here.
138 
139       // write down the snapshot info in the working directory
140       SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, workingDir, this.fs);
141       new TableInfoCopyTask(monitor, snapshot, fs, rootDir).call();
142       monitor.rethrowException();
143 
144       List<Pair<HRegionInfo, ServerName>> regionsAndLocations =
145           MetaReader.getTableRegionsAndLocations(this.server.getCatalogTracker(),
146             Bytes.toBytes(snapshot.getTable()), true);
147 
148       // run the snapshot
149       snapshotRegions(regionsAndLocations);
150 
151       // extract each pair to separate lists
152       Set<String> serverNames = new HashSet<String>();
153       for (Pair<HRegionInfo, ServerName> p : regionsAndLocations) {
154         serverNames.add(p.getSecond().toString());
155       }
156 
157       // verify the snapshot is valid
158       status.setStatus("Verifying snapshot: " + snapshot.getName());
159       verifier.verifySnapshot(this.workingDir, serverNames);
160 
161       // complete the snapshot, atomically moving from tmp to .snapshot dir.
162       completeSnapshot(this.snapshotDir, this.workingDir, this.fs);
163       status.markComplete("Snapshot " + snapshot.getName() + " of table " + snapshot.getTable()
164           + " completed");
165       metricsMaster.addSnapshot(status.getCompletionTimestamp() - status.getStartTime());
166     } catch (Exception e) {
167       status.abort("Failed to complete snapshot " + snapshot.getName() + " on table " +
168           snapshot.getTable() + " because " + e.getMessage());
169       String reason = "Failed taking snapshot " + SnapshotDescriptionUtils.toString(snapshot)
170           + " due to exception:" + e.getMessage();
171       LOG.error(reason, e);
172       ForeignException ee = new ForeignException(reason, e);
173       monitor.receive(ee);
174       // need to mark this completed to close off and allow cleanup to happen.
175       cancel("Failed to take snapshot '" + SnapshotDescriptionUtils.toString(snapshot)
176           + "' due to exception");
177     } finally {
178       LOG.debug("Launching cleanup of working dir:" + workingDir);
179       try {
180         // if the working dir is still present, the snapshot has failed.  it is present we delete
181         // it.
182         if (fs.exists(workingDir) && !this.fs.delete(workingDir, true)) {
183           LOG.error("Couldn't delete snapshot working directory:" + workingDir);
184         }
185       } catch (IOException e) {
186         LOG.error("Couldn't delete snapshot working directory:" + workingDir);
187       }
188     }
189   }
190 
191   /**
192    * Reset the manager to allow another snapshot to proceed
193    *
194    * @param snapshotDir final path of the snapshot
195    * @param workingDir directory where the in progress snapshot was built
196    * @param fs {@link FileSystem} where the snapshot was built
197    * @throws SnapshotCreationException if the snapshot could not be moved
198    * @throws IOException the filesystem could not be reached
199    */
200   public void completeSnapshot(Path snapshotDir, Path workingDir, FileSystem fs)
201       throws SnapshotCreationException, IOException {
202     LOG.debug("Sentinel is done, just moving the snapshot from " + workingDir + " to "
203         + snapshotDir);
204     if (!fs.rename(workingDir, snapshotDir)) {
205       throw new SnapshotCreationException("Failed to move working directory(" + workingDir
206           + ") to completed directory(" + snapshotDir + ").");
207     }
208     finished = true;
209   }
210 
211   /**
212    * Snapshot the specified regions
213    */
214   protected abstract void snapshotRegions(List<Pair<HRegionInfo, ServerName>> regions)
215       throws IOException, KeeperException;
216 
217   @Override
218   public void cancel(String why) {
219     if (finished) return;
220 
221     this.finished = true;
222     LOG.info("Stop taking snapshot=" + SnapshotDescriptionUtils.toString(snapshot) + " because: "
223         + why);
224     CancellationException ce = new CancellationException(why);
225     monitor.receive(new ForeignException(master.getServerName().toString(), ce));
226   }
227 
228   @Override
229   public boolean isFinished() {
230     return finished;
231   }
232 
233   @Override
234   public long getCompletionTimestamp() {
235     return this.status.getCompletionTimestamp();
236   }
237 
238   @Override
239   public SnapshotDescription getSnapshot() {
240     return snapshot;
241   }
242 
243   @Override
244   public ForeignException getExceptionIfFailed() {
245     return monitor.getException();
246   }
247 
248   @Override
249   public void rethrowExceptionIfFailed() throws ForeignException {
250     monitor.rethrowException();
251   }
252 
253   @Override
254   public void rethrowException() throws ForeignException {
255     monitor.rethrowException();
256   }
257 
258   @Override
259   public boolean hasException() {
260     return monitor.hasException();
261   }
262 
263   @Override
264   public ForeignException getException() {
265     return monitor.getException();
266   }
267 
268 }