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) throws IOException {
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     loadTableDescriptor(); // check that .tableinfo is present
103 
104     // prepare the verify
105     this.verifier = new MasterSnapshotVerifier(masterServices, snapshot, rootDir);
106     // update the running tasks
107     this.status = TaskMonitor.get().createStatus(
108       "Taking " + snapshot.getType() + " snapshot on table: " + snapshot.getTable());
109   }
110 
111   private HTableDescriptor loadTableDescriptor()
112       throws FileNotFoundException, IOException {
113     final String name = snapshot.getTable();
114     HTableDescriptor htd =
115       this.master.getTableDescriptors().get(name);
116     if (htd == null) {
117       throw new IOException("HTableDescriptor missing for " + name);
118     }
119     return htd;
120   }
121 
122   /**
123    * Execute the core common portions of taking a snapshot. The {@link #snapshotRegions(List)}
124    * call should get implemented for each snapshot flavor.
125    */
126   @Override
127   public void process() {
128     String msg = "Running " + snapshot.getType() + " table snapshot " + snapshot.getName() + " "
129         + eventType + " on table " + snapshot.getTable();
130     LOG.info(msg);
131     status.setStatus(msg);
132     try {
133       // If regions move after this meta scan, the region specific snapshot should fail, triggering
134       // an external exception that gets captured here.
135 
136       // write down the snapshot info in the working directory
137       SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, workingDir, this.fs);
138       new TableInfoCopyTask(monitor, snapshot, fs, rootDir).call();
139       monitor.rethrowException();
140 
141       List<Pair<HRegionInfo, ServerName>> regionsAndLocations =
142           MetaReader.getTableRegionsAndLocations(this.server.getCatalogTracker(),
143             Bytes.toBytes(snapshot.getTable()), true);
144 
145       // run the snapshot
146       snapshotRegions(regionsAndLocations);
147 
148       // extract each pair to separate lists
149       Set<String> serverNames = new HashSet<String>();
150       for (Pair<HRegionInfo, ServerName> p : regionsAndLocations) {
151         serverNames.add(p.getSecond().toString());
152       }
153 
154       // verify the snapshot is valid
155       status.setStatus("Verifying snapshot: " + snapshot.getName());
156       verifier.verifySnapshot(this.workingDir, serverNames);
157 
158       // complete the snapshot, atomically moving from tmp to .snapshot dir.
159       completeSnapshot(this.snapshotDir, this.workingDir, this.fs);
160       status.markComplete("Snapshot " + snapshot.getName() + " of table " + snapshot.getTable()
161           + " completed");
162       metricsMaster.addSnapshot(status.getCompletionTimestamp() - status.getStartTime());
163     } catch (Exception e) {
164       status.abort("Failed to complete snapshot " + snapshot.getName() + " on table " +
165           snapshot.getTable() + " because " + e.getMessage());
166       String reason = "Failed taking snapshot " + SnapshotDescriptionUtils.toString(snapshot)
167           + " due to exception:" + e.getMessage();
168       LOG.error(reason, e);
169       ForeignException ee = new ForeignException(reason, e);
170       monitor.receive(ee);
171       // need to mark this completed to close off and allow cleanup to happen.
172       cancel("Failed to take snapshot '" + SnapshotDescriptionUtils.toString(snapshot)
173           + "' due to exception");
174     } finally {
175       LOG.debug("Launching cleanup of working dir:" + workingDir);
176       try {
177         // if the working dir is still present, the snapshot has failed.  it is present we delete
178         // it.
179         if (fs.exists(workingDir) && !this.fs.delete(workingDir, true)) {
180           LOG.error("Couldn't delete snapshot working directory:" + workingDir);
181         }
182       } catch (IOException e) {
183         LOG.error("Couldn't delete snapshot working directory:" + workingDir);
184       }
185     }
186   }
187 
188   /**
189    * Reset the manager to allow another snapshot to proceed
190    *
191    * @param snapshotDir final path of the snapshot
192    * @param workingDir directory where the in progress snapshot was built
193    * @param fs {@link FileSystem} where the snapshot was built
194    * @throws SnapshotCreationException if the snapshot could not be moved
195    * @throws IOException the filesystem could not be reached
196    */
197   public void completeSnapshot(Path snapshotDir, Path workingDir, FileSystem fs)
198       throws SnapshotCreationException, IOException {
199     LOG.debug("Sentinel is done, just moving the snapshot from " + workingDir + " to "
200         + snapshotDir);
201     if (!fs.rename(workingDir, snapshotDir)) {
202       throw new SnapshotCreationException("Failed to move working directory(" + workingDir
203           + ") to completed directory(" + snapshotDir + ").");
204     }
205     finished = true;
206   }
207 
208   /**
209    * Snapshot the specified regions
210    */
211   protected abstract void snapshotRegions(List<Pair<HRegionInfo, ServerName>> regions)
212       throws IOException, KeeperException;
213 
214   @Override
215   public void cancel(String why) {
216     if (finished) return;
217 
218     this.finished = true;
219     LOG.info("Stop taking snapshot=" + SnapshotDescriptionUtils.toString(snapshot) + " because: "
220         + why);
221     CancellationException ce = new CancellationException(why);
222     monitor.receive(new ForeignException(master.getServerName().toString(), ce));
223   }
224 
225   @Override
226   public boolean isFinished() {
227     return finished;
228   }
229 
230   @Override
231   public SnapshotDescription getSnapshot() {
232     return snapshot;
233   }
234 
235   @Override
236   public ForeignException getExceptionIfFailed() {
237     return monitor.getException();
238   }
239 
240   @Override
241   public void rethrowException() throws ForeignException {
242     monitor.rethrowException();
243   }
244 
245   @Override
246   public boolean hasException() {
247     return monitor.hasException();
248   }
249 
250   @Override
251   public ForeignException getException() {
252     return monitor.getException();
253   }
254 
255 }