001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.client; 019 020import com.google.protobuf.Descriptors; 021import com.google.protobuf.Message; 022import com.google.protobuf.RpcController; 023import java.io.Closeable; 024import java.io.IOException; 025import java.io.InterruptedIOException; 026import java.util.ArrayList; 027import java.util.Arrays; 028import java.util.EnumSet; 029import java.util.HashMap; 030import java.util.Iterator; 031import java.util.LinkedList; 032import java.util.List; 033import java.util.Map; 034import java.util.Set; 035import java.util.concurrent.Callable; 036import java.util.concurrent.ExecutionException; 037import java.util.concurrent.Future; 038import java.util.concurrent.TimeUnit; 039import java.util.concurrent.TimeoutException; 040import java.util.concurrent.atomic.AtomicInteger; 041import java.util.concurrent.atomic.AtomicReference; 042import java.util.regex.Pattern; 043import java.util.stream.Collectors; 044import java.util.stream.Stream; 045import org.apache.hadoop.conf.Configuration; 046import org.apache.hadoop.hbase.Abortable; 047import org.apache.hadoop.hbase.CacheEvictionStats; 048import org.apache.hadoop.hbase.CacheEvictionStatsBuilder; 049import org.apache.hadoop.hbase.ClusterMetrics; 050import org.apache.hadoop.hbase.ClusterMetrics.Option; 051import org.apache.hadoop.hbase.ClusterMetricsBuilder; 052import org.apache.hadoop.hbase.DoNotRetryIOException; 053import org.apache.hadoop.hbase.HBaseConfiguration; 054import org.apache.hadoop.hbase.HConstants; 055import org.apache.hadoop.hbase.HRegionInfo; 056import org.apache.hadoop.hbase.HRegionLocation; 057import org.apache.hadoop.hbase.HTableDescriptor; 058import org.apache.hadoop.hbase.MasterNotRunningException; 059import org.apache.hadoop.hbase.MetaTableAccessor; 060import org.apache.hadoop.hbase.NamespaceDescriptor; 061import org.apache.hadoop.hbase.NamespaceNotFoundException; 062import org.apache.hadoop.hbase.NotServingRegionException; 063import org.apache.hadoop.hbase.RegionLocations; 064import org.apache.hadoop.hbase.RegionMetrics; 065import org.apache.hadoop.hbase.RegionMetricsBuilder; 066import org.apache.hadoop.hbase.ServerName; 067import org.apache.hadoop.hbase.TableExistsException; 068import org.apache.hadoop.hbase.TableName; 069import org.apache.hadoop.hbase.TableNotDisabledException; 070import org.apache.hadoop.hbase.TableNotFoundException; 071import org.apache.hadoop.hbase.UnknownRegionException; 072import org.apache.hadoop.hbase.ZooKeeperConnectionException; 073import org.apache.hadoop.hbase.client.replication.ReplicationPeerConfigUtil; 074import org.apache.hadoop.hbase.client.replication.TableCFs; 075import org.apache.hadoop.hbase.client.security.SecurityCapability; 076import org.apache.hadoop.hbase.exceptions.TimeoutIOException; 077import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel; 078import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils; 079import org.apache.hadoop.hbase.ipc.HBaseRpcController; 080import org.apache.hadoop.hbase.ipc.RpcControllerFactory; 081import org.apache.hadoop.hbase.quotas.QuotaFilter; 082import org.apache.hadoop.hbase.quotas.QuotaRetriever; 083import org.apache.hadoop.hbase.quotas.QuotaSettings; 084import org.apache.hadoop.hbase.regionserver.wal.FailedLogCloseException; 085import org.apache.hadoop.hbase.replication.ReplicationException; 086import org.apache.hadoop.hbase.replication.ReplicationPeerConfig; 087import org.apache.hadoop.hbase.replication.ReplicationPeerDescription; 088import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils; 089import org.apache.hadoop.hbase.snapshot.HBaseSnapshotException; 090import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException; 091import org.apache.hadoop.hbase.snapshot.SnapshotCreationException; 092import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException; 093import org.apache.hadoop.hbase.util.Addressing; 094import org.apache.hadoop.hbase.util.Bytes; 095import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 096import org.apache.hadoop.hbase.util.ForeignExceptionUtil; 097import org.apache.hadoop.hbase.util.Pair; 098import org.apache.hadoop.ipc.RemoteException; 099import org.apache.hadoop.util.StringUtils; 100import org.apache.yetus.audience.InterfaceAudience; 101import org.apache.yetus.audience.InterfaceStability; 102import org.slf4j.Logger; 103import org.slf4j.LoggerFactory; 104 105import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; 106import org.apache.hbase.thirdparty.com.google.protobuf.ServiceException; 107import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 108import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter; 109import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos; 110import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.AdminService; 111import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearCompactionQueuesRequest; 112import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearRegionBlockCacheRequest; 113import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearRegionBlockCacheResponse; 114import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactRegionRequest; 115import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.FlushRegionRequest; 116import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoRequest; 117import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoResponse; 118import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.RollWALWriterRequest; 119import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.RollWALWriterResponse; 120import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.StopServerRequest; 121import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.UpdateConfigurationRequest; 122import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos; 123import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.CoprocessorServiceRequest; 124import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.CoprocessorServiceResponse; 125import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos; 126import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.ProcedureDescription; 127import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType; 128import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.TableSchema; 129import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos; 130import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AbortProcedureRequest; 131import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AbortProcedureResponse; 132import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AddColumnRequest; 133import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AddColumnResponse; 134import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AssignRegionRequest; 135import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ClearDeadServersRequest; 136import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateNamespaceRequest; 137import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateNamespaceResponse; 138import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateTableRequest; 139import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateTableResponse; 140import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteColumnRequest; 141import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteColumnResponse; 142import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteNamespaceRequest; 143import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteNamespaceResponse; 144import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteSnapshotRequest; 145import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteTableRequest; 146import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteTableResponse; 147import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DisableTableRequest; 148import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DisableTableResponse; 149import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.EnableTableRequest; 150import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.EnableTableResponse; 151import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ExecProcedureRequest; 152import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ExecProcedureResponse; 153import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetClusterStatusRequest; 154import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetCompletedSnapshotsRequest; 155import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetLocksRequest; 156import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetLocksResponse; 157import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetNamespaceDescriptorRequest; 158import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProcedureResultRequest; 159import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProcedureResultResponse; 160import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProceduresRequest; 161import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProceduresResponse; 162import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetSchemaAlterStatusRequest; 163import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetSchemaAlterStatusResponse; 164import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableDescriptorsRequest; 165import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableDescriptorsResponse; 166import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableNamesRequest; 167import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsInMaintenanceModeRequest; 168import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsInMaintenanceModeResponse; 169import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsProcedureDoneRequest; 170import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsProcedureDoneResponse; 171import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSnapshotDoneRequest; 172import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSnapshotDoneResponse; 173import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListDecommissionedRegionServersRequest; 174import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListNamespaceDescriptorsRequest; 175import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceRequest; 176import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableNamesByNamespaceRequest; 177import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MajorCompactionTimestampForRegionRequest; 178import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MajorCompactionTimestampRequest; 179import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MergeTableRegionsRequest; 180import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MergeTableRegionsResponse; 181import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyColumnRequest; 182import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyColumnResponse; 183import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyNamespaceRequest; 184import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyNamespaceResponse; 185import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyTableRequest; 186import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyTableResponse; 187import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MoveRegionRequest; 188import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RestoreSnapshotRequest; 189import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RestoreSnapshotResponse; 190import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SecurityCapabilitiesRequest; 191import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetBalancerRunningRequest; 192import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetNormalizerRunningRequest; 193import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ShutdownRequest; 194import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SnapshotRequest; 195import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SnapshotResponse; 196import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SplitTableRegionRequest; 197import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SplitTableRegionResponse; 198import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.StopMasterRequest; 199import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.TruncateTableRequest; 200import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.TruncateTableResponse; 201import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.UnassignRegionRequest; 202import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos; 203import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.GetReplicationPeerConfigResponse; 204import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos; 205 206/** 207 * HBaseAdmin is no longer a client API. It is marked InterfaceAudience.Private indicating that 208 * this is an HBase-internal class as defined in 209 * https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/InterfaceClassification.html 210 * There are no guarantees for backwards source / binary compatibility and methods or class can 211 * change or go away without deprecation. 212 * Use {@link Connection#getAdmin()} to obtain an instance of {@link Admin} instead of constructing 213 * an HBaseAdmin directly. 214 * 215 * <p>Connection should be an <i>unmanaged</i> connection obtained via 216 * {@link ConnectionFactory#createConnection(Configuration)} 217 * 218 * @see ConnectionFactory 219 * @see Connection 220 * @see Admin 221 */ 222@InterfaceAudience.Private 223@InterfaceStability.Evolving 224public class HBaseAdmin implements Admin { 225 private static final Logger LOG = LoggerFactory.getLogger(HBaseAdmin.class); 226 227 private ClusterConnection connection; 228 229 private final Configuration conf; 230 private final long pause; 231 private final int numRetries; 232 private final int syncWaitTimeout; 233 private boolean aborted; 234 private int operationTimeout; 235 private int rpcTimeout; 236 237 private RpcRetryingCallerFactory rpcCallerFactory; 238 private RpcControllerFactory rpcControllerFactory; 239 240 private NonceGenerator ng; 241 242 @Override 243 public int getOperationTimeout() { 244 return operationTimeout; 245 } 246 247 HBaseAdmin(ClusterConnection connection) throws IOException { 248 this.conf = connection.getConfiguration(); 249 this.connection = connection; 250 251 // TODO: receive ConnectionConfiguration here rather than re-parsing these configs every time. 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.operationTimeout = this.conf.getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, 257 HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT); 258 this.rpcTimeout = this.conf.getInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 259 HConstants.DEFAULT_HBASE_RPC_TIMEOUT); 260 this.syncWaitTimeout = this.conf.getInt( 261 "hbase.client.sync.wait.timeout.msec", 10 * 60000); // 10min 262 263 this.rpcCallerFactory = connection.getRpcRetryingCallerFactory(); 264 this.rpcControllerFactory = connection.getRpcControllerFactory(); 265 266 this.ng = this.connection.getNonceGenerator(); 267 } 268 269 @Override 270 public void abort(String why, Throwable e) { 271 // Currently does nothing but throw the passed message and exception 272 this.aborted = true; 273 throw new RuntimeException(why, e); 274 } 275 276 @Override 277 public boolean isAborted() { 278 return this.aborted; 279 } 280 281 @Override 282 public boolean abortProcedure(final long procId, final boolean mayInterruptIfRunning) 283 throws IOException { 284 return get(abortProcedureAsync(procId, mayInterruptIfRunning), this.syncWaitTimeout, 285 TimeUnit.MILLISECONDS); 286 } 287 288 @Override 289 public Future<Boolean> abortProcedureAsync(final long procId, final boolean mayInterruptIfRunning) 290 throws IOException { 291 Boolean abortProcResponse = 292 executeCallable(new MasterCallable<AbortProcedureResponse>(getConnection(), 293 getRpcControllerFactory()) { 294 @Override 295 protected AbortProcedureResponse rpcCall() throws Exception { 296 AbortProcedureRequest abortProcRequest = 297 AbortProcedureRequest.newBuilder().setProcId(procId).build(); 298 return master.abortProcedure(getRpcController(), abortProcRequest); 299 } 300 }).getIsProcedureAborted(); 301 return new AbortProcedureFuture(this, procId, abortProcResponse); 302 } 303 304 @Override 305 public List<TableDescriptor> listTableDescriptors() throws IOException { 306 return listTableDescriptors((Pattern)null, false); 307 } 308 309 @Override 310 public List<TableDescriptor> listTableDescriptors(Pattern pattern) throws IOException { 311 return listTableDescriptors(pattern, false); 312 } 313 314 @Override 315 public List<TableDescriptor> listTableDescriptors(Pattern pattern, boolean includeSysTables) 316 throws IOException { 317 return executeCallable(new MasterCallable<List<TableDescriptor>>(getConnection(), 318 getRpcControllerFactory()) { 319 @Override 320 protected List<TableDescriptor> rpcCall() throws Exception { 321 GetTableDescriptorsRequest req = 322 RequestConverter.buildGetTableDescriptorsRequest(pattern, includeSysTables); 323 return ProtobufUtil.toTableDescriptorList(master.getTableDescriptors(getRpcController(), 324 req)); 325 } 326 }); 327 } 328 329 @Override 330 public TableDescriptor getDescriptor(TableName tableName) 331 throws TableNotFoundException, IOException { 332 return getTableDescriptor(tableName, getConnection(), rpcCallerFactory, rpcControllerFactory, 333 operationTimeout, rpcTimeout); 334 } 335 336 @Override 337 public void modifyTable(TableDescriptor td) throws IOException { 338 get(modifyTableAsync(td), syncWaitTimeout, TimeUnit.MILLISECONDS); 339 } 340 341 @Override 342 public Future<Void> modifyTableAsync(TableDescriptor td) throws IOException { 343 ModifyTableResponse response = executeCallable( 344 new MasterCallable<ModifyTableResponse>(getConnection(), getRpcControllerFactory()) { 345 @Override 346 protected ModifyTableResponse rpcCall() throws Exception { 347 setPriority(td.getTableName()); 348 ModifyTableRequest request = RequestConverter.buildModifyTableRequest( 349 td.getTableName(), td, ng.getNonceGroup(), ng.newNonce()); 350 return master.modifyTable(getRpcController(), request); 351 } 352 }); 353 return new ModifyTableFuture(this, td.getTableName(), response); 354 } 355 356 @Override 357 public List<TableDescriptor> listTableDescriptorsByNamespace(byte[] name) throws IOException { 358 return executeCallable(new MasterCallable<List<TableDescriptor>>(getConnection(), 359 getRpcControllerFactory()) { 360 @Override 361 protected List<TableDescriptor> rpcCall() throws Exception { 362 return master.listTableDescriptorsByNamespace(getRpcController(), 363 ListTableDescriptorsByNamespaceRequest.newBuilder() 364 .setNamespaceName(Bytes.toString(name)).build()) 365 .getTableSchemaList() 366 .stream() 367 .map(ProtobufUtil::toTableDescriptor) 368 .collect(Collectors.toList()); 369 } 370 }); 371 } 372 373 @Override 374 public List<TableDescriptor> listTableDescriptors(List<TableName> tableNames) throws IOException { 375 return executeCallable(new MasterCallable<List<TableDescriptor>>(getConnection(), 376 getRpcControllerFactory()) { 377 @Override 378 protected List<TableDescriptor> rpcCall() throws Exception { 379 GetTableDescriptorsRequest req = 380 RequestConverter.buildGetTableDescriptorsRequest(tableNames); 381 return ProtobufUtil.toTableDescriptorList(master.getTableDescriptors(getRpcController(), 382 req)); 383 } 384 }); 385 } 386 387 @Override 388 public List<RegionInfo> getRegions(final ServerName sn) throws IOException { 389 AdminService.BlockingInterface admin = this.connection.getAdmin(sn); 390 // TODO: There is no timeout on this controller. Set one! 391 HBaseRpcController controller = rpcControllerFactory.newController(); 392 return ProtobufUtil.getOnlineRegions(controller, admin); 393 } 394 395 @Override 396 public List<RegionInfo> getRegions(TableName tableName) throws IOException { 397 if (TableName.isMetaTableName(tableName)) { 398 return Arrays.asList(RegionInfoBuilder.FIRST_META_REGIONINFO); 399 } else { 400 return MetaTableAccessor.getTableRegions(connection, tableName, true); 401 } 402 } 403 404 private static class AbortProcedureFuture extends ProcedureFuture<Boolean> { 405 private boolean isAbortInProgress; 406 407 public AbortProcedureFuture( 408 final HBaseAdmin admin, 409 final Long procId, 410 final Boolean abortProcResponse) { 411 super(admin, procId); 412 this.isAbortInProgress = abortProcResponse; 413 } 414 415 @Override 416 public Boolean get(long timeout, TimeUnit unit) 417 throws InterruptedException, ExecutionException, TimeoutException { 418 if (!this.isAbortInProgress) { 419 return false; 420 } 421 super.get(timeout, unit); 422 return true; 423 } 424 } 425 426 /** @return Connection used by this object. */ 427 @Override 428 public Connection getConnection() { 429 return connection; 430 } 431 432 @Override 433 public boolean tableExists(final TableName tableName) throws IOException { 434 return executeCallable(new RpcRetryingCallable<Boolean>() { 435 @Override 436 protected Boolean rpcCall(int callTimeout) throws Exception { 437 return MetaTableAccessor.tableExists(connection, tableName); 438 } 439 }); 440 } 441 442 @Override 443 public HTableDescriptor[] listTables() throws IOException { 444 return listTables((Pattern)null, false); 445 } 446 447 @Override 448 public HTableDescriptor[] listTables(Pattern pattern) throws IOException { 449 return listTables(pattern, false); 450 } 451 452 @Override 453 public HTableDescriptor[] listTables(String regex) throws IOException { 454 return listTables(Pattern.compile(regex), false); 455 } 456 457 @Override 458 public HTableDescriptor[] listTables(final Pattern pattern, final boolean includeSysTables) 459 throws IOException { 460 return executeCallable(new MasterCallable<HTableDescriptor[]>(getConnection(), 461 getRpcControllerFactory()) { 462 @Override 463 protected HTableDescriptor[] rpcCall() throws Exception { 464 GetTableDescriptorsRequest req = 465 RequestConverter.buildGetTableDescriptorsRequest(pattern, includeSysTables); 466 return ProtobufUtil.toTableDescriptorList(master.getTableDescriptors(getRpcController(), 467 req)).stream().map(ImmutableHTableDescriptor::new).toArray(HTableDescriptor[]::new); 468 } 469 }); 470 } 471 472 @Override 473 public HTableDescriptor[] listTables(String regex, boolean includeSysTables) 474 throws IOException { 475 return listTables(Pattern.compile(regex), includeSysTables); 476 } 477 478 @Override 479 public TableName[] listTableNames() throws IOException { 480 return listTableNames((Pattern)null, false); 481 } 482 483 @Override 484 public TableName[] listTableNames(Pattern pattern) throws IOException { 485 return listTableNames(pattern, false); 486 } 487 488 @Override 489 public TableName[] listTableNames(String regex) throws IOException { 490 return listTableNames(Pattern.compile(regex), false); 491 } 492 493 @Override 494 public TableName[] listTableNames(final Pattern pattern, final boolean includeSysTables) 495 throws IOException { 496 return executeCallable(new MasterCallable<TableName[]>(getConnection(), 497 getRpcControllerFactory()) { 498 @Override 499 protected TableName[] rpcCall() throws Exception { 500 GetTableNamesRequest req = 501 RequestConverter.buildGetTableNamesRequest(pattern, includeSysTables); 502 return ProtobufUtil.getTableNameArray(master.getTableNames(getRpcController(), req) 503 .getTableNamesList()); 504 } 505 }); 506 } 507 508 @Override 509 public TableName[] listTableNames(final String regex, final boolean includeSysTables) 510 throws IOException { 511 return listTableNames(Pattern.compile(regex), includeSysTables); 512 } 513 514 @Override 515 public HTableDescriptor getTableDescriptor(final TableName tableName) throws IOException { 516 return getHTableDescriptor(tableName, getConnection(), rpcCallerFactory, rpcControllerFactory, 517 operationTimeout, rpcTimeout); 518 } 519 520 static TableDescriptor getTableDescriptor(final TableName tableName, Connection connection, 521 RpcRetryingCallerFactory rpcCallerFactory, final RpcControllerFactory rpcControllerFactory, 522 int operationTimeout, int rpcTimeout) throws IOException { 523 if (tableName == null) return null; 524 TableDescriptor td = 525 executeCallable(new MasterCallable<TableDescriptor>(connection, rpcControllerFactory) { 526 @Override 527 protected TableDescriptor rpcCall() throws Exception { 528 GetTableDescriptorsRequest req = 529 RequestConverter.buildGetTableDescriptorsRequest(tableName); 530 GetTableDescriptorsResponse htds = master.getTableDescriptors(getRpcController(), req); 531 if (!htds.getTableSchemaList().isEmpty()) { 532 return ProtobufUtil.toTableDescriptor(htds.getTableSchemaList().get(0)); 533 } 534 return null; 535 } 536 }, rpcCallerFactory, operationTimeout, rpcTimeout); 537 if (td != null) { 538 return td; 539 } 540 throw new TableNotFoundException(tableName.getNameAsString()); 541 } 542 543 /** 544 * @deprecated since 2.0 version and will be removed in 3.0 version. 545 * use {@link #getTableDescriptor(TableName, 546 * Connection, RpcRetryingCallerFactory,RpcControllerFactory,int,int)} 547 */ 548 @Deprecated 549 static HTableDescriptor getHTableDescriptor(final TableName tableName, Connection connection, 550 RpcRetryingCallerFactory rpcCallerFactory, final RpcControllerFactory rpcControllerFactory, 551 int operationTimeout, int rpcTimeout) throws IOException { 552 if (tableName == null) { 553 return null; 554 } 555 HTableDescriptor htd = 556 executeCallable(new MasterCallable<HTableDescriptor>(connection, rpcControllerFactory) { 557 @Override 558 protected HTableDescriptor rpcCall() throws Exception { 559 GetTableDescriptorsRequest req = 560 RequestConverter.buildGetTableDescriptorsRequest(tableName); 561 GetTableDescriptorsResponse htds = master.getTableDescriptors(getRpcController(), req); 562 if (!htds.getTableSchemaList().isEmpty()) { 563 return new ImmutableHTableDescriptor( 564 ProtobufUtil.toTableDescriptor(htds.getTableSchemaList().get(0))); 565 } 566 return null; 567 } 568 }, rpcCallerFactory, operationTimeout, rpcTimeout); 569 if (htd != null) { 570 return new ImmutableHTableDescriptor(htd); 571 } 572 throw new TableNotFoundException(tableName.getNameAsString()); 573 } 574 575 private long getPauseTime(int tries) { 576 int triesCount = tries; 577 if (triesCount >= HConstants.RETRY_BACKOFF.length) { 578 triesCount = HConstants.RETRY_BACKOFF.length - 1; 579 } 580 return this.pause * HConstants.RETRY_BACKOFF[triesCount]; 581 } 582 583 @Override 584 public void createTable(TableDescriptor desc) 585 throws IOException { 586 createTable(desc, null); 587 } 588 589 @Override 590 public void createTable(TableDescriptor desc, byte [] startKey, 591 byte [] endKey, int numRegions) 592 throws IOException { 593 if(numRegions < 3) { 594 throw new IllegalArgumentException("Must create at least three regions"); 595 } else if(Bytes.compareTo(startKey, endKey) >= 0) { 596 throw new IllegalArgumentException("Start key must be smaller than end key"); 597 } 598 if (numRegions == 3) { 599 createTable(desc, new byte[][]{startKey, endKey}); 600 return; 601 } 602 byte [][] splitKeys = Bytes.split(startKey, endKey, numRegions - 3); 603 if(splitKeys == null || splitKeys.length != numRegions - 1) { 604 throw new IllegalArgumentException("Unable to split key range into enough regions"); 605 } 606 createTable(desc, splitKeys); 607 } 608 609 @Override 610 public void createTable(final TableDescriptor desc, byte [][] splitKeys) 611 throws IOException { 612 get(createTableAsync(desc, splitKeys), syncWaitTimeout, TimeUnit.MILLISECONDS); 613 } 614 615 @Override 616 public Future<Void> createTableAsync(final TableDescriptor desc, final byte[][] splitKeys) 617 throws IOException { 618 if (desc.getTableName() == null) { 619 throw new IllegalArgumentException("TableName cannot be null"); 620 } 621 if (splitKeys != null && splitKeys.length > 0) { 622 Arrays.sort(splitKeys, Bytes.BYTES_COMPARATOR); 623 // Verify there are no duplicate split keys 624 byte[] lastKey = null; 625 for (byte[] splitKey : splitKeys) { 626 if (Bytes.compareTo(splitKey, HConstants.EMPTY_BYTE_ARRAY) == 0) { 627 throw new IllegalArgumentException( 628 "Empty split key must not be passed in the split keys."); 629 } 630 if (lastKey != null && Bytes.equals(splitKey, lastKey)) { 631 throw new IllegalArgumentException("All split keys must be unique, " + 632 "found duplicate: " + Bytes.toStringBinary(splitKey) + 633 ", " + Bytes.toStringBinary(lastKey)); 634 } 635 lastKey = splitKey; 636 } 637 } 638 639 CreateTableResponse response = executeCallable( 640 new MasterCallable<CreateTableResponse>(getConnection(), getRpcControllerFactory()) { 641 @Override 642 protected CreateTableResponse rpcCall() throws Exception { 643 setPriority(desc.getTableName()); 644 CreateTableRequest request = RequestConverter.buildCreateTableRequest( 645 desc, splitKeys, ng.getNonceGroup(), ng.newNonce()); 646 return master.createTable(getRpcController(), request); 647 } 648 }); 649 return new CreateTableFuture(this, desc, splitKeys, response); 650 } 651 652 private static class CreateTableFuture extends TableFuture<Void> { 653 private final TableDescriptor desc; 654 private final byte[][] splitKeys; 655 656 public CreateTableFuture(final HBaseAdmin admin, final TableDescriptor desc, 657 final byte[][] splitKeys, final CreateTableResponse response) { 658 super(admin, desc.getTableName(), 659 (response != null && response.hasProcId()) ? response.getProcId() : null); 660 this.splitKeys = splitKeys; 661 this.desc = desc; 662 } 663 664 @Override 665 protected TableDescriptor getTableDescriptor() { 666 return desc; 667 } 668 669 @Override 670 public String getOperationType() { 671 return "CREATE"; 672 } 673 674 @Override 675 protected Void waitOperationResult(final long deadlineTs) throws IOException, TimeoutException { 676 waitForTableEnabled(deadlineTs); 677 waitForAllRegionsOnline(deadlineTs, splitKeys); 678 return null; 679 } 680 } 681 682 @Override 683 public void deleteTable(final TableName tableName) throws IOException { 684 get(deleteTableAsync(tableName), syncWaitTimeout, TimeUnit.MILLISECONDS); 685 } 686 687 @Override 688 public Future<Void> deleteTableAsync(final TableName tableName) throws IOException { 689 DeleteTableResponse response = executeCallable( 690 new MasterCallable<DeleteTableResponse>(getConnection(), getRpcControllerFactory()) { 691 @Override 692 protected DeleteTableResponse rpcCall() throws Exception { 693 setPriority(tableName); 694 DeleteTableRequest req = 695 RequestConverter.buildDeleteTableRequest(tableName, ng.getNonceGroup(),ng.newNonce()); 696 return master.deleteTable(getRpcController(), req); 697 } 698 }); 699 return new DeleteTableFuture(this, tableName, response); 700 } 701 702 private static class DeleteTableFuture extends TableFuture<Void> { 703 public DeleteTableFuture(final HBaseAdmin admin, final TableName tableName, 704 final DeleteTableResponse response) { 705 super(admin, tableName, 706 (response != null && response.hasProcId()) ? response.getProcId() : null); 707 } 708 709 @Override 710 public String getOperationType() { 711 return "DELETE"; 712 } 713 714 @Override 715 protected Void waitOperationResult(final long deadlineTs) 716 throws IOException, TimeoutException { 717 waitTableNotFound(deadlineTs); 718 return null; 719 } 720 721 @Override 722 protected Void postOperationResult(final Void result, final long deadlineTs) 723 throws IOException, TimeoutException { 724 // Delete cached information to prevent clients from using old locations 725 ((ClusterConnection) getAdmin().getConnection()).clearRegionCache(getTableName()); 726 return super.postOperationResult(result, deadlineTs); 727 } 728 } 729 730 @Override 731 public HTableDescriptor[] deleteTables(String regex) throws IOException { 732 return deleteTables(Pattern.compile(regex)); 733 } 734 735 /** 736 * Delete tables matching the passed in pattern and wait on completion. 737 * 738 * Warning: Use this method carefully, there is no prompting and the effect is 739 * immediate. Consider using {@link #listTables(java.util.regex.Pattern) } and 740 * {@link #deleteTable(TableName)} 741 * 742 * @param pattern The pattern to match table names against 743 * @return Table descriptors for tables that couldn't be deleted 744 * @throws IOException 745 */ 746 @Override 747 public HTableDescriptor[] deleteTables(Pattern pattern) throws IOException { 748 List<HTableDescriptor> failed = new LinkedList<>(); 749 for (HTableDescriptor table : listTables(pattern)) { 750 try { 751 deleteTable(table.getTableName()); 752 } catch (IOException ex) { 753 LOG.info("Failed to delete table " + table.getTableName(), ex); 754 failed.add(table); 755 } 756 } 757 return failed.toArray(new HTableDescriptor[failed.size()]); 758 } 759 760 @Override 761 public void truncateTable(final TableName tableName, final boolean preserveSplits) 762 throws IOException { 763 get(truncateTableAsync(tableName, preserveSplits), syncWaitTimeout, TimeUnit.MILLISECONDS); 764 } 765 766 @Override 767 public Future<Void> truncateTableAsync(final TableName tableName, final boolean preserveSplits) 768 throws IOException { 769 TruncateTableResponse response = 770 executeCallable(new MasterCallable<TruncateTableResponse>(getConnection(), 771 getRpcControllerFactory()) { 772 @Override 773 protected TruncateTableResponse rpcCall() throws Exception { 774 setPriority(tableName); 775 LOG.info("Started truncating " + tableName); 776 TruncateTableRequest req = RequestConverter.buildTruncateTableRequest( 777 tableName, preserveSplits, ng.getNonceGroup(), ng.newNonce()); 778 return master.truncateTable(getRpcController(), req); 779 } 780 }); 781 return new TruncateTableFuture(this, tableName, preserveSplits, response); 782 } 783 784 private static class TruncateTableFuture extends TableFuture<Void> { 785 private final boolean preserveSplits; 786 787 public TruncateTableFuture(final HBaseAdmin admin, final TableName tableName, 788 final boolean preserveSplits, final TruncateTableResponse response) { 789 super(admin, tableName, 790 (response != null && response.hasProcId()) ? response.getProcId() : null); 791 this.preserveSplits = preserveSplits; 792 } 793 794 @Override 795 public String getOperationType() { 796 return "TRUNCATE"; 797 } 798 799 @Override 800 protected Void waitOperationResult(final long deadlineTs) throws IOException, TimeoutException { 801 waitForTableEnabled(deadlineTs); 802 // once the table is enabled, we know the operation is done. so we can fetch the splitKeys 803 byte[][] splitKeys = preserveSplits ? getAdmin().getTableSplits(getTableName()) : null; 804 waitForAllRegionsOnline(deadlineTs, splitKeys); 805 return null; 806 } 807 } 808 809 private byte[][] getTableSplits(final TableName tableName) throws IOException { 810 byte[][] splits = null; 811 try (RegionLocator locator = getConnection().getRegionLocator(tableName)) { 812 byte[][] startKeys = locator.getStartKeys(); 813 if (startKeys.length == 1) { 814 return splits; 815 } 816 splits = new byte[startKeys.length - 1][]; 817 for (int i = 1; i < startKeys.length; i++) { 818 splits[i - 1] = startKeys[i]; 819 } 820 } 821 return splits; 822 } 823 824 @Override 825 public void enableTable(final TableName tableName) 826 throws IOException { 827 get(enableTableAsync(tableName), syncWaitTimeout, TimeUnit.MILLISECONDS); 828 } 829 830 @Override 831 public Future<Void> enableTableAsync(final TableName tableName) throws IOException { 832 TableName.isLegalFullyQualifiedTableName(tableName.getName()); 833 EnableTableResponse response = executeCallable( 834 new MasterCallable<EnableTableResponse>(getConnection(), getRpcControllerFactory()) { 835 @Override 836 protected EnableTableResponse rpcCall() throws Exception { 837 setPriority(tableName); 838 LOG.info("Started enable of " + tableName); 839 EnableTableRequest req = 840 RequestConverter.buildEnableTableRequest(tableName, ng.getNonceGroup(),ng.newNonce()); 841 return master.enableTable(getRpcController(),req); 842 } 843 }); 844 return new EnableTableFuture(this, tableName, response); 845 } 846 847 private static class EnableTableFuture extends TableFuture<Void> { 848 public EnableTableFuture(final HBaseAdmin admin, final TableName tableName, 849 final EnableTableResponse response) { 850 super(admin, tableName, 851 (response != null && response.hasProcId()) ? response.getProcId() : null); 852 } 853 854 @Override 855 public String getOperationType() { 856 return "ENABLE"; 857 } 858 859 @Override 860 protected Void waitOperationResult(final long deadlineTs) throws IOException, TimeoutException { 861 waitForTableEnabled(deadlineTs); 862 return null; 863 } 864 } 865 866 @Override 867 public HTableDescriptor[] enableTables(String regex) throws IOException { 868 return enableTables(Pattern.compile(regex)); 869 } 870 871 @Override 872 public HTableDescriptor[] enableTables(Pattern pattern) throws IOException { 873 List<HTableDescriptor> failed = new LinkedList<>(); 874 for (HTableDescriptor table : listTables(pattern)) { 875 if (isTableDisabled(table.getTableName())) { 876 try { 877 enableTable(table.getTableName()); 878 } catch (IOException ex) { 879 LOG.info("Failed to enable table " + table.getTableName(), ex); 880 failed.add(table); 881 } 882 } 883 } 884 return failed.toArray(new HTableDescriptor[failed.size()]); 885 } 886 887 @Override 888 public void disableTable(final TableName tableName) 889 throws IOException { 890 get(disableTableAsync(tableName), syncWaitTimeout, TimeUnit.MILLISECONDS); 891 } 892 893 @Override 894 public Future<Void> disableTableAsync(final TableName tableName) throws IOException { 895 TableName.isLegalFullyQualifiedTableName(tableName.getName()); 896 DisableTableResponse response = executeCallable( 897 new MasterCallable<DisableTableResponse>(getConnection(), getRpcControllerFactory()) { 898 @Override 899 protected DisableTableResponse rpcCall() throws Exception { 900 setPriority(tableName); 901 LOG.info("Started disable of " + tableName); 902 DisableTableRequest req = 903 RequestConverter.buildDisableTableRequest( 904 tableName, ng.getNonceGroup(), ng.newNonce()); 905 return master.disableTable(getRpcController(), req); 906 } 907 }); 908 return new DisableTableFuture(this, tableName, response); 909 } 910 911 private static class DisableTableFuture extends TableFuture<Void> { 912 public DisableTableFuture(final HBaseAdmin admin, final TableName tableName, 913 final DisableTableResponse response) { 914 super(admin, tableName, 915 (response != null && response.hasProcId()) ? response.getProcId() : null); 916 } 917 918 @Override 919 public String getOperationType() { 920 return "DISABLE"; 921 } 922 923 @Override 924 protected Void waitOperationResult(long deadlineTs) throws IOException, TimeoutException { 925 waitForTableDisabled(deadlineTs); 926 return null; 927 } 928 } 929 930 @Override 931 public HTableDescriptor[] disableTables(String regex) throws IOException { 932 return disableTables(Pattern.compile(regex)); 933 } 934 935 @Override 936 public HTableDescriptor[] disableTables(Pattern pattern) throws IOException { 937 List<HTableDescriptor> failed = new LinkedList<>(); 938 for (HTableDescriptor table : listTables(pattern)) { 939 if (isTableEnabled(table.getTableName())) { 940 try { 941 disableTable(table.getTableName()); 942 } catch (IOException ex) { 943 LOG.info("Failed to disable table " + table.getTableName(), ex); 944 failed.add(table); 945 } 946 } 947 } 948 return failed.toArray(new HTableDescriptor[failed.size()]); 949 } 950 951 @Override 952 public boolean isTableEnabled(final TableName tableName) throws IOException { 953 checkTableExists(tableName); 954 return executeCallable(new RpcRetryingCallable<Boolean>() { 955 @Override 956 protected Boolean rpcCall(int callTimeout) throws Exception { 957 TableState tableState = MetaTableAccessor.getTableState(getConnection(), tableName); 958 if (tableState == null) { 959 throw new TableNotFoundException(tableName); 960 } 961 return tableState.inStates(TableState.State.ENABLED); 962 } 963 }); 964 } 965 966 @Override 967 public boolean isTableDisabled(TableName tableName) throws IOException { 968 checkTableExists(tableName); 969 return connection.isTableDisabled(tableName); 970 } 971 972 @Override 973 public boolean isTableAvailable(TableName tableName) throws IOException { 974 return connection.isTableAvailable(tableName, null); 975 } 976 977 @Override 978 public boolean isTableAvailable(TableName tableName, byte[][] splitKeys) throws IOException { 979 return connection.isTableAvailable(tableName, splitKeys); 980 } 981 982 @Override 983 public Pair<Integer, Integer> getAlterStatus(final TableName tableName) throws IOException { 984 return executeCallable(new MasterCallable<Pair<Integer, Integer>>(getConnection(), 985 getRpcControllerFactory()) { 986 @Override 987 protected Pair<Integer, Integer> rpcCall() throws Exception { 988 setPriority(tableName); 989 GetSchemaAlterStatusRequest req = RequestConverter 990 .buildGetSchemaAlterStatusRequest(tableName); 991 GetSchemaAlterStatusResponse ret = master.getSchemaAlterStatus(getRpcController(), req); 992 Pair<Integer, Integer> pair = new Pair<>(ret.getYetToUpdateRegions(), 993 ret.getTotalRegions()); 994 return pair; 995 } 996 }); 997 } 998 999 @Override 1000 public Pair<Integer, Integer> getAlterStatus(final byte[] tableName) throws IOException { 1001 return getAlterStatus(TableName.valueOf(tableName)); 1002 } 1003 1004 @Override 1005 public void addColumnFamily(final TableName tableName, final ColumnFamilyDescriptor columnFamily) 1006 throws IOException { 1007 get(addColumnFamilyAsync(tableName, columnFamily), syncWaitTimeout, TimeUnit.MILLISECONDS); 1008 } 1009 1010 @Override 1011 public Future<Void> addColumnFamilyAsync(final TableName tableName, 1012 final ColumnFamilyDescriptor columnFamily) throws IOException { 1013 AddColumnResponse response = 1014 executeCallable(new MasterCallable<AddColumnResponse>(getConnection(), 1015 getRpcControllerFactory()) { 1016 @Override 1017 protected AddColumnResponse rpcCall() throws Exception { 1018 setPriority(tableName); 1019 AddColumnRequest req = 1020 RequestConverter.buildAddColumnRequest(tableName, columnFamily, ng.getNonceGroup(), 1021 ng.newNonce()); 1022 return master.addColumn(getRpcController(), req); 1023 } 1024 }); 1025 return new AddColumnFamilyFuture(this, tableName, response); 1026 } 1027 1028 private static class AddColumnFamilyFuture extends ModifyTableFuture { 1029 public AddColumnFamilyFuture(final HBaseAdmin admin, final TableName tableName, 1030 final AddColumnResponse response) { 1031 super(admin, tableName, (response != null && response.hasProcId()) ? response.getProcId() 1032 : null); 1033 } 1034 1035 @Override 1036 public String getOperationType() { 1037 return "ADD_COLUMN_FAMILY"; 1038 } 1039 } 1040 1041 /** 1042 * {@inheritDoc} 1043 * @deprecated Since 2.0. Will be removed in 3.0. Use 1044 * {@link #deleteColumnFamily(TableName, byte[])} instead. 1045 */ 1046 @Override 1047 @Deprecated 1048 public void deleteColumn(final TableName tableName, final byte[] columnFamily) 1049 throws IOException { 1050 deleteColumnFamily(tableName, columnFamily); 1051 } 1052 1053 @Override 1054 public void deleteColumnFamily(final TableName tableName, final byte[] columnFamily) 1055 throws IOException { 1056 get(deleteColumnFamilyAsync(tableName, columnFamily), syncWaitTimeout, TimeUnit.MILLISECONDS); 1057 } 1058 1059 @Override 1060 public Future<Void> deleteColumnFamilyAsync(final TableName tableName, final byte[] columnFamily) 1061 throws IOException { 1062 DeleteColumnResponse response = 1063 executeCallable(new MasterCallable<DeleteColumnResponse>(getConnection(), 1064 getRpcControllerFactory()) { 1065 @Override 1066 protected DeleteColumnResponse rpcCall() throws Exception { 1067 setPriority(tableName); 1068 DeleteColumnRequest req = 1069 RequestConverter.buildDeleteColumnRequest(tableName, columnFamily, 1070 ng.getNonceGroup(), ng.newNonce()); 1071 return master.deleteColumn(getRpcController(), req); 1072 } 1073 }); 1074 return new DeleteColumnFamilyFuture(this, tableName, response); 1075 } 1076 1077 private static class DeleteColumnFamilyFuture extends ModifyTableFuture { 1078 public DeleteColumnFamilyFuture(final HBaseAdmin admin, final TableName tableName, 1079 final DeleteColumnResponse response) { 1080 super(admin, tableName, (response != null && response.hasProcId()) ? response.getProcId() 1081 : null); 1082 } 1083 1084 @Override 1085 public String getOperationType() { 1086 return "DELETE_COLUMN_FAMILY"; 1087 } 1088 } 1089 1090 @Override 1091 public void modifyColumnFamily(final TableName tableName, 1092 final ColumnFamilyDescriptor columnFamily) throws IOException { 1093 get(modifyColumnFamilyAsync(tableName, columnFamily), syncWaitTimeout, TimeUnit.MILLISECONDS); 1094 } 1095 1096 @Override 1097 public Future<Void> modifyColumnFamilyAsync(final TableName tableName, 1098 final ColumnFamilyDescriptor columnFamily) throws IOException { 1099 ModifyColumnResponse response = 1100 executeCallable(new MasterCallable<ModifyColumnResponse>(getConnection(), 1101 getRpcControllerFactory()) { 1102 @Override 1103 protected ModifyColumnResponse rpcCall() throws Exception { 1104 setPriority(tableName); 1105 ModifyColumnRequest req = 1106 RequestConverter.buildModifyColumnRequest(tableName, columnFamily, 1107 ng.getNonceGroup(), ng.newNonce()); 1108 return master.modifyColumn(getRpcController(), req); 1109 } 1110 }); 1111 return new ModifyColumnFamilyFuture(this, tableName, response); 1112 } 1113 1114 private static class ModifyColumnFamilyFuture extends ModifyTableFuture { 1115 public ModifyColumnFamilyFuture(final HBaseAdmin admin, final TableName tableName, 1116 final ModifyColumnResponse response) { 1117 super(admin, tableName, (response != null && response.hasProcId()) ? response.getProcId() 1118 : null); 1119 } 1120 1121 @Override 1122 public String getOperationType() { 1123 return "MODIFY_COLUMN_FAMILY"; 1124 } 1125 } 1126 1127 @Deprecated 1128 @Override 1129 public void closeRegion(final String regionName, final String unused) throws IOException { 1130 unassign(Bytes.toBytes(regionName), true); 1131 } 1132 1133 @Deprecated 1134 @Override 1135 public void closeRegion(final byte [] regionName, final String unused) throws IOException { 1136 unassign(regionName, true); 1137 } 1138 1139 @Deprecated 1140 @Override 1141 public boolean closeRegionWithEncodedRegionName(final String encodedRegionName, 1142 final String unused) throws IOException { 1143 unassign(Bytes.toBytes(encodedRegionName), true); 1144 return true; 1145 } 1146 1147 @Deprecated 1148 @Override 1149 public void closeRegion(final ServerName unused, final HRegionInfo hri) throws IOException { 1150 unassign(hri.getRegionName(), true); 1151 } 1152 1153 /** 1154 * @param sn 1155 * @return List of {@link HRegionInfo}. 1156 * @throws IOException 1157 * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0 1158 * Use {@link #getRegions(ServerName)}. 1159 */ 1160 @Deprecated 1161 @Override 1162 public List<HRegionInfo> getOnlineRegions(final ServerName sn) throws IOException { 1163 return getRegions(sn).stream().map(ImmutableHRegionInfo::new).collect(Collectors.toList()); 1164 } 1165 1166 @Override 1167 public void flush(final TableName tableName) throws IOException { 1168 checkTableExists(tableName); 1169 if (isTableDisabled(tableName)) { 1170 LOG.info("Table is disabled: " + tableName.getNameAsString()); 1171 return; 1172 } 1173 execProcedure("flush-table-proc", tableName.getNameAsString(), new HashMap<>()); 1174 } 1175 1176 @Override 1177 public void flushRegion(final byte[] regionName) throws IOException { 1178 Pair<RegionInfo, ServerName> regionServerPair = getRegion(regionName); 1179 if (regionServerPair == null) { 1180 throw new IllegalArgumentException("Unknown regionname: " + Bytes.toStringBinary(regionName)); 1181 } 1182 if (regionServerPair.getSecond() == null) { 1183 throw new NoServerForRegionException(Bytes.toStringBinary(regionName)); 1184 } 1185 final RegionInfo regionInfo = regionServerPair.getFirst(); 1186 ServerName serverName = regionServerPair.getSecond(); 1187 flush(this.connection.getAdmin(serverName), regionInfo); 1188 } 1189 1190 private void flush(AdminService.BlockingInterface admin, final RegionInfo info) 1191 throws IOException { 1192 ProtobufUtil.call(() -> { 1193 // TODO: There is no timeout on this controller. Set one! 1194 HBaseRpcController controller = rpcControllerFactory.newController(); 1195 FlushRegionRequest request = 1196 RequestConverter.buildFlushRegionRequest(info.getRegionName()); 1197 admin.flushRegion(controller, request); 1198 return null; 1199 }); 1200 } 1201 1202 @Override 1203 public void flushRegionServer(ServerName serverName) throws IOException { 1204 for (RegionInfo region : getRegions(serverName)) { 1205 flush(this.connection.getAdmin(serverName), region); 1206 } 1207 } 1208 1209 /** 1210 * {@inheritDoc} 1211 */ 1212 @Override 1213 public void compact(final TableName tableName) 1214 throws IOException { 1215 compact(tableName, null, false, CompactType.NORMAL); 1216 } 1217 1218 @Override 1219 public void compactRegion(final byte[] regionName) 1220 throws IOException { 1221 compactRegion(regionName, null, false); 1222 } 1223 1224 /** 1225 * {@inheritDoc} 1226 */ 1227 @Override 1228 public void compact(final TableName tableName, final byte[] columnFamily) 1229 throws IOException { 1230 compact(tableName, columnFamily, false, CompactType.NORMAL); 1231 } 1232 1233 /** 1234 * {@inheritDoc} 1235 */ 1236 @Override 1237 public void compactRegion(final byte[] regionName, final byte[] columnFamily) 1238 throws IOException { 1239 compactRegion(regionName, columnFamily, false); 1240 } 1241 1242 @Override 1243 public void compactRegionServer(final ServerName serverName) throws IOException { 1244 for (RegionInfo region : getRegions(serverName)) { 1245 compact(this.connection.getAdmin(serverName), region, false, null); 1246 } 1247 } 1248 1249 @Override 1250 public void majorCompactRegionServer(final ServerName serverName) throws IOException { 1251 for (RegionInfo region : getRegions(serverName)) { 1252 compact(this.connection.getAdmin(serverName), region, true, null); 1253 } 1254 } 1255 1256 @Override 1257 public void majorCompact(final TableName tableName) 1258 throws IOException { 1259 compact(tableName, null, true, CompactType.NORMAL); 1260 } 1261 1262 @Override 1263 public void majorCompactRegion(final byte[] regionName) 1264 throws IOException { 1265 compactRegion(regionName, null, true); 1266 } 1267 1268 /** 1269 * {@inheritDoc} 1270 */ 1271 @Override 1272 public void majorCompact(final TableName tableName, final byte[] columnFamily) 1273 throws IOException { 1274 compact(tableName, columnFamily, true, CompactType.NORMAL); 1275 } 1276 1277 @Override 1278 public void majorCompactRegion(final byte[] regionName, final byte[] columnFamily) 1279 throws IOException { 1280 compactRegion(regionName, columnFamily, true); 1281 } 1282 1283 /** 1284 * Compact a table. 1285 * Asynchronous operation. 1286 * 1287 * @param tableName table or region to compact 1288 * @param columnFamily column family within a table or region 1289 * @param major True if we are to do a major compaction. 1290 * @param compactType {@link org.apache.hadoop.hbase.client.CompactType} 1291 * @throws IOException if a remote or network exception occurs 1292 */ 1293 private void compact(final TableName tableName, final byte[] columnFamily,final boolean major, 1294 CompactType compactType) throws IOException { 1295 switch (compactType) { 1296 case MOB: 1297 compact(this.connection.getAdminForMaster(), RegionInfo.createMobRegionInfo(tableName), 1298 major, columnFamily); 1299 break; 1300 case NORMAL: 1301 checkTableExists(tableName); 1302 for (HRegionLocation loc :connection.locateRegions(tableName, false, false)) { 1303 ServerName sn = loc.getServerName(); 1304 if (sn == null) { 1305 continue; 1306 } 1307 try { 1308 compact(this.connection.getAdmin(sn), loc.getRegion(), major, columnFamily); 1309 } catch (NotServingRegionException e) { 1310 if (LOG.isDebugEnabled()) { 1311 LOG.debug("Trying to" + (major ? " major" : "") + " compact " + loc.getRegion() + 1312 ": " + StringUtils.stringifyException(e)); 1313 } 1314 } 1315 } 1316 break; 1317 default: 1318 throw new IllegalArgumentException("Unknown compactType: " + compactType); 1319 } 1320 } 1321 1322 /** 1323 * Compact an individual region. 1324 * Asynchronous operation. 1325 * 1326 * @param regionName region to compact 1327 * @param columnFamily column family within a table or region 1328 * @param major True if we are to do a major compaction. 1329 * @throws IOException if a remote or network exception occurs 1330 * @throws InterruptedException 1331 */ 1332 private void compactRegion(final byte[] regionName, final byte[] columnFamily, 1333 final boolean major) throws IOException { 1334 Pair<RegionInfo, ServerName> regionServerPair = getRegion(regionName); 1335 if (regionServerPair == null) { 1336 throw new IllegalArgumentException("Invalid region: " + Bytes.toStringBinary(regionName)); 1337 } 1338 if (regionServerPair.getSecond() == null) { 1339 throw new NoServerForRegionException(Bytes.toStringBinary(regionName)); 1340 } 1341 compact(this.connection.getAdmin(regionServerPair.getSecond()), regionServerPair.getFirst(), 1342 major, columnFamily); 1343 } 1344 1345 private void compact(AdminService.BlockingInterface admin, RegionInfo hri, boolean major, 1346 byte[] family) throws IOException { 1347 Callable<Void> callable = new Callable<Void>() { 1348 @Override 1349 public Void call() throws Exception { 1350 // TODO: There is no timeout on this controller. Set one! 1351 HBaseRpcController controller = rpcControllerFactory.newController(); 1352 CompactRegionRequest request = 1353 RequestConverter.buildCompactRegionRequest(hri.getRegionName(), major, family); 1354 admin.compactRegion(controller, request); 1355 return null; 1356 } 1357 }; 1358 ProtobufUtil.call(callable); 1359 } 1360 1361 @Override 1362 public void move(final byte[] encodedRegionName, final byte[] destServerName) throws IOException { 1363 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 1364 @Override 1365 protected Void rpcCall() throws Exception { 1366 setPriority(encodedRegionName); 1367 MoveRegionRequest request = 1368 RequestConverter.buildMoveRegionRequest(encodedRegionName, 1369 destServerName != null ? ServerName.valueOf(Bytes.toString(destServerName)) : null); 1370 master.moveRegion(getRpcController(), request); 1371 return null; 1372 } 1373 }); 1374 } 1375 1376 @Override 1377 public void assign(final byte [] regionName) throws MasterNotRunningException, 1378 ZooKeeperConnectionException, IOException { 1379 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 1380 @Override 1381 protected Void rpcCall() throws Exception { 1382 setPriority(regionName); 1383 AssignRegionRequest request = 1384 RequestConverter.buildAssignRegionRequest(getRegionName(regionName)); 1385 master.assignRegion(getRpcController(), request); 1386 return null; 1387 } 1388 }); 1389 } 1390 1391 @Override 1392 public void unassign(final byte [] regionName, final boolean force) throws IOException { 1393 final byte[] toBeUnassigned = getRegionName(regionName); 1394 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 1395 @Override 1396 protected Void rpcCall() throws Exception { 1397 setPriority(regionName); 1398 UnassignRegionRequest request = 1399 RequestConverter.buildUnassignRegionRequest(toBeUnassigned, force); 1400 master.unassignRegion(getRpcController(), request); 1401 return null; 1402 } 1403 }); 1404 } 1405 1406 @Override 1407 public void offline(final byte [] regionName) 1408 throws IOException { 1409 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 1410 @Override 1411 protected Void rpcCall() throws Exception { 1412 setPriority(regionName); 1413 master.offlineRegion(getRpcController(), 1414 RequestConverter.buildOfflineRegionRequest(regionName)); 1415 return null; 1416 } 1417 }); 1418 } 1419 1420 @Override 1421 public boolean balancerSwitch(final boolean on, final boolean synchronous) 1422 throws IOException { 1423 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1424 @Override 1425 protected Boolean rpcCall() throws Exception { 1426 SetBalancerRunningRequest req = 1427 RequestConverter.buildSetBalancerRunningRequest(on, synchronous); 1428 return master.setBalancerRunning(getRpcController(), req).getPrevBalanceValue(); 1429 } 1430 }); 1431 } 1432 1433 @Override 1434 public boolean balance() throws IOException { 1435 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1436 @Override 1437 protected Boolean rpcCall() throws Exception { 1438 return master.balance(getRpcController(), 1439 RequestConverter.buildBalanceRequest(false)).getBalancerRan(); 1440 } 1441 }); 1442 } 1443 1444 @Override 1445 public boolean balance(final boolean force) throws IOException { 1446 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1447 @Override 1448 protected Boolean rpcCall() throws Exception { 1449 return master.balance(getRpcController(), 1450 RequestConverter.buildBalanceRequest(force)).getBalancerRan(); 1451 } 1452 }); 1453 } 1454 1455 @Override 1456 public boolean isBalancerEnabled() throws IOException { 1457 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1458 @Override 1459 protected Boolean rpcCall() throws Exception { 1460 return master.isBalancerEnabled(getRpcController(), 1461 RequestConverter.buildIsBalancerEnabledRequest()).getEnabled(); 1462 } 1463 }); 1464 } 1465 1466 /** 1467 * {@inheritDoc} 1468 */ 1469 @Override 1470 public CacheEvictionStats clearBlockCache(final TableName tableName) throws IOException { 1471 checkTableExists(tableName); 1472 CacheEvictionStatsBuilder cacheEvictionStats = CacheEvictionStats.builder(); 1473 List<Pair<RegionInfo, ServerName>> pairs = 1474 MetaTableAccessor.getTableRegionsAndLocations(connection, tableName); 1475 Map<ServerName, List<RegionInfo>> regionInfoByServerName = 1476 pairs.stream() 1477 .filter(pair -> !(pair.getFirst().isOffline())) 1478 .filter(pair -> pair.getSecond() != null) 1479 .collect(Collectors.groupingBy(pair -> pair.getSecond(), 1480 Collectors.mapping(pair -> pair.getFirst(), Collectors.toList()))); 1481 1482 for (Map.Entry<ServerName, List<RegionInfo>> entry : regionInfoByServerName.entrySet()) { 1483 CacheEvictionStats stats = clearBlockCache(entry.getKey(), entry.getValue()); 1484 cacheEvictionStats = cacheEvictionStats.append(stats); 1485 if (stats.getExceptionCount() > 0) { 1486 for (Map.Entry<byte[], Throwable> exception : stats.getExceptions().entrySet()) { 1487 LOG.debug("Failed to clear block cache for " 1488 + Bytes.toStringBinary(exception.getKey()) 1489 + " on " + entry.getKey() + ": ", exception.getValue()); 1490 } 1491 } 1492 } 1493 return cacheEvictionStats.build(); 1494 } 1495 1496 private CacheEvictionStats clearBlockCache(final ServerName sn, final List<RegionInfo> hris) 1497 throws IOException { 1498 HBaseRpcController controller = rpcControllerFactory.newController(); 1499 AdminService.BlockingInterface admin = this.connection.getAdmin(sn); 1500 ClearRegionBlockCacheRequest request = 1501 RequestConverter.buildClearRegionBlockCacheRequest(hris); 1502 ClearRegionBlockCacheResponse response; 1503 try { 1504 response = admin.clearRegionBlockCache(controller, request); 1505 return ProtobufUtil.toCacheEvictionStats(response.getStats()); 1506 } catch (ServiceException se) { 1507 throw ProtobufUtil.getRemoteException(se); 1508 } 1509 } 1510 1511 /** 1512 * Invoke region normalizer. Can NOT run for various reasons. Check logs. 1513 * 1514 * @return True if region normalizer ran, false otherwise. 1515 */ 1516 @Override 1517 public boolean normalize() throws IOException { 1518 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1519 @Override 1520 protected Boolean rpcCall() throws Exception { 1521 return master.normalize(getRpcController(), 1522 RequestConverter.buildNormalizeRequest()).getNormalizerRan(); 1523 } 1524 }); 1525 } 1526 1527 @Override 1528 public boolean isNormalizerEnabled() throws IOException { 1529 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1530 @Override 1531 protected Boolean rpcCall() throws Exception { 1532 return master.isNormalizerEnabled(getRpcController(), 1533 RequestConverter.buildIsNormalizerEnabledRequest()).getEnabled(); 1534 } 1535 }); 1536 } 1537 1538 @Override 1539 public boolean normalizerSwitch(final boolean on) throws IOException { 1540 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1541 @Override 1542 protected Boolean rpcCall() throws Exception { 1543 SetNormalizerRunningRequest req = 1544 RequestConverter.buildSetNormalizerRunningRequest(on); 1545 return master.setNormalizerRunning(getRpcController(), req).getPrevNormalizerValue(); 1546 } 1547 }); 1548 } 1549 1550 @Override 1551 public boolean catalogJanitorSwitch(final boolean enable) throws IOException { 1552 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1553 @Override 1554 protected Boolean rpcCall() throws Exception { 1555 return master.enableCatalogJanitor(getRpcController(), 1556 RequestConverter.buildEnableCatalogJanitorRequest(enable)).getPrevValue(); 1557 } 1558 }); 1559 } 1560 1561 @Override 1562 public int runCatalogJanitor() throws IOException { 1563 return executeCallable(new MasterCallable<Integer>(getConnection(), getRpcControllerFactory()) { 1564 @Override 1565 protected Integer rpcCall() throws Exception { 1566 return master.runCatalogScan(getRpcController(), 1567 RequestConverter.buildCatalogScanRequest()).getScanResult(); 1568 } 1569 }); 1570 } 1571 1572 @Override 1573 public boolean isCatalogJanitorEnabled() throws IOException { 1574 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1575 @Override 1576 protected Boolean rpcCall() throws Exception { 1577 return master.isCatalogJanitorEnabled(getRpcController(), 1578 RequestConverter.buildIsCatalogJanitorEnabledRequest()).getValue(); 1579 } 1580 }); 1581 } 1582 1583 @Override 1584 public boolean cleanerChoreSwitch(final boolean on) throws IOException { 1585 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1586 @Override public Boolean rpcCall() throws Exception { 1587 return master.setCleanerChoreRunning(getRpcController(), 1588 RequestConverter.buildSetCleanerChoreRunningRequest(on)).getPrevValue(); 1589 } 1590 }); 1591 } 1592 1593 @Override 1594 public boolean runCleanerChore() throws IOException { 1595 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1596 @Override public Boolean rpcCall() throws Exception { 1597 return master.runCleanerChore(getRpcController(), 1598 RequestConverter.buildRunCleanerChoreRequest()).getCleanerChoreRan(); 1599 } 1600 }); 1601 } 1602 1603 @Override 1604 public boolean isCleanerChoreEnabled() throws IOException { 1605 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 1606 @Override public Boolean rpcCall() throws Exception { 1607 return master.isCleanerChoreEnabled(getRpcController(), 1608 RequestConverter.buildIsCleanerChoreEnabledRequest()).getValue(); 1609 } 1610 }); 1611 } 1612 1613 /** 1614 * Merge two regions. Synchronous operation. 1615 * Note: It is not feasible to predict the length of merge. 1616 * Therefore, this is for internal testing only. 1617 * @param nameOfRegionA encoded or full name of region a 1618 * @param nameOfRegionB encoded or full name of region b 1619 * @param forcible true if do a compulsory merge, otherwise we will only merge 1620 * two adjacent regions 1621 * @throws IOException 1622 */ 1623 @VisibleForTesting 1624 public void mergeRegionsSync( 1625 final byte[] nameOfRegionA, 1626 final byte[] nameOfRegionB, 1627 final boolean forcible) throws IOException { 1628 get( 1629 mergeRegionsAsync(nameOfRegionA, nameOfRegionB, forcible), 1630 syncWaitTimeout, 1631 TimeUnit.MILLISECONDS); 1632 } 1633 1634 /** 1635 * Merge two regions. Asynchronous operation. 1636 * @param nameOfRegionA encoded or full name of region a 1637 * @param nameOfRegionB encoded or full name of region b 1638 * @param forcible true if do a compulsory merge, otherwise we will only merge 1639 * two adjacent regions 1640 * @throws IOException 1641 * @deprecated Since 2.0. Will be removed in 3.0. Use 1642 * {@link #mergeRegionsAsync(byte[], byte[], boolean)} instead. 1643 */ 1644 @Deprecated 1645 @Override 1646 public void mergeRegions(final byte[] nameOfRegionA, 1647 final byte[] nameOfRegionB, final boolean forcible) 1648 throws IOException { 1649 mergeRegionsAsync(nameOfRegionA, nameOfRegionB, forcible); 1650 } 1651 1652 /** 1653 * Merge two regions. Asynchronous operation. 1654 * @param nameOfRegionA encoded or full name of region a 1655 * @param nameOfRegionB encoded or full name of region b 1656 * @param forcible true if do a compulsory merge, otherwise we will only merge 1657 * two adjacent regions 1658 * @throws IOException 1659 */ 1660 @Override 1661 public Future<Void> mergeRegionsAsync( 1662 final byte[] nameOfRegionA, 1663 final byte[] nameOfRegionB, 1664 final boolean forcible) throws IOException { 1665 byte[][] nameofRegionsToMerge = new byte[2][]; 1666 nameofRegionsToMerge[0] = nameOfRegionA; 1667 nameofRegionsToMerge[1] = nameOfRegionB; 1668 return mergeRegionsAsync(nameofRegionsToMerge, forcible); 1669 } 1670 1671 /** 1672 * Merge two regions. Asynchronous operation. 1673 * @param nameofRegionsToMerge encoded or full name of daughter regions 1674 * @param forcible true if do a compulsory merge, otherwise we will only merge 1675 * adjacent regions 1676 * @throws IOException 1677 */ 1678 @Override 1679 public Future<Void> mergeRegionsAsync( 1680 final byte[][] nameofRegionsToMerge, 1681 final boolean forcible) throws IOException { 1682 assert(nameofRegionsToMerge.length >= 2); 1683 byte[][] encodedNameofRegionsToMerge = new byte[nameofRegionsToMerge.length][]; 1684 for(int i = 0; i < nameofRegionsToMerge.length; i++) { 1685 encodedNameofRegionsToMerge[i] = HRegionInfo.isEncodedRegionName(nameofRegionsToMerge[i]) ? 1686 nameofRegionsToMerge[i] : 1687 Bytes.toBytes(HRegionInfo.encodeRegionName(nameofRegionsToMerge[i])); 1688 } 1689 1690 TableName tableName = null; 1691 Pair<RegionInfo, ServerName> pair; 1692 1693 for(int i = 0; i < nameofRegionsToMerge.length; i++) { 1694 pair = getRegion(nameofRegionsToMerge[i]); 1695 1696 if (pair != null) { 1697 if (pair.getFirst().getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID) { 1698 throw new IllegalArgumentException ("Can't invoke merge on non-default regions directly"); 1699 } 1700 if (tableName == null) { 1701 tableName = pair.getFirst().getTable(); 1702 } else if (!tableName.equals(pair.getFirst().getTable())) { 1703 throw new IllegalArgumentException ("Cannot merge regions from two different tables " + 1704 tableName + " and " + pair.getFirst().getTable()); 1705 } 1706 } else { 1707 throw new UnknownRegionException ( 1708 "Can't invoke merge on unknown region " 1709 + Bytes.toStringBinary(encodedNameofRegionsToMerge[i])); 1710 } 1711 } 1712 1713 MergeTableRegionsResponse response = 1714 executeCallable(new MasterCallable<MergeTableRegionsResponse>(getConnection(), 1715 getRpcControllerFactory()) { 1716 @Override 1717 protected MergeTableRegionsResponse rpcCall() throws Exception { 1718 MergeTableRegionsRequest request = RequestConverter 1719 .buildMergeTableRegionsRequest( 1720 encodedNameofRegionsToMerge, 1721 forcible, 1722 ng.getNonceGroup(), 1723 ng.newNonce()); 1724 return master.mergeTableRegions(getRpcController(), request); 1725 } 1726 }); 1727 return new MergeTableRegionsFuture(this, tableName, response); 1728 } 1729 1730 private static class MergeTableRegionsFuture extends TableFuture<Void> { 1731 public MergeTableRegionsFuture( 1732 final HBaseAdmin admin, 1733 final TableName tableName, 1734 final MergeTableRegionsResponse response) { 1735 super(admin, tableName, 1736 (response != null && response.hasProcId()) ? response.getProcId() : null); 1737 } 1738 1739 public MergeTableRegionsFuture( 1740 final HBaseAdmin admin, 1741 final TableName tableName, 1742 final Long procId) { 1743 super(admin, tableName, procId); 1744 } 1745 1746 @Override 1747 public String getOperationType() { 1748 return "MERGE_REGIONS"; 1749 } 1750 } 1751 /** 1752 * Split one region. Synchronous operation. 1753 * Note: It is not feasible to predict the length of split. 1754 * Therefore, this is for internal testing only. 1755 * @param regionName encoded or full name of region 1756 * @param splitPoint key where region splits 1757 * @throws IOException 1758 */ 1759 @VisibleForTesting 1760 public void splitRegionSync(byte[] regionName, byte[] splitPoint) throws IOException { 1761 splitRegionSync(regionName, splitPoint, syncWaitTimeout, TimeUnit.MILLISECONDS); 1762 } 1763 1764 1765 /** 1766 * Split one region. Synchronous operation. 1767 * @param regionName region to be split 1768 * @param splitPoint split point 1769 * @param timeout how long to wait on split 1770 * @param units time units 1771 * @throws IOException 1772 */ 1773 public void splitRegionSync(byte[] regionName, byte[] splitPoint, 1774 final long timeout, final TimeUnit units) throws IOException { 1775 get( 1776 splitRegionAsync(regionName, splitPoint), 1777 timeout, 1778 units); 1779 } 1780 1781 @Override 1782 public Future<Void> splitRegionAsync(byte[] regionName, byte[] splitPoint) 1783 throws IOException { 1784 byte[] encodedNameofRegionToSplit = HRegionInfo.isEncodedRegionName(regionName) ? 1785 regionName : Bytes.toBytes(HRegionInfo.encodeRegionName(regionName)); 1786 Pair<RegionInfo, ServerName> pair = getRegion(regionName); 1787 if (pair != null) { 1788 if (pair.getFirst() != null && 1789 pair.getFirst().getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID) { 1790 throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); 1791 } 1792 } else { 1793 throw new UnknownRegionException ( 1794 "Can't invoke merge on unknown region " 1795 + Bytes.toStringBinary(encodedNameofRegionToSplit)); 1796 } 1797 1798 return splitRegionAsync(pair.getFirst(), splitPoint); 1799 } 1800 1801 Future<Void> splitRegionAsync(RegionInfo hri, byte[] splitPoint) throws IOException { 1802 TableName tableName = hri.getTable(); 1803 if (hri.getStartKey() != null && splitPoint != null && 1804 Bytes.compareTo(hri.getStartKey(), splitPoint) == 0) { 1805 throw new IOException("should not give a splitkey which equals to startkey!"); 1806 } 1807 1808 SplitTableRegionResponse response = executeCallable( 1809 new MasterCallable<SplitTableRegionResponse>(getConnection(), getRpcControllerFactory()) { 1810 @Override 1811 protected SplitTableRegionResponse rpcCall() throws Exception { 1812 setPriority(tableName); 1813 SplitTableRegionRequest request = RequestConverter 1814 .buildSplitTableRegionRequest(hri, splitPoint, ng.getNonceGroup(), ng.newNonce()); 1815 return master.splitRegion(getRpcController(), request); 1816 } 1817 }); 1818 return new SplitTableRegionFuture(this, tableName, response); 1819 } 1820 1821 private static class SplitTableRegionFuture extends TableFuture<Void> { 1822 public SplitTableRegionFuture(final HBaseAdmin admin, 1823 final TableName tableName, 1824 final SplitTableRegionResponse response) { 1825 super(admin, tableName, 1826 (response != null && response.hasProcId()) ? response.getProcId() : null); 1827 } 1828 1829 public SplitTableRegionFuture( 1830 final HBaseAdmin admin, 1831 final TableName tableName, 1832 final Long procId) { 1833 super(admin, tableName, procId); 1834 } 1835 1836 @Override 1837 public String getOperationType() { 1838 return "SPLIT_REGION"; 1839 } 1840 } 1841 1842 @Override 1843 public void split(final TableName tableName) throws IOException { 1844 split(tableName, null); 1845 } 1846 1847 @Override 1848 public void splitRegion(final byte[] regionName) throws IOException { 1849 splitRegion(regionName, null); 1850 } 1851 1852 @Override 1853 public void split(final TableName tableName, final byte[] splitPoint) throws IOException { 1854 checkTableExists(tableName); 1855 for (HRegionLocation loc : connection.locateRegions(tableName, false, false)) { 1856 ServerName sn = loc.getServerName(); 1857 if (sn == null) { 1858 continue; 1859 } 1860 RegionInfo r = loc.getRegion(); 1861 // check for parents 1862 if (r.isSplitParent()) { 1863 continue; 1864 } 1865 // if a split point given, only split that particular region 1866 if (r.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID || 1867 (splitPoint != null && !r.containsRow(splitPoint))) { 1868 continue; 1869 } 1870 // call out to master to do split now 1871 splitRegionAsync(r, splitPoint); 1872 } 1873 } 1874 1875 @Override 1876 public void splitRegion(final byte[] regionName, final byte [] splitPoint) throws IOException { 1877 Pair<RegionInfo, ServerName> regionServerPair = getRegion(regionName); 1878 if (regionServerPair == null) { 1879 throw new IllegalArgumentException("Invalid region: " + Bytes.toStringBinary(regionName)); 1880 } 1881 if (regionServerPair.getFirst() != null && 1882 regionServerPair.getFirst().getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID) { 1883 throw new IllegalArgumentException("Can't split replicas directly. " 1884 + "Replicas are auto-split when their primary is split."); 1885 } 1886 if (regionServerPair.getSecond() == null) { 1887 throw new NoServerForRegionException(Bytes.toStringBinary(regionName)); 1888 } 1889 splitRegionAsync(regionServerPair.getFirst(), splitPoint); 1890 } 1891 1892 @Override 1893 public void modifyTable(final TableName tableName, final TableDescriptor td) 1894 throws IOException { 1895 get(modifyTableAsync(tableName, td), syncWaitTimeout, TimeUnit.MILLISECONDS); 1896 } 1897 1898 @Override 1899 public Future<Void> modifyTableAsync(final TableName tableName, final TableDescriptor td) 1900 throws IOException { 1901 if (!tableName.equals(td.getTableName())) { 1902 throw new IllegalArgumentException("the specified table name '" + tableName + 1903 "' doesn't match with the HTD one: " + td.getTableName()); 1904 } 1905 return modifyTableAsync(td); 1906 } 1907 1908 private static class ModifyTableFuture extends TableFuture<Void> { 1909 public ModifyTableFuture(final HBaseAdmin admin, final TableName tableName, 1910 final ModifyTableResponse response) { 1911 super(admin, tableName, 1912 (response != null && response.hasProcId()) ? response.getProcId() : null); 1913 } 1914 1915 public ModifyTableFuture(final HBaseAdmin admin, final TableName tableName, final Long procId) { 1916 super(admin, tableName, procId); 1917 } 1918 1919 @Override 1920 public String getOperationType() { 1921 return "MODIFY"; 1922 } 1923 1924 @Override 1925 protected Void postOperationResult(final Void result, final long deadlineTs) 1926 throws IOException, TimeoutException { 1927 // The modify operation on the table is asynchronous on the server side irrespective 1928 // of whether Procedure V2 is supported or not. So, we wait in the client till 1929 // all regions get updated. 1930 waitForSchemaUpdate(deadlineTs); 1931 return result; 1932 } 1933 } 1934 1935 /** 1936 * @param regionName Name of a region. 1937 * @return a pair of HRegionInfo and ServerName if <code>regionName</code> is 1938 * a verified region name (we call {@link 1939 * MetaTableAccessor#getRegionLocation(Connection, byte[])} 1940 * else null. 1941 * Throw IllegalArgumentException if <code>regionName</code> is null. 1942 * @throws IOException 1943 */ 1944 Pair<RegionInfo, ServerName> getRegion(final byte[] regionName) throws IOException { 1945 if (regionName == null) { 1946 throw new IllegalArgumentException("Pass a table name or region name"); 1947 } 1948 Pair<RegionInfo, ServerName> pair = MetaTableAccessor.getRegion(connection, regionName); 1949 if (pair == null) { 1950 final AtomicReference<Pair<RegionInfo, ServerName>> result = new AtomicReference<>(null); 1951 final String encodedName = Bytes.toString(regionName); 1952 MetaTableAccessor.Visitor visitor = new MetaTableAccessor.Visitor() { 1953 @Override 1954 public boolean visit(Result data) throws IOException { 1955 RegionInfo info = MetaTableAccessor.getRegionInfo(data); 1956 if (info == null) { 1957 LOG.warn("No serialized HRegionInfo in " + data); 1958 return true; 1959 } 1960 RegionLocations rl = MetaTableAccessor.getRegionLocations(data); 1961 boolean matched = false; 1962 ServerName sn = null; 1963 if (rl != null) { 1964 for (HRegionLocation h : rl.getRegionLocations()) { 1965 if (h != null && encodedName.equals(h.getRegionInfo().getEncodedName())) { 1966 sn = h.getServerName(); 1967 info = h.getRegionInfo(); 1968 matched = true; 1969 } 1970 } 1971 } 1972 if (!matched) return true; 1973 result.set(new Pair<>(info, sn)); 1974 return false; // found the region, stop 1975 } 1976 }; 1977 1978 MetaTableAccessor.fullScanRegions(connection, visitor); 1979 pair = result.get(); 1980 } 1981 return pair; 1982 } 1983 1984 /** 1985 * If the input is a region name, it is returned as is. If it's an 1986 * encoded region name, the corresponding region is found from meta 1987 * and its region name is returned. If we can't find any region in 1988 * meta matching the input as either region name or encoded region 1989 * name, the input is returned as is. We don't throw unknown 1990 * region exception. 1991 */ 1992 private byte[] getRegionName( 1993 final byte[] regionNameOrEncodedRegionName) throws IOException { 1994 if (Bytes.equals(regionNameOrEncodedRegionName, 1995 HRegionInfo.FIRST_META_REGIONINFO.getRegionName()) 1996 || Bytes.equals(regionNameOrEncodedRegionName, 1997 HRegionInfo.FIRST_META_REGIONINFO.getEncodedNameAsBytes())) { 1998 return HRegionInfo.FIRST_META_REGIONINFO.getRegionName(); 1999 } 2000 byte[] tmp = regionNameOrEncodedRegionName; 2001 Pair<RegionInfo, ServerName> regionServerPair = getRegion(regionNameOrEncodedRegionName); 2002 if (regionServerPair != null && regionServerPair.getFirst() != null) { 2003 tmp = regionServerPair.getFirst().getRegionName(); 2004 } 2005 return tmp; 2006 } 2007 2008 /** 2009 * Check if table exists or not 2010 * @param tableName Name of a table. 2011 * @return tableName instance 2012 * @throws IOException if a remote or network exception occurs. 2013 * @throws TableNotFoundException if table does not exist. 2014 */ 2015 private TableName checkTableExists(final TableName tableName) 2016 throws IOException { 2017 return executeCallable(new RpcRetryingCallable<TableName>() { 2018 @Override 2019 protected TableName rpcCall(int callTimeout) throws Exception { 2020 if (!MetaTableAccessor.tableExists(connection, tableName)) { 2021 throw new TableNotFoundException(tableName); 2022 } 2023 return tableName; 2024 } 2025 }); 2026 } 2027 2028 @Override 2029 public synchronized void shutdown() throws IOException { 2030 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 2031 @Override 2032 protected Void rpcCall() throws Exception { 2033 setPriority(HConstants.HIGH_QOS); 2034 master.shutdown(getRpcController(), ShutdownRequest.newBuilder().build()); 2035 return null; 2036 } 2037 }); 2038 } 2039 2040 @Override 2041 public synchronized void stopMaster() throws IOException { 2042 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 2043 @Override 2044 protected Void rpcCall() throws Exception { 2045 setPriority(HConstants.HIGH_QOS); 2046 master.stopMaster(getRpcController(), StopMasterRequest.newBuilder().build()); 2047 return null; 2048 } 2049 }); 2050 } 2051 2052 @Override 2053 public synchronized void stopRegionServer(final String hostnamePort) 2054 throws IOException { 2055 String hostname = Addressing.parseHostname(hostnamePort); 2056 int port = Addressing.parsePort(hostnamePort); 2057 final AdminService.BlockingInterface admin = 2058 this.connection.getAdmin(ServerName.valueOf(hostname, port, 0)); 2059 // TODO: There is no timeout on this controller. Set one! 2060 HBaseRpcController controller = rpcControllerFactory.newController(); 2061 controller.setPriority(HConstants.HIGH_QOS); 2062 StopServerRequest request = RequestConverter.buildStopServerRequest( 2063 "Called by admin client " + this.connection.toString()); 2064 try { 2065 admin.stopServer(controller, request); 2066 } catch (Exception e) { 2067 throw ProtobufUtil.handleRemoteException(e); 2068 } 2069 } 2070 2071 @Override 2072 public boolean isMasterInMaintenanceMode() throws IOException { 2073 return executeCallable(new MasterCallable<IsInMaintenanceModeResponse>(getConnection(), 2074 this.rpcControllerFactory) { 2075 @Override 2076 protected IsInMaintenanceModeResponse rpcCall() throws Exception { 2077 return master.isMasterInMaintenanceMode(getRpcController(), 2078 IsInMaintenanceModeRequest.newBuilder().build()); 2079 } 2080 }).getInMaintenanceMode(); 2081 } 2082 2083 @Override 2084 public ClusterMetrics getClusterMetrics(EnumSet<Option> options) throws IOException { 2085 return executeCallable(new MasterCallable<ClusterMetrics>(getConnection(), 2086 this.rpcControllerFactory) { 2087 @Override 2088 protected ClusterMetrics rpcCall() throws Exception { 2089 GetClusterStatusRequest req = RequestConverter.buildGetClusterStatusRequest(options); 2090 return ClusterMetricsBuilder.toClusterMetrics( 2091 master.getClusterStatus(getRpcController(), req).getClusterStatus()); 2092 } 2093 }); 2094 } 2095 2096 @Override 2097 public List<RegionMetrics> getRegionMetrics(ServerName serverName, TableName tableName) 2098 throws IOException { 2099 AdminService.BlockingInterface admin = this.connection.getAdmin(serverName); 2100 HBaseRpcController controller = rpcControllerFactory.newController(); 2101 AdminProtos.GetRegionLoadRequest request = 2102 RequestConverter.buildGetRegionLoadRequest(tableName); 2103 try { 2104 return admin.getRegionLoad(controller, request).getRegionLoadsList().stream() 2105 .map(RegionMetricsBuilder::toRegionMetrics).collect(Collectors.toList()); 2106 } catch (ServiceException se) { 2107 throw ProtobufUtil.getRemoteException(se); 2108 } 2109 } 2110 2111 @Override 2112 public Configuration getConfiguration() { 2113 return this.conf; 2114 } 2115 2116 /** 2117 * Do a get with a timeout against the passed in <code>future</code>. 2118 */ 2119 private static <T> T get(final Future<T> future, final long timeout, final TimeUnit units) 2120 throws IOException { 2121 try { 2122 // TODO: how long should we wait? Spin forever? 2123 return future.get(timeout, units); 2124 } catch (InterruptedException e) { 2125 throw new InterruptedIOException("Interrupt while waiting on " + future); 2126 } catch (TimeoutException e) { 2127 throw new TimeoutIOException(e); 2128 } catch (ExecutionException e) { 2129 if (e.getCause() instanceof IOException) { 2130 throw (IOException)e.getCause(); 2131 } else { 2132 throw new IOException(e.getCause()); 2133 } 2134 } 2135 } 2136 2137 @Override 2138 public void createNamespace(final NamespaceDescriptor descriptor) 2139 throws IOException { 2140 get(createNamespaceAsync(descriptor), this.syncWaitTimeout, TimeUnit.MILLISECONDS); 2141 } 2142 2143 @Override 2144 public Future<Void> createNamespaceAsync(final NamespaceDescriptor descriptor) 2145 throws IOException { 2146 CreateNamespaceResponse response = 2147 executeCallable(new MasterCallable<CreateNamespaceResponse>(getConnection(), 2148 getRpcControllerFactory()) { 2149 @Override 2150 protected CreateNamespaceResponse rpcCall() throws Exception { 2151 return master.createNamespace(getRpcController(), 2152 CreateNamespaceRequest.newBuilder().setNamespaceDescriptor(ProtobufUtil. 2153 toProtoNamespaceDescriptor(descriptor)).build()); 2154 } 2155 }); 2156 return new NamespaceFuture(this, descriptor.getName(), response.getProcId()) { 2157 @Override 2158 public String getOperationType() { 2159 return "CREATE_NAMESPACE"; 2160 } 2161 }; 2162 } 2163 2164 @Override 2165 public void modifyNamespace(final NamespaceDescriptor descriptor) 2166 throws IOException { 2167 get(modifyNamespaceAsync(descriptor), this.syncWaitTimeout, TimeUnit.MILLISECONDS); 2168 } 2169 2170 @Override 2171 public Future<Void> modifyNamespaceAsync(final NamespaceDescriptor descriptor) 2172 throws IOException { 2173 ModifyNamespaceResponse response = 2174 executeCallable(new MasterCallable<ModifyNamespaceResponse>(getConnection(), 2175 getRpcControllerFactory()) { 2176 @Override 2177 protected ModifyNamespaceResponse rpcCall() throws Exception { 2178 // TODO: set priority based on NS? 2179 return master.modifyNamespace(getRpcController(), ModifyNamespaceRequest.newBuilder(). 2180 setNamespaceDescriptor(ProtobufUtil.toProtoNamespaceDescriptor(descriptor)).build()); 2181 } 2182 }); 2183 return new NamespaceFuture(this, descriptor.getName(), response.getProcId()) { 2184 @Override 2185 public String getOperationType() { 2186 return "MODIFY_NAMESPACE"; 2187 } 2188 }; 2189 } 2190 2191 @Override 2192 public void deleteNamespace(final String name) 2193 throws IOException { 2194 get(deleteNamespaceAsync(name), this.syncWaitTimeout, TimeUnit.MILLISECONDS); 2195 } 2196 2197 @Override 2198 public Future<Void> deleteNamespaceAsync(final String name) 2199 throws IOException { 2200 DeleteNamespaceResponse response = 2201 executeCallable(new MasterCallable<DeleteNamespaceResponse>(getConnection(), 2202 getRpcControllerFactory()) { 2203 @Override 2204 protected DeleteNamespaceResponse rpcCall() throws Exception { 2205 // TODO: set priority based on NS? 2206 return master.deleteNamespace(getRpcController(), DeleteNamespaceRequest.newBuilder(). 2207 setNamespaceName(name).build()); 2208 } 2209 }); 2210 return new NamespaceFuture(this, name, response.getProcId()) { 2211 @Override 2212 public String getOperationType() { 2213 return "DELETE_NAMESPACE"; 2214 } 2215 }; 2216 } 2217 2218 @Override 2219 public NamespaceDescriptor getNamespaceDescriptor(final String name) 2220 throws NamespaceNotFoundException, IOException { 2221 return executeCallable(new MasterCallable<NamespaceDescriptor>(getConnection(), 2222 getRpcControllerFactory()) { 2223 @Override 2224 protected NamespaceDescriptor rpcCall() throws Exception { 2225 return ProtobufUtil.toNamespaceDescriptor( 2226 master.getNamespaceDescriptor(getRpcController(), 2227 GetNamespaceDescriptorRequest.newBuilder(). 2228 setNamespaceName(name).build()).getNamespaceDescriptor()); 2229 } 2230 }); 2231 } 2232 2233 @Override 2234 public NamespaceDescriptor[] listNamespaceDescriptors() throws IOException { 2235 return executeCallable(new MasterCallable<NamespaceDescriptor[]>(getConnection(), 2236 getRpcControllerFactory()) { 2237 @Override 2238 protected NamespaceDescriptor[] rpcCall() throws Exception { 2239 List<HBaseProtos.NamespaceDescriptor> list = 2240 master.listNamespaceDescriptors(getRpcController(), 2241 ListNamespaceDescriptorsRequest.newBuilder().build()).getNamespaceDescriptorList(); 2242 NamespaceDescriptor[] res = new NamespaceDescriptor[list.size()]; 2243 for(int i = 0; i < list.size(); i++) { 2244 res[i] = ProtobufUtil.toNamespaceDescriptor(list.get(i)); 2245 } 2246 return res; 2247 } 2248 }); 2249 } 2250 2251 @Override 2252 public String getProcedures() throws IOException { 2253 return executeCallable(new MasterCallable<String>(getConnection(), 2254 getRpcControllerFactory()) { 2255 @Override 2256 protected String rpcCall() throws Exception { 2257 GetProceduresRequest request = GetProceduresRequest.newBuilder().build(); 2258 GetProceduresResponse response = master.getProcedures(getRpcController(), request); 2259 return ProtobufUtil.toProcedureJson(response.getProcedureList()); 2260 } 2261 }); 2262 } 2263 2264 @Override 2265 public String getLocks() throws IOException { 2266 return executeCallable(new MasterCallable<String>(getConnection(), 2267 getRpcControllerFactory()) { 2268 @Override 2269 protected String rpcCall() throws Exception { 2270 GetLocksRequest request = GetLocksRequest.newBuilder().build(); 2271 GetLocksResponse response = master.getLocks(getRpcController(), request); 2272 return ProtobufUtil.toLockJson(response.getLockList()); 2273 } 2274 }); 2275 } 2276 2277 @Override 2278 public HTableDescriptor[] listTableDescriptorsByNamespace(final String name) throws IOException { 2279 return executeCallable(new MasterCallable<HTableDescriptor[]>(getConnection(), 2280 getRpcControllerFactory()) { 2281 @Override 2282 protected HTableDescriptor[] rpcCall() throws Exception { 2283 List<TableSchema> list = 2284 master.listTableDescriptorsByNamespace(getRpcController(), 2285 ListTableDescriptorsByNamespaceRequest.newBuilder().setNamespaceName(name) 2286 .build()).getTableSchemaList(); 2287 HTableDescriptor[] res = new HTableDescriptor[list.size()]; 2288 for(int i=0; i < list.size(); i++) { 2289 res[i] = new ImmutableHTableDescriptor(ProtobufUtil.toTableDescriptor(list.get(i))); 2290 } 2291 return res; 2292 } 2293 }); 2294 } 2295 2296 @Override 2297 public TableName[] listTableNamesByNamespace(final String name) throws IOException { 2298 return executeCallable(new MasterCallable<TableName[]>(getConnection(), 2299 getRpcControllerFactory()) { 2300 @Override 2301 protected TableName[] rpcCall() throws Exception { 2302 List<HBaseProtos.TableName> tableNames = 2303 master.listTableNamesByNamespace(getRpcController(), ListTableNamesByNamespaceRequest. 2304 newBuilder().setNamespaceName(name).build()) 2305 .getTableNameList(); 2306 TableName[] result = new TableName[tableNames.size()]; 2307 for (int i = 0; i < tableNames.size(); i++) { 2308 result[i] = ProtobufUtil.toTableName(tableNames.get(i)); 2309 } 2310 return result; 2311 } 2312 }); 2313 } 2314 2315 /** 2316 * Is HBase available? Throw an exception if not. 2317 * @param conf system configuration 2318 * @throws MasterNotRunningException if the master is not running. 2319 * @throws ZooKeeperConnectionException if unable to connect to zookeeper. // TODO do not expose 2320 * ZKConnectionException. 2321 */ 2322 public static void available(final Configuration conf) 2323 throws MasterNotRunningException, ZooKeeperConnectionException, IOException { 2324 Configuration copyOfConf = HBaseConfiguration.create(conf); 2325 // We set it to make it fail as soon as possible if HBase is not available 2326 copyOfConf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1); 2327 copyOfConf.setInt("zookeeper.recovery.retry", 0); 2328 2329 // Check ZK first. 2330 // If the connection exists, we may have a connection to ZK that does not work anymore 2331 try (ClusterConnection connection = 2332 (ClusterConnection) ConnectionFactory.createConnection(copyOfConf)) { 2333 // can throw MasterNotRunningException 2334 connection.isMasterRunning(); 2335 } 2336 } 2337 2338 /** 2339 * 2340 * @param tableName 2341 * @return List of {@link HRegionInfo}. 2342 * @throws IOException 2343 * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0 2344 * Use {@link #getRegions(TableName)}. 2345 */ 2346 @Deprecated 2347 @Override 2348 public List<HRegionInfo> getTableRegions(final TableName tableName) 2349 throws IOException { 2350 return getRegions(tableName).stream() 2351 .map(ImmutableHRegionInfo::new) 2352 .collect(Collectors.toList()); 2353 } 2354 2355 @Override 2356 public synchronized void close() throws IOException { 2357 } 2358 2359 @Override 2360 public HTableDescriptor[] getTableDescriptorsByTableName(final List<TableName> tableNames) 2361 throws IOException { 2362 return executeCallable(new MasterCallable<HTableDescriptor[]>(getConnection(), 2363 getRpcControllerFactory()) { 2364 @Override 2365 protected HTableDescriptor[] rpcCall() throws Exception { 2366 GetTableDescriptorsRequest req = 2367 RequestConverter.buildGetTableDescriptorsRequest(tableNames); 2368 return ProtobufUtil 2369 .toTableDescriptorList(master.getTableDescriptors(getRpcController(), req)).stream() 2370 .map(ImmutableHTableDescriptor::new).toArray(HTableDescriptor[]::new); 2371 } 2372 }); 2373 } 2374 2375 @Override 2376 public HTableDescriptor[] getTableDescriptors(List<String> names) 2377 throws IOException { 2378 List<TableName> tableNames = new ArrayList<>(names.size()); 2379 for(String name : names) { 2380 tableNames.add(TableName.valueOf(name)); 2381 } 2382 return getTableDescriptorsByTableName(tableNames); 2383 } 2384 2385 private RollWALWriterResponse rollWALWriterImpl(final ServerName sn) throws IOException, 2386 FailedLogCloseException { 2387 final AdminService.BlockingInterface admin = this.connection.getAdmin(sn); 2388 RollWALWriterRequest request = RequestConverter.buildRollWALWriterRequest(); 2389 // TODO: There is no timeout on this controller. Set one! 2390 HBaseRpcController controller = rpcControllerFactory.newController(); 2391 try { 2392 return admin.rollWALWriter(controller, request); 2393 } catch (ServiceException e) { 2394 throw ProtobufUtil.handleRemoteException(e); 2395 } 2396 } 2397 2398 /** 2399 * Roll the log writer. I.e. when using a file system based write ahead log, 2400 * start writing log messages to a new file. 2401 * 2402 * Note that when talking to a version 1.0+ HBase deployment, the rolling is asynchronous. 2403 * This method will return as soon as the roll is requested and the return value will 2404 * always be null. Additionally, the named region server may schedule store flushes at the 2405 * request of the wal handling the roll request. 2406 * 2407 * When talking to a 0.98 or older HBase deployment, the rolling is synchronous and the 2408 * return value may be either null or a list of encoded region names. 2409 * 2410 * @param serverName 2411 * The servername of the regionserver. A server name is made of host, 2412 * port and startcode. This is mandatory. Here is an example: 2413 * <code> host187.example.com,60020,1289493121758</code> 2414 * @return a set of {@link HRegionInfo#getEncodedName()} that would allow the wal to 2415 * clean up some underlying files. null if there's nothing to flush. 2416 * @throws IOException if a remote or network exception occurs 2417 * @throws FailedLogCloseException 2418 * @deprecated use {@link #rollWALWriter(ServerName)} 2419 */ 2420 @Deprecated 2421 public synchronized byte[][] rollHLogWriter(String serverName) 2422 throws IOException, FailedLogCloseException { 2423 ServerName sn = ServerName.valueOf(serverName); 2424 final RollWALWriterResponse response = rollWALWriterImpl(sn); 2425 int regionCount = response.getRegionToFlushCount(); 2426 if (0 == regionCount) { 2427 return null; 2428 } 2429 byte[][] regionsToFlush = new byte[regionCount][]; 2430 for (int i = 0; i < regionCount; i++) { 2431 regionsToFlush[i] = ProtobufUtil.toBytes(response.getRegionToFlush(i)); 2432 } 2433 return regionsToFlush; 2434 } 2435 2436 @Override 2437 public synchronized void rollWALWriter(ServerName serverName) 2438 throws IOException, FailedLogCloseException { 2439 rollWALWriterImpl(serverName); 2440 } 2441 2442 @Override 2443 public CompactionState getCompactionState(final TableName tableName) 2444 throws IOException { 2445 return getCompactionState(tableName, CompactType.NORMAL); 2446 } 2447 2448 @Override 2449 public CompactionState getCompactionStateForRegion(final byte[] regionName) 2450 throws IOException { 2451 final Pair<RegionInfo, ServerName> regionServerPair = getRegion(regionName); 2452 if (regionServerPair == null) { 2453 throw new IllegalArgumentException("Invalid region: " + Bytes.toStringBinary(regionName)); 2454 } 2455 if (regionServerPair.getSecond() == null) { 2456 throw new NoServerForRegionException(Bytes.toStringBinary(regionName)); 2457 } 2458 ServerName sn = regionServerPair.getSecond(); 2459 final AdminService.BlockingInterface admin = this.connection.getAdmin(sn); 2460 // TODO: There is no timeout on this controller. Set one! 2461 HBaseRpcController controller = rpcControllerFactory.newController(); 2462 GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest( 2463 regionServerPair.getFirst().getRegionName(), true); 2464 GetRegionInfoResponse response; 2465 try { 2466 response = admin.getRegionInfo(controller, request); 2467 } catch (ServiceException e) { 2468 throw ProtobufUtil.handleRemoteException(e); 2469 } 2470 if (response.getCompactionState() != null) { 2471 return ProtobufUtil.createCompactionState(response.getCompactionState()); 2472 } 2473 return null; 2474 } 2475 2476 @Override 2477 public void snapshot(final String snapshotName, 2478 final TableName tableName) throws IOException, 2479 SnapshotCreationException, IllegalArgumentException { 2480 snapshot(snapshotName, tableName, SnapshotType.FLUSH); 2481 } 2482 2483 @Override 2484 public void snapshot(final byte[] snapshotName, final TableName tableName) 2485 throws IOException, SnapshotCreationException, IllegalArgumentException { 2486 snapshot(Bytes.toString(snapshotName), tableName, SnapshotType.FLUSH); 2487 } 2488 2489 @Override 2490 public void snapshot(final String snapshotName, final TableName tableName, 2491 SnapshotType type) 2492 throws IOException, SnapshotCreationException, IllegalArgumentException { 2493 snapshot(new SnapshotDescription(snapshotName, tableName, type)); 2494 } 2495 2496 @Override 2497 public void snapshot(SnapshotDescription snapshotDesc) 2498 throws IOException, SnapshotCreationException, IllegalArgumentException { 2499 // actually take the snapshot 2500 SnapshotProtos.SnapshotDescription snapshot = 2501 ProtobufUtil.createHBaseProtosSnapshotDesc(snapshotDesc); 2502 SnapshotResponse response = asyncSnapshot(snapshot); 2503 final IsSnapshotDoneRequest request = 2504 IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot).build(); 2505 IsSnapshotDoneResponse done = null; 2506 long start = EnvironmentEdgeManager.currentTime(); 2507 long max = response.getExpectedTimeout(); 2508 long maxPauseTime = max / this.numRetries; 2509 int tries = 0; 2510 LOG.debug("Waiting a max of " + max + " ms for snapshot '" + 2511 ClientSnapshotDescriptionUtils.toString(snapshot) + "'' to complete. (max " + 2512 maxPauseTime + " ms per retry)"); 2513 while (tries == 0 2514 || ((EnvironmentEdgeManager.currentTime() - start) < max && !done.getDone())) { 2515 try { 2516 // sleep a backoff <= pauseTime amount 2517 long sleep = getPauseTime(tries++); 2518 sleep = sleep > maxPauseTime ? maxPauseTime : sleep; 2519 LOG.debug("(#" + tries + ") Sleeping: " + sleep + 2520 "ms while waiting for snapshot completion."); 2521 Thread.sleep(sleep); 2522 } catch (InterruptedException e) { 2523 throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e); 2524 } 2525 LOG.debug("Getting current status of snapshot from master..."); 2526 done = executeCallable(new MasterCallable<IsSnapshotDoneResponse>(getConnection(), 2527 getRpcControllerFactory()) { 2528 @Override 2529 protected IsSnapshotDoneResponse rpcCall() throws Exception { 2530 return master.isSnapshotDone(getRpcController(), request); 2531 } 2532 }); 2533 } 2534 if (!done.getDone()) { 2535 throw new SnapshotCreationException("Snapshot '" + snapshot.getName() 2536 + "' wasn't completed in expectedTime:" + max + " ms", snapshotDesc); 2537 } 2538 } 2539 2540 @Override 2541 public void snapshotAsync(SnapshotDescription snapshotDesc) throws IOException, 2542 SnapshotCreationException { 2543 asyncSnapshot(ProtobufUtil.createHBaseProtosSnapshotDesc(snapshotDesc)); 2544 } 2545 2546 private SnapshotResponse asyncSnapshot(SnapshotProtos.SnapshotDescription snapshot) 2547 throws IOException { 2548 ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot); 2549 final SnapshotRequest request = SnapshotRequest.newBuilder().setSnapshot(snapshot) 2550 .build(); 2551 // run the snapshot on the master 2552 return executeCallable(new MasterCallable<SnapshotResponse>(getConnection(), 2553 getRpcControllerFactory()) { 2554 @Override 2555 protected SnapshotResponse rpcCall() throws Exception { 2556 return master.snapshot(getRpcController(), request); 2557 } 2558 }); 2559 } 2560 2561 @Override 2562 public boolean isSnapshotFinished(final SnapshotDescription snapshotDesc) 2563 throws IOException, HBaseSnapshotException, UnknownSnapshotException { 2564 final SnapshotProtos.SnapshotDescription snapshot = 2565 ProtobufUtil.createHBaseProtosSnapshotDesc(snapshotDesc); 2566 return executeCallable(new MasterCallable<IsSnapshotDoneResponse>(getConnection(), 2567 getRpcControllerFactory()) { 2568 @Override 2569 protected IsSnapshotDoneResponse rpcCall() throws Exception { 2570 return master.isSnapshotDone(getRpcController(), 2571 IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot).build()); 2572 } 2573 }).getDone(); 2574 } 2575 2576 @Override 2577 public void restoreSnapshot(final byte[] snapshotName) 2578 throws IOException, RestoreSnapshotException { 2579 restoreSnapshot(Bytes.toString(snapshotName)); 2580 } 2581 2582 @Override 2583 public void restoreSnapshot(final String snapshotName) 2584 throws IOException, RestoreSnapshotException { 2585 boolean takeFailSafeSnapshot = 2586 conf.getBoolean(HConstants.SNAPSHOT_RESTORE_TAKE_FAILSAFE_SNAPSHOT, 2587 HConstants.DEFAULT_SNAPSHOT_RESTORE_TAKE_FAILSAFE_SNAPSHOT); 2588 restoreSnapshot(snapshotName, takeFailSafeSnapshot); 2589 } 2590 2591 @Override 2592 public void restoreSnapshot(final byte[] snapshotName, final boolean takeFailSafeSnapshot) 2593 throws IOException, RestoreSnapshotException { 2594 restoreSnapshot(Bytes.toString(snapshotName), takeFailSafeSnapshot); 2595 } 2596 2597 /* 2598 * Check whether the snapshot exists and contains disabled table 2599 * 2600 * @param snapshotName name of the snapshot to restore 2601 * @throws IOException if a remote or network exception occurs 2602 * @throws RestoreSnapshotException if no valid snapshot is found 2603 */ 2604 private TableName getTableNameBeforeRestoreSnapshot(final String snapshotName) 2605 throws IOException, RestoreSnapshotException { 2606 TableName tableName = null; 2607 for (SnapshotDescription snapshotInfo: listSnapshots()) { 2608 if (snapshotInfo.getName().equals(snapshotName)) { 2609 tableName = snapshotInfo.getTableName(); 2610 break; 2611 } 2612 } 2613 2614 if (tableName == null) { 2615 throw new RestoreSnapshotException( 2616 "Unable to find the table name for snapshot=" + snapshotName); 2617 } 2618 return tableName; 2619 } 2620 2621 @Override 2622 public void restoreSnapshot(String snapshotName, boolean takeFailSafeSnapshot) 2623 throws IOException, RestoreSnapshotException { 2624 restoreSnapshot(snapshotName, takeFailSafeSnapshot, false); 2625 } 2626 2627 @Override 2628 public void restoreSnapshot(final String snapshotName, final boolean takeFailSafeSnapshot, 2629 final boolean restoreAcl) throws IOException, RestoreSnapshotException { 2630 TableName tableName = getTableNameBeforeRestoreSnapshot(snapshotName); 2631 2632 // The table does not exists, switch to clone. 2633 if (!tableExists(tableName)) { 2634 cloneSnapshot(snapshotName, tableName, restoreAcl); 2635 return; 2636 } 2637 2638 // Check if the table is disabled 2639 if (!isTableDisabled(tableName)) { 2640 throw new TableNotDisabledException(tableName); 2641 } 2642 2643 // Take a snapshot of the current state 2644 String failSafeSnapshotSnapshotName = null; 2645 if (takeFailSafeSnapshot) { 2646 failSafeSnapshotSnapshotName = conf.get("hbase.snapshot.restore.failsafe.name", 2647 "hbase-failsafe-{snapshot.name}-{restore.timestamp}"); 2648 failSafeSnapshotSnapshotName = failSafeSnapshotSnapshotName 2649 .replace("{snapshot.name}", snapshotName) 2650 .replace("{table.name}", tableName.toString().replace(TableName.NAMESPACE_DELIM, '.')) 2651 .replace("{restore.timestamp}", String.valueOf(EnvironmentEdgeManager.currentTime())); 2652 LOG.info("Taking restore-failsafe snapshot: " + failSafeSnapshotSnapshotName); 2653 snapshot(failSafeSnapshotSnapshotName, tableName); 2654 } 2655 2656 try { 2657 // Restore snapshot 2658 get( 2659 internalRestoreSnapshotAsync(snapshotName, tableName, restoreAcl), 2660 syncWaitTimeout, 2661 TimeUnit.MILLISECONDS); 2662 } catch (IOException e) { 2663 // Something went wrong during the restore... 2664 // if the pre-restore snapshot is available try to rollback 2665 if (takeFailSafeSnapshot) { 2666 try { 2667 get( 2668 internalRestoreSnapshotAsync(failSafeSnapshotSnapshotName, tableName, restoreAcl), 2669 syncWaitTimeout, 2670 TimeUnit.MILLISECONDS); 2671 String msg = "Restore snapshot=" + snapshotName + 2672 " failed. Rollback to snapshot=" + failSafeSnapshotSnapshotName + " succeeded."; 2673 LOG.error(msg, e); 2674 throw new RestoreSnapshotException(msg, e); 2675 } catch (IOException ex) { 2676 String msg = "Failed to restore and rollback to snapshot=" + failSafeSnapshotSnapshotName; 2677 LOG.error(msg, ex); 2678 throw new RestoreSnapshotException(msg, e); 2679 } 2680 } else { 2681 throw new RestoreSnapshotException("Failed to restore snapshot=" + snapshotName, e); 2682 } 2683 } 2684 2685 // If the restore is succeeded, delete the pre-restore snapshot 2686 if (takeFailSafeSnapshot) { 2687 try { 2688 LOG.info("Deleting restore-failsafe snapshot: " + failSafeSnapshotSnapshotName); 2689 deleteSnapshot(failSafeSnapshotSnapshotName); 2690 } catch (IOException e) { 2691 LOG.error("Unable to remove the failsafe snapshot: " + failSafeSnapshotSnapshotName, e); 2692 } 2693 } 2694 } 2695 2696 @Override 2697 public Future<Void> restoreSnapshotAsync(final String snapshotName) 2698 throws IOException, RestoreSnapshotException { 2699 TableName tableName = getTableNameBeforeRestoreSnapshot(snapshotName); 2700 2701 // The table does not exists, switch to clone. 2702 if (!tableExists(tableName)) { 2703 return cloneSnapshotAsync(snapshotName, tableName); 2704 } 2705 2706 // Check if the table is disabled 2707 if (!isTableDisabled(tableName)) { 2708 throw new TableNotDisabledException(tableName); 2709 } 2710 2711 return internalRestoreSnapshotAsync(snapshotName, tableName, false); 2712 } 2713 2714 @Override 2715 public void cloneSnapshot(final byte[] snapshotName, final TableName tableName) 2716 throws IOException, TableExistsException, RestoreSnapshotException { 2717 cloneSnapshot(Bytes.toString(snapshotName), tableName); 2718 } 2719 2720 @Override 2721 public void cloneSnapshot(String snapshotName, TableName tableName, boolean restoreAcl) 2722 throws IOException, TableExistsException, RestoreSnapshotException { 2723 if (tableExists(tableName)) { 2724 throw new TableExistsException(tableName); 2725 } 2726 get( 2727 internalRestoreSnapshotAsync(snapshotName, tableName, restoreAcl), 2728 Integer.MAX_VALUE, 2729 TimeUnit.MILLISECONDS); 2730 } 2731 2732 @Override 2733 public void cloneSnapshot(final String snapshotName, final TableName tableName) 2734 throws IOException, TableExistsException, RestoreSnapshotException { 2735 cloneSnapshot(snapshotName, tableName, false); 2736 } 2737 2738 @Override 2739 public Future<Void> cloneSnapshotAsync(final String snapshotName, final TableName tableName) 2740 throws IOException, TableExistsException { 2741 if (tableExists(tableName)) { 2742 throw new TableExistsException(tableName); 2743 } 2744 return internalRestoreSnapshotAsync(snapshotName, tableName, false); 2745 } 2746 2747 @Override 2748 public byte[] execProcedureWithReturn(String signature, String instance, Map<String, 2749 String> props) throws IOException { 2750 ProcedureDescription desc = ProtobufUtil.buildProcedureDescription(signature, instance, props); 2751 final ExecProcedureRequest request = 2752 ExecProcedureRequest.newBuilder().setProcedure(desc).build(); 2753 // run the procedure on the master 2754 ExecProcedureResponse response = executeCallable( 2755 new MasterCallable<ExecProcedureResponse>(getConnection(), getRpcControllerFactory()) { 2756 @Override 2757 protected ExecProcedureResponse rpcCall() throws Exception { 2758 return master.execProcedureWithRet(getRpcController(), request); 2759 } 2760 }); 2761 2762 return response.hasReturnData() ? response.getReturnData().toByteArray() : null; 2763 } 2764 2765 @Override 2766 public void execProcedure(String signature, String instance, Map<String, String> props) 2767 throws IOException { 2768 ProcedureDescription desc = ProtobufUtil.buildProcedureDescription(signature, instance, props); 2769 final ExecProcedureRequest request = 2770 ExecProcedureRequest.newBuilder().setProcedure(desc).build(); 2771 // run the procedure on the master 2772 ExecProcedureResponse response = executeCallable(new MasterCallable<ExecProcedureResponse>( 2773 getConnection(), getRpcControllerFactory()) { 2774 @Override 2775 protected ExecProcedureResponse rpcCall() throws Exception { 2776 return master.execProcedure(getRpcController(), request); 2777 } 2778 }); 2779 2780 long start = EnvironmentEdgeManager.currentTime(); 2781 long max = response.getExpectedTimeout(); 2782 long maxPauseTime = max / this.numRetries; 2783 int tries = 0; 2784 LOG.debug("Waiting a max of " + max + " ms for procedure '" + 2785 signature + " : " + instance + "'' to complete. (max " + maxPauseTime + " ms per retry)"); 2786 boolean done = false; 2787 while (tries == 0 2788 || ((EnvironmentEdgeManager.currentTime() - start) < max && !done)) { 2789 try { 2790 // sleep a backoff <= pauseTime amount 2791 long sleep = getPauseTime(tries++); 2792 sleep = sleep > maxPauseTime ? maxPauseTime : sleep; 2793 LOG.debug("(#" + tries + ") Sleeping: " + sleep + 2794 "ms while waiting for procedure completion."); 2795 Thread.sleep(sleep); 2796 } catch (InterruptedException e) { 2797 throw (InterruptedIOException)new InterruptedIOException("Interrupted").initCause(e); 2798 } 2799 LOG.debug("Getting current status of procedure from master..."); 2800 done = isProcedureFinished(signature, instance, props); 2801 } 2802 if (!done) { 2803 throw new IOException("Procedure '" + signature + " : " + instance 2804 + "' wasn't completed in expectedTime:" + max + " ms"); 2805 } 2806 } 2807 2808 @Override 2809 public boolean isProcedureFinished(String signature, String instance, Map<String, String> props) 2810 throws IOException { 2811 ProcedureDescription desc = ProtobufUtil.buildProcedureDescription(signature, instance, props); 2812 return executeCallable( 2813 new MasterCallable<IsProcedureDoneResponse>(getConnection(), getRpcControllerFactory()) { 2814 @Override 2815 protected IsProcedureDoneResponse rpcCall() throws Exception { 2816 return master.isProcedureDone(getRpcController(), 2817 IsProcedureDoneRequest.newBuilder().setProcedure(desc).build()); 2818 } 2819 }).getDone(); 2820 } 2821 2822 /** 2823 * Execute Restore/Clone snapshot and wait for the server to complete (blocking). 2824 * To check if the cloned table exists, use {@link #isTableAvailable} -- it is not safe to 2825 * create an HTable instance to this table before it is available. 2826 * @param snapshotName snapshot to restore 2827 * @param tableName table name to restore the snapshot on 2828 * @throws IOException if a remote or network exception occurs 2829 * @throws RestoreSnapshotException if snapshot failed to be restored 2830 * @throws IllegalArgumentException if the restore request is formatted incorrectly 2831 */ 2832 private Future<Void> internalRestoreSnapshotAsync(final String snapshotName, 2833 final TableName tableName, final boolean restoreAcl) 2834 throws IOException, RestoreSnapshotException { 2835 final SnapshotProtos.SnapshotDescription snapshot = 2836 SnapshotProtos.SnapshotDescription.newBuilder() 2837 .setName(snapshotName).setTable(tableName.getNameAsString()).build(); 2838 2839 // actually restore the snapshot 2840 ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot); 2841 2842 RestoreSnapshotResponse response = executeCallable( 2843 new MasterCallable<RestoreSnapshotResponse>(getConnection(), getRpcControllerFactory()) { 2844 @Override 2845 protected RestoreSnapshotResponse rpcCall() throws Exception { 2846 final RestoreSnapshotRequest request = RestoreSnapshotRequest.newBuilder() 2847 .setSnapshot(snapshot) 2848 .setNonceGroup(ng.getNonceGroup()) 2849 .setNonce(ng.newNonce()) 2850 .setRestoreACL(restoreAcl) 2851 .build(); 2852 return master.restoreSnapshot(getRpcController(), request); 2853 } 2854 }); 2855 2856 return new RestoreSnapshotFuture(this, snapshot, tableName, response); 2857 } 2858 2859 private static class RestoreSnapshotFuture extends TableFuture<Void> { 2860 public RestoreSnapshotFuture( 2861 final HBaseAdmin admin, 2862 final SnapshotProtos.SnapshotDescription snapshot, 2863 final TableName tableName, 2864 final RestoreSnapshotResponse response) { 2865 super(admin, tableName, 2866 (response != null && response.hasProcId()) ? response.getProcId() : null); 2867 2868 if (response != null && !response.hasProcId()) { 2869 throw new UnsupportedOperationException("Client could not call old version of Server"); 2870 } 2871 } 2872 2873 public RestoreSnapshotFuture( 2874 final HBaseAdmin admin, 2875 final TableName tableName, 2876 final Long procId) { 2877 super(admin, tableName, procId); 2878 } 2879 2880 @Override 2881 public String getOperationType() { 2882 return "MODIFY"; 2883 } 2884 } 2885 2886 @Override 2887 public List<SnapshotDescription> listSnapshots() throws IOException { 2888 return executeCallable(new MasterCallable<List<SnapshotDescription>>(getConnection(), 2889 getRpcControllerFactory()) { 2890 @Override 2891 protected List<SnapshotDescription> rpcCall() throws Exception { 2892 List<SnapshotProtos.SnapshotDescription> snapshotsList = master 2893 .getCompletedSnapshots(getRpcController(), 2894 GetCompletedSnapshotsRequest.newBuilder().build()) 2895 .getSnapshotsList(); 2896 List<SnapshotDescription> result = new ArrayList<>(snapshotsList.size()); 2897 for (SnapshotProtos.SnapshotDescription snapshot : snapshotsList) { 2898 result.add(ProtobufUtil.createSnapshotDesc(snapshot)); 2899 } 2900 return result; 2901 } 2902 }); 2903 } 2904 2905 @Override 2906 public List<SnapshotDescription> listSnapshots(String regex) throws IOException { 2907 return listSnapshots(Pattern.compile(regex)); 2908 } 2909 2910 @Override 2911 public List<SnapshotDescription> listSnapshots(Pattern pattern) throws IOException { 2912 List<SnapshotDescription> matched = new LinkedList<>(); 2913 List<SnapshotDescription> snapshots = listSnapshots(); 2914 for (SnapshotDescription snapshot : snapshots) { 2915 if (pattern.matcher(snapshot.getName()).matches()) { 2916 matched.add(snapshot); 2917 } 2918 } 2919 return matched; 2920 } 2921 2922 @Override 2923 public List<SnapshotDescription> listTableSnapshots(String tableNameRegex, 2924 String snapshotNameRegex) throws IOException { 2925 return listTableSnapshots(Pattern.compile(tableNameRegex), Pattern.compile(snapshotNameRegex)); 2926 } 2927 2928 @Override 2929 public List<SnapshotDescription> listTableSnapshots(Pattern tableNamePattern, 2930 Pattern snapshotNamePattern) throws IOException { 2931 TableName[] tableNames = listTableNames(tableNamePattern); 2932 2933 List<SnapshotDescription> tableSnapshots = new LinkedList<>(); 2934 List<SnapshotDescription> snapshots = listSnapshots(snapshotNamePattern); 2935 2936 List<TableName> listOfTableNames = Arrays.asList(tableNames); 2937 for (SnapshotDescription snapshot : snapshots) { 2938 if (listOfTableNames.contains(snapshot.getTableName())) { 2939 tableSnapshots.add(snapshot); 2940 } 2941 } 2942 return tableSnapshots; 2943 } 2944 2945 @Override 2946 public void deleteSnapshot(final byte[] snapshotName) throws IOException { 2947 deleteSnapshot(Bytes.toString(snapshotName)); 2948 } 2949 2950 @Override 2951 public void deleteSnapshot(final String snapshotName) throws IOException { 2952 // make sure the snapshot is possibly valid 2953 TableName.isLegalFullyQualifiedTableName(Bytes.toBytes(snapshotName)); 2954 // do the delete 2955 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 2956 @Override 2957 protected Void rpcCall() throws Exception { 2958 master.deleteSnapshot(getRpcController(), 2959 DeleteSnapshotRequest.newBuilder().setSnapshot( 2960 SnapshotProtos.SnapshotDescription.newBuilder().setName(snapshotName).build()) 2961 .build() 2962 ); 2963 return null; 2964 } 2965 }); 2966 } 2967 2968 @Override 2969 public void deleteSnapshots(final String regex) throws IOException { 2970 deleteSnapshots(Pattern.compile(regex)); 2971 } 2972 2973 @Override 2974 public void deleteSnapshots(final Pattern pattern) throws IOException { 2975 List<SnapshotDescription> snapshots = listSnapshots(pattern); 2976 for (final SnapshotDescription snapshot : snapshots) { 2977 try { 2978 internalDeleteSnapshot(snapshot); 2979 } catch (IOException ex) { 2980 LOG.info("Failed to delete snapshot " + snapshot.getName() + " for table " 2981 + snapshot.getTableNameAsString(), ex); 2982 } 2983 } 2984 } 2985 2986 private void internalDeleteSnapshot(final SnapshotDescription snapshot) throws IOException { 2987 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 2988 @Override 2989 protected Void rpcCall() throws Exception { 2990 this.master.deleteSnapshot(getRpcController(), DeleteSnapshotRequest.newBuilder() 2991 .setSnapshot(ProtobufUtil.createHBaseProtosSnapshotDesc(snapshot)).build()); 2992 return null; 2993 } 2994 }); 2995 } 2996 2997 @Override 2998 public void deleteTableSnapshots(String tableNameRegex, String snapshotNameRegex) 2999 throws IOException { 3000 deleteTableSnapshots(Pattern.compile(tableNameRegex), Pattern.compile(snapshotNameRegex)); 3001 } 3002 3003 @Override 3004 public void deleteTableSnapshots(Pattern tableNamePattern, Pattern snapshotNamePattern) 3005 throws IOException { 3006 List<SnapshotDescription> snapshots = listTableSnapshots(tableNamePattern, snapshotNamePattern); 3007 for (SnapshotDescription snapshot : snapshots) { 3008 try { 3009 internalDeleteSnapshot(snapshot); 3010 LOG.debug("Successfully deleted snapshot: " + snapshot.getName()); 3011 } catch (IOException e) { 3012 LOG.error("Failed to delete snapshot: " + snapshot.getName(), e); 3013 } 3014 } 3015 } 3016 3017 @Override 3018 public void setQuota(final QuotaSettings quota) throws IOException { 3019 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 3020 @Override 3021 protected Void rpcCall() throws Exception { 3022 this.master.setQuota(getRpcController(), QuotaSettings.buildSetQuotaRequestProto(quota)); 3023 return null; 3024 } 3025 }); 3026 } 3027 3028 @Override 3029 public QuotaRetriever getQuotaRetriever(final QuotaFilter filter) throws IOException { 3030 return QuotaRetriever.open(conf, filter); 3031 } 3032 3033 @Override 3034 public List<QuotaSettings> getQuota(QuotaFilter filter) throws IOException { 3035 List<QuotaSettings> quotas = new LinkedList<>(); 3036 try (QuotaRetriever retriever = QuotaRetriever.open(conf, filter)) { 3037 Iterator<QuotaSettings> iterator = retriever.iterator(); 3038 while (iterator.hasNext()) { 3039 quotas.add(iterator.next()); 3040 } 3041 } 3042 return quotas; 3043 } 3044 3045 private <C extends RetryingCallable<V> & Closeable, V> V executeCallable(C callable) 3046 throws IOException { 3047 return executeCallable(callable, rpcCallerFactory, operationTimeout, rpcTimeout); 3048 } 3049 3050 static private <C extends RetryingCallable<V> & Closeable, V> V executeCallable(C callable, 3051 RpcRetryingCallerFactory rpcCallerFactory, int operationTimeout, int rpcTimeout) 3052 throws IOException { 3053 RpcRetryingCaller<V> caller = rpcCallerFactory.newCaller(rpcTimeout); 3054 try { 3055 return caller.callWithRetries(callable, operationTimeout); 3056 } finally { 3057 callable.close(); 3058 } 3059 } 3060 3061 @Override 3062 // Coprocessor Endpoint against the Master. 3063 public CoprocessorRpcChannel coprocessorService() { 3064 return new SyncCoprocessorRpcChannel() { 3065 @Override 3066 protected Message callExecService(final RpcController controller, 3067 final Descriptors.MethodDescriptor method, final Message request, 3068 final Message responsePrototype) 3069 throws IOException { 3070 if (LOG.isTraceEnabled()) { 3071 LOG.trace("Call: " + method.getName() + ", " + request.toString()); 3072 } 3073 // Try-with-resources so close gets called when we are done. 3074 try (MasterCallable<CoprocessorServiceResponse> callable = 3075 new MasterCallable<CoprocessorServiceResponse>(connection, 3076 connection.getRpcControllerFactory()) { 3077 @Override 3078 protected CoprocessorServiceResponse rpcCall() throws Exception { 3079 CoprocessorServiceRequest csr = 3080 CoprocessorRpcUtils.getCoprocessorServiceRequest(method, request); 3081 return this.master.execMasterService(getRpcController(), csr); 3082 } 3083 }) { 3084 // TODO: Are we retrying here? Does not seem so. We should use RetryingRpcCaller 3085 callable.prepare(false); 3086 int operationTimeout = connection.getConnectionConfiguration().getOperationTimeout(); 3087 CoprocessorServiceResponse result = callable.call(operationTimeout); 3088 return CoprocessorRpcUtils.getResponse(result, responsePrototype); 3089 } 3090 } 3091 }; 3092 } 3093 3094 /** 3095 * Simple {@link Abortable}, throwing RuntimeException on abort. 3096 */ 3097 private static class ThrowableAbortable implements Abortable { 3098 @Override 3099 public void abort(String why, Throwable e) { 3100 throw new RuntimeException(why, e); 3101 } 3102 3103 @Override 3104 public boolean isAborted() { 3105 return true; 3106 } 3107 } 3108 3109 @Override 3110 public CoprocessorRpcChannel coprocessorService(final ServerName serverName) { 3111 return new SyncCoprocessorRpcChannel() { 3112 @Override 3113 protected Message callExecService(RpcController controller, 3114 Descriptors.MethodDescriptor method, Message request, Message responsePrototype) 3115 throws IOException { 3116 if (LOG.isTraceEnabled()) { 3117 LOG.trace("Call: " + method.getName() + ", " + request.toString()); 3118 } 3119 CoprocessorServiceRequest csr = 3120 CoprocessorRpcUtils.getCoprocessorServiceRequest(method, request); 3121 // TODO: Are we retrying here? Does not seem so. We should use RetryingRpcCaller 3122 // TODO: Make this same as RegionCoprocessorRpcChannel and MasterCoprocessorRpcChannel. They 3123 // are all different though should do same thing; e.g. RpcChannel setup. 3124 ClientProtos.ClientService.BlockingInterface stub = connection.getClient(serverName); 3125 CoprocessorServiceResponse result; 3126 try { 3127 result = stub. 3128 execRegionServerService(connection.getRpcControllerFactory().newController(), csr); 3129 return CoprocessorRpcUtils.getResponse(result, responsePrototype); 3130 } catch (ServiceException e) { 3131 throw ProtobufUtil.handleRemoteException(e); 3132 } 3133 } 3134 }; 3135 } 3136 3137 @Override 3138 public void updateConfiguration(final ServerName server) throws IOException { 3139 final AdminService.BlockingInterface admin = this.connection.getAdmin(server); 3140 Callable<Void> callable = new Callable<Void>() { 3141 @Override 3142 public Void call() throws Exception { 3143 admin.updateConfiguration(null, UpdateConfigurationRequest.getDefaultInstance()); 3144 return null; 3145 } 3146 }; 3147 ProtobufUtil.call(callable); 3148 } 3149 3150 @Override 3151 public void updateConfiguration() throws IOException { 3152 ClusterMetrics status = getClusterMetrics( 3153 EnumSet.of(Option.LIVE_SERVERS, Option.MASTER, Option.BACKUP_MASTERS)); 3154 for (ServerName server : status.getLiveServerMetrics().keySet()) { 3155 updateConfiguration(server); 3156 } 3157 3158 updateConfiguration(status.getMasterName()); 3159 3160 for (ServerName server : status.getBackupMasterNames()) { 3161 updateConfiguration(server); 3162 } 3163 } 3164 3165 @Override 3166 public long getLastMajorCompactionTimestamp(final TableName tableName) throws IOException { 3167 return executeCallable(new MasterCallable<Long>(getConnection(), getRpcControllerFactory()) { 3168 @Override 3169 protected Long rpcCall() throws Exception { 3170 MajorCompactionTimestampRequest req = 3171 MajorCompactionTimestampRequest.newBuilder() 3172 .setTableName(ProtobufUtil.toProtoTableName(tableName)).build(); 3173 return master.getLastMajorCompactionTimestamp(getRpcController(), req). 3174 getCompactionTimestamp(); 3175 } 3176 }); 3177 } 3178 3179 @Override 3180 public long getLastMajorCompactionTimestampForRegion(final byte[] regionName) throws IOException { 3181 return executeCallable(new MasterCallable<Long>(getConnection(), getRpcControllerFactory()) { 3182 @Override 3183 protected Long rpcCall() throws Exception { 3184 MajorCompactionTimestampForRegionRequest req = 3185 MajorCompactionTimestampForRegionRequest.newBuilder().setRegion(RequestConverter 3186 .buildRegionSpecifier(RegionSpecifierType.REGION_NAME, regionName)).build(); 3187 return master.getLastMajorCompactionTimestampForRegion(getRpcController(), req) 3188 .getCompactionTimestamp(); 3189 } 3190 }); 3191 } 3192 3193 /** 3194 * {@inheritDoc} 3195 */ 3196 @Override 3197 public void compact(final TableName tableName, final byte[] columnFamily, CompactType compactType) 3198 throws IOException, InterruptedException { 3199 compact(tableName, columnFamily, false, compactType); 3200 } 3201 3202 /** 3203 * {@inheritDoc} 3204 */ 3205 @Override 3206 public void compact(final TableName tableName, CompactType compactType) 3207 throws IOException, InterruptedException { 3208 compact(tableName, null, false, compactType); 3209 } 3210 3211 /** 3212 * {@inheritDoc} 3213 */ 3214 @Override 3215 public void majorCompact(final TableName tableName, final byte[] columnFamily, 3216 CompactType compactType) throws IOException, InterruptedException { 3217 compact(tableName, columnFamily, true, compactType); 3218 } 3219 3220 /** 3221 * {@inheritDoc} 3222 */ 3223 @Override 3224 public void majorCompact(final TableName tableName, CompactType compactType) 3225 throws IOException, InterruptedException { 3226 compact(tableName, null, true, compactType); 3227 } 3228 3229 /** 3230 * {@inheritDoc} 3231 */ 3232 @Override 3233 public CompactionState getCompactionState(final TableName tableName, CompactType compactType) 3234 throws IOException { 3235 AdminProtos.GetRegionInfoResponse.CompactionState state = 3236 AdminProtos.GetRegionInfoResponse.CompactionState.NONE; 3237 checkTableExists(tableName); 3238 // TODO: There is no timeout on this controller. Set one! 3239 HBaseRpcController rpcController = rpcControllerFactory.newController(); 3240 switch (compactType) { 3241 case MOB: 3242 final AdminProtos.AdminService.BlockingInterface masterAdmin = 3243 this.connection.getAdminForMaster(); 3244 Callable<AdminProtos.GetRegionInfoResponse.CompactionState> callable = 3245 new Callable<AdminProtos.GetRegionInfoResponse.CompactionState>() { 3246 @Override 3247 public AdminProtos.GetRegionInfoResponse.CompactionState call() throws Exception { 3248 RegionInfo info = RegionInfo.createMobRegionInfo(tableName); 3249 GetRegionInfoRequest request = 3250 RequestConverter.buildGetRegionInfoRequest(info.getRegionName(), true); 3251 GetRegionInfoResponse response = masterAdmin.getRegionInfo(rpcController, request); 3252 return response.getCompactionState(); 3253 } 3254 }; 3255 state = ProtobufUtil.call(callable); 3256 break; 3257 case NORMAL: 3258 for (HRegionLocation loc : connection.locateRegions(tableName, false, false)) { 3259 ServerName sn = loc.getServerName(); 3260 if (sn == null) { 3261 continue; 3262 } 3263 byte[] regionName = loc.getRegion().getRegionName(); 3264 AdminService.BlockingInterface snAdmin = this.connection.getAdmin(sn); 3265 try { 3266 Callable<GetRegionInfoResponse> regionInfoCallable = 3267 new Callable<GetRegionInfoResponse>() { 3268 @Override 3269 public GetRegionInfoResponse call() throws Exception { 3270 GetRegionInfoRequest request = 3271 RequestConverter.buildGetRegionInfoRequest(regionName, true); 3272 return snAdmin.getRegionInfo(rpcController, request); 3273 } 3274 }; 3275 GetRegionInfoResponse response = ProtobufUtil.call(regionInfoCallable); 3276 switch (response.getCompactionState()) { 3277 case MAJOR_AND_MINOR: 3278 return CompactionState.MAJOR_AND_MINOR; 3279 case MAJOR: 3280 if (state == AdminProtos.GetRegionInfoResponse.CompactionState.MINOR) { 3281 return CompactionState.MAJOR_AND_MINOR; 3282 } 3283 state = AdminProtos.GetRegionInfoResponse.CompactionState.MAJOR; 3284 break; 3285 case MINOR: 3286 if (state == AdminProtos.GetRegionInfoResponse.CompactionState.MAJOR) { 3287 return CompactionState.MAJOR_AND_MINOR; 3288 } 3289 state = AdminProtos.GetRegionInfoResponse.CompactionState.MINOR; 3290 break; 3291 case NONE: 3292 default: // nothing, continue 3293 } 3294 } catch (NotServingRegionException e) { 3295 if (LOG.isDebugEnabled()) { 3296 LOG.debug("Trying to get compaction state of " + loc.getRegion() + ": " + 3297 StringUtils.stringifyException(e)); 3298 } 3299 } catch (RemoteException e) { 3300 if (e.getMessage().indexOf(NotServingRegionException.class.getName()) >= 0) { 3301 if (LOG.isDebugEnabled()) { 3302 LOG.debug("Trying to get compaction state of " + loc.getRegion() + ": " + 3303 StringUtils.stringifyException(e)); 3304 } 3305 } else { 3306 throw e; 3307 } 3308 } 3309 } 3310 break; 3311 default: 3312 throw new IllegalArgumentException("Unknown compactType: " + compactType); 3313 } 3314 if (state != null) { 3315 return ProtobufUtil.createCompactionState(state); 3316 } 3317 return null; 3318 } 3319 3320 /** 3321 * Future that waits on a procedure result. 3322 * Returned by the async version of the Admin calls, 3323 * and used internally by the sync calls to wait on the result of the procedure. 3324 */ 3325 @InterfaceAudience.Private 3326 @InterfaceStability.Evolving 3327 protected static class ProcedureFuture<V> implements Future<V> { 3328 private ExecutionException exception = null; 3329 private boolean procResultFound = false; 3330 private boolean done = false; 3331 private boolean cancelled = false; 3332 private V result = null; 3333 3334 private final HBaseAdmin admin; 3335 private final Long procId; 3336 3337 public ProcedureFuture(final HBaseAdmin admin, final Long procId) { 3338 this.admin = admin; 3339 this.procId = procId; 3340 } 3341 3342 @Override 3343 public boolean cancel(boolean mayInterruptIfRunning) { 3344 AbortProcedureRequest abortProcRequest = AbortProcedureRequest.newBuilder() 3345 .setProcId(procId).setMayInterruptIfRunning(mayInterruptIfRunning).build(); 3346 try { 3347 cancelled = abortProcedureResult(abortProcRequest).getIsProcedureAborted(); 3348 if (cancelled) { 3349 done = true; 3350 } 3351 } catch (IOException e) { 3352 // Cancell thrown exception for some reason. At this time, we are not sure whether 3353 // the cancell succeeds or fails. We assume that it is failed, but print out a warning 3354 // for debugging purpose. 3355 LOG.warn( 3356 "Cancelling the procedure with procId=" + procId + " throws exception " + e.getMessage(), 3357 e); 3358 cancelled = false; 3359 } 3360 return cancelled; 3361 } 3362 3363 @Override 3364 public boolean isCancelled() { 3365 return cancelled; 3366 } 3367 3368 protected AbortProcedureResponse abortProcedureResult( 3369 final AbortProcedureRequest request) throws IOException { 3370 return admin.executeCallable(new MasterCallable<AbortProcedureResponse>( 3371 admin.getConnection(), admin.getRpcControllerFactory()) { 3372 @Override 3373 protected AbortProcedureResponse rpcCall() throws Exception { 3374 return master.abortProcedure(getRpcController(), request); 3375 } 3376 }); 3377 } 3378 3379 @Override 3380 public V get() throws InterruptedException, ExecutionException { 3381 // TODO: should we ever spin forever? 3382 throw new UnsupportedOperationException(); 3383 } 3384 3385 @Override 3386 public V get(long timeout, TimeUnit unit) 3387 throws InterruptedException, ExecutionException, TimeoutException { 3388 if (!done) { 3389 long deadlineTs = EnvironmentEdgeManager.currentTime() + unit.toMillis(timeout); 3390 try { 3391 try { 3392 // if the master support procedures, try to wait the result 3393 if (procId != null) { 3394 result = waitProcedureResult(procId, deadlineTs); 3395 } 3396 // if we don't have a proc result, try the compatibility wait 3397 if (!procResultFound) { 3398 result = waitOperationResult(deadlineTs); 3399 } 3400 result = postOperationResult(result, deadlineTs); 3401 done = true; 3402 } catch (IOException e) { 3403 result = postOperationFailure(e, deadlineTs); 3404 done = true; 3405 } 3406 } catch (IOException e) { 3407 exception = new ExecutionException(e); 3408 done = true; 3409 } 3410 } 3411 if (exception != null) { 3412 throw exception; 3413 } 3414 return result; 3415 } 3416 3417 @Override 3418 public boolean isDone() { 3419 return done; 3420 } 3421 3422 protected HBaseAdmin getAdmin() { 3423 return admin; 3424 } 3425 3426 private V waitProcedureResult(long procId, long deadlineTs) 3427 throws IOException, TimeoutException, InterruptedException { 3428 GetProcedureResultRequest request = GetProcedureResultRequest.newBuilder() 3429 .setProcId(procId) 3430 .build(); 3431 3432 int tries = 0; 3433 IOException serviceEx = null; 3434 while (EnvironmentEdgeManager.currentTime() < deadlineTs) { 3435 GetProcedureResultResponse response = null; 3436 try { 3437 // Try to fetch the result 3438 response = getProcedureResult(request); 3439 } catch (IOException e) { 3440 serviceEx = unwrapException(e); 3441 3442 // the master may be down 3443 LOG.warn("failed to get the procedure result procId=" + procId, serviceEx); 3444 3445 // Not much to do, if we have a DoNotRetryIOException 3446 if (serviceEx instanceof DoNotRetryIOException) { 3447 // TODO: looks like there is no way to unwrap this exception and get the proper 3448 // UnsupportedOperationException aside from looking at the message. 3449 // anyway, if we fail here we just failover to the compatibility side 3450 // and that is always a valid solution. 3451 LOG.warn("Proc-v2 is unsupported on this master: " + serviceEx.getMessage(), serviceEx); 3452 procResultFound = false; 3453 return null; 3454 } 3455 } 3456 3457 // If the procedure is no longer running, we should have a result 3458 if (response != null && response.getState() != GetProcedureResultResponse.State.RUNNING) { 3459 procResultFound = response.getState() != GetProcedureResultResponse.State.NOT_FOUND; 3460 return convertResult(response); 3461 } 3462 3463 try { 3464 Thread.sleep(getAdmin().getPauseTime(tries++)); 3465 } catch (InterruptedException e) { 3466 throw new InterruptedException( 3467 "Interrupted while waiting for the result of proc " + procId); 3468 } 3469 } 3470 if (serviceEx != null) { 3471 throw serviceEx; 3472 } else { 3473 throw new TimeoutException("The procedure " + procId + " is still running"); 3474 } 3475 } 3476 3477 private static IOException unwrapException(IOException e) { 3478 if (e instanceof RemoteException) { 3479 return ((RemoteException)e).unwrapRemoteException(); 3480 } 3481 return e; 3482 } 3483 3484 protected GetProcedureResultResponse getProcedureResult(final GetProcedureResultRequest request) 3485 throws IOException { 3486 return admin.executeCallable(new MasterCallable<GetProcedureResultResponse>( 3487 admin.getConnection(), admin.getRpcControllerFactory()) { 3488 @Override 3489 protected GetProcedureResultResponse rpcCall() throws Exception { 3490 return master.getProcedureResult(getRpcController(), request); 3491 } 3492 }); 3493 } 3494 3495 /** 3496 * Convert the procedure result response to a specified type. 3497 * @param response the procedure result object to parse 3498 * @return the result data of the procedure. 3499 */ 3500 protected V convertResult(final GetProcedureResultResponse response) throws IOException { 3501 if (response.hasException()) { 3502 throw ForeignExceptionUtil.toIOException(response.getException()); 3503 } 3504 return null; 3505 } 3506 3507 /** 3508 * Fallback implementation in case the procedure is not supported by the server. 3509 * It should try to wait until the operation is completed. 3510 * @param deadlineTs the timestamp after which this method should throw a TimeoutException 3511 * @return the result data of the operation 3512 */ 3513 protected V waitOperationResult(final long deadlineTs) 3514 throws IOException, TimeoutException { 3515 return null; 3516 } 3517 3518 /** 3519 * Called after the operation is completed and the result fetched. this allows to perform extra 3520 * steps after the procedure is completed. it allows to apply transformations to the result that 3521 * will be returned by get(). 3522 * @param result the result of the procedure 3523 * @param deadlineTs the timestamp after which this method should throw a TimeoutException 3524 * @return the result of the procedure, which may be the same as the passed one 3525 */ 3526 protected V postOperationResult(final V result, final long deadlineTs) 3527 throws IOException, TimeoutException { 3528 return result; 3529 } 3530 3531 /** 3532 * Called after the operation is terminated with a failure. 3533 * this allows to perform extra steps after the procedure is terminated. 3534 * it allows to apply transformations to the result that will be returned by get(). 3535 * The default implementation will rethrow the exception 3536 * @param exception the exception got from fetching the result 3537 * @param deadlineTs the timestamp after which this method should throw a TimeoutException 3538 * @return the result of the procedure, which may be the same as the passed one 3539 */ 3540 protected V postOperationFailure(final IOException exception, final long deadlineTs) 3541 throws IOException, TimeoutException { 3542 throw exception; 3543 } 3544 3545 protected interface WaitForStateCallable { 3546 boolean checkState(int tries) throws IOException; 3547 void throwInterruptedException() throws InterruptedIOException; 3548 void throwTimeoutException(long elapsed) throws TimeoutException; 3549 } 3550 3551 protected void waitForState(final long deadlineTs, final WaitForStateCallable callable) 3552 throws IOException, TimeoutException { 3553 int tries = 0; 3554 IOException serverEx = null; 3555 long startTime = EnvironmentEdgeManager.currentTime(); 3556 while (EnvironmentEdgeManager.currentTime() < deadlineTs) { 3557 serverEx = null; 3558 try { 3559 if (callable.checkState(tries)) { 3560 return; 3561 } 3562 } catch (IOException e) { 3563 serverEx = e; 3564 } 3565 try { 3566 Thread.sleep(getAdmin().getPauseTime(tries++)); 3567 } catch (InterruptedException e) { 3568 callable.throwInterruptedException(); 3569 } 3570 } 3571 if (serverEx != null) { 3572 throw unwrapException(serverEx); 3573 } else { 3574 callable.throwTimeoutException(EnvironmentEdgeManager.currentTime() - startTime); 3575 } 3576 } 3577 } 3578 3579 @InterfaceAudience.Private 3580 @InterfaceStability.Evolving 3581 protected static abstract class TableFuture<V> extends ProcedureFuture<V> { 3582 private final TableName tableName; 3583 3584 public TableFuture(final HBaseAdmin admin, final TableName tableName, final Long procId) { 3585 super(admin, procId); 3586 this.tableName = tableName; 3587 } 3588 3589 @Override 3590 public String toString() { 3591 return getDescription(); 3592 } 3593 3594 /** 3595 * @return the table name 3596 */ 3597 protected TableName getTableName() { 3598 return tableName; 3599 } 3600 3601 /** 3602 * @return the table descriptor 3603 */ 3604 protected TableDescriptor getTableDescriptor() throws IOException { 3605 return getAdmin().getDescriptor(getTableName()); 3606 } 3607 3608 /** 3609 * @return the operation type like CREATE, DELETE, DISABLE etc. 3610 */ 3611 public abstract String getOperationType(); 3612 3613 /** 3614 * @return a description of the operation 3615 */ 3616 protected String getDescription() { 3617 return "Operation: " + getOperationType() + ", " 3618 + "Table Name: " + tableName.getNameWithNamespaceInclAsString(); 3619 3620 } 3621 3622 protected abstract class TableWaitForStateCallable implements WaitForStateCallable { 3623 @Override 3624 public void throwInterruptedException() throws InterruptedIOException { 3625 throw new InterruptedIOException("Interrupted while waiting for operation: " 3626 + getOperationType() + " on table: " + tableName.getNameWithNamespaceInclAsString()); 3627 } 3628 3629 @Override 3630 public void throwTimeoutException(long elapsedTime) throws TimeoutException { 3631 throw new TimeoutException("The operation: " + getOperationType() + " on table: " + 3632 tableName.getNameAsString() + " has not completed after " + elapsedTime + "ms"); 3633 } 3634 } 3635 3636 @Override 3637 protected V postOperationResult(final V result, final long deadlineTs) 3638 throws IOException, TimeoutException { 3639 LOG.info(getDescription() + " completed"); 3640 return super.postOperationResult(result, deadlineTs); 3641 } 3642 3643 @Override 3644 protected V postOperationFailure(final IOException exception, final long deadlineTs) 3645 throws IOException, TimeoutException { 3646 LOG.info(getDescription() + " failed with " + exception.getMessage()); 3647 return super.postOperationFailure(exception, deadlineTs); 3648 } 3649 3650 protected void waitForTableEnabled(final long deadlineTs) 3651 throws IOException, TimeoutException { 3652 waitForState(deadlineTs, new TableWaitForStateCallable() { 3653 @Override 3654 public boolean checkState(int tries) throws IOException { 3655 try { 3656 if (getAdmin().isTableAvailable(tableName)) { 3657 return true; 3658 } 3659 } catch (TableNotFoundException tnfe) { 3660 LOG.debug("Table " + tableName.getNameWithNamespaceInclAsString() 3661 + " was not enabled, sleeping. tries=" + tries); 3662 } 3663 return false; 3664 } 3665 }); 3666 } 3667 3668 protected void waitForTableDisabled(final long deadlineTs) 3669 throws IOException, TimeoutException { 3670 waitForState(deadlineTs, new TableWaitForStateCallable() { 3671 @Override 3672 public boolean checkState(int tries) throws IOException { 3673 return getAdmin().isTableDisabled(tableName); 3674 } 3675 }); 3676 } 3677 3678 protected void waitTableNotFound(final long deadlineTs) 3679 throws IOException, TimeoutException { 3680 waitForState(deadlineTs, new TableWaitForStateCallable() { 3681 @Override 3682 public boolean checkState(int tries) throws IOException { 3683 return !getAdmin().tableExists(tableName); 3684 } 3685 }); 3686 } 3687 3688 protected void waitForSchemaUpdate(final long deadlineTs) 3689 throws IOException, TimeoutException { 3690 waitForState(deadlineTs, new TableWaitForStateCallable() { 3691 @Override 3692 public boolean checkState(int tries) throws IOException { 3693 return getAdmin().getAlterStatus(tableName).getFirst() == 0; 3694 } 3695 }); 3696 } 3697 3698 protected void waitForAllRegionsOnline(final long deadlineTs, final byte[][] splitKeys) 3699 throws IOException, TimeoutException { 3700 final TableDescriptor desc = getTableDescriptor(); 3701 final AtomicInteger actualRegCount = new AtomicInteger(0); 3702 final MetaTableAccessor.Visitor visitor = new MetaTableAccessor.Visitor() { 3703 @Override 3704 public boolean visit(Result rowResult) throws IOException { 3705 RegionLocations list = MetaTableAccessor.getRegionLocations(rowResult); 3706 if (list == null) { 3707 LOG.warn("No serialized HRegionInfo in " + rowResult); 3708 return true; 3709 } 3710 HRegionLocation l = list.getRegionLocation(); 3711 if (l == null) { 3712 return true; 3713 } 3714 if (!l.getRegionInfo().getTable().equals(desc.getTableName())) { 3715 return false; 3716 } 3717 if (l.getRegionInfo().isOffline() || l.getRegionInfo().isSplit()) return true; 3718 HRegionLocation[] locations = list.getRegionLocations(); 3719 for (HRegionLocation location : locations) { 3720 if (location == null) continue; 3721 ServerName serverName = location.getServerName(); 3722 // Make sure that regions are assigned to server 3723 if (serverName != null && serverName.getHostAndPort() != null) { 3724 actualRegCount.incrementAndGet(); 3725 } 3726 } 3727 return true; 3728 } 3729 }; 3730 3731 int tries = 0; 3732 int numRegs = (splitKeys == null ? 1 : splitKeys.length + 1) * desc.getRegionReplication(); 3733 while (EnvironmentEdgeManager.currentTime() < deadlineTs) { 3734 actualRegCount.set(0); 3735 MetaTableAccessor.scanMetaForTableRegions(getAdmin().getConnection(), visitor, 3736 desc.getTableName()); 3737 if (actualRegCount.get() == numRegs) { 3738 // all the regions are online 3739 return; 3740 } 3741 3742 try { 3743 Thread.sleep(getAdmin().getPauseTime(tries++)); 3744 } catch (InterruptedException e) { 3745 throw new InterruptedIOException("Interrupted when opening" + " regions; " 3746 + actualRegCount.get() + " of " + numRegs + " regions processed so far"); 3747 } 3748 } 3749 throw new TimeoutException("Only " + actualRegCount.get() + " of " + numRegs 3750 + " regions are online; retries exhausted."); 3751 } 3752 } 3753 3754 @InterfaceAudience.Private 3755 @InterfaceStability.Evolving 3756 protected static abstract class NamespaceFuture extends ProcedureFuture<Void> { 3757 private final String namespaceName; 3758 3759 public NamespaceFuture(final HBaseAdmin admin, final String namespaceName, final Long procId) { 3760 super(admin, procId); 3761 this.namespaceName = namespaceName; 3762 } 3763 3764 /** 3765 * @return the namespace name 3766 */ 3767 protected String getNamespaceName() { 3768 return namespaceName; 3769 } 3770 3771 /** 3772 * @return the operation type like CREATE_NAMESPACE, DELETE_NAMESPACE, etc. 3773 */ 3774 public abstract String getOperationType(); 3775 3776 @Override 3777 public String toString() { 3778 return "Operation: " + getOperationType() + ", Namespace: " + getNamespaceName(); 3779 } 3780 } 3781 3782 @Override 3783 public List<SecurityCapability> getSecurityCapabilities() throws IOException { 3784 try { 3785 return executeCallable(new MasterCallable<List<SecurityCapability>>(getConnection(), 3786 getRpcControllerFactory()) { 3787 @Override 3788 protected List<SecurityCapability> rpcCall() throws Exception { 3789 SecurityCapabilitiesRequest req = SecurityCapabilitiesRequest.newBuilder().build(); 3790 return ProtobufUtil.toSecurityCapabilityList( 3791 master.getSecurityCapabilities(getRpcController(), req).getCapabilitiesList()); 3792 } 3793 }); 3794 } catch (IOException e) { 3795 if (e instanceof RemoteException) { 3796 e = ((RemoteException)e).unwrapRemoteException(); 3797 } 3798 throw e; 3799 } 3800 } 3801 3802 @Override 3803 public boolean splitSwitch(boolean enabled, boolean synchronous) throws IOException { 3804 return splitOrMergeSwitch(enabled, synchronous, MasterSwitchType.SPLIT); 3805 } 3806 3807 @Override 3808 public boolean mergeSwitch(boolean enabled, boolean synchronous) throws IOException { 3809 return splitOrMergeSwitch(enabled, synchronous, MasterSwitchType.MERGE); 3810 } 3811 3812 private boolean splitOrMergeSwitch(boolean enabled, boolean synchronous, 3813 MasterSwitchType switchType) throws IOException { 3814 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 3815 @Override 3816 protected Boolean rpcCall() throws Exception { 3817 MasterProtos.SetSplitOrMergeEnabledResponse response = master.setSplitOrMergeEnabled( 3818 getRpcController(), 3819 RequestConverter.buildSetSplitOrMergeEnabledRequest(enabled, synchronous, switchType)); 3820 return response.getPrevValueList().get(0); 3821 } 3822 }); 3823 } 3824 3825 @Override 3826 public boolean isSplitEnabled() throws IOException { 3827 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 3828 @Override 3829 protected Boolean rpcCall() throws Exception { 3830 return master.isSplitOrMergeEnabled(getRpcController(), 3831 RequestConverter.buildIsSplitOrMergeEnabledRequest(MasterSwitchType.SPLIT)).getEnabled(); 3832 } 3833 }); 3834 } 3835 3836 @Override 3837 public boolean isMergeEnabled() throws IOException { 3838 return executeCallable(new MasterCallable<Boolean>(getConnection(), getRpcControllerFactory()) { 3839 @Override 3840 protected Boolean rpcCall() throws Exception { 3841 return master.isSplitOrMergeEnabled(getRpcController(), 3842 RequestConverter.buildIsSplitOrMergeEnabledRequest(MasterSwitchType.MERGE)).getEnabled(); 3843 } 3844 }); 3845 } 3846 3847 private RpcControllerFactory getRpcControllerFactory() { 3848 return this.rpcControllerFactory; 3849 } 3850 3851 @Override 3852 public void addReplicationPeer(String peerId, ReplicationPeerConfig peerConfig, boolean enabled) 3853 throws IOException { 3854 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 3855 @Override 3856 protected Void rpcCall() throws Exception { 3857 master.addReplicationPeer(getRpcController(), 3858 RequestConverter.buildAddReplicationPeerRequest(peerId, peerConfig, enabled)); 3859 return null; 3860 } 3861 }); 3862 } 3863 3864 @Override 3865 public void removeReplicationPeer(String peerId) throws IOException { 3866 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 3867 @Override 3868 protected Void rpcCall() throws Exception { 3869 master.removeReplicationPeer(getRpcController(), 3870 RequestConverter.buildRemoveReplicationPeerRequest(peerId)); 3871 return null; 3872 } 3873 }); 3874 } 3875 3876 @Override 3877 public void enableReplicationPeer(final String peerId) throws IOException { 3878 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 3879 @Override 3880 protected Void rpcCall() throws Exception { 3881 master.enableReplicationPeer(getRpcController(), 3882 RequestConverter.buildEnableReplicationPeerRequest(peerId)); 3883 return null; 3884 } 3885 }); 3886 } 3887 3888 @Override 3889 public void disableReplicationPeer(final String peerId) throws IOException { 3890 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 3891 @Override 3892 protected Void rpcCall() throws Exception { 3893 master.disableReplicationPeer(getRpcController(), 3894 RequestConverter.buildDisableReplicationPeerRequest(peerId)); 3895 return null; 3896 } 3897 }); 3898 } 3899 3900 @Override 3901 public ReplicationPeerConfig getReplicationPeerConfig(final String peerId) throws IOException { 3902 return executeCallable(new MasterCallable<ReplicationPeerConfig>(getConnection(), 3903 getRpcControllerFactory()) { 3904 @Override 3905 protected ReplicationPeerConfig rpcCall() throws Exception { 3906 GetReplicationPeerConfigResponse response = master.getReplicationPeerConfig( 3907 getRpcController(), RequestConverter.buildGetReplicationPeerConfigRequest(peerId)); 3908 return ReplicationPeerConfigUtil.convert(response.getPeerConfig()); 3909 } 3910 }); 3911 } 3912 3913 @Override 3914 public void updateReplicationPeerConfig(final String peerId, 3915 final ReplicationPeerConfig peerConfig) throws IOException { 3916 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 3917 @Override 3918 protected Void rpcCall() throws Exception { 3919 master.updateReplicationPeerConfig(getRpcController(), 3920 RequestConverter.buildUpdateReplicationPeerConfigRequest(peerId, peerConfig)); 3921 return null; 3922 } 3923 }); 3924 } 3925 3926 @Override 3927 public void appendReplicationPeerTableCFs(String id, 3928 Map<TableName, List<String>> tableCfs) 3929 throws ReplicationException, IOException { 3930 if (tableCfs == null) { 3931 throw new ReplicationException("tableCfs is null"); 3932 } 3933 ReplicationPeerConfig peerConfig = getReplicationPeerConfig(id); 3934 ReplicationPeerConfig newPeerConfig = 3935 ReplicationPeerConfigUtil.appendTableCFsToReplicationPeerConfig(tableCfs, peerConfig); 3936 updateReplicationPeerConfig(id, newPeerConfig); 3937 } 3938 3939 @Override 3940 public void removeReplicationPeerTableCFs(String id, 3941 Map<TableName, List<String>> tableCfs) 3942 throws ReplicationException, IOException { 3943 if (tableCfs == null) { 3944 throw new ReplicationException("tableCfs is null"); 3945 } 3946 ReplicationPeerConfig peerConfig = getReplicationPeerConfig(id); 3947 ReplicationPeerConfig newPeerConfig = 3948 ReplicationPeerConfigUtil.removeTableCFsFromReplicationPeerConfig(tableCfs, peerConfig, id); 3949 updateReplicationPeerConfig(id, newPeerConfig); 3950 } 3951 3952 @Override 3953 public List<ReplicationPeerDescription> listReplicationPeers() throws IOException { 3954 return listReplicationPeers((Pattern)null); 3955 } 3956 3957 @Override 3958 public List<ReplicationPeerDescription> listReplicationPeers(Pattern pattern) 3959 throws IOException { 3960 return executeCallable(new MasterCallable<List<ReplicationPeerDescription>>(getConnection(), 3961 getRpcControllerFactory()) { 3962 @Override 3963 protected List<ReplicationPeerDescription> rpcCall() throws Exception { 3964 List<ReplicationProtos.ReplicationPeerDescription> peersList = master.listReplicationPeers( 3965 getRpcController(), RequestConverter.buildListReplicationPeersRequest(pattern)) 3966 .getPeerDescList(); 3967 List<ReplicationPeerDescription> result = new ArrayList<>(peersList.size()); 3968 for (ReplicationProtos.ReplicationPeerDescription peer : peersList) { 3969 result.add(ReplicationPeerConfigUtil.toReplicationPeerDescription(peer)); 3970 } 3971 return result; 3972 } 3973 }); 3974 } 3975 3976 @Override 3977 public void decommissionRegionServers(List<ServerName> servers, boolean offload) 3978 throws IOException { 3979 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 3980 @Override 3981 public Void rpcCall() throws ServiceException { 3982 master.decommissionRegionServers(getRpcController(), 3983 RequestConverter.buildDecommissionRegionServersRequest(servers, offload)); 3984 return null; 3985 } 3986 }); 3987 } 3988 3989 @Override 3990 public List<ServerName> listDecommissionedRegionServers() throws IOException { 3991 return executeCallable(new MasterCallable<List<ServerName>>(getConnection(), 3992 getRpcControllerFactory()) { 3993 @Override 3994 public List<ServerName> rpcCall() throws ServiceException { 3995 ListDecommissionedRegionServersRequest req = 3996 ListDecommissionedRegionServersRequest.newBuilder().build(); 3997 List<ServerName> servers = new ArrayList<>(); 3998 for (HBaseProtos.ServerName server : master 3999 .listDecommissionedRegionServers(getRpcController(), req).getServerNameList()) { 4000 servers.add(ProtobufUtil.toServerName(server)); 4001 } 4002 return servers; 4003 } 4004 }); 4005 } 4006 4007 @Override 4008 public void recommissionRegionServer(ServerName server, List<byte[]> encodedRegionNames) 4009 throws IOException { 4010 executeCallable(new MasterCallable<Void>(getConnection(), getRpcControllerFactory()) { 4011 @Override 4012 public Void rpcCall() throws ServiceException { 4013 master.recommissionRegionServer(getRpcController(), 4014 RequestConverter.buildRecommissionRegionServerRequest(server, encodedRegionNames)); 4015 return null; 4016 } 4017 }); 4018 } 4019 4020 @Override 4021 public List<TableCFs> listReplicatedTableCFs() throws IOException { 4022 List<TableCFs> replicatedTableCFs = new ArrayList<>(); 4023 List<TableDescriptor> tables = listTableDescriptors(); 4024 tables.forEach(table -> { 4025 Map<String, Integer> cfs = new HashMap<>(); 4026 Stream.of(table.getColumnFamilies()) 4027 .filter(column -> column.getScope() != HConstants.REPLICATION_SCOPE_LOCAL) 4028 .forEach(column -> { 4029 cfs.put(column.getNameAsString(), column.getScope()); 4030 }); 4031 if (!cfs.isEmpty()) { 4032 replicatedTableCFs.add(new TableCFs(table.getTableName(), cfs)); 4033 } 4034 }); 4035 return replicatedTableCFs; 4036 } 4037 4038 @Override 4039 public void enableTableReplication(final TableName tableName) throws IOException { 4040 if (tableName == null) { 4041 throw new IllegalArgumentException("Table name cannot be null"); 4042 } 4043 if (!tableExists(tableName)) { 4044 throw new TableNotFoundException("Table '" + tableName.getNameAsString() 4045 + "' does not exists."); 4046 } 4047 byte[][] splits = getTableSplits(tableName); 4048 checkAndSyncTableDescToPeers(tableName, splits); 4049 setTableRep(tableName, true); 4050 } 4051 4052 @Override 4053 public void disableTableReplication(final TableName tableName) throws IOException { 4054 if (tableName == null) { 4055 throw new IllegalArgumentException("Table name is null"); 4056 } 4057 if (!tableExists(tableName)) { 4058 throw new TableNotFoundException("Table '" + tableName.getNameAsString() 4059 + "' does not exists."); 4060 } 4061 setTableRep(tableName, false); 4062 } 4063 4064 /** 4065 * Connect to peer and check the table descriptor on peer: 4066 * <ol> 4067 * <li>Create the same table on peer when not exist.</li> 4068 * <li>Throw an exception if the table already has replication enabled on any of the column 4069 * families.</li> 4070 * <li>Throw an exception if the table exists on peer cluster but descriptors are not same.</li> 4071 * </ol> 4072 * @param tableName name of the table to sync to the peer 4073 * @param splits table split keys 4074 * @throws IOException 4075 */ 4076 private void checkAndSyncTableDescToPeers(final TableName tableName, final byte[][] splits) 4077 throws IOException { 4078 List<ReplicationPeerDescription> peers = listReplicationPeers(); 4079 if (peers == null || peers.size() <= 0) { 4080 throw new IllegalArgumentException("Found no peer cluster for replication."); 4081 } 4082 4083 for (ReplicationPeerDescription peerDesc : peers) { 4084 if (peerDesc.getPeerConfig().needToReplicate(tableName)) { 4085 Configuration peerConf = 4086 ReplicationPeerConfigUtil.getPeerClusterConfiguration(this.conf, peerDesc); 4087 try (Connection conn = ConnectionFactory.createConnection(peerConf); 4088 Admin repHBaseAdmin = conn.getAdmin()) { 4089 TableDescriptor tableDesc = getDescriptor(tableName); 4090 TableDescriptor peerTableDesc = null; 4091 if (!repHBaseAdmin.tableExists(tableName)) { 4092 repHBaseAdmin.createTable(tableDesc, splits); 4093 } else { 4094 peerTableDesc = repHBaseAdmin.getDescriptor(tableName); 4095 if (peerTableDesc == null) { 4096 throw new IllegalArgumentException("Failed to get table descriptor for table " 4097 + tableName.getNameAsString() + " from peer cluster " + peerDesc.getPeerId()); 4098 } 4099 if (TableDescriptor.COMPARATOR_IGNORE_REPLICATION.compare(peerTableDesc, 4100 tableDesc) != 0) { 4101 throw new IllegalArgumentException("Table " + tableName.getNameAsString() 4102 + " exists in peer cluster " + peerDesc.getPeerId() 4103 + ", but the table descriptors are not same when compared with source cluster." 4104 + " Thus can not enable the table's replication switch."); 4105 } 4106 } 4107 } 4108 } 4109 } 4110 } 4111 4112 /** 4113 * Set the table's replication switch if the table's replication switch is already not set. 4114 * @param tableName name of the table 4115 * @param enableRep is replication switch enable or disable 4116 * @throws IOException if a remote or network exception occurs 4117 */ 4118 private void setTableRep(final TableName tableName, boolean enableRep) throws IOException { 4119 TableDescriptor tableDesc = getDescriptor(tableName); 4120 if (!tableDesc.matchReplicationScope(enableRep)) { 4121 int scope = 4122 enableRep ? HConstants.REPLICATION_SCOPE_GLOBAL : HConstants.REPLICATION_SCOPE_LOCAL; 4123 modifyTable(TableDescriptorBuilder.newBuilder(tableDesc).setReplicationScope(scope).build()); 4124 } 4125 } 4126 4127 @Override 4128 public void clearCompactionQueues(final ServerName sn, final Set<String> queues) 4129 throws IOException, InterruptedException { 4130 if (queues == null || queues.size() == 0) { 4131 throw new IllegalArgumentException("queues cannot be null or empty"); 4132 } 4133 final AdminService.BlockingInterface admin = this.connection.getAdmin(sn); 4134 Callable<Void> callable = new Callable<Void>() { 4135 @Override 4136 public Void call() throws Exception { 4137 // TODO: There is no timeout on this controller. Set one! 4138 HBaseRpcController controller = rpcControllerFactory.newController(); 4139 ClearCompactionQueuesRequest request = 4140 RequestConverter.buildClearCompactionQueuesRequest(queues); 4141 admin.clearCompactionQueues(controller, request); 4142 return null; 4143 } 4144 }; 4145 ProtobufUtil.call(callable); 4146 } 4147 4148 @Override 4149 public List<ServerName> clearDeadServers(final List<ServerName> servers) throws IOException { 4150 if (servers == null || servers.size() == 0) { 4151 throw new IllegalArgumentException("servers cannot be null or empty"); 4152 } 4153 return executeCallable(new MasterCallable<List<ServerName>>(getConnection(), 4154 getRpcControllerFactory()) { 4155 @Override 4156 protected List<ServerName> rpcCall() throws Exception { 4157 ClearDeadServersRequest req = RequestConverter.buildClearDeadServersRequest(servers); 4158 return ProtobufUtil.toServerNameList( 4159 master.clearDeadServers(getRpcController(), req).getServerNameList()); 4160 } 4161 }); 4162 } 4163}