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.master; 019 020import static org.apache.hadoop.hbase.HConstants.DEFAULT_HBASE_SPLIT_COORDINATED_BY_ZK; 021import static org.apache.hadoop.hbase.HConstants.HBASE_MASTER_LOGCLEANER_PLUGINS; 022import static org.apache.hadoop.hbase.HConstants.HBASE_SPLIT_WAL_COORDINATED_BY_ZK; 023import static org.apache.hadoop.hbase.master.cleaner.HFileCleaner.CUSTOM_POOL_SIZE; 024import static org.apache.hadoop.hbase.util.DNS.MASTER_HOSTNAME_KEY; 025 026import com.google.errorprone.annotations.RestrictedApi; 027import io.opentelemetry.api.trace.Span; 028import io.opentelemetry.api.trace.StatusCode; 029import io.opentelemetry.context.Scope; 030import java.io.IOException; 031import java.io.InterruptedIOException; 032import java.lang.reflect.Constructor; 033import java.lang.reflect.InvocationTargetException; 034import java.net.InetAddress; 035import java.net.InetSocketAddress; 036import java.net.UnknownHostException; 037import java.time.Instant; 038import java.time.ZoneId; 039import java.time.format.DateTimeFormatter; 040import java.util.ArrayList; 041import java.util.Arrays; 042import java.util.Collection; 043import java.util.Collections; 044import java.util.Comparator; 045import java.util.EnumSet; 046import java.util.HashMap; 047import java.util.HashSet; 048import java.util.Iterator; 049import java.util.LinkedList; 050import java.util.List; 051import java.util.Map; 052import java.util.Objects; 053import java.util.Optional; 054import java.util.Set; 055import java.util.concurrent.ExecutionException; 056import java.util.concurrent.Future; 057import java.util.concurrent.Semaphore; 058import java.util.concurrent.TimeUnit; 059import java.util.concurrent.TimeoutException; 060import java.util.concurrent.atomic.AtomicInteger; 061import java.util.regex.Pattern; 062import java.util.stream.Collectors; 063import javax.servlet.http.HttpServlet; 064import org.apache.commons.lang3.StringUtils; 065import org.apache.hadoop.conf.Configuration; 066import org.apache.hadoop.fs.FSDataInputStream; 067import org.apache.hadoop.fs.FSDataOutputStream; 068import org.apache.hadoop.fs.Path; 069import org.apache.hadoop.hbase.CatalogFamilyFormat; 070import org.apache.hadoop.hbase.Cell; 071import org.apache.hadoop.hbase.CellBuilderFactory; 072import org.apache.hadoop.hbase.CellBuilderType; 073import org.apache.hadoop.hbase.ClusterId; 074import org.apache.hadoop.hbase.ClusterMetrics; 075import org.apache.hadoop.hbase.ClusterMetrics.Option; 076import org.apache.hadoop.hbase.ClusterMetricsBuilder; 077import org.apache.hadoop.hbase.DoNotRetryIOException; 078import org.apache.hadoop.hbase.HBaseIOException; 079import org.apache.hadoop.hbase.HBaseInterfaceAudience; 080import org.apache.hadoop.hbase.HBaseServerBase; 081import org.apache.hadoop.hbase.HConstants; 082import org.apache.hadoop.hbase.HRegionLocation; 083import org.apache.hadoop.hbase.InvalidFamilyOperationException; 084import org.apache.hadoop.hbase.MasterNotRunningException; 085import org.apache.hadoop.hbase.MetaTableAccessor; 086import org.apache.hadoop.hbase.NamespaceDescriptor; 087import org.apache.hadoop.hbase.NamespaceNotFoundException; 088import org.apache.hadoop.hbase.PleaseHoldException; 089import org.apache.hadoop.hbase.PleaseRestartMasterException; 090import org.apache.hadoop.hbase.RegionMetrics; 091import org.apache.hadoop.hbase.ReplicationPeerNotFoundException; 092import org.apache.hadoop.hbase.ScheduledChore; 093import org.apache.hadoop.hbase.ServerMetrics; 094import org.apache.hadoop.hbase.ServerName; 095import org.apache.hadoop.hbase.ServerTask; 096import org.apache.hadoop.hbase.ServerTaskBuilder; 097import org.apache.hadoop.hbase.TableName; 098import org.apache.hadoop.hbase.TableNotDisabledException; 099import org.apache.hadoop.hbase.TableNotFoundException; 100import org.apache.hadoop.hbase.UnknownRegionException; 101import org.apache.hadoop.hbase.client.BalanceRequest; 102import org.apache.hadoop.hbase.client.BalanceResponse; 103import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; 104import org.apache.hadoop.hbase.client.CompactionState; 105import org.apache.hadoop.hbase.client.MasterSwitchType; 106import org.apache.hadoop.hbase.client.NormalizeTableFilterParams; 107import org.apache.hadoop.hbase.client.Put; 108import org.apache.hadoop.hbase.client.RegionInfo; 109import org.apache.hadoop.hbase.client.RegionInfoBuilder; 110import org.apache.hadoop.hbase.client.RegionStatesCount; 111import org.apache.hadoop.hbase.client.ResultScanner; 112import org.apache.hadoop.hbase.client.Scan; 113import org.apache.hadoop.hbase.client.TableDescriptor; 114import org.apache.hadoop.hbase.client.TableDescriptorBuilder; 115import org.apache.hadoop.hbase.client.TableState; 116import org.apache.hadoop.hbase.coprocessor.CoprocessorHost; 117import org.apache.hadoop.hbase.exceptions.DeserializationException; 118import org.apache.hadoop.hbase.exceptions.MasterStoppedException; 119import org.apache.hadoop.hbase.executor.ExecutorType; 120import org.apache.hadoop.hbase.favored.FavoredNodesManager; 121import org.apache.hadoop.hbase.http.HttpServer; 122import org.apache.hadoop.hbase.http.InfoServer; 123import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils; 124import org.apache.hadoop.hbase.ipc.RpcServer; 125import org.apache.hadoop.hbase.ipc.ServerNotRunningYetException; 126import org.apache.hadoop.hbase.log.HBaseMarkers; 127import org.apache.hadoop.hbase.master.MasterRpcServices.BalanceSwitchMode; 128import org.apache.hadoop.hbase.master.assignment.AssignmentManager; 129import org.apache.hadoop.hbase.master.assignment.MergeTableRegionsProcedure; 130import org.apache.hadoop.hbase.master.assignment.RegionStateNode; 131import org.apache.hadoop.hbase.master.assignment.RegionStateStore; 132import org.apache.hadoop.hbase.master.assignment.RegionStates; 133import org.apache.hadoop.hbase.master.assignment.TransitRegionStateProcedure; 134import org.apache.hadoop.hbase.master.balancer.BalancerChore; 135import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer; 136import org.apache.hadoop.hbase.master.balancer.ClusterStatusChore; 137import org.apache.hadoop.hbase.master.balancer.LoadBalancerFactory; 138import org.apache.hadoop.hbase.master.balancer.LoadBalancerStateStore; 139import org.apache.hadoop.hbase.master.balancer.MaintenanceLoadBalancer; 140import org.apache.hadoop.hbase.master.cleaner.DirScanPool; 141import org.apache.hadoop.hbase.master.cleaner.HFileCleaner; 142import org.apache.hadoop.hbase.master.cleaner.LogCleaner; 143import org.apache.hadoop.hbase.master.cleaner.ReplicationBarrierCleaner; 144import org.apache.hadoop.hbase.master.cleaner.SnapshotCleanerChore; 145import org.apache.hadoop.hbase.master.hbck.HbckChore; 146import org.apache.hadoop.hbase.master.http.MasterDumpServlet; 147import org.apache.hadoop.hbase.master.http.MasterRedirectServlet; 148import org.apache.hadoop.hbase.master.http.MasterStatusServlet; 149import org.apache.hadoop.hbase.master.http.api_v1.ResourceConfigFactory; 150import org.apache.hadoop.hbase.master.http.hbck.HbckConfigFactory; 151import org.apache.hadoop.hbase.master.janitor.CatalogJanitor; 152import org.apache.hadoop.hbase.master.locking.LockManager; 153import org.apache.hadoop.hbase.master.migrate.RollingUpgradeChore; 154import org.apache.hadoop.hbase.master.normalizer.RegionNormalizerFactory; 155import org.apache.hadoop.hbase.master.normalizer.RegionNormalizerManager; 156import org.apache.hadoop.hbase.master.normalizer.RegionNormalizerStateStore; 157import org.apache.hadoop.hbase.master.procedure.CreateTableProcedure; 158import org.apache.hadoop.hbase.master.procedure.DeleteNamespaceProcedure; 159import org.apache.hadoop.hbase.master.procedure.DeleteTableProcedure; 160import org.apache.hadoop.hbase.master.procedure.DisableTableProcedure; 161import org.apache.hadoop.hbase.master.procedure.EnableTableProcedure; 162import org.apache.hadoop.hbase.master.procedure.FlushTableProcedure; 163import org.apache.hadoop.hbase.master.procedure.InitMetaProcedure; 164import org.apache.hadoop.hbase.master.procedure.LogRollProcedure; 165import org.apache.hadoop.hbase.master.procedure.MasterProcedureConstants; 166import org.apache.hadoop.hbase.master.procedure.MasterProcedureEnv; 167import org.apache.hadoop.hbase.master.procedure.MasterProcedureScheduler; 168import org.apache.hadoop.hbase.master.procedure.MasterProcedureUtil; 169import org.apache.hadoop.hbase.master.procedure.MasterProcedureUtil.NonceProcedureRunnable; 170import org.apache.hadoop.hbase.master.procedure.ModifyTableProcedure; 171import org.apache.hadoop.hbase.master.procedure.ProcedurePrepareLatch; 172import org.apache.hadoop.hbase.master.procedure.ProcedureSyncWait; 173import org.apache.hadoop.hbase.master.procedure.RSProcedureDispatcher; 174import org.apache.hadoop.hbase.master.procedure.RefreshHFilesTableProcedure; 175import org.apache.hadoop.hbase.master.procedure.RefreshMetaProcedure; 176import org.apache.hadoop.hbase.master.procedure.ReloadQuotasProcedure; 177import org.apache.hadoop.hbase.master.procedure.ReopenTableRegionsProcedure; 178import org.apache.hadoop.hbase.master.procedure.ServerCrashProcedure; 179import org.apache.hadoop.hbase.master.procedure.TruncateRegionProcedure; 180import org.apache.hadoop.hbase.master.procedure.TruncateTableProcedure; 181import org.apache.hadoop.hbase.master.region.MasterRegion; 182import org.apache.hadoop.hbase.master.region.MasterRegionFactory; 183import org.apache.hadoop.hbase.master.replication.AbstractPeerProcedure; 184import org.apache.hadoop.hbase.master.replication.AddPeerProcedure; 185import org.apache.hadoop.hbase.master.replication.DisablePeerProcedure; 186import org.apache.hadoop.hbase.master.replication.EnablePeerProcedure; 187import org.apache.hadoop.hbase.master.replication.MigrateReplicationQueueFromZkToTableProcedure; 188import org.apache.hadoop.hbase.master.replication.RemovePeerProcedure; 189import org.apache.hadoop.hbase.master.replication.ReplicationPeerManager; 190import org.apache.hadoop.hbase.master.replication.ReplicationPeerModificationStateStore; 191import org.apache.hadoop.hbase.master.replication.SyncReplicationReplayWALManager; 192import org.apache.hadoop.hbase.master.replication.TransitPeerSyncReplicationStateProcedure; 193import org.apache.hadoop.hbase.master.replication.UpdatePeerConfigProcedure; 194import org.apache.hadoop.hbase.master.slowlog.SlowLogMasterService; 195import org.apache.hadoop.hbase.master.snapshot.SnapshotCleanupStateStore; 196import org.apache.hadoop.hbase.master.snapshot.SnapshotManager; 197import org.apache.hadoop.hbase.master.waleventtracker.WALEventTrackerTableCreator; 198import org.apache.hadoop.hbase.master.zksyncer.MasterAddressSyncer; 199import org.apache.hadoop.hbase.master.zksyncer.MetaLocationSyncer; 200import org.apache.hadoop.hbase.mob.MobFileCleanerChore; 201import org.apache.hadoop.hbase.mob.MobFileCompactionChore; 202import org.apache.hadoop.hbase.monitoring.MemoryBoundedLogMessageBuffer; 203import org.apache.hadoop.hbase.monitoring.MonitoredTask; 204import org.apache.hadoop.hbase.monitoring.TaskGroup; 205import org.apache.hadoop.hbase.monitoring.TaskMonitor; 206import org.apache.hadoop.hbase.namequeues.NamedQueueRecorder; 207import org.apache.hadoop.hbase.procedure.MasterProcedureManagerHost; 208import org.apache.hadoop.hbase.procedure.flush.MasterFlushTableProcedureManager; 209import org.apache.hadoop.hbase.procedure2.LockedResource; 210import org.apache.hadoop.hbase.procedure2.Procedure; 211import org.apache.hadoop.hbase.procedure2.ProcedureEvent; 212import org.apache.hadoop.hbase.procedure2.ProcedureExecutor; 213import org.apache.hadoop.hbase.procedure2.RemoteProcedureDispatcher.RemoteProcedure; 214import org.apache.hadoop.hbase.procedure2.RemoteProcedureException; 215import org.apache.hadoop.hbase.procedure2.store.ProcedureStore; 216import org.apache.hadoop.hbase.procedure2.store.ProcedureStore.ProcedureStoreListener; 217import org.apache.hadoop.hbase.procedure2.store.region.RegionProcedureStore; 218import org.apache.hadoop.hbase.quotas.MasterQuotaManager; 219import org.apache.hadoop.hbase.quotas.MasterQuotasObserver; 220import org.apache.hadoop.hbase.quotas.QuotaObserverChore; 221import org.apache.hadoop.hbase.quotas.QuotaTableUtil; 222import org.apache.hadoop.hbase.quotas.QuotaUtil; 223import org.apache.hadoop.hbase.quotas.RpcThrottleStateStore; 224import org.apache.hadoop.hbase.quotas.SnapshotQuotaObserverChore; 225import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshot; 226import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshot.SpaceQuotaStatus; 227import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshotNotifier; 228import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshotNotifierFactory; 229import org.apache.hadoop.hbase.quotas.SpaceViolationPolicy; 230import org.apache.hadoop.hbase.regionserver.HRegionServer; 231import org.apache.hadoop.hbase.regionserver.NoSuchColumnFamilyException; 232import org.apache.hadoop.hbase.regionserver.storefiletracker.ModifyColumnFamilyStoreFileTrackerProcedure; 233import org.apache.hadoop.hbase.regionserver.storefiletracker.ModifyTableStoreFileTrackerProcedure; 234import org.apache.hadoop.hbase.replication.ReplicationException; 235import org.apache.hadoop.hbase.replication.ReplicationLoadSource; 236import org.apache.hadoop.hbase.replication.ReplicationPeerConfig; 237import org.apache.hadoop.hbase.replication.ReplicationPeerDescription; 238import org.apache.hadoop.hbase.replication.ReplicationUtils; 239import org.apache.hadoop.hbase.replication.SyncReplicationState; 240import org.apache.hadoop.hbase.replication.ZKReplicationQueueStorageForMigration; 241import org.apache.hadoop.hbase.replication.master.ReplicationHFileCleaner; 242import org.apache.hadoop.hbase.replication.master.ReplicationLogCleaner; 243import org.apache.hadoop.hbase.replication.master.ReplicationLogCleanerBarrier; 244import org.apache.hadoop.hbase.replication.master.ReplicationSinkTrackerTableCreator; 245import org.apache.hadoop.hbase.replication.regionserver.ReplicationSyncUp; 246import org.apache.hadoop.hbase.replication.regionserver.ReplicationSyncUp.ReplicationSyncUpToolInfo; 247import org.apache.hadoop.hbase.rsgroup.RSGroupAdminEndpoint; 248import org.apache.hadoop.hbase.rsgroup.RSGroupBasedLoadBalancer; 249import org.apache.hadoop.hbase.rsgroup.RSGroupInfoManager; 250import org.apache.hadoop.hbase.rsgroup.RSGroupUtil; 251import org.apache.hadoop.hbase.security.AccessDeniedException; 252import org.apache.hadoop.hbase.security.SecurityConstants; 253import org.apache.hadoop.hbase.security.Superusers; 254import org.apache.hadoop.hbase.security.UserProvider; 255import org.apache.hadoop.hbase.security.access.AbstractReadOnlyController; 256import org.apache.hadoop.hbase.trace.TraceUtil; 257import org.apache.hadoop.hbase.util.Addressing; 258import org.apache.hadoop.hbase.util.Bytes; 259import org.apache.hadoop.hbase.util.CommonFSUtils; 260import org.apache.hadoop.hbase.util.ConfigurationUtil; 261import org.apache.hadoop.hbase.util.CoprocessorConfigurationUtil; 262import org.apache.hadoop.hbase.util.DNS; 263import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 264import org.apache.hadoop.hbase.util.FSTableDescriptors; 265import org.apache.hadoop.hbase.util.FSUtils; 266import org.apache.hadoop.hbase.util.FutureUtils; 267import org.apache.hadoop.hbase.util.HBaseFsck; 268import org.apache.hadoop.hbase.util.HFileArchiveUtil; 269import org.apache.hadoop.hbase.util.IdLock; 270import org.apache.hadoop.hbase.util.JVMClusterUtil; 271import org.apache.hadoop.hbase.util.JsonMapper; 272import org.apache.hadoop.hbase.util.ModifyRegionUtils; 273import org.apache.hadoop.hbase.util.Pair; 274import org.apache.hadoop.hbase.util.ReflectionUtils; 275import org.apache.hadoop.hbase.util.RetryCounter; 276import org.apache.hadoop.hbase.util.RetryCounterFactory; 277import org.apache.hadoop.hbase.util.TableDescriptorChecker; 278import org.apache.hadoop.hbase.util.Threads; 279import org.apache.hadoop.hbase.util.VersionInfo; 280import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker; 281import org.apache.hadoop.hbase.zookeeper.MetaTableLocator; 282import org.apache.hadoop.hbase.zookeeper.ZKClusterId; 283import org.apache.hadoop.hbase.zookeeper.ZKUtil; 284import org.apache.hadoop.hbase.zookeeper.ZKWatcher; 285import org.apache.hadoop.hbase.zookeeper.ZNodePaths; 286import org.apache.yetus.audience.InterfaceAudience; 287import org.apache.zookeeper.KeeperException; 288import org.slf4j.Logger; 289import org.slf4j.LoggerFactory; 290 291import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 292import org.apache.hbase.thirdparty.com.google.common.collect.Maps; 293import org.apache.hbase.thirdparty.com.google.common.collect.Sets; 294import org.apache.hbase.thirdparty.com.google.common.io.ByteStreams; 295import org.apache.hbase.thirdparty.com.google.common.io.Closeables; 296import org.apache.hbase.thirdparty.com.google.gson.JsonParseException; 297import org.apache.hbase.thirdparty.com.google.protobuf.Descriptors; 298import org.apache.hbase.thirdparty.com.google.protobuf.Service; 299import org.apache.hbase.thirdparty.org.eclipse.jetty.ee8.servlet.ServletHolder; 300import org.apache.hbase.thirdparty.org.eclipse.jetty.ee8.webapp.WebAppContext; 301import org.apache.hbase.thirdparty.org.eclipse.jetty.server.Server; 302import org.apache.hbase.thirdparty.org.eclipse.jetty.server.ServerConnector; 303import org.apache.hbase.thirdparty.org.glassfish.jersey.server.ResourceConfig; 304import org.apache.hbase.thirdparty.org.glassfish.jersey.servlet.ServletContainer; 305 306import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter; 307import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoResponse; 308import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos.SnapshotDescription; 309 310/** 311 * HMaster is the "master server" for HBase. An HBase cluster has one active master. If many masters 312 * are started, all compete. Whichever wins goes on to run the cluster. All others park themselves 313 * in their constructor until master or cluster shutdown or until the active master loses its lease 314 * in zookeeper. Thereafter, all running master jostle to take over master role. 315 * <p/> 316 * The Master can be asked shutdown the cluster. See {@link #shutdown()}. In this case it will tell 317 * all regionservers to go down and then wait on them all reporting in that they are down. This 318 * master will then shut itself down. 319 * <p/> 320 * You can also shutdown just this master. Call {@link #stopMaster()}. 321 * @see org.apache.zookeeper.Watcher 322 */ 323@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS) 324public class HMaster extends HBaseServerBase<MasterRpcServices> implements MasterServices { 325 326 private static final Logger LOG = LoggerFactory.getLogger(HMaster.class); 327 328 // MASTER is name of the webapp and the attribute name used stuffing this 329 // instance into a web context !! AND OTHER PLACES !! 330 public static final String MASTER = "master"; 331 332 // Manager and zk listener for master election 333 private final ActiveMasterManager activeMasterManager; 334 // Region server tracker 335 private final RegionServerTracker regionServerTracker; 336 // Draining region server tracker 337 private DrainingServerTracker drainingServerTracker; 338 // Tracker for load balancer state 339 LoadBalancerStateStore loadBalancerStateStore; 340 // Tracker for meta location, if any client ZK quorum specified 341 private MetaLocationSyncer metaLocationSyncer; 342 // Tracker for active master location, if any client ZK quorum specified 343 @InterfaceAudience.Private 344 MasterAddressSyncer masterAddressSyncer; 345 // Tracker for auto snapshot cleanup state 346 SnapshotCleanupStateStore snapshotCleanupStateStore; 347 348 // Tracker for split and merge state 349 private SplitOrMergeStateStore splitOrMergeStateStore; 350 351 private ClusterSchemaService clusterSchemaService; 352 353 public static final String HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS = 354 "hbase.master.wait.on.service.seconds"; 355 public static final int DEFAULT_HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS = 5 * 60; 356 357 public static final String HBASE_MASTER_CLEANER_INTERVAL = "hbase.master.cleaner.interval"; 358 359 public static final int DEFAULT_HBASE_MASTER_CLEANER_INTERVAL = 600 * 1000; 360 361 private String clusterId; 362 363 // Metrics for the HMaster 364 final MetricsMaster metricsMaster; 365 // file system manager for the master FS operations 366 private MasterFileSystem fileSystemManager; 367 private MasterWalManager walManager; 368 369 // manager to manage procedure-based WAL splitting, can be null if current 370 // is zk-based WAL splitting. SplitWALManager will replace SplitLogManager 371 // and MasterWalManager, which means zk-based WAL splitting code will be 372 // useless after we switch to the procedure-based one. our eventual goal 373 // is to remove all the zk-based WAL splitting code. 374 private SplitWALManager splitWALManager; 375 376 // server manager to deal with region server info 377 private volatile ServerManager serverManager; 378 379 // manager of assignment nodes in zookeeper 380 private AssignmentManager assignmentManager; 381 382 private RSGroupInfoManager rsGroupInfoManager; 383 384 private final ReplicationLogCleanerBarrier replicationLogCleanerBarrier = 385 new ReplicationLogCleanerBarrier(); 386 387 // Only allow to add one sync replication peer concurrently 388 private final Semaphore syncReplicationPeerLock = new Semaphore(1); 389 390 // manager of replication 391 private ReplicationPeerManager replicationPeerManager; 392 393 private SyncReplicationReplayWALManager syncReplicationReplayWALManager; 394 395 // buffer for "fatal error" notices from region servers 396 // in the cluster. This is only used for assisting 397 // operations/debugging. 398 MemoryBoundedLogMessageBuffer rsFatals; 399 400 // flag set after we become the active master (used for testing) 401 private volatile boolean activeMaster = false; 402 403 // flag set after we complete initialization once active 404 private final ProcedureEvent<?> initialized = new ProcedureEvent<>("master initialized"); 405 406 // flag set after master services are started, 407 // initialization may have not completed yet. 408 volatile boolean serviceStarted = false; 409 410 // Maximum time we should run balancer for 411 private final int maxBalancingTime; 412 // Maximum percent of regions in transition when balancing 413 private final double maxRitPercent; 414 415 private final LockManager lockManager = new LockManager(this); 416 417 private RSGroupBasedLoadBalancer balancer; 418 private BalancerChore balancerChore; 419 private static boolean disableBalancerChoreForTest = false; 420 private RegionNormalizerManager regionNormalizerManager; 421 private ClusterStatusChore clusterStatusChore; 422 private ClusterStatusPublisher clusterStatusPublisherChore = null; 423 private SnapshotCleanerChore snapshotCleanerChore = null; 424 425 private HbckChore hbckChore; 426 CatalogJanitor catalogJanitorChore; 427 // Threadpool for scanning the Old logs directory, used by the LogCleaner 428 private DirScanPool logCleanerPool; 429 private LogCleaner logCleaner; 430 // HFile cleaners for the custom hfile archive paths and the default archive path 431 // The archive path cleaner is the first element 432 private List<HFileCleaner> hfileCleaners = new ArrayList<>(); 433 // The hfile cleaner paths, including custom paths and the default archive path 434 private List<Path> hfileCleanerPaths = new ArrayList<>(); 435 // The shared hfile cleaner pool for the custom archive paths 436 private DirScanPool sharedHFileCleanerPool; 437 // The exclusive hfile cleaner pool for scanning the archive directory 438 private DirScanPool exclusiveHFileCleanerPool; 439 private ReplicationBarrierCleaner replicationBarrierCleaner; 440 private MobFileCleanerChore mobFileCleanerChore; 441 private MobFileCompactionChore mobFileCompactionChore; 442 private RollingUpgradeChore rollingUpgradeChore; 443 // used to synchronize the mobCompactionStates 444 private final IdLock mobCompactionLock = new IdLock(); 445 // save the information of mob compactions in tables. 446 // the key is table name, the value is the number of compactions in that table. 447 private Map<TableName, AtomicInteger> mobCompactionStates = Maps.newConcurrentMap(); 448 449 volatile MasterCoprocessorHost cpHost; 450 451 private final boolean preLoadTableDescriptors; 452 453 // Time stamps for when a hmaster became active 454 private long masterActiveTime; 455 456 // Time stamp for when HMaster finishes becoming Active Master 457 private long masterFinishedInitializationTime; 458 459 Map<String, Service> coprocessorServiceHandlers = Maps.newHashMap(); 460 461 // monitor for snapshot of hbase tables 462 SnapshotManager snapshotManager; 463 // monitor for distributed procedures 464 private MasterProcedureManagerHost mpmHost; 465 466 private RegionsRecoveryChore regionsRecoveryChore = null; 467 468 private RegionsRecoveryConfigManager regionsRecoveryConfigManager = null; 469 // it is assigned after 'initialized' guard set to true, so should be volatile 470 private volatile MasterQuotaManager quotaManager; 471 private RpcThrottleStateStore rpcThrottleStateStore; 472 private SpaceQuotaSnapshotNotifier spaceQuotaSnapshotNotifier; 473 private QuotaObserverChore quotaObserverChore; 474 private SnapshotQuotaObserverChore snapshotQuotaChore; 475 private OldWALsDirSizeChore oldWALsDirSizeChore; 476 477 private ProcedureExecutor<MasterProcedureEnv> procedureExecutor; 478 private ProcedureStore procedureStore; 479 480 // the master local storage to store procedure data, meta region locations, etc. 481 private MasterRegion masterRegion; 482 483 private RegionServerList rsListStorage; 484 485 // handle table states 486 private TableStateManager tableStateManager; 487 488 /** jetty server for master to redirect requests to regionserver infoServer */ 489 private Server masterJettyServer; 490 491 // Determine if we should do normal startup or minimal "single-user" mode with no region 492 // servers and no user tables. Useful for repair and recovery of hbase:meta 493 private final boolean maintenanceMode; 494 static final String MAINTENANCE_MODE = "hbase.master.maintenance_mode"; 495 496 // the in process region server for carry system regions in maintenanceMode 497 private JVMClusterUtil.RegionServerThread maintenanceRegionServer; 498 499 // Cached clusterId on stand by masters to serve clusterID requests from clients. 500 private final CachedClusterId cachedClusterId; 501 502 public static final String WARMUP_BEFORE_MOVE = "hbase.master.warmup.before.move"; 503 private static final boolean DEFAULT_WARMUP_BEFORE_MOVE = true; 504 505 /** 506 * Use RSProcedureDispatcher instance to initiate master -> rs remote procedure execution. Use 507 * this config to extend RSProcedureDispatcher (mainly for testing purpose). 508 */ 509 public static final String HBASE_MASTER_RSPROC_DISPATCHER_CLASS = 510 "hbase.master.rsproc.dispatcher.class"; 511 private static final String DEFAULT_HBASE_MASTER_RSPROC_DISPATCHER_CLASS = 512 RSProcedureDispatcher.class.getName(); 513 514 private TaskGroup startupTaskGroup; 515 516 /** 517 * Store whether we allow replication peer modification operations. 518 */ 519 private ReplicationPeerModificationStateStore replicationPeerModificationStateStore; 520 521 /** 522 * Initializes the HMaster. The steps are as follows: 523 * <p> 524 * <ol> 525 * <li>Initialize the local HRegionServer 526 * <li>Start the ActiveMasterManager. 527 * </ol> 528 * <p> 529 * Remaining steps of initialization occur in {@link #finishActiveMasterInitialization()} after 530 * the master becomes the active one. 531 */ 532 public HMaster(final Configuration conf) throws IOException { 533 super(conf, "Master"); 534 final Span span = TraceUtil.createSpan("HMaster.cxtor"); 535 try (Scope ignored = span.makeCurrent()) { 536 if (conf.getBoolean(MAINTENANCE_MODE, false)) { 537 LOG.info("Detected {}=true via configuration.", MAINTENANCE_MODE); 538 maintenanceMode = true; 539 } else if (Boolean.getBoolean(MAINTENANCE_MODE)) { 540 LOG.info("Detected {}=true via environment variables.", MAINTENANCE_MODE); 541 maintenanceMode = true; 542 } else { 543 maintenanceMode = false; 544 } 545 this.rsFatals = new MemoryBoundedLogMessageBuffer( 546 conf.getLong("hbase.master.buffer.for.rs.fatals", 1 * 1024 * 1024)); 547 LOG.info("hbase.rootdir={}, hbase.cluster.distributed={}", 548 CommonFSUtils.getRootDir(this.conf), 549 this.conf.getBoolean(HConstants.CLUSTER_DISTRIBUTED, false)); 550 551 // Disable usage of meta replicas in the master 552 this.conf.setBoolean(HConstants.USE_META_REPLICAS, false); 553 554 decorateMasterConfiguration(this.conf); 555 556 // Hack! Maps DFSClient => Master for logs. HDFS made this 557 // config param for task trackers, but we can piggyback off of it. 558 if (this.conf.get("mapreduce.task.attempt.id") == null) { 559 this.conf.set("mapreduce.task.attempt.id", "hb_m_" + this.serverName.toString()); 560 } 561 562 this.metricsMaster = new MetricsMaster(new MetricsMasterWrapperImpl(this)); 563 564 // preload table descriptor at startup 565 this.preLoadTableDescriptors = conf.getBoolean("hbase.master.preload.tabledescriptors", true); 566 567 this.maxBalancingTime = getMaxBalancingTime(); 568 this.maxRitPercent = conf.getDouble(HConstants.HBASE_MASTER_BALANCER_MAX_RIT_PERCENT, 569 HConstants.DEFAULT_HBASE_MASTER_BALANCER_MAX_RIT_PERCENT); 570 571 // Do we publish the status? 572 boolean shouldPublish = 573 conf.getBoolean(HConstants.STATUS_PUBLISHED, HConstants.STATUS_PUBLISHED_DEFAULT); 574 Class<? extends ClusterStatusPublisher.Publisher> publisherClass = 575 conf.getClass(ClusterStatusPublisher.STATUS_PUBLISHER_CLASS, 576 ClusterStatusPublisher.DEFAULT_STATUS_PUBLISHER_CLASS, 577 ClusterStatusPublisher.Publisher.class); 578 579 if (shouldPublish) { 580 if (publisherClass == null) { 581 LOG.warn(HConstants.STATUS_PUBLISHED + " is true, but " 582 + ClusterStatusPublisher.DEFAULT_STATUS_PUBLISHER_CLASS 583 + " is not set - not publishing status"); 584 } else { 585 clusterStatusPublisherChore = new ClusterStatusPublisher(this, conf, publisherClass); 586 LOG.debug("Created {}", this.clusterStatusPublisherChore); 587 getChoreService().scheduleChore(clusterStatusPublisherChore); 588 } 589 } 590 this.activeMasterManager = createActiveMasterManager(zooKeeper, serverName, this); 591 cachedClusterId = new CachedClusterId(this, conf); 592 this.regionServerTracker = new RegionServerTracker(zooKeeper, this); 593 this.rpcServices.start(zooKeeper); 594 span.setStatus(StatusCode.OK); 595 } catch (Throwable t) { 596 // Make sure we log the exception. HMaster is often started via reflection and the 597 // cause of failed startup is lost. 598 TraceUtil.setError(span, t); 599 LOG.error("Failed construction of Master", t); 600 throw t; 601 } finally { 602 span.end(); 603 } 604 } 605 606 /** 607 * Protected to have custom implementations in tests override the default ActiveMaster 608 * implementation. 609 */ 610 protected ActiveMasterManager createActiveMasterManager(ZKWatcher zk, ServerName sn, 611 org.apache.hadoop.hbase.Server server) throws InterruptedIOException { 612 return new ActiveMasterManager(zk, sn, server); 613 } 614 615 @Override 616 protected String getUseThisHostnameInstead(Configuration conf) { 617 return conf.get(MASTER_HOSTNAME_KEY); 618 } 619 620 @Override 621 protected DNS.ServerType getDNSServerType() { 622 return DNS.ServerType.MASTER; 623 } 624 625 private void registerConfigurationObservers() { 626 configurationManager.registerObserver(this.rpcServices); 627 configurationManager.registerObserver(this); 628 } 629 630 // Main run loop. Calls through to the regionserver run loop AFTER becoming active Master; will 631 // block in here until then. 632 @Override 633 public void run() { 634 try { 635 installShutdownHook(); 636 registerConfigurationObservers(); 637 Threads.setDaemonThreadRunning(new Thread(TraceUtil.tracedRunnable(() -> { 638 try { 639 int infoPort = putUpJettyServer(); 640 startActiveMasterManager(infoPort); 641 } catch (Throwable t) { 642 // Make sure we log the exception. 643 String error = "Failed to become Active Master"; 644 LOG.error(error, t); 645 // Abort should have been called already. 646 if (!isAborted()) { 647 abort(error, t); 648 } 649 } 650 }, "HMaster.becomeActiveMaster")), getName() + ":becomeActiveMaster"); 651 while (!isStopped() && !isAborted()) { 652 sleeper.sleep(); 653 } 654 final Span span = TraceUtil.createSpan("HMaster exiting main loop"); 655 try (Scope ignored = span.makeCurrent()) { 656 stopInfoServer(); 657 closeClusterConnection(); 658 stopServiceThreads(); 659 if (this.rpcServices != null) { 660 this.rpcServices.stop(); 661 } 662 closeZooKeeper(); 663 closeTableDescriptors(); 664 span.setStatus(StatusCode.OK); 665 } finally { 666 span.end(); 667 } 668 } finally { 669 if (this.clusterSchemaService != null) { 670 // If on way out, then we are no longer active master. 671 this.clusterSchemaService.stopAsync(); 672 try { 673 this.clusterSchemaService 674 .awaitTerminated(getConfiguration().getInt(HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS, 675 DEFAULT_HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS), TimeUnit.SECONDS); 676 } catch (TimeoutException te) { 677 LOG.warn("Failed shutdown of clusterSchemaService", te); 678 } 679 } 680 this.activeMaster = false; 681 } 682 } 683 684 // return the actual infoPort, -1 means disable info server. 685 private int putUpJettyServer() throws IOException { 686 if (!conf.getBoolean("hbase.master.infoserver.redirect", true)) { 687 return -1; 688 } 689 final int infoPort = 690 conf.getInt("hbase.master.info.port.orig", HConstants.DEFAULT_MASTER_INFOPORT); 691 // -1 is for disabling info server, so no redirecting 692 if (infoPort < 0 || infoServer == null) { 693 return -1; 694 } 695 if (infoPort == infoServer.getPort()) { 696 // server is already running 697 return infoPort; 698 } 699 final String addr = conf.get("hbase.master.info.bindAddress", "0.0.0.0"); 700 if (!Addressing.isLocalAddress(InetAddress.getByName(addr))) { 701 String msg = "Failed to start redirecting jetty server. Address " + addr 702 + " does not belong to this host. Correct configuration parameter: " 703 + "hbase.master.info.bindAddress"; 704 LOG.error(msg); 705 throw new IOException(msg); 706 } 707 708 // TODO I'm pretty sure we could just add another binding to the InfoServer run by 709 // the RegionServer and have it run the RedirectServlet instead of standing up 710 // a second entire stack here. 711 masterJettyServer = new Server(); 712 final ServerConnector connector = new ServerConnector(masterJettyServer); 713 connector.setHost(addr); 714 connector.setPort(infoPort); 715 masterJettyServer.addConnector(connector); 716 masterJettyServer.setStopAtShutdown(true); 717 masterJettyServer.setHandler(HttpServer.buildGzipHandler(masterJettyServer.getHandler())); 718 719 final String redirectHostname = 720 StringUtils.isBlank(useThisHostnameInstead) ? null : useThisHostnameInstead; 721 722 final MasterRedirectServlet redirect = new MasterRedirectServlet(infoServer, redirectHostname); 723 final WebAppContext context = 724 new WebAppContext(null, "/", null, null, null, null, WebAppContext.NO_SESSIONS); 725 context.addServlet(new ServletHolder(redirect), "/*"); 726 context.setServer(masterJettyServer); 727 728 try { 729 masterJettyServer.start(); 730 } catch (Exception e) { 731 throw new IOException("Failed to start redirecting jetty server", e); 732 } 733 return connector.getLocalPort(); 734 } 735 736 /** 737 * For compatibility, if failed with regionserver credentials, try the master one 738 */ 739 @Override 740 protected void login(UserProvider user, String host) throws IOException { 741 try { 742 user.login(SecurityConstants.REGIONSERVER_KRB_KEYTAB_FILE, 743 SecurityConstants.REGIONSERVER_KRB_PRINCIPAL, host); 744 } catch (IOException ie) { 745 user.login(SecurityConstants.MASTER_KRB_KEYTAB_FILE, SecurityConstants.MASTER_KRB_PRINCIPAL, 746 host); 747 } 748 } 749 750 public MasterRpcServices getMasterRpcServices() { 751 return rpcServices; 752 } 753 754 @Override 755 protected MasterCoprocessorHost getCoprocessorHost() { 756 return getMasterCoprocessorHost(); 757 } 758 759 public boolean balanceSwitch(final boolean b) throws IOException { 760 return getMasterRpcServices().switchBalancer(b, BalanceSwitchMode.ASYNC); 761 } 762 763 @Override 764 protected String getProcessName() { 765 return MASTER; 766 } 767 768 @Override 769 protected boolean canCreateBaseZNode() { 770 return true; 771 } 772 773 @Override 774 protected boolean canUpdateTableDescriptor() { 775 return true; 776 } 777 778 @Override 779 protected boolean cacheTableDescriptor() { 780 return true; 781 } 782 783 protected MasterRpcServices createRpcServices() throws IOException { 784 return new MasterRpcServices(this); 785 } 786 787 @Override 788 protected void configureInfoServer(InfoServer infoServer) { 789 infoServer.addUnprivilegedServlet("master-status", "/master-status", MasterStatusServlet.class); 790 infoServer.addUnprivilegedServlet("api_v1", "/api/v1/*", buildApiV1Servlet()); 791 infoServer.addUnprivilegedServlet("hbck", "/hbck/*", buildHbckServlet()); 792 793 infoServer.setAttribute(MASTER, this); 794 } 795 796 private ServletHolder buildApiV1Servlet() { 797 final ResourceConfig config = ResourceConfigFactory.createResourceConfig(conf, this); 798 return new ServletHolder(new ServletContainer(config)); 799 } 800 801 private ServletHolder buildHbckServlet() { 802 final ResourceConfig config = HbckConfigFactory.createResourceConfig(conf, this); 803 return new ServletHolder(new ServletContainer(config)); 804 } 805 806 @Override 807 protected Class<? extends HttpServlet> getDumpServlet() { 808 return MasterDumpServlet.class; 809 } 810 811 @Override 812 public MetricsMaster getMasterMetrics() { 813 return metricsMaster; 814 } 815 816 /** 817 * Initialize all ZK based system trackers. But do not include {@link RegionServerTracker}, it 818 * should have already been initialized along with {@link ServerManager}. 819 */ 820 private void initializeZKBasedSystemTrackers() 821 throws IOException, KeeperException, ReplicationException, DeserializationException { 822 if (maintenanceMode) { 823 // in maintenance mode, always use MaintenanceLoadBalancer. 824 conf.unset(LoadBalancer.HBASE_RSGROUP_LOADBALANCER_CLASS); 825 conf.setClass(HConstants.HBASE_MASTER_LOADBALANCER_CLASS, MaintenanceLoadBalancer.class, 826 LoadBalancer.class); 827 } 828 this.balancer = new RSGroupBasedLoadBalancer(); 829 this.loadBalancerStateStore = new LoadBalancerStateStore(masterRegion, zooKeeper); 830 831 this.regionNormalizerManager = 832 RegionNormalizerFactory.createNormalizerManager(conf, masterRegion, zooKeeper, this); 833 this.configurationManager.registerObserver(regionNormalizerManager); 834 this.regionNormalizerManager.start(); 835 836 this.splitOrMergeStateStore = new SplitOrMergeStateStore(masterRegion, zooKeeper, conf); 837 838 // This is for backwards compatible. We do not need the CP for rs group now but if user want to 839 // load it, we need to enable rs group. 840 String[] cpClasses = conf.getStrings(MasterCoprocessorHost.MASTER_COPROCESSOR_CONF_KEY); 841 if (cpClasses != null) { 842 for (String cpClass : cpClasses) { 843 if (RSGroupAdminEndpoint.class.getName().equals(cpClass)) { 844 RSGroupUtil.enableRSGroup(conf); 845 break; 846 } 847 } 848 } 849 this.rsGroupInfoManager = RSGroupInfoManager.create(this); 850 851 this.replicationPeerManager = ReplicationPeerManager.create(this, clusterId); 852 this.configurationManager.registerObserver(replicationPeerManager); 853 this.replicationPeerModificationStateStore = 854 new ReplicationPeerModificationStateStore(masterRegion); 855 856 this.drainingServerTracker = new DrainingServerTracker(zooKeeper, this, this.serverManager); 857 this.drainingServerTracker.start(); 858 859 this.snapshotCleanupStateStore = new SnapshotCleanupStateStore(masterRegion, zooKeeper); 860 861 String clientQuorumServers = conf.get(HConstants.CLIENT_ZOOKEEPER_QUORUM); 862 boolean clientZkObserverMode = conf.getBoolean(HConstants.CLIENT_ZOOKEEPER_OBSERVER_MODE, 863 HConstants.DEFAULT_CLIENT_ZOOKEEPER_OBSERVER_MODE); 864 if (clientQuorumServers != null && !clientZkObserverMode) { 865 // we need to take care of the ZK information synchronization 866 // if given client ZK are not observer nodes 867 ZKWatcher clientZkWatcher = new ZKWatcher(conf, 868 getProcessName() + ":" + rpcServices.getSocketAddress().getPort() + "-clientZK", this, 869 false, true); 870 this.metaLocationSyncer = new MetaLocationSyncer(zooKeeper, clientZkWatcher, this); 871 this.metaLocationSyncer.start(); 872 this.masterAddressSyncer = new MasterAddressSyncer(zooKeeper, clientZkWatcher, this); 873 this.masterAddressSyncer.start(); 874 // set cluster id is a one-go effort 875 ZKClusterId.setClusterId(clientZkWatcher, fileSystemManager.getClusterId()); 876 } 877 878 // Set the cluster as up. If new RSs, they'll be waiting on this before 879 // going ahead with their startup. 880 boolean wasUp = this.clusterStatusTracker.isClusterUp(); 881 if (!wasUp) this.clusterStatusTracker.setClusterUp(); 882 883 LOG.info("Active/primary master=" + this.serverName + ", sessionid=0x" 884 + Long.toHexString(this.zooKeeper.getRecoverableZooKeeper().getSessionId()) 885 + ", setting cluster-up flag (Was=" + wasUp + ")"); 886 887 // create/initialize the snapshot manager and other procedure managers 888 this.snapshotManager = new SnapshotManager(); 889 this.mpmHost = new MasterProcedureManagerHost(); 890 this.mpmHost.register(this.snapshotManager); 891 this.mpmHost.register(new MasterFlushTableProcedureManager()); 892 this.mpmHost.loadProcedures(conf); 893 this.mpmHost.initialize(this, this.metricsMaster); 894 895 String rpcThrottleZNode = conf.get(RpcThrottleStateStore.RPC_THROTTLE_ZNODE, 896 RpcThrottleStateStore.RPC_THROTTLE_ZNODE_DEFAULT); 897 this.rpcThrottleStateStore = new RpcThrottleStateStore(masterRegion, zooKeeper, 898 ZNodePaths.joinZNode(zooKeeper.getZNodePaths().baseZNode, rpcThrottleZNode)); 899 } 900 901 // Will be overriden in test to inject customized AssignmentManager 902 @InterfaceAudience.Private 903 protected AssignmentManager createAssignmentManager(MasterServices master, 904 MasterRegion masterRegion) { 905 return new AssignmentManager(master, masterRegion); 906 } 907 908 private void tryMigrateMetaLocationsFromZooKeeper() throws IOException, KeeperException { 909 // try migrate data from zookeeper 910 try (ResultScanner scanner = 911 masterRegion.getScanner(new Scan().addFamily(HConstants.CATALOG_FAMILY))) { 912 if (scanner.next() != null) { 913 // notice that all replicas for a region are in the same row, so the migration can be 914 // done with in a one row put, which means if we have data in catalog family then we can 915 // make sure that the migration is done. 916 LOG.info("The {} family in master local region already has data in it, skip migrating...", 917 HConstants.CATALOG_FAMILY_STR); 918 return; 919 } 920 } 921 // start migrating 922 byte[] row = CatalogFamilyFormat.getMetaKeyForRegion(RegionInfoBuilder.FIRST_META_REGIONINFO); 923 Put put = new Put(row); 924 List<String> metaReplicaNodes = zooKeeper.getMetaReplicaNodes(); 925 StringBuilder info = new StringBuilder("Migrating meta locations:"); 926 for (String metaReplicaNode : metaReplicaNodes) { 927 int replicaId = zooKeeper.getZNodePaths().getMetaReplicaIdFromZNode(metaReplicaNode); 928 RegionState state = MetaTableLocator.getMetaRegionState(zooKeeper, replicaId); 929 info.append(" ").append(state); 930 put.setTimestamp(state.getStamp()); 931 MetaTableAccessor.addRegionInfo(put, state.getRegion()); 932 if (state.getServerName() != null) { 933 MetaTableAccessor.addLocation(put, state.getServerName(), HConstants.NO_SEQNUM, replicaId); 934 } 935 put.add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY).setRow(put.getRow()) 936 .setFamily(HConstants.CATALOG_FAMILY) 937 .setQualifier(RegionStateStore.getStateColumn(replicaId)).setTimestamp(put.getTimestamp()) 938 .setType(Cell.Type.Put).setValue(Bytes.toBytes(state.getState().name())).build()); 939 } 940 if (!put.isEmpty()) { 941 LOG.info(info.toString()); 942 masterRegion.update(r -> r.put(put)); 943 } else { 944 LOG.info("No meta location available on zookeeper, skip migrating..."); 945 } 946 } 947 948 /** 949 * Finish initialization of HMaster after becoming the primary master. 950 * <p/> 951 * The startup order is a bit complicated but very important, do not change it unless you know 952 * what you are doing. 953 * <ol> 954 * <li>Initialize file system based components - file system manager, wal manager, table 955 * descriptors, etc</li> 956 * <li>Publish cluster id</li> 957 * <li>Here comes the most complicated part - initialize server manager, assignment manager and 958 * region server tracker 959 * <ol type='i'> 960 * <li>Create server manager</li> 961 * <li>Create master local region</li> 962 * <li>Create procedure executor, load the procedures, but do not start workers. We will start it 963 * later after we finish scheduling SCPs to avoid scheduling duplicated SCPs for the same 964 * server</li> 965 * <li>Create assignment manager and start it, load the meta region state, but do not load data 966 * from meta region</li> 967 * <li>Start region server tracker, construct the online servers set and find out dead servers and 968 * schedule SCP for them. The online servers will be constructed by scanning zk, and we will also 969 * scan the wal directory and load from master local region to find out possible live region 970 * servers, and the differences between these two sets are the dead servers</li> 971 * </ol> 972 * </li> 973 * <li>If this is a new deploy, schedule a InitMetaProcedure to initialize meta</li> 974 * <li>Start necessary service threads - balancer, catalog janitor, executor services, and also 975 * the procedure executor, etc. Notice that the balancer must be created first as assignment 976 * manager may use it when assigning regions.</li> 977 * <li>Wait for meta to be initialized if necessary, start table state manager.</li> 978 * <li>Wait for enough region servers to check-in</li> 979 * <li>Let assignment manager load data from meta and construct region states</li> 980 * <li>Start all other things such as chore services, etc</li> 981 * </ol> 982 * <p/> 983 * Notice that now we will not schedule a special procedure to make meta online(unless the first 984 * time where meta has not been created yet), we will rely on SCP to bring meta online. 985 */ 986 private void finishActiveMasterInitialization() throws IOException, InterruptedException, 987 KeeperException, ReplicationException, DeserializationException { 988 /* 989 * We are active master now... go initialize components we need to run. 990 */ 991 startupTaskGroup.addTask("Initializing Master file system"); 992 993 this.masterActiveTime = EnvironmentEdgeManager.currentTime(); 994 // TODO: Do this using Dependency Injection, using PicoContainer, Guice or Spring. 995 996 // always initialize the MemStoreLAB as we use a region to store data in master now, see 997 // localStore. 998 initializeMemStoreChunkCreator(null); 999 this.fileSystemManager = new MasterFileSystem(conf); 1000 this.walManager = new MasterWalManager(this); 1001 1002 // warm-up HTDs cache on master initialization 1003 if (preLoadTableDescriptors) { 1004 startupTaskGroup.addTask("Pre-loading table descriptors"); 1005 this.tableDescriptors.getAll(); 1006 } 1007 1008 // Publish cluster ID; set it in Master too. The superclass RegionServer does this later but 1009 // only after it has checked in with the Master. At least a few tests ask Master for clusterId 1010 // before it has called its run method and before RegionServer has done the reportForDuty. 1011 ClusterId clusterId = fileSystemManager.getClusterId(); 1012 startupTaskGroup.addTask("Publishing Cluster ID " + clusterId + " in ZooKeeper"); 1013 ZKClusterId.setClusterId(this.zooKeeper, fileSystemManager.getClusterId()); 1014 this.clusterId = clusterId.toString(); 1015 1016 // Precaution. Put in place the old hbck1 lock file to fence out old hbase1s running their 1017 // hbck1s against an hbase2 cluster; it could do damage. To skip this behavior, set 1018 // hbase.write.hbck1.lock.file to false. 1019 if (this.conf.getBoolean("hbase.write.hbck1.lock.file", true)) { 1020 Pair<Path, FSDataOutputStream> result = null; 1021 try { 1022 result = HBaseFsck.checkAndMarkRunningHbck(this.conf, 1023 HBaseFsck.createLockRetryCounterFactory(this.conf).create()); 1024 } finally { 1025 if (result != null) { 1026 Closeables.close(result.getSecond(), true); 1027 } 1028 } 1029 } 1030 1031 startupTaskGroup.addTask("Initialize ServerManager and schedule SCP for crash servers"); 1032 // The below two managers must be created before loading procedures, as they will be used during 1033 // loading. 1034 // initialize master local region 1035 masterRegion = MasterRegionFactory.create(this); 1036 rsListStorage = new MasterRegionServerList(masterRegion, this); 1037 1038 // Initialize the ServerManager and register it as a configuration observer 1039 this.serverManager = createServerManager(this, rsListStorage); 1040 this.configurationManager.registerObserver(this.serverManager); 1041 1042 this.syncReplicationReplayWALManager = new SyncReplicationReplayWALManager(this); 1043 if ( 1044 !conf.getBoolean(HBASE_SPLIT_WAL_COORDINATED_BY_ZK, DEFAULT_HBASE_SPLIT_COORDINATED_BY_ZK) 1045 ) { 1046 this.splitWALManager = new SplitWALManager(this); 1047 } 1048 1049 tryMigrateMetaLocationsFromZooKeeper(); 1050 1051 createProcedureExecutor(); 1052 Map<Class<?>, List<Procedure<MasterProcedureEnv>>> procsByType = procedureExecutor 1053 .getActiveProceduresNoCopy().stream().collect(Collectors.groupingBy(p -> p.getClass())); 1054 1055 // Create Assignment Manager 1056 this.assignmentManager = createAssignmentManager(this, masterRegion); 1057 this.assignmentManager.start(); 1058 // TODO: TRSP can perform as the sub procedure for other procedures, so even if it is marked as 1059 // completed, it could still be in the procedure list. This is a bit strange but is another 1060 // story, need to verify the implementation for ProcedureExecutor and ProcedureStore. 1061 List<TransitRegionStateProcedure> ritList = 1062 procsByType.getOrDefault(TransitRegionStateProcedure.class, Collections.emptyList()).stream() 1063 .filter(p -> !p.isFinished()).map(p -> (TransitRegionStateProcedure) p) 1064 .collect(Collectors.toList()); 1065 this.assignmentManager.setupRIT(ritList); 1066 1067 // Start RegionServerTracker with listing of servers found with exiting SCPs -- these should 1068 // be registered in the deadServers set -- and the servernames loaded from the WAL directory 1069 // and master local region that COULD BE 'alive'(we'll schedule SCPs for each and let SCP figure 1070 // it out). 1071 // We also pass dirs that are already 'splitting'... so we can do some checks down in tracker. 1072 // TODO: Generate the splitting and live Set in one pass instead of two as we currently do. 1073 this.regionServerTracker.upgrade( 1074 procsByType.getOrDefault(ServerCrashProcedure.class, Collections.emptyList()).stream() 1075 .map(p -> (ServerCrashProcedure) p).collect( 1076 Collectors.toMap(ServerCrashProcedure::getServerName, Procedure::getSubmittedTime)), 1077 Sets.union(rsListStorage.getAll(), walManager.getLiveServersFromWALDir()), 1078 walManager.getSplittingServersFromWALDir()); 1079 // This manager must be accessed AFTER hbase:meta is confirmed on line.. 1080 this.tableStateManager = new TableStateManager(this); 1081 1082 startupTaskGroup.addTask("Initializing ZK system trackers"); 1083 initializeZKBasedSystemTrackers(); 1084 startupTaskGroup.addTask("Loading last flushed sequence id of regions"); 1085 try { 1086 this.serverManager.loadLastFlushedSequenceIds(); 1087 } catch (IOException e) { 1088 LOG.info("Failed to load last flushed sequence id of regions" + " from file system", e); 1089 } 1090 // Set ourselves as active Master now our claim has succeeded up in zk. 1091 this.activeMaster = true; 1092 1093 // Start the Zombie master detector after setting master as active, see HBASE-21535 1094 Thread zombieDetector = new Thread(new MasterInitializationMonitor(this), 1095 "ActiveMasterInitializationMonitor-" + EnvironmentEdgeManager.currentTime()); 1096 zombieDetector.setDaemon(true); 1097 zombieDetector.start(); 1098 1099 if (!maintenanceMode) { 1100 startupTaskGroup.addTask("Initializing master coprocessors"); 1101 setQuotasObserver(conf); 1102 CoprocessorConfigurationUtil.syncReadOnlyConfigurations(conf, 1103 CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY); 1104 AbstractReadOnlyController.manageActiveClusterIdFile( 1105 ConfigurationUtil.isReadOnlyModeEnabledInConf(conf), this.getMasterFileSystem()); 1106 initializeCoprocessorHost(conf); 1107 } else { 1108 // start an in process region server for carrying system regions 1109 maintenanceRegionServer = 1110 JVMClusterUtil.createRegionServerThread(getConfiguration(), HRegionServer.class, 0); 1111 maintenanceRegionServer.start(); 1112 } 1113 1114 // Checking if meta needs initializing. 1115 startupTaskGroup.addTask("Initializing meta table if this is a new deploy"); 1116 InitMetaProcedure initMetaProc = null; 1117 1118 // Always look for an already-running InitMetaProcedure first. Once such a procedure has passed 1119 // the INIT_META_ASSIGN_META state, a RegionState for meta exists, so guarding this lookup with 1120 // hasTableRegionStates would hide a still-running procedure, and we would skip awaiting it. 1121 // Filter out finished procedures: getProcedures() also returns completed procedures reloaded 1122 // from the procedure store, and awaiting such a procedure would block forever because its 1123 // completion latch is reset to 1 on deserialization and never counted down again. 1124 Optional<InitMetaProcedure> optProc = procedureExecutor.getProcedures().stream() 1125 .filter(p -> p instanceof InitMetaProcedure && !p.isFinished()) 1126 .map(o -> (InitMetaProcedure) o).findAny(); 1127 if (optProc.isPresent()) { 1128 initMetaProc = optProc.get(); 1129 } else if ( 1130 !this.assignmentManager.getRegionStates().hasTableRegionStates(TableName.META_TABLE_NAME) 1131 ) { 1132 // schedule an init meta procedure if meta has not been deployed yet 1133 initMetaProc = new InitMetaProcedure(); 1134 procedureExecutor.submitProcedure(initMetaProc); 1135 } 1136 1137 // initialize load balancer 1138 this.balancer.setMasterServices(this); 1139 this.balancer.initialize(); 1140 this.balancer.updateClusterMetrics(getClusterMetricsWithoutCoprocessor()); 1141 1142 // try migrate replication data 1143 ZKReplicationQueueStorageForMigration oldReplicationQueueStorage = 1144 new ZKReplicationQueueStorageForMigration(zooKeeper, conf); 1145 // check whether there are something to migrate and we haven't scheduled a migration procedure 1146 // yet 1147 if ( 1148 oldReplicationQueueStorage.hasData() && procedureExecutor.getProcedures().stream() 1149 .allMatch(p -> !(p instanceof MigrateReplicationQueueFromZkToTableProcedure)) 1150 ) { 1151 procedureExecutor.submitProcedure(new MigrateReplicationQueueFromZkToTableProcedure()); 1152 } 1153 // start up all service threads. 1154 startupTaskGroup.addTask("Initializing master service threads"); 1155 startServiceThreads(); 1156 // wait meta to be initialized after we start procedure executor 1157 if (initMetaProc != null) { 1158 initMetaProc.await(); 1159 if (initMetaProc.isFailed() && initMetaProc.hasException()) { 1160 throw new IOException("Failed to initialize meta table", initMetaProc.getException()); 1161 } 1162 } 1163 // Wake up this server to check in 1164 sleeper.skipSleepCycle(); 1165 1166 // Wait for region servers to report in. 1167 // With this as part of master initialization, it precludes our being able to start a single 1168 // server that is both Master and RegionServer. Needs more thought. TODO. 1169 String statusStr = "Wait for region servers to report in"; 1170 MonitoredTask waitRegionServer = startupTaskGroup.addTask(statusStr); 1171 LOG.info(Objects.toString(waitRegionServer)); 1172 waitForRegionServers(waitRegionServer); 1173 1174 // Check if master is shutting down because issue initializing regionservers or balancer. 1175 if (isStopped()) { 1176 return; 1177 } 1178 1179 startupTaskGroup.addTask("Starting assignment manager"); 1180 // FIRST HBASE:META READ!!!! 1181 // The below cannot make progress w/o hbase:meta being online. 1182 // This is the FIRST attempt at going to hbase:meta. Meta on-lining is going on in background 1183 // as procedures run -- in particular SCPs for crashed servers... One should put up hbase:meta 1184 // if it is down. It may take a while to come online. So, wait here until meta if for sure 1185 // available. That's what waitForMetaOnline does. 1186 if (!waitForMetaOnline()) { 1187 return; 1188 } 1189 1190 TableDescriptor metaDescriptor = tableDescriptors.get(TableName.META_TABLE_NAME); 1191 final ColumnFamilyDescriptor tableFamilyDesc = 1192 metaDescriptor.getColumnFamily(HConstants.TABLE_FAMILY); 1193 final ColumnFamilyDescriptor replBarrierFamilyDesc = 1194 metaDescriptor.getColumnFamily(HConstants.REPLICATION_BARRIER_FAMILY); 1195 1196 this.assignmentManager.initializationPostMetaOnline(); 1197 this.assignmentManager.joinCluster(); 1198 // The below depends on hbase:meta being online. 1199 this.assignmentManager.processOfflineRegions(); 1200 // this must be called after the above processOfflineRegions to prevent race 1201 this.assignmentManager.wakeMetaLoadedEvent(); 1202 1203 // for migrating from a version without HBASE-25099, and also for honoring the configuration 1204 // first. 1205 if (conf.get(HConstants.META_REPLICAS_NUM) != null) { 1206 int replicasNumInConf = 1207 conf.getInt(HConstants.META_REPLICAS_NUM, HConstants.DEFAULT_META_REPLICA_NUM); 1208 TableDescriptor metaDesc = tableDescriptors.get(TableName.META_TABLE_NAME); 1209 if (metaDesc.getRegionReplication() != replicasNumInConf) { 1210 // it is possible that we already have some replicas before upgrading, so we must set the 1211 // region replication number in meta TableDescriptor directly first, without creating a 1212 // ModifyTableProcedure, otherwise it may cause a double assign for the meta replicas. 1213 int existingReplicasCount = 1214 assignmentManager.getRegionStates().getRegionsOfTable(TableName.META_TABLE_NAME).size(); 1215 if (existingReplicasCount > metaDesc.getRegionReplication()) { 1216 LOG.info( 1217 "Update replica count of {} from {}(in TableDescriptor)" + " to {}(existing ZNodes)", 1218 TableName.META_TABLE_NAME, metaDesc.getRegionReplication(), existingReplicasCount); 1219 metaDesc = TableDescriptorBuilder.newBuilder(metaDesc) 1220 .setRegionReplication(existingReplicasCount).build(); 1221 tableDescriptors.update(metaDesc); 1222 } 1223 // check again, and issue a ModifyTableProcedure if needed 1224 if (metaDesc.getRegionReplication() != replicasNumInConf) { 1225 LOG.info( 1226 "The {} config is {} while the replica count in TableDescriptor is {}" 1227 + " for {}, altering...", 1228 HConstants.META_REPLICAS_NUM, replicasNumInConf, metaDesc.getRegionReplication(), 1229 TableName.META_TABLE_NAME); 1230 procedureExecutor.submitProcedure(new ModifyTableProcedure( 1231 procedureExecutor.getEnvironment(), TableDescriptorBuilder.newBuilder(metaDesc) 1232 .setRegionReplication(replicasNumInConf).build(), 1233 null, metaDesc, false, true)); 1234 } 1235 } 1236 } 1237 // Initialize after meta is up as below scans meta 1238 FavoredNodesManager fnm = getFavoredNodesManager(); 1239 if (fnm != null) { 1240 fnm.initializeFromMeta(); 1241 } 1242 1243 // set cluster status again after user regions are assigned 1244 this.balancer.updateClusterMetrics(getClusterMetricsWithoutCoprocessor()); 1245 1246 // Start balancer and meta catalog janitor after meta and regions have been assigned. 1247 startupTaskGroup.addTask("Starting balancer and catalog janitor"); 1248 this.clusterStatusChore = new ClusterStatusChore(this, balancer); 1249 getChoreService().scheduleChore(clusterStatusChore); 1250 this.balancerChore = new BalancerChore(this); 1251 if (!disableBalancerChoreForTest) { 1252 getChoreService().scheduleChore(balancerChore); 1253 } 1254 if (regionNormalizerManager != null) { 1255 getChoreService().scheduleChore(regionNormalizerManager.getRegionNormalizerChore()); 1256 } 1257 this.catalogJanitorChore = new CatalogJanitor(this); 1258 getChoreService().scheduleChore(catalogJanitorChore); 1259 this.hbckChore = new HbckChore(this); 1260 getChoreService().scheduleChore(hbckChore); 1261 this.serverManager.startChore(); 1262 1263 // Only for rolling upgrade, where we need to migrate the data in namespace table to meta table. 1264 if (!waitForNamespaceOnline()) { 1265 return; 1266 } 1267 startupTaskGroup.addTask("Starting cluster schema service"); 1268 try { 1269 initClusterSchemaService(); 1270 } catch (IllegalStateException e) { 1271 if ( 1272 e.getCause() != null && e.getCause() instanceof NoSuchColumnFamilyException 1273 && tableFamilyDesc == null && replBarrierFamilyDesc == null 1274 ) { 1275 LOG.info("ClusterSchema service could not be initialized. This is " 1276 + "expected during HBase 1 to 2 upgrade", e); 1277 } else { 1278 throw e; 1279 } 1280 } 1281 1282 if (this.cpHost != null) { 1283 try { 1284 this.cpHost.preMasterInitialization(); 1285 } catch (IOException e) { 1286 LOG.error("Coprocessor preMasterInitialization() hook failed", e); 1287 } 1288 } 1289 1290 LOG.info(String.format("Master has completed initialization %.3fsec", 1291 (EnvironmentEdgeManager.currentTime() - masterActiveTime) / 1000.0f)); 1292 this.masterFinishedInitializationTime = EnvironmentEdgeManager.currentTime(); 1293 configurationManager.registerObserver(this.balancer); 1294 configurationManager.registerObserver(this.logCleanerPool); 1295 configurationManager.registerObserver(this.logCleaner); 1296 configurationManager.registerObserver(this.regionsRecoveryConfigManager); 1297 configurationManager.registerObserver(this.exclusiveHFileCleanerPool); 1298 if (this.sharedHFileCleanerPool != null) { 1299 configurationManager.registerObserver(this.sharedHFileCleanerPool); 1300 } 1301 if (this.hfileCleaners != null) { 1302 for (HFileCleaner cleaner : hfileCleaners) { 1303 configurationManager.registerObserver(cleaner); 1304 } 1305 } 1306 // Set master as 'initialized'. 1307 setInitialized(true); 1308 startupTaskGroup.markComplete("Initialization successful"); 1309 MonitoredTask status = 1310 TaskMonitor.get().createStatus("Progress after master initialized", false, true); 1311 1312 if (tableFamilyDesc == null && replBarrierFamilyDesc == null) { 1313 // create missing CFs in meta table after master is set to 'initialized'. 1314 createMissingCFsInMetaDuringUpgrade(metaDescriptor); 1315 1316 // Throwing this Exception to abort active master is painful but this 1317 // seems the only way to add missing CFs in meta while upgrading from 1318 // HBase 1 to 2 (where HBase 2 has HBASE-23055 & HBASE-23782 checked-in). 1319 // So, why do we abort active master after adding missing CFs in meta? 1320 // When we reach here, we would have already bypassed NoSuchColumnFamilyException 1321 // in initClusterSchemaService(), meaning ClusterSchemaService is not 1322 // correctly initialized but we bypassed it. Similarly, we bypassed 1323 // tableStateManager.start() as well. Hence, we should better abort 1324 // current active master because our main task - adding missing CFs 1325 // in meta table is done (possible only after master state is set as 1326 // initialized) at the expense of bypassing few important tasks as part 1327 // of active master init routine. So now we abort active master so that 1328 // next active master init will not face any issues and all mandatory 1329 // services will be started during master init phase. 1330 throw new PleaseRestartMasterException("Aborting active master after missing" 1331 + " CFs are successfully added in meta. Subsequent active master " 1332 + "initialization should be uninterrupted"); 1333 } 1334 1335 if (maintenanceMode) { 1336 LOG.info("Detected repair mode, skipping final initialization steps."); 1337 return; 1338 } 1339 1340 assignmentManager.checkIfShouldMoveSystemRegionAsync(); 1341 status.setStatus("Starting quota manager"); 1342 initQuotaManager(); 1343 if (QuotaUtil.isQuotaEnabled(conf)) { 1344 // Create the quota snapshot notifier 1345 spaceQuotaSnapshotNotifier = createQuotaSnapshotNotifier(); 1346 spaceQuotaSnapshotNotifier.initialize(getConnection()); 1347 this.quotaObserverChore = new QuotaObserverChore(this, getMasterMetrics()); 1348 // Start the chore to read the region FS space reports and act on them 1349 getChoreService().scheduleChore(quotaObserverChore); 1350 1351 this.snapshotQuotaChore = new SnapshotQuotaObserverChore(this, getMasterMetrics()); 1352 // Start the chore to read snapshots and add their usage to table/NS quotas 1353 getChoreService().scheduleChore(snapshotQuotaChore); 1354 } 1355 final SlowLogMasterService slowLogMasterService = new SlowLogMasterService(conf, this); 1356 slowLogMasterService.init(); 1357 1358 WALEventTrackerTableCreator.createIfNeededAndNotExists(conf, this); 1359 // Create REPLICATION.SINK_TRACKER table if needed. 1360 ReplicationSinkTrackerTableCreator.createIfNeededAndNotExists(conf, this); 1361 1362 // clear the dead servers with same host name and port of online server because we are not 1363 // removing dead server with same hostname and port of rs which is trying to check in before 1364 // master initialization. See HBASE-5916. 1365 this.serverManager.clearDeadServersWithSameHostNameAndPortOfOnlineServer(); 1366 1367 // Check and set the znode ACLs if needed in case we are overtaking a non-secure configuration 1368 status.setStatus("Checking ZNode ACLs"); 1369 zooKeeper.checkAndSetZNodeAcls(); 1370 1371 status.setStatus("Initializing MOB Cleaner"); 1372 initMobCleaner(); 1373 1374 // delete the stale data for replication sync up tool if necessary 1375 status.setStatus("Cleanup ReplicationSyncUp status if necessary"); 1376 Path replicationSyncUpInfoFile = 1377 new Path(new Path(dataRootDir, ReplicationSyncUp.INFO_DIR), ReplicationSyncUp.INFO_FILE); 1378 if (dataFs.exists(replicationSyncUpInfoFile)) { 1379 // info file is available, load the timestamp and use it to clean up stale data in replication 1380 // queue storage. 1381 byte[] data; 1382 try (FSDataInputStream in = dataFs.open(replicationSyncUpInfoFile)) { 1383 data = ByteStreams.toByteArray(in); 1384 } 1385 ReplicationSyncUpToolInfo info = null; 1386 try { 1387 info = JsonMapper.fromJson(Bytes.toString(data), ReplicationSyncUpToolInfo.class); 1388 } catch (JsonParseException e) { 1389 // usually this should be a partial file, which means the ReplicationSyncUp tool did not 1390 // finish properly, so not a problem. Here we do not clean up the status as we do not know 1391 // the reason why the tool did not finish properly, so let users clean the status up 1392 // manually 1393 LOG.warn("failed to parse replication sync up info file, ignore and continue...", e); 1394 } 1395 if (info != null) { 1396 LOG.info("Remove last sequence ids and hfile references which are written before {}({})", 1397 info.getStartTimeMs(), DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneId.systemDefault()) 1398 .format(Instant.ofEpochMilli(info.getStartTimeMs()))); 1399 replicationPeerManager.getQueueStorage() 1400 .removeLastSequenceIdsAndHFileRefsBefore(info.getStartTimeMs()); 1401 // delete the file after removing the stale data, so next time we do not need to do this 1402 // again. 1403 dataFs.delete(replicationSyncUpInfoFile, false); 1404 } 1405 } 1406 status.setStatus("Calling postStartMaster coprocessors"); 1407 if (this.cpHost != null) { 1408 // don't let cp initialization errors kill the master 1409 try { 1410 this.cpHost.postStartMaster(); 1411 } catch (IOException ioe) { 1412 LOG.error("Coprocessor postStartMaster() hook failed", ioe); 1413 } 1414 } 1415 1416 zombieDetector.interrupt(); 1417 1418 /* 1419 * After master has started up, lets do balancer post startup initialization. Since this runs in 1420 * activeMasterManager thread, it should be fine. 1421 */ 1422 long start = EnvironmentEdgeManager.currentTime(); 1423 this.balancer.postMasterStartupInitialize(); 1424 if (LOG.isDebugEnabled()) { 1425 LOG.debug("Balancer post startup initialization complete, took " 1426 + ((EnvironmentEdgeManager.currentTime() - start) / 1000) + " seconds"); 1427 } 1428 1429 this.rollingUpgradeChore = new RollingUpgradeChore(this); 1430 getChoreService().scheduleChore(rollingUpgradeChore); 1431 1432 this.oldWALsDirSizeChore = new OldWALsDirSizeChore(this); 1433 getChoreService().scheduleChore(this.oldWALsDirSizeChore); 1434 1435 status.markComplete("Progress after master initialized complete"); 1436 } 1437 1438 /** 1439 * Used for testing only to set Mock objects. 1440 * @param hbckChore hbckChore 1441 */ 1442 public void setHbckChoreForTesting(HbckChore hbckChore) { 1443 this.hbckChore = hbckChore; 1444 } 1445 1446 /** 1447 * Used for testing only to set Mock objects. 1448 * @param catalogJanitorChore catalogJanitorChore 1449 */ 1450 public void setCatalogJanitorChoreForTesting(CatalogJanitor catalogJanitorChore) { 1451 this.catalogJanitorChore = catalogJanitorChore; 1452 } 1453 1454 private void createMissingCFsInMetaDuringUpgrade(TableDescriptor metaDescriptor) 1455 throws IOException { 1456 TableDescriptor newMetaDesc = TableDescriptorBuilder.newBuilder(metaDescriptor) 1457 .setColumnFamily(FSTableDescriptors.getTableFamilyDescForMeta(conf)) 1458 .setColumnFamily(FSTableDescriptors.getReplBarrierFamilyDescForMeta()).build(); 1459 long pid = this.modifyTable(TableName.META_TABLE_NAME, () -> newMetaDesc, 0, 0, false); 1460 waitForProcedureToComplete(pid, "Failed to add table and rep_barrier CFs to meta"); 1461 } 1462 1463 private void waitForProcedureToComplete(long pid, String errorMessage) throws IOException { 1464 int tries = 30; 1465 while ( 1466 !(getMasterProcedureExecutor().isFinished(pid)) && getMasterProcedureExecutor().isRunning() 1467 && tries > 0 1468 ) { 1469 try { 1470 Thread.sleep(1000); 1471 } catch (InterruptedException e) { 1472 throw new IOException("Wait interrupted", e); 1473 } 1474 tries--; 1475 } 1476 if (tries <= 0) { 1477 throw new HBaseIOException( 1478 "Failed to add table and rep_barrier CFs to meta in a given time."); 1479 } else { 1480 Procedure<?> result = getMasterProcedureExecutor().getResult(pid); 1481 if (result != null && result.isFailed()) { 1482 throw new IOException( 1483 errorMessage + ". " + MasterProcedureUtil.unwrapRemoteIOException(result)); 1484 } 1485 } 1486 } 1487 1488 /** 1489 * Check hbase:meta is up and ready for reading. For use during Master startup only. 1490 * @return True if meta is UP and online and startup can progress. Otherwise, meta is not online 1491 * and we will hold here until operator intervention. 1492 */ 1493 @InterfaceAudience.Private 1494 public boolean waitForMetaOnline() { 1495 return isRegionOnline(RegionInfoBuilder.FIRST_META_REGIONINFO); 1496 } 1497 1498 /** 1499 * @return True if region is online and scannable else false if an error or shutdown (Otherwise we 1500 * just block in here holding up all forward-progess). 1501 */ 1502 private boolean isRegionOnline(RegionInfo ri) { 1503 RetryCounter rc = null; 1504 while (!isStopped()) { 1505 RegionState rs = this.assignmentManager.getRegionStates().getRegionState(ri); 1506 if (rs != null && rs.isOpened()) { 1507 if (this.getServerManager().isServerOnline(rs.getServerName())) { 1508 return true; 1509 } 1510 } 1511 // Region is not OPEN. 1512 Optional<Procedure<MasterProcedureEnv>> optProc = this.procedureExecutor.getProcedures() 1513 .stream().filter(p -> p instanceof ServerCrashProcedure).findAny(); 1514 // TODO: Add a page to refguide on how to do repair. Have this log message point to it. 1515 // Page will talk about loss of edits, how to schedule at least the meta WAL recovery, and 1516 // then how to assign including how to break region lock if one held. 1517 LOG.warn( 1518 "{} is NOT online; state={}; ServerCrashProcedures={}. Master startup cannot " 1519 + "progress, in holding-pattern until region onlined.", 1520 ri.getRegionNameAsString(), rs, optProc.isPresent()); 1521 // Check once-a-minute. 1522 if (rc == null) { 1523 rc = new RetryCounterFactory(Integer.MAX_VALUE, 1000, 60_000).create(); 1524 } 1525 Threads.sleep(rc.getBackoffTimeAndIncrementAttempts()); 1526 } 1527 return false; 1528 } 1529 1530 /** 1531 * Check hbase:namespace table is assigned. If not, startup will hang looking for the ns table 1532 * <p/> 1533 * This is for rolling upgrading, later we will migrate the data in ns table to the ns family of 1534 * meta table. And if this is a new cluster, this method will return immediately as there will be 1535 * no namespace table/region. 1536 * @return True if namespace table is up/online. 1537 */ 1538 private boolean waitForNamespaceOnline() throws IOException { 1539 TableState nsTableState = 1540 MetaTableAccessor.getTableState(getConnection(), TableName.NAMESPACE_TABLE_NAME); 1541 if (nsTableState == null || nsTableState.isDisabled()) { 1542 // this means we have already migrated the data and disabled or deleted the namespace table, 1543 // or this is a new deploy which does not have a namespace table from the beginning. 1544 return true; 1545 } 1546 List<RegionInfo> ris = 1547 this.assignmentManager.getRegionStates().getRegionsOfTable(TableName.NAMESPACE_TABLE_NAME); 1548 if (ris.isEmpty()) { 1549 // maybe this will not happen any more, but anyway, no harm to add a check here... 1550 return true; 1551 } 1552 // Else there are namespace regions up in meta. Ensure they are assigned before we go on. 1553 for (RegionInfo ri : ris) { 1554 if (!isRegionOnline(ri)) { 1555 return false; 1556 } 1557 } 1558 return true; 1559 } 1560 1561 /** 1562 * Adds the {@code MasterQuotasObserver} to the list of configured Master observers to 1563 * automatically remove quotas for a table when that table is deleted. 1564 */ 1565 @InterfaceAudience.Private 1566 public void updateConfigurationForQuotasObserver(Configuration conf) { 1567 // We're configured to not delete quotas on table deletion, so we don't need to add the obs. 1568 if ( 1569 !conf.getBoolean(MasterQuotasObserver.REMOVE_QUOTA_ON_TABLE_DELETE, 1570 MasterQuotasObserver.REMOVE_QUOTA_ON_TABLE_DELETE_DEFAULT) 1571 ) { 1572 return; 1573 } 1574 String[] masterCoprocs = conf.getStrings(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY); 1575 final int length = null == masterCoprocs ? 0 : masterCoprocs.length; 1576 String[] updatedCoprocs = new String[length + 1]; 1577 if (length > 0) { 1578 System.arraycopy(masterCoprocs, 0, updatedCoprocs, 0, masterCoprocs.length); 1579 } 1580 updatedCoprocs[length] = MasterQuotasObserver.class.getName(); 1581 conf.setStrings(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, updatedCoprocs); 1582 } 1583 1584 private void initMobCleaner() { 1585 this.mobFileCleanerChore = new MobFileCleanerChore(this); 1586 configurationManager.registerObserver(this.mobFileCleanerChore); 1587 getChoreService().scheduleChore(mobFileCleanerChore); 1588 this.mobFileCompactionChore = new MobFileCompactionChore(this); 1589 getChoreService().scheduleChore(mobFileCompactionChore); 1590 } 1591 1592 /** 1593 * <p> 1594 * Create a {@link ServerManager} instance. 1595 * </p> 1596 * <p> 1597 * Will be overridden in tests. 1598 * </p> 1599 */ 1600 @InterfaceAudience.Private 1601 protected ServerManager createServerManager(MasterServices master, RegionServerList storage) 1602 throws IOException { 1603 // We put this out here in a method so can do a Mockito.spy and stub it out 1604 // w/ a mocked up ServerManager. 1605 setupClusterConnection(); 1606 return new ServerManager(master, storage); 1607 } 1608 1609 private void waitForRegionServers(final MonitoredTask status) 1610 throws IOException, InterruptedException { 1611 this.serverManager.waitForRegionServers(status); 1612 } 1613 1614 // Will be overridden in tests 1615 @InterfaceAudience.Private 1616 protected void initClusterSchemaService() throws IOException, InterruptedException { 1617 this.clusterSchemaService = new ClusterSchemaServiceImpl(this); 1618 this.clusterSchemaService.startAsync(); 1619 try { 1620 this.clusterSchemaService 1621 .awaitRunning(getConfiguration().getInt(HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS, 1622 DEFAULT_HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS), TimeUnit.SECONDS); 1623 } catch (TimeoutException toe) { 1624 throw new IOException("Timedout starting ClusterSchemaService", toe); 1625 } 1626 } 1627 1628 private void initQuotaManager() throws IOException { 1629 MasterQuotaManager quotaManager = new MasterQuotaManager(this); 1630 quotaManager.start(); 1631 this.quotaManager = quotaManager; 1632 } 1633 1634 private SpaceQuotaSnapshotNotifier createQuotaSnapshotNotifier() { 1635 SpaceQuotaSnapshotNotifier notifier = 1636 SpaceQuotaSnapshotNotifierFactory.getInstance().create(getConfiguration()); 1637 return notifier; 1638 } 1639 1640 public boolean isCatalogJanitorEnabled() { 1641 return catalogJanitorChore != null ? catalogJanitorChore.getEnabled() : false; 1642 } 1643 1644 boolean isCleanerChoreEnabled() { 1645 boolean hfileCleanerFlag = true, logCleanerFlag = true; 1646 1647 if (getHFileCleaner() != null) { 1648 hfileCleanerFlag = getHFileCleaner().getEnabled(); 1649 } 1650 1651 if (logCleaner != null) { 1652 logCleanerFlag = logCleaner.getEnabled(); 1653 } 1654 1655 return (hfileCleanerFlag && logCleanerFlag); 1656 } 1657 1658 @Override 1659 public ServerManager getServerManager() { 1660 return this.serverManager; 1661 } 1662 1663 @Override 1664 public MasterFileSystem getMasterFileSystem() { 1665 return this.fileSystemManager; 1666 } 1667 1668 @Override 1669 public MasterWalManager getMasterWalManager() { 1670 return this.walManager; 1671 } 1672 1673 @Override 1674 public boolean rotateSystemKeyIfChanged() throws IOException { 1675 // STUB - Feature not yet implemented 1676 return false; 1677 } 1678 1679 @Override 1680 public SplitWALManager getSplitWALManager() { 1681 return splitWALManager; 1682 } 1683 1684 @Override 1685 public TableStateManager getTableStateManager() { 1686 return tableStateManager; 1687 } 1688 1689 /* 1690 * Start up all services. If any of these threads gets an unhandled exception then they just die 1691 * with a logged message. This should be fine because in general, we do not expect the master to 1692 * get such unhandled exceptions as OOMEs; it should be lightly loaded. See what HRegionServer 1693 * does if need to install an unexpected exception handler. 1694 */ 1695 private void startServiceThreads() throws IOException { 1696 // Start the executor service pools 1697 final int masterOpenRegionPoolSize = conf.getInt(HConstants.MASTER_OPEN_REGION_THREADS, 1698 HConstants.MASTER_OPEN_REGION_THREADS_DEFAULT); 1699 executorService.startExecutorService(executorService.new ExecutorConfig() 1700 .setExecutorType(ExecutorType.MASTER_OPEN_REGION).setCorePoolSize(masterOpenRegionPoolSize)); 1701 final int masterCloseRegionPoolSize = conf.getInt(HConstants.MASTER_CLOSE_REGION_THREADS, 1702 HConstants.MASTER_CLOSE_REGION_THREADS_DEFAULT); 1703 executorService.startExecutorService( 1704 executorService.new ExecutorConfig().setExecutorType(ExecutorType.MASTER_CLOSE_REGION) 1705 .setCorePoolSize(masterCloseRegionPoolSize)); 1706 final int masterServerOpThreads = conf.getInt(HConstants.MASTER_SERVER_OPERATIONS_THREADS, 1707 HConstants.MASTER_SERVER_OPERATIONS_THREADS_DEFAULT); 1708 executorService.startExecutorService( 1709 executorService.new ExecutorConfig().setExecutorType(ExecutorType.MASTER_SERVER_OPERATIONS) 1710 .setCorePoolSize(masterServerOpThreads)); 1711 final int masterServerMetaOpsThreads = 1712 conf.getInt(HConstants.MASTER_META_SERVER_OPERATIONS_THREADS, 1713 HConstants.MASTER_META_SERVER_OPERATIONS_THREADS_DEFAULT); 1714 executorService.startExecutorService(executorService.new ExecutorConfig() 1715 .setExecutorType(ExecutorType.MASTER_META_SERVER_OPERATIONS) 1716 .setCorePoolSize(masterServerMetaOpsThreads)); 1717 final int masterLogReplayThreads = conf.getInt(HConstants.MASTER_LOG_REPLAY_OPS_THREADS, 1718 HConstants.MASTER_LOG_REPLAY_OPS_THREADS_DEFAULT); 1719 executorService.startExecutorService(executorService.new ExecutorConfig() 1720 .setExecutorType(ExecutorType.M_LOG_REPLAY_OPS).setCorePoolSize(masterLogReplayThreads)); 1721 final int masterSnapshotThreads = conf.getInt(SnapshotManager.SNAPSHOT_POOL_THREADS_KEY, 1722 SnapshotManager.SNAPSHOT_POOL_THREADS_DEFAULT); 1723 executorService.startExecutorService( 1724 executorService.new ExecutorConfig().setExecutorType(ExecutorType.MASTER_SNAPSHOT_OPERATIONS) 1725 .setCorePoolSize(masterSnapshotThreads).setAllowCoreThreadTimeout(true)); 1726 final int masterMergeDispatchThreads = conf.getInt(HConstants.MASTER_MERGE_DISPATCH_THREADS, 1727 HConstants.MASTER_MERGE_DISPATCH_THREADS_DEFAULT); 1728 executorService.startExecutorService( 1729 executorService.new ExecutorConfig().setExecutorType(ExecutorType.MASTER_MERGE_OPERATIONS) 1730 .setCorePoolSize(masterMergeDispatchThreads).setAllowCoreThreadTimeout(true)); 1731 1732 // We depend on there being only one instance of this executor running 1733 // at a time. To do concurrency, would need fencing of enable/disable of 1734 // tables. 1735 // Any time changing this maxThreads to > 1, pls see the comment at 1736 // AccessController#postCompletedCreateTableAction 1737 executorService.startExecutorService(executorService.new ExecutorConfig() 1738 .setExecutorType(ExecutorType.MASTER_TABLE_OPERATIONS).setCorePoolSize(1)); 1739 startProcedureExecutor(); 1740 1741 // Create log cleaner thread pool 1742 logCleanerPool = DirScanPool.getLogCleanerScanPool(conf); 1743 Map<String, Object> params = new HashMap<>(); 1744 params.put(MASTER, this); 1745 // Start log cleaner thread 1746 int cleanerInterval = 1747 conf.getInt(HBASE_MASTER_CLEANER_INTERVAL, DEFAULT_HBASE_MASTER_CLEANER_INTERVAL); 1748 this.logCleaner = 1749 new LogCleaner(cleanerInterval, this, conf, getMasterWalManager().getFileSystem(), 1750 getMasterWalManager().getOldLogDir(), logCleanerPool, params); 1751 getChoreService().scheduleChore(logCleaner); 1752 1753 Path archiveDir = HFileArchiveUtil.getArchivePath(conf); 1754 1755 // Create custom archive hfile cleaners 1756 String[] paths = conf.getStrings(HFileCleaner.HFILE_CLEANER_CUSTOM_PATHS); 1757 // todo: handle the overlap issues for the custom paths 1758 1759 if (paths != null && paths.length > 0) { 1760 if (conf.getStrings(HFileCleaner.HFILE_CLEANER_CUSTOM_PATHS_PLUGINS) == null) { 1761 Set<String> cleanerClasses = new HashSet<>(); 1762 String[] cleaners = conf.getStrings(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS); 1763 if (cleaners != null) { 1764 Collections.addAll(cleanerClasses, cleaners); 1765 } 1766 conf.setStrings(HFileCleaner.HFILE_CLEANER_CUSTOM_PATHS_PLUGINS, 1767 cleanerClasses.toArray(new String[cleanerClasses.size()])); 1768 LOG.info("Archive custom cleaner paths: {}, plugins: {}", Arrays.asList(paths), 1769 cleanerClasses); 1770 } 1771 // share the hfile cleaner pool in custom paths 1772 sharedHFileCleanerPool = DirScanPool.getHFileCleanerScanPool(conf.get(CUSTOM_POOL_SIZE, "6")); 1773 for (int i = 0; i < paths.length; i++) { 1774 Path path = new Path(paths[i].trim()); 1775 HFileCleaner cleaner = 1776 new HFileCleaner("ArchiveCustomHFileCleaner-" + path.getName(), cleanerInterval, this, 1777 conf, getMasterFileSystem().getFileSystem(), new Path(archiveDir, path), 1778 HFileCleaner.HFILE_CLEANER_CUSTOM_PATHS_PLUGINS, sharedHFileCleanerPool, params, null); 1779 hfileCleaners.add(cleaner); 1780 hfileCleanerPaths.add(path); 1781 } 1782 } 1783 1784 // Create the whole archive dir cleaner thread pool 1785 exclusiveHFileCleanerPool = DirScanPool.getHFileCleanerScanPool(conf); 1786 hfileCleaners.add(0, 1787 new HFileCleaner(cleanerInterval, this, conf, getMasterFileSystem().getFileSystem(), 1788 archiveDir, exclusiveHFileCleanerPool, params, hfileCleanerPaths)); 1789 hfileCleanerPaths.add(0, archiveDir); 1790 // Schedule all the hfile cleaners 1791 for (HFileCleaner hFileCleaner : hfileCleaners) { 1792 getChoreService().scheduleChore(hFileCleaner); 1793 } 1794 1795 // Regions Reopen based on very high storeFileRefCount is considered enabled 1796 // only if hbase.regions.recovery.store.file.ref.count has value > 0 1797 final int maxStoreFileRefCount = conf.getInt(HConstants.STORE_FILE_REF_COUNT_THRESHOLD, 1798 HConstants.DEFAULT_STORE_FILE_REF_COUNT_THRESHOLD); 1799 if (maxStoreFileRefCount > 0) { 1800 this.regionsRecoveryChore = new RegionsRecoveryChore(this, conf, this); 1801 getChoreService().scheduleChore(this.regionsRecoveryChore); 1802 } else { 1803 LOG.info( 1804 "Reopening regions with very high storeFileRefCount is disabled. " 1805 + "Provide threshold value > 0 for {} to enable it.", 1806 HConstants.STORE_FILE_REF_COUNT_THRESHOLD); 1807 } 1808 1809 this.regionsRecoveryConfigManager = new RegionsRecoveryConfigManager(this); 1810 1811 replicationBarrierCleaner = 1812 new ReplicationBarrierCleaner(conf, this, getConnection(), replicationPeerManager); 1813 getChoreService().scheduleChore(replicationBarrierCleaner); 1814 1815 final boolean isSnapshotChoreEnabled = this.snapshotCleanupStateStore.get(); 1816 this.snapshotCleanerChore = new SnapshotCleanerChore(this, conf, getSnapshotManager()); 1817 if (isSnapshotChoreEnabled) { 1818 getChoreService().scheduleChore(this.snapshotCleanerChore); 1819 } else { 1820 if (LOG.isTraceEnabled()) { 1821 LOG.trace("Snapshot Cleaner Chore is disabled. Not starting up the chore.."); 1822 } 1823 } 1824 serviceStarted = true; 1825 if (LOG.isTraceEnabled()) { 1826 LOG.trace("Started service threads"); 1827 } 1828 } 1829 1830 protected void stopServiceThreads() { 1831 if (masterJettyServer != null) { 1832 LOG.info("Stopping master jetty server"); 1833 try { 1834 masterJettyServer.stop(); 1835 } catch (Exception e) { 1836 LOG.error("Failed to stop master jetty server", e); 1837 } 1838 } 1839 stopChoreService(); 1840 stopExecutorService(); 1841 if (exclusiveHFileCleanerPool != null) { 1842 exclusiveHFileCleanerPool.shutdownNow(); 1843 exclusiveHFileCleanerPool = null; 1844 } 1845 if (logCleanerPool != null) { 1846 logCleanerPool.shutdownNow(); 1847 logCleanerPool = null; 1848 } 1849 if (sharedHFileCleanerPool != null) { 1850 sharedHFileCleanerPool.shutdownNow(); 1851 sharedHFileCleanerPool = null; 1852 } 1853 if (maintenanceRegionServer != null) { 1854 maintenanceRegionServer.getRegionServer().stop(HBASE_MASTER_CLEANER_INTERVAL); 1855 } 1856 1857 LOG.debug("Stopping service threads"); 1858 // stop procedure executor prior to other services such as server manager and assignment 1859 // manager, as these services are important for some running procedures. See HBASE-24117 for 1860 // example. 1861 stopProcedureExecutor(); 1862 1863 if (regionNormalizerManager != null) { 1864 regionNormalizerManager.stop(); 1865 } 1866 if (this.quotaManager != null) { 1867 this.quotaManager.stop(); 1868 } 1869 1870 if (this.activeMasterManager != null) { 1871 this.activeMasterManager.stop(); 1872 } 1873 if (this.serverManager != null) { 1874 this.serverManager.stop(); 1875 } 1876 if (this.assignmentManager != null) { 1877 this.assignmentManager.stop(); 1878 } 1879 1880 if (masterRegion != null) { 1881 masterRegion.close(isAborted()); 1882 } 1883 if (this.walManager != null) { 1884 this.walManager.stop(); 1885 } 1886 if (this.fileSystemManager != null) { 1887 this.fileSystemManager.stop(); 1888 } 1889 if (this.mpmHost != null) { 1890 this.mpmHost.stop("server shutting down."); 1891 } 1892 if (this.regionServerTracker != null) { 1893 this.regionServerTracker.stop(); 1894 } 1895 } 1896 1897 private void createProcedureExecutor() throws IOException { 1898 final String procedureDispatcherClassName = 1899 conf.get(HBASE_MASTER_RSPROC_DISPATCHER_CLASS, DEFAULT_HBASE_MASTER_RSPROC_DISPATCHER_CLASS); 1900 final RSProcedureDispatcher procedureDispatcher = ReflectionUtils.instantiateWithCustomCtor( 1901 procedureDispatcherClassName, new Class[] { MasterServices.class }, new Object[] { this }); 1902 final MasterProcedureEnv procEnv = new MasterProcedureEnv(this, procedureDispatcher); 1903 procedureStore = new RegionProcedureStore(this, masterRegion, 1904 new MasterProcedureEnv.FsUtilsLeaseRecovery(this)); 1905 procedureStore.registerListener(new ProcedureStoreListener() { 1906 1907 @Override 1908 public void abortProcess() { 1909 abort("The Procedure Store lost the lease", null); 1910 } 1911 }); 1912 MasterProcedureScheduler procedureScheduler = procEnv.getProcedureScheduler(); 1913 procedureExecutor = new ProcedureExecutor<>(conf, procEnv, procedureStore, procedureScheduler); 1914 configurationManager.registerObserver(procEnv); 1915 1916 int cpus = Runtime.getRuntime().availableProcessors(); 1917 int defaultNumThreads = Math.max((cpus > 0 ? cpus / 4 : 0), 1918 MasterProcedureConstants.DEFAULT_MIN_MASTER_PROCEDURE_THREADS); 1919 int numThreads = 1920 conf.getInt(MasterProcedureConstants.MASTER_PROCEDURE_THREADS, defaultNumThreads); 1921 if (numThreads <= 0) { 1922 LOG.warn("{} is set to {}, which is invalid, using default value {} instead", 1923 MasterProcedureConstants.MASTER_PROCEDURE_THREADS, numThreads, defaultNumThreads); 1924 numThreads = defaultNumThreads; 1925 } 1926 final boolean abortOnCorruption = 1927 conf.getBoolean(MasterProcedureConstants.EXECUTOR_ABORT_ON_CORRUPTION, 1928 MasterProcedureConstants.DEFAULT_EXECUTOR_ABORT_ON_CORRUPTION); 1929 procedureStore.start(numThreads); 1930 // Just initialize it but do not start the workers, we will start the workers later by calling 1931 // startProcedureExecutor. See the javadoc for finishActiveMasterInitialization for more 1932 // details. 1933 procedureExecutor.init(numThreads, abortOnCorruption); 1934 if (!procEnv.getRemoteDispatcher().start()) { 1935 throw new HBaseIOException("Failed start of remote dispatcher"); 1936 } 1937 } 1938 1939 // will be override in UT 1940 protected void startProcedureExecutor() throws IOException { 1941 procedureExecutor.startWorkers(); 1942 } 1943 1944 /** 1945 * Turn on/off Snapshot Cleanup Chore 1946 * @param on indicates whether Snapshot Cleanup Chore is to be run 1947 */ 1948 void switchSnapshotCleanup(final boolean on, final boolean synchronous) throws IOException { 1949 if (synchronous) { 1950 synchronized (this.snapshotCleanerChore) { 1951 switchSnapshotCleanup(on); 1952 } 1953 } else { 1954 switchSnapshotCleanup(on); 1955 } 1956 } 1957 1958 private void switchSnapshotCleanup(final boolean on) throws IOException { 1959 snapshotCleanupStateStore.set(on); 1960 if (on) { 1961 getChoreService().scheduleChore(this.snapshotCleanerChore); 1962 } else { 1963 this.snapshotCleanerChore.cancel(); 1964 } 1965 } 1966 1967 private void stopProcedureExecutor() { 1968 if (procedureExecutor != null) { 1969 configurationManager.deregisterObserver(procedureExecutor.getEnvironment()); 1970 procedureExecutor.getEnvironment().getRemoteDispatcher().stop(); 1971 procedureExecutor.stop(); 1972 procedureExecutor.join(); 1973 procedureExecutor = null; 1974 } 1975 1976 if (procedureStore != null) { 1977 procedureStore.stop(isAborted()); 1978 procedureStore = null; 1979 } 1980 } 1981 1982 protected void stopChores() { 1983 shutdownChore(mobFileCleanerChore); 1984 shutdownChore(mobFileCompactionChore); 1985 shutdownChore(balancerChore); 1986 if (regionNormalizerManager != null) { 1987 shutdownChore(regionNormalizerManager.getRegionNormalizerChore()); 1988 } 1989 shutdownChore(clusterStatusChore); 1990 shutdownChore(catalogJanitorChore); 1991 shutdownChore(clusterStatusPublisherChore); 1992 shutdownChore(snapshotQuotaChore); 1993 shutdownChore(logCleaner); 1994 if (hfileCleaners != null) { 1995 for (ScheduledChore chore : hfileCleaners) { 1996 chore.shutdown(); 1997 } 1998 hfileCleaners = null; 1999 } 2000 shutdownChore(replicationBarrierCleaner); 2001 shutdownChore(snapshotCleanerChore); 2002 shutdownChore(hbckChore); 2003 shutdownChore(regionsRecoveryChore); 2004 shutdownChore(rollingUpgradeChore); 2005 shutdownChore(oldWALsDirSizeChore); 2006 } 2007 2008 /** Returns Get remote side's InetAddress */ 2009 InetAddress getRemoteInetAddress(final int port, final long serverStartCode) 2010 throws UnknownHostException { 2011 // Do it out here in its own little method so can fake an address when 2012 // mocking up in tests. 2013 InetAddress ia = RpcServer.getRemoteIp(); 2014 2015 // The call could be from the local regionserver, 2016 // in which case, there is no remote address. 2017 if (ia == null && serverStartCode == startcode) { 2018 InetSocketAddress isa = rpcServices.getSocketAddress(); 2019 if (isa != null && isa.getPort() == port) { 2020 ia = isa.getAddress(); 2021 } 2022 } 2023 return ia; 2024 } 2025 2026 /** Returns Maximum time we should run balancer for */ 2027 private int getMaxBalancingTime() { 2028 // if max balancing time isn't set, defaulting it to period time 2029 int maxBalancingTime = 2030 getConfiguration().getInt(HConstants.HBASE_BALANCER_MAX_BALANCING, getConfiguration() 2031 .getInt(HConstants.HBASE_BALANCER_PERIOD, HConstants.DEFAULT_HBASE_BALANCER_PERIOD)); 2032 return maxBalancingTime; 2033 } 2034 2035 /** Returns Maximum number of regions in transition */ 2036 private int getMaxRegionsInTransition() { 2037 int numRegions = this.assignmentManager.getRegionStates().getRegionAssignments().size(); 2038 return Math.max((int) Math.floor(numRegions * this.maxRitPercent), 1); 2039 } 2040 2041 /** 2042 * It first sleep to the next balance plan start time. Meanwhile, throttling by the max number 2043 * regions in transition to protect availability. 2044 * @param nextBalanceStartTime The next balance plan start time 2045 * @param maxRegionsInTransition max number of regions in transition 2046 * @param cutoffTime when to exit balancer 2047 */ 2048 private void balanceThrottling(long nextBalanceStartTime, int maxRegionsInTransition, 2049 long cutoffTime) { 2050 boolean interrupted = false; 2051 2052 // Sleep to next balance plan start time 2053 // But if there are zero regions in transition, it can skip sleep to speed up. 2054 while ( 2055 !interrupted && EnvironmentEdgeManager.currentTime() < nextBalanceStartTime 2056 && this.assignmentManager.getRegionTransitScheduledCount() > 0 2057 ) { 2058 try { 2059 Thread.sleep(100); 2060 } catch (InterruptedException ie) { 2061 interrupted = true; 2062 } 2063 } 2064 2065 // Throttling by max number regions in transition 2066 while ( 2067 !interrupted && maxRegionsInTransition > 0 2068 && this.assignmentManager.getRegionTransitScheduledCount() >= maxRegionsInTransition 2069 && EnvironmentEdgeManager.currentTime() <= cutoffTime 2070 ) { 2071 try { 2072 // sleep if the number of regions in transition exceeds the limit 2073 Thread.sleep(100); 2074 } catch (InterruptedException ie) { 2075 interrupted = true; 2076 } 2077 } 2078 2079 if (interrupted) Thread.currentThread().interrupt(); 2080 } 2081 2082 public BalanceResponse balance() throws IOException { 2083 return balance(BalanceRequest.defaultInstance()); 2084 } 2085 2086 /** 2087 * Trigger a normal balance, see {@link HMaster#balance()} . If the balance is not executed this 2088 * time, the metrics related to the balance will be updated. When balance is running, related 2089 * metrics will be updated at the same time. But if some checking logic failed and cause the 2090 * balancer exit early, we lost the chance to update balancer metrics. This will lead to user 2091 * missing the latest balancer info. 2092 */ 2093 public BalanceResponse balanceOrUpdateMetrics() throws IOException { 2094 synchronized (this.balancer) { 2095 BalanceResponse response = balance(); 2096 if (!response.isBalancerRan()) { 2097 Map<TableName, Map<ServerName, List<RegionInfo>>> assignments = 2098 this.assignmentManager.getRegionStates().getAssignmentsForBalancer(this.tableStateManager, 2099 this.serverManager.getOnlineServersList()); 2100 for (Map<ServerName, List<RegionInfo>> serverMap : assignments.values()) { 2101 serverMap.keySet().removeAll(this.serverManager.getDrainingServersList()); 2102 } 2103 this.balancer.updateBalancerLoadInfo(assignments); 2104 } 2105 return response; 2106 } 2107 } 2108 2109 /** 2110 * Checks master state before initiating action over region topology. 2111 * @param action the name of the action under consideration, for logging. 2112 * @return {@code true} when the caller should exit early, {@code false} otherwise. 2113 */ 2114 @Override 2115 public boolean skipRegionManagementAction(final String action) { 2116 // Note: this method could be `default` on MasterServices if but for logging. 2117 if (!isInitialized()) { 2118 LOG.debug("Master has not been initialized, don't run {}.", action); 2119 return true; 2120 } 2121 if (this.getServerManager().isClusterShutdown()) { 2122 LOG.info("Cluster is shutting down, don't run {}.", action); 2123 return true; 2124 } 2125 if (isInMaintenanceMode()) { 2126 LOG.info("Master is in maintenance mode, don't run {}.", action); 2127 return true; 2128 } 2129 return false; 2130 } 2131 2132 public BalanceResponse balance(BalanceRequest request) throws IOException { 2133 checkInitialized(); 2134 2135 BalanceResponse.Builder responseBuilder = BalanceResponse.newBuilder(); 2136 2137 if (loadBalancerStateStore == null || !(loadBalancerStateStore.get() || request.isDryRun())) { 2138 return responseBuilder.build(); 2139 } 2140 2141 if (skipRegionManagementAction("balancer")) { 2142 return responseBuilder.build(); 2143 } 2144 2145 synchronized (this.balancer) { 2146 try { 2147 this.balancer.onBalancingStart(); 2148 // Only allow one balance run at at time. 2149 if (this.assignmentManager.getRegionTransitScheduledCount() > 0) { 2150 List<RegionStateNode> regionsInTransition = assignmentManager.getRegionsInTransition(); 2151 // if hbase:meta region is in transition, result of assignment cannot be recorded 2152 // ignore the force flag in that case 2153 boolean metaInTransition = assignmentManager.isMetaRegionInTransition(); 2154 List<RegionStateNode> toPrint = regionsInTransition; 2155 int max = 5; 2156 boolean truncated = false; 2157 if (regionsInTransition.size() > max) { 2158 toPrint = regionsInTransition.subList(0, max); 2159 truncated = true; 2160 } 2161 2162 if (!request.isIgnoreRegionsInTransition() || metaInTransition) { 2163 LOG.info("Not running balancer (ignoreRIT=false" + ", metaRIT=" + metaInTransition 2164 + ") because " + assignmentManager.getRegionTransitScheduledCount() 2165 + " region(s) are scheduled to transit " + toPrint 2166 + (truncated ? "(truncated list)" : "")); 2167 return responseBuilder.build(); 2168 } 2169 } 2170 if (this.serverManager.areDeadServersInProgress()) { 2171 LOG.info("Not running balancer because processing dead regionserver(s): " 2172 + this.serverManager.getDeadServers()); 2173 return responseBuilder.build(); 2174 } 2175 2176 if (this.cpHost != null) { 2177 try { 2178 if (this.cpHost.preBalance(request)) { 2179 LOG.debug("Coprocessor bypassing balancer request"); 2180 return responseBuilder.build(); 2181 } 2182 } catch (IOException ioe) { 2183 LOG.error("Error invoking master coprocessor preBalance()", ioe); 2184 return responseBuilder.build(); 2185 } 2186 } 2187 2188 Map<TableName, Map<ServerName, List<RegionInfo>>> assignments = 2189 this.assignmentManager.getRegionStates().getAssignmentsForBalancer(tableStateManager, 2190 this.serverManager.getOnlineServersList()); 2191 for (Map<ServerName, List<RegionInfo>> serverMap : assignments.values()) { 2192 serverMap.keySet().removeAll(this.serverManager.getDrainingServersList()); 2193 } 2194 2195 // Give the balancer the current cluster state. 2196 this.balancer.updateClusterMetrics(getClusterMetricsWithoutCoprocessor()); 2197 2198 List<RegionPlan> plans = this.balancer.balanceCluster(assignments); 2199 2200 responseBuilder.setBalancerRan(true).setMovesCalculated(plans == null ? 0 : plans.size()); 2201 2202 if (skipRegionManagementAction("balancer")) { 2203 // make one last check that the cluster isn't shutting down before proceeding. 2204 return responseBuilder.build(); 2205 } 2206 2207 // For dry run we don't actually want to execute the moves, but we do want 2208 // to execute the coprocessor below 2209 List<RegionPlan> sucRPs = 2210 request.isDryRun() ? Collections.emptyList() : executeRegionPlansWithThrottling(plans); 2211 2212 if (this.cpHost != null) { 2213 try { 2214 this.cpHost.postBalance(request, sucRPs); 2215 } catch (IOException ioe) { 2216 // balancing already succeeded so don't change the result 2217 LOG.error("Error invoking master coprocessor postBalance()", ioe); 2218 } 2219 } 2220 2221 responseBuilder.setMovesExecuted(sucRPs.size()); 2222 } finally { 2223 this.balancer.onBalancingComplete(); 2224 } 2225 } 2226 2227 // If LoadBalancer did not generate any plans, it means the cluster is already balanced. 2228 // Return true indicating a success. 2229 return responseBuilder.build(); 2230 } 2231 2232 /** 2233 * Execute region plans with throttling 2234 * @param plans to execute 2235 * @return succeeded plans 2236 */ 2237 public List<RegionPlan> executeRegionPlansWithThrottling(List<RegionPlan> plans) { 2238 List<RegionPlan> successRegionPlans = new ArrayList<>(); 2239 int maxRegionsInTransition = getMaxRegionsInTransition(); 2240 long balanceStartTime = EnvironmentEdgeManager.currentTime(); 2241 long cutoffTime = balanceStartTime + this.maxBalancingTime; 2242 int rpCount = 0; // number of RegionPlans balanced so far 2243 if (plans != null && !plans.isEmpty()) { 2244 int balanceInterval = this.maxBalancingTime / plans.size(); 2245 LOG.info( 2246 "Balancer plans size is " + plans.size() + ", the balance interval is " + balanceInterval 2247 + " ms, and the max number regions in transition is " + maxRegionsInTransition); 2248 2249 for (RegionPlan plan : plans) { 2250 LOG.info("balance " + plan); 2251 // TODO: bulk assign 2252 try { 2253 this.assignmentManager.balance(plan); 2254 this.balancer.updateClusterMetrics(getClusterMetricsWithoutCoprocessor()); 2255 this.balancer.throttle(plan); 2256 } catch (HBaseIOException hioe) { 2257 // should ignore failed plans here, avoiding the whole balance plans be aborted 2258 // later calls of balance() can fetch up the failed and skipped plans 2259 LOG.warn("Failed balance plan {}, skipping...", plan, hioe); 2260 } catch (Exception e) { 2261 LOG.warn("Failed throttling assigning a new plan.", e); 2262 } 2263 // rpCount records balance plans processed, does not care if a plan succeeds 2264 rpCount++; 2265 successRegionPlans.add(plan); 2266 2267 if (this.maxBalancingTime > 0) { 2268 balanceThrottling(balanceStartTime + rpCount * balanceInterval, maxRegionsInTransition, 2269 cutoffTime); 2270 } 2271 2272 // if performing next balance exceeds cutoff time, exit the loop 2273 if ( 2274 this.maxBalancingTime > 0 && rpCount < plans.size() 2275 && EnvironmentEdgeManager.currentTime() > cutoffTime 2276 ) { 2277 // TODO: After balance, there should not be a cutoff time (keeping it as 2278 // a security net for now) 2279 LOG.debug( 2280 "No more balancing till next balance run; maxBalanceTime=" + this.maxBalancingTime); 2281 break; 2282 } 2283 } 2284 } 2285 LOG.debug("Balancer is going into sleep until next period in {}ms", getConfiguration() 2286 .getInt(HConstants.HBASE_BALANCER_PERIOD, HConstants.DEFAULT_HBASE_BALANCER_PERIOD)); 2287 return successRegionPlans; 2288 } 2289 2290 @Override 2291 public RegionNormalizerManager getRegionNormalizerManager() { 2292 return regionNormalizerManager; 2293 } 2294 2295 @Override 2296 public boolean normalizeRegions(final NormalizeTableFilterParams ntfp, 2297 final boolean isHighPriority) throws IOException { 2298 if (regionNormalizerManager == null || !regionNormalizerManager.isNormalizerOn()) { 2299 LOG.debug("Region normalization is disabled, don't run region normalizer."); 2300 return false; 2301 } 2302 if (skipRegionManagementAction("region normalizer")) { 2303 return false; 2304 } 2305 if (assignmentManager.getRegionTransitScheduledCount() > 0) { 2306 return false; 2307 } 2308 2309 final Set<TableName> matchingTables = getTableDescriptors(new LinkedList<>(), 2310 ntfp.getNamespace(), ntfp.getRegex(), ntfp.getTableNames(), false).stream() 2311 .map(TableDescriptor::getTableName).collect(Collectors.toSet()); 2312 final Set<TableName> allEnabledTables = 2313 tableStateManager.getTablesInStates(TableState.State.ENABLED); 2314 final List<TableName> targetTables = 2315 new ArrayList<>(Sets.intersection(matchingTables, allEnabledTables)); 2316 Collections.shuffle(targetTables); 2317 return regionNormalizerManager.normalizeRegions(targetTables, isHighPriority); 2318 } 2319 2320 /** Returns Client info for use as prefix on an audit log string; who did an action */ 2321 @Override 2322 public String getClientIdAuditPrefix() { 2323 return "Client=" + RpcServer.getRequestUserName().orElse(null) + "/" 2324 + RpcServer.getRemoteAddress().orElse(null); 2325 } 2326 2327 /** 2328 * Switch for the background CatalogJanitor thread. Used for testing. The thread will continue to 2329 * run. It will just be a noop if disabled. 2330 * @param b If false, the catalog janitor won't do anything. 2331 */ 2332 public void setCatalogJanitorEnabled(final boolean b) { 2333 this.catalogJanitorChore.setEnabled(b); 2334 } 2335 2336 @Override 2337 public long mergeRegions(final RegionInfo[] regionsToMerge, final boolean forcible, final long ng, 2338 final long nonce) throws IOException { 2339 checkInitialized(); 2340 2341 final String regionNamesToLog = RegionInfo.getShortNameToLog(regionsToMerge); 2342 2343 if (!isSplitOrMergeEnabled(MasterSwitchType.MERGE)) { 2344 LOG.warn("Merge switch is off! skip merge of " + regionNamesToLog); 2345 throw new DoNotRetryIOException( 2346 "Merge of " + regionNamesToLog + " failed because merge switch is off"); 2347 } 2348 2349 if (!getTableDescriptors().get(regionsToMerge[0].getTable()).isMergeEnabled()) { 2350 LOG.warn("Merge is disabled for the table! Skipping merge of {}", regionNamesToLog); 2351 throw new DoNotRetryIOException( 2352 "Merge of " + regionNamesToLog + " failed as region merge is disabled for the table"); 2353 } 2354 2355 return MasterProcedureUtil.submitProcedure(new NonceProcedureRunnable(this, ng, nonce) { 2356 @Override 2357 protected void run() throws IOException { 2358 getMaster().getMasterCoprocessorHost().preMergeRegions(regionsToMerge); 2359 String aid = getClientIdAuditPrefix(); 2360 LOG.info("{} merge regions {}", aid, regionNamesToLog); 2361 submitProcedure(new MergeTableRegionsProcedure(procedureExecutor.getEnvironment(), 2362 regionsToMerge, forcible)); 2363 getMaster().getMasterCoprocessorHost().postMergeRegions(regionsToMerge); 2364 } 2365 2366 @Override 2367 protected String getDescription() { 2368 return "MergeTableProcedure"; 2369 } 2370 }); 2371 } 2372 2373 @Override 2374 public long splitRegion(final RegionInfo regionInfo, final byte[] splitRow, final long nonceGroup, 2375 final long nonce) throws IOException { 2376 checkInitialized(); 2377 2378 if (!isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { 2379 LOG.warn("Split switch is off! skip split of " + regionInfo); 2380 throw new DoNotRetryIOException( 2381 "Split region " + regionInfo.getRegionNameAsString() + " failed due to split switch off"); 2382 } 2383 2384 if (!getTableDescriptors().get(regionInfo.getTable()).isSplitEnabled()) { 2385 LOG.warn("Split is disabled for the table! Skipping split of {}", regionInfo); 2386 throw new DoNotRetryIOException("Split region " + regionInfo.getRegionNameAsString() 2387 + " failed as region split is disabled for the table"); 2388 } 2389 2390 return MasterProcedureUtil 2391 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2392 @Override 2393 protected void run() throws IOException { 2394 getMaster().getMasterCoprocessorHost().preSplitRegion(regionInfo.getTable(), splitRow); 2395 LOG.info(getClientIdAuditPrefix() + " split " + regionInfo.getRegionNameAsString()); 2396 2397 // Execute the operation asynchronously 2398 submitProcedure(getAssignmentManager().createSplitProcedure(regionInfo, splitRow)); 2399 } 2400 2401 @Override 2402 protected String getDescription() { 2403 return "SplitTableProcedure"; 2404 } 2405 }); 2406 } 2407 2408 private void warmUpRegion(ServerName server, RegionInfo region) { 2409 FutureUtils.addListener(asyncClusterConnection.getRegionServerAdmin(server) 2410 .warmupRegion(RequestConverter.buildWarmupRegionRequest(region)), (r, e) -> { 2411 if (e != null) { 2412 LOG.warn("Failed to warm up region {} on server {}", region, server, e); 2413 } 2414 }); 2415 } 2416 2417 // Public so can be accessed by tests. Blocks until move is done. 2418 // Replace with an async implementation from which you can get 2419 // a success/failure result. 2420 @InterfaceAudience.Private 2421 public void move(final byte[] encodedRegionName, byte[] destServerName) throws IOException { 2422 RegionState regionState = 2423 assignmentManager.getRegionStates().getRegionState(Bytes.toString(encodedRegionName)); 2424 2425 RegionInfo hri; 2426 if (regionState != null) { 2427 hri = regionState.getRegion(); 2428 } else { 2429 throw new UnknownRegionException(Bytes.toStringBinary(encodedRegionName)); 2430 } 2431 2432 ServerName dest; 2433 List<ServerName> exclude = hri.getTable().isSystemTable() 2434 ? assignmentManager.getExcludedServersForSystemTable() 2435 : new ArrayList<>(1); 2436 if ( 2437 destServerName != null && exclude.contains(ServerName.valueOf(Bytes.toString(destServerName))) 2438 ) { 2439 LOG.info(Bytes.toString(encodedRegionName) + " can not move to " 2440 + Bytes.toString(destServerName) + " because the server is in exclude list"); 2441 destServerName = null; 2442 } 2443 if (destServerName == null || destServerName.length == 0) { 2444 LOG.info("Passed destination servername is null/empty so " + "choosing a server at random"); 2445 exclude.add(regionState.getServerName()); 2446 final List<ServerName> destServers = this.serverManager.createDestinationServersList(exclude); 2447 dest = balancer.randomAssignment(hri, destServers); 2448 if (dest == null) { 2449 LOG.debug("Unable to determine a plan to assign " + hri); 2450 return; 2451 } 2452 } else { 2453 ServerName candidate = ServerName.valueOf(Bytes.toString(destServerName)); 2454 dest = balancer.randomAssignment(hri, Lists.newArrayList(candidate)); 2455 if (dest == null) { 2456 LOG.debug("Unable to determine a plan to assign " + hri); 2457 return; 2458 } 2459 // TODO: deal with table on master for rs group. 2460 if (dest.equals(serverName)) { 2461 // To avoid unnecessary region moving later by balancer. Don't put user 2462 // regions on master. 2463 LOG.debug("Skipping move of region " + hri.getRegionNameAsString() 2464 + " to avoid unnecessary region moving later by load balancer," 2465 + " because it should not be on master"); 2466 return; 2467 } 2468 } 2469 2470 if (dest.equals(regionState.getServerName())) { 2471 LOG.debug("Skipping move of region " + hri.getRegionNameAsString() 2472 + " because region already assigned to the same server " + dest + "."); 2473 return; 2474 } 2475 2476 // Now we can do the move 2477 RegionPlan rp = new RegionPlan(hri, regionState.getServerName(), dest); 2478 assert rp.getDestination() != null : rp.toString() + " " + dest; 2479 2480 try { 2481 checkInitialized(); 2482 if (this.cpHost != null) { 2483 this.cpHost.preMove(hri, rp.getSource(), rp.getDestination()); 2484 } 2485 2486 TransitRegionStateProcedure proc = 2487 this.assignmentManager.createMoveRegionProcedure(rp.getRegionInfo(), rp.getDestination()); 2488 if (conf.getBoolean(WARMUP_BEFORE_MOVE, DEFAULT_WARMUP_BEFORE_MOVE)) { 2489 // Warmup the region on the destination before initiating the move. 2490 // A region server could reject the close request because it either does not 2491 // have the specified region or the region is being split. 2492 LOG.info(getClientIdAuditPrefix() + " move " + rp + ", warming up region on " 2493 + rp.getDestination()); 2494 warmUpRegion(rp.getDestination(), hri); 2495 } 2496 LOG.info(getClientIdAuditPrefix() + " move " + rp + ", running balancer"); 2497 Future<byte[]> future = ProcedureSyncWait.submitProcedure(this.procedureExecutor, proc); 2498 try { 2499 // Is this going to work? Will we throw exception on error? 2500 // TODO: CompletableFuture rather than this stunted Future. 2501 future.get(); 2502 } catch (InterruptedException | ExecutionException e) { 2503 throw new HBaseIOException(e); 2504 } 2505 if (this.cpHost != null) { 2506 this.cpHost.postMove(hri, rp.getSource(), rp.getDestination()); 2507 } 2508 } catch (IOException ioe) { 2509 if (ioe instanceof HBaseIOException) { 2510 throw (HBaseIOException) ioe; 2511 } 2512 throw new HBaseIOException(ioe); 2513 } 2514 } 2515 2516 @Override 2517 public long createTable(final TableDescriptor tableDescriptor, final byte[][] splitKeys, 2518 final long nonceGroup, final long nonce) throws IOException { 2519 checkInitialized(); 2520 TableDescriptor desc = getMasterCoprocessorHost().preCreateTableRegionsInfos(tableDescriptor); 2521 if (desc == null) { 2522 throw new IOException("Creation for " + tableDescriptor + " is canceled by CP"); 2523 } 2524 String namespace = desc.getTableName().getNamespaceAsString(); 2525 this.clusterSchemaService.getNamespace(namespace); 2526 2527 RegionInfo[] newRegions = ModifyRegionUtils.createRegionInfos(desc, splitKeys); 2528 TableDescriptorChecker.sanityCheck(conf, desc); 2529 2530 return MasterProcedureUtil 2531 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2532 @Override 2533 protected void run() throws IOException { 2534 getMaster().getMasterCoprocessorHost().preCreateTable(desc, newRegions); 2535 2536 LOG.info(getClientIdAuditPrefix() + " create " + desc); 2537 2538 // TODO: We can handle/merge duplicate requests, and differentiate the case of 2539 // TableExistsException by saying if the schema is the same or not. 2540 // 2541 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2542 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2543 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 2544 submitProcedure( 2545 new CreateTableProcedure(procedureExecutor.getEnvironment(), desc, newRegions, latch)); 2546 latch.await(); 2547 2548 getMaster().getMasterCoprocessorHost().postCreateTable(desc, newRegions); 2549 } 2550 2551 @Override 2552 protected String getDescription() { 2553 return "CreateTableProcedure"; 2554 } 2555 }); 2556 } 2557 2558 @Override 2559 public long createSystemTable(final TableDescriptor tableDescriptor) throws IOException { 2560 return createSystemTable(tableDescriptor, false); 2561 } 2562 2563 private long createSystemTable(final TableDescriptor tableDescriptor, final boolean isCritical) 2564 throws IOException { 2565 if (isStopped()) { 2566 throw new MasterNotRunningException(); 2567 } 2568 2569 TableName tableName = tableDescriptor.getTableName(); 2570 if (!(tableName.isSystemTable())) { 2571 throw new IllegalArgumentException( 2572 "Only system table creation can use this createSystemTable API"); 2573 } 2574 2575 RegionInfo[] newRegions = ModifyRegionUtils.createRegionInfos(tableDescriptor, null); 2576 2577 LOG.info(getClientIdAuditPrefix() + " create " + tableDescriptor); 2578 2579 // This special create table is called locally to master. Therefore, no RPC means no need 2580 // to use nonce to detect duplicated RPC call. 2581 CreateTableProcedure proc = 2582 new CreateTableProcedure(procedureExecutor.getEnvironment(), tableDescriptor, newRegions); 2583 proc.setCriticalSystemTable(isCritical); 2584 return this.procedureExecutor.submitProcedure(proc); 2585 } 2586 2587 private void startActiveMasterManager(int infoPort) throws KeeperException { 2588 String backupZNode = ZNodePaths.joinZNode(zooKeeper.getZNodePaths().backupMasterAddressesZNode, 2589 serverName.toString()); 2590 /* 2591 * Add a ZNode for ourselves in the backup master directory since we may not become the active 2592 * master. If so, we want the actual active master to know we are backup masters, so that it 2593 * won't assign regions to us if so configured. If we become the active master later, 2594 * ActiveMasterManager will delete this node explicitly. If we crash before then, ZooKeeper will 2595 * delete this node for us since it is ephemeral. 2596 */ 2597 LOG.info("Adding backup master ZNode " + backupZNode); 2598 if (!MasterAddressTracker.setMasterAddress(zooKeeper, backupZNode, serverName, infoPort)) { 2599 LOG.warn("Failed create of " + backupZNode + " by " + serverName); 2600 } 2601 this.activeMasterManager.setInfoPort(infoPort); 2602 int timeout = conf.getInt(HConstants.ZK_SESSION_TIMEOUT, HConstants.DEFAULT_ZK_SESSION_TIMEOUT); 2603 // If we're a backup master, stall until a primary to write this address 2604 if (conf.getBoolean(HConstants.MASTER_TYPE_BACKUP, HConstants.DEFAULT_MASTER_TYPE_BACKUP)) { 2605 LOG.debug("HMaster started in backup mode. Stalling until master znode is written."); 2606 // This will only be a minute or so while the cluster starts up, 2607 // so don't worry about setting watches on the parent znode 2608 while (!activeMasterManager.hasActiveMaster()) { 2609 LOG.debug("Waiting for master address and cluster state znode to be written."); 2610 Threads.sleep(timeout); 2611 } 2612 } 2613 2614 // Here for the master startup process, we use TaskGroup to monitor the whole progress. 2615 // The UI is similar to how Hadoop designed the startup page for the NameNode. 2616 // See HBASE-21521 for more details. 2617 // We do not cleanup the startupTaskGroup, let the startup progress information 2618 // be permanent in the MEM. 2619 startupTaskGroup = TaskMonitor.createTaskGroup(true, "Master startup"); 2620 try { 2621 if (activeMasterManager.blockUntilBecomingActiveMaster(timeout, startupTaskGroup)) { 2622 finishActiveMasterInitialization(); 2623 } 2624 } catch (Throwable t) { 2625 startupTaskGroup.abort("Failed to become active master due to:" + t.getMessage()); 2626 LOG.error(HBaseMarkers.FATAL, "Failed to become active master", t); 2627 // HBASE-5680: Likely hadoop23 vs hadoop 20.x/1.x incompatibility 2628 if ( 2629 t instanceof NoClassDefFoundError 2630 && t.getMessage().contains("org/apache/hadoop/hdfs/protocol/HdfsConstants$SafeModeAction") 2631 ) { 2632 // improved error message for this special case 2633 abort("HBase is having a problem with its Hadoop jars. You may need to recompile " 2634 + "HBase against Hadoop version " + org.apache.hadoop.util.VersionInfo.getVersion() 2635 + " or change your hadoop jars to start properly", t); 2636 } else { 2637 abort("Unhandled exception. Starting shutdown.", t); 2638 } 2639 } 2640 } 2641 2642 private static boolean isCatalogTable(final TableName tableName) { 2643 return tableName.equals(TableName.META_TABLE_NAME); 2644 } 2645 2646 @Override 2647 public long deleteTable(final TableName tableName, final long nonceGroup, final long nonce) 2648 throws IOException { 2649 checkInitialized(); 2650 2651 return MasterProcedureUtil 2652 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2653 @Override 2654 protected void run() throws IOException { 2655 getMaster().getMasterCoprocessorHost().preDeleteTable(tableName); 2656 2657 LOG.info(getClientIdAuditPrefix() + " delete " + tableName); 2658 2659 // TODO: We can handle/merge duplicate request 2660 // 2661 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2662 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2663 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 2664 submitProcedure( 2665 new DeleteTableProcedure(procedureExecutor.getEnvironment(), tableName, latch)); 2666 latch.await(); 2667 2668 getMaster().getMasterCoprocessorHost().postDeleteTable(tableName); 2669 } 2670 2671 @Override 2672 protected String getDescription() { 2673 return "DeleteTableProcedure"; 2674 } 2675 }); 2676 } 2677 2678 @Override 2679 public long truncateTable(final TableName tableName, final boolean preserveSplits, 2680 final long nonceGroup, final long nonce) throws IOException { 2681 checkInitialized(); 2682 2683 return MasterProcedureUtil 2684 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2685 @Override 2686 protected void run() throws IOException { 2687 getMaster().getMasterCoprocessorHost().preTruncateTable(tableName); 2688 2689 LOG.info(getClientIdAuditPrefix() + " truncate " + tableName); 2690 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createLatch(2, 0); 2691 submitProcedure(new TruncateTableProcedure(procedureExecutor.getEnvironment(), tableName, 2692 preserveSplits, latch)); 2693 latch.await(); 2694 2695 getMaster().getMasterCoprocessorHost().postTruncateTable(tableName); 2696 } 2697 2698 @Override 2699 protected String getDescription() { 2700 return "TruncateTableProcedure"; 2701 } 2702 }); 2703 } 2704 2705 @Override 2706 public long truncateRegion(final RegionInfo regionInfo, final long nonceGroup, final long nonce) 2707 throws IOException { 2708 checkInitialized(); 2709 2710 return MasterProcedureUtil 2711 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2712 @Override 2713 protected void run() throws IOException { 2714 getMaster().getMasterCoprocessorHost().preTruncateRegion(regionInfo); 2715 2716 LOG.info( 2717 getClientIdAuditPrefix() + " truncate region " + regionInfo.getRegionNameAsString()); 2718 2719 // Execute the operation asynchronously 2720 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createLatch(2, 0); 2721 submitProcedure( 2722 new TruncateRegionProcedure(procedureExecutor.getEnvironment(), regionInfo, latch)); 2723 latch.await(); 2724 2725 getMaster().getMasterCoprocessorHost().postTruncateRegion(regionInfo); 2726 } 2727 2728 @Override 2729 protected String getDescription() { 2730 return "TruncateRegionProcedure"; 2731 } 2732 }); 2733 } 2734 2735 @Override 2736 public long addColumn(final TableName tableName, final ColumnFamilyDescriptor column, 2737 final long nonceGroup, final long nonce) throws IOException { 2738 checkInitialized(); 2739 checkTableExists(tableName); 2740 2741 return modifyTable(tableName, new TableDescriptorGetter() { 2742 2743 @Override 2744 public TableDescriptor get() throws IOException { 2745 TableDescriptor old = getTableDescriptors().get(tableName); 2746 if (old.hasColumnFamily(column.getName())) { 2747 throw new InvalidFamilyOperationException("Column family '" + column.getNameAsString() 2748 + "' in table '" + tableName + "' already exists so cannot be added"); 2749 } 2750 2751 return TableDescriptorBuilder.newBuilder(old).setColumnFamily(column).build(); 2752 } 2753 }, nonceGroup, nonce, true); 2754 } 2755 2756 /** 2757 * Implement to return TableDescriptor after pre-checks 2758 */ 2759 protected interface TableDescriptorGetter { 2760 TableDescriptor get() throws IOException; 2761 } 2762 2763 @Override 2764 public long modifyColumn(final TableName tableName, final ColumnFamilyDescriptor descriptor, 2765 final long nonceGroup, final long nonce) throws IOException { 2766 checkInitialized(); 2767 checkTableExists(tableName); 2768 return modifyTable(tableName, new TableDescriptorGetter() { 2769 2770 @Override 2771 public TableDescriptor get() throws IOException { 2772 TableDescriptor old = getTableDescriptors().get(tableName); 2773 if (!old.hasColumnFamily(descriptor.getName())) { 2774 throw new InvalidFamilyOperationException("Family '" + descriptor.getNameAsString() 2775 + "' does not exist, so it cannot be modified"); 2776 } 2777 2778 return TableDescriptorBuilder.newBuilder(old).modifyColumnFamily(descriptor).build(); 2779 } 2780 }, nonceGroup, nonce, true); 2781 } 2782 2783 @Override 2784 public long modifyColumnStoreFileTracker(TableName tableName, byte[] family, String dstSFT, 2785 long nonceGroup, long nonce) throws IOException { 2786 checkInitialized(); 2787 return MasterProcedureUtil 2788 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2789 2790 @Override 2791 protected void run() throws IOException { 2792 String sft = getMaster().getMasterCoprocessorHost() 2793 .preModifyColumnFamilyStoreFileTracker(tableName, family, dstSFT); 2794 LOG.info("{} modify column {} store file tracker of table {} to {}", 2795 getClientIdAuditPrefix(), Bytes.toStringBinary(family), tableName, sft); 2796 submitProcedure(new ModifyColumnFamilyStoreFileTrackerProcedure( 2797 procedureExecutor.getEnvironment(), tableName, family, sft)); 2798 getMaster().getMasterCoprocessorHost().postModifyColumnFamilyStoreFileTracker(tableName, 2799 family, dstSFT); 2800 } 2801 2802 @Override 2803 protected String getDescription() { 2804 return "ModifyColumnFamilyStoreFileTrackerProcedure"; 2805 } 2806 }); 2807 } 2808 2809 @Override 2810 public long deleteColumn(final TableName tableName, final byte[] columnName, 2811 final long nonceGroup, final long nonce) throws IOException { 2812 checkInitialized(); 2813 checkTableExists(tableName); 2814 2815 return modifyTable(tableName, new TableDescriptorGetter() { 2816 2817 @Override 2818 public TableDescriptor get() throws IOException { 2819 TableDescriptor old = getTableDescriptors().get(tableName); 2820 2821 if (!old.hasColumnFamily(columnName)) { 2822 throw new InvalidFamilyOperationException( 2823 "Family '" + Bytes.toString(columnName) + "' does not exist, so it cannot be deleted"); 2824 } 2825 if (old.getColumnFamilyCount() == 1) { 2826 throw new InvalidFamilyOperationException("Family '" + Bytes.toString(columnName) 2827 + "' is the only column family in the table, so it cannot be deleted"); 2828 } 2829 return TableDescriptorBuilder.newBuilder(old).removeColumnFamily(columnName).build(); 2830 } 2831 }, nonceGroup, nonce, true); 2832 } 2833 2834 @Override 2835 public long enableTable(final TableName tableName, final long nonceGroup, final long nonce) 2836 throws IOException { 2837 checkInitialized(); 2838 2839 return MasterProcedureUtil 2840 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2841 @Override 2842 protected void run() throws IOException { 2843 getMaster().getMasterCoprocessorHost().preEnableTable(tableName); 2844 2845 // Normally, it would make sense for this authorization check to exist inside 2846 // AccessController, but because the authorization check is done based on internal state 2847 // (rather than explicit permissions) we'll do the check here instead of in the 2848 // coprocessor. 2849 MasterQuotaManager quotaManager = getMasterQuotaManager(); 2850 if (quotaManager != null) { 2851 if (quotaManager.isQuotaInitialized()) { 2852 // skip checking quotas for system tables, see: 2853 // https://issues.apache.org/jira/browse/HBASE-28183 2854 if (!tableName.isSystemTable()) { 2855 SpaceQuotaSnapshot currSnapshotOfTable = 2856 QuotaTableUtil.getCurrentSnapshotFromQuotaTable(getConnection(), tableName); 2857 if (currSnapshotOfTable != null) { 2858 SpaceQuotaStatus quotaStatus = currSnapshotOfTable.getQuotaStatus(); 2859 if ( 2860 quotaStatus.isInViolation() 2861 && SpaceViolationPolicy.DISABLE == quotaStatus.getPolicy().orElse(null) 2862 ) { 2863 throw new AccessDeniedException("Enabling the table '" + tableName 2864 + "' is disallowed due to a violated space quota."); 2865 } 2866 } 2867 } 2868 } else if (LOG.isTraceEnabled()) { 2869 LOG 2870 .trace("Unable to check for space quotas as the MasterQuotaManager is not enabled"); 2871 } 2872 } 2873 2874 LOG.info(getClientIdAuditPrefix() + " enable " + tableName); 2875 2876 // Execute the operation asynchronously - client will check the progress of the operation 2877 // In case the request is from a <1.1 client before returning, 2878 // we want to make sure that the table is prepared to be 2879 // enabled (the table is locked and the table state is set). 2880 // Note: if the procedure throws exception, we will catch it and rethrow. 2881 final ProcedurePrepareLatch prepareLatch = ProcedurePrepareLatch.createLatch(); 2882 submitProcedure( 2883 new EnableTableProcedure(procedureExecutor.getEnvironment(), tableName, prepareLatch)); 2884 prepareLatch.await(); 2885 2886 getMaster().getMasterCoprocessorHost().postEnableTable(tableName); 2887 } 2888 2889 @Override 2890 protected String getDescription() { 2891 return "EnableTableProcedure"; 2892 } 2893 }); 2894 } 2895 2896 @Override 2897 public long disableTable(final TableName tableName, final long nonceGroup, final long nonce) 2898 throws IOException { 2899 checkInitialized(); 2900 2901 return MasterProcedureUtil 2902 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2903 @Override 2904 protected void run() throws IOException { 2905 getMaster().getMasterCoprocessorHost().preDisableTable(tableName); 2906 2907 LOG.info(getClientIdAuditPrefix() + " disable " + tableName); 2908 2909 // Execute the operation asynchronously - client will check the progress of the operation 2910 // In case the request is from a <1.1 client before returning, 2911 // we want to make sure that the table is prepared to be 2912 // enabled (the table is locked and the table state is set). 2913 // Note: if the procedure throws exception, we will catch it and rethrow. 2914 // 2915 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2916 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2917 final ProcedurePrepareLatch prepareLatch = ProcedurePrepareLatch.createBlockingLatch(); 2918 submitProcedure(new DisableTableProcedure(procedureExecutor.getEnvironment(), tableName, 2919 false, prepareLatch)); 2920 prepareLatch.await(); 2921 2922 getMaster().getMasterCoprocessorHost().postDisableTable(tableName); 2923 } 2924 2925 @Override 2926 protected String getDescription() { 2927 return "DisableTableProcedure"; 2928 } 2929 }); 2930 } 2931 2932 private long modifyTable(final TableName tableName, 2933 final TableDescriptorGetter newDescriptorGetter, final long nonceGroup, final long nonce, 2934 final boolean shouldCheckDescriptor) throws IOException { 2935 return modifyTable(tableName, newDescriptorGetter, nonceGroup, nonce, shouldCheckDescriptor, 2936 true); 2937 } 2938 2939 private long modifyTable(final TableName tableName, 2940 final TableDescriptorGetter newDescriptorGetter, final long nonceGroup, final long nonce, 2941 final boolean shouldCheckDescriptor, final boolean reopenRegions) throws IOException { 2942 return MasterProcedureUtil 2943 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2944 @Override 2945 protected void run() throws IOException { 2946 TableDescriptor oldDescriptor = getMaster().getTableDescriptors().get(tableName); 2947 TableDescriptor newDescriptor = getMaster().getMasterCoprocessorHost() 2948 .preModifyTable(tableName, oldDescriptor, newDescriptorGetter.get()); 2949 TableDescriptorChecker.sanityCheck(conf, newDescriptor); 2950 LOG.info("{} modify table {} from {} to {}", getClientIdAuditPrefix(), tableName, 2951 oldDescriptor, newDescriptor); 2952 2953 // Execute the operation synchronously - wait for the operation completes before 2954 // continuing. 2955 // 2956 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2957 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2958 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 2959 submitProcedure(new ModifyTableProcedure(procedureExecutor.getEnvironment(), 2960 newDescriptor, latch, oldDescriptor, shouldCheckDescriptor, reopenRegions)); 2961 latch.await(); 2962 2963 getMaster().getMasterCoprocessorHost().postModifyTable(tableName, oldDescriptor, 2964 newDescriptor); 2965 } 2966 2967 @Override 2968 protected String getDescription() { 2969 return "ModifyTableProcedure"; 2970 } 2971 }); 2972 2973 } 2974 2975 @Override 2976 public long modifyTable(final TableName tableName, final TableDescriptor newDescriptor, 2977 final long nonceGroup, final long nonce, final boolean reopenRegions) throws IOException { 2978 checkInitialized(); 2979 return modifyTable(tableName, new TableDescriptorGetter() { 2980 @Override 2981 public TableDescriptor get() throws IOException { 2982 return newDescriptor; 2983 } 2984 }, nonceGroup, nonce, false, reopenRegions); 2985 2986 } 2987 2988 @Override 2989 public long modifyTableStoreFileTracker(TableName tableName, String dstSFT, long nonceGroup, 2990 long nonce) throws IOException { 2991 checkInitialized(); 2992 return MasterProcedureUtil 2993 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2994 2995 @Override 2996 protected void run() throws IOException { 2997 String sft = getMaster().getMasterCoprocessorHost() 2998 .preModifyTableStoreFileTracker(tableName, dstSFT); 2999 LOG.info("{} modify table store file tracker of table {} to {}", getClientIdAuditPrefix(), 3000 tableName, sft); 3001 submitProcedure(new ModifyTableStoreFileTrackerProcedure( 3002 procedureExecutor.getEnvironment(), tableName, sft)); 3003 getMaster().getMasterCoprocessorHost().postModifyTableStoreFileTracker(tableName, sft); 3004 } 3005 3006 @Override 3007 protected String getDescription() { 3008 return "ModifyTableStoreFileTrackerProcedure"; 3009 } 3010 }); 3011 } 3012 3013 public long restoreSnapshot(final SnapshotDescription snapshotDesc, final long nonceGroup, 3014 final long nonce, final boolean restoreAcl, final String customSFT) throws IOException { 3015 checkInitialized(); 3016 getSnapshotManager().checkSnapshotSupport(); 3017 3018 // Ensure namespace exists. Will throw exception if non-known NS. 3019 final TableName dstTable = TableName.valueOf(snapshotDesc.getTable()); 3020 getClusterSchema().getNamespace(dstTable.getNamespaceAsString()); 3021 3022 return MasterProcedureUtil 3023 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 3024 @Override 3025 protected void run() throws IOException { 3026 setProcId(getSnapshotManager().restoreOrCloneSnapshot(snapshotDesc, getNonceKey(), 3027 restoreAcl, customSFT)); 3028 } 3029 3030 @Override 3031 protected String getDescription() { 3032 return "RestoreSnapshotProcedure"; 3033 } 3034 }); 3035 } 3036 3037 private void checkTableExists(final TableName tableName) 3038 throws IOException, TableNotFoundException { 3039 if (!tableDescriptors.exists(tableName)) { 3040 throw new TableNotFoundException(tableName); 3041 } 3042 } 3043 3044 @Override 3045 public void checkTableModifiable(final TableName tableName) 3046 throws IOException, TableNotFoundException, TableNotDisabledException { 3047 if (isCatalogTable(tableName)) { 3048 throw new IOException("Can't modify catalog tables"); 3049 } 3050 checkTableExists(tableName); 3051 TableState ts = getTableStateManager().getTableState(tableName); 3052 if (!ts.isDisabled()) { 3053 throw new TableNotDisabledException("Not DISABLED; " + ts); 3054 } 3055 } 3056 3057 public void reloadRegionServerQuotas() { 3058 // multiple reloads are harmless, so no need for NonceProcedureRunnable 3059 getLiveRegionServers() 3060 .forEach(sn -> procedureExecutor.submitProcedure(new ReloadQuotasProcedure(sn))); 3061 } 3062 3063 public ClusterMetrics getClusterMetricsWithoutCoprocessor() throws InterruptedIOException { 3064 return getClusterMetricsWithoutCoprocessor(EnumSet.allOf(Option.class)); 3065 } 3066 3067 public ClusterMetrics getClusterMetricsWithoutCoprocessor(EnumSet<Option> options) 3068 throws InterruptedIOException { 3069 ClusterMetricsBuilder builder = ClusterMetricsBuilder.newBuilder(); 3070 // given that hbase1 can't submit the request with Option, 3071 // we return all information to client if the list of Option is empty. 3072 if (options.isEmpty()) { 3073 options = EnumSet.allOf(Option.class); 3074 } 3075 3076 // TASKS and/or LIVE_SERVERS will populate this map, which will be given to the builder if 3077 // not null after option processing completes. 3078 Map<ServerName, ServerMetrics> serverMetricsMap = null; 3079 3080 for (Option opt : options) { 3081 switch (opt) { 3082 case HBASE_VERSION: 3083 builder.setHBaseVersion(VersionInfo.getVersion()); 3084 break; 3085 case CLUSTER_ID: 3086 builder.setClusterId(getClusterId()); 3087 break; 3088 case MASTER: 3089 builder.setMasterName(getServerName()); 3090 break; 3091 case BACKUP_MASTERS: 3092 builder.setBackerMasterNames(getBackupMasters()); 3093 break; 3094 case TASKS: { 3095 // Master tasks 3096 builder.setMasterTasks(TaskMonitor.get().getTasks().stream() 3097 .map(task -> ServerTaskBuilder.newBuilder().setDescription(task.getDescription()) 3098 .setStatus(task.getStatus()) 3099 .setState(ServerTask.State.valueOf(task.getState().name())) 3100 .setStartTime(task.getStartTime()).setCompletionTime(task.getCompletionTimestamp()) 3101 .build()) 3102 .collect(Collectors.toList())); 3103 // TASKS is also synonymous with LIVE_SERVERS for now because task information for 3104 // regionservers is carried in ServerLoad. 3105 // Add entries to serverMetricsMap for all live servers, if we haven't already done so 3106 if (serverMetricsMap == null) { 3107 serverMetricsMap = getOnlineServers(); 3108 } 3109 break; 3110 } 3111 case LIVE_SERVERS: { 3112 // Add entries to serverMetricsMap for all live servers, if we haven't already done so 3113 if (serverMetricsMap == null) { 3114 serverMetricsMap = getOnlineServers(); 3115 } 3116 break; 3117 } 3118 case DEAD_SERVERS: { 3119 if (serverManager != null) { 3120 builder.setDeadServerNames( 3121 new ArrayList<>(serverManager.getDeadServers().copyServerNames())); 3122 } 3123 break; 3124 } 3125 case UNKNOWN_SERVERS: { 3126 if (serverManager != null) { 3127 builder.setUnknownServerNames(getUnknownServers()); 3128 } 3129 break; 3130 } 3131 case MASTER_COPROCESSORS: { 3132 if (cpHost != null) { 3133 builder.setMasterCoprocessorNames(Arrays.asList(getMasterCoprocessors())); 3134 } 3135 break; 3136 } 3137 case REGIONS_IN_TRANSITION: { 3138 if (assignmentManager != null) { 3139 builder.setRegionsInTransition( 3140 new ArrayList<>(assignmentManager.getRegionsStateInTransition())); 3141 } 3142 break; 3143 } 3144 case BALANCER_ON: { 3145 if (loadBalancerStateStore != null) { 3146 builder.setBalancerOn(loadBalancerStateStore.get()); 3147 } 3148 break; 3149 } 3150 case MASTER_INFO_PORT: { 3151 if (infoServer != null) { 3152 builder.setMasterInfoPort(infoServer.getPort()); 3153 } 3154 break; 3155 } 3156 case SERVERS_NAME: { 3157 if (serverManager != null) { 3158 builder.setServerNames(serverManager.getOnlineServersList()); 3159 } 3160 break; 3161 } 3162 case TABLE_TO_REGIONS_COUNT: { 3163 if (isActiveMaster() && isInitialized() && assignmentManager != null) { 3164 try { 3165 Map<TableName, RegionStatesCount> tableRegionStatesCountMap = new HashMap<>(); 3166 List<TableDescriptor> tableDescriptors = listTableDescriptors(null, null, null, true); 3167 for (TableDescriptor tableDescriptor : tableDescriptors) { 3168 TableName tableName = tableDescriptor.getTableName(); 3169 RegionStatesCount regionStatesCount = 3170 assignmentManager.getRegionStatesCount(tableName); 3171 tableRegionStatesCountMap.put(tableName, regionStatesCount); 3172 } 3173 builder.setTableRegionStatesCount(tableRegionStatesCountMap); 3174 } catch (IOException e) { 3175 LOG.error("Error while populating TABLE_TO_REGIONS_COUNT for Cluster Metrics..", e); 3176 } 3177 } 3178 break; 3179 } 3180 case DECOMMISSIONED_SERVERS: { 3181 if (serverManager != null) { 3182 builder.setDecommissionedServerNames(serverManager.getDrainingServersList()); 3183 } 3184 break; 3185 } 3186 } 3187 } 3188 3189 if (serverMetricsMap != null) { 3190 builder.setLiveServerMetrics(serverMetricsMap); 3191 } 3192 3193 return builder.build(); 3194 } 3195 3196 private List<ServerName> getUnknownServers() { 3197 if (serverManager != null) { 3198 final Set<ServerName> serverNames = getAssignmentManager().getRegionStates().getRegionStates() 3199 .stream().map(RegionState::getServerName).collect(Collectors.toSet()); 3200 final List<ServerName> unknownServerNames = serverNames.stream() 3201 .filter(sn -> sn != null && serverManager.isServerUnknown(sn)).collect(Collectors.toList()); 3202 return unknownServerNames; 3203 } 3204 return null; 3205 } 3206 3207 private Map<ServerName, ServerMetrics> getOnlineServers() { 3208 if (serverManager != null) { 3209 final Map<ServerName, ServerMetrics> map = new HashMap<>(); 3210 serverManager.getOnlineServers().entrySet().forEach(e -> map.put(e.getKey(), e.getValue())); 3211 return map; 3212 } 3213 return null; 3214 } 3215 3216 /** Returns cluster status */ 3217 public ClusterMetrics getClusterMetrics() throws IOException { 3218 return getClusterMetrics(EnumSet.allOf(Option.class)); 3219 } 3220 3221 public ClusterMetrics getClusterMetrics(EnumSet<Option> options) throws IOException { 3222 if (cpHost != null) { 3223 cpHost.preGetClusterMetrics(); 3224 } 3225 ClusterMetrics status = getClusterMetricsWithoutCoprocessor(options); 3226 if (cpHost != null) { 3227 cpHost.postGetClusterMetrics(status); 3228 } 3229 return status; 3230 } 3231 3232 /** Returns info port of active master or 0 if any exception occurs. */ 3233 public int getActiveMasterInfoPort() { 3234 return activeMasterManager.getActiveMasterInfoPort(); 3235 } 3236 3237 /** 3238 * @param sn is ServerName of the backup master 3239 * @return info port of backup master or 0 if any exception occurs. 3240 */ 3241 public int getBackupMasterInfoPort(final ServerName sn) { 3242 return activeMasterManager.getBackupMasterInfoPort(sn); 3243 } 3244 3245 /** 3246 * The set of loaded coprocessors is stored in a static set. Since it's statically allocated, it 3247 * does not require that HMaster's cpHost be initialized prior to accessing it. 3248 * @return a String representation of the set of names of the loaded coprocessors. 3249 */ 3250 public static String getLoadedCoprocessors() { 3251 return CoprocessorHost.getLoadedCoprocessors().toString(); 3252 } 3253 3254 /** Returns timestamp in millis when HMaster was started. */ 3255 public long getMasterStartTime() { 3256 return startcode; 3257 } 3258 3259 /** Returns timestamp in millis when HMaster became the active master. */ 3260 @Override 3261 public long getMasterActiveTime() { 3262 return masterActiveTime; 3263 } 3264 3265 /** Returns timestamp in millis when HMaster finished becoming the active master */ 3266 public long getMasterFinishedInitializationTime() { 3267 return masterFinishedInitializationTime; 3268 } 3269 3270 public int getNumWALFiles() { 3271 return 0; 3272 } 3273 3274 public ProcedureStore getProcedureStore() { 3275 return procedureStore; 3276 } 3277 3278 public int getRegionServerInfoPort(final ServerName sn) { 3279 int port = this.serverManager.getInfoPort(sn); 3280 return port == 0 3281 ? conf.getInt(HConstants.REGIONSERVER_INFO_PORT, HConstants.DEFAULT_REGIONSERVER_INFOPORT) 3282 : port; 3283 } 3284 3285 @Override 3286 public String getRegionServerVersion(ServerName sn) { 3287 // Will return "0.0.0" if the server is not online to prevent move system region to unknown 3288 // version RS. 3289 return this.serverManager.getVersion(sn); 3290 } 3291 3292 @Override 3293 public void checkIfShouldMoveSystemRegionAsync() { 3294 assignmentManager.checkIfShouldMoveSystemRegionAsync(); 3295 } 3296 3297 /** Returns array of coprocessor SimpleNames. */ 3298 public String[] getMasterCoprocessors() { 3299 Set<String> masterCoprocessors = getMasterCoprocessorHost().getCoprocessors(); 3300 return masterCoprocessors.toArray(new String[masterCoprocessors.size()]); 3301 } 3302 3303 @Override 3304 public void abort(String reason, Throwable cause) { 3305 if (!setAbortRequested() || isStopped()) { 3306 LOG.debug("Abort called but aborted={}, stopped={}", isAborted(), isStopped()); 3307 return; 3308 } 3309 if (cpHost != null) { 3310 // HBASE-4014: dump a list of loaded coprocessors. 3311 LOG.error(HBaseMarkers.FATAL, 3312 "Master server abort: loaded coprocessors are: " + getLoadedCoprocessors()); 3313 } 3314 String msg = "***** ABORTING master " + this + ": " + reason + " *****"; 3315 if (cause != null) { 3316 LOG.error(HBaseMarkers.FATAL, msg, cause); 3317 } else { 3318 LOG.error(HBaseMarkers.FATAL, msg); 3319 } 3320 3321 try { 3322 stopMaster(); 3323 } catch (IOException e) { 3324 LOG.error("Exception occurred while stopping master", e); 3325 } 3326 } 3327 3328 @Override 3329 public MasterCoprocessorHost getMasterCoprocessorHost() { 3330 return cpHost; 3331 } 3332 3333 @Override 3334 public MasterQuotaManager getMasterQuotaManager() { 3335 return quotaManager; 3336 } 3337 3338 @Override 3339 public ProcedureExecutor<MasterProcedureEnv> getMasterProcedureExecutor() { 3340 return procedureExecutor; 3341 } 3342 3343 @Override 3344 public ServerName getServerName() { 3345 return this.serverName; 3346 } 3347 3348 @Override 3349 public AssignmentManager getAssignmentManager() { 3350 return this.assignmentManager; 3351 } 3352 3353 @Override 3354 public CatalogJanitor getCatalogJanitor() { 3355 return this.catalogJanitorChore; 3356 } 3357 3358 public MemoryBoundedLogMessageBuffer getRegionServerFatalLogBuffer() { 3359 return rsFatals; 3360 } 3361 3362 public TaskGroup getStartupProgress() { 3363 return startupTaskGroup; 3364 } 3365 3366 /** 3367 * Shutdown the cluster. Master runs a coordinated stop of all RegionServers and then itself. 3368 */ 3369 public void shutdown() throws IOException { 3370 TraceUtil.trace(() -> { 3371 if (cpHost != null) { 3372 cpHost.preShutdown(); 3373 } 3374 3375 // Tell the servermanager cluster shutdown has been called. This makes it so when Master is 3376 // last running server, it'll stop itself. Next, we broadcast the cluster shutdown by setting 3377 // the cluster status as down. RegionServers will notice this change in state and will start 3378 // shutting themselves down. When last has exited, Master can go down. 3379 if (this.serverManager != null) { 3380 this.serverManager.shutdownCluster(); 3381 } 3382 if (this.clusterStatusTracker != null) { 3383 try { 3384 this.clusterStatusTracker.setClusterDown(); 3385 } catch (KeeperException e) { 3386 LOG.error("ZooKeeper exception trying to set cluster as down in ZK", e); 3387 } 3388 } 3389 // Stop the procedure executor. Will stop any ongoing assign, unassign, server crash etc., 3390 // processing so we can go down. 3391 if (this.procedureExecutor != null) { 3392 this.procedureExecutor.stop(); 3393 } 3394 // Shutdown our cluster connection. This will kill any hosted RPCs that might be going on; 3395 // this is what we want especially if the Master is in startup phase doing call outs to 3396 // hbase:meta, etc. when cluster is down. Without ths connection close, we'd have to wait on 3397 // the rpc to timeout. 3398 if (this.asyncClusterConnection != null) { 3399 this.asyncClusterConnection.close(); 3400 } 3401 }, "HMaster.shutdown"); 3402 } 3403 3404 public void stopMaster() throws IOException { 3405 if (cpHost != null) { 3406 cpHost.preStopMaster(); 3407 } 3408 stop("Stopped by " + Thread.currentThread().getName()); 3409 } 3410 3411 @Override 3412 public void stop(String msg) { 3413 if (!this.stopped) { 3414 LOG.info("***** STOPPING master '" + this + "' *****"); 3415 this.stopped = true; 3416 LOG.info("STOPPED: " + msg); 3417 // Wakes run() if it is sleeping 3418 sleeper.skipSleepCycle(); 3419 if (this.activeMasterManager != null) { 3420 this.activeMasterManager.stop(); 3421 } 3422 } 3423 } 3424 3425 protected void checkServiceStarted() throws ServerNotRunningYetException { 3426 if (!serviceStarted) { 3427 throw new ServerNotRunningYetException("Server is not running yet"); 3428 } 3429 } 3430 3431 void checkInitialized() throws PleaseHoldException, ServerNotRunningYetException, 3432 MasterNotRunningException, MasterStoppedException { 3433 checkServiceStarted(); 3434 if (!isInitialized()) { 3435 throw new PleaseHoldException("Master is initializing"); 3436 } 3437 if (isStopped()) { 3438 throw new MasterStoppedException(); 3439 } 3440 } 3441 3442 /** 3443 * Report whether this master is currently the active master or not. If not active master, we are 3444 * parked on ZK waiting to become active. This method is used for testing. 3445 * @return true if active master, false if not. 3446 */ 3447 @Override 3448 public boolean isActiveMaster() { 3449 return activeMaster; 3450 } 3451 3452 /** 3453 * Report whether this master has completed with its initialization and is ready. If ready, the 3454 * master is also the active master. A standby master is never ready. This method is used for 3455 * testing. 3456 * @return true if master is ready to go, false if not. 3457 */ 3458 @Override 3459 public boolean isInitialized() { 3460 return initialized.isReady(); 3461 } 3462 3463 /** 3464 * Report whether this master is started This method is used for testing. 3465 * @return true if master is ready to go, false if not. 3466 */ 3467 public boolean isOnline() { 3468 return serviceStarted; 3469 } 3470 3471 /** 3472 * Report whether this master is in maintenance mode. 3473 * @return true if master is in maintenanceMode 3474 */ 3475 @Override 3476 public boolean isInMaintenanceMode() { 3477 return maintenanceMode; 3478 } 3479 3480 public void setInitialized(boolean isInitialized) { 3481 procedureExecutor.getEnvironment().setEventReady(initialized, isInitialized); 3482 } 3483 3484 /** 3485 * Mainly used in procedure related tests, where we will restart ProcedureExecutor and 3486 * AssignmentManager, but we do not want to restart master(to speed up the test), so we need to 3487 * disable rpc for a while otherwise some critical rpc requests such as 3488 * reportRegionStateTransition could fail and cause region server to abort. 3489 */ 3490 @RestrictedApi(explanation = "Should only be called in tests", link = "", 3491 allowedOnPath = ".*/src/test/.*") 3492 public void setServiceStarted(boolean started) { 3493 this.serviceStarted = started; 3494 } 3495 3496 @Override 3497 public ProcedureEvent<?> getInitializedEvent() { 3498 return initialized; 3499 } 3500 3501 /** 3502 * Compute the average load across all region servers. Currently, this uses a very naive 3503 * computation - just uses the number of regions being served, ignoring stats about number of 3504 * requests. 3505 * @return the average load 3506 */ 3507 public double getAverageLoad() { 3508 if (this.assignmentManager == null) { 3509 return 0; 3510 } 3511 3512 RegionStates regionStates = this.assignmentManager.getRegionStates(); 3513 if (regionStates == null) { 3514 return 0; 3515 } 3516 return regionStates.getAverageLoad(); 3517 } 3518 3519 @Override 3520 public boolean registerService(Service instance) { 3521 /* 3522 * No stacking of instances is allowed for a single service name 3523 */ 3524 Descriptors.ServiceDescriptor serviceDesc = instance.getDescriptorForType(); 3525 String serviceName = CoprocessorRpcUtils.getServiceName(serviceDesc); 3526 if (coprocessorServiceHandlers.containsKey(serviceName)) { 3527 LOG.error("Coprocessor service " + serviceName 3528 + " already registered, rejecting request from " + instance); 3529 return false; 3530 } 3531 3532 coprocessorServiceHandlers.put(serviceName, instance); 3533 if (LOG.isDebugEnabled()) { 3534 LOG.debug("Registered master coprocessor service: service=" + serviceName); 3535 } 3536 return true; 3537 } 3538 3539 /** 3540 * Utility for constructing an instance of the passed HMaster class. 3541 * @return HMaster instance. 3542 */ 3543 public static HMaster constructMaster(Class<? extends HMaster> masterClass, 3544 final Configuration conf) { 3545 try { 3546 Constructor<? extends HMaster> c = masterClass.getConstructor(Configuration.class); 3547 return c.newInstance(conf); 3548 } catch (Exception e) { 3549 Throwable error = e; 3550 if ( 3551 e instanceof InvocationTargetException 3552 && ((InvocationTargetException) e).getTargetException() != null 3553 ) { 3554 error = ((InvocationTargetException) e).getTargetException(); 3555 } 3556 throw new RuntimeException("Failed construction of Master: " + masterClass.toString() + ". ", 3557 error); 3558 } 3559 } 3560 3561 /** 3562 * @see org.apache.hadoop.hbase.master.HMasterCommandLine 3563 */ 3564 public static void main(String[] args) { 3565 LOG.info("STARTING service " + HMaster.class.getSimpleName()); 3566 VersionInfo.logVersion(); 3567 new HMasterCommandLine(HMaster.class).doMain(args); 3568 } 3569 3570 public HFileCleaner getHFileCleaner() { 3571 return this.hfileCleaners.get(0); 3572 } 3573 3574 public List<HFileCleaner> getHFileCleaners() { 3575 return this.hfileCleaners; 3576 } 3577 3578 public LogCleaner getLogCleaner() { 3579 return this.logCleaner; 3580 } 3581 3582 /** Returns the underlying snapshot manager */ 3583 @Override 3584 public SnapshotManager getSnapshotManager() { 3585 return this.snapshotManager; 3586 } 3587 3588 /** Returns the underlying MasterProcedureManagerHost */ 3589 @Override 3590 public MasterProcedureManagerHost getMasterProcedureManagerHost() { 3591 return mpmHost; 3592 } 3593 3594 @Override 3595 public ClusterSchema getClusterSchema() { 3596 return this.clusterSchemaService; 3597 } 3598 3599 /** 3600 * Create a new Namespace. 3601 * @param namespaceDescriptor descriptor for new Namespace 3602 * @param nonceGroup Identifier for the source of the request, a client or process. 3603 * @param nonce A unique identifier for this operation from the client or process 3604 * identified by <code>nonceGroup</code> (the source must ensure each 3605 * operation gets a unique id). 3606 * @return procedure id 3607 */ 3608 long createNamespace(final NamespaceDescriptor namespaceDescriptor, final long nonceGroup, 3609 final long nonce) throws IOException { 3610 checkInitialized(); 3611 3612 TableName.isLegalNamespaceName(Bytes.toBytes(namespaceDescriptor.getName())); 3613 3614 return MasterProcedureUtil 3615 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 3616 @Override 3617 protected void run() throws IOException { 3618 getMaster().getMasterCoprocessorHost().preCreateNamespace(namespaceDescriptor); 3619 // We need to wait for the procedure to potentially fail due to "prepare" sanity 3620 // checks. This will block only the beginning of the procedure. See HBASE-19953. 3621 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 3622 LOG.info(getClientIdAuditPrefix() + " creating " + namespaceDescriptor); 3623 // Execute the operation synchronously - wait for the operation to complete before 3624 // continuing. 3625 setProcId(getClusterSchema().createNamespace(namespaceDescriptor, getNonceKey(), latch)); 3626 latch.await(); 3627 getMaster().getMasterCoprocessorHost().postCreateNamespace(namespaceDescriptor); 3628 } 3629 3630 @Override 3631 protected String getDescription() { 3632 return "CreateNamespaceProcedure"; 3633 } 3634 }); 3635 } 3636 3637 /** 3638 * Modify an existing Namespace. 3639 * @param nonceGroup Identifier for the source of the request, a client or process. 3640 * @param nonce A unique identifier for this operation from the client or process identified 3641 * by <code>nonceGroup</code> (the source must ensure each operation gets a 3642 * unique id). 3643 * @return procedure id 3644 */ 3645 long modifyNamespace(final NamespaceDescriptor newNsDescriptor, final long nonceGroup, 3646 final long nonce) throws IOException { 3647 checkInitialized(); 3648 3649 TableName.isLegalNamespaceName(Bytes.toBytes(newNsDescriptor.getName())); 3650 3651 return MasterProcedureUtil 3652 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 3653 @Override 3654 protected void run() throws IOException { 3655 NamespaceDescriptor oldNsDescriptor = getNamespace(newNsDescriptor.getName()); 3656 getMaster().getMasterCoprocessorHost().preModifyNamespace(oldNsDescriptor, 3657 newNsDescriptor); 3658 // We need to wait for the procedure to potentially fail due to "prepare" sanity 3659 // checks. This will block only the beginning of the procedure. See HBASE-19953. 3660 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 3661 LOG.info(getClientIdAuditPrefix() + " modify " + newNsDescriptor); 3662 // Execute the operation synchronously - wait for the operation to complete before 3663 // continuing. 3664 setProcId(getClusterSchema().modifyNamespace(newNsDescriptor, getNonceKey(), latch)); 3665 latch.await(); 3666 getMaster().getMasterCoprocessorHost().postModifyNamespace(oldNsDescriptor, 3667 newNsDescriptor); 3668 } 3669 3670 @Override 3671 protected String getDescription() { 3672 return "ModifyNamespaceProcedure"; 3673 } 3674 }); 3675 } 3676 3677 /** 3678 * Delete an existing Namespace. Only empty Namespaces (no tables) can be removed. 3679 * @param nonceGroup Identifier for the source of the request, a client or process. 3680 * @param nonce A unique identifier for this operation from the client or process identified 3681 * by <code>nonceGroup</code> (the source must ensure each operation gets a 3682 * unique id). 3683 * @return procedure id 3684 */ 3685 long deleteNamespace(final String name, final long nonceGroup, final long nonce) 3686 throws IOException { 3687 checkInitialized(); 3688 3689 return MasterProcedureUtil 3690 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 3691 @Override 3692 protected void run() throws IOException { 3693 getMaster().getMasterCoprocessorHost().preDeleteNamespace(name); 3694 LOG.info(getClientIdAuditPrefix() + " delete " + name); 3695 // Execute the operation synchronously - wait for the operation to complete before 3696 // continuing. 3697 // 3698 // We need to wait for the procedure to potentially fail due to "prepare" sanity 3699 // checks. This will block only the beginning of the procedure. See HBASE-19953. 3700 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 3701 setProcId(submitProcedure( 3702 new DeleteNamespaceProcedure(procedureExecutor.getEnvironment(), name, latch))); 3703 latch.await(); 3704 // Will not be invoked in the face of Exception thrown by the Procedure's execution 3705 getMaster().getMasterCoprocessorHost().postDeleteNamespace(name); 3706 } 3707 3708 @Override 3709 protected String getDescription() { 3710 return "DeleteNamespaceProcedure"; 3711 } 3712 }); 3713 } 3714 3715 /** 3716 * Get a Namespace 3717 * @param name Name of the Namespace 3718 * @return Namespace descriptor for <code>name</code> 3719 */ 3720 NamespaceDescriptor getNamespace(String name) throws IOException { 3721 checkInitialized(); 3722 if (this.cpHost != null) this.cpHost.preGetNamespaceDescriptor(name); 3723 NamespaceDescriptor nsd = this.clusterSchemaService.getNamespace(name); 3724 if (this.cpHost != null) this.cpHost.postGetNamespaceDescriptor(nsd); 3725 return nsd; 3726 } 3727 3728 /** 3729 * Get all Namespaces 3730 * @return All Namespace descriptors 3731 */ 3732 List<NamespaceDescriptor> getNamespaces() throws IOException { 3733 checkInitialized(); 3734 final List<NamespaceDescriptor> nsds = new ArrayList<>(); 3735 if (cpHost != null) { 3736 cpHost.preListNamespaceDescriptors(nsds); 3737 } 3738 nsds.addAll(this.clusterSchemaService.getNamespaces()); 3739 if (this.cpHost != null) { 3740 this.cpHost.postListNamespaceDescriptors(nsds); 3741 } 3742 return nsds; 3743 } 3744 3745 /** 3746 * List namespace names 3747 * @return All namespace names 3748 */ 3749 public List<String> listNamespaces() throws IOException { 3750 checkInitialized(); 3751 List<String> namespaces = new ArrayList<>(); 3752 if (cpHost != null) { 3753 cpHost.preListNamespaces(namespaces); 3754 } 3755 for (NamespaceDescriptor namespace : clusterSchemaService.getNamespaces()) { 3756 namespaces.add(namespace.getName()); 3757 } 3758 if (cpHost != null) { 3759 cpHost.postListNamespaces(namespaces); 3760 } 3761 return namespaces; 3762 } 3763 3764 @Override 3765 public List<TableName> listTableNamesByNamespace(String name) throws IOException { 3766 checkInitialized(); 3767 return listTableNames(name, null, true); 3768 } 3769 3770 @Override 3771 public List<TableDescriptor> listTableDescriptorsByNamespace(String name) throws IOException { 3772 checkInitialized(); 3773 return listTableDescriptors(name, null, null, true); 3774 } 3775 3776 @Override 3777 public boolean abortProcedure(final long procId, final boolean mayInterruptIfRunning) 3778 throws IOException { 3779 if (cpHost != null) { 3780 cpHost.preAbortProcedure(this.procedureExecutor, procId); 3781 } 3782 3783 final boolean result = this.procedureExecutor.abort(procId, mayInterruptIfRunning); 3784 3785 if (cpHost != null) { 3786 cpHost.postAbortProcedure(); 3787 } 3788 3789 return result; 3790 } 3791 3792 @Override 3793 public List<Procedure<?>> getProcedures() throws IOException { 3794 if (cpHost != null) { 3795 cpHost.preGetProcedures(); 3796 } 3797 3798 @SuppressWarnings({ "unchecked", "rawtypes" }) 3799 List<Procedure<?>> procList = (List) this.procedureExecutor.getProcedures(); 3800 3801 if (cpHost != null) { 3802 cpHost.postGetProcedures(procList); 3803 } 3804 3805 return procList; 3806 } 3807 3808 @Override 3809 public List<LockedResource> getLocks() throws IOException { 3810 if (cpHost != null) { 3811 cpHost.preGetLocks(); 3812 } 3813 3814 MasterProcedureScheduler procedureScheduler = 3815 procedureExecutor.getEnvironment().getProcedureScheduler(); 3816 3817 final List<LockedResource> lockedResources = procedureScheduler.getLocks(); 3818 3819 if (cpHost != null) { 3820 cpHost.postGetLocks(lockedResources); 3821 } 3822 3823 return lockedResources; 3824 } 3825 3826 /** 3827 * Returns the list of table descriptors that match the specified request 3828 * @param namespace the namespace to query, or null if querying for all 3829 * @param regex The regular expression to match against, or null if querying for all 3830 * @param tableNameList the list of table names, or null if querying for all 3831 * @param includeSysTables False to match only against userspace tables 3832 * @return the list of table descriptors 3833 */ 3834 public List<TableDescriptor> listTableDescriptors(final String namespace, final String regex, 3835 final List<TableName> tableNameList, final boolean includeSysTables) throws IOException { 3836 List<TableDescriptor> htds = new ArrayList<>(); 3837 if (cpHost != null) { 3838 cpHost.preGetTableDescriptors(tableNameList, htds, regex); 3839 } 3840 htds = getTableDescriptors(htds, namespace, regex, tableNameList, includeSysTables); 3841 if (cpHost != null) { 3842 cpHost.postGetTableDescriptors(tableNameList, htds, regex); 3843 } 3844 return htds; 3845 } 3846 3847 /** 3848 * Returns the list of table names that match the specified request 3849 * @param regex The regular expression to match against, or null if querying for all 3850 * @param namespace the namespace to query, or null if querying for all 3851 * @param includeSysTables False to match only against userspace tables 3852 * @return the list of table names 3853 */ 3854 public List<TableName> listTableNames(final String namespace, final String regex, 3855 final boolean includeSysTables) throws IOException { 3856 List<TableDescriptor> htds = new ArrayList<>(); 3857 if (cpHost != null) { 3858 cpHost.preGetTableNames(htds, regex); 3859 } 3860 htds = getTableDescriptors(htds, namespace, regex, null, includeSysTables); 3861 if (cpHost != null) { 3862 cpHost.postGetTableNames(htds, regex); 3863 } 3864 List<TableName> result = new ArrayList<>(htds.size()); 3865 for (TableDescriptor htd : htds) 3866 result.add(htd.getTableName()); 3867 return result; 3868 } 3869 3870 /** 3871 * Return a list of table descriptors after applying any provided filter parameters. Note that the 3872 * user-facing description of this filter logic is presented on the class-level javadoc of 3873 * {@link NormalizeTableFilterParams}. 3874 */ 3875 private List<TableDescriptor> getTableDescriptors(final List<TableDescriptor> htds, 3876 final String namespace, final String regex, final List<TableName> tableNameList, 3877 final boolean includeSysTables) throws IOException { 3878 if (tableNameList == null || tableNameList.isEmpty()) { 3879 // request for all TableDescriptors 3880 Collection<TableDescriptor> allHtds; 3881 if (namespace != null && namespace.length() > 0) { 3882 // Do a check on the namespace existence. Will fail if it does not exist. 3883 this.clusterSchemaService.getNamespace(namespace); 3884 allHtds = tableDescriptors.getByNamespace(namespace).values(); 3885 } else { 3886 allHtds = tableDescriptors.getAll().values(); 3887 } 3888 for (TableDescriptor desc : allHtds) { 3889 if ( 3890 tableStateManager.isTablePresent(desc.getTableName()) 3891 && (includeSysTables || !desc.getTableName().isSystemTable()) 3892 ) { 3893 htds.add(desc); 3894 } 3895 } 3896 } else { 3897 for (TableName s : tableNameList) { 3898 if (tableStateManager.isTablePresent(s)) { 3899 TableDescriptor desc = tableDescriptors.get(s); 3900 if (desc != null) { 3901 htds.add(desc); 3902 } 3903 } 3904 } 3905 } 3906 3907 // Retains only those matched by regular expression. 3908 if (regex != null) filterTablesByRegex(htds, Pattern.compile(regex)); 3909 return htds; 3910 } 3911 3912 /** 3913 * Removes the table descriptors that don't match the pattern. 3914 * @param descriptors list of table descriptors to filter 3915 * @param pattern the regex to use 3916 */ 3917 private static void filterTablesByRegex(final Collection<TableDescriptor> descriptors, 3918 final Pattern pattern) { 3919 final String defaultNS = NamespaceDescriptor.DEFAULT_NAMESPACE_NAME_STR; 3920 Iterator<TableDescriptor> itr = descriptors.iterator(); 3921 while (itr.hasNext()) { 3922 TableDescriptor htd = itr.next(); 3923 String tableName = htd.getTableName().getNameAsString(); 3924 boolean matched = pattern.matcher(tableName).matches(); 3925 if (!matched && htd.getTableName().getNamespaceAsString().equals(defaultNS)) { 3926 matched = pattern.matcher(defaultNS + TableName.NAMESPACE_DELIM + tableName).matches(); 3927 } 3928 if (!matched) { 3929 itr.remove(); 3930 } 3931 } 3932 } 3933 3934 @Override 3935 public long getLastMajorCompactionTimestamp(TableName table) throws IOException { 3936 return getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS)) 3937 .getLastMajorCompactionTimestamp(table); 3938 } 3939 3940 @Override 3941 public long getLastMajorCompactionTimestampForRegion(byte[] regionName) throws IOException { 3942 return getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS)) 3943 .getLastMajorCompactionTimestamp(regionName); 3944 } 3945 3946 /** 3947 * Gets the mob file compaction state for a specific table. Whether all the mob files are selected 3948 * is known during the compaction execution, but the statistic is done just before compaction 3949 * starts, it is hard to know the compaction type at that time, so the rough statistics are chosen 3950 * for the mob file compaction. Only two compaction states are available, 3951 * CompactionState.MAJOR_AND_MINOR and CompactionState.NONE. 3952 * @param tableName The current table name. 3953 * @return If a given table is in mob file compaction now. 3954 */ 3955 public GetRegionInfoResponse.CompactionState getMobCompactionState(TableName tableName) { 3956 AtomicInteger compactionsCount = mobCompactionStates.get(tableName); 3957 if (compactionsCount != null && compactionsCount.get() != 0) { 3958 return GetRegionInfoResponse.CompactionState.MAJOR_AND_MINOR; 3959 } 3960 return GetRegionInfoResponse.CompactionState.NONE; 3961 } 3962 3963 public void reportMobCompactionStart(TableName tableName) throws IOException { 3964 IdLock.Entry lockEntry = null; 3965 try { 3966 lockEntry = mobCompactionLock.getLockEntry(tableName.hashCode()); 3967 AtomicInteger compactionsCount = mobCompactionStates.get(tableName); 3968 if (compactionsCount == null) { 3969 compactionsCount = new AtomicInteger(0); 3970 mobCompactionStates.put(tableName, compactionsCount); 3971 } 3972 compactionsCount.incrementAndGet(); 3973 } finally { 3974 if (lockEntry != null) { 3975 mobCompactionLock.releaseLockEntry(lockEntry); 3976 } 3977 } 3978 } 3979 3980 public void reportMobCompactionEnd(TableName tableName) throws IOException { 3981 IdLock.Entry lockEntry = null; 3982 try { 3983 lockEntry = mobCompactionLock.getLockEntry(tableName.hashCode()); 3984 AtomicInteger compactionsCount = mobCompactionStates.get(tableName); 3985 if (compactionsCount != null) { 3986 int count = compactionsCount.decrementAndGet(); 3987 // remove the entry if the count is 0. 3988 if (count == 0) { 3989 mobCompactionStates.remove(tableName); 3990 } 3991 } 3992 } finally { 3993 if (lockEntry != null) { 3994 mobCompactionLock.releaseLockEntry(lockEntry); 3995 } 3996 } 3997 } 3998 3999 /** 4000 * Queries the state of the {@link LoadBalancerStateStore}. If the balancer is not initialized, 4001 * false is returned. 4002 * @return The state of the load balancer, or false if the load balancer isn't defined. 4003 */ 4004 public boolean isBalancerOn() { 4005 return !isInMaintenanceMode() && loadBalancerStateStore != null && loadBalancerStateStore.get(); 4006 } 4007 4008 /** 4009 * Queries the state of the {@link RegionNormalizerStateStore}. If it's not initialized, false is 4010 * returned. 4011 */ 4012 public boolean isNormalizerOn() { 4013 return !isInMaintenanceMode() && getRegionNormalizerManager().isNormalizerOn(); 4014 } 4015 4016 /** 4017 * Queries the state of the {@link SplitOrMergeStateStore}. If it is not initialized, false is 4018 * returned. If switchType is illegal, false will return. 4019 * @param switchType see {@link org.apache.hadoop.hbase.client.MasterSwitchType} 4020 * @return The state of the switch 4021 */ 4022 @Override 4023 public boolean isSplitOrMergeEnabled(MasterSwitchType switchType) { 4024 return !isInMaintenanceMode() && splitOrMergeStateStore != null 4025 && splitOrMergeStateStore.isSplitOrMergeEnabled(switchType); 4026 } 4027 4028 /** 4029 * Fetch the configured {@link LoadBalancer} class name. If none is set, a default is returned. 4030 * <p/> 4031 * Notice that, the base load balancer will always be {@link RSGroupBasedLoadBalancer} now, so 4032 * this method will return the balancer used inside each rs group. 4033 * @return The name of the {@link LoadBalancer} in use. 4034 */ 4035 public String getLoadBalancerClassName() { 4036 return conf.get(HConstants.HBASE_MASTER_LOADBALANCER_CLASS, 4037 LoadBalancerFactory.getDefaultLoadBalancerClass().getName()); 4038 } 4039 4040 public SplitOrMergeStateStore getSplitOrMergeStateStore() { 4041 return splitOrMergeStateStore; 4042 } 4043 4044 @Override 4045 public RSGroupBasedLoadBalancer getLoadBalancer() { 4046 return balancer; 4047 } 4048 4049 @Override 4050 public FavoredNodesManager getFavoredNodesManager() { 4051 return balancer.getFavoredNodesManager(); 4052 } 4053 4054 private long executePeerProcedure(AbstractPeerProcedure<?> procedure) throws IOException { 4055 if (!isReplicationPeerModificationEnabled()) { 4056 throw new IOException("Replication peer modification disabled"); 4057 } 4058 long procId = procedureExecutor.submitProcedure(procedure); 4059 procedure.getLatch().await(); 4060 return procId; 4061 } 4062 4063 @Override 4064 public long addReplicationPeer(String peerId, ReplicationPeerConfig peerConfig, boolean enabled) 4065 throws ReplicationException, IOException { 4066 LOG.info(getClientIdAuditPrefix() + " creating replication peer, id=" + peerId + ", config=" 4067 + peerConfig + ", state=" + (enabled ? "ENABLED" : "DISABLED")); 4068 return executePeerProcedure(new AddPeerProcedure(peerId, peerConfig, enabled)); 4069 } 4070 4071 @Override 4072 public long removeReplicationPeer(String peerId) throws ReplicationException, IOException { 4073 LOG.info(getClientIdAuditPrefix() + " removing replication peer, id=" + peerId); 4074 return executePeerProcedure(new RemovePeerProcedure(peerId)); 4075 } 4076 4077 @Override 4078 public long enableReplicationPeer(String peerId) throws ReplicationException, IOException { 4079 LOG.info(getClientIdAuditPrefix() + " enable replication peer, id=" + peerId); 4080 return executePeerProcedure(new EnablePeerProcedure(peerId)); 4081 } 4082 4083 @Override 4084 public long disableReplicationPeer(String peerId) throws ReplicationException, IOException { 4085 LOG.info(getClientIdAuditPrefix() + " disable replication peer, id=" + peerId); 4086 return executePeerProcedure(new DisablePeerProcedure(peerId)); 4087 } 4088 4089 @Override 4090 public ReplicationPeerConfig getReplicationPeerConfig(String peerId) 4091 throws ReplicationException, IOException { 4092 if (cpHost != null) { 4093 cpHost.preGetReplicationPeerConfig(peerId); 4094 } 4095 LOG.info(getClientIdAuditPrefix() + " get replication peer config, id=" + peerId); 4096 ReplicationPeerConfig peerConfig = this.replicationPeerManager.getPeerConfig(peerId) 4097 .orElseThrow(() -> new ReplicationPeerNotFoundException(peerId)); 4098 if (cpHost != null) { 4099 cpHost.postGetReplicationPeerConfig(peerId); 4100 } 4101 return peerConfig; 4102 } 4103 4104 @Override 4105 public long updateReplicationPeerConfig(String peerId, ReplicationPeerConfig peerConfig) 4106 throws ReplicationException, IOException { 4107 LOG.info(getClientIdAuditPrefix() + " update replication peer config, id=" + peerId 4108 + ", config=" + peerConfig); 4109 return executePeerProcedure(new UpdatePeerConfigProcedure(peerId, peerConfig)); 4110 } 4111 4112 @Override 4113 public List<ReplicationPeerDescription> listReplicationPeers(String regex) 4114 throws ReplicationException, IOException { 4115 if (cpHost != null) { 4116 cpHost.preListReplicationPeers(regex); 4117 } 4118 LOG.debug("{} list replication peers, regex={}", getClientIdAuditPrefix(), regex); 4119 Pattern pattern = regex == null ? null : Pattern.compile(regex); 4120 List<ReplicationPeerDescription> peers = this.replicationPeerManager.listPeers(pattern); 4121 if (cpHost != null) { 4122 cpHost.postListReplicationPeers(regex); 4123 } 4124 return peers; 4125 } 4126 4127 @Override 4128 public long transitReplicationPeerSyncReplicationState(String peerId, SyncReplicationState state) 4129 throws ReplicationException, IOException { 4130 LOG.info( 4131 getClientIdAuditPrefix() 4132 + " transit current cluster state to {} in a synchronous replication peer id={}", 4133 state, peerId); 4134 return executePeerProcedure(new TransitPeerSyncReplicationStateProcedure(peerId, state)); 4135 } 4136 4137 @Override 4138 public boolean replicationPeerModificationSwitch(boolean on) throws IOException { 4139 return replicationPeerModificationStateStore.set(on); 4140 } 4141 4142 @Override 4143 public boolean isReplicationPeerModificationEnabled() { 4144 return replicationPeerModificationStateStore.get(); 4145 } 4146 4147 /** 4148 * Mark region server(s) as decommissioned (previously called 'draining') to prevent additional 4149 * regions from getting assigned to them. Also unload the regions on the servers asynchronously.0 4150 * @param servers Region servers to decommission. 4151 */ 4152 public void decommissionRegionServers(final List<ServerName> servers, final boolean offload) 4153 throws IOException { 4154 List<ServerName> serversAdded = new ArrayList<>(servers.size()); 4155 // Place the decommission marker first. 4156 String parentZnode = getZooKeeper().getZNodePaths().drainingZNode; 4157 for (ServerName server : servers) { 4158 try { 4159 String node = ZNodePaths.joinZNode(parentZnode, server.getServerName()); 4160 ZKUtil.createAndFailSilent(getZooKeeper(), node); 4161 } catch (KeeperException ke) { 4162 throw new HBaseIOException( 4163 this.zooKeeper.prefix("Unable to decommission '" + server.getServerName() + "'."), ke); 4164 } 4165 if (this.serverManager.addServerToDrainList(server)) { 4166 serversAdded.add(server); 4167 } 4168 } 4169 // Move the regions off the decommissioned servers. 4170 if (offload) { 4171 final List<ServerName> destServers = this.serverManager.createDestinationServersList(); 4172 for (ServerName server : serversAdded) { 4173 final List<RegionInfo> regionsOnServer = this.assignmentManager.getRegionsOnServer(server); 4174 for (RegionInfo hri : regionsOnServer) { 4175 ServerName dest = balancer.randomAssignment(hri, destServers); 4176 if (dest == null) { 4177 throw new HBaseIOException("Unable to determine a plan to move " + hri); 4178 } 4179 RegionPlan rp = new RegionPlan(hri, server, dest); 4180 this.assignmentManager.moveAsync(rp); 4181 } 4182 } 4183 } 4184 } 4185 4186 /** 4187 * List region servers marked as decommissioned (previously called 'draining') to not get regions 4188 * assigned to them. 4189 * @return List of decommissioned servers. 4190 */ 4191 public List<ServerName> listDecommissionedRegionServers() { 4192 return this.serverManager.getDrainingServersList(); 4193 } 4194 4195 /** 4196 * Remove decommission marker (previously called 'draining') from a region server to allow regions 4197 * assignments. Load regions onto the server asynchronously if a list of regions is given 4198 * @param server Region server to remove decommission marker from. 4199 */ 4200 public void recommissionRegionServer(final ServerName server, 4201 final List<byte[]> encodedRegionNames) throws IOException { 4202 // Remove the server from decommissioned (draining) server list. 4203 String parentZnode = getZooKeeper().getZNodePaths().drainingZNode; 4204 String node = ZNodePaths.joinZNode(parentZnode, server.getServerName()); 4205 try { 4206 ZKUtil.deleteNodeFailSilent(getZooKeeper(), node); 4207 } catch (KeeperException ke) { 4208 throw new HBaseIOException( 4209 this.zooKeeper.prefix("Unable to recommission '" + server.getServerName() + "'."), ke); 4210 } 4211 this.serverManager.removeServerFromDrainList(server); 4212 4213 // Load the regions onto the server if we are given a list of regions. 4214 if (encodedRegionNames == null || encodedRegionNames.isEmpty()) { 4215 return; 4216 } 4217 if (!this.serverManager.isServerOnline(server)) { 4218 return; 4219 } 4220 for (byte[] encodedRegionName : encodedRegionNames) { 4221 RegionState regionState = 4222 assignmentManager.getRegionStates().getRegionState(Bytes.toString(encodedRegionName)); 4223 if (regionState == null) { 4224 LOG.warn("Unknown region " + Bytes.toStringBinary(encodedRegionName)); 4225 continue; 4226 } 4227 RegionInfo hri = regionState.getRegion(); 4228 if (server.equals(regionState.getServerName())) { 4229 LOG.info("Skipping move of region " + hri.getRegionNameAsString() 4230 + " because region already assigned to the same server " + server + "."); 4231 continue; 4232 } 4233 RegionPlan rp = new RegionPlan(hri, regionState.getServerName(), server); 4234 this.assignmentManager.moveAsync(rp); 4235 } 4236 } 4237 4238 @Override 4239 public LockManager getLockManager() { 4240 return lockManager; 4241 } 4242 4243 public QuotaObserverChore getQuotaObserverChore() { 4244 return this.quotaObserverChore; 4245 } 4246 4247 public SpaceQuotaSnapshotNotifier getSpaceQuotaSnapshotNotifier() { 4248 return this.spaceQuotaSnapshotNotifier; 4249 } 4250 4251 @SuppressWarnings("unchecked") 4252 private RemoteProcedure<MasterProcedureEnv, ?> getRemoteProcedure(long procId) { 4253 Procedure<?> procedure = procedureExecutor.getProcedure(procId); 4254 if (procedure == null) { 4255 return null; 4256 } 4257 assert procedure instanceof RemoteProcedure; 4258 return (RemoteProcedure<MasterProcedureEnv, ?>) procedure; 4259 } 4260 4261 public void remoteProcedureCompleted(long procId, byte[] remoteResultData) { 4262 LOG.debug("Remote procedure done, pid={}", procId); 4263 RemoteProcedure<MasterProcedureEnv, ?> procedure = getRemoteProcedure(procId); 4264 if (procedure != null) { 4265 procedure.remoteOperationCompleted(procedureExecutor.getEnvironment(), remoteResultData); 4266 } 4267 } 4268 4269 public void remoteProcedureFailed(long procId, RemoteProcedureException error) { 4270 LOG.debug("Remote procedure failed, pid={}", procId, error); 4271 RemoteProcedure<MasterProcedureEnv, ?> procedure = getRemoteProcedure(procId); 4272 if (procedure != null) { 4273 procedure.remoteOperationFailed(procedureExecutor.getEnvironment(), error); 4274 } 4275 } 4276 4277 /** 4278 * Reopen regions provided in the argument 4279 * @param tableName The current table name 4280 * @param regionNames The region names of the regions to reopen 4281 * @param nonceGroup Identifier for the source of the request, a client or process 4282 * @param nonce A unique identifier for this operation from the client or process identified 4283 * by <code>nonceGroup</code> (the source must ensure each operation gets a 4284 * unique id). 4285 * @return procedure Id 4286 * @throws IOException if reopening region fails while running procedure 4287 * @deprecated since 3.0.0 and will be removed in 4.0.0. Use 4288 * {@link #reopenRegionsThrottled(TableName, List, long, long)} instead so region 4289 * reopening honors the configured throttling. 4290 * @see <a href="https://issues.apache.org/jira/browse/HBASE-29809">HBASE-29809</a> 4291 */ 4292 @Deprecated 4293 long reopenRegions(final TableName tableName, final List<byte[]> regionNames, 4294 final long nonceGroup, final long nonce) throws IOException { 4295 4296 return MasterProcedureUtil 4297 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4298 4299 @Override 4300 protected void run() throws IOException { 4301 submitProcedure(new ReopenTableRegionsProcedure(tableName, regionNames)); 4302 } 4303 4304 @Override 4305 protected String getDescription() { 4306 return "ReopenTableRegionsProcedure"; 4307 } 4308 4309 }); 4310 4311 } 4312 4313 /** 4314 * Reopen regions provided in the argument. Applies throttling to the procedure to avoid 4315 * overwhelming the system. This is used by the reopenTableRegions methods in the Admin API via 4316 * HMaster. 4317 * @param tableName The current table name 4318 * @param regionNames The region names of the regions to reopen 4319 * @param nonceGroup Identifier for the source of the request, a client or process 4320 * @param nonce A unique identifier for this operation from the client or process identified 4321 * by <code>nonceGroup</code> (the source must ensure each operation gets a 4322 * unique id). 4323 * @return procedure Id 4324 * @throws IOException if reopening region fails while running procedure 4325 */ 4326 long reopenRegionsThrottled(final TableName tableName, final List<byte[]> regionNames, 4327 final long nonceGroup, final long nonce) throws IOException { 4328 4329 checkInitialized(); 4330 4331 if (!tableStateManager.isTablePresent(tableName)) { 4332 throw new TableNotFoundException(tableName); 4333 } 4334 4335 TableDescriptor tableDescriptor = getTableDescriptors().get(tableName); 4336 if (tableDescriptor == null) { 4337 throw new TableNotFoundException(tableName); 4338 } 4339 4340 return MasterProcedureUtil 4341 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4342 @Override 4343 protected void run() throws IOException { 4344 ReopenTableRegionsProcedure proc; 4345 if (regionNames.isEmpty()) { 4346 proc = ReopenTableRegionsProcedure.throttled(getConfiguration(), tableDescriptor); 4347 } else { 4348 proc = ReopenTableRegionsProcedure.throttled(getConfiguration(), tableDescriptor, 4349 regionNames); 4350 } 4351 4352 LOG.info("{} throttled reopening {} regions for table {}", getClientIdAuditPrefix(), 4353 regionNames.isEmpty() ? "all" : regionNames.size(), tableName); 4354 4355 submitProcedure(proc); 4356 } 4357 4358 @Override 4359 protected String getDescription() { 4360 return "Throttled ReopenTableRegionsProcedure for " + tableName; 4361 } 4362 }); 4363 } 4364 4365 @Override 4366 public ReplicationPeerManager getReplicationPeerManager() { 4367 return replicationPeerManager; 4368 } 4369 4370 @Override 4371 public ReplicationLogCleanerBarrier getReplicationLogCleanerBarrier() { 4372 return replicationLogCleanerBarrier; 4373 } 4374 4375 @Override 4376 public Semaphore getSyncReplicationPeerLock() { 4377 return syncReplicationPeerLock; 4378 } 4379 4380 public HashMap<String, List<Pair<ServerName, ReplicationLoadSource>>> 4381 getReplicationLoad(ServerName[] serverNames) { 4382 List<ReplicationPeerDescription> peerList = this.getReplicationPeerManager().listPeers(null); 4383 if (peerList == null) { 4384 return null; 4385 } 4386 HashMap<String, List<Pair<ServerName, ReplicationLoadSource>>> replicationLoadSourceMap = 4387 new HashMap<>(peerList.size()); 4388 peerList.stream() 4389 .forEach(peer -> replicationLoadSourceMap.put(peer.getPeerId(), new ArrayList<>())); 4390 for (ServerName serverName : serverNames) { 4391 List<ReplicationLoadSource> replicationLoadSources = 4392 getServerManager().getLoad(serverName).getReplicationLoadSourceList(); 4393 for (ReplicationLoadSource replicationLoadSource : replicationLoadSources) { 4394 List<Pair<ServerName, ReplicationLoadSource>> replicationLoadSourceList = 4395 replicationLoadSourceMap.get(replicationLoadSource.getPeerID()); 4396 if (replicationLoadSourceList == null) { 4397 LOG.debug("{} does not exist, but it exists " 4398 + "in znode(/hbase/replication/rs). when the rs restarts, peerId is deleted, so " 4399 + "we just need to ignore it", replicationLoadSource.getPeerID()); 4400 continue; 4401 } 4402 replicationLoadSourceList.add(new Pair<>(serverName, replicationLoadSource)); 4403 } 4404 } 4405 for (List<Pair<ServerName, ReplicationLoadSource>> loads : replicationLoadSourceMap.values()) { 4406 if (loads.size() > 0) { 4407 loads.sort(Comparator.comparingLong(load -> (-1) * load.getSecond().getReplicationLag())); 4408 } 4409 } 4410 return replicationLoadSourceMap; 4411 } 4412 4413 /** 4414 * This method modifies the master's configuration in order to inject replication-related features 4415 */ 4416 @InterfaceAudience.Private 4417 public static void decorateMasterConfiguration(Configuration conf) { 4418 String plugins = conf.get(HBASE_MASTER_LOGCLEANER_PLUGINS); 4419 String cleanerClass = ReplicationLogCleaner.class.getCanonicalName(); 4420 if (plugins == null || !plugins.contains(cleanerClass)) { 4421 conf.set(HBASE_MASTER_LOGCLEANER_PLUGINS, plugins + "," + cleanerClass); 4422 } 4423 if (ReplicationUtils.isReplicationForBulkLoadDataEnabled(conf)) { 4424 plugins = conf.get(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS); 4425 cleanerClass = ReplicationHFileCleaner.class.getCanonicalName(); 4426 if (!plugins.contains(cleanerClass)) { 4427 conf.set(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS, plugins + "," + cleanerClass); 4428 } 4429 } 4430 } 4431 4432 public SnapshotQuotaObserverChore getSnapshotQuotaObserverChore() { 4433 return this.snapshotQuotaChore; 4434 } 4435 4436 public ActiveMasterManager getActiveMasterManager() { 4437 return activeMasterManager; 4438 } 4439 4440 @Override 4441 public SyncReplicationReplayWALManager getSyncReplicationReplayWALManager() { 4442 return this.syncReplicationReplayWALManager; 4443 } 4444 4445 @Override 4446 public HbckChore getHbckChore() { 4447 return this.hbckChore; 4448 } 4449 4450 @Override 4451 public void runReplicationBarrierCleaner() { 4452 ReplicationBarrierCleaner rbc = this.replicationBarrierCleaner; 4453 if (rbc != null) { 4454 rbc.chore(); 4455 } 4456 } 4457 4458 @Override 4459 public RSGroupInfoManager getRSGroupInfoManager() { 4460 return rsGroupInfoManager; 4461 } 4462 4463 /** 4464 * Get the compaction state of the table 4465 * @param tableName The table name 4466 * @return CompactionState Compaction state of the table 4467 */ 4468 public CompactionState getCompactionState(final TableName tableName) { 4469 CompactionState compactionState = CompactionState.NONE; 4470 try { 4471 List<RegionInfo> regions = assignmentManager.getRegionStates().getRegionsOfTable(tableName); 4472 for (RegionInfo regionInfo : regions) { 4473 ServerName serverName = 4474 assignmentManager.getRegionStates().getRegionServerOfRegion(regionInfo); 4475 if (serverName == null) { 4476 continue; 4477 } 4478 ServerMetrics sl = serverManager.getLoad(serverName); 4479 if (sl == null) { 4480 continue; 4481 } 4482 RegionMetrics regionMetrics = sl.getRegionMetrics().get(regionInfo.getRegionName()); 4483 if (regionMetrics == null) { 4484 LOG.warn("Can not get compaction details for the region: {} , it may be not online.", 4485 regionInfo.getRegionNameAsString()); 4486 continue; 4487 } 4488 if (regionMetrics.getCompactionState() == CompactionState.MAJOR) { 4489 if (compactionState == CompactionState.MINOR) { 4490 compactionState = CompactionState.MAJOR_AND_MINOR; 4491 } else { 4492 compactionState = CompactionState.MAJOR; 4493 } 4494 } else if (regionMetrics.getCompactionState() == CompactionState.MINOR) { 4495 if (compactionState == CompactionState.MAJOR) { 4496 compactionState = CompactionState.MAJOR_AND_MINOR; 4497 } else { 4498 compactionState = CompactionState.MINOR; 4499 } 4500 } 4501 } 4502 } catch (Exception e) { 4503 compactionState = null; 4504 LOG.error("Exception when get compaction state for " + tableName.getNameAsString(), e); 4505 } 4506 return compactionState; 4507 } 4508 4509 @Override 4510 public MetaLocationSyncer getMetaLocationSyncer() { 4511 return metaLocationSyncer; 4512 } 4513 4514 @RestrictedApi(explanation = "Should only be called in tests", link = "", 4515 allowedOnPath = ".*/src/test/.*") 4516 public MasterRegion getMasterRegion() { 4517 return masterRegion; 4518 } 4519 4520 /** 4521 * Dynamically updates HMaster's configuration. Since HMaster inherits from 4522 * {@link HBaseServerBase}, the {@code updatedConf} parameter references the same 4523 * {@link Configuration} object as HMaster's {@code this.conf} instance variable in a real HBase 4524 * deployment. This isn't necessarily the case in unit tests. 4525 * @param updatedConf the dynamically updated configuration 4526 */ 4527 @Override 4528 public void onConfigurationChange(Configuration updatedConf) { 4529 try { 4530 Superusers.initialize(updatedConf); 4531 } catch (IOException e) { 4532 LOG.warn("Failed to initialize SuperUsers on reloading of the configuration"); 4533 } 4534 // append the quotas observer back to the master coprocessor key 4535 setQuotasObserver(updatedConf); 4536 4537 boolean originalIsReadOnlyEnabled = CoprocessorConfigurationUtil 4538 .areReadOnlyCoprocessorsLoaded(this.conf, CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY); 4539 boolean newReadOnlyEnabled = ConfigurationUtil.isReadOnlyModeEnabledInConf(updatedConf); 4540 4541 // The updatedConf is potentially a shared Configuration object, so we do not want to directly 4542 // revert its read-only value if another active cluster already exists. For now, we reference 4543 // updatedConf and create a copy for modification below if necessary. 4544 Configuration confForCoprocessors = updatedConf; 4545 4546 if (originalIsReadOnlyEnabled && !newReadOnlyEnabled) { 4547 // Changing this cluster from a replica to an active cluster. There should not be another 4548 // active cluster already. 4549 MasterFileSystem mfs = this.getMasterFileSystem(); 4550 if ( 4551 AbstractReadOnlyController.isAnotherClusterActive(mfs.getFileSystem(), mfs.getRootDir(), 4552 mfs.getActiveClusterSuffix()) 4553 ) { 4554 String activeClusterId = 4555 FSUtils.getClusterIdFromActiveClusterFile(mfs.getFileSystem(), mfs.getRootDir()); 4556 // Revert read-only mode here 4557 confForCoprocessors = this.blockReadOnlyTransition(updatedConf, activeClusterId); 4558 } 4559 } 4560 4561 // In a real HBase deployment, confForCoprocessors may reference the same object as this.conf. 4562 // This is assuming confForCoprocessors still references updatedConf, as mentioned in a previous 4563 // comment. For unit tests, this Configuration object is not shared, so we need to make sure to 4564 // update the coprocessors specifically for this.conf. 4565 CoprocessorConfigurationUtil.maybeUpdateCoprocessors(confForCoprocessors, this.conf, 4566 originalIsReadOnlyEnabled, this.cpHost, CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, 4567 this.maintenanceMode, this.toString(), this::initializeCoprocessorHost); 4568 4569 boolean maybeUpdatedReadOnlyMode = CoprocessorConfigurationUtil 4570 .areReadOnlyCoprocessorsLoaded(this.conf, CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY); 4571 4572 if (maybeUpdatedReadOnlyMode != originalIsReadOnlyEnabled) { 4573 AbstractReadOnlyController.manageActiveClusterIdFile(maybeUpdatedReadOnlyMode, 4574 this.getMasterFileSystem()); 4575 } 4576 } 4577 4578 @Override 4579 protected NamedQueueRecorder createNamedQueueRecord() { 4580 final boolean isBalancerDecisionRecording = 4581 conf.getBoolean(BaseLoadBalancer.BALANCER_DECISION_BUFFER_ENABLED, 4582 BaseLoadBalancer.DEFAULT_BALANCER_DECISION_BUFFER_ENABLED); 4583 final boolean isBalancerRejectionRecording = 4584 conf.getBoolean(BaseLoadBalancer.BALANCER_REJECTION_BUFFER_ENABLED, 4585 BaseLoadBalancer.DEFAULT_BALANCER_REJECTION_BUFFER_ENABLED); 4586 if (isBalancerDecisionRecording || isBalancerRejectionRecording) { 4587 return NamedQueueRecorder.getInstance(conf); 4588 } else { 4589 return null; 4590 } 4591 } 4592 4593 @Override 4594 protected boolean clusterMode() { 4595 return true; 4596 } 4597 4598 public String getClusterId() { 4599 if (activeMaster) { 4600 return clusterId; 4601 } 4602 return cachedClusterId.getFromCacheOrFetch(); 4603 } 4604 4605 public Optional<ServerName> getActiveMaster() { 4606 return activeMasterManager.getActiveMasterServerName(); 4607 } 4608 4609 public List<ServerName> getBackupMasters() { 4610 return activeMasterManager.getBackupMasters(); 4611 } 4612 4613 @Override 4614 public Iterator<ServerName> getBootstrapNodes() { 4615 return regionServerTracker.getRegionServers().iterator(); 4616 } 4617 4618 @Override 4619 public List<HRegionLocation> getMetaLocations() { 4620 return metaRegionLocationCache.getMetaRegionLocations(); 4621 } 4622 4623 @Override 4624 public void flushMasterStore() throws IOException { 4625 LOG.info("Force flush master local region."); 4626 if (this.cpHost != null) { 4627 try { 4628 cpHost.preMasterStoreFlush(); 4629 } catch (IOException ioe) { 4630 LOG.error("Error invoking master coprocessor preMasterStoreFlush()", ioe); 4631 } 4632 } 4633 masterRegion.flush(true); 4634 if (this.cpHost != null) { 4635 try { 4636 cpHost.postMasterStoreFlush(); 4637 } catch (IOException ioe) { 4638 LOG.error("Error invoking master coprocessor postMasterStoreFlush()", ioe); 4639 } 4640 } 4641 } 4642 4643 public Collection<ServerName> getLiveRegionServers() { 4644 return regionServerTracker.getRegionServers(); 4645 } 4646 4647 @RestrictedApi(explanation = "Should only be called in tests", link = "", 4648 allowedOnPath = ".*/src/test/.*") 4649 void setLoadBalancer(RSGroupBasedLoadBalancer loadBalancer) { 4650 this.balancer = loadBalancer; 4651 } 4652 4653 @RestrictedApi(explanation = "Should only be called in tests", link = "", 4654 allowedOnPath = ".*/src/test/.*") 4655 void setAssignmentManager(AssignmentManager assignmentManager) { 4656 this.assignmentManager = assignmentManager; 4657 } 4658 4659 @RestrictedApi(explanation = "Should only be called in tests", link = "", 4660 allowedOnPath = ".*/src/test/.*") 4661 static void setDisableBalancerChoreForTest(boolean disable) { 4662 disableBalancerChoreForTest = disable; 4663 } 4664 4665 private void setQuotasObserver(Configuration conf) { 4666 // Add the Observer to delete quotas on table deletion before starting all CPs by 4667 // default with quota support, avoiding if user specifically asks to not load this Observer. 4668 if (QuotaUtil.isQuotaEnabled(conf)) { 4669 updateConfigurationForQuotasObserver(conf); 4670 } 4671 } 4672 4673 private void initializeCoprocessorHost(Configuration conf) { 4674 // initialize master side coprocessors before we start handling requests 4675 this.cpHost = new MasterCoprocessorHost(this, conf); 4676 } 4677 4678 @Override 4679 public long flushTable(TableName tableName, List<byte[]> columnFamilies, long nonceGroup, 4680 long nonce) throws IOException { 4681 checkInitialized(); 4682 4683 if ( 4684 !getConfiguration().getBoolean(MasterFlushTableProcedureManager.FLUSH_PROCEDURE_ENABLED, 4685 MasterFlushTableProcedureManager.FLUSH_PROCEDURE_ENABLED_DEFAULT) 4686 ) { 4687 throw new DoNotRetryIOException("FlushTableProcedureV2 is DISABLED"); 4688 } 4689 4690 return MasterProcedureUtil 4691 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4692 @Override 4693 protected void run() throws IOException { 4694 getMaster().getMasterCoprocessorHost().preTableFlush(tableName); 4695 LOG.info("{} flush {}", getClientIdAuditPrefix(), tableName); 4696 submitProcedure( 4697 new FlushTableProcedure(procedureExecutor.getEnvironment(), tableName, columnFamilies)); 4698 getMaster().getMasterCoprocessorHost().postTableFlush(tableName); 4699 } 4700 4701 @Override 4702 protected String getDescription() { 4703 return "FlushTableProcedure"; 4704 } 4705 }); 4706 } 4707 4708 @Override 4709 public long rollAllWALWriters(long nonceGroup, long nonce) throws IOException { 4710 return MasterProcedureUtil 4711 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4712 @Override 4713 protected void run() { 4714 LOG.info("{} roll all wal writers", getClientIdAuditPrefix()); 4715 submitProcedure(new LogRollProcedure()); 4716 } 4717 4718 @Override 4719 protected String getDescription() { 4720 return "RollAllWALWriters"; 4721 } 4722 }); 4723 } 4724 4725 @RestrictedApi(explanation = "Should only be called in tests", link = "", 4726 allowedOnPath = ".*/src/test/.*") 4727 public MobFileCleanerChore getMobFileCleanerChore() { 4728 return mobFileCleanerChore; 4729 } 4730 4731 public Long refreshMeta(long nonceGroup, long nonce) throws IOException { 4732 return MasterProcedureUtil 4733 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4734 @Override 4735 protected void run() throws IOException { 4736 LOG.info("Submitting RefreshMetaProcedure"); 4737 submitProcedure(new RefreshMetaProcedure(procedureExecutor.getEnvironment())); 4738 } 4739 4740 @Override 4741 protected String getDescription() { 4742 return "RefreshMetaProcedure"; 4743 } 4744 }); 4745 } 4746 4747 public Long refreshHfiles(final TableName tableName, final long nonceGroup, final long nonce) 4748 throws IOException { 4749 checkInitialized(); 4750 4751 if (!tableDescriptors.exists(tableName)) { 4752 LOG.info("RefreshHfilesProcedure failed because table {} does not exist", 4753 tableName.getNameAsString()); 4754 throw new TableNotFoundException(tableName); 4755 } 4756 4757 return MasterProcedureUtil 4758 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4759 @Override 4760 protected void run() throws IOException { 4761 LOG.info("Submitting RefreshHfilesTableProcedure for table {}", 4762 tableName.getNameAsString()); 4763 submitProcedure( 4764 new RefreshHFilesTableProcedure(procedureExecutor.getEnvironment(), tableName)); 4765 } 4766 4767 @Override 4768 protected String getDescription() { 4769 return "RefreshHfilesProcedure for a table"; 4770 } 4771 }); 4772 } 4773 4774 public Long refreshHfiles(final String namespace, final long nonceGroup, final long nonce) 4775 throws IOException { 4776 checkInitialized(); 4777 4778 try { 4779 this.clusterSchemaService.getNamespace(namespace); 4780 } catch (IOException e) { 4781 LOG.info("RefreshHfilesProcedure failed because namespace {} does not exist", namespace); 4782 throw new NamespaceNotFoundException(namespace); 4783 } 4784 4785 return MasterProcedureUtil 4786 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4787 @Override 4788 protected void run() throws IOException { 4789 LOG.info("Submitting RefreshHfilesProcedure for namespace {}", namespace); 4790 submitProcedure( 4791 new RefreshHFilesTableProcedure(procedureExecutor.getEnvironment(), namespace)); 4792 } 4793 4794 @Override 4795 protected String getDescription() { 4796 return "RefreshHfilesProcedure for namespace"; 4797 } 4798 }); 4799 } 4800 4801 public Long refreshHfiles(final long nonceGroup, final long nonce) throws IOException { 4802 checkInitialized(); 4803 4804 return MasterProcedureUtil 4805 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4806 @Override 4807 protected void run() throws IOException { 4808 LOG.info("Submitting RefreshHfilesProcedure for all tables"); 4809 submitProcedure(new RefreshHFilesTableProcedure(procedureExecutor.getEnvironment())); 4810 } 4811 4812 @Override 4813 protected String getDescription() { 4814 return "RefreshHfilesProcedure for all tables"; 4815 } 4816 }); 4817 } 4818 4819 @Override 4820 public RpcThrottleStateStore getRpcThrottleStateStore() { 4821 return rpcThrottleStateStore; 4822 } 4823}