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