1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.client;
20
21 import java.io.Closeable;
22 import java.io.IOException;
23 import java.io.InterruptedIOException;
24 import java.net.SocketTimeoutException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.concurrent.atomic.AtomicInteger;
30 import java.util.concurrent.atomic.AtomicReference;
31 import java.util.regex.Pattern;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.apache.hadoop.classification.InterfaceAudience;
36 import org.apache.hadoop.classification.InterfaceStability;
37 import org.apache.hadoop.conf.Configuration;
38 import org.apache.hadoop.hbase.Abortable;
39 import org.apache.hadoop.hbase.ClusterStatus;
40 import org.apache.hadoop.hbase.TableName;
41 import org.apache.hadoop.hbase.HBaseConfiguration;
42 import org.apache.hadoop.hbase.HBaseIOException;
43 import org.apache.hadoop.hbase.HColumnDescriptor;
44 import org.apache.hadoop.hbase.HConstants;
45 import org.apache.hadoop.hbase.HRegionInfo;
46 import org.apache.hadoop.hbase.HRegionLocation;
47 import org.apache.hadoop.hbase.HTableDescriptor;
48 import org.apache.hadoop.hbase.NamespaceDescriptor;
49 import org.apache.hadoop.hbase.MasterNotRunningException;
50 import org.apache.hadoop.hbase.NotServingRegionException;
51 import org.apache.hadoop.hbase.RegionException;
52 import org.apache.hadoop.hbase.ServerName;
53 import org.apache.hadoop.hbase.TableExistsException;
54 import org.apache.hadoop.hbase.TableNotDisabledException;
55 import org.apache.hadoop.hbase.TableNotEnabledException;
56 import org.apache.hadoop.hbase.TableNotFoundException;
57 import org.apache.hadoop.hbase.UnknownRegionException;
58 import org.apache.hadoop.hbase.ZooKeeperConnectionException;
59 import org.apache.hadoop.hbase.catalog.CatalogTracker;
60 import org.apache.hadoop.hbase.catalog.MetaReader;
61 import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitor;
62 import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitorBase;
63 import org.apache.hadoop.hbase.exceptions.DeserializationException;
64 import org.apache.hadoop.hbase.regionserver.wal.FailedLogCloseException;
65 import org.apache.hadoop.hbase.snapshot.HBaseSnapshotException;
66 import org.apache.hadoop.hbase.exceptions.MergeRegionException;
67 import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
68 import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
69 import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException;
70 import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
71 import org.apache.hadoop.hbase.ipc.MasterCoprocessorRpcChannel;
72 import org.apache.hadoop.hbase.ipc.PayloadCarryingRpcController;
73 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
74 import org.apache.hadoop.hbase.protobuf.RequestConverter;
75 import org.apache.hadoop.hbase.protobuf.ResponseConverter;
76 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
77 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest;
78 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionResponse;
79 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CompactRegionRequest;
80 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.FlushRegionRequest;
81 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
82 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
83 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse.CompactionState;
84 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.RollWALWriterRequest;
85 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.RollWALWriterResponse;
86 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.StopServerRequest;
87 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ClientService;
88 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
89 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
90 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
91 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
92 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.TableSchema;
93 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.AddColumnRequest;
94 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.AssignRegionRequest;
95 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateNamespaceRequest;
96 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateTableRequest;
97 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteColumnRequest;
98 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteNamespaceRequest;
99 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteSnapshotRequest;
100 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteTableRequest;
101 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DisableTableRequest;
102 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DispatchMergingRegionsRequest;
103 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.EnableTableRequest;
104 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetClusterStatusRequest;
105 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsRequest;
106 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetNamespaceDescriptorRequest;
107 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetSchemaAlterStatusRequest;
108 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetSchemaAlterStatusResponse;
109 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsRequest;
110 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsResponse;
111 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsRestoreSnapshotDoneRequest;
112 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsRestoreSnapshotDoneResponse;
113 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
114 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
115 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListNamespaceDescriptorsRequest;
116 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceRequest;
117 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListTableNamesByNamespaceRequest;
118 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyColumnRequest;
119 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyNamespaceRequest;
120 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyTableRequest;
121 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MoveRegionRequest;
122 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RestoreSnapshotRequest;
123 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RestoreSnapshotResponse;
124 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetBalancerRunningRequest;
125 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ShutdownRequest;
126 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SnapshotRequest;
127 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SnapshotResponse;
128 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.StopMasterRequest;
129 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.UnassignRegionRequest;
130 import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
131 import org.apache.hadoop.hbase.util.Addressing;
132 import org.apache.hadoop.hbase.util.Bytes;
133 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
134 import org.apache.hadoop.hbase.util.Pair;
135 import org.apache.hadoop.ipc.RemoteException;
136 import org.apache.hadoop.util.StringUtils;
137 import org.apache.zookeeper.KeeperException;
138
139 import com.google.protobuf.ByteString;
140 import com.google.protobuf.ServiceException;
141
142
143
144
145
146
147
148
149
150
151 @InterfaceAudience.Public
152 @InterfaceStability.Evolving
153 public class HBaseAdmin implements Abortable, Closeable {
154 private static final Log LOG = LogFactory.getLog(HBaseAdmin.class);
155
156
157
158 private HConnection connection;
159
160 private volatile Configuration conf;
161 private final long pause;
162 private final int numRetries;
163
164
165
166 private final int retryLongerMultiplier;
167 private boolean aborted;
168 private boolean cleanupConnectionOnClose = false;
169 private boolean closed = false;
170
171 private RpcRetryingCallerFactory rpcCallerFactory;
172
173
174
175
176
177
178
179 public HBaseAdmin(Configuration c)
180 throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
181
182
183 this(HConnectionManager.getConnection(new Configuration(c)));
184 this.cleanupConnectionOnClose = true;
185 }
186
187
188
189
190
191
192
193
194
195 public HBaseAdmin(HConnection connection)
196 throws MasterNotRunningException, ZooKeeperConnectionException {
197 this.conf = connection.getConfiguration();
198 this.connection = connection;
199
200 this.pause = this.conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
201 HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
202 this.numRetries = this.conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
203 HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
204 this.retryLongerMultiplier = this.conf.getInt(
205 "hbase.client.retries.longer.multiplier", 10);
206 this.rpcCallerFactory = RpcRetryingCallerFactory.instantiate(this.conf);
207 }
208
209
210
211
212
213
214
215
216 private synchronized CatalogTracker getCatalogTracker()
217 throws ZooKeeperConnectionException, IOException {
218 CatalogTracker ct = null;
219 try {
220 ct = new CatalogTracker(this.conf);
221 ct.start();
222 } catch (InterruptedException e) {
223
224 throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
225 }
226 return ct;
227 }
228
229 private void cleanupCatalogTracker(final CatalogTracker ct) {
230 ct.stop();
231 }
232
233 @Override
234 public void abort(String why, Throwable e) {
235
236 this.aborted = true;
237 throw new RuntimeException(why, e);
238 }
239
240 @Override
241 public boolean isAborted(){
242 return this.aborted;
243 }
244
245
246 public HConnection getConnection() {
247 return connection;
248 }
249
250
251
252
253
254
255 public boolean isMasterRunning()
256 throws MasterNotRunningException, ZooKeeperConnectionException {
257 return connection.isMasterRunning();
258 }
259
260
261
262
263
264
265 public boolean tableExists(final TableName tableName)
266 throws IOException {
267 boolean b = false;
268 CatalogTracker ct = getCatalogTracker();
269 try {
270 b = MetaReader.tableExists(ct, tableName);
271 } finally {
272 cleanupCatalogTracker(ct);
273 }
274 return b;
275 }
276
277 public boolean tableExists(final byte[] tableName)
278 throws IOException {
279 return tableExists(TableName.valueOf(tableName));
280 }
281
282 public boolean tableExists(final String tableName)
283 throws IOException {
284 return tableExists(TableName.valueOf(tableName));
285 }
286
287
288
289
290
291
292
293
294
295
296
297 public HTableDescriptor[] listTables() throws IOException {
298 return this.connection.listTables();
299 }
300
301
302
303
304
305
306
307
308
309 public HTableDescriptor[] listTables(Pattern pattern) throws IOException {
310 List<HTableDescriptor> matched = new LinkedList<HTableDescriptor>();
311 HTableDescriptor[] tables = listTables();
312 for (HTableDescriptor table : tables) {
313 if (pattern.matcher(table.getTableName().getNameAsString()).matches()) {
314 matched.add(table);
315 }
316 }
317 return matched.toArray(new HTableDescriptor[matched.size()]);
318 }
319
320
321
322
323
324
325
326
327
328 public HTableDescriptor[] listTables(String regex) throws IOException {
329 return listTables(Pattern.compile(regex));
330 }
331
332
333
334
335
336
337 @Deprecated
338 public String[] getTableNames() throws IOException {
339 return this.connection.getTableNames();
340 }
341
342
343
344
345
346
347
348 @Deprecated
349 public String[] getTableNames(Pattern pattern) throws IOException {
350 List<String> matched = new ArrayList<String>();
351 for (String name: this.connection.getTableNames()) {
352 if (pattern.matcher(name).matches()) {
353 matched.add(name);
354 }
355 }
356 return matched.toArray(new String[matched.size()]);
357 }
358
359
360
361
362
363
364
365 @Deprecated
366 public String[] getTableNames(String regex) throws IOException {
367 return getTableNames(Pattern.compile(regex));
368 }
369
370
371
372
373
374
375 public TableName[] listTableNames() throws IOException {
376 return this.connection.listTableNames();
377 }
378
379
380
381
382
383
384
385
386 public HTableDescriptor getTableDescriptor(final TableName tableName)
387 throws TableNotFoundException, IOException {
388 return this.connection.getHTableDescriptor(tableName);
389 }
390
391 public HTableDescriptor getTableDescriptor(final byte[] tableName)
392 throws TableNotFoundException, IOException {
393 return getTableDescriptor(TableName.valueOf(tableName));
394 }
395
396 private long getPauseTime(int tries) {
397 int triesCount = tries;
398 if (triesCount >= HConstants.RETRY_BACKOFF.length) {
399 triesCount = HConstants.RETRY_BACKOFF.length - 1;
400 }
401 return this.pause * HConstants.RETRY_BACKOFF[triesCount];
402 }
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417 public void createTable(HTableDescriptor desc)
418 throws IOException {
419 createTable(desc, null);
420 }
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446 public void createTable(HTableDescriptor desc, byte [] startKey,
447 byte [] endKey, int numRegions)
448 throws IOException {
449 if(numRegions < 3) {
450 throw new IllegalArgumentException("Must create at least three regions");
451 } else if(Bytes.compareTo(startKey, endKey) >= 0) {
452 throw new IllegalArgumentException("Start key must be smaller than end key");
453 }
454 if (numRegions == 3) {
455 createTable(desc, new byte[][]{startKey, endKey});
456 return;
457 }
458 byte [][] splitKeys = Bytes.split(startKey, endKey, numRegions - 3);
459 if(splitKeys == null || splitKeys.length != numRegions - 1) {
460 throw new IllegalArgumentException("Unable to split key range into enough regions");
461 }
462 createTable(desc, splitKeys);
463 }
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482 public void createTable(final HTableDescriptor desc, byte [][] splitKeys)
483 throws IOException {
484 try {
485 createTableAsync(desc, splitKeys);
486 } catch (SocketTimeoutException ste) {
487 LOG.warn("Creating " + desc.getTableName() + " took too long", ste);
488 }
489 int numRegs = splitKeys == null ? 1 : splitKeys.length + 1;
490 int prevRegCount = 0;
491 boolean doneWithMetaScan = false;
492 for (int tries = 0; tries < this.numRetries * this.retryLongerMultiplier;
493 ++tries) {
494 if (!doneWithMetaScan) {
495
496 final AtomicInteger actualRegCount = new AtomicInteger(0);
497 MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
498 @Override
499 public boolean processRow(Result rowResult) throws IOException {
500 HRegionInfo info = HRegionInfo.getHRegionInfo(rowResult);
501 if (info == null) {
502 LOG.warn("No serialized HRegionInfo in " + rowResult);
503 return true;
504 }
505 if (!info.getTable().equals(desc.getTableName())) {
506 return false;
507 }
508 ServerName serverName = HRegionInfo.getServerName(rowResult);
509
510 if (!(info.isOffline() || info.isSplit()) && serverName != null
511 && serverName.getHostAndPort() != null) {
512 actualRegCount.incrementAndGet();
513 }
514 return true;
515 }
516 };
517 MetaScanner.metaScan(conf, connection, visitor, desc.getTableName());
518 if (actualRegCount.get() < numRegs) {
519 if (tries == this.numRetries * this.retryLongerMultiplier - 1) {
520 throw new RegionOfflineException("Only " + actualRegCount.get() +
521 " of " + numRegs + " regions are online; retries exhausted.");
522 }
523 try {
524 Thread.sleep(getPauseTime(tries));
525 } catch (InterruptedException e) {
526 throw new InterruptedIOException("Interrupted when opening" +
527 " regions; " + actualRegCount.get() + " of " + numRegs +
528 " regions processed so far");
529 }
530 if (actualRegCount.get() > prevRegCount) {
531 prevRegCount = actualRegCount.get();
532 tries = -1;
533 }
534 } else {
535 doneWithMetaScan = true;
536 tries = -1;
537 }
538 } else if (isTableEnabled(desc.getTableName())) {
539 return;
540 } else {
541 try {
542 Thread.sleep(getPauseTime(tries));
543 } catch (InterruptedException e) {
544 throw new InterruptedIOException("Interrupted when waiting" +
545 " for table to be enabled; meta scan was done");
546 }
547 }
548 }
549 throw new TableNotEnabledException(
550 "Retries exhausted while still waiting for table: "
551 + desc.getTableName() + " to be enabled");
552 }
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570 public void createTableAsync(
571 final HTableDescriptor desc, final byte [][] splitKeys)
572 throws IOException {
573 if(desc.getTableName() == null) {
574 throw new IllegalArgumentException("TableName cannot be null");
575 }
576 if(splitKeys != null && splitKeys.length > 0) {
577 Arrays.sort(splitKeys, Bytes.BYTES_COMPARATOR);
578
579 byte [] lastKey = null;
580 for(byte [] splitKey : splitKeys) {
581 if (Bytes.compareTo(splitKey, HConstants.EMPTY_BYTE_ARRAY) == 0) {
582 throw new IllegalArgumentException(
583 "Empty split key must not be passed in the split keys.");
584 }
585 if(lastKey != null && Bytes.equals(splitKey, lastKey)) {
586 throw new IllegalArgumentException("All split keys must be unique, " +
587 "found duplicate: " + Bytes.toStringBinary(splitKey) +
588 ", " + Bytes.toStringBinary(lastKey));
589 }
590 lastKey = splitKey;
591 }
592 }
593
594 executeCallable(new MasterCallable<Void>(getConnection()) {
595 @Override
596 public Void call() throws ServiceException {
597 CreateTableRequest request = RequestConverter.buildCreateTableRequest(desc, splitKeys);
598 master.createTable(null, request);
599 return null;
600 }
601 });
602 }
603
604 public void deleteTable(final String tableName) throws IOException {
605 deleteTable(TableName.valueOf(tableName));
606 }
607
608 public void deleteTable(final byte[] tableName) throws IOException {
609 deleteTable(TableName.valueOf(tableName));
610 }
611
612
613
614
615
616
617
618
619 public void deleteTable(final TableName tableName) throws IOException {
620 HRegionLocation firstMetaServer = getFirstMetaServerForTable(tableName);
621 boolean tableExists = true;
622
623 executeCallable(new MasterCallable<Void>(getConnection()) {
624 @Override
625 public Void call() throws ServiceException {
626 DeleteTableRequest req = RequestConverter.buildDeleteTableRequest(tableName);
627 master.deleteTable(null,req);
628 return null;
629 }
630 });
631
632
633 for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
634 try {
635
636 Scan scan = MetaReader.getScanForTableName(tableName);
637 scan.addColumn(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER);
638 ScanRequest request = RequestConverter.buildScanRequest(
639 firstMetaServer.getRegionInfo().getRegionName(), scan, 1, true);
640 Result[] values = null;
641
642 ClientService.BlockingInterface server = connection.getClient(firstMetaServer
643 .getServerName());
644 PayloadCarryingRpcController controller = new PayloadCarryingRpcController();
645 try {
646 controller.setPriority(tableName);
647 ScanResponse response = server.scan(controller, request);
648 values = ResponseConverter.getResults(controller.cellScanner(), response);
649 } catch (ServiceException se) {
650 throw ProtobufUtil.getRemoteException(se);
651 }
652
653
654
655 if (values == null || values.length == 0) {
656 tableExists = false;
657 GetTableDescriptorsResponse htds;
658 MasterKeepAliveConnection master = connection.getKeepAliveMasterService();
659 try {
660 GetTableDescriptorsRequest req =
661 RequestConverter.buildGetTableDescriptorsRequest(tableName);
662 htds = master.getTableDescriptors(null, req);
663 } catch (ServiceException se) {
664 throw ProtobufUtil.getRemoteException(se);
665 } finally {
666 master.close();
667 }
668 tableExists = !htds.getTableSchemaList().isEmpty();
669 if (!tableExists) {
670 break;
671 }
672 }
673 } catch (IOException ex) {
674 if(tries == numRetries - 1) {
675 if (ex instanceof RemoteException) {
676 throw ((RemoteException) ex).unwrapRemoteException();
677 } else {
678 throw ex;
679 }
680 }
681 }
682 try {
683 Thread.sleep(getPauseTime(tries));
684 } catch (InterruptedException e) {
685
686 }
687 }
688
689 if (tableExists) {
690 throw new IOException("Retries exhausted, it took too long to wait"+
691 " for the table " + tableName + " to be deleted.");
692 }
693
694 this.connection.clearRegionCache(tableName);
695 LOG.info("Deleted " + tableName);
696 }
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711 public HTableDescriptor[] deleteTables(String regex) throws IOException {
712 return deleteTables(Pattern.compile(regex));
713 }
714
715
716
717
718
719
720
721
722
723
724
725
726 public HTableDescriptor[] deleteTables(Pattern pattern) throws IOException {
727 List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
728 for (HTableDescriptor table : listTables(pattern)) {
729 try {
730 deleteTable(table.getTableName());
731 } catch (IOException ex) {
732 LOG.info("Failed to delete table " + table.getTableName(), ex);
733 failed.add(table);
734 }
735 }
736 return failed.toArray(new HTableDescriptor[failed.size()]);
737 }
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753 public void enableTable(final TableName tableName)
754 throws IOException {
755 enableTableAsync(tableName);
756
757
758 waitUntilTableIsEnabled(tableName);
759
760 LOG.info("Enabled table " + tableName);
761 }
762
763 public void enableTable(final byte[] tableName)
764 throws IOException {
765 enableTable(TableName.valueOf(tableName));
766 }
767
768 public void enableTable(final String tableName)
769 throws IOException {
770 enableTable(TableName.valueOf(tableName));
771 }
772
773
774
775
776
777
778
779
780 private void waitUntilTableIsEnabled(final TableName tableName) throws IOException {
781 boolean enabled = false;
782 long start = EnvironmentEdgeManager.currentTimeMillis();
783 for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
784 try {
785 enabled = isTableEnabled(tableName);
786 } catch (TableNotFoundException tnfe) {
787
788 enabled = false;
789 }
790 enabled = enabled && isTableAvailable(tableName);
791 if (enabled) {
792 break;
793 }
794 long sleep = getPauseTime(tries);
795 if (LOG.isDebugEnabled()) {
796 LOG.debug("Sleeping= " + sleep + "ms, waiting for all regions to be " +
797 "enabled in " + tableName);
798 }
799 try {
800 Thread.sleep(sleep);
801 } catch (InterruptedException e) {
802
803
804 throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
805 }
806 }
807 if (!enabled) {
808 long msec = EnvironmentEdgeManager.currentTimeMillis() - start;
809 throw new IOException("Table '" + tableName +
810 "' not yet enabled, after " + msec + "ms.");
811 }
812 }
813
814
815
816
817
818
819
820
821
822
823
824 public void enableTableAsync(final TableName tableName)
825 throws IOException {
826 TableName.isLegalFullyQualifiedTableName(tableName.getName());
827 executeCallable(new MasterCallable<Void>(getConnection()) {
828 @Override
829 public Void call() throws ServiceException {
830 LOG.info("Started enable of " + tableName);
831 EnableTableRequest req = RequestConverter.buildEnableTableRequest(tableName);
832 master.enableTable(null,req);
833 return null;
834 }
835 });
836 }
837
838 public void enableTableAsync(final byte[] tableName)
839 throws IOException {
840 enableTable(TableName.valueOf(tableName));
841 }
842
843 public void enableTableAsync(final String tableName)
844 throws IOException {
845 enableTableAsync(TableName.valueOf(tableName));
846 }
847
848
849
850
851
852
853
854
855
856
857
858
859
860 public HTableDescriptor[] enableTables(String regex) throws IOException {
861 return enableTables(Pattern.compile(regex));
862 }
863
864
865
866
867
868
869
870
871
872
873
874 public HTableDescriptor[] enableTables(Pattern pattern) throws IOException {
875 List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
876 for (HTableDescriptor table : listTables(pattern)) {
877 if (isTableDisabled(table.getTableName())) {
878 try {
879 enableTable(table.getTableName());
880 } catch (IOException ex) {
881 LOG.info("Failed to enable table " + table.getTableName(), ex);
882 failed.add(table);
883 }
884 }
885 }
886 return failed.toArray(new HTableDescriptor[failed.size()]);
887 }
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902 public void disableTableAsync(final TableName tableName) throws IOException {
903 TableName.isLegalFullyQualifiedTableName(tableName.getName());
904 executeCallable(new MasterCallable<Void>(getConnection()) {
905 @Override
906 public Void call() throws ServiceException {
907 LOG.info("Started disable of " + tableName);
908 DisableTableRequest req = RequestConverter.buildDisableTableRequest(tableName);
909 master.disableTable(null,req);
910 return null;
911 }
912 });
913 }
914
915 public void disableTableAsync(final byte[] tableName) throws IOException {
916 disableTableAsync(TableName.valueOf(tableName));
917 }
918
919 public void disableTableAsync(final String tableName) throws IOException {
920 disableTableAsync(TableName.valueOf(tableName));
921 }
922
923
924
925
926
927
928
929
930
931
932
933
934 public void disableTable(final TableName tableName)
935 throws IOException {
936 disableTableAsync(tableName);
937
938 boolean disabled = false;
939 for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
940 disabled = isTableDisabled(tableName);
941 if (disabled) {
942 break;
943 }
944 long sleep = getPauseTime(tries);
945 if (LOG.isDebugEnabled()) {
946 LOG.debug("Sleeping= " + sleep + "ms, waiting for all regions to be " +
947 "disabled in " + tableName);
948 }
949 try {
950 Thread.sleep(sleep);
951 } catch (InterruptedException e) {
952
953
954 throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
955 }
956 }
957 if (!disabled) {
958 throw new RegionException("Retries exhausted, it took too long to wait"+
959 " for the table " + tableName + " to be disabled.");
960 }
961 LOG.info("Disabled " + tableName);
962 }
963
964 public void disableTable(final byte[] tableName)
965 throws IOException {
966 disableTable(TableName.valueOf(tableName));
967 }
968
969 public void disableTable(final String tableName)
970 throws IOException {
971 disableTable(TableName.valueOf(tableName));
972 }
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987 public HTableDescriptor[] disableTables(String regex) throws IOException {
988 return disableTables(Pattern.compile(regex));
989 }
990
991
992
993
994
995
996
997
998
999
1000
1001
1002 public HTableDescriptor[] disableTables(Pattern pattern) throws IOException {
1003 List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
1004 for (HTableDescriptor table : listTables(pattern)) {
1005 if (isTableEnabled(table.getTableName())) {
1006 try {
1007 disableTable(table.getTableName());
1008 } catch (IOException ex) {
1009 LOG.info("Failed to disable table " + table.getTableName(), ex);
1010 failed.add(table);
1011 }
1012 }
1013 }
1014 return failed.toArray(new HTableDescriptor[failed.size()]);
1015 }
1016
1017
1018
1019
1020
1021 private void checkTableExistence(TableName tableName) throws IOException {
1022 if (!tableExists(tableName)) {
1023 throw new TableNotFoundException(tableName);
1024 }
1025 }
1026
1027
1028
1029
1030
1031
1032 public boolean isTableEnabled(TableName tableName) throws IOException {
1033 checkTableExistence(tableName);
1034 return connection.isTableEnabled(tableName);
1035 }
1036
1037 public boolean isTableEnabled(byte[] tableName) throws IOException {
1038 return isTableEnabled(TableName.valueOf(tableName));
1039 }
1040
1041 public boolean isTableEnabled(String tableName) throws IOException {
1042 return isTableEnabled(TableName.valueOf(tableName));
1043 }
1044
1045
1046
1047
1048
1049
1050
1051
1052 public boolean isTableDisabled(TableName tableName) throws IOException {
1053 checkTableExistence(tableName);
1054 return connection.isTableDisabled(tableName);
1055 }
1056
1057 public boolean isTableDisabled(byte[] tableName) throws IOException {
1058 return isTableDisabled(TableName.valueOf(tableName));
1059 }
1060
1061 public boolean isTableDisabled(String tableName) throws IOException {
1062 return isTableDisabled(TableName.valueOf(tableName));
1063 }
1064
1065
1066
1067
1068
1069
1070 public boolean isTableAvailable(TableName tableName) throws IOException {
1071 return connection.isTableAvailable(tableName);
1072 }
1073
1074 public boolean isTableAvailable(byte[] tableName) throws IOException {
1075 return isTableAvailable(TableName.valueOf(tableName));
1076 }
1077
1078 public boolean isTableAvailable(String tableName) throws IOException {
1079 return isTableAvailable(TableName.valueOf(tableName));
1080 }
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094 public boolean isTableAvailable(TableName tableName,
1095 byte[][] splitKeys) throws IOException {
1096 return connection.isTableAvailable(tableName, splitKeys);
1097 }
1098
1099 public boolean isTableAvailable(byte[] tableName,
1100 byte[][] splitKeys) throws IOException {
1101 return isTableAvailable(TableName.valueOf(tableName), splitKeys);
1102 }
1103
1104 public boolean isTableAvailable(String tableName,
1105 byte[][] splitKeys) throws IOException {
1106 return isTableAvailable(TableName.valueOf(tableName), splitKeys);
1107 }
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120 public Pair<Integer, Integer> getAlterStatus(final TableName tableName)
1121 throws IOException {
1122 return executeCallable(new MasterCallable<Pair<Integer, Integer>>(getConnection()) {
1123 @Override
1124 public Pair<Integer, Integer> call() throws ServiceException {
1125 GetSchemaAlterStatusRequest req = RequestConverter
1126 .buildGetSchemaAlterStatusRequest(tableName);
1127 GetSchemaAlterStatusResponse ret = master.getSchemaAlterStatus(null, req);
1128 Pair<Integer, Integer> pair = new Pair<Integer, Integer>(Integer.valueOf(ret
1129 .getYetToUpdateRegions()), Integer.valueOf(ret.getTotalRegions()));
1130 return pair;
1131 }
1132 });
1133 }
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147 public Pair<Integer, Integer> getAlterStatus(final byte[] tableName)
1148 throws IOException {
1149 return getAlterStatus(TableName.valueOf(tableName));
1150 }
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160 public void addColumn(final byte[] tableName, HColumnDescriptor column)
1161 throws IOException {
1162 addColumn(TableName.valueOf(tableName), column);
1163 }
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174 public void addColumn(final String tableName, HColumnDescriptor column)
1175 throws IOException {
1176 addColumn(TableName.valueOf(tableName), column);
1177 }
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187 public void addColumn(final TableName tableName, final HColumnDescriptor column)
1188 throws IOException {
1189 executeCallable(new MasterCallable<Void>(getConnection()) {
1190 @Override
1191 public Void call() throws ServiceException {
1192 AddColumnRequest req = RequestConverter.buildAddColumnRequest(tableName, column);
1193 master.addColumn(null,req);
1194 return null;
1195 }
1196 });
1197 }
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207 public void deleteColumn(final byte[] tableName, final String columnName)
1208 throws IOException {
1209 deleteColumn(TableName.valueOf(tableName), Bytes.toBytes(columnName));
1210 }
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220 public void deleteColumn(final String tableName, final String columnName)
1221 throws IOException {
1222 deleteColumn(TableName.valueOf(tableName), Bytes.toBytes(columnName));
1223 }
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233 public void deleteColumn(final TableName tableName, final byte [] columnName)
1234 throws IOException {
1235 executeCallable(new MasterCallable<Void>(getConnection()) {
1236 @Override
1237 public Void call() throws ServiceException {
1238 DeleteColumnRequest req = RequestConverter.buildDeleteColumnRequest(tableName, columnName);
1239 master.deleteColumn(null,req);
1240 return null;
1241 }
1242 });
1243 }
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253 public void modifyColumn(final String tableName, HColumnDescriptor descriptor)
1254 throws IOException {
1255 modifyColumn(TableName.valueOf(tableName), descriptor);
1256 }
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266 public void modifyColumn(final byte[] tableName, HColumnDescriptor descriptor)
1267 throws IOException {
1268 modifyColumn(TableName.valueOf(tableName), descriptor);
1269 }
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281 public void modifyColumn(final TableName tableName, final HColumnDescriptor descriptor)
1282 throws IOException {
1283 executeCallable(new MasterCallable<Void>(getConnection()) {
1284 @Override
1285 public Void call() throws ServiceException {
1286 ModifyColumnRequest req = RequestConverter.buildModifyColumnRequest(tableName, descriptor);
1287 master.modifyColumn(null,req);
1288 return null;
1289 }
1290 });
1291 }
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301 public void closeRegion(final String regionname, final String serverName)
1302 throws IOException {
1303 closeRegion(Bytes.toBytes(regionname), serverName);
1304 }
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316 public void closeRegion(final byte [] regionname, final String serverName)
1317 throws IOException {
1318 CatalogTracker ct = getCatalogTracker();
1319 try {
1320 if (serverName != null) {
1321 Pair<HRegionInfo, ServerName> pair = MetaReader.getRegion(ct, regionname);
1322 if (pair == null || pair.getFirst() == null) {
1323 throw new UnknownRegionException(Bytes.toStringBinary(regionname));
1324 } else {
1325 closeRegion(ServerName.valueOf(serverName), pair.getFirst());
1326 }
1327 } else {
1328 Pair<HRegionInfo, ServerName> pair = MetaReader.getRegion(ct, regionname);
1329 if (pair == null) {
1330 throw new UnknownRegionException(Bytes.toStringBinary(regionname));
1331 } else if (pair.getSecond() == null) {
1332 throw new NoServerForRegionException(Bytes.toStringBinary(regionname));
1333 } else {
1334 closeRegion(pair.getSecond(), pair.getFirst());
1335 }
1336 }
1337 } finally {
1338 cleanupCatalogTracker(ct);
1339 }
1340 }
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363 public boolean closeRegionWithEncodedRegionName(final String encodedRegionName,
1364 final String serverName) throws IOException {
1365 if (null == serverName || ("").equals(serverName.trim())) {
1366 throw new IllegalArgumentException(
1367 "The servername cannot be null or empty.");
1368 }
1369 ServerName sn = ServerName.valueOf(serverName);
1370 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1371
1372 CloseRegionRequest request =
1373 RequestConverter.buildCloseRegionRequest(encodedRegionName, false);
1374 try {
1375 CloseRegionResponse response = admin.closeRegion(null, request);
1376 boolean isRegionClosed = response.getClosed();
1377 if (false == isRegionClosed) {
1378 LOG.error("Not able to close the region " + encodedRegionName + ".");
1379 }
1380 return isRegionClosed;
1381 } catch (ServiceException se) {
1382 throw ProtobufUtil.getRemoteException(se);
1383 }
1384 }
1385
1386
1387
1388
1389
1390
1391
1392
1393 public void closeRegion(final ServerName sn, final HRegionInfo hri)
1394 throws IOException {
1395 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1396
1397 ProtobufUtil.closeRegion(admin, hri.getRegionName(), false);
1398 }
1399
1400
1401
1402
1403 public List<HRegionInfo> getOnlineRegions(
1404 final ServerName sn) throws IOException {
1405 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1406 return ProtobufUtil.getOnlineRegions(admin);
1407 }
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417 public void flush(final String tableNameOrRegionName)
1418 throws IOException, InterruptedException {
1419 flush(Bytes.toBytes(tableNameOrRegionName));
1420 }
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430 public void flush(final byte[] tableNameOrRegionName)
1431 throws IOException, InterruptedException {
1432 CatalogTracker ct = getCatalogTracker();
1433 try {
1434 Pair<HRegionInfo, ServerName> regionServerPair
1435 = getRegion(tableNameOrRegionName, ct);
1436 if (regionServerPair != null) {
1437 if (regionServerPair.getSecond() == null) {
1438 throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
1439 } else {
1440 flush(regionServerPair.getSecond(), regionServerPair.getFirst());
1441 }
1442 } else {
1443 final TableName tableName = checkTableExists(
1444 TableName.valueOf(tableNameOrRegionName), ct);
1445 List<Pair<HRegionInfo, ServerName>> pairs =
1446 MetaReader.getTableRegionsAndLocations(ct,
1447 tableName);
1448 for (Pair<HRegionInfo, ServerName> pair: pairs) {
1449 if (pair.getFirst().isOffline()) continue;
1450 if (pair.getSecond() == null) continue;
1451 try {
1452 flush(pair.getSecond(), pair.getFirst());
1453 } catch (NotServingRegionException e) {
1454 if (LOG.isDebugEnabled()) {
1455 LOG.debug("Trying to flush " + pair.getFirst() + ": " +
1456 StringUtils.stringifyException(e));
1457 }
1458 }
1459 }
1460 }
1461 } finally {
1462 cleanupCatalogTracker(ct);
1463 }
1464 }
1465
1466 private void flush(final ServerName sn, final HRegionInfo hri)
1467 throws IOException {
1468 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1469 FlushRegionRequest request =
1470 RequestConverter.buildFlushRegionRequest(hri.getRegionName());
1471 try {
1472 admin.flushRegion(null, request);
1473 } catch (ServiceException se) {
1474 throw ProtobufUtil.getRemoteException(se);
1475 }
1476 }
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486 public void compact(final String tableNameOrRegionName)
1487 throws IOException, InterruptedException {
1488 compact(Bytes.toBytes(tableNameOrRegionName));
1489 }
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499 public void compact(final byte[] tableNameOrRegionName)
1500 throws IOException, InterruptedException {
1501 compact(tableNameOrRegionName, null, false);
1502 }
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513 public void compact(String tableOrRegionName, String columnFamily)
1514 throws IOException, InterruptedException {
1515 compact(Bytes.toBytes(tableOrRegionName), Bytes.toBytes(columnFamily));
1516 }
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527 public void compact(final byte[] tableNameOrRegionName, final byte[] columnFamily)
1528 throws IOException, InterruptedException {
1529 compact(tableNameOrRegionName, columnFamily, false);
1530 }
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540 public void majorCompact(final String tableNameOrRegionName)
1541 throws IOException, InterruptedException {
1542 majorCompact(Bytes.toBytes(tableNameOrRegionName));
1543 }
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553 public void majorCompact(final byte[] tableNameOrRegionName)
1554 throws IOException, InterruptedException {
1555 compact(tableNameOrRegionName, null, true);
1556 }
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567 public void majorCompact(final String tableNameOrRegionName,
1568 final String columnFamily) throws IOException, InterruptedException {
1569 majorCompact(Bytes.toBytes(tableNameOrRegionName),
1570 Bytes.toBytes(columnFamily));
1571 }
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582 public void majorCompact(final byte[] tableNameOrRegionName,
1583 final byte[] columnFamily) throws IOException, InterruptedException {
1584 compact(tableNameOrRegionName, columnFamily, true);
1585 }
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597 private void compact(final byte[] tableNameOrRegionName,
1598 final byte[] columnFamily,final boolean major)
1599 throws IOException, InterruptedException {
1600 CatalogTracker ct = getCatalogTracker();
1601 try {
1602 Pair<HRegionInfo, ServerName> regionServerPair
1603 = getRegion(tableNameOrRegionName, ct);
1604 if (regionServerPair != null) {
1605 if (regionServerPair.getSecond() == null) {
1606 throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
1607 } else {
1608 compact(regionServerPair.getSecond(), regionServerPair.getFirst(), major, columnFamily);
1609 }
1610 } else {
1611 final TableName tableName =
1612 checkTableExists(TableName.valueOf(tableNameOrRegionName), ct);
1613 List<Pair<HRegionInfo, ServerName>> pairs =
1614 MetaReader.getTableRegionsAndLocations(ct,
1615 tableName);
1616 for (Pair<HRegionInfo, ServerName> pair: pairs) {
1617 if (pair.getFirst().isOffline()) continue;
1618 if (pair.getSecond() == null) continue;
1619 try {
1620 compact(pair.getSecond(), pair.getFirst(), major, columnFamily);
1621 } catch (NotServingRegionException e) {
1622 if (LOG.isDebugEnabled()) {
1623 LOG.debug("Trying to" + (major ? " major" : "") + " compact " +
1624 pair.getFirst() + ": " +
1625 StringUtils.stringifyException(e));
1626 }
1627 }
1628 }
1629 }
1630 } finally {
1631 cleanupCatalogTracker(ct);
1632 }
1633 }
1634
1635 private void compact(final ServerName sn, final HRegionInfo hri,
1636 final boolean major, final byte [] family)
1637 throws IOException {
1638 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1639 CompactRegionRequest request =
1640 RequestConverter.buildCompactRegionRequest(hri.getRegionName(), major, family);
1641 try {
1642 admin.compactRegion(null, request);
1643 } catch (ServiceException se) {
1644 throw ProtobufUtil.getRemoteException(se);
1645 }
1646 }
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663 public void move(final byte [] encodedRegionName, final byte [] destServerName)
1664 throws HBaseIOException, MasterNotRunningException, ZooKeeperConnectionException {
1665 MasterKeepAliveConnection stub = connection.getKeepAliveMasterService();
1666 try {
1667 MoveRegionRequest request =
1668 RequestConverter.buildMoveRegionRequest(encodedRegionName, destServerName);
1669 stub.moveRegion(null,request);
1670 } catch (ServiceException se) {
1671 IOException ioe = ProtobufUtil.getRemoteException(se);
1672 if (ioe instanceof HBaseIOException) {
1673 throw (HBaseIOException)ioe;
1674 }
1675 LOG.error("Unexpected exception: " + se + " from calling HMaster.moveRegion");
1676 } catch (DeserializationException de) {
1677 LOG.error("Could not parse destination server name: " + de);
1678 } finally {
1679 stub.close();
1680 }
1681 }
1682
1683
1684
1685
1686
1687
1688
1689
1690 public void assign(final byte[] regionName) throws MasterNotRunningException,
1691 ZooKeeperConnectionException, IOException {
1692 final byte[] toBeAssigned = getRegionName(regionName);
1693 executeCallable(new MasterCallable<Void>(getConnection()) {
1694 @Override
1695 public Void call() throws ServiceException {
1696 AssignRegionRequest request =
1697 RequestConverter.buildAssignRegionRequest(toBeAssigned);
1698 master.assignRegion(null,request);
1699 return null;
1700 }
1701 });
1702 }
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718 public void unassign(final byte [] regionName, final boolean force)
1719 throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
1720 final byte[] toBeUnassigned = getRegionName(regionName);
1721 executeCallable(new MasterCallable<Void>(getConnection()) {
1722 @Override
1723 public Void call() throws ServiceException {
1724 UnassignRegionRequest request =
1725 RequestConverter.buildUnassignRegionRequest(toBeUnassigned, force);
1726 master.unassignRegion(null,request);
1727 return null;
1728 }
1729 });
1730 }
1731
1732
1733
1734
1735 public void offline(final byte [] regionName)
1736 throws IOException {
1737 MasterKeepAliveConnection master = connection.getKeepAliveMasterService();
1738 try {
1739 master.offlineRegion(null,RequestConverter.buildOfflineRegionRequest(regionName));
1740 } catch (ServiceException se) {
1741 throw ProtobufUtil.getRemoteException(se);
1742 } finally {
1743 master.close();
1744 }
1745 }
1746
1747
1748
1749
1750
1751
1752
1753 public boolean setBalancerRunning(final boolean on, final boolean synchronous)
1754 throws MasterNotRunningException, ZooKeeperConnectionException {
1755 MasterKeepAliveConnection stub = connection.getKeepAliveMasterService();
1756 try {
1757 SetBalancerRunningRequest req =
1758 RequestConverter.buildSetBalancerRunningRequest(on, synchronous);
1759 return stub.setBalancerRunning(null, req).getPrevBalanceValue();
1760 } catch (ServiceException se) {
1761 IOException ioe = ProtobufUtil.getRemoteException(se);
1762 if (ioe instanceof MasterNotRunningException) {
1763 throw (MasterNotRunningException)ioe;
1764 }
1765 if (ioe instanceof ZooKeeperConnectionException) {
1766 throw (ZooKeeperConnectionException)ioe;
1767 }
1768
1769
1770
1771 throw new MasterNotRunningException("Unexpected exception when calling balanceSwitch",se);
1772 } finally {
1773 stub.close();
1774 }
1775 }
1776
1777
1778
1779
1780
1781
1782
1783 public boolean balancer()
1784 throws MasterNotRunningException, ZooKeeperConnectionException, ServiceException {
1785 MasterKeepAliveConnection stub = connection.getKeepAliveMasterService();
1786 try {
1787 return stub.balance(null,RequestConverter.buildBalanceRequest()).getBalancerRan();
1788 } finally {
1789 stub.close();
1790 }
1791 }
1792
1793
1794
1795
1796
1797
1798
1799
1800 public boolean enableCatalogJanitor(boolean enable)
1801 throws ServiceException, MasterNotRunningException {
1802 MasterKeepAliveConnection stub = connection.getKeepAliveMasterService();
1803 try {
1804 return stub.enableCatalogJanitor(null,
1805 RequestConverter.buildEnableCatalogJanitorRequest(enable)).getPrevValue();
1806 } finally {
1807 stub.close();
1808 }
1809 }
1810
1811
1812
1813
1814
1815
1816
1817 public int runCatalogScan() throws ServiceException, MasterNotRunningException {
1818 MasterKeepAliveConnection stub = connection.getKeepAliveMasterService();
1819 try {
1820 return stub.runCatalogScan(null,
1821 RequestConverter.buildCatalogScanRequest()).getScanResult();
1822 } finally {
1823 stub.close();
1824 }
1825 }
1826
1827
1828
1829
1830
1831
1832 public boolean isCatalogJanitorEnabled() throws ServiceException, MasterNotRunningException {
1833 MasterKeepAliveConnection stub = connection.getKeepAliveMasterService();
1834 try {
1835 return stub.isCatalogJanitorEnabled(null,
1836 RequestConverter.buildIsCatalogJanitorEnabledRequest()).getValue();
1837 } finally {
1838 stub.close();
1839 }
1840 }
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850 public void mergeRegions(final byte[] encodedNameOfRegionA,
1851 final byte[] encodedNameOfRegionB, final boolean forcible)
1852 throws IOException {
1853 MasterKeepAliveConnection master = connection
1854 .getKeepAliveMasterService();
1855 try {
1856 DispatchMergingRegionsRequest request = RequestConverter
1857 .buildDispatchMergingRegionsRequest(encodedNameOfRegionA,
1858 encodedNameOfRegionB, forcible);
1859 master.dispatchMergingRegions(null, request);
1860 } catch (ServiceException se) {
1861 IOException ioe = ProtobufUtil.getRemoteException(se);
1862 if (ioe instanceof UnknownRegionException) {
1863 throw (UnknownRegionException) ioe;
1864 }
1865 if (ioe instanceof MergeRegionException) {
1866 throw (MergeRegionException) ioe;
1867 }
1868 LOG.error("Unexpected exception: " + se
1869 + " from calling HMaster.dispatchMergingRegions");
1870 } catch (DeserializationException de) {
1871 LOG.error("Could not parse destination server name: " + de);
1872 } finally {
1873 master.close();
1874 }
1875 }
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885 public void split(final String tableNameOrRegionName)
1886 throws IOException, InterruptedException {
1887 split(Bytes.toBytes(tableNameOrRegionName));
1888 }
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898 public void split(final byte[] tableNameOrRegionName)
1899 throws IOException, InterruptedException {
1900 split(tableNameOrRegionName, null);
1901 }
1902
1903 public void split(final String tableNameOrRegionName,
1904 final String splitPoint) throws IOException, InterruptedException {
1905 split(Bytes.toBytes(tableNameOrRegionName), Bytes.toBytes(splitPoint));
1906 }
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917 public void split(final byte[] tableNameOrRegionName,
1918 final byte [] splitPoint) throws IOException, InterruptedException {
1919 CatalogTracker ct = getCatalogTracker();
1920 try {
1921 Pair<HRegionInfo, ServerName> regionServerPair
1922 = getRegion(tableNameOrRegionName, ct);
1923 if (regionServerPair != null) {
1924 if (regionServerPair.getSecond() == null) {
1925 throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
1926 } else {
1927 split(regionServerPair.getSecond(), regionServerPair.getFirst(), splitPoint);
1928 }
1929 } else {
1930 final TableName tableName =
1931 checkTableExists(TableName.valueOf(tableNameOrRegionName), ct);
1932 List<Pair<HRegionInfo, ServerName>> pairs =
1933 MetaReader.getTableRegionsAndLocations(ct,
1934 tableName);
1935 for (Pair<HRegionInfo, ServerName> pair: pairs) {
1936
1937 if (pair.getSecond() == null) continue;
1938 HRegionInfo r = pair.getFirst();
1939
1940 if (r.isSplitParent()) continue;
1941
1942 if (splitPoint != null && !r.containsRow(splitPoint)) continue;
1943
1944 split(pair.getSecond(), pair.getFirst(), splitPoint);
1945 }
1946 }
1947 } finally {
1948 cleanupCatalogTracker(ct);
1949 }
1950 }
1951
1952 private void split(final ServerName sn, final HRegionInfo hri,
1953 byte[] splitPoint) throws IOException {
1954 if (hri.getStartKey() != null && splitPoint != null &&
1955 Bytes.compareTo(hri.getStartKey(), splitPoint) == 0) {
1956 throw new IOException("should not give a splitkey which equals to startkey!");
1957 }
1958 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1959 ProtobufUtil.split(admin, hri, splitPoint);
1960 }
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971 public void modifyTable(final TableName tableName, final HTableDescriptor htd)
1972 throws IOException {
1973 if (!tableName.equals(htd.getTableName())) {
1974 throw new IllegalArgumentException("the specified table name '" + tableName +
1975 "' doesn't match with the HTD one: " + htd.getTableName());
1976 }
1977
1978 executeCallable(new MasterCallable<Void>(getConnection()) {
1979 @Override
1980 public Void call() throws ServiceException {
1981 ModifyTableRequest request = RequestConverter.buildModifyTableRequest(tableName, htd);
1982 master.modifyTable(null, request);
1983 return null;
1984 }
1985 });
1986 }
1987
1988 public void modifyTable(final byte[] tableName, final HTableDescriptor htd)
1989 throws IOException {
1990 modifyTable(TableName.valueOf(tableName), htd);
1991 }
1992
1993 public void modifyTable(final String tableName, final HTableDescriptor htd)
1994 throws IOException {
1995 modifyTable(TableName.valueOf(tableName), htd);
1996 }
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007 Pair<HRegionInfo, ServerName> getRegion(final byte[] tableNameOrRegionName,
2008 final CatalogTracker ct) throws IOException {
2009 if (tableNameOrRegionName == null) {
2010 throw new IllegalArgumentException("Pass a table name or region name");
2011 }
2012 Pair<HRegionInfo, ServerName> pair = MetaReader.getRegion(ct, tableNameOrRegionName);
2013 if (pair == null) {
2014 final AtomicReference<Pair<HRegionInfo, ServerName>> result =
2015 new AtomicReference<Pair<HRegionInfo, ServerName>>(null);
2016 final String encodedName = Bytes.toString(tableNameOrRegionName);
2017 MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
2018 @Override
2019 public boolean processRow(Result data) throws IOException {
2020 HRegionInfo info = HRegionInfo.getHRegionInfo(data);
2021 if (info == null) {
2022 LOG.warn("No serialized HRegionInfo in " + data);
2023 return true;
2024 }
2025 if (!encodedName.equals(info.getEncodedName())) return true;
2026 ServerName sn = HRegionInfo.getServerName(data);
2027 result.set(new Pair<HRegionInfo, ServerName>(info, sn));
2028 return false;
2029 }
2030 };
2031
2032 MetaScanner.metaScan(conf, connection, visitor, null);
2033 pair = result.get();
2034 }
2035 return pair;
2036 }
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046 private byte[] getRegionName(
2047 final byte[] regionNameOrEncodedRegionName) throws IOException {
2048 if (Bytes.equals(regionNameOrEncodedRegionName,
2049 HRegionInfo.FIRST_META_REGIONINFO.getRegionName())
2050 || Bytes.equals(regionNameOrEncodedRegionName,
2051 HRegionInfo.FIRST_META_REGIONINFO.getEncodedNameAsBytes())) {
2052 return HRegionInfo.FIRST_META_REGIONINFO.getRegionName();
2053 }
2054 CatalogTracker ct = getCatalogTracker();
2055 byte[] tmp = regionNameOrEncodedRegionName;
2056 try {
2057 Pair<HRegionInfo, ServerName> regionServerPair
2058 = getRegion(regionNameOrEncodedRegionName, ct);
2059 if (regionServerPair != null && regionServerPair.getFirst() != null) {
2060 tmp = regionServerPair.getFirst().getRegionName();
2061 }
2062 } finally {
2063 cleanupCatalogTracker(ct);
2064 }
2065 return tmp;
2066 }
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077 private TableName checkTableExists(
2078 final TableName tableName, CatalogTracker ct)
2079 throws IOException {
2080 if (!MetaReader.tableExists(ct, tableName)) {
2081 throw new TableNotFoundException(tableName);
2082 }
2083 return tableName;
2084 }
2085
2086
2087
2088
2089
2090 public synchronized void shutdown() throws IOException {
2091 executeCallable(new MasterCallable<Void>(getConnection()) {
2092 @Override
2093 public Void call() throws ServiceException {
2094 master.shutdown(null,ShutdownRequest.newBuilder().build());
2095 return null;
2096 }
2097 });
2098 }
2099
2100
2101
2102
2103
2104
2105
2106 public synchronized void stopMaster() throws IOException {
2107 executeCallable(new MasterCallable<Void>(getConnection()) {
2108 @Override
2109 public Void call() throws ServiceException {
2110 master.stopMaster(null,StopMasterRequest.newBuilder().build());
2111 return null;
2112 }
2113 });
2114 }
2115
2116
2117
2118
2119
2120
2121
2122 public synchronized void stopRegionServer(final String hostnamePort)
2123 throws IOException {
2124 String hostname = Addressing.parseHostname(hostnamePort);
2125 int port = Addressing.parsePort(hostnamePort);
2126 AdminService.BlockingInterface admin =
2127 this.connection.getAdmin(ServerName.valueOf(hostname, port, 0));
2128 StopServerRequest request = RequestConverter.buildStopServerRequest(
2129 "Called by admin client " + this.connection.toString());
2130 try {
2131 admin.stopServer(null, request);
2132 } catch (ServiceException se) {
2133 throw ProtobufUtil.getRemoteException(se);
2134 }
2135 }
2136
2137
2138
2139
2140
2141
2142 public ClusterStatus getClusterStatus() throws IOException {
2143 return executeCallable(new MasterCallable<ClusterStatus>(getConnection()) {
2144 @Override
2145 public ClusterStatus call() throws ServiceException {
2146 GetClusterStatusRequest req = RequestConverter.buildGetClusterStatusRequest();
2147 return ClusterStatus.convert(master.getClusterStatus(null,req).getClusterStatus());
2148 }
2149 });
2150 }
2151
2152 private HRegionLocation getFirstMetaServerForTable(final TableName tableName)
2153 throws IOException {
2154 return connection.locateRegion(TableName.META_TABLE_NAME,
2155 HRegionInfo.createRegionName(tableName, null, HConstants.NINES, false));
2156 }
2157
2158
2159
2160
2161 public Configuration getConfiguration() {
2162 return this.conf;
2163 }
2164
2165
2166
2167
2168
2169
2170 public void createNamespace(final NamespaceDescriptor descriptor) throws IOException {
2171 executeCallable(new MasterCallable<Void>(getConnection()) {
2172 @Override
2173 public Void call() throws Exception {
2174 master.createNamespace(null,
2175 CreateNamespaceRequest.newBuilder()
2176 .setNamespaceDescriptor(ProtobufUtil
2177 .toProtoNamespaceDescriptor(descriptor)).build());
2178 return null;
2179 }
2180 });
2181 }
2182
2183
2184
2185
2186
2187
2188 public void modifyNamespace(final NamespaceDescriptor descriptor) throws IOException {
2189 executeCallable(new MasterCallable<Void>(getConnection()) {
2190 @Override
2191 public Void call() throws Exception {
2192 master.modifyNamespace(null, ModifyNamespaceRequest.newBuilder().
2193 setNamespaceDescriptor(ProtobufUtil.toProtoNamespaceDescriptor(descriptor)).build());
2194 return null;
2195 }
2196 });
2197 }
2198
2199
2200
2201
2202
2203
2204 public void deleteNamespace(final String name) throws IOException {
2205 executeCallable(new MasterCallable<Void>(getConnection()) {
2206 @Override
2207 public Void call() throws Exception {
2208 master.deleteNamespace(null, DeleteNamespaceRequest.newBuilder().
2209 setNamespaceName(name).build());
2210 return null;
2211 }
2212 });
2213 }
2214
2215
2216
2217
2218
2219
2220
2221 public NamespaceDescriptor getNamespaceDescriptor(final String name) throws IOException {
2222 return
2223 executeCallable(new MasterCallable<NamespaceDescriptor>(getConnection()) {
2224 @Override
2225 public NamespaceDescriptor call() throws Exception {
2226 return ProtobufUtil.toNamespaceDescriptor(
2227 master.getNamespaceDescriptor(null, GetNamespaceDescriptorRequest.newBuilder().
2228 setNamespaceName(name).build()).getNamespaceDescriptor());
2229 }
2230 });
2231 }
2232
2233
2234
2235
2236
2237
2238 public NamespaceDescriptor[] listNamespaceDescriptors() throws IOException {
2239 return
2240 executeCallable(new MasterCallable<NamespaceDescriptor[]>(getConnection()) {
2241 @Override
2242 public NamespaceDescriptor[] call() throws Exception {
2243 List<HBaseProtos.NamespaceDescriptor> list =
2244 master.listNamespaceDescriptors(null, ListNamespaceDescriptorsRequest.newBuilder().
2245 build()).getNamespaceDescriptorList();
2246 NamespaceDescriptor[] res = new NamespaceDescriptor[list.size()];
2247 for(int i = 0; i < list.size(); i++) {
2248 res[i] = ProtobufUtil.toNamespaceDescriptor(list.get(i));
2249 }
2250 return res;
2251 }
2252 });
2253 }
2254
2255
2256
2257
2258
2259
2260
2261 public HTableDescriptor[] listTableDescriptorsByNamespace(final String name) throws IOException {
2262 return
2263 executeCallable(new MasterCallable<HTableDescriptor[]>(getConnection()) {
2264 @Override
2265 public HTableDescriptor[] call() throws Exception {
2266 List<TableSchema> list =
2267 master.listTableDescriptorsByNamespace(null, ListTableDescriptorsByNamespaceRequest.
2268 newBuilder().setNamespaceName(name).build()).getTableSchemaList();
2269 HTableDescriptor[] res = new HTableDescriptor[list.size()];
2270 for(int i=0; i < list.size(); i++) {
2271
2272 res[i] = HTableDescriptor.convert(list.get(i));
2273 }
2274 return res;
2275 }
2276 });
2277 }
2278
2279
2280
2281
2282
2283
2284
2285 public TableName[] listTableNamesByNamespace(final String name) throws IOException {
2286 return
2287 executeCallable(new MasterCallable<TableName[]>(getConnection()) {
2288 @Override
2289 public TableName[] call() throws Exception {
2290 List<HBaseProtos.TableName> tableNames =
2291 master.listTableNamesByNamespace(null, ListTableNamesByNamespaceRequest.
2292 newBuilder().setNamespaceName(name).build())
2293 .getTableNameList();
2294 TableName[] result = new TableName[tableNames.size()];
2295 for (int i = 0; i < tableNames.size(); i++) {
2296 result[i] = ProtobufUtil.toTableName(tableNames.get(i));
2297 }
2298 return result;
2299 }
2300 });
2301 }
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311 public static void checkHBaseAvailable(Configuration conf)
2312 throws MasterNotRunningException, ZooKeeperConnectionException, ServiceException, IOException {
2313 Configuration copyOfConf = HBaseConfiguration.create(conf);
2314
2315
2316 copyOfConf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);
2317 copyOfConf.setInt("zookeeper.recovery.retry", 0);
2318
2319 HConnectionManager.HConnectionImplementation connection
2320 = (HConnectionManager.HConnectionImplementation)
2321 HConnectionManager.getConnection(copyOfConf);
2322
2323 try {
2324
2325
2326
2327 ZooKeeperKeepAliveConnection zkw = null;
2328 try {
2329 zkw = connection.getKeepAliveZooKeeperWatcher();
2330 zkw.getRecoverableZooKeeper().getZooKeeper().exists(
2331 zkw.baseZNode, false);
2332
2333 } catch (IOException e) {
2334 throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
2335 } catch (InterruptedException e) {
2336 throw (InterruptedIOException)
2337 new InterruptedIOException("Can't connect to ZooKeeper").initCause(e);
2338 } catch (KeeperException e) {
2339 throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
2340 } finally {
2341 if (zkw != null) {
2342 zkw.close();
2343 }
2344 }
2345
2346
2347 connection.isMasterRunning();
2348
2349 } finally {
2350 connection.close();
2351 }
2352 }
2353
2354
2355
2356
2357
2358
2359
2360
2361 public List<HRegionInfo> getTableRegions(final TableName tableName)
2362 throws IOException {
2363 CatalogTracker ct = getCatalogTracker();
2364 List<HRegionInfo> Regions = null;
2365 try {
2366 Regions = MetaReader.getTableRegions(ct, tableName, true);
2367 } finally {
2368 cleanupCatalogTracker(ct);
2369 }
2370 return Regions;
2371 }
2372
2373 public List<HRegionInfo> getTableRegions(final byte[] tableName)
2374 throws IOException {
2375 return getTableRegions(TableName.valueOf(tableName));
2376 }
2377
2378 @Override
2379 public synchronized void close() throws IOException {
2380 if (cleanupConnectionOnClose && this.connection != null && !this.closed) {
2381 this.connection.close();
2382 this.closed = true;
2383 }
2384 }
2385
2386
2387
2388
2389
2390
2391
2392 public HTableDescriptor[] getTableDescriptorsByTableName(List<TableName> tableNames)
2393 throws IOException {
2394 return this.connection.getHTableDescriptorsByTableName(tableNames);
2395 }
2396
2397
2398
2399
2400
2401
2402
2403 public HTableDescriptor[] getTableDescriptors(List<String> names)
2404 throws IOException {
2405 List<TableName> tableNames = new ArrayList<TableName>(names.size());
2406 for(String name : names) {
2407 tableNames.add(TableName.valueOf(name));
2408 }
2409 return getTableDescriptorsByTableName(tableNames);
2410 }
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425 public synchronized byte[][] rollHLogWriter(String serverName)
2426 throws IOException, FailedLogCloseException {
2427 ServerName sn = ServerName.valueOf(serverName);
2428 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
2429 RollWALWriterRequest request = RequestConverter.buildRollWALWriterRequest();
2430 try {
2431 RollWALWriterResponse response = admin.rollWALWriter(null, request);
2432 int regionCount = response.getRegionToFlushCount();
2433 byte[][] regionsToFlush = new byte[regionCount][];
2434 for (int i = 0; i < regionCount; i++) {
2435 ByteString region = response.getRegionToFlush(i);
2436 regionsToFlush[i] = region.toByteArray();
2437 }
2438 return regionsToFlush;
2439 } catch (ServiceException se) {
2440 throw ProtobufUtil.getRemoteException(se);
2441 }
2442 }
2443
2444 public String[] getMasterCoprocessors() {
2445 try {
2446 return getClusterStatus().getMasterCoprocessors();
2447 } catch (IOException e) {
2448 LOG.error("Could not getClusterStatus()",e);
2449 return null;
2450 }
2451 }
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462 public CompactionState getCompactionState(final String tableNameOrRegionName)
2463 throws IOException, InterruptedException {
2464 return getCompactionState(Bytes.toBytes(tableNameOrRegionName));
2465 }
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476 public CompactionState getCompactionState(final byte[] tableNameOrRegionName)
2477 throws IOException, InterruptedException {
2478 CompactionState state = CompactionState.NONE;
2479 CatalogTracker ct = getCatalogTracker();
2480 try {
2481 Pair<HRegionInfo, ServerName> regionServerPair
2482 = getRegion(tableNameOrRegionName, ct);
2483 if (regionServerPair != null) {
2484 if (regionServerPair.getSecond() == null) {
2485 throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
2486 } else {
2487 ServerName sn = regionServerPair.getSecond();
2488 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
2489 GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest(
2490 regionServerPair.getFirst().getRegionName(), true);
2491 GetRegionInfoResponse response = admin.getRegionInfo(null, request);
2492 return response.getCompactionState();
2493 }
2494 } else {
2495 final TableName tableName =
2496 checkTableExists(TableName.valueOf(tableNameOrRegionName), ct);
2497 List<Pair<HRegionInfo, ServerName>> pairs =
2498 MetaReader.getTableRegionsAndLocations(ct, tableName);
2499 for (Pair<HRegionInfo, ServerName> pair: pairs) {
2500 if (pair.getFirst().isOffline()) continue;
2501 if (pair.getSecond() == null) continue;
2502 try {
2503 ServerName sn = pair.getSecond();
2504 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
2505 GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest(
2506 pair.getFirst().getRegionName(), true);
2507 GetRegionInfoResponse response = admin.getRegionInfo(null, request);
2508 switch (response.getCompactionState()) {
2509 case MAJOR_AND_MINOR:
2510 return CompactionState.MAJOR_AND_MINOR;
2511 case MAJOR:
2512 if (state == CompactionState.MINOR) {
2513 return CompactionState.MAJOR_AND_MINOR;
2514 }
2515 state = CompactionState.MAJOR;
2516 break;
2517 case MINOR:
2518 if (state == CompactionState.MAJOR) {
2519 return CompactionState.MAJOR_AND_MINOR;
2520 }
2521 state = CompactionState.MINOR;
2522 break;
2523 case NONE:
2524 default:
2525 }
2526 } catch (NotServingRegionException e) {
2527 if (LOG.isDebugEnabled()) {
2528 LOG.debug("Trying to get compaction state of " +
2529 pair.getFirst() + ": " +
2530 StringUtils.stringifyException(e));
2531 }
2532 } catch (RemoteException e) {
2533 if (e.getMessage().indexOf(NotServingRegionException.class.getName()) >= 0) {
2534 if (LOG.isDebugEnabled()) {
2535 LOG.debug("Trying to get compaction state of " + pair.getFirst() + ": "
2536 + StringUtils.stringifyException(e));
2537 }
2538 } else {
2539 throw e;
2540 }
2541 }
2542 }
2543 }
2544 } catch (ServiceException se) {
2545 throw ProtobufUtil.getRemoteException(se);
2546 } finally {
2547 cleanupCatalogTracker(ct);
2548 }
2549 return state;
2550 }
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568 public void snapshot(final String snapshotName,
2569 final TableName tableName) throws IOException,
2570 SnapshotCreationException, IllegalArgumentException {
2571 snapshot(snapshotName, tableName, SnapshotDescription.Type.FLUSH);
2572 }
2573
2574 public void snapshot(final String snapshotName,
2575 final String tableName) throws IOException,
2576 SnapshotCreationException, IllegalArgumentException {
2577 snapshot(snapshotName, TableName.valueOf(tableName),
2578 SnapshotDescription.Type.FLUSH);
2579 }
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597 public void snapshot(final byte[] snapshotName,
2598 final TableName tableName) throws IOException,
2599 SnapshotCreationException, IllegalArgumentException {
2600 snapshot(Bytes.toString(snapshotName), tableName, SnapshotDescription.Type.FLUSH);
2601 }
2602
2603 public void snapshot(final byte[] snapshotName,
2604 final byte[] tableName) throws IOException,
2605 SnapshotCreationException, IllegalArgumentException {
2606 snapshot(Bytes.toString(snapshotName), TableName.valueOf(tableName),
2607 SnapshotDescription.Type.FLUSH);
2608 }
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628 public void snapshot(final String snapshotName,
2629 final TableName tableName,
2630 SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
2631 IllegalArgumentException {
2632 SnapshotDescription.Builder builder = SnapshotDescription.newBuilder();
2633 builder.setTable(tableName.getNameAsString());
2634 builder.setName(snapshotName);
2635 builder.setType(type);
2636 snapshot(builder.build());
2637 }
2638
2639 public void snapshot(final String snapshotName,
2640 final String tableName,
2641 SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
2642 IllegalArgumentException {
2643 snapshot(snapshotName, TableName.valueOf(tableName), type);
2644 }
2645
2646 public void snapshot(final String snapshotName,
2647 final byte[] tableName,
2648 SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
2649 IllegalArgumentException {
2650 snapshot(snapshotName, TableName.valueOf(tableName), type);
2651 }
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674 public void snapshot(SnapshotDescription snapshot) throws IOException, SnapshotCreationException,
2675 IllegalArgumentException {
2676
2677 SnapshotResponse response = takeSnapshotAsync(snapshot);
2678 final IsSnapshotDoneRequest request = IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot)
2679 .build();
2680 IsSnapshotDoneResponse done = null;
2681 long start = EnvironmentEdgeManager.currentTimeMillis();
2682 long max = response.getExpectedTimeout();
2683 long maxPauseTime = max / this.numRetries;
2684 int tries = 0;
2685 LOG.debug("Waiting a max of " + max + " ms for snapshot '" +
2686 ClientSnapshotDescriptionUtils.toString(snapshot) + "'' to complete. (max " +
2687 maxPauseTime + " ms per retry)");
2688 while (tries == 0
2689 || ((EnvironmentEdgeManager.currentTimeMillis() - start) < max && !done.getDone())) {
2690 try {
2691
2692 long sleep = getPauseTime(tries++);
2693 sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
2694 LOG.debug("(#" + tries + ") Sleeping: " + sleep +
2695 "ms while waiting for snapshot completion.");
2696 Thread.sleep(sleep);
2697
2698 } catch (InterruptedException e) {
2699 LOG.debug("Interrupted while waiting for snapshot " + snapshot + " to complete");
2700 Thread.currentThread().interrupt();
2701 }
2702 LOG.debug("Getting current status of snapshot from master...");
2703 done = executeCallable(new MasterCallable<IsSnapshotDoneResponse>(getConnection()) {
2704 @Override
2705 public IsSnapshotDoneResponse call() throws ServiceException {
2706 return master.isSnapshotDone(null, request);
2707 }
2708 });
2709 };
2710 if (!done.getDone()) {
2711 throw new SnapshotCreationException("Snapshot '" + snapshot.getName()
2712 + "' wasn't completed in expectedTime:" + max + " ms", snapshot);
2713 }
2714 }
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726 public SnapshotResponse takeSnapshotAsync(SnapshotDescription snapshot) throws IOException,
2727 SnapshotCreationException {
2728 ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
2729 final SnapshotRequest request = SnapshotRequest.newBuilder().setSnapshot(snapshot)
2730 .build();
2731
2732 return executeCallable(new MasterCallable<SnapshotResponse>(getConnection()) {
2733 @Override
2734 public SnapshotResponse call() throws ServiceException {
2735 return master.snapshot(null, request);
2736 }
2737 });
2738 }
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760 public boolean isSnapshotFinished(final SnapshotDescription snapshot)
2761 throws IOException, HBaseSnapshotException, UnknownSnapshotException {
2762
2763 return executeCallable(new MasterCallable<IsSnapshotDoneResponse>(getConnection()) {
2764 @Override
2765 public IsSnapshotDoneResponse call() throws ServiceException {
2766 return master.isSnapshotDone(null,
2767 IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot).build());
2768 }
2769 }).getDone();
2770 }
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785 public void restoreSnapshot(final byte[] snapshotName)
2786 throws IOException, RestoreSnapshotException {
2787 restoreSnapshot(Bytes.toString(snapshotName));
2788 }
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803 public void restoreSnapshot(final String snapshotName)
2804 throws IOException, RestoreSnapshotException {
2805 boolean takeFailSafeSnapshot =
2806 conf.getBoolean("hbase.snapshot.restore.take.failsafe.snapshot", false);
2807 restoreSnapshot(snapshotName, takeFailSafeSnapshot);
2808 }
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826 public void restoreSnapshot(final byte[] snapshotName, final boolean takeFailSafeSnapshot)
2827 throws IOException, RestoreSnapshotException {
2828 restoreSnapshot(Bytes.toString(snapshotName), takeFailSafeSnapshot);
2829 }
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847 public void restoreSnapshot(final String snapshotName, boolean takeFailSafeSnapshot)
2848 throws IOException, RestoreSnapshotException {
2849 TableName tableName = null;
2850 for (SnapshotDescription snapshotInfo: listSnapshots()) {
2851 if (snapshotInfo.getName().equals(snapshotName)) {
2852 tableName = TableName.valueOf(snapshotInfo.getTable());
2853 break;
2854 }
2855 }
2856
2857 if (tableName == null) {
2858 throw new RestoreSnapshotException(
2859 "Unable to find the table name for snapshot=" + snapshotName);
2860 }
2861
2862
2863 if (!tableExists(tableName)) {
2864 try {
2865 cloneSnapshot(snapshotName, tableName);
2866 } catch (InterruptedException e) {
2867 throw new InterruptedIOException("Interrupted when restoring a nonexistent table: " +
2868 e.getMessage());
2869 }
2870 return;
2871 }
2872
2873
2874 if (!isTableDisabled(tableName)) {
2875 throw new TableNotDisabledException(tableName);
2876 }
2877
2878
2879 String failSafeSnapshotSnapshotName = null;
2880 if (takeFailSafeSnapshot) {
2881 failSafeSnapshotSnapshotName = conf.get("hbase.snapshot.restore.failsafe.name",
2882 "hbase-failsafe-{snapshot.name}-{restore.timestamp}");
2883 failSafeSnapshotSnapshotName = failSafeSnapshotSnapshotName
2884 .replace("{snapshot.name}", snapshotName)
2885 .replace("{table.name}", tableName.toString().replace(TableName.NAMESPACE_DELIM, '.'))
2886 .replace("{restore.timestamp}", String.valueOf(EnvironmentEdgeManager.currentTimeMillis()));
2887 LOG.info("Taking restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
2888 snapshot(failSafeSnapshotSnapshotName, tableName);
2889 }
2890
2891 try {
2892
2893 internalRestoreSnapshot(snapshotName, tableName);
2894 } catch (IOException e) {
2895
2896
2897 if (takeFailSafeSnapshot) {
2898 try {
2899 internalRestoreSnapshot(failSafeSnapshotSnapshotName, tableName);
2900 String msg = "Restore snapshot=" + snapshotName +
2901 " failed. Rollback to snapshot=" + failSafeSnapshotSnapshotName + " succeeded.";
2902 LOG.error(msg, e);
2903 throw new RestoreSnapshotException(msg, e);
2904 } catch (IOException ex) {
2905 String msg = "Failed to restore and rollback to snapshot=" + failSafeSnapshotSnapshotName;
2906 LOG.error(msg, ex);
2907 throw new RestoreSnapshotException(msg, e);
2908 }
2909 } else {
2910 throw new RestoreSnapshotException("Failed to restore snapshot=" + snapshotName, e);
2911 }
2912 }
2913
2914
2915 if (takeFailSafeSnapshot) {
2916 try {
2917 LOG.info("Deleting restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
2918 deleteSnapshot(failSafeSnapshotSnapshotName);
2919 } catch (IOException e) {
2920 LOG.error("Unable to remove the failsafe snapshot: " + failSafeSnapshotSnapshotName, e);
2921 }
2922 }
2923 }
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935 public void cloneSnapshot(final byte[] snapshotName, final byte[] tableName)
2936 throws IOException, TableExistsException, RestoreSnapshotException, InterruptedException {
2937 cloneSnapshot(Bytes.toString(snapshotName), TableName.valueOf(tableName));
2938 }
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950 public void cloneSnapshot(final byte[] snapshotName, final TableName tableName)
2951 throws IOException, TableExistsException, RestoreSnapshotException, InterruptedException {
2952 cloneSnapshot(Bytes.toString(snapshotName), tableName);
2953 }
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967 public void cloneSnapshot(final String snapshotName, final String tableName)
2968 throws IOException, TableExistsException, RestoreSnapshotException, InterruptedException {
2969 cloneSnapshot(snapshotName, TableName.valueOf(tableName));
2970 }
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982 public void cloneSnapshot(final String snapshotName, final TableName tableName)
2983 throws IOException, TableExistsException, RestoreSnapshotException, InterruptedException {
2984 if (tableExists(tableName)) {
2985 throw new TableExistsException(tableName);
2986 }
2987 internalRestoreSnapshot(snapshotName, tableName);
2988 waitUntilTableIsEnabled(tableName);
2989 }
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001 private void internalRestoreSnapshot(final String snapshotName, final TableName
3002 tableName)
3003 throws IOException, RestoreSnapshotException {
3004 SnapshotDescription snapshot = SnapshotDescription.newBuilder()
3005 .setName(snapshotName).setTable(tableName.getNameAsString()).build();
3006
3007
3008 internalRestoreSnapshotAsync(snapshot);
3009
3010 final IsRestoreSnapshotDoneRequest request = IsRestoreSnapshotDoneRequest.newBuilder()
3011 .setSnapshot(snapshot).build();
3012 IsRestoreSnapshotDoneResponse done = IsRestoreSnapshotDoneResponse.newBuilder()
3013 .setDone(false).buildPartial();
3014 final long maxPauseTime = 5000;
3015 int tries = 0;
3016 while (!done.getDone()) {
3017 try {
3018
3019 long sleep = getPauseTime(tries++);
3020 sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
3021 LOG.debug(tries + ") Sleeping: " + sleep + " ms while we wait for snapshot restore to complete.");
3022 Thread.sleep(sleep);
3023 } catch (InterruptedException e) {
3024 LOG.debug("Interrupted while waiting for snapshot " + snapshot + " restore to complete");
3025 Thread.currentThread().interrupt();
3026 }
3027 LOG.debug("Getting current status of snapshot restore from master...");
3028 done = executeCallable(new MasterCallable<IsRestoreSnapshotDoneResponse>(
3029 getConnection()) {
3030 @Override
3031 public IsRestoreSnapshotDoneResponse call() throws ServiceException {
3032 return master.isRestoreSnapshotDone(null, request);
3033 }
3034 });
3035 }
3036 if (!done.getDone()) {
3037 throw new RestoreSnapshotException("Snapshot '" + snapshot.getName() + "' wasn't restored.");
3038 }
3039 }
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051 private RestoreSnapshotResponse internalRestoreSnapshotAsync(final SnapshotDescription snapshot)
3052 throws IOException, RestoreSnapshotException {
3053 ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
3054
3055 final RestoreSnapshotRequest request = RestoreSnapshotRequest.newBuilder().setSnapshot(snapshot)
3056 .build();
3057
3058
3059 return executeCallable(new MasterCallable<RestoreSnapshotResponse>(getConnection()) {
3060 @Override
3061 public RestoreSnapshotResponse call() throws ServiceException {
3062 return master.restoreSnapshot(null, request);
3063 }
3064 });
3065 }
3066
3067
3068
3069
3070
3071
3072 public List<SnapshotDescription> listSnapshots() throws IOException {
3073 return executeCallable(new MasterCallable<List<SnapshotDescription>>(getConnection()) {
3074 @Override
3075 public List<SnapshotDescription> call() throws ServiceException {
3076 return master.getCompletedSnapshots(null, GetCompletedSnapshotsRequest.newBuilder().build())
3077 .getSnapshotsList();
3078 }
3079 });
3080 }
3081
3082
3083
3084
3085
3086
3087
3088
3089 public List<SnapshotDescription> listSnapshots(String regex) throws IOException {
3090 return listSnapshots(Pattern.compile(regex));
3091 }
3092
3093
3094
3095
3096
3097
3098
3099
3100 public List<SnapshotDescription> listSnapshots(Pattern pattern) throws IOException {
3101 List<SnapshotDescription> matched = new LinkedList<SnapshotDescription>();
3102 List<SnapshotDescription> snapshots = listSnapshots();
3103 for (SnapshotDescription snapshot : snapshots) {
3104 if (pattern.matcher(snapshot.getName()).matches()) {
3105 matched.add(snapshot);
3106 }
3107 }
3108 return matched;
3109 }
3110
3111
3112
3113
3114
3115
3116 public void deleteSnapshot(final byte[] snapshotName) throws IOException {
3117 deleteSnapshot(Bytes.toString(snapshotName));
3118 }
3119
3120
3121
3122
3123
3124
3125 public void deleteSnapshot(final String snapshotName) throws IOException {
3126
3127 TableName.isLegalFullyQualifiedTableName(Bytes.toBytes(snapshotName));
3128
3129 executeCallable(new MasterCallable<Void>(getConnection()) {
3130 @Override
3131 public Void call() throws ServiceException {
3132 master.deleteSnapshot(null,
3133 DeleteSnapshotRequest.newBuilder().
3134 setSnapshot(SnapshotDescription.newBuilder().setName(snapshotName).build()).build());
3135 return null;
3136 }
3137 });
3138 }
3139
3140
3141
3142
3143
3144
3145 public void deleteSnapshots(final String regex) throws IOException {
3146 deleteSnapshots(Pattern.compile(regex));
3147 }
3148
3149
3150
3151
3152
3153
3154 public void deleteSnapshots(final Pattern pattern) throws IOException {
3155 List<SnapshotDescription> snapshots = listSnapshots(pattern);
3156 for (final SnapshotDescription snapshot : snapshots) {
3157
3158 executeCallable(new MasterCallable<Void>(getConnection()) {
3159 @Override
3160 public Void call() throws ServiceException {
3161 this.master.deleteSnapshot(null,
3162 DeleteSnapshotRequest.newBuilder().setSnapshot(snapshot).build());
3163 return null;
3164 }
3165 });
3166 }
3167 }
3168
3169
3170
3171
3172
3173
3174 abstract static class MasterCallable<V> implements RetryingCallable<V>, Closeable {
3175 protected HConnection connection;
3176 protected MasterKeepAliveConnection master;
3177
3178 public MasterCallable(final HConnection connection) {
3179 this.connection = connection;
3180 }
3181
3182 @Override
3183 public void prepare(boolean reload) throws IOException {
3184 this.master = this.connection.getKeepAliveMasterService();
3185 }
3186
3187 @Override
3188 public void close() throws IOException {
3189
3190 if (this.master != null) this.master.close();
3191 }
3192
3193 @Override
3194 public void throwable(Throwable t, boolean retrying) {
3195 }
3196
3197 @Override
3198 public String getExceptionMessageAdditionalDetail() {
3199 return "";
3200 }
3201
3202 @Override
3203 public long sleep(long pause, int tries) {
3204 return ConnectionUtils.getPauseTime(pause, tries);
3205 }
3206 }
3207
3208 private <V> V executeCallable(MasterCallable<V> callable) throws IOException {
3209 RpcRetryingCaller<V> caller = rpcCallerFactory.newCaller();
3210 try {
3211 return caller.callWithRetries(callable);
3212 } finally {
3213 callable.close();
3214 }
3215 }
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238 public CoprocessorRpcChannel coprocessorService() {
3239 return new MasterCoprocessorRpcChannel(connection);
3240 }
3241 }