View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.master.snapshot;
21  
22  import java.io.IOException;
23  import java.util.List;
24  import java.util.concurrent.CancellationException;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.apache.hadoop.classification.InterfaceAudience;
29  import org.apache.hadoop.fs.FileSystem;
30  import org.apache.hadoop.fs.Path;
31  import org.apache.hadoop.hbase.HRegionInfo;
32  import org.apache.hadoop.hbase.HTableDescriptor;
33  import org.apache.hadoop.hbase.NotAllMetaRegionsOnlineException;
34  import org.apache.hadoop.hbase.TableExistsException;
35  import org.apache.hadoop.hbase.catalog.MetaReader;
36  import org.apache.hadoop.hbase.catalog.CatalogTracker;
37  import org.apache.hadoop.hbase.errorhandling.ForeignException;
38  import org.apache.hadoop.hbase.errorhandling.ForeignExceptionDispatcher;
39  import org.apache.hadoop.hbase.master.MasterServices;
40  import org.apache.hadoop.hbase.master.SnapshotSentinel;
41  import org.apache.hadoop.hbase.master.handler.CreateTableHandler;
42  import org.apache.hadoop.hbase.master.metrics.MasterMetrics;
43  import org.apache.hadoop.hbase.monitoring.MonitoredTask;
44  import org.apache.hadoop.hbase.monitoring.TaskMonitor;
45  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
46  import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
47  import org.apache.hadoop.hbase.snapshot.RestoreSnapshotHelper;
48  import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
49  import org.apache.hadoop.hbase.util.Bytes;
50  
51  import com.google.common.base.Preconditions;
52  
53  /**
54   * Handler to Clone a snapshot.
55   *
56   * <p>Uses {@link RestoreSnapshotHelper} to create a new table with the same
57   * content of the specified snapshot.
58   */
59  @InterfaceAudience.Private
60  public class CloneSnapshotHandler extends CreateTableHandler implements SnapshotSentinel {
61    private static final Log LOG = LogFactory.getLog(CloneSnapshotHandler.class);
62  
63    private final static String NAME = "Master CloneSnapshotHandler";
64  
65    private final SnapshotDescription snapshot;
66  
67    private final ForeignExceptionDispatcher monitor;
68    private final MasterMetrics metricsMaster;
69    private final MonitoredTask status;
70  
71    private RestoreSnapshotHelper.RestoreMetaChanges metaChanges;
72  
73    private volatile boolean stopped = false;
74  
75    public CloneSnapshotHandler(final MasterServices masterServices,
76        final SnapshotDescription snapshot, final HTableDescriptor hTableDescriptor,
77        final MasterMetrics metricsMaster)
78        throws NotAllMetaRegionsOnlineException, TableExistsException, IOException {
79      super(masterServices, masterServices.getMasterFileSystem(),
80        masterServices.getServerManager(), hTableDescriptor,
81        masterServices.getConfiguration(), null, masterServices.getCatalogTracker(),
82        masterServices.getAssignmentManager());
83      this.metricsMaster = metricsMaster;
84  
85      // Snapshot information
86      this.snapshot = snapshot;
87  
88      // Monitor
89      this.monitor = new ForeignExceptionDispatcher();
90      this.status = TaskMonitor.get().createStatus("Cloning  snapshot '" + snapshot.getName() +
91        "' to table " + hTableDescriptor.getNameAsString());
92    }
93  
94    /**
95     * Create the on-disk regions, using the tableRootDir provided by the CreateTableHandler.
96     * The cloned table will be created in a temp directory, and then the CreateTableHandler
97     * will be responsible to add the regions returned by this method to META and do the assignment.
98     */
99    @Override
100   protected List<HRegionInfo> handleCreateHdfsRegions(final Path tableRootDir,
101       final String tableName) throws IOException {
102     status.setStatus("Creating regions for table: " + tableName);
103     FileSystem fs = fileSystemManager.getFileSystem();
104     Path rootDir = fileSystemManager.getRootDir();
105     Path tableDir = new Path(tableRootDir, tableName);
106 
107     try {
108       // 1. Execute the on-disk Clone
109       Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshot, rootDir);
110       RestoreSnapshotHelper restoreHelper = new RestoreSnapshotHelper(conf, fs,
111           snapshot, snapshotDir, hTableDescriptor, tableDir, monitor, status);
112       metaChanges = restoreHelper.restoreHdfsRegions();
113 
114       // Clone operation should not have stuff to restore or remove
115       Preconditions.checkArgument(!metaChanges.hasRegionsToRestore(),
116           "A clone should not have regions to restore");
117       Preconditions.checkArgument(!metaChanges.hasRegionsToRemove(),
118           "A clone should not have regions to remove");
119 
120       // At this point the clone is complete. Next step is enabling the table.
121       String msg = "Clone snapshot=" + snapshot.getName() +" on table=" + tableName + " completed!";
122       LOG.info(msg);
123       status.setStatus(msg + " Waiting for table to be enabled...");
124 
125       // 2. let the CreateTableHandler add the regions to meta
126       return metaChanges.getRegionsToAdd();
127     } catch (Exception e) {
128       String msg = "clone snapshot=" + SnapshotDescriptionUtils.toString(snapshot) + " failed";
129       LOG.error(msg, e);
130       IOException rse = new RestoreSnapshotException(msg, e, snapshot);
131 
132       // these handlers aren't futures so we need to register the error here.
133       this.monitor.receive(new ForeignException(NAME, rse));
134       throw rse;
135     }
136   }
137 
138   @Override
139   protected void addRegionsToMeta(final CatalogTracker ct, final List<HRegionInfo> regionInfos)
140       throws IOException {
141     super.addRegionsToMeta(ct, regionInfos);
142     metaChanges.updateMetaParentRegions(ct, regionInfos);
143   }
144 
145   @Override
146   protected void completed(final Throwable exception) {
147     this.stopped = true;
148     if (exception != null) {
149      status.abort("Snapshot '" + snapshot.getName() + "' clone failed because " +
150         exception.getMessage());
151     } else {
152       status.markComplete("Snapshot '"+ snapshot.getName() +"' clone completed and table enabled!");
153     }
154     metricsMaster.addSnapshotClone(status.getCompletionTimestamp() - status.getStartTime());
155     super.completed(exception);
156   }
157 
158   @Override
159   public boolean isFinished() {
160     return this.stopped;
161   }
162 
163   @Override
164   public long getCompletionTimestamp() {
165     return this.status.getCompletionTimestamp();
166   }
167 
168   @Override
169   public SnapshotDescription getSnapshot() {
170     return snapshot;
171   }
172 
173   @Override
174   public void cancel(String why) {
175     if (this.stopped) return;
176     this.stopped = true;
177     String msg = "Stopping clone snapshot=" + snapshot + " because: " + why;
178     LOG.info(msg);
179     status.abort(msg);
180     this.monitor.receive(new ForeignException(NAME, new CancellationException(why)));
181   }
182 
183   @Override
184   public ForeignException getExceptionIfFailed() {
185     return this.monitor.getException();
186   }
187 
188   @Override
189   public void rethrowExceptionIfFailed() throws ForeignException {
190     monitor.rethrowException();
191   }
192 }