1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.master.snapshot;
19
20 import java.io.FileNotFoundException;
21 import java.io.IOException;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30 import java.util.concurrent.ThreadPoolExecutor;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.apache.hadoop.hbase.classification.InterfaceAudience;
35 import org.apache.hadoop.hbase.classification.InterfaceStability;
36 import org.apache.hadoop.conf.Configuration;
37 import org.apache.hadoop.fs.FSDataInputStream;
38 import org.apache.hadoop.fs.FileStatus;
39 import org.apache.hadoop.fs.FileSystem;
40 import org.apache.hadoop.fs.Path;
41 import org.apache.hadoop.hbase.TableName;
42 import org.apache.hadoop.hbase.HBaseInterfaceAudience;
43 import org.apache.hadoop.hbase.HConstants;
44 import org.apache.hadoop.hbase.HTableDescriptor;
45 import org.apache.hadoop.hbase.Stoppable;
46 import org.apache.hadoop.hbase.MetaTableAccessor;
47 import org.apache.hadoop.hbase.errorhandling.ForeignException;
48 import org.apache.hadoop.hbase.executor.ExecutorService;
49 import org.apache.hadoop.hbase.ipc.RpcServer;
50 import org.apache.hadoop.hbase.master.AssignmentManager;
51 import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
52 import org.apache.hadoop.hbase.master.MasterFileSystem;
53 import org.apache.hadoop.hbase.master.MasterServices;
54 import org.apache.hadoop.hbase.master.MetricsMaster;
55 import org.apache.hadoop.hbase.master.SnapshotSentinel;
56 import org.apache.hadoop.hbase.master.cleaner.HFileCleaner;
57 import org.apache.hadoop.hbase.master.cleaner.HFileLinkCleaner;
58 import org.apache.hadoop.hbase.procedure.MasterProcedureManager;
59 import org.apache.hadoop.hbase.procedure.Procedure;
60 import org.apache.hadoop.hbase.procedure.ProcedureCoordinator;
61 import org.apache.hadoop.hbase.procedure.ProcedureCoordinatorRpcs;
62 import org.apache.hadoop.hbase.procedure.ZKProcedureCoordinatorRpcs;
63 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameStringPair;
64 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ProcedureDescription;
65 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
66 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription.Type;
67 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
68 import org.apache.hadoop.hbase.security.AccessDeniedException;
69 import org.apache.hadoop.hbase.security.User;
70 import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
71 import org.apache.hadoop.hbase.snapshot.HBaseSnapshotException;
72 import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
73 import org.apache.hadoop.hbase.snapshot.RestoreSnapshotHelper;
74 import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
75 import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
76 import org.apache.hadoop.hbase.snapshot.SnapshotDoesNotExistException;
77 import org.apache.hadoop.hbase.snapshot.SnapshotExistsException;
78 import org.apache.hadoop.hbase.snapshot.SnapshotManifest;
79 import org.apache.hadoop.hbase.snapshot.SnapshotReferenceUtil;
80 import org.apache.hadoop.hbase.snapshot.TablePartiallyOpenException;
81 import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException;
82 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
83 import org.apache.hadoop.hbase.util.FSUtils;
84 import org.apache.zookeeper.KeeperException;
85
86
87
88
89
90
91
92
93
94
95 @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
96 @InterfaceStability.Unstable
97 public class SnapshotManager extends MasterProcedureManager implements Stoppable {
98 private static final Log LOG = LogFactory.getLog(SnapshotManager.class);
99
100
101 private static final int SNAPSHOT_WAKE_MILLIS_DEFAULT = 500;
102
103
104
105
106
107
108
109
110
111
112
113
114 private static final int SNAPSHOT_SENTINELS_CLEANUP_TIMEOUT = 60 * 1000;
115
116
117 public static final String HBASE_SNAPSHOT_ENABLED = "hbase.snapshot.enabled";
118
119
120
121
122
123 private static final String SNAPSHOT_WAKE_MILLIS_KEY = "hbase.snapshot.master.wakeMillis";
124
125
126 private static final int SNAPSHOT_TIMEOUT_MILLIS_DEFAULT = 60000;
127
128
129
130
131
132 private static final String SNAPSHOT_TIMEOUT_MILLIS_KEY = "hbase.snapshot.master.timeoutMillis";
133
134
135 public static final String ONLINE_SNAPSHOT_CONTROLLER_DESCRIPTION = "online-snapshot";
136
137
138 private static final String SNAPSHOT_POOL_THREADS_KEY = "hbase.snapshot.master.threads";
139
140
141 private static final int SNAPSHOT_POOL_THREADS_DEFAULT = 1;
142
143 private boolean stopped;
144 private MasterServices master;
145 private ProcedureCoordinator coordinator;
146
147
148 private boolean isSnapshotSupported = false;
149
150
151
152
153
154 private Map<TableName, SnapshotSentinel> snapshotHandlers =
155 new HashMap<TableName, SnapshotSentinel>();
156
157
158
159
160
161 private Map<TableName, SnapshotSentinel> restoreHandlers =
162 new HashMap<TableName, SnapshotSentinel>();
163
164 private Path rootDir;
165 private ExecutorService executorService;
166
167 public SnapshotManager() {}
168
169
170
171
172
173
174
175 public SnapshotManager(final MasterServices master, final MetricsMaster metricsMaster,
176 ProcedureCoordinator coordinator, ExecutorService pool)
177 throws IOException, UnsupportedOperationException {
178 this.master = master;
179
180 this.rootDir = master.getMasterFileSystem().getRootDir();
181 checkSnapshotSupport(master.getConfiguration(), master.getMasterFileSystem());
182
183 this.coordinator = coordinator;
184 this.executorService = pool;
185 resetTempDir();
186 }
187
188
189
190
191
192
193 public List<SnapshotDescription> getCompletedSnapshots() throws IOException {
194 return getCompletedSnapshots(SnapshotDescriptionUtils.getSnapshotsDir(rootDir));
195 }
196
197
198
199
200
201
202
203 private List<SnapshotDescription> getCompletedSnapshots(Path snapshotDir) throws IOException {
204 List<SnapshotDescription> snapshotDescs = new ArrayList<SnapshotDescription>();
205
206 FileSystem fs = master.getMasterFileSystem().getFileSystem();
207 if (snapshotDir == null) snapshotDir = SnapshotDescriptionUtils.getSnapshotsDir(rootDir);
208
209
210 if (!fs.exists(snapshotDir)) {
211 return snapshotDescs;
212 }
213
214
215 FileStatus[] snapshots = fs.listStatus(snapshotDir,
216 new SnapshotDescriptionUtils.CompletedSnaphotDirectoriesFilter(fs));
217 MasterCoprocessorHost cpHost = master.getMasterCoprocessorHost();
218
219 for (FileStatus snapshot : snapshots) {
220 Path info = new Path(snapshot.getPath(), SnapshotDescriptionUtils.SNAPSHOTINFO_FILE);
221
222 if (!fs.exists(info)) {
223 LOG.error("Snapshot information for " + snapshot.getPath() + " doesn't exist");
224 continue;
225 }
226 FSDataInputStream in = null;
227 try {
228 in = fs.open(info);
229 SnapshotDescription desc = SnapshotDescription.parseFrom(in);
230 if (cpHost != null) {
231 try {
232 cpHost.preListSnapshot(desc);
233 } catch (AccessDeniedException e) {
234 LOG.warn("Current user does not have access to " + desc.getName() + " snapshot. "
235 + "Either you should be owner of this snapshot or admin user.");
236
237 continue;
238 }
239 }
240 snapshotDescs.add(desc);
241
242
243 if (cpHost != null) {
244 cpHost.postListSnapshot(desc);
245 }
246 } catch (IOException e) {
247 LOG.warn("Found a corrupted snapshot " + snapshot.getPath(), e);
248 } finally {
249 if (in != null) {
250 in.close();
251 }
252 }
253 }
254 return snapshotDescs;
255 }
256
257
258
259
260
261
262
263 void resetTempDir() throws IOException {
264
265 Path tmpdir = SnapshotDescriptionUtils.getWorkingSnapshotDir(rootDir);
266 if (master.getMasterFileSystem().getFileSystem().exists(tmpdir)) {
267 if (!master.getMasterFileSystem().getFileSystem().delete(tmpdir, true)) {
268 LOG.warn("Couldn't delete working snapshot directory: " + tmpdir);
269 }
270 }
271 }
272
273
274
275
276
277
278
279 public void deleteSnapshot(SnapshotDescription snapshot) throws SnapshotDoesNotExistException, IOException {
280
281 if (!isSnapshotCompleted(snapshot)) {
282 throw new SnapshotDoesNotExistException(snapshot);
283 }
284
285 String snapshotName = snapshot.getName();
286
287 FileSystem fs = master.getMasterFileSystem().getFileSystem();
288 Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
289
290
291 snapshot = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
292
293
294 MasterCoprocessorHost cpHost = master.getMasterCoprocessorHost();
295 if (cpHost != null) {
296 cpHost.preDeleteSnapshot(snapshot);
297 }
298
299 LOG.debug("Deleting snapshot: " + snapshotName);
300
301 if (!fs.delete(snapshotDir, true)) {
302 throw new HBaseSnapshotException("Failed to delete snapshot directory: " + snapshotDir);
303 }
304
305
306 if (cpHost != null) {
307 cpHost.postDeleteSnapshot(snapshot);
308 }
309
310 }
311
312
313
314
315
316
317
318
319
320 public boolean isSnapshotDone(SnapshotDescription expected) throws IOException {
321
322 if (expected == null) {
323 throw new UnknownSnapshotException(
324 "No snapshot name passed in request, can't figure out which snapshot you want to check.");
325 }
326
327 String ssString = ClientSnapshotDescriptionUtils.toString(expected);
328
329
330
331 SnapshotSentinel handler = removeSentinelIfFinished(this.snapshotHandlers, expected);
332
333
334 cleanupSentinels();
335
336 if (handler == null) {
337
338
339
340
341
342
343 if (!isSnapshotCompleted(expected)) {
344 throw new UnknownSnapshotException("Snapshot " + ssString
345 + " is not currently running or one of the known completed snapshots.");
346 }
347
348 return true;
349 }
350
351
352 try {
353 handler.rethrowExceptionIfFailed();
354 } catch (ForeignException e) {
355
356 String status;
357 Procedure p = coordinator.getProcedure(expected.getName());
358 if (p != null) {
359 status = p.getStatus();
360 } else {
361 status = expected.getName() + " not found in proclist " + coordinator.getProcedureNames();
362 }
363 throw new HBaseSnapshotException("Snapshot " + ssString + " had an error. " + status, e,
364 expected);
365 }
366
367
368 if (handler.isFinished()) {
369 LOG.debug("Snapshot '" + ssString + "' has completed, notifying client.");
370 return true;
371 } else if (LOG.isDebugEnabled()) {
372 LOG.debug("Snapshoting '" + ssString + "' is still in progress!");
373 }
374 return false;
375 }
376
377
378
379
380
381
382
383
384
385 synchronized boolean isTakingSnapshot(final SnapshotDescription snapshot) {
386 TableName snapshotTable = TableName.valueOf(snapshot.getTable());
387 if (isTakingSnapshot(snapshotTable)) {
388 return true;
389 }
390 Iterator<Map.Entry<TableName, SnapshotSentinel>> it = this.snapshotHandlers.entrySet().iterator();
391 while (it.hasNext()) {
392 Map.Entry<TableName, SnapshotSentinel> entry = it.next();
393 SnapshotSentinel sentinel = entry.getValue();
394 if (snapshot.getName().equals(sentinel.getSnapshot().getName()) && !sentinel.isFinished()) {
395 return true;
396 }
397 }
398 return false;
399 }
400
401
402
403
404
405
406
407 synchronized boolean isTakingSnapshot(final TableName tableName) {
408 SnapshotSentinel handler = this.snapshotHandlers.get(tableName);
409 return handler != null && !handler.isFinished();
410 }
411
412
413
414
415
416
417
418 private synchronized void prepareToTakeSnapshot(SnapshotDescription snapshot)
419 throws HBaseSnapshotException {
420 FileSystem fs = master.getMasterFileSystem().getFileSystem();
421 Path workingDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(snapshot, rootDir);
422 TableName snapshotTable =
423 TableName.valueOf(snapshot.getTable());
424
425
426 if (isTakingSnapshot(snapshot)) {
427 SnapshotSentinel handler = this.snapshotHandlers.get(snapshotTable);
428 throw new SnapshotCreationException("Rejected taking "
429 + ClientSnapshotDescriptionUtils.toString(snapshot)
430 + " because we are already running another snapshot "
431 + (handler != null ? ("on the same table " +
432 ClientSnapshotDescriptionUtils.toString(handler.getSnapshot()))
433 : "with the same name"), snapshot);
434 }
435
436
437 if (isRestoringTable(snapshotTable)) {
438 SnapshotSentinel handler = restoreHandlers.get(snapshotTable);
439 throw new SnapshotCreationException("Rejected taking "
440 + ClientSnapshotDescriptionUtils.toString(snapshot)
441 + " because we are already have a restore in progress on the same snapshot "
442 + ClientSnapshotDescriptionUtils.toString(handler.getSnapshot()), snapshot);
443 }
444
445 try {
446
447
448 fs.delete(workingDir, true);
449
450
451 if (!fs.mkdirs(workingDir)) {
452 throw new SnapshotCreationException("Couldn't create working directory (" + workingDir
453 + ") for snapshot" , snapshot);
454 }
455 } catch (HBaseSnapshotException e) {
456 throw e;
457 } catch (IOException e) {
458 throw new SnapshotCreationException(
459 "Exception while checking to see if snapshot could be started.", e, snapshot);
460 }
461 }
462
463
464
465
466
467
468 private synchronized void snapshotDisabledTable(SnapshotDescription snapshot)
469 throws HBaseSnapshotException {
470
471 prepareToTakeSnapshot(snapshot);
472
473
474 snapshot = snapshot.toBuilder().setType(Type.DISABLED).build();
475
476
477 DisabledTableSnapshotHandler handler =
478 new DisabledTableSnapshotHandler(snapshot, master);
479 snapshotTable(snapshot, handler);
480 }
481
482
483
484
485
486
487 private synchronized void snapshotEnabledTable(SnapshotDescription snapshot)
488 throws HBaseSnapshotException {
489
490 prepareToTakeSnapshot(snapshot);
491
492
493 EnabledTableSnapshotHandler handler =
494 new EnabledTableSnapshotHandler(snapshot, master, this);
495 snapshotTable(snapshot, handler);
496 }
497
498
499
500
501
502
503
504
505
506 private synchronized void snapshotTable(SnapshotDescription snapshot,
507 final TakeSnapshotHandler handler) throws HBaseSnapshotException {
508 try {
509 handler.prepare();
510 this.executorService.submit(handler);
511 this.snapshotHandlers.put(TableName.valueOf(snapshot.getTable()), handler);
512 } catch (Exception e) {
513
514 Path workingDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(snapshot, rootDir);
515 try {
516 if (!this.master.getMasterFileSystem().getFileSystem().delete(workingDir, true)) {
517 LOG.error("Couldn't delete working directory (" + workingDir + " for snapshot:" +
518 ClientSnapshotDescriptionUtils.toString(snapshot));
519 }
520 } catch (IOException e1) {
521 LOG.error("Couldn't delete working directory (" + workingDir + " for snapshot:" +
522 ClientSnapshotDescriptionUtils.toString(snapshot));
523 }
524
525 throw new SnapshotCreationException("Could not build snapshot handler", e, snapshot);
526 }
527 }
528
529
530
531
532
533
534
535
536 public void takeSnapshot(SnapshotDescription snapshot) throws IOException {
537
538 if (isSnapshotCompleted(snapshot)) {
539 throw new SnapshotExistsException("Snapshot '" + snapshot.getName()
540 + "' already stored on the filesystem.", snapshot);
541 }
542
543 LOG.debug("No existing snapshot, attempting snapshot...");
544
545
546 cleanupSentinels();
547
548
549 HTableDescriptor desc = null;
550 try {
551 desc = master.getTableDescriptors().get(
552 TableName.valueOf(snapshot.getTable()));
553 } catch (FileNotFoundException e) {
554 String msg = "Table:" + snapshot.getTable() + " info doesn't exist!";
555 LOG.error(msg);
556 throw new SnapshotCreationException(msg, e, snapshot);
557 } catch (IOException e) {
558 throw new SnapshotCreationException("Error while geting table description for table "
559 + snapshot.getTable(), e, snapshot);
560 }
561 if (desc == null) {
562 throw new SnapshotCreationException("Table '" + snapshot.getTable()
563 + "' doesn't exist, can't take snapshot.", snapshot);
564 }
565 SnapshotDescription.Builder builder = snapshot.toBuilder();
566
567 if (!snapshot.hasVersion()) {
568 builder.setVersion(SnapshotDescriptionUtils.SNAPSHOT_LAYOUT_VERSION);
569 }
570 User user = RpcServer.getRequestUser();
571 if (User.isHBaseSecurityEnabled(master.getConfiguration()) && user != null) {
572 builder.setOwner(user.getShortName());
573 }
574 snapshot = builder.build();
575
576
577 MasterCoprocessorHost cpHost = master.getMasterCoprocessorHost();
578 if (cpHost != null) {
579 cpHost.preSnapshot(snapshot, desc);
580 }
581
582
583 TableName snapshotTable = TableName.valueOf(snapshot.getTable());
584 AssignmentManager assignmentMgr = master.getAssignmentManager();
585 if (assignmentMgr.getTableStateManager().isTableState(snapshotTable,
586 ZooKeeperProtos.Table.State.ENABLED)) {
587 LOG.debug("Table enabled, starting distributed snapshot.");
588 snapshotEnabledTable(snapshot);
589 LOG.debug("Started snapshot: " + ClientSnapshotDescriptionUtils.toString(snapshot));
590 }
591
592 else if (assignmentMgr.getTableStateManager().isTableState(snapshotTable,
593 ZooKeeperProtos.Table.State.DISABLED)) {
594 LOG.debug("Table is disabled, running snapshot entirely on master.");
595 snapshotDisabledTable(snapshot);
596 LOG.debug("Started snapshot: " + ClientSnapshotDescriptionUtils.toString(snapshot));
597 } else {
598 LOG.error("Can't snapshot table '" + snapshot.getTable()
599 + "', isn't open or closed, we don't know what to do!");
600 TablePartiallyOpenException tpoe = new TablePartiallyOpenException(snapshot.getTable()
601 + " isn't fully open.");
602 throw new SnapshotCreationException("Table is not entirely open or closed", tpoe, snapshot);
603 }
604
605
606 if (cpHost != null) {
607 cpHost.postSnapshot(snapshot, desc);
608 }
609 }
610
611
612
613
614
615
616
617
618
619
620 public synchronized void setSnapshotHandlerForTesting(
621 final TableName tableName,
622 final SnapshotSentinel handler) {
623 if (handler != null) {
624 this.snapshotHandlers.put(tableName, handler);
625 } else {
626 this.snapshotHandlers.remove(tableName);
627 }
628 }
629
630
631
632
633 ProcedureCoordinator getCoordinator() {
634 return coordinator;
635 }
636
637
638
639
640
641
642
643
644
645
646
647 private boolean isSnapshotCompleted(SnapshotDescription snapshot) throws IOException {
648 try {
649 final Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshot, rootDir);
650 FileSystem fs = master.getMasterFileSystem().getFileSystem();
651
652 return fs.exists(snapshotDir);
653 } catch (IllegalArgumentException iae) {
654 throw new UnknownSnapshotException("Unexpected exception thrown", iae);
655 }
656 }
657
658
659
660
661
662
663
664
665 synchronized void cloneSnapshot(final SnapshotDescription snapshot,
666 final HTableDescriptor hTableDescriptor) throws HBaseSnapshotException {
667 TableName tableName = hTableDescriptor.getTableName();
668
669
670 if (isTakingSnapshot(tableName)) {
671 throw new RestoreSnapshotException("Snapshot in progress on the restore table=" + tableName);
672 }
673
674
675 if (isRestoringTable(tableName)) {
676 throw new RestoreSnapshotException("Restore already in progress on the table=" + tableName);
677 }
678
679 try {
680 CloneSnapshotHandler handler =
681 new CloneSnapshotHandler(master, snapshot, hTableDescriptor).prepare();
682 this.executorService.submit(handler);
683 this.restoreHandlers.put(tableName, handler);
684 } catch (Exception e) {
685 String msg = "Couldn't clone the snapshot=" + ClientSnapshotDescriptionUtils.toString(snapshot) +
686 " on table=" + tableName;
687 LOG.error(msg, e);
688 throw new RestoreSnapshotException(msg, e);
689 }
690 }
691
692
693
694
695
696
697 public void restoreSnapshot(SnapshotDescription reqSnapshot) throws IOException {
698 FileSystem fs = master.getMasterFileSystem().getFileSystem();
699 Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(reqSnapshot, rootDir);
700 MasterCoprocessorHost cpHost = master.getMasterCoprocessorHost();
701
702
703 if (!fs.exists(snapshotDir)) {
704 LOG.error("A Snapshot named '" + reqSnapshot.getName() + "' does not exist.");
705 throw new SnapshotDoesNotExistException(reqSnapshot);
706 }
707
708
709
710
711 SnapshotDescription snapshot = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
712 SnapshotManifest manifest = SnapshotManifest.open(master.getConfiguration(), fs,
713 snapshotDir, snapshot);
714 HTableDescriptor snapshotTableDesc = manifest.getTableDescriptor();
715 TableName tableName = TableName.valueOf(reqSnapshot.getTable());
716
717
718 cleanupSentinels();
719
720
721 SnapshotReferenceUtil.verifySnapshot(master.getConfiguration(), fs, manifest);
722
723
724 if (MetaTableAccessor.tableExists(master.getConnection(), tableName)) {
725 if (master.getAssignmentManager().getTableStateManager().isTableState(
726 TableName.valueOf(snapshot.getTable()), ZooKeeperProtos.Table.State.ENABLED)) {
727 throw new UnsupportedOperationException("Table '" +
728 TableName.valueOf(snapshot.getTable()) + "' must be disabled in order to " +
729 "perform a restore operation" +
730 ".");
731 }
732
733
734 if (cpHost != null) {
735 cpHost.preRestoreSnapshot(reqSnapshot, snapshotTableDesc);
736 }
737 restoreSnapshot(snapshot, snapshotTableDesc);
738 LOG.info("Restore snapshot=" + snapshot.getName() + " as table=" + tableName);
739
740 if (cpHost != null) {
741 cpHost.postRestoreSnapshot(reqSnapshot, snapshotTableDesc);
742 }
743 } else {
744 HTableDescriptor htd = RestoreSnapshotHelper.cloneTableSchema(snapshotTableDesc, tableName);
745 if (cpHost != null) {
746 cpHost.preCloneSnapshot(reqSnapshot, htd);
747 }
748 cloneSnapshot(snapshot, htd);
749 LOG.info("Clone snapshot=" + snapshot.getName() + " as table=" + tableName);
750
751 if (cpHost != null) {
752 cpHost.postCloneSnapshot(reqSnapshot, htd);
753 }
754 }
755 }
756
757
758
759
760
761
762
763
764 private synchronized void restoreSnapshot(final SnapshotDescription snapshot,
765 final HTableDescriptor hTableDescriptor) throws HBaseSnapshotException {
766 TableName tableName = hTableDescriptor.getTableName();
767
768
769 if (isTakingSnapshot(tableName)) {
770 throw new RestoreSnapshotException("Snapshot in progress on the restore table=" + tableName);
771 }
772
773
774 if (isRestoringTable(tableName)) {
775 throw new RestoreSnapshotException("Restore already in progress on the table=" + tableName);
776 }
777
778 try {
779 RestoreSnapshotHandler handler =
780 new RestoreSnapshotHandler(master, snapshot, hTableDescriptor).prepare();
781 this.executorService.submit(handler);
782 restoreHandlers.put(tableName, handler);
783 } catch (Exception e) {
784 String msg = "Couldn't restore the snapshot=" + ClientSnapshotDescriptionUtils.toString(
785 snapshot) +
786 " on table=" + tableName;
787 LOG.error(msg, e);
788 throw new RestoreSnapshotException(msg, e);
789 }
790 }
791
792
793
794
795
796
797
798 private synchronized boolean isRestoringTable(final TableName tableName) {
799 SnapshotSentinel sentinel = this.restoreHandlers.get(tableName);
800 return(sentinel != null && !sentinel.isFinished());
801 }
802
803
804
805
806
807
808
809
810
811 public boolean isRestoreDone(final SnapshotDescription snapshot) throws IOException {
812
813
814 SnapshotSentinel sentinel = removeSentinelIfFinished(this.restoreHandlers, snapshot);
815
816
817 cleanupSentinels();
818
819 if (sentinel == null) {
820
821 return true;
822 }
823
824 LOG.debug("Verify snapshot=" + snapshot.getName() + " against="
825 + sentinel.getSnapshot().getName() + " table=" +
826 TableName.valueOf(snapshot.getTable()));
827
828
829 sentinel.rethrowExceptionIfFailed();
830
831
832 if (sentinel.isFinished()) {
833 LOG.debug("Restore snapshot=" + ClientSnapshotDescriptionUtils.toString(snapshot) +
834 " has completed. Notifying the client.");
835 return true;
836 }
837
838 if (LOG.isDebugEnabled()) {
839 LOG.debug("Sentinel is not yet finished with restoring snapshot=" +
840 ClientSnapshotDescriptionUtils.toString(snapshot));
841 }
842 return false;
843 }
844
845
846
847
848
849
850
851
852 private synchronized SnapshotSentinel removeSentinelIfFinished(
853 final Map<TableName, SnapshotSentinel> sentinels,
854 final SnapshotDescription snapshot) {
855 if (!snapshot.hasTable()) {
856 return null;
857 }
858
859 TableName snapshotTable = TableName.valueOf(snapshot.getTable());
860 SnapshotSentinel h = sentinels.get(snapshotTable);
861 if (h == null) {
862 return null;
863 }
864
865 if (!h.getSnapshot().getName().equals(snapshot.getName())) {
866
867 return null;
868 }
869
870
871 if (h.isFinished()) {
872 sentinels.remove(snapshotTable);
873 }
874
875 return h;
876 }
877
878
879
880
881
882
883
884
885 private void cleanupSentinels() {
886 cleanupSentinels(this.snapshotHandlers);
887 cleanupSentinels(this.restoreHandlers);
888 }
889
890
891
892
893
894
895 private synchronized void cleanupSentinels(final Map<TableName, SnapshotSentinel> sentinels) {
896 long currentTime = EnvironmentEdgeManager.currentTime();
897 Iterator<Map.Entry<TableName, SnapshotSentinel>> it =
898 sentinels.entrySet().iterator();
899 while (it.hasNext()) {
900 Map.Entry<TableName, SnapshotSentinel> entry = it.next();
901 SnapshotSentinel sentinel = entry.getValue();
902 if (sentinel.isFinished() &&
903 (currentTime - sentinel.getCompletionTimestamp()) > SNAPSHOT_SENTINELS_CLEANUP_TIMEOUT)
904 {
905 it.remove();
906 }
907 }
908 }
909
910
911
912
913
914 @Override
915 public void stop(String why) {
916
917 if (this.stopped) return;
918
919 this.stopped = true;
920
921 for (SnapshotSentinel snapshotHandler: this.snapshotHandlers.values()) {
922 snapshotHandler.cancel(why);
923 }
924
925
926 for (SnapshotSentinel restoreHandler: this.restoreHandlers.values()) {
927 restoreHandler.cancel(why);
928 }
929 try {
930 if (coordinator != null) {
931 coordinator.close();
932 }
933 } catch (IOException e) {
934 LOG.error("stop ProcedureCoordinator error", e);
935 }
936 }
937
938 @Override
939 public boolean isStopped() {
940 return this.stopped;
941 }
942
943
944
945
946
947
948 public void checkSnapshotSupport() throws UnsupportedOperationException {
949 if (!this.isSnapshotSupported) {
950 throw new UnsupportedOperationException(
951 "To use snapshots, You must add to the hbase-site.xml of the HBase Master: '" +
952 HBASE_SNAPSHOT_ENABLED + "' property with value 'true'.");
953 }
954 }
955
956
957
958
959
960
961
962
963
964
965
966 private void checkSnapshotSupport(final Configuration conf, final MasterFileSystem mfs)
967 throws IOException, UnsupportedOperationException {
968
969 String enabled = conf.get(HBASE_SNAPSHOT_ENABLED);
970 boolean snapshotEnabled = conf.getBoolean(HBASE_SNAPSHOT_ENABLED, false);
971 boolean userDisabled = (enabled != null && enabled.trim().length() > 0 && !snapshotEnabled);
972
973
974 Set<String> hfileCleaners = new HashSet<String>();
975 String[] cleaners = conf.getStrings(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS);
976 if (cleaners != null) Collections.addAll(hfileCleaners, cleaners);
977
978 Set<String> logCleaners = new HashSet<String>();
979 cleaners = conf.getStrings(HConstants.HBASE_MASTER_LOGCLEANER_PLUGINS);
980 if (cleaners != null) Collections.addAll(logCleaners, cleaners);
981
982
983 Path oldSnapshotDir = new Path(mfs.getRootDir(), HConstants.OLD_SNAPSHOT_DIR_NAME);
984 FileSystem fs = mfs.getFileSystem();
985 List<SnapshotDescription> ss = getCompletedSnapshots(new Path(rootDir, oldSnapshotDir));
986 if (ss != null && !ss.isEmpty()) {
987 LOG.error("Snapshots from an earlier release were found under: " + oldSnapshotDir);
988 LOG.error("Please rename the directory as " + HConstants.SNAPSHOT_DIR_NAME);
989 }
990
991
992
993
994 if (snapshotEnabled) {
995
996 hfileCleaners.add(SnapshotHFileCleaner.class.getName());
997 hfileCleaners.add(HFileLinkCleaner.class.getName());
998 logCleaners.add(SnapshotLogCleaner.class.getName());
999
1000
1001 conf.setStrings(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS,
1002 hfileCleaners.toArray(new String[hfileCleaners.size()]));
1003 conf.setStrings(HConstants.HBASE_MASTER_LOGCLEANER_PLUGINS,
1004 logCleaners.toArray(new String[logCleaners.size()]));
1005 } else {
1006
1007 snapshotEnabled = logCleaners.contains(SnapshotLogCleaner.class.getName()) &&
1008 hfileCleaners.contains(SnapshotHFileCleaner.class.getName()) &&
1009 hfileCleaners.contains(HFileLinkCleaner.class.getName());
1010
1011
1012 if (snapshotEnabled) {
1013 LOG.warn("Snapshot log and hfile cleaners are present in the configuration, " +
1014 "but the '" + HBASE_SNAPSHOT_ENABLED + "' property " +
1015 (userDisabled ? "is set to 'false'." : "is not set."));
1016 }
1017 }
1018
1019
1020 this.isSnapshotSupported = snapshotEnabled && !userDisabled;
1021
1022
1023
1024 if (!snapshotEnabled) {
1025 LOG.info("Snapshot feature is not enabled, missing log and hfile cleaners.");
1026 Path snapshotDir = SnapshotDescriptionUtils.getSnapshotsDir(mfs.getRootDir());
1027 if (fs.exists(snapshotDir)) {
1028 FileStatus[] snapshots = FSUtils.listStatus(fs, snapshotDir,
1029 new SnapshotDescriptionUtils.CompletedSnaphotDirectoriesFilter(fs));
1030 if (snapshots != null) {
1031 LOG.error("Snapshots are present, but cleaners are not enabled.");
1032 checkSnapshotSupport();
1033 }
1034 }
1035 }
1036 }
1037
1038 @Override
1039 public void initialize(MasterServices master, MetricsMaster metricsMaster) throws KeeperException,
1040 IOException, UnsupportedOperationException {
1041 this.master = master;
1042
1043 this.rootDir = master.getMasterFileSystem().getRootDir();
1044 checkSnapshotSupport(master.getConfiguration(), master.getMasterFileSystem());
1045
1046
1047 Configuration conf = master.getConfiguration();
1048 long wakeFrequency = conf.getInt(SNAPSHOT_WAKE_MILLIS_KEY, SNAPSHOT_WAKE_MILLIS_DEFAULT);
1049 long timeoutMillis = conf.getLong(SNAPSHOT_TIMEOUT_MILLIS_KEY, SNAPSHOT_TIMEOUT_MILLIS_DEFAULT);
1050 int opThreads = conf.getInt(SNAPSHOT_POOL_THREADS_KEY, SNAPSHOT_POOL_THREADS_DEFAULT);
1051
1052
1053 String name = master.getServerName().toString();
1054 ThreadPoolExecutor tpool = ProcedureCoordinator.defaultPool(name, opThreads);
1055 ProcedureCoordinatorRpcs comms = new ZKProcedureCoordinatorRpcs(
1056 master.getZooKeeper(), SnapshotManager.ONLINE_SNAPSHOT_CONTROLLER_DESCRIPTION, name);
1057
1058 this.coordinator = new ProcedureCoordinator(comms, tpool, timeoutMillis, wakeFrequency);
1059 this.executorService = master.getExecutorService();
1060 resetTempDir();
1061 }
1062
1063 @Override
1064 public String getProcedureSignature() {
1065 return ONLINE_SNAPSHOT_CONTROLLER_DESCRIPTION;
1066 }
1067
1068 @Override
1069 public void execProcedure(ProcedureDescription desc) throws IOException {
1070 takeSnapshot(toSnapshotDescription(desc));
1071 }
1072
1073 @Override
1074 public boolean isProcedureDone(ProcedureDescription desc) throws IOException {
1075 return isSnapshotDone(toSnapshotDescription(desc));
1076 }
1077
1078 private SnapshotDescription toSnapshotDescription(ProcedureDescription desc)
1079 throws IOException {
1080 SnapshotDescription.Builder builder = SnapshotDescription.newBuilder();
1081 if (!desc.hasInstance()) {
1082 throw new IOException("Snapshot name is not defined: " + desc.toString());
1083 }
1084 String snapshotName = desc.getInstance();
1085 List<NameStringPair> props = desc.getConfigurationList();
1086 String table = null;
1087 for (NameStringPair prop : props) {
1088 if ("table".equalsIgnoreCase(prop.getName())) {
1089 table = prop.getValue();
1090 }
1091 }
1092 if (table == null) {
1093 throw new IOException("Snapshot table is not defined: " + desc.toString());
1094 }
1095 TableName tableName = TableName.valueOf(table);
1096 builder.setTable(tableName.getNameAsString());
1097 builder.setName(snapshotName);
1098 builder.setType(SnapshotDescription.Type.FLUSH);
1099 return builder.build();
1100 }
1101 }