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