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.LinkedList;
24  import java.util.List;
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.fs.FileSystem;
31  import org.apache.hadoop.fs.Path;
32  import org.apache.hadoop.hbase.HRegionInfo;
33  import org.apache.hadoop.hbase.HTableDescriptor;
34  import org.apache.hadoop.hbase.TableName;
35  import org.apache.hadoop.hbase.MetaTableAccessor;
36  import org.apache.hadoop.hbase.client.HConnection;
37  import org.apache.hadoop.hbase.errorhandling.ForeignException;
38  import org.apache.hadoop.hbase.errorhandling.ForeignExceptionDispatcher;
39  import org.apache.hadoop.hbase.executor.EventType;
40  import org.apache.hadoop.hbase.master.AssignmentManager;
41  import org.apache.hadoop.hbase.master.MasterFileSystem;
42  import org.apache.hadoop.hbase.master.MasterServices;
43  import org.apache.hadoop.hbase.master.MetricsSnapshot;
44  import org.apache.hadoop.hbase.master.RegionStates;
45  import org.apache.hadoop.hbase.master.SnapshotSentinel;
46  import org.apache.hadoop.hbase.master.handler.TableEventHandler;
47  import org.apache.hadoop.hbase.monitoring.MonitoredTask;
48  import org.apache.hadoop.hbase.monitoring.TaskMonitor;
49  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
50  import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
51  import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
52  import org.apache.hadoop.hbase.snapshot.RestoreSnapshotHelper;
53  import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
54  import org.apache.hadoop.hbase.snapshot.SnapshotManifest;
55  
56  /**
57   * Handler to Restore a snapshot.
58   *
59   * <p>Uses {@link RestoreSnapshotHelper} to replace the table content with the
60   * data available in the snapshot.
61   */
62  @InterfaceAudience.Private
63  public class RestoreSnapshotHandler extends TableEventHandler implements SnapshotSentinel {
64    private static final Log LOG = LogFactory.getLog(RestoreSnapshotHandler.class);
65  
66    private final HTableDescriptor hTableDescriptor;
67    private final SnapshotDescription snapshot;
68  
69    private final ForeignExceptionDispatcher monitor;
70    private final MetricsSnapshot metricsSnapshot = new MetricsSnapshot();
71    private final MonitoredTask status;
72  
73    private volatile boolean stopped = false;
74  
75    public RestoreSnapshotHandler(final MasterServices masterServices,
76        final SnapshotDescription snapshot, final HTableDescriptor htd) throws IOException {
77      super(EventType.C_M_RESTORE_SNAPSHOT, htd.getTableName(), masterServices, masterServices);
78  
79      // Snapshot information
80      this.snapshot = snapshot;
81  
82      // Monitor
83      this.monitor = new ForeignExceptionDispatcher();
84  
85      // Check table exists.
86      getTableDescriptor();
87  
88      // This is the new schema we are going to write out as this modification.
89      this.hTableDescriptor = htd;
90  
91      this.status = TaskMonitor.get().createStatus(
92        "Restoring  snapshot '" + snapshot.getName() + "' to table "
93            + hTableDescriptor.getTableName());
94    }
95  
96    @Override
97    public RestoreSnapshotHandler prepare() throws IOException {
98      return (RestoreSnapshotHandler) super.prepare();
99    }
100 
101   /**
102    * The restore table is executed in place.
103    *  - The on-disk data will be restored - reference files are put in place without moving data
104    *  -  [if something fail here: you need to delete the table and re-run the restore]
105    *  - hbase:meta will be updated
106    *  -  [if something fail here: you need to run hbck to fix hbase:meta entries]
107    * The passed in list gets changed in this method
108    */
109   @Override
110   protected void handleTableOperation(List<HRegionInfo> hris) throws IOException {
111     MasterFileSystem fileSystemManager = masterServices.getMasterFileSystem();
112     HConnection conn = masterServices.getShortCircuitConnection();
113     FileSystem fs = fileSystemManager.getFileSystem();
114     Path rootDir = fileSystemManager.getRootDir();
115     TableName tableName = hTableDescriptor.getTableName();
116 
117     try {
118       // 1. Update descriptor
119       this.masterServices.getTableDescriptors().add(hTableDescriptor);
120 
121       // 2. Execute the on-disk Restore
122       LOG.debug("Starting restore snapshot=" + ClientSnapshotDescriptionUtils.toString(snapshot));
123       Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshot, rootDir);
124       SnapshotManifest manifest = SnapshotManifest.open(masterServices.getConfiguration(), fs,
125                                                         snapshotDir, snapshot);
126       RestoreSnapshotHelper restoreHelper = new RestoreSnapshotHelper(
127           masterServices.getConfiguration(), fs, manifest,
128           this.hTableDescriptor, rootDir, monitor, status);
129       RestoreSnapshotHelper.RestoreMetaChanges metaChanges = restoreHelper.restoreHdfsRegions();
130 
131       // 3. Forces all the RegionStates to be offline
132       //
133       // The AssignmentManager keeps all the region states around
134       // with no possibility to remove them, until the master is restarted.
135       // This means that a region marked as SPLIT before the restore will never be assigned again.
136       // To avoid having all states around all the regions are switched to the OFFLINE state,
137       // which is the same state that the regions will be after a delete table.
138       forceRegionsOffline(metaChanges);
139 
140       // 4. Applies changes to hbase:meta
141       status.setStatus("Preparing to restore each region");
142 
143       // 4.1 Removes the current set of regions from META
144       //
145       // By removing also the regions to restore (the ones present both in the snapshot
146       // and in the current state) we ensure that no extra fields are present in META
147       // e.g. with a simple add addRegionToMeta() the splitA and splitB attributes
148       // not overwritten/removed, so you end up with old informations
149       // that are not correct after the restore.
150       List<HRegionInfo> hrisToRemove = new LinkedList<HRegionInfo>();
151       if (metaChanges.hasRegionsToRemove()) hrisToRemove.addAll(metaChanges.getRegionsToRemove());
152       MetaTableAccessor.deleteRegions(conn, hrisToRemove);
153 
154       // 4.2 Add the new set of regions to META
155       //
156       // At this point the old regions are no longer present in META.
157       // and the set of regions present in the snapshot will be written to META.
158       // All the information in hbase:meta are coming from the .regioninfo of each region present
159       // in the snapshot folder.
160       hris.clear();
161       if (metaChanges.hasRegionsToAdd()) hris.addAll(metaChanges.getRegionsToAdd());
162       MetaTableAccessor.addRegionsToMeta(conn, hris);
163       if (metaChanges.hasRegionsToRestore()) {
164         MetaTableAccessor.overwriteRegions(conn, metaChanges.getRegionsToRestore());
165       }
166       metaChanges.updateMetaParentRegions(this.server.getShortCircuitConnection(), hris);
167 
168       // At this point the restore is complete. Next step is enabling the table.
169       LOG.info("Restore snapshot=" + ClientSnapshotDescriptionUtils.toString(snapshot) +
170         " on table=" + tableName + " completed!");
171     } catch (IOException e) {
172       String msg = "restore snapshot=" + ClientSnapshotDescriptionUtils.toString(snapshot)
173           + " failed. Try re-running the restore command.";
174       LOG.error(msg, e);
175       monitor.receive(new ForeignException(masterServices.getServerName().toString(), e));
176       throw new RestoreSnapshotException(msg, e);
177     }
178   }
179 
180   private void forceRegionsOffline(final RestoreSnapshotHelper.RestoreMetaChanges metaChanges) {
181     forceRegionsOffline(metaChanges.getRegionsToAdd());
182     forceRegionsOffline(metaChanges.getRegionsToRestore());
183     forceRegionsOffline(metaChanges.getRegionsToRemove());
184   }
185 
186   private void forceRegionsOffline(final List<HRegionInfo> hris) {
187     AssignmentManager am = this.masterServices.getAssignmentManager();
188     RegionStates states = am.getRegionStates();
189     if (hris != null) {
190       for (HRegionInfo hri: hris) {
191         states.regionOffline(hri);
192       }
193     }
194   }
195 
196   @Override
197   protected void completed(final Throwable exception) {
198     this.stopped = true;
199     if (exception != null) {
200       status.abort("Restore snapshot '" + snapshot.getName() + "' failed because " +
201           exception.getMessage());
202     } else {
203       status.markComplete("Restore snapshot '"+ snapshot.getName() +"'!");
204     }
205     metricsSnapshot.addSnapshotRestore(status.getCompletionTimestamp() - status.getStartTime());
206     super.completed(exception);
207   }
208 
209   @Override
210   public boolean isFinished() {
211     return this.stopped;
212   }
213 
214   @Override
215   public long getCompletionTimestamp() {
216     return this.status.getCompletionTimestamp();
217   }
218 
219   @Override
220   public SnapshotDescription getSnapshot() {
221     return snapshot;
222   }
223 
224   @Override
225   public void cancel(String why) {
226     if (this.stopped) return;
227     this.stopped = true;
228     String msg = "Stopping restore snapshot=" + ClientSnapshotDescriptionUtils.toString(snapshot)
229         + " because: " + why;
230     LOG.info(msg);
231     CancellationException ce = new CancellationException(why);
232     this.monitor.receive(new ForeignException(masterServices.getServerName().toString(), ce));
233   }
234 
235   @Override
236   public ForeignException getExceptionIfFailed() {
237     return this.monitor.getException();
238   }
239 
240   @Override
241   public void rethrowExceptionIfFailed() throws ForeignException {
242     monitor.rethrowException();
243   }
244 }