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.IOException;
22 import java.io.InterruptedIOException;
23 import java.net.SocketTimeoutException;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.concurrent.atomic.AtomicInteger;
32 import java.util.concurrent.atomic.AtomicReference;
33 import java.util.concurrent.ExecutionException;
34 import java.util.concurrent.Future;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.TimeoutException;
37 import java.util.regex.Pattern;
38
39 import org.apache.commons.logging.Log;
40 import org.apache.commons.logging.LogFactory;
41 import org.apache.hadoop.conf.Configuration;
42 import org.apache.hadoop.hbase.Abortable;
43 import org.apache.hadoop.hbase.ClusterStatus;
44 import org.apache.hadoop.hbase.DoNotRetryIOException;
45 import org.apache.hadoop.hbase.HBaseConfiguration;
46 import org.apache.hadoop.hbase.HColumnDescriptor;
47 import org.apache.hadoop.hbase.HConstants;
48 import org.apache.hadoop.hbase.HRegionInfo;
49 import org.apache.hadoop.hbase.HRegionLocation;
50 import org.apache.hadoop.hbase.HTableDescriptor;
51 import org.apache.hadoop.hbase.MasterNotRunningException;
52 import org.apache.hadoop.hbase.MetaTableAccessor;
53 import org.apache.hadoop.hbase.NamespaceDescriptor;
54 import org.apache.hadoop.hbase.NotServingRegionException;
55 import org.apache.hadoop.hbase.RegionException;
56 import org.apache.hadoop.hbase.RegionLocations;
57 import org.apache.hadoop.hbase.ServerName;
58 import org.apache.hadoop.hbase.TableExistsException;
59 import org.apache.hadoop.hbase.TableName;
60 import org.apache.hadoop.hbase.TableNotDisabledException;
61 import org.apache.hadoop.hbase.TableNotEnabledException;
62 import org.apache.hadoop.hbase.TableNotFoundException;
63 import org.apache.hadoop.hbase.UnknownRegionException;
64 import org.apache.hadoop.hbase.ZooKeeperConnectionException;
65 import org.apache.hadoop.hbase.classification.InterfaceAudience;
66 import org.apache.hadoop.hbase.classification.InterfaceStability;
67 import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitor;
68 import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitorBase;
69 import org.apache.hadoop.hbase.exceptions.DeserializationException;
70 import org.apache.hadoop.hbase.exceptions.TimeoutIOException;
71 import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
72 import org.apache.hadoop.hbase.ipc.MasterCoprocessorRpcChannel;
73 import org.apache.hadoop.hbase.ipc.RegionServerCoprocessorRpcChannel;
74 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
75 import org.apache.hadoop.hbase.protobuf.RequestConverter;
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.AdminProtos.UpdateConfigurationRequest;
88 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
89 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameStringPair;
90 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ProcedureDescription;
91 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType;
92 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
93 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.TableSchema;
94 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.AddColumnRequest;
95 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.AssignRegionRequest;
96 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateNamespaceRequest;
97 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateTableRequest;
98 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateTableResponse;
99 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteColumnRequest;
100 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteNamespaceRequest;
101 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteSnapshotRequest;
102 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteTableRequest;
103 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteTableResponse;
104 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DisableTableRequest;
105 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DisableTableResponse;
106 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DispatchMergingRegionsRequest;
107 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.EnableTableRequest;
108 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.EnableTableResponse;
109 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ExecProcedureRequest;
110 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ExecProcedureResponse;
111 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetClusterStatusRequest;
112 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsRequest;
113 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetNamespaceDescriptorRequest;
114 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetProcedureResultRequest;
115 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetProcedureResultResponse;
116 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetSchemaAlterStatusRequest;
117 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetSchemaAlterStatusResponse;
118 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsRequest;
119 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsResponse;
120 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableNamesRequest;
121 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsProcedureDoneRequest;
122 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsProcedureDoneResponse;
123 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsRestoreSnapshotDoneRequest;
124 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsRestoreSnapshotDoneResponse;
125 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
126 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
127 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListNamespaceDescriptorsRequest;
128 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceRequest;
129 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ListTableNamesByNamespaceRequest;
130 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MajorCompactionTimestampForRegionRequest;
131 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MajorCompactionTimestampRequest;
132 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyColumnRequest;
133 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyNamespaceRequest;
134 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ModifyTableRequest;
135 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MoveRegionRequest;
136 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RestoreSnapshotRequest;
137 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.RestoreSnapshotResponse;
138 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SetBalancerRunningRequest;
139 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.ShutdownRequest;
140 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SnapshotRequest;
141 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.SnapshotResponse;
142 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.StopMasterRequest;
143 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.TruncateTableRequest;
144 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.UnassignRegionRequest;
145 import org.apache.hadoop.hbase.quotas.QuotaFilter;
146 import org.apache.hadoop.hbase.quotas.QuotaRetriever;
147 import org.apache.hadoop.hbase.quotas.QuotaSettings;
148 import org.apache.hadoop.hbase.regionserver.wal.FailedLogCloseException;
149 import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
150 import org.apache.hadoop.hbase.snapshot.HBaseSnapshotException;
151 import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
152 import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
153 import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException;
154 import org.apache.hadoop.hbase.util.Addressing;
155 import org.apache.hadoop.hbase.util.Bytes;
156 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
157 import org.apache.hadoop.hbase.util.ForeignExceptionUtil;
158 import org.apache.hadoop.hbase.util.Pair;
159 import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker;
160 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
161 import org.apache.hadoop.ipc.RemoteException;
162 import org.apache.hadoop.util.StringUtils;
163 import org.apache.zookeeper.KeeperException;
164
165 import com.google.common.annotations.VisibleForTesting;
166 import com.google.protobuf.ByteString;
167 import com.google.protobuf.ServiceException;
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185 @InterfaceAudience.Private
186 @InterfaceStability.Evolving
187 public class HBaseAdmin implements Admin {
188 private static final Log LOG = LogFactory.getLog(HBaseAdmin.class);
189
190 private static final String ZK_IDENTIFIER_PREFIX = "hbase-admin-on-";
191
192 private ClusterConnection connection;
193
194 private volatile Configuration conf;
195 private final long pause;
196 private final int numRetries;
197
198
199
200 private final int retryLongerMultiplier;
201 private final int syncWaitTimeout;
202 private boolean aborted;
203 private boolean cleanupConnectionOnClose = false;
204 private boolean closed = false;
205 private int operationTimeout;
206
207 private RpcRetryingCallerFactory rpcCallerFactory;
208
209
210
211
212
213
214
215
216
217 @Deprecated
218 public HBaseAdmin(Configuration c)
219 throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
220
221
222 this(ConnectionManager.getConnectionInternal(new Configuration(c)));
223 this.cleanupConnectionOnClose = true;
224 }
225
226 @Override
227 public int getOperationTimeout() {
228 return operationTimeout;
229 }
230
231
232
233
234
235
236
237
238
239
240
241
242 @Deprecated
243 public HBaseAdmin(Connection connection)
244 throws MasterNotRunningException, ZooKeeperConnectionException {
245 this((ClusterConnection)connection);
246 }
247
248 HBaseAdmin(ClusterConnection connection) {
249 this.conf = connection.getConfiguration();
250 this.connection = connection;
251
252 this.pause = this.conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
253 HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
254 this.numRetries = this.conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
255 HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
256 this.retryLongerMultiplier = this.conf.getInt(
257 "hbase.client.retries.longer.multiplier", 10);
258 this.operationTimeout = this.conf.getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
259 HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
260 this.syncWaitTimeout = this.conf.getInt(
261 "hbase.client.sync.wait.timeout.msec", 10 * 60000);
262
263 this.rpcCallerFactory = RpcRetryingCallerFactory.instantiate(this.conf);
264 }
265
266 @Override
267 public void abort(String why, Throwable e) {
268
269 this.aborted = true;
270 throw new RuntimeException(why, e);
271 }
272
273 @Override
274 public boolean isAborted(){
275 return this.aborted;
276 }
277
278
279 @Override
280 public HConnection getConnection() {
281 return connection;
282 }
283
284
285
286
287
288
289
290 @Deprecated
291 public boolean isMasterRunning()
292 throws MasterNotRunningException, ZooKeeperConnectionException {
293 return connection.isMasterRunning();
294 }
295
296
297
298
299
300
301 @Override
302 public boolean tableExists(final TableName tableName) throws IOException {
303 return MetaTableAccessor.tableExists(connection, tableName);
304 }
305
306 public boolean tableExists(final byte[] tableName)
307 throws IOException {
308 return tableExists(TableName.valueOf(tableName));
309 }
310
311 public boolean tableExists(final String tableName)
312 throws IOException {
313 return tableExists(TableName.valueOf(tableName));
314 }
315
316 @Override
317 public HTableDescriptor[] listTables() throws IOException {
318 return listTables((Pattern)null, false);
319 }
320
321 @Override
322 public HTableDescriptor[] listTables(Pattern pattern) throws IOException {
323 return listTables(pattern, false);
324 }
325
326 @Override
327 public HTableDescriptor[] listTables(String regex) throws IOException {
328 return listTables(Pattern.compile(regex), false);
329 }
330
331 @Override
332 public HTableDescriptor[] listTables(final Pattern pattern, final boolean includeSysTables)
333 throws IOException {
334 return executeCallable(new MasterCallable<HTableDescriptor[]>(getConnection()) {
335 @Override
336 public HTableDescriptor[] call(int callTimeout) throws ServiceException {
337 GetTableDescriptorsRequest req =
338 RequestConverter.buildGetTableDescriptorsRequest(pattern, includeSysTables);
339 return ProtobufUtil.getHTableDescriptorArray(master.getTableDescriptors(null, req));
340 }
341 });
342 }
343
344 @Override
345 public HTableDescriptor[] listTables(String regex, boolean includeSysTables)
346 throws IOException {
347 return listTables(Pattern.compile(regex), includeSysTables);
348 }
349
350
351
352
353
354
355
356 @Deprecated
357 public String[] getTableNames() throws IOException {
358 TableName[] tableNames = listTableNames();
359 String result[] = new String[tableNames.length];
360 for (int i = 0; i < tableNames.length; i++) {
361 result[i] = tableNames[i].getNameAsString();
362 }
363 return result;
364 }
365
366
367
368
369
370
371
372
373 @Deprecated
374 public String[] getTableNames(Pattern pattern) throws IOException {
375 TableName[] tableNames = listTableNames(pattern);
376 String result[] = new String[tableNames.length];
377 for (int i = 0; i < tableNames.length; i++) {
378 result[i] = tableNames[i].getNameAsString();
379 }
380 return result;
381 }
382
383
384
385
386
387
388
389
390 @Deprecated
391 public String[] getTableNames(String regex) throws IOException {
392 return getTableNames(Pattern.compile(regex));
393 }
394
395 @Override
396 public TableName[] listTableNames() throws IOException {
397 return listTableNames((Pattern)null, false);
398 }
399
400 @Override
401 public TableName[] listTableNames(Pattern pattern) throws IOException {
402 return listTableNames(pattern, false);
403 }
404
405 @Override
406 public TableName[] listTableNames(String regex) throws IOException {
407 return listTableNames(Pattern.compile(regex), false);
408 }
409
410 @Override
411 public TableName[] listTableNames(final Pattern pattern, final boolean includeSysTables)
412 throws IOException {
413 return executeCallable(new MasterCallable<TableName[]>(getConnection()) {
414 @Override
415 public TableName[] call(int callTimeout) throws ServiceException {
416 GetTableNamesRequest req =
417 RequestConverter.buildGetTableNamesRequest(pattern, includeSysTables);
418 return ProtobufUtil.getTableNameArray(master.getTableNames(null, req)
419 .getTableNamesList());
420 }
421 });
422 }
423
424 @Override
425 public TableName[] listTableNames(final String regex, final boolean includeSysTables)
426 throws IOException {
427 return listTableNames(Pattern.compile(regex), includeSysTables);
428 }
429
430
431
432
433
434
435
436
437 @Override
438 public HTableDescriptor getTableDescriptor(final TableName tableName)
439 throws TableNotFoundException, IOException {
440 if (tableName == null) return null;
441 HTableDescriptor htd = executeCallable(new MasterCallable<HTableDescriptor>(getConnection()) {
442 @Override
443 public HTableDescriptor call(int callTimeout) throws ServiceException {
444 GetTableDescriptorsResponse htds;
445 GetTableDescriptorsRequest req =
446 RequestConverter.buildGetTableDescriptorsRequest(tableName);
447 htds = master.getTableDescriptors(null, req);
448
449 if (!htds.getTableSchemaList().isEmpty()) {
450 return HTableDescriptor.convert(htds.getTableSchemaList().get(0));
451 }
452 return null;
453 }
454 });
455 if (htd != null) {
456 return htd;
457 }
458 throw new TableNotFoundException(tableName.getNameAsString());
459 }
460
461 public HTableDescriptor getTableDescriptor(final byte[] tableName)
462 throws TableNotFoundException, IOException {
463 return getTableDescriptor(TableName.valueOf(tableName));
464 }
465
466 private long getPauseTime(int tries) {
467 int triesCount = tries;
468 if (triesCount >= HConstants.RETRY_BACKOFF.length) {
469 triesCount = HConstants.RETRY_BACKOFF.length - 1;
470 }
471 return this.pause * HConstants.RETRY_BACKOFF[triesCount];
472 }
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487 @Override
488 public void createTable(HTableDescriptor desc)
489 throws IOException {
490 createTable(desc, null);
491 }
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517 @Override
518 public void createTable(HTableDescriptor desc, byte [] startKey,
519 byte [] endKey, int numRegions)
520 throws IOException {
521 if(numRegions < 3) {
522 throw new IllegalArgumentException("Must create at least three regions");
523 } else if(Bytes.compareTo(startKey, endKey) >= 0) {
524 throw new IllegalArgumentException("Start key must be smaller than end key");
525 }
526 if (numRegions == 3) {
527 createTable(desc, new byte[][]{startKey, endKey});
528 return;
529 }
530 byte [][] splitKeys = Bytes.split(startKey, endKey, numRegions - 3);
531 if(splitKeys == null || splitKeys.length != numRegions - 1) {
532 throw new IllegalArgumentException("Unable to split key range into enough regions");
533 }
534 createTable(desc, splitKeys);
535 }
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554 @Override
555 public void createTable(final HTableDescriptor desc, byte [][] splitKeys)
556 throws IOException {
557 Future<Void> future = createTableAsyncV2(desc, splitKeys);
558 try {
559
560 future.get(syncWaitTimeout, TimeUnit.MILLISECONDS);
561 } catch (InterruptedException e) {
562 throw new InterruptedIOException("Interrupted when waiting" +
563 " for table to be enabled; meta scan was done");
564 } catch (TimeoutException e) {
565 throw new TimeoutIOException(e);
566 } catch (ExecutionException e) {
567 if (e.getCause() instanceof IOException) {
568 throw (IOException)e.getCause();
569 } else {
570 throw new IOException(e.getCause());
571 }
572 }
573 }
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591 @Override
592 public void createTableAsync(final HTableDescriptor desc, final byte [][] splitKeys)
593 throws IOException {
594 createTableAsyncV2(desc, splitKeys);
595 }
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613 private Future<Void> createTableAsyncV2(final HTableDescriptor desc, final byte[][] splitKeys)
614 throws IOException {
615 if (desc.getTableName() == null) {
616 throw new IllegalArgumentException("TableName cannot be null");
617 }
618 if (splitKeys != null && splitKeys.length > 0) {
619 Arrays.sort(splitKeys, Bytes.BYTES_COMPARATOR);
620
621 byte[] lastKey = null;
622 for (byte[] splitKey : splitKeys) {
623 if (Bytes.compareTo(splitKey, HConstants.EMPTY_BYTE_ARRAY) == 0) {
624 throw new IllegalArgumentException(
625 "Empty split key must not be passed in the split keys.");
626 }
627 if (lastKey != null && Bytes.equals(splitKey, lastKey)) {
628 throw new IllegalArgumentException("All split keys must be unique, " +
629 "found duplicate: " + Bytes.toStringBinary(splitKey) +
630 ", " + Bytes.toStringBinary(lastKey));
631 }
632 lastKey = splitKey;
633 }
634 }
635
636 CreateTableResponse response = executeCallable(
637 new MasterCallable<CreateTableResponse>(getConnection()) {
638 @Override
639 public CreateTableResponse call(int callTimeout) throws ServiceException {
640 CreateTableRequest request = RequestConverter.buildCreateTableRequest(desc, splitKeys);
641 return master.createTable(null, request);
642 }
643 });
644 return new CreateTableFuture(this, desc, splitKeys, response);
645 }
646
647 private static class CreateTableFuture extends ProcedureFuture<Void> {
648 private final HTableDescriptor desc;
649 private final byte[][] splitKeys;
650
651 public CreateTableFuture(final HBaseAdmin admin, final HTableDescriptor desc,
652 final byte[][] splitKeys, final CreateTableResponse response) {
653 super(admin, (response != null && response.hasProcId()) ? response.getProcId() : null);
654 this.splitKeys = splitKeys;
655 this.desc = desc;
656 }
657
658 @Override
659 protected Void waitOperationResult(final long deadlineTs)
660 throws IOException, TimeoutException {
661 waitForTableEnabled(deadlineTs);
662 waitForAllRegionsOnline(deadlineTs);
663 return null;
664 }
665
666 @Override
667 protected Void postOperationResult(final Void result, final long deadlineTs)
668 throws IOException, TimeoutException {
669 LOG.info("Created " + desc.getTableName());
670 return result;
671 }
672
673 private void waitForTableEnabled(final long deadlineTs)
674 throws IOException, TimeoutException {
675 waitForState(deadlineTs, new WaitForStateCallable() {
676 @Override
677 public boolean checkState(int tries) throws IOException {
678 try {
679 if (getAdmin().isTableAvailable(desc.getTableName())) {
680 return true;
681 }
682 } catch (TableNotFoundException tnfe) {
683 LOG.debug("Table "+ desc.getTableName() +" was not enabled, sleeping. tries="+ tries);
684 }
685 return false;
686 }
687
688 @Override
689 public void throwInterruptedException() throws InterruptedIOException {
690 throw new InterruptedIOException("Interrupted when waiting for table " +
691 desc.getTableName() + " to be enabled");
692 }
693
694 @Override
695 public void throwTimeoutException(long elapsedTime) throws TimeoutException {
696 throw new TimeoutException("Table " + desc.getTableName() +
697 " not enabled after " + elapsedTime + "msec");
698 }
699 });
700 }
701
702 private void waitForAllRegionsOnline(final long deadlineTs)
703 throws IOException, TimeoutException {
704 final AtomicInteger actualRegCount = new AtomicInteger(0);
705 final MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
706 @Override
707 public boolean processRow(Result rowResult) throws IOException {
708 RegionLocations list = MetaTableAccessor.getRegionLocations(rowResult);
709 if (list == null) {
710 LOG.warn("No serialized HRegionInfo in " + rowResult);
711 return true;
712 }
713 HRegionLocation l = list.getRegionLocation();
714 if (l == null) {
715 return true;
716 }
717 if (!l.getRegionInfo().getTable().equals(desc.getTableName())) {
718 return false;
719 }
720 if (l.getRegionInfo().isOffline() || l.getRegionInfo().isSplit()) return true;
721 HRegionLocation[] locations = list.getRegionLocations();
722 for (HRegionLocation location : locations) {
723 if (location == null) continue;
724 ServerName serverName = location.getServerName();
725
726 if (serverName != null && serverName.getHostAndPort() != null) {
727 actualRegCount.incrementAndGet();
728 }
729 }
730 return true;
731 }
732 };
733
734 int tries = 0;
735 IOException serverEx = null;
736 int numRegs = (splitKeys == null ? 1 : splitKeys.length + 1) * desc.getRegionReplication();
737 while (EnvironmentEdgeManager.currentTime() < deadlineTs) {
738 actualRegCount.set(0);
739 MetaScanner.metaScan(getAdmin().getConnection(), visitor, desc.getTableName());
740 if (actualRegCount.get() == numRegs) {
741
742 return;
743 }
744
745 try {
746 Thread.sleep(getAdmin().getPauseTime(tries++));
747 } catch (InterruptedException e) {
748 throw new InterruptedIOException("Interrupted when opening" +
749 " regions; " + actualRegCount.get() + " of " + numRegs +
750 " regions processed so far");
751 }
752 }
753 throw new TimeoutException("Only " + actualRegCount.get() +
754 " of " + numRegs + " regions are online; retries exhausted.");
755 }
756 }
757
758 public void deleteTable(final String tableName) throws IOException {
759 deleteTable(TableName.valueOf(tableName));
760 }
761
762 public void deleteTable(final byte[] tableName) throws IOException {
763 deleteTable(TableName.valueOf(tableName));
764 }
765
766
767
768
769
770
771
772
773 @Override
774 public void deleteTable(final TableName tableName) throws IOException {
775 Future<Void> future = deleteTableAsyncV2(tableName);
776 try {
777 future.get(syncWaitTimeout, TimeUnit.MILLISECONDS);
778 } catch (InterruptedException e) {
779 throw new InterruptedIOException("Interrupted when waiting for table to be deleted");
780 } catch (TimeoutException e) {
781 throw new TimeoutIOException(e);
782 } catch (ExecutionException e) {
783 if (e.getCause() instanceof IOException) {
784 throw (IOException)e.getCause();
785 } else {
786 throw new IOException(e.getCause());
787 }
788 }
789 }
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805 private Future<Void> deleteTableAsyncV2(final TableName tableName) throws IOException {
806 DeleteTableResponse response = executeCallable(
807 new MasterCallable<DeleteTableResponse>(getConnection()) {
808 @Override
809 public DeleteTableResponse call(int callTimeout) throws ServiceException {
810 DeleteTableRequest req = RequestConverter.buildDeleteTableRequest(tableName);
811 return master.deleteTable(null,req);
812 }
813 });
814 return new DeleteTableFuture(this, tableName, response);
815 }
816
817 private static class DeleteTableFuture extends ProcedureFuture<Void> {
818 private final TableName tableName;
819
820 public DeleteTableFuture(final HBaseAdmin admin, final TableName tableName,
821 final DeleteTableResponse response) {
822 super(admin, (response != null && response.hasProcId()) ? response.getProcId() : null);
823 this.tableName = tableName;
824 }
825
826 @Override
827 protected Void waitOperationResult(final long deadlineTs)
828 throws IOException, TimeoutException {
829 waitTableNotFound(deadlineTs);
830 return null;
831 }
832
833 @Override
834 protected Void postOperationResult(final Void result, final long deadlineTs)
835 throws IOException, TimeoutException {
836
837 getAdmin().getConnection().clearRegionCache(tableName);
838 LOG.info("Deleted " + tableName);
839 return result;
840 }
841
842 private void waitTableNotFound(final long deadlineTs)
843 throws IOException, TimeoutException {
844 waitForState(deadlineTs, new WaitForStateCallable() {
845 @Override
846 public boolean checkState(int tries) throws IOException {
847 return !getAdmin().tableExists(tableName);
848 }
849
850 @Override
851 public void throwInterruptedException() throws InterruptedIOException {
852 throw new InterruptedIOException("Interrupted when waiting for table to be deleted");
853 }
854
855 @Override
856 public void throwTimeoutException(long elapsedTime) throws TimeoutException {
857 throw new TimeoutException("Table " + tableName + " not yet deleted after " +
858 elapsedTime + "msec");
859 }
860 });
861 }
862 }
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877 @Override
878 public HTableDescriptor[] deleteTables(String regex) throws IOException {
879 return deleteTables(Pattern.compile(regex));
880 }
881
882
883
884
885
886
887
888
889
890
891
892
893 @Override
894 public HTableDescriptor[] deleteTables(Pattern pattern) throws IOException {
895 List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
896 for (HTableDescriptor table : listTables(pattern)) {
897 try {
898 deleteTable(table.getTableName());
899 } catch (IOException ex) {
900 LOG.info("Failed to delete table " + table.getTableName(), ex);
901 failed.add(table);
902 }
903 }
904 return failed.toArray(new HTableDescriptor[failed.size()]);
905 }
906
907
908
909
910
911
912
913
914
915 @Override
916 public void truncateTable(final TableName tableName, final boolean preserveSplits)
917 throws IOException {
918 executeCallable(new MasterCallable<Void>(getConnection()) {
919 @Override
920 public Void call(int callTimeout) throws ServiceException {
921 TruncateTableRequest req = RequestConverter.buildTruncateTableRequest(
922 tableName, preserveSplits);
923 master.truncateTable(null, req);
924 return null;
925 }
926 });
927 }
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942 @Override
943 public void enableTable(final TableName tableName)
944 throws IOException {
945 Future<Void> future = enableTableAsyncV2(tableName);
946 try {
947 future.get(syncWaitTimeout, TimeUnit.MILLISECONDS);
948 } catch (InterruptedException e) {
949 throw new InterruptedIOException("Interrupted when waiting for table to be disabled");
950 } catch (TimeoutException e) {
951 throw new TimeoutIOException(e);
952 } catch (ExecutionException e) {
953 if (e.getCause() instanceof IOException) {
954 throw (IOException)e.getCause();
955 } else {
956 throw new IOException(e.getCause());
957 }
958 }
959 }
960
961 public void enableTable(final byte[] tableName)
962 throws IOException {
963 enableTable(TableName.valueOf(tableName));
964 }
965
966 public void enableTable(final String tableName)
967 throws IOException {
968 enableTable(TableName.valueOf(tableName));
969 }
970
971
972
973
974
975
976
977
978 private void waitUntilTableIsEnabled(final TableName tableName) throws IOException {
979 boolean enabled = false;
980 long start = EnvironmentEdgeManager.currentTime();
981 for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
982 try {
983 enabled = isTableEnabled(tableName);
984 } catch (TableNotFoundException tnfe) {
985
986 enabled = false;
987 }
988 enabled = enabled && isTableAvailable(tableName);
989 if (enabled) {
990 break;
991 }
992 long sleep = getPauseTime(tries);
993 if (LOG.isDebugEnabled()) {
994 LOG.debug("Sleeping= " + sleep + "ms, waiting for all regions to be " +
995 "enabled in " + tableName);
996 }
997 try {
998 Thread.sleep(sleep);
999 } catch (InterruptedException e) {
1000
1001
1002 throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
1003 }
1004 }
1005 if (!enabled) {
1006 long msec = EnvironmentEdgeManager.currentTime() - start;
1007 throw new IOException("Table '" + tableName +
1008 "' not yet enabled, after " + msec + "ms.");
1009 }
1010 }
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022 @Override
1023 public void enableTableAsync(final TableName tableName)
1024 throws IOException {
1025 enableTableAsyncV2(tableName);
1026 }
1027
1028 public void enableTableAsync(final byte[] tableName)
1029 throws IOException {
1030 enableTable(TableName.valueOf(tableName));
1031 }
1032
1033 public void enableTableAsync(final String tableName)
1034 throws IOException {
1035 enableTableAsync(TableName.valueOf(tableName));
1036 }
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051 private Future<Void> enableTableAsyncV2(final TableName tableName) throws IOException {
1052 TableName.isLegalFullyQualifiedTableName(tableName.getName());
1053 EnableTableResponse response = executeCallable(
1054 new MasterCallable<EnableTableResponse>(getConnection()) {
1055 @Override
1056 public EnableTableResponse call(int callTimeout) throws ServiceException {
1057 LOG.info("Started enable of " + tableName);
1058 EnableTableRequest req = RequestConverter.buildEnableTableRequest(tableName);
1059 return master.enableTable(null,req);
1060 }
1061 });
1062 return new EnableTableFuture(this, tableName, response);
1063 }
1064
1065 private static class EnableTableFuture extends ProcedureFuture<Void> {
1066 private final TableName tableName;
1067
1068 public EnableTableFuture(final HBaseAdmin admin, final TableName tableName,
1069 final EnableTableResponse response) {
1070 super(admin, (response != null && response.hasProcId()) ? response.getProcId() : null);
1071 this.tableName = tableName;
1072 }
1073
1074 @Override
1075 protected Void waitOperationResult(final long deadlineTs)
1076 throws IOException, TimeoutException {
1077 waitTableEnabled(deadlineTs);
1078 return null;
1079 }
1080
1081 @Override
1082 protected Void postOperationResult(final Void result, final long deadlineTs)
1083 throws IOException, TimeoutException {
1084 LOG.info("Enabled " + tableName);
1085 return result;
1086 }
1087
1088 private void waitTableEnabled(final long deadlineTs)
1089 throws IOException, TimeoutException {
1090 waitForState(deadlineTs, new WaitForStateCallable() {
1091 @Override
1092 public boolean checkState(int tries) throws IOException {
1093 boolean enabled;
1094 try {
1095 enabled = getAdmin().isTableEnabled(tableName);
1096 } catch (TableNotFoundException tnfe) {
1097 return false;
1098 }
1099 return enabled && getAdmin().isTableAvailable(tableName);
1100 }
1101
1102 @Override
1103 public void throwInterruptedException() throws InterruptedIOException {
1104 throw new InterruptedIOException("Interrupted when waiting for table to be enabled");
1105 }
1106
1107 @Override
1108 public void throwTimeoutException(long elapsedTime) throws TimeoutException {
1109 throw new TimeoutException("Table " + tableName + " not yet enabled after " +
1110 elapsedTime + "msec");
1111 }
1112 });
1113 }
1114 }
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128 @Override
1129 public HTableDescriptor[] enableTables(String regex) throws IOException {
1130 return enableTables(Pattern.compile(regex));
1131 }
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143 @Override
1144 public HTableDescriptor[] enableTables(Pattern pattern) throws IOException {
1145 List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
1146 for (HTableDescriptor table : listTables(pattern)) {
1147 if (isTableDisabled(table.getTableName())) {
1148 try {
1149 enableTable(table.getTableName());
1150 } catch (IOException ex) {
1151 LOG.info("Failed to enable table " + table.getTableName(), ex);
1152 failed.add(table);
1153 }
1154 }
1155 }
1156 return failed.toArray(new HTableDescriptor[failed.size()]);
1157 }
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172 @Override
1173 public void disableTableAsync(final TableName tableName) throws IOException {
1174 disableTableAsyncV2(tableName);
1175 }
1176
1177 public void disableTableAsync(final byte[] tableName) throws IOException {
1178 disableTableAsync(TableName.valueOf(tableName));
1179 }
1180
1181 public void disableTableAsync(final String tableName) throws IOException {
1182 disableTableAsync(TableName.valueOf(tableName));
1183 }
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196 @Override
1197 public void disableTable(final TableName tableName)
1198 throws IOException {
1199 Future<Void> future = disableTableAsyncV2(tableName);
1200 try {
1201 future.get(syncWaitTimeout, TimeUnit.MILLISECONDS);
1202 } catch (InterruptedException e) {
1203 throw new InterruptedIOException("Interrupted when waiting for table to be disabled");
1204 } catch (TimeoutException e) {
1205 throw new TimeoutIOException(e);
1206 } catch (ExecutionException e) {
1207 if (e.getCause() instanceof IOException) {
1208 throw (IOException)e.getCause();
1209 } else {
1210 throw new IOException(e.getCause());
1211 }
1212 }
1213 }
1214
1215 public void disableTable(final byte[] tableName)
1216 throws IOException {
1217 disableTable(TableName.valueOf(tableName));
1218 }
1219
1220 public void disableTable(final String tableName)
1221 throws IOException {
1222 disableTable(TableName.valueOf(tableName));
1223 }
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238 private Future<Void> disableTableAsyncV2(final TableName tableName) throws IOException {
1239 TableName.isLegalFullyQualifiedTableName(tableName.getName());
1240 DisableTableResponse response = executeCallable(
1241 new MasterCallable<DisableTableResponse>(getConnection()) {
1242 @Override
1243 public DisableTableResponse call(int callTimeout) throws ServiceException {
1244 LOG.info("Started disable of " + tableName);
1245 DisableTableRequest req = RequestConverter.buildDisableTableRequest(tableName);
1246 return master.disableTable(null, req);
1247 }
1248 });
1249 return new DisableTableFuture(this, tableName, response);
1250 }
1251
1252 private static class DisableTableFuture extends ProcedureFuture<Void> {
1253 private final TableName tableName;
1254
1255 public DisableTableFuture(final HBaseAdmin admin, final TableName tableName,
1256 final DisableTableResponse response) {
1257 super(admin, (response != null && response.hasProcId()) ? response.getProcId() : null);
1258 this.tableName = tableName;
1259 }
1260
1261 @Override
1262 protected Void waitOperationResult(final long deadlineTs)
1263 throws IOException, TimeoutException {
1264 waitTableDisabled(deadlineTs);
1265 return null;
1266 }
1267
1268 @Override
1269 protected Void postOperationResult(final Void result, final long deadlineTs)
1270 throws IOException, TimeoutException {
1271 LOG.info("Disabled " + tableName);
1272 return result;
1273 }
1274
1275 private void waitTableDisabled(final long deadlineTs)
1276 throws IOException, TimeoutException {
1277 waitForState(deadlineTs, new WaitForStateCallable() {
1278 @Override
1279 public boolean checkState(int tries) throws IOException {
1280 return getAdmin().isTableDisabled(tableName);
1281 }
1282
1283 @Override
1284 public void throwInterruptedException() throws InterruptedIOException {
1285 throw new InterruptedIOException("Interrupted when waiting for table to be disabled");
1286 }
1287
1288 @Override
1289 public void throwTimeoutException(long elapsedTime) throws TimeoutException {
1290 throw new TimeoutException("Table " + tableName + " not yet disabled after " +
1291 elapsedTime + "msec");
1292 }
1293 });
1294 }
1295 }
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310 @Override
1311 public HTableDescriptor[] disableTables(String regex) throws IOException {
1312 return disableTables(Pattern.compile(regex));
1313 }
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326 @Override
1327 public HTableDescriptor[] disableTables(Pattern pattern) throws IOException {
1328 List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
1329 for (HTableDescriptor table : listTables(pattern)) {
1330 if (isTableEnabled(table.getTableName())) {
1331 try {
1332 disableTable(table.getTableName());
1333 } catch (IOException ex) {
1334 LOG.info("Failed to disable table " + table.getTableName(), ex);
1335 failed.add(table);
1336 }
1337 }
1338 }
1339 return failed.toArray(new HTableDescriptor[failed.size()]);
1340 }
1341
1342
1343
1344
1345
1346 private void checkTableExistence(TableName tableName) throws IOException {
1347 if (!tableExists(tableName)) {
1348 throw new TableNotFoundException(tableName);
1349 }
1350 }
1351
1352
1353
1354
1355
1356
1357 @Override
1358 public boolean isTableEnabled(TableName tableName) throws IOException {
1359 checkTableExistence(tableName);
1360 return connection.isTableEnabled(tableName);
1361 }
1362
1363 public boolean isTableEnabled(byte[] tableName) throws IOException {
1364 return isTableEnabled(TableName.valueOf(tableName));
1365 }
1366
1367 public boolean isTableEnabled(String tableName) throws IOException {
1368 return isTableEnabled(TableName.valueOf(tableName));
1369 }
1370
1371
1372
1373
1374
1375
1376
1377
1378 @Override
1379 public boolean isTableDisabled(TableName tableName) throws IOException {
1380 checkTableExistence(tableName);
1381 return connection.isTableDisabled(tableName);
1382 }
1383
1384 public boolean isTableDisabled(byte[] tableName) throws IOException {
1385 return isTableDisabled(TableName.valueOf(tableName));
1386 }
1387
1388 public boolean isTableDisabled(String tableName) throws IOException {
1389 return isTableDisabled(TableName.valueOf(tableName));
1390 }
1391
1392
1393
1394
1395
1396
1397 @Override
1398 public boolean isTableAvailable(TableName tableName) throws IOException {
1399 return connection.isTableAvailable(tableName);
1400 }
1401
1402 public boolean isTableAvailable(byte[] tableName) throws IOException {
1403 return isTableAvailable(TableName.valueOf(tableName));
1404 }
1405
1406 public boolean isTableAvailable(String tableName) throws IOException {
1407 return isTableAvailable(TableName.valueOf(tableName));
1408 }
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422 @Override
1423 public boolean isTableAvailable(TableName tableName,
1424 byte[][] splitKeys) throws IOException {
1425 return connection.isTableAvailable(tableName, splitKeys);
1426 }
1427
1428 public boolean isTableAvailable(byte[] tableName,
1429 byte[][] splitKeys) throws IOException {
1430 return isTableAvailable(TableName.valueOf(tableName), splitKeys);
1431 }
1432
1433 public boolean isTableAvailable(String tableName,
1434 byte[][] splitKeys) throws IOException {
1435 return isTableAvailable(TableName.valueOf(tableName), splitKeys);
1436 }
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449 @Override
1450 public Pair<Integer, Integer> getAlterStatus(final TableName tableName)
1451 throws IOException {
1452 return executeCallable(new MasterCallable<Pair<Integer, Integer>>(getConnection()) {
1453 @Override
1454 public Pair<Integer, Integer> call(int callTimeout) throws ServiceException {
1455 GetSchemaAlterStatusRequest req = RequestConverter
1456 .buildGetSchemaAlterStatusRequest(tableName);
1457 GetSchemaAlterStatusResponse ret = master.getSchemaAlterStatus(null, req);
1458 Pair<Integer, Integer> pair = new Pair<Integer, Integer>(Integer.valueOf(ret
1459 .getYetToUpdateRegions()), Integer.valueOf(ret.getTotalRegions()));
1460 return pair;
1461 }
1462 });
1463 }
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477 @Override
1478 public Pair<Integer, Integer> getAlterStatus(final byte[] tableName)
1479 throws IOException {
1480 return getAlterStatus(TableName.valueOf(tableName));
1481 }
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491 public void addColumn(final byte[] tableName, HColumnDescriptor column)
1492 throws IOException {
1493 addColumn(TableName.valueOf(tableName), column);
1494 }
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505 public void addColumn(final String tableName, HColumnDescriptor column)
1506 throws IOException {
1507 addColumn(TableName.valueOf(tableName), column);
1508 }
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518 @Override
1519 public void addColumn(final TableName tableName, final HColumnDescriptor column)
1520 throws IOException {
1521 executeCallable(new MasterCallable<Void>(getConnection()) {
1522 @Override
1523 public Void call(int callTimeout) throws ServiceException {
1524 AddColumnRequest req = RequestConverter.buildAddColumnRequest(tableName, column);
1525 master.addColumn(null,req);
1526 return null;
1527 }
1528 });
1529 }
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539 public void deleteColumn(final byte[] tableName, final String columnName)
1540 throws IOException {
1541 deleteColumn(TableName.valueOf(tableName), Bytes.toBytes(columnName));
1542 }
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552 public void deleteColumn(final String tableName, final String columnName)
1553 throws IOException {
1554 deleteColumn(TableName.valueOf(tableName), Bytes.toBytes(columnName));
1555 }
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565 @Override
1566 public void deleteColumn(final TableName tableName, final byte [] columnName)
1567 throws IOException {
1568 executeCallable(new MasterCallable<Void>(getConnection()) {
1569 @Override
1570 public Void call(int callTimeout) throws ServiceException {
1571 DeleteColumnRequest req = RequestConverter.buildDeleteColumnRequest(tableName, columnName);
1572 master.deleteColumn(null,req);
1573 return null;
1574 }
1575 });
1576 }
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586 public void modifyColumn(final String tableName, HColumnDescriptor descriptor)
1587 throws IOException {
1588 modifyColumn(TableName.valueOf(tableName), descriptor);
1589 }
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599 public void modifyColumn(final byte[] tableName, HColumnDescriptor descriptor)
1600 throws IOException {
1601 modifyColumn(TableName.valueOf(tableName), descriptor);
1602 }
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614 @Override
1615 public void modifyColumn(final TableName tableName, final HColumnDescriptor descriptor)
1616 throws IOException {
1617 executeCallable(new MasterCallable<Void>(getConnection()) {
1618 @Override
1619 public Void call(int callTimeout) throws ServiceException {
1620 ModifyColumnRequest req = RequestConverter.buildModifyColumnRequest(tableName, descriptor);
1621 master.modifyColumn(null,req);
1622 return null;
1623 }
1624 });
1625 }
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635 @Override
1636 public void closeRegion(final String regionname, final String serverName)
1637 throws IOException {
1638 closeRegion(Bytes.toBytes(regionname), serverName);
1639 }
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651 @Override
1652 public void closeRegion(final byte [] regionname, final String serverName)
1653 throws IOException {
1654 if (serverName != null) {
1655 Pair<HRegionInfo, ServerName> pair = MetaTableAccessor.getRegion(connection, regionname);
1656 if (pair == null || pair.getFirst() == null) {
1657 throw new UnknownRegionException(Bytes.toStringBinary(regionname));
1658 } else {
1659 closeRegion(ServerName.valueOf(serverName), pair.getFirst());
1660 }
1661 } else {
1662 Pair<HRegionInfo, ServerName> pair = MetaTableAccessor.getRegion(connection, regionname);
1663 if (pair == null) {
1664 throw new UnknownRegionException(Bytes.toStringBinary(regionname));
1665 } else if (pair.getSecond() == null) {
1666 throw new NoServerForRegionException(Bytes.toStringBinary(regionname));
1667 } else {
1668 closeRegion(pair.getSecond(), pair.getFirst());
1669 }
1670 }
1671 }
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694 @Override
1695 public boolean closeRegionWithEncodedRegionName(final String encodedRegionName,
1696 final String serverName) throws IOException {
1697 if (null == serverName || ("").equals(serverName.trim())) {
1698 throw new IllegalArgumentException(
1699 "The servername cannot be null or empty.");
1700 }
1701 ServerName sn = ServerName.valueOf(serverName);
1702 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1703
1704 CloseRegionRequest request =
1705 RequestConverter.buildCloseRegionRequest(sn, encodedRegionName, false);
1706 try {
1707 CloseRegionResponse response = admin.closeRegion(null, request);
1708 boolean isRegionClosed = response.getClosed();
1709 if (false == isRegionClosed) {
1710 LOG.error("Not able to close the region " + encodedRegionName + ".");
1711 }
1712 return isRegionClosed;
1713 } catch (ServiceException se) {
1714 throw ProtobufUtil.getRemoteException(se);
1715 }
1716 }
1717
1718
1719
1720
1721
1722
1723
1724
1725 @Override
1726 public void closeRegion(final ServerName sn, final HRegionInfo hri)
1727 throws IOException {
1728 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1729
1730 ProtobufUtil.closeRegion(admin, sn, hri.getRegionName(), false);
1731 }
1732
1733
1734
1735
1736 @Override
1737 public List<HRegionInfo> getOnlineRegions(final ServerName sn) throws IOException {
1738 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1739 return ProtobufUtil.getOnlineRegions(admin);
1740 }
1741
1742
1743
1744
1745 @Override
1746 public void flush(final TableName tableName) throws IOException {
1747 checkTableExists(tableName);
1748 if (isTableDisabled(tableName)) {
1749 LOG.info("Table is disabled: " + tableName.getNameAsString());
1750 return;
1751 }
1752 execProcedure("flush-table-proc", tableName.getNameAsString(),
1753 new HashMap<String, String>());
1754 }
1755
1756
1757
1758
1759 @Override
1760 public void flushRegion(final byte[] regionName) throws IOException {
1761 Pair<HRegionInfo, ServerName> regionServerPair = getRegion(regionName);
1762 if (regionServerPair == null) {
1763 throw new IllegalArgumentException("Unknown regionname: " + Bytes.toStringBinary(regionName));
1764 }
1765 if (regionServerPair.getSecond() == null) {
1766 throw new NoServerForRegionException(Bytes.toStringBinary(regionName));
1767 }
1768 flush(regionServerPair.getSecond(), regionServerPair.getFirst());
1769 }
1770
1771
1772
1773
1774
1775 @Deprecated
1776 public void flush(final String tableNameOrRegionName)
1777 throws IOException, InterruptedException {
1778 flush(Bytes.toBytes(tableNameOrRegionName));
1779 }
1780
1781
1782
1783
1784
1785 @Deprecated
1786 public void flush(final byte[] tableNameOrRegionName)
1787 throws IOException, InterruptedException {
1788 try {
1789 flushRegion(tableNameOrRegionName);
1790 } catch (IllegalArgumentException e) {
1791
1792 flush(TableName.valueOf(tableNameOrRegionName));
1793 }
1794 }
1795
1796 private void flush(final ServerName sn, final HRegionInfo hri)
1797 throws IOException {
1798 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
1799 FlushRegionRequest request =
1800 RequestConverter.buildFlushRegionRequest(hri.getRegionName());
1801 try {
1802 admin.flushRegion(null, request);
1803 } catch (ServiceException se) {
1804 throw ProtobufUtil.getRemoteException(se);
1805 }
1806 }
1807
1808
1809
1810
1811 @Override
1812 public void compact(final TableName tableName)
1813 throws IOException {
1814 compact(tableName, null, false);
1815 }
1816
1817
1818
1819
1820 @Override
1821 public void compactRegion(final byte[] regionName)
1822 throws IOException {
1823 compactRegion(regionName, null, false);
1824 }
1825
1826
1827
1828
1829
1830 @Deprecated
1831 public void compact(final String tableNameOrRegionName)
1832 throws IOException {
1833 compact(Bytes.toBytes(tableNameOrRegionName));
1834 }
1835
1836
1837
1838
1839
1840 @Deprecated
1841 public void compact(final byte[] tableNameOrRegionName)
1842 throws IOException {
1843 try {
1844 compactRegion(tableNameOrRegionName, null, false);
1845 } catch (IllegalArgumentException e) {
1846 compact(TableName.valueOf(tableNameOrRegionName), null, false);
1847 }
1848 }
1849
1850
1851
1852
1853 @Override
1854 public void compact(final TableName tableName, final byte[] columnFamily)
1855 throws IOException {
1856 compact(tableName, columnFamily, false);
1857 }
1858
1859
1860
1861
1862 @Override
1863 public void compactRegion(final byte[] regionName, final byte[] columnFamily)
1864 throws IOException {
1865 compactRegion(regionName, columnFamily, false);
1866 }
1867
1868
1869
1870
1871
1872 @Deprecated
1873 public void compact(String tableOrRegionName, String columnFamily)
1874 throws IOException {
1875 compact(Bytes.toBytes(tableOrRegionName), Bytes.toBytes(columnFamily));
1876 }
1877
1878
1879
1880
1881
1882 @Deprecated
1883 public void compact(final byte[] tableNameOrRegionName, final byte[] columnFamily)
1884 throws IOException {
1885 try {
1886 compactRegion(tableNameOrRegionName, columnFamily, false);
1887 } catch (IllegalArgumentException e) {
1888
1889 compact(TableName.valueOf(tableNameOrRegionName), columnFamily, false);
1890 }
1891 }
1892
1893
1894
1895
1896 @Override
1897 public void compactRegionServer(final ServerName sn, boolean major)
1898 throws IOException, InterruptedException {
1899 for (HRegionInfo region : getOnlineRegions(sn)) {
1900 compact(sn, region, major, null);
1901 }
1902 }
1903
1904
1905
1906
1907 @Override
1908 public void majorCompact(final TableName tableName)
1909 throws IOException {
1910 compact(tableName, null, true);
1911 }
1912
1913
1914
1915
1916 @Override
1917 public void majorCompactRegion(final byte[] regionName)
1918 throws IOException {
1919 compactRegion(regionName, null, true);
1920 }
1921
1922
1923
1924
1925
1926 @Deprecated
1927 public void majorCompact(final String tableNameOrRegionName)
1928 throws IOException {
1929 majorCompact(Bytes.toBytes(tableNameOrRegionName));
1930 }
1931
1932
1933
1934
1935
1936 @Deprecated
1937 public void majorCompact(final byte[] tableNameOrRegionName)
1938 throws IOException {
1939 try {
1940 compactRegion(tableNameOrRegionName, null, true);
1941 } catch (IllegalArgumentException e) {
1942
1943 compact(TableName.valueOf(tableNameOrRegionName), null, true);
1944 }
1945 }
1946
1947
1948
1949
1950 @Override
1951 public void majorCompact(final TableName tableName, final byte[] columnFamily)
1952 throws IOException {
1953 compact(tableName, columnFamily, true);
1954 }
1955
1956
1957
1958
1959 @Override
1960 public void majorCompactRegion(final byte[] regionName, final byte[] columnFamily)
1961 throws IOException {
1962 compactRegion(regionName, columnFamily, true);
1963 }
1964
1965
1966
1967
1968
1969 @Deprecated
1970 public void majorCompact(final String tableNameOrRegionName, final String columnFamily)
1971 throws IOException {
1972 majorCompact(Bytes.toBytes(tableNameOrRegionName), Bytes.toBytes(columnFamily));
1973 }
1974
1975
1976
1977
1978
1979 @Deprecated
1980 public void majorCompact(final byte[] tableNameOrRegionName, final byte[] columnFamily)
1981 throws IOException {
1982 try {
1983 compactRegion(tableNameOrRegionName, columnFamily, true);
1984 } catch (IllegalArgumentException e) {
1985
1986 compact(TableName.valueOf(tableNameOrRegionName), columnFamily, true);
1987 }
1988 }
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000 private void compact(final TableName tableName, final byte[] columnFamily,final boolean major)
2001 throws IOException {
2002 ZooKeeperWatcher zookeeper = null;
2003 try {
2004 checkTableExists(tableName);
2005 zookeeper = new ZooKeeperWatcher(conf, ZK_IDENTIFIER_PREFIX + connection.toString(),
2006 new ThrowableAbortable());
2007 List<Pair<HRegionInfo, ServerName>> pairs =
2008 MetaTableAccessor.getTableRegionsAndLocations(zookeeper, connection, tableName);
2009 for (Pair<HRegionInfo, ServerName> pair: pairs) {
2010 if (pair.getFirst().isOffline()) continue;
2011 if (pair.getSecond() == null) continue;
2012 try {
2013 compact(pair.getSecond(), pair.getFirst(), major, columnFamily);
2014 } catch (NotServingRegionException e) {
2015 if (LOG.isDebugEnabled()) {
2016 LOG.debug("Trying to" + (major ? " major" : "") + " compact " +
2017 pair.getFirst() + ": " +
2018 StringUtils.stringifyException(e));
2019 }
2020 }
2021 }
2022 } finally {
2023 if (zookeeper != null) {
2024 zookeeper.close();
2025 }
2026 }
2027 }
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039 private void compactRegion(final byte[] regionName, final byte[] columnFamily,final boolean major)
2040 throws IOException {
2041 Pair<HRegionInfo, ServerName> regionServerPair = getRegion(regionName);
2042 if (regionServerPair == null) {
2043 throw new IllegalArgumentException("Invalid region: " + Bytes.toStringBinary(regionName));
2044 }
2045 if (regionServerPair.getSecond() == null) {
2046 throw new NoServerForRegionException(Bytes.toStringBinary(regionName));
2047 }
2048 compact(regionServerPair.getSecond(), regionServerPair.getFirst(), major, columnFamily);
2049 }
2050
2051 private void compact(final ServerName sn, final HRegionInfo hri,
2052 final boolean major, final byte [] family)
2053 throws IOException {
2054 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
2055 CompactRegionRequest request =
2056 RequestConverter.buildCompactRegionRequest(hri.getRegionName(), major, family);
2057 try {
2058 admin.compactRegion(null, request);
2059 } catch (ServiceException se) {
2060 throw ProtobufUtil.getRemoteException(se);
2061 }
2062 }
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077 @Override
2078 public void move(final byte [] encodedRegionName, final byte [] destServerName)
2079 throws IOException {
2080
2081 executeCallable(new MasterCallable<Void>(getConnection()) {
2082 @Override
2083 public Void call(int callTimeout) throws ServiceException {
2084 try {
2085 MoveRegionRequest request =
2086 RequestConverter.buildMoveRegionRequest(encodedRegionName, destServerName);
2087 master.moveRegion(null, request);
2088 } catch (DeserializationException de) {
2089 LOG.error("Could not parse destination server name: " + de);
2090 throw new ServiceException(new DoNotRetryIOException(de));
2091 }
2092 return null;
2093 }
2094 });
2095 }
2096
2097
2098
2099
2100
2101
2102
2103
2104 @Override
2105 public void assign(final byte[] regionName) throws MasterNotRunningException,
2106 ZooKeeperConnectionException, IOException {
2107 final byte[] toBeAssigned = getRegionName(regionName);
2108 executeCallable(new MasterCallable<Void>(getConnection()) {
2109 @Override
2110 public Void call(int callTimeout) throws ServiceException {
2111 AssignRegionRequest request =
2112 RequestConverter.buildAssignRegionRequest(toBeAssigned);
2113 master.assignRegion(null,request);
2114 return null;
2115 }
2116 });
2117 }
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133 @Override
2134 public void unassign(final byte [] regionName, final boolean force)
2135 throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
2136 final byte[] toBeUnassigned = getRegionName(regionName);
2137 executeCallable(new MasterCallable<Void>(getConnection()) {
2138 @Override
2139 public Void call(int callTimeout) throws ServiceException {
2140 UnassignRegionRequest request =
2141 RequestConverter.buildUnassignRegionRequest(toBeUnassigned, force);
2142 master.unassignRegion(null, request);
2143 return null;
2144 }
2145 });
2146 }
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160 @Override
2161 public void offline(final byte [] regionName)
2162 throws IOException {
2163 executeCallable(new MasterCallable<Void>(getConnection()) {
2164 @Override
2165 public Void call(int callTimeout) throws ServiceException {
2166 master.offlineRegion(null,RequestConverter.buildOfflineRegionRequest(regionName));
2167 return null;
2168 }
2169 });
2170 }
2171
2172
2173
2174
2175
2176
2177
2178 @Override
2179 public boolean setBalancerRunning(final boolean on, final boolean synchronous)
2180 throws IOException {
2181 return executeCallable(new MasterCallable<Boolean>(getConnection()) {
2182 @Override
2183 public Boolean call(int callTimeout) throws ServiceException {
2184 SetBalancerRunningRequest req =
2185 RequestConverter.buildSetBalancerRunningRequest(on, synchronous);
2186 return master.setBalancerRunning(null, req).getPrevBalanceValue();
2187 }
2188 });
2189 }
2190
2191
2192
2193
2194
2195
2196
2197 @Override
2198 public boolean balancer() throws IOException {
2199 return executeCallable(new MasterCallable<Boolean>(getConnection()) {
2200 @Override
2201 public Boolean call(int callTimeout) throws ServiceException {
2202 return master.balance(null, RequestConverter.buildBalanceRequest()).getBalancerRan();
2203 }
2204 });
2205 }
2206
2207
2208
2209
2210
2211
2212
2213 @Override
2214 public boolean isBalancerEnabled() throws IOException {
2215 return executeCallable(new MasterCallable<Boolean>(getConnection()) {
2216 @Override
2217 public Boolean call(int callTimeout) throws ServiceException {
2218 return master.isBalancerEnabled(null, RequestConverter.buildIsBalancerEnabledRequest())
2219 .getEnabled();
2220 }
2221 });
2222 }
2223
2224
2225
2226
2227
2228
2229
2230 @Override
2231 public boolean enableCatalogJanitor(final boolean enable)
2232 throws IOException {
2233 return executeCallable(new MasterCallable<Boolean>(getConnection()) {
2234 @Override
2235 public Boolean call(int callTimeout) throws ServiceException {
2236 return master.enableCatalogJanitor(null,
2237 RequestConverter.buildEnableCatalogJanitorRequest(enable)).getPrevValue();
2238 }
2239 });
2240 }
2241
2242
2243
2244
2245
2246
2247 @Override
2248 public int runCatalogScan() throws IOException {
2249 return executeCallable(new MasterCallable<Integer>(getConnection()) {
2250 @Override
2251 public Integer call(int callTimeout) throws ServiceException {
2252 return master.runCatalogScan(null,
2253 RequestConverter.buildCatalogScanRequest()).getScanResult();
2254 }
2255 });
2256 }
2257
2258
2259
2260
2261
2262 @Override
2263 public boolean isCatalogJanitorEnabled() throws IOException {
2264 return executeCallable(new MasterCallable<Boolean>(getConnection()) {
2265 @Override
2266 public Boolean call(int callTimeout) throws ServiceException {
2267 return master.isCatalogJanitorEnabled(null,
2268 RequestConverter.buildIsCatalogJanitorEnabledRequest()).getValue();
2269 }
2270 });
2271 }
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281 @Override
2282 public void mergeRegions(final byte[] encodedNameOfRegionA,
2283 final byte[] encodedNameOfRegionB, final boolean forcible)
2284 throws IOException {
2285 Pair<HRegionInfo, ServerName> pair = getRegion(encodedNameOfRegionA);
2286 if (pair != null && pair.getFirst().getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID)
2287 throw new IllegalArgumentException("Can't invoke merge on non-default regions directly");
2288 pair = getRegion(encodedNameOfRegionB);
2289 if (pair != null && pair.getFirst().getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID)
2290 throw new IllegalArgumentException("Can't invoke merge on non-default regions directly");
2291 executeCallable(new MasterCallable<Void>(getConnection()) {
2292 @Override
2293 public Void call(int callTimeout) throws ServiceException {
2294 try {
2295 DispatchMergingRegionsRequest request = RequestConverter
2296 .buildDispatchMergingRegionsRequest(encodedNameOfRegionA,
2297 encodedNameOfRegionB, forcible);
2298 master.dispatchMergingRegions(null, request);
2299 } catch (DeserializationException de) {
2300 LOG.error("Could not parse destination server name: " + de);
2301 }
2302 return null;
2303 }
2304 });
2305 }
2306
2307
2308
2309
2310 @Override
2311 public void split(final TableName tableName)
2312 throws IOException {
2313 split(tableName, null);
2314 }
2315
2316
2317
2318
2319 @Override
2320 public void splitRegion(final byte[] regionName)
2321 throws IOException {
2322 splitRegion(regionName, null);
2323 }
2324
2325
2326
2327
2328
2329 @Deprecated
2330 public void split(final String tableNameOrRegionName)
2331 throws IOException, InterruptedException {
2332 split(Bytes.toBytes(tableNameOrRegionName));
2333 }
2334
2335
2336
2337
2338
2339 @Deprecated
2340 public void split(final byte[] tableNameOrRegionName)
2341 throws IOException, InterruptedException {
2342 split(tableNameOrRegionName, null);
2343 }
2344
2345
2346
2347
2348 @Override
2349 public void split(final TableName tableName, final byte [] splitPoint)
2350 throws IOException {
2351 ZooKeeperWatcher zookeeper = null;
2352 try {
2353 checkTableExists(tableName);
2354 zookeeper = new ZooKeeperWatcher(conf, ZK_IDENTIFIER_PREFIX + connection.toString(),
2355 new ThrowableAbortable());
2356 List<Pair<HRegionInfo, ServerName>> pairs =
2357 MetaTableAccessor.getTableRegionsAndLocations(zookeeper, connection, tableName);
2358 for (Pair<HRegionInfo, ServerName> pair: pairs) {
2359
2360 if (pair.getSecond() == null) continue;
2361 HRegionInfo r = pair.getFirst();
2362
2363 if (r.isSplitParent()) continue;
2364
2365 if (r.getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID ||
2366 (splitPoint != null && !r.containsRow(splitPoint))) continue;
2367
2368 split(pair.getSecond(), pair.getFirst(), splitPoint);
2369 }
2370 } finally {
2371 if (zookeeper != null) {
2372 zookeeper.close();
2373 }
2374 }
2375 }
2376
2377
2378
2379
2380 @Override
2381 public void splitRegion(final byte[] regionName, final byte [] splitPoint)
2382 throws IOException {
2383 Pair<HRegionInfo, ServerName> regionServerPair = getRegion(regionName);
2384 if (regionServerPair == null) {
2385 throw new IllegalArgumentException("Invalid region: " + Bytes.toStringBinary(regionName));
2386 }
2387 if (regionServerPair.getFirst() != null &&
2388 regionServerPair.getFirst().getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID) {
2389 throw new IllegalArgumentException("Can't split replicas directly. "
2390 + "Replicas are auto-split when their primary is split.");
2391 }
2392 if (regionServerPair.getSecond() == null) {
2393 throw new NoServerForRegionException(Bytes.toStringBinary(regionName));
2394 }
2395 split(regionServerPair.getSecond(), regionServerPair.getFirst(), splitPoint);
2396 }
2397
2398
2399
2400
2401
2402 @Deprecated
2403 public void split(final String tableNameOrRegionName,
2404 final String splitPoint) throws IOException {
2405 split(Bytes.toBytes(tableNameOrRegionName), Bytes.toBytes(splitPoint));
2406 }
2407
2408
2409
2410
2411
2412 @Deprecated
2413 public void split(final byte[] tableNameOrRegionName,
2414 final byte [] splitPoint) throws IOException {
2415 try {
2416 splitRegion(tableNameOrRegionName, splitPoint);
2417 } catch (IllegalArgumentException e) {
2418
2419 split(TableName.valueOf(tableNameOrRegionName), splitPoint);
2420 }
2421 }
2422
2423 @VisibleForTesting
2424 public void split(final ServerName sn, final HRegionInfo hri,
2425 byte[] splitPoint) throws IOException {
2426 if (hri.getStartKey() != null && splitPoint != null &&
2427 Bytes.compareTo(hri.getStartKey(), splitPoint) == 0) {
2428 throw new IOException("should not give a splitkey which equals to startkey!");
2429 }
2430
2431 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
2432 ProtobufUtil.split(admin, hri, splitPoint);
2433 }
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444 @Override
2445 public void modifyTable(final TableName tableName, final HTableDescriptor htd)
2446 throws IOException {
2447 if (!tableName.equals(htd.getTableName())) {
2448 throw new IllegalArgumentException("the specified table name '" + tableName +
2449 "' doesn't match with the HTD one: " + htd.getTableName());
2450 }
2451
2452 executeCallable(new MasterCallable<Void>(getConnection()) {
2453 @Override
2454 public Void call(int callTimeout) throws ServiceException {
2455 ModifyTableRequest request = RequestConverter.buildModifyTableRequest(tableName, htd);
2456 master.modifyTable(null, request);
2457 return null;
2458 }
2459 });
2460 }
2461
2462 public void modifyTable(final byte[] tableName, final HTableDescriptor htd)
2463 throws IOException {
2464 modifyTable(TableName.valueOf(tableName), htd);
2465 }
2466
2467 public void modifyTable(final String tableName, final HTableDescriptor htd)
2468 throws IOException {
2469 modifyTable(TableName.valueOf(tableName), htd);
2470 }
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481 Pair<HRegionInfo, ServerName> getRegion(final byte[] regionName) throws IOException {
2482 if (regionName == null) {
2483 throw new IllegalArgumentException("Pass a table name or region name");
2484 }
2485 Pair<HRegionInfo, ServerName> pair =
2486 MetaTableAccessor.getRegion(connection, regionName);
2487 if (pair == null) {
2488 final AtomicReference<Pair<HRegionInfo, ServerName>> result =
2489 new AtomicReference<Pair<HRegionInfo, ServerName>>(null);
2490 final String encodedName = Bytes.toString(regionName);
2491 MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
2492 @Override
2493 public boolean processRow(Result data) throws IOException {
2494 HRegionInfo info = HRegionInfo.getHRegionInfo(data);
2495 if (info == null) {
2496 LOG.warn("No serialized HRegionInfo in " + data);
2497 return true;
2498 }
2499 RegionLocations rl = MetaTableAccessor.getRegionLocations(data);
2500 boolean matched = false;
2501 ServerName sn = null;
2502 for (HRegionLocation h : rl.getRegionLocations()) {
2503 if (h != null && encodedName.equals(h.getRegionInfo().getEncodedName())) {
2504 sn = h.getServerName();
2505 info = h.getRegionInfo();
2506 matched = true;
2507 }
2508 }
2509 if (!matched) return true;
2510 result.set(new Pair<HRegionInfo, ServerName>(info, sn));
2511 return false;
2512 }
2513 };
2514
2515 MetaScanner.metaScan(connection, visitor, null);
2516 pair = result.get();
2517 }
2518 return pair;
2519 }
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529 private byte[] getRegionName(
2530 final byte[] regionNameOrEncodedRegionName) throws IOException {
2531 if (Bytes.equals(regionNameOrEncodedRegionName,
2532 HRegionInfo.FIRST_META_REGIONINFO.getRegionName())
2533 || Bytes.equals(regionNameOrEncodedRegionName,
2534 HRegionInfo.FIRST_META_REGIONINFO.getEncodedNameAsBytes())) {
2535 return HRegionInfo.FIRST_META_REGIONINFO.getRegionName();
2536 }
2537 byte[] tmp = regionNameOrEncodedRegionName;
2538 Pair<HRegionInfo, ServerName> regionServerPair = getRegion(regionNameOrEncodedRegionName);
2539 if (regionServerPair != null && regionServerPair.getFirst() != null) {
2540 tmp = regionServerPair.getFirst().getRegionName();
2541 }
2542 return tmp;
2543 }
2544
2545
2546
2547
2548
2549
2550
2551
2552 private TableName checkTableExists(final TableName tableName)
2553 throws IOException {
2554 if (!MetaTableAccessor.tableExists(connection, tableName)) {
2555 throw new TableNotFoundException(tableName);
2556 }
2557 return tableName;
2558 }
2559
2560
2561
2562
2563
2564 @Override
2565 public synchronized void shutdown() throws IOException {
2566 executeCallable(new MasterCallable<Void>(getConnection()) {
2567 @Override
2568 public Void call(int callTimeout) throws ServiceException {
2569 master.shutdown(null,ShutdownRequest.newBuilder().build());
2570 return null;
2571 }
2572 });
2573 }
2574
2575
2576
2577
2578
2579
2580
2581 @Override
2582 public synchronized void stopMaster() throws IOException {
2583 executeCallable(new MasterCallable<Void>(getConnection()) {
2584 @Override
2585 public Void call(int callTimeout) throws ServiceException {
2586 master.stopMaster(null, StopMasterRequest.newBuilder().build());
2587 return null;
2588 }
2589 });
2590 }
2591
2592
2593
2594
2595
2596
2597
2598 @Override
2599 public synchronized void stopRegionServer(final String hostnamePort)
2600 throws IOException {
2601 String hostname = Addressing.parseHostname(hostnamePort);
2602 int port = Addressing.parsePort(hostnamePort);
2603 AdminService.BlockingInterface admin =
2604 this.connection.getAdmin(ServerName.valueOf(hostname, port, 0));
2605 StopServerRequest request = RequestConverter.buildStopServerRequest(
2606 "Called by admin client " + this.connection.toString());
2607 try {
2608 admin.stopServer(null, request);
2609 } catch (ServiceException se) {
2610 throw ProtobufUtil.getRemoteException(se);
2611 }
2612 }
2613
2614
2615
2616
2617
2618
2619 @Override
2620 public ClusterStatus getClusterStatus() throws IOException {
2621 return executeCallable(new MasterCallable<ClusterStatus>(getConnection()) {
2622 @Override
2623 public ClusterStatus call(int callTimeout) throws ServiceException {
2624 GetClusterStatusRequest req = RequestConverter.buildGetClusterStatusRequest();
2625 return ClusterStatus.convert(master.getClusterStatus(null, req).getClusterStatus());
2626 }
2627 });
2628 }
2629
2630
2631
2632
2633 @Override
2634 public Configuration getConfiguration() {
2635 return this.conf;
2636 }
2637
2638
2639
2640
2641
2642
2643 @Override
2644 public void createNamespace(final NamespaceDescriptor descriptor) throws IOException {
2645 executeCallable(new MasterCallable<Void>(getConnection()) {
2646 @Override
2647 public Void call(int callTimeout) throws Exception {
2648 master.createNamespace(null,
2649 CreateNamespaceRequest.newBuilder()
2650 .setNamespaceDescriptor(ProtobufUtil
2651 .toProtoNamespaceDescriptor(descriptor)).build()
2652 );
2653 return null;
2654 }
2655 });
2656 }
2657
2658
2659
2660
2661
2662
2663 @Override
2664 public void modifyNamespace(final NamespaceDescriptor descriptor) throws IOException {
2665 executeCallable(new MasterCallable<Void>(getConnection()) {
2666 @Override
2667 public Void call(int callTimeout) throws Exception {
2668 master.modifyNamespace(null, ModifyNamespaceRequest.newBuilder().
2669 setNamespaceDescriptor(ProtobufUtil.toProtoNamespaceDescriptor(descriptor)).build());
2670 return null;
2671 }
2672 });
2673 }
2674
2675
2676
2677
2678
2679
2680 @Override
2681 public void deleteNamespace(final String name) throws IOException {
2682 executeCallable(new MasterCallable<Void>(getConnection()) {
2683 @Override
2684 public Void call(int callTimeout) throws Exception {
2685 master.deleteNamespace(null, DeleteNamespaceRequest.newBuilder().
2686 setNamespaceName(name).build());
2687 return null;
2688 }
2689 });
2690 }
2691
2692
2693
2694
2695
2696
2697
2698 @Override
2699 public NamespaceDescriptor getNamespaceDescriptor(final String name) throws IOException {
2700 return
2701 executeCallable(new MasterCallable<NamespaceDescriptor>(getConnection()) {
2702 @Override
2703 public NamespaceDescriptor call(int callTimeout) throws Exception {
2704 return ProtobufUtil.toNamespaceDescriptor(
2705 master.getNamespaceDescriptor(null, GetNamespaceDescriptorRequest.newBuilder().
2706 setNamespaceName(name).build()).getNamespaceDescriptor());
2707 }
2708 });
2709 }
2710
2711
2712
2713
2714
2715
2716 @Override
2717 public NamespaceDescriptor[] listNamespaceDescriptors() throws IOException {
2718 return
2719 executeCallable(new MasterCallable<NamespaceDescriptor[]>(getConnection()) {
2720 @Override
2721 public NamespaceDescriptor[] call(int callTimeout) throws Exception {
2722 List<HBaseProtos.NamespaceDescriptor> list =
2723 master.listNamespaceDescriptors(null, ListNamespaceDescriptorsRequest.newBuilder().
2724 build()).getNamespaceDescriptorList();
2725 NamespaceDescriptor[] res = new NamespaceDescriptor[list.size()];
2726 for(int i = 0; i < list.size(); i++) {
2727 res[i] = ProtobufUtil.toNamespaceDescriptor(list.get(i));
2728 }
2729 return res;
2730 }
2731 });
2732 }
2733
2734
2735
2736
2737
2738
2739
2740 @Override
2741 public HTableDescriptor[] listTableDescriptorsByNamespace(final String name) throws IOException {
2742 return
2743 executeCallable(new MasterCallable<HTableDescriptor[]>(getConnection()) {
2744 @Override
2745 public HTableDescriptor[] call(int callTimeout) throws Exception {
2746 List<TableSchema> list =
2747 master.listTableDescriptorsByNamespace(null, ListTableDescriptorsByNamespaceRequest.
2748 newBuilder().setNamespaceName(name).build()).getTableSchemaList();
2749 HTableDescriptor[] res = new HTableDescriptor[list.size()];
2750 for(int i=0; i < list.size(); i++) {
2751
2752 res[i] = HTableDescriptor.convert(list.get(i));
2753 }
2754 return res;
2755 }
2756 });
2757 }
2758
2759
2760
2761
2762
2763
2764
2765 @Override
2766 public TableName[] listTableNamesByNamespace(final String name) throws IOException {
2767 return
2768 executeCallable(new MasterCallable<TableName[]>(getConnection()) {
2769 @Override
2770 public TableName[] call(int callTimeout) throws Exception {
2771 List<HBaseProtos.TableName> tableNames =
2772 master.listTableNamesByNamespace(null, ListTableNamesByNamespaceRequest.
2773 newBuilder().setNamespaceName(name).build())
2774 .getTableNameList();
2775 TableName[] result = new TableName[tableNames.size()];
2776 for (int i = 0; i < tableNames.size(); i++) {
2777 result[i] = ProtobufUtil.toTableName(tableNames.get(i));
2778 }
2779 return result;
2780 }
2781 });
2782 }
2783
2784
2785
2786
2787
2788
2789
2790
2791 public static void checkHBaseAvailable(Configuration conf)
2792 throws MasterNotRunningException, ZooKeeperConnectionException, ServiceException, IOException {
2793 Configuration copyOfConf = HBaseConfiguration.create(conf);
2794
2795 copyOfConf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1);
2796 copyOfConf.setInt("zookeeper.recovery.retry", 0);
2797 try (ClusterConnection connection =
2798 (ClusterConnection)ConnectionFactory.createConnection(copyOfConf)) {
2799
2800
2801 ZooKeeperKeepAliveConnection zkw = null;
2802 try {
2803
2804 zkw = ((ConnectionManager.HConnectionImplementation)connection).
2805 getKeepAliveZooKeeperWatcher();
2806 zkw.getRecoverableZooKeeper().getZooKeeper().exists(zkw.baseZNode, false);
2807 } catch (IOException e) {
2808 throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
2809 } catch (InterruptedException e) {
2810 throw (InterruptedIOException)
2811 new InterruptedIOException("Can't connect to ZooKeeper").initCause(e);
2812 } catch (KeeperException e) {
2813 throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
2814 } finally {
2815 if (zkw != null) {
2816 zkw.close();
2817 }
2818 }
2819 connection.isMasterRunning();
2820 }
2821 }
2822
2823
2824
2825
2826
2827
2828
2829
2830 @Override
2831 public List<HRegionInfo> getTableRegions(final TableName tableName)
2832 throws IOException {
2833 ZooKeeperWatcher zookeeper =
2834 new ZooKeeperWatcher(conf, ZK_IDENTIFIER_PREFIX + connection.toString(),
2835 new ThrowableAbortable());
2836 List<HRegionInfo> Regions = null;
2837 try {
2838 Regions = MetaTableAccessor.getTableRegions(zookeeper, connection, tableName, true);
2839 } finally {
2840 zookeeper.close();
2841 }
2842 return Regions;
2843 }
2844
2845 public List<HRegionInfo> getTableRegions(final byte[] tableName)
2846 throws IOException {
2847 return getTableRegions(TableName.valueOf(tableName));
2848 }
2849
2850 @Override
2851 public synchronized void close() throws IOException {
2852 if (cleanupConnectionOnClose && this.connection != null && !this.closed) {
2853 this.connection.close();
2854 this.closed = true;
2855 }
2856 }
2857
2858
2859
2860
2861
2862
2863
2864 @Override
2865 public HTableDescriptor[] getTableDescriptorsByTableName(final List<TableName> tableNames)
2866 throws IOException {
2867 return executeCallable(new MasterCallable<HTableDescriptor[]>(getConnection()) {
2868 @Override
2869 public HTableDescriptor[] call(int callTimeout) throws Exception {
2870 GetTableDescriptorsRequest req =
2871 RequestConverter.buildGetTableDescriptorsRequest(tableNames);
2872 return ProtobufUtil.getHTableDescriptorArray(master.getTableDescriptors(null, req));
2873 }
2874 });
2875 }
2876
2877
2878
2879
2880
2881
2882
2883 private HTableDescriptor getTableDescriptorByTableName(TableName tableName)
2884 throws IOException {
2885 List<TableName> tableNames = new ArrayList<TableName>(1);
2886 tableNames.add(tableName);
2887
2888 HTableDescriptor[] htdl = getTableDescriptorsByTableName(tableNames);
2889
2890 if (htdl == null || htdl.length == 0) {
2891 return null;
2892 }
2893 else {
2894 return htdl[0];
2895 }
2896 }
2897
2898
2899
2900
2901
2902
2903
2904 @Override
2905 public HTableDescriptor[] getTableDescriptors(List<String> names)
2906 throws IOException {
2907 List<TableName> tableNames = new ArrayList<TableName>(names.size());
2908 for(String name : names) {
2909 tableNames.add(TableName.valueOf(name));
2910 }
2911 return getTableDescriptorsByTableName(tableNames);
2912 }
2913
2914 private RollWALWriterResponse rollWALWriterImpl(final ServerName sn) throws IOException,
2915 FailedLogCloseException {
2916 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
2917 RollWALWriterRequest request = RequestConverter.buildRollWALWriterRequest();
2918 try {
2919 return admin.rollWALWriter(null, request);
2920 } catch (ServiceException se) {
2921 throw ProtobufUtil.getRemoteException(se);
2922 }
2923 }
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947 @Deprecated
2948 public synchronized byte[][] rollHLogWriter(String serverName)
2949 throws IOException, FailedLogCloseException {
2950 ServerName sn = ServerName.valueOf(serverName);
2951 final RollWALWriterResponse response = rollWALWriterImpl(sn);
2952 int regionCount = response.getRegionToFlushCount();
2953 if (0 == regionCount) {
2954 return null;
2955 }
2956 byte[][] regionsToFlush = new byte[regionCount][];
2957 for (int i = 0; i < regionCount; i++) {
2958 ByteString region = response.getRegionToFlush(i);
2959 regionsToFlush[i] = region.toByteArray();
2960 }
2961 return regionsToFlush;
2962 }
2963
2964 @Override
2965 public synchronized void rollWALWriter(ServerName serverName)
2966 throws IOException, FailedLogCloseException {
2967 rollWALWriterImpl(serverName);
2968 }
2969
2970 @Override
2971 public String[] getMasterCoprocessors() {
2972 try {
2973 return getClusterStatus().getMasterCoprocessors();
2974 } catch (IOException e) {
2975 LOG.error("Could not getClusterStatus()",e);
2976 return null;
2977 }
2978 }
2979
2980
2981
2982
2983 @Override
2984 public CompactionState getCompactionState(final TableName tableName)
2985 throws IOException {
2986 CompactionState state = CompactionState.NONE;
2987 ZooKeeperWatcher zookeeper =
2988 new ZooKeeperWatcher(conf, ZK_IDENTIFIER_PREFIX + connection.toString(),
2989 new ThrowableAbortable());
2990 try {
2991 checkTableExists(tableName);
2992 List<Pair<HRegionInfo, ServerName>> pairs =
2993 MetaTableAccessor.getTableRegionsAndLocations(zookeeper, connection, tableName);
2994 for (Pair<HRegionInfo, ServerName> pair: pairs) {
2995 if (pair.getFirst().isOffline()) continue;
2996 if (pair.getSecond() == null) continue;
2997 try {
2998 ServerName sn = pair.getSecond();
2999 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
3000 GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest(
3001 pair.getFirst().getRegionName(), true);
3002 GetRegionInfoResponse response = admin.getRegionInfo(null, request);
3003 switch (response.getCompactionState()) {
3004 case MAJOR_AND_MINOR:
3005 return CompactionState.MAJOR_AND_MINOR;
3006 case MAJOR:
3007 if (state == CompactionState.MINOR) {
3008 return CompactionState.MAJOR_AND_MINOR;
3009 }
3010 state = CompactionState.MAJOR;
3011 break;
3012 case MINOR:
3013 if (state == CompactionState.MAJOR) {
3014 return CompactionState.MAJOR_AND_MINOR;
3015 }
3016 state = CompactionState.MINOR;
3017 break;
3018 case NONE:
3019 default:
3020 }
3021 } catch (NotServingRegionException e) {
3022 if (LOG.isDebugEnabled()) {
3023 LOG.debug("Trying to get compaction state of " +
3024 pair.getFirst() + ": " +
3025 StringUtils.stringifyException(e));
3026 }
3027 } catch (RemoteException e) {
3028 if (e.getMessage().indexOf(NotServingRegionException.class.getName()) >= 0) {
3029 if (LOG.isDebugEnabled()) {
3030 LOG.debug("Trying to get compaction state of " + pair.getFirst() + ": "
3031 + StringUtils.stringifyException(e));
3032 }
3033 } else {
3034 throw e;
3035 }
3036 }
3037 }
3038 } catch (ServiceException se) {
3039 throw ProtobufUtil.getRemoteException(se);
3040 } finally {
3041 zookeeper.close();
3042 }
3043 return state;
3044 }
3045
3046
3047
3048
3049 @Override
3050 public CompactionState getCompactionStateForRegion(final byte[] regionName)
3051 throws IOException {
3052 try {
3053 Pair<HRegionInfo, ServerName> regionServerPair = getRegion(regionName);
3054 if (regionServerPair == null) {
3055 throw new IllegalArgumentException("Invalid region: " + Bytes.toStringBinary(regionName));
3056 }
3057 if (regionServerPair.getSecond() == null) {
3058 throw new NoServerForRegionException(Bytes.toStringBinary(regionName));
3059 }
3060 ServerName sn = regionServerPair.getSecond();
3061 AdminService.BlockingInterface admin = this.connection.getAdmin(sn);
3062 GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest(
3063 regionServerPair.getFirst().getRegionName(), true);
3064 GetRegionInfoResponse response = admin.getRegionInfo(null, request);
3065 return response.getCompactionState();
3066 } catch (ServiceException se) {
3067 throw ProtobufUtil.getRemoteException(se);
3068 }
3069 }
3070
3071
3072
3073
3074
3075 @Deprecated
3076 public CompactionState getCompactionState(final String tableNameOrRegionName)
3077 throws IOException, InterruptedException {
3078 return getCompactionState(Bytes.toBytes(tableNameOrRegionName));
3079 }
3080
3081
3082
3083
3084
3085 @Deprecated
3086 public CompactionState getCompactionState(final byte[] tableNameOrRegionName)
3087 throws IOException, InterruptedException {
3088 try {
3089 return getCompactionStateForRegion(tableNameOrRegionName);
3090 } catch (IllegalArgumentException e) {
3091
3092 return getCompactionState(TableName.valueOf(tableNameOrRegionName));
3093 }
3094 }
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112 @Override
3113 public void snapshot(final String snapshotName,
3114 final TableName tableName) throws IOException,
3115 SnapshotCreationException, IllegalArgumentException {
3116 snapshot(snapshotName, tableName, SnapshotDescription.Type.FLUSH);
3117 }
3118
3119 public void snapshot(final String snapshotName,
3120 final String tableName) throws IOException,
3121 SnapshotCreationException, IllegalArgumentException {
3122 snapshot(snapshotName, TableName.valueOf(tableName),
3123 SnapshotDescription.Type.FLUSH);
3124 }
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141 public void snapshot(final byte[] snapshotName, final byte[] tableName,
3142 final SnapshotDescription.Type flushType) throws
3143 IOException, SnapshotCreationException, IllegalArgumentException {
3144 snapshot(Bytes.toString(snapshotName), Bytes.toString(tableName), flushType);
3145 }
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162 @Override
3163 public void snapshot(final byte[] snapshotName,
3164 final TableName tableName) throws IOException,
3165 SnapshotCreationException, IllegalArgumentException {
3166 snapshot(Bytes.toString(snapshotName), tableName, SnapshotDescription.Type.FLUSH);
3167 }
3168
3169 public void snapshot(final byte[] snapshotName,
3170 final byte[] tableName) throws IOException,
3171 SnapshotCreationException, IllegalArgumentException {
3172 snapshot(Bytes.toString(snapshotName), TableName.valueOf(tableName),
3173 SnapshotDescription.Type.FLUSH);
3174 }
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194 @Override
3195 public void snapshot(final String snapshotName,
3196 final TableName tableName,
3197 SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
3198 IllegalArgumentException {
3199 SnapshotDescription.Builder builder = SnapshotDescription.newBuilder();
3200 builder.setTable(tableName.getNameAsString());
3201 builder.setName(snapshotName);
3202 builder.setType(type);
3203 snapshot(builder.build());
3204 }
3205
3206 public void snapshot(final String snapshotName,
3207 final String tableName,
3208 SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
3209 IllegalArgumentException {
3210 snapshot(snapshotName, TableName.valueOf(tableName), type);
3211 }
3212
3213 public void snapshot(final String snapshotName,
3214 final byte[] tableName,
3215 SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
3216 IllegalArgumentException {
3217 snapshot(snapshotName, TableName.valueOf(tableName), type);
3218 }
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241 @Override
3242 public void snapshot(SnapshotDescription snapshot) throws IOException, SnapshotCreationException,
3243 IllegalArgumentException {
3244
3245 SnapshotResponse response = takeSnapshotAsync(snapshot);
3246 final IsSnapshotDoneRequest request = IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot)
3247 .build();
3248 IsSnapshotDoneResponse done = null;
3249 long start = EnvironmentEdgeManager.currentTime();
3250 long max = response.getExpectedTimeout();
3251 long maxPauseTime = max / this.numRetries;
3252 int tries = 0;
3253 LOG.debug("Waiting a max of " + max + " ms for snapshot '" +
3254 ClientSnapshotDescriptionUtils.toString(snapshot) + "'' to complete. (max " +
3255 maxPauseTime + " ms per retry)");
3256 while (tries == 0
3257 || ((EnvironmentEdgeManager.currentTime() - start) < max && !done.getDone())) {
3258 try {
3259
3260 long sleep = getPauseTime(tries++);
3261 sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
3262 LOG.debug("(#" + tries + ") Sleeping: " + sleep +
3263 "ms while waiting for snapshot completion.");
3264 Thread.sleep(sleep);
3265 } catch (InterruptedException e) {
3266 throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
3267 }
3268 LOG.debug("Getting current status of snapshot from master...");
3269 done = executeCallable(new MasterCallable<IsSnapshotDoneResponse>(getConnection()) {
3270 @Override
3271 public IsSnapshotDoneResponse call(int callTimeout) throws ServiceException {
3272 return master.isSnapshotDone(null, request);
3273 }
3274 });
3275 }
3276 if (!done.getDone()) {
3277 throw new SnapshotCreationException("Snapshot '" + snapshot.getName()
3278 + "' wasn't completed in expectedTime:" + max + " ms", snapshot);
3279 }
3280 }
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292 @Override
3293 public SnapshotResponse takeSnapshotAsync(SnapshotDescription snapshot) throws IOException,
3294 SnapshotCreationException {
3295 ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
3296 final SnapshotRequest request = SnapshotRequest.newBuilder().setSnapshot(snapshot)
3297 .build();
3298
3299 return executeCallable(new MasterCallable<SnapshotResponse>(getConnection()) {
3300 @Override
3301 public SnapshotResponse call(int callTimeout) throws ServiceException {
3302 return master.snapshot(null, request);
3303 }
3304 });
3305 }
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327 @Override
3328 public boolean isSnapshotFinished(final SnapshotDescription snapshot)
3329 throws IOException, HBaseSnapshotException, UnknownSnapshotException {
3330
3331 return executeCallable(new MasterCallable<IsSnapshotDoneResponse>(getConnection()) {
3332 @Override
3333 public IsSnapshotDoneResponse call(int callTimeout) throws ServiceException {
3334 return master.isSnapshotDone(null,
3335 IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot).build());
3336 }
3337 }).getDone();
3338 }
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353 @Override
3354 public void restoreSnapshot(final byte[] snapshotName)
3355 throws IOException, RestoreSnapshotException {
3356 restoreSnapshot(Bytes.toString(snapshotName));
3357 }
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372 @Override
3373 public void restoreSnapshot(final String snapshotName)
3374 throws IOException, RestoreSnapshotException {
3375 boolean takeFailSafeSnapshot =
3376 conf.getBoolean("hbase.snapshot.restore.take.failsafe.snapshot", false);
3377 restoreSnapshot(snapshotName, takeFailSafeSnapshot);
3378 }
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396 @Override
3397 public void restoreSnapshot(final byte[] snapshotName, final boolean takeFailSafeSnapshot)
3398 throws IOException, RestoreSnapshotException {
3399 restoreSnapshot(Bytes.toString(snapshotName), takeFailSafeSnapshot);
3400 }
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418 @Override
3419 public void restoreSnapshot(final String snapshotName, boolean takeFailSafeSnapshot)
3420 throws IOException, RestoreSnapshotException {
3421 TableName tableName = null;
3422 for (SnapshotDescription snapshotInfo: listSnapshots()) {
3423 if (snapshotInfo.getName().equals(snapshotName)) {
3424 tableName = TableName.valueOf(snapshotInfo.getTable());
3425 break;
3426 }
3427 }
3428
3429 if (tableName == null) {
3430 throw new RestoreSnapshotException(
3431 "Unable to find the table name for snapshot=" + snapshotName);
3432 }
3433
3434
3435 if (!tableExists(tableName)) {
3436 cloneSnapshot(snapshotName, tableName);
3437 return;
3438 }
3439
3440
3441 if (!isTableDisabled(tableName)) {
3442 throw new TableNotDisabledException(tableName);
3443 }
3444
3445
3446 String failSafeSnapshotSnapshotName = null;
3447 if (takeFailSafeSnapshot) {
3448 failSafeSnapshotSnapshotName = conf.get("hbase.snapshot.restore.failsafe.name",
3449 "hbase-failsafe-{snapshot.name}-{restore.timestamp}");
3450 failSafeSnapshotSnapshotName = failSafeSnapshotSnapshotName
3451 .replace("{snapshot.name}", snapshotName)
3452 .replace("{table.name}", tableName.toString().replace(TableName.NAMESPACE_DELIM, '.'))
3453 .replace("{restore.timestamp}", String.valueOf(EnvironmentEdgeManager.currentTime()));
3454 LOG.info("Taking restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
3455 snapshot(failSafeSnapshotSnapshotName, tableName);
3456 }
3457
3458 try {
3459
3460 internalRestoreSnapshot(snapshotName, tableName);
3461 } catch (IOException e) {
3462
3463
3464 if (takeFailSafeSnapshot) {
3465 try {
3466 internalRestoreSnapshot(failSafeSnapshotSnapshotName, tableName);
3467 String msg = "Restore snapshot=" + snapshotName +
3468 " failed. Rollback to snapshot=" + failSafeSnapshotSnapshotName + " succeeded.";
3469 LOG.error(msg, e);
3470 throw new RestoreSnapshotException(msg, e);
3471 } catch (IOException ex) {
3472 String msg = "Failed to restore and rollback to snapshot=" + failSafeSnapshotSnapshotName;
3473 LOG.error(msg, ex);
3474 throw new RestoreSnapshotException(msg, e);
3475 }
3476 } else {
3477 throw new RestoreSnapshotException("Failed to restore snapshot=" + snapshotName, e);
3478 }
3479 }
3480
3481
3482 if (takeFailSafeSnapshot) {
3483 try {
3484 LOG.info("Deleting restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
3485 deleteSnapshot(failSafeSnapshotSnapshotName);
3486 } catch (IOException e) {
3487 LOG.error("Unable to remove the failsafe snapshot: " + failSafeSnapshotSnapshotName, e);
3488 }
3489 }
3490 }
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502 public void cloneSnapshot(final byte[] snapshotName, final byte[] tableName)
3503 throws IOException, TableExistsException, RestoreSnapshotException {
3504 cloneSnapshot(Bytes.toString(snapshotName), TableName.valueOf(tableName));
3505 }
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517 @Override
3518 public void cloneSnapshot(final byte[] snapshotName, final TableName tableName)
3519 throws IOException, TableExistsException, RestoreSnapshotException {
3520 cloneSnapshot(Bytes.toString(snapshotName), tableName);
3521 }
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535 public void cloneSnapshot(final String snapshotName, final String tableName)
3536 throws IOException, TableExistsException, RestoreSnapshotException, InterruptedException {
3537 cloneSnapshot(snapshotName, TableName.valueOf(tableName));
3538 }
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550 @Override
3551 public void cloneSnapshot(final String snapshotName, final TableName tableName)
3552 throws IOException, TableExistsException, RestoreSnapshotException {
3553 if (tableExists(tableName)) {
3554 throw new TableExistsException(tableName);
3555 }
3556 internalRestoreSnapshot(snapshotName, tableName);
3557 waitUntilTableIsEnabled(tableName);
3558 }
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571 @Override
3572 public byte[] execProcedureWithRet(String signature, String instance,
3573 Map<String, String> props) throws IOException {
3574 ProcedureDescription.Builder builder = ProcedureDescription.newBuilder();
3575 builder.setSignature(signature).setInstance(instance);
3576 for (Entry<String, String> entry : props.entrySet()) {
3577 NameStringPair pair = NameStringPair.newBuilder().setName(entry.getKey())
3578 .setValue(entry.getValue()).build();
3579 builder.addConfiguration(pair);
3580 }
3581
3582 final ExecProcedureRequest request = ExecProcedureRequest.newBuilder()
3583 .setProcedure(builder.build()).build();
3584
3585 ExecProcedureResponse response = executeCallable(new MasterCallable<ExecProcedureResponse>(
3586 getConnection()) {
3587 @Override
3588 public ExecProcedureResponse call(int callTimeout) throws ServiceException {
3589 return master.execProcedureWithRet(null, request);
3590 }
3591 });
3592
3593 return response.hasReturnData() ? response.getReturnData().toByteArray() : null;
3594 }
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605 @Override
3606 public void execProcedure(String signature, String instance,
3607 Map<String, String> props) throws IOException {
3608 ProcedureDescription.Builder builder = ProcedureDescription.newBuilder();
3609 builder.setSignature(signature).setInstance(instance);
3610 for (Entry<String, String> entry : props.entrySet()) {
3611 NameStringPair pair = NameStringPair.newBuilder().setName(entry.getKey())
3612 .setValue(entry.getValue()).build();
3613 builder.addConfiguration(pair);
3614 }
3615
3616 final ExecProcedureRequest request = ExecProcedureRequest.newBuilder()
3617 .setProcedure(builder.build()).build();
3618
3619 ExecProcedureResponse response = executeCallable(new MasterCallable<ExecProcedureResponse>(
3620 getConnection()) {
3621 @Override
3622 public ExecProcedureResponse call(int callTimeout) throws ServiceException {
3623 return master.execProcedure(null, request);
3624 }
3625 });
3626
3627 long start = EnvironmentEdgeManager.currentTime();
3628 long max = response.getExpectedTimeout();
3629 long maxPauseTime = max / this.numRetries;
3630 int tries = 0;
3631 LOG.debug("Waiting a max of " + max + " ms for procedure '" +
3632 signature + " : " + instance + "'' to complete. (max " + maxPauseTime + " ms per retry)");
3633 boolean done = false;
3634 while (tries == 0
3635 || ((EnvironmentEdgeManager.currentTime() - start) < max && !done)) {
3636 try {
3637
3638 long sleep = getPauseTime(tries++);
3639 sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
3640 LOG.debug("(#" + tries + ") Sleeping: " + sleep +
3641 "ms while waiting for procedure completion.");
3642 Thread.sleep(sleep);
3643 } catch (InterruptedException e) {
3644 throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
3645 }
3646 LOG.debug("Getting current status of procedure from master...");
3647 done = isProcedureFinished(signature, instance, props);
3648 }
3649 if (!done) {
3650 throw new IOException("Procedure '" + signature + " : " + instance
3651 + "' wasn't completed in expectedTime:" + max + " ms");
3652 }
3653 }
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672 @Override
3673 public boolean isProcedureFinished(String signature, String instance, Map<String, String> props)
3674 throws IOException {
3675 final ProcedureDescription.Builder builder = ProcedureDescription.newBuilder();
3676 builder.setSignature(signature).setInstance(instance);
3677 for (Entry<String, String> entry : props.entrySet()) {
3678 NameStringPair pair = NameStringPair.newBuilder().setName(entry.getKey())
3679 .setValue(entry.getValue()).build();
3680 builder.addConfiguration(pair);
3681 }
3682 final ProcedureDescription desc = builder.build();
3683 return executeCallable(
3684 new MasterCallable<IsProcedureDoneResponse>(getConnection()) {
3685 @Override
3686 public IsProcedureDoneResponse call(int callTimeout) throws ServiceException {
3687 return master.isProcedureDone(null, IsProcedureDoneRequest
3688 .newBuilder().setProcedure(desc).build());
3689 }
3690 }).getDone();
3691 }
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703 private void internalRestoreSnapshot(final String snapshotName, final TableName
3704 tableName)
3705 throws IOException, RestoreSnapshotException {
3706 SnapshotDescription snapshot = SnapshotDescription.newBuilder()
3707 .setName(snapshotName).setTable(tableName.getNameAsString()).build();
3708
3709
3710 internalRestoreSnapshotAsync(snapshot);
3711
3712 final IsRestoreSnapshotDoneRequest request = IsRestoreSnapshotDoneRequest.newBuilder()
3713 .setSnapshot(snapshot).build();
3714 IsRestoreSnapshotDoneResponse done = IsRestoreSnapshotDoneResponse.newBuilder()
3715 .setDone(false).buildPartial();
3716 final long maxPauseTime = 5000;
3717 int tries = 0;
3718 while (!done.getDone()) {
3719 try {
3720
3721 long sleep = getPauseTime(tries++);
3722 sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
3723 LOG.debug(tries + ") Sleeping: " + sleep + " ms while we wait for snapshot restore to complete.");
3724 Thread.sleep(sleep);
3725 } catch (InterruptedException e) {
3726 throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e);
3727 }
3728 LOG.debug("Getting current status of snapshot restore from master...");
3729 done = executeCallable(new MasterCallable<IsRestoreSnapshotDoneResponse>(
3730 getConnection()) {
3731 @Override
3732 public IsRestoreSnapshotDoneResponse call(int callTimeout) throws ServiceException {
3733 return master.isRestoreSnapshotDone(null, request);
3734 }
3735 });
3736 }
3737 if (!done.getDone()) {
3738 throw new RestoreSnapshotException("Snapshot '" + snapshot.getName() + "' wasn't restored.");
3739 }
3740 }
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752 private RestoreSnapshotResponse internalRestoreSnapshotAsync(final SnapshotDescription snapshot)
3753 throws IOException, RestoreSnapshotException {
3754 ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
3755
3756 final RestoreSnapshotRequest request = RestoreSnapshotRequest.newBuilder().setSnapshot(snapshot)
3757 .build();
3758
3759
3760 return executeCallable(new MasterCallable<RestoreSnapshotResponse>(getConnection()) {
3761 @Override
3762 public RestoreSnapshotResponse call(int callTimeout) throws ServiceException {
3763 return master.restoreSnapshot(null, request);
3764 }
3765 });
3766 }
3767
3768
3769
3770
3771
3772
3773 @Override
3774 public List<SnapshotDescription> listSnapshots() throws IOException {
3775 return executeCallable(new MasterCallable<List<SnapshotDescription>>(getConnection()) {
3776 @Override
3777 public List<SnapshotDescription> call(int callTimeout) throws ServiceException {
3778 return master.getCompletedSnapshots(null, GetCompletedSnapshotsRequest.newBuilder().build())
3779 .getSnapshotsList();
3780 }
3781 });
3782 }
3783
3784
3785
3786
3787
3788
3789
3790
3791 @Override
3792 public List<SnapshotDescription> listSnapshots(String regex) throws IOException {
3793 return listSnapshots(Pattern.compile(regex));
3794 }
3795
3796
3797
3798
3799
3800
3801
3802
3803 @Override
3804 public List<SnapshotDescription> listSnapshots(Pattern pattern) throws IOException {
3805 List<SnapshotDescription> matched = new LinkedList<SnapshotDescription>();
3806 List<SnapshotDescription> snapshots = listSnapshots();
3807 for (SnapshotDescription snapshot : snapshots) {
3808 if (pattern.matcher(snapshot.getName()).matches()) {
3809 matched.add(snapshot);
3810 }
3811 }
3812 return matched;
3813 }
3814
3815
3816
3817
3818
3819
3820 @Override
3821 public void deleteSnapshot(final byte[] snapshotName) throws IOException {
3822 deleteSnapshot(Bytes.toString(snapshotName));
3823 }
3824
3825
3826
3827
3828
3829
3830 @Override
3831 public void deleteSnapshot(final String snapshotName) throws IOException {
3832
3833 TableName.isLegalFullyQualifiedTableName(Bytes.toBytes(snapshotName));
3834
3835 executeCallable(new MasterCallable<Void>(getConnection()) {
3836 @Override
3837 public Void call(int callTimeout) throws ServiceException {
3838 master.deleteSnapshot(null,
3839 DeleteSnapshotRequest.newBuilder().
3840 setSnapshot(SnapshotDescription.newBuilder().setName(snapshotName).build()).build()
3841 );
3842 return null;
3843 }
3844 });
3845 }
3846
3847
3848
3849
3850
3851
3852 @Override
3853 public void deleteSnapshots(final String regex) throws IOException {
3854 deleteSnapshots(Pattern.compile(regex));
3855 }
3856
3857
3858
3859
3860
3861
3862 @Override
3863 public void deleteSnapshots(final Pattern pattern) throws IOException {
3864 List<SnapshotDescription> snapshots = listSnapshots(pattern);
3865 for (final SnapshotDescription snapshot : snapshots) {
3866 try {
3867 internalDeleteSnapshot(snapshot);
3868 } catch (IOException ex) {
3869 LOG.info(
3870 "Failed to delete snapshot " + snapshot.getName() + " for table " + snapshot.getTable(),
3871 ex);
3872 }
3873 }
3874 }
3875
3876 private void internalDeleteSnapshot(final SnapshotDescription snapshot) throws IOException {
3877 executeCallable(new MasterCallable<Void>(getConnection()) {
3878 @Override
3879 public Void call(int callTimeout) throws ServiceException {
3880 this.master.deleteSnapshot(null, DeleteSnapshotRequest.newBuilder().setSnapshot(snapshot)
3881 .build());
3882 return null;
3883 }
3884 });
3885 }
3886
3887
3888
3889
3890
3891
3892 @Override
3893 public void setQuota(final QuotaSettings quota) throws IOException {
3894 executeCallable(new MasterCallable<Void>(getConnection()) {
3895 @Override
3896 public Void call(int callTimeout) throws ServiceException {
3897 this.master.setQuota(null, QuotaSettings.buildSetQuotaRequestProto(quota));
3898 return null;
3899 }
3900 });
3901 }
3902
3903
3904
3905
3906
3907
3908
3909 @Override
3910 public QuotaRetriever getQuotaRetriever(final QuotaFilter filter) throws IOException {
3911 return QuotaRetriever.open(conf, filter);
3912 }
3913
3914 private <V> V executeCallable(MasterCallable<V> callable) throws IOException {
3915 RpcRetryingCaller<V> caller = rpcCallerFactory.newCaller();
3916 try {
3917 return caller.callWithRetries(callable, operationTimeout);
3918 } finally {
3919 callable.close();
3920 }
3921 }
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944 @Override
3945 public CoprocessorRpcChannel coprocessorService() {
3946 return new MasterCoprocessorRpcChannel(connection);
3947 }
3948
3949
3950
3951
3952 private static class ThrowableAbortable implements Abortable {
3953
3954 @Override
3955 public void abort(String why, Throwable e) {
3956 throw new RuntimeException(why, e);
3957 }
3958
3959 @Override
3960 public boolean isAborted() {
3961 return true;
3962 }
3963 }
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987 @Override
3988 public CoprocessorRpcChannel coprocessorService(ServerName sn) {
3989 return new RegionServerCoprocessorRpcChannel(connection, sn);
3990 }
3991
3992 @Override
3993 public void updateConfiguration(ServerName server) throws IOException {
3994 try {
3995 this.connection.getAdmin(server).updateConfiguration(null,
3996 UpdateConfigurationRequest.getDefaultInstance());
3997 } catch (ServiceException e) {
3998 throw ProtobufUtil.getRemoteException(e);
3999 }
4000 }
4001
4002 @Override
4003 public void updateConfiguration() throws IOException {
4004 for (ServerName server : this.getClusterStatus().getServers()) {
4005 updateConfiguration(server);
4006 }
4007 }
4008
4009 @Override
4010 public int getMasterInfoPort() throws IOException {
4011
4012 ConnectionManager.HConnectionImplementation connection =
4013 (ConnectionManager.HConnectionImplementation)this.connection;
4014 ZooKeeperKeepAliveConnection zkw = connection.getKeepAliveZooKeeperWatcher();
4015 try {
4016 return MasterAddressTracker.getMasterInfoPort(zkw);
4017 } catch (KeeperException e) {
4018 throw new IOException("Failed to get master info port from MasterAddressTracker", e);
4019 }
4020 }
4021
4022 @Override
4023 public long getLastMajorCompactionTimestamp(final TableName tableName) throws IOException {
4024 return executeCallable(new MasterCallable<Long>(getConnection()) {
4025 @Override
4026 public Long call(int callTimeout) throws ServiceException {
4027 MajorCompactionTimestampRequest req =
4028 MajorCompactionTimestampRequest.newBuilder()
4029 .setTableName(ProtobufUtil.toProtoTableName(tableName)).build();
4030 return master.getLastMajorCompactionTimestamp(null, req).getCompactionTimestamp();
4031 }
4032 });
4033 }
4034
4035 @Override
4036 public long getLastMajorCompactionTimestampForRegion(final byte[] regionName) throws IOException {
4037 return executeCallable(new MasterCallable<Long>(getConnection()) {
4038 @Override
4039 public Long call(int callTimeout) throws ServiceException {
4040 MajorCompactionTimestampForRegionRequest req =
4041 MajorCompactionTimestampForRegionRequest
4042 .newBuilder()
4043 .setRegion(
4044 RequestConverter
4045 .buildRegionSpecifier(RegionSpecifierType.REGION_NAME, regionName)).build();
4046 return master.getLastMajorCompactionTimestampForRegion(null, req).getCompactionTimestamp();
4047 }
4048 });
4049 }
4050
4051
4052
4053
4054
4055
4056 @InterfaceAudience.Private
4057 @InterfaceStability.Evolving
4058 protected static class ProcedureFuture<V> implements Future<V> {
4059 private ExecutionException exception = null;
4060 private boolean procResultFound = false;
4061 private boolean done = false;
4062 private V result = null;
4063
4064 private final HBaseAdmin admin;
4065 private final Long procId;
4066
4067 public ProcedureFuture(final HBaseAdmin admin, final Long procId) {
4068 this.admin = admin;
4069 this.procId = procId;
4070 }
4071
4072 @Override
4073 public boolean cancel(boolean mayInterruptIfRunning) {
4074 throw new UnsupportedOperationException();
4075 }
4076
4077 @Override
4078 public boolean isCancelled() {
4079
4080 return false;
4081 }
4082
4083 @Override
4084 public V get() throws InterruptedException, ExecutionException {
4085
4086 throw new UnsupportedOperationException();
4087 }
4088
4089 @Override
4090 public V get(long timeout, TimeUnit unit)
4091 throws InterruptedException, ExecutionException, TimeoutException {
4092 if (!done) {
4093 long deadlineTs = EnvironmentEdgeManager.currentTime() + unit.toMillis(timeout);
4094 try {
4095 try {
4096
4097 if (procId != null) {
4098 result = waitProcedureResult(procId, deadlineTs);
4099 }
4100
4101 if (!procResultFound) {
4102 result = waitOperationResult(deadlineTs);
4103 }
4104 result = postOperationResult(result, deadlineTs);
4105 done = true;
4106 } catch (IOException e) {
4107 result = postOpeartionFailure(e, deadlineTs);
4108 done = true;
4109 }
4110 } catch (IOException e) {
4111 exception = new ExecutionException(e);
4112 done = true;
4113 }
4114 }
4115 if (exception != null) {
4116 throw exception;
4117 }
4118 return result;
4119 }
4120
4121 @Override
4122 public boolean isDone() {
4123 return done;
4124 }
4125
4126 protected HBaseAdmin getAdmin() {
4127 return admin;
4128 }
4129
4130 private V waitProcedureResult(long procId, long deadlineTs)
4131 throws IOException, TimeoutException, InterruptedException {
4132 GetProcedureResultRequest request = GetProcedureResultRequest.newBuilder()
4133 .setProcId(procId)
4134 .build();
4135
4136 int tries = 0;
4137 IOException serviceEx = null;
4138 while (EnvironmentEdgeManager.currentTime() < deadlineTs) {
4139 GetProcedureResultResponse response = null;
4140 try {
4141
4142 response = getProcedureResult(request);
4143 } catch (IOException e) {
4144 serviceEx = unwrapException(e);
4145
4146
4147 LOG.warn("failed to get the procedure result procId=" + procId, serviceEx);
4148
4149
4150 if (serviceEx instanceof DoNotRetryIOException) {
4151
4152
4153
4154
4155 LOG.warn("Proc-v2 is unsupported on this master: " + serviceEx.getMessage(), serviceEx);
4156 procResultFound = false;
4157 return null;
4158 }
4159 }
4160
4161
4162 if (response != null && response.getState() != GetProcedureResultResponse.State.RUNNING) {
4163 procResultFound = response.getState() != GetProcedureResultResponse.State.NOT_FOUND;
4164 return convertResult(response);
4165 }
4166
4167 try {
4168 Thread.sleep(getAdmin().getPauseTime(tries++));
4169 } catch (InterruptedException e) {
4170 throw new InterruptedException(
4171 "Interrupted while waiting for the result of proc " + procId);
4172 }
4173 }
4174 if (serviceEx != null) {
4175 throw serviceEx;
4176 } else {
4177 throw new TimeoutException("The procedure " + procId + " is still running");
4178 }
4179 }
4180
4181 private static IOException unwrapException(IOException e) {
4182 if (e instanceof RemoteException) {
4183 return ((RemoteException)e).unwrapRemoteException();
4184 }
4185 return e;
4186 }
4187
4188 protected GetProcedureResultResponse getProcedureResult(final GetProcedureResultRequest request)
4189 throws IOException {
4190 return admin.executeCallable(new MasterCallable<GetProcedureResultResponse>(
4191 admin.getConnection()) {
4192 @Override
4193 public GetProcedureResultResponse call(int callTimeout) throws ServiceException {
4194 return master.getProcedureResult(null, request);
4195 }
4196 });
4197 }
4198
4199
4200
4201
4202
4203
4204 protected V convertResult(final GetProcedureResultResponse response) throws IOException {
4205 if (response.hasException()) {
4206 throw ForeignExceptionUtil.toIOException(response.getException());
4207 }
4208 return null;
4209 }
4210
4211
4212
4213
4214
4215
4216
4217 protected V waitOperationResult(final long deadlineTs)
4218 throws IOException, TimeoutException {
4219 return null;
4220 }
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230 protected V postOperationResult(final V result, final long deadlineTs)
4231 throws IOException, TimeoutException {
4232 return result;
4233 }
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244 protected V postOpeartionFailure(final IOException exception, final long deadlineTs)
4245 throws IOException, TimeoutException {
4246 throw exception;
4247 }
4248
4249 protected interface WaitForStateCallable {
4250 boolean checkState(int tries) throws IOException;
4251 void throwInterruptedException() throws InterruptedIOException;
4252 void throwTimeoutException(long elapsed) throws TimeoutException;
4253 }
4254
4255 protected void waitForState(final long deadlineTs, final WaitForStateCallable callable)
4256 throws IOException, TimeoutException {
4257 int tries = 0;
4258 IOException serverEx = null;
4259 long startTime = EnvironmentEdgeManager.currentTime();
4260 while (EnvironmentEdgeManager.currentTime() < deadlineTs) {
4261 serverEx = null;
4262 try {
4263 if (callable.checkState(tries)) {
4264 return;
4265 }
4266 } catch (IOException e) {
4267 serverEx = e;
4268 }
4269 try {
4270 Thread.sleep(getAdmin().getPauseTime(tries++));
4271 } catch (InterruptedException e) {
4272 callable.throwInterruptedException();
4273 }
4274 }
4275 if (serverEx != null) {
4276 throw unwrapException(serverEx);
4277 } else {
4278 callable.throwTimeoutException(EnvironmentEdgeManager.currentTime() - startTime);
4279 }
4280 }
4281 }
4282 }