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