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 configurationManager.registerObserver(this.mobFileCleanerChore); 1571 getChoreService().scheduleChore(mobFileCleanerChore); 1572 this.mobFileCompactionChore = new MobFileCompactionChore(this); 1573 getChoreService().scheduleChore(mobFileCompactionChore); 1574 } 1575 1576 /** 1577 * <p> 1578 * Create a {@link ServerManager} instance. 1579 * </p> 1580 * <p> 1581 * Will be overridden in tests. 1582 * </p> 1583 */ 1584 @InterfaceAudience.Private 1585 protected ServerManager createServerManager(MasterServices master, RegionServerList storage) 1586 throws IOException { 1587 // We put this out here in a method so can do a Mockito.spy and stub it out 1588 // w/ a mocked up ServerManager. 1589 setupClusterConnection(); 1590 return new ServerManager(master, storage); 1591 } 1592 1593 private void waitForRegionServers(final MonitoredTask status) 1594 throws IOException, InterruptedException { 1595 this.serverManager.waitForRegionServers(status); 1596 } 1597 1598 // Will be overridden in tests 1599 @InterfaceAudience.Private 1600 protected void initClusterSchemaService() throws IOException, InterruptedException { 1601 this.clusterSchemaService = new ClusterSchemaServiceImpl(this); 1602 this.clusterSchemaService.startAsync(); 1603 try { 1604 this.clusterSchemaService 1605 .awaitRunning(getConfiguration().getInt(HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS, 1606 DEFAULT_HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS), TimeUnit.SECONDS); 1607 } catch (TimeoutException toe) { 1608 throw new IOException("Timedout starting ClusterSchemaService", toe); 1609 } 1610 } 1611 1612 private void initQuotaManager() throws IOException { 1613 MasterQuotaManager quotaManager = new MasterQuotaManager(this); 1614 quotaManager.start(); 1615 this.quotaManager = quotaManager; 1616 } 1617 1618 private SpaceQuotaSnapshotNotifier createQuotaSnapshotNotifier() { 1619 SpaceQuotaSnapshotNotifier notifier = 1620 SpaceQuotaSnapshotNotifierFactory.getInstance().create(getConfiguration()); 1621 return notifier; 1622 } 1623 1624 public boolean isCatalogJanitorEnabled() { 1625 return catalogJanitorChore != null ? catalogJanitorChore.getEnabled() : false; 1626 } 1627 1628 boolean isCleanerChoreEnabled() { 1629 boolean hfileCleanerFlag = true, logCleanerFlag = true; 1630 1631 if (getHFileCleaner() != null) { 1632 hfileCleanerFlag = getHFileCleaner().getEnabled(); 1633 } 1634 1635 if (logCleaner != null) { 1636 logCleanerFlag = logCleaner.getEnabled(); 1637 } 1638 1639 return (hfileCleanerFlag && logCleanerFlag); 1640 } 1641 1642 @Override 1643 public ServerManager getServerManager() { 1644 return this.serverManager; 1645 } 1646 1647 @Override 1648 public MasterFileSystem getMasterFileSystem() { 1649 return this.fileSystemManager; 1650 } 1651 1652 @Override 1653 public MasterWalManager getMasterWalManager() { 1654 return this.walManager; 1655 } 1656 1657 @Override 1658 public boolean rotateSystemKeyIfChanged() throws IOException { 1659 // STUB - Feature not yet implemented 1660 return false; 1661 } 1662 1663 @Override 1664 public SplitWALManager getSplitWALManager() { 1665 return splitWALManager; 1666 } 1667 1668 @Override 1669 public TableStateManager getTableStateManager() { 1670 return tableStateManager; 1671 } 1672 1673 /* 1674 * Start up all services. If any of these threads gets an unhandled exception then they just die 1675 * with a logged message. This should be fine because in general, we do not expect the master to 1676 * get such unhandled exceptions as OOMEs; it should be lightly loaded. See what HRegionServer 1677 * does if need to install an unexpected exception handler. 1678 */ 1679 private void startServiceThreads() throws IOException { 1680 // Start the executor service pools 1681 final int masterOpenRegionPoolSize = conf.getInt(HConstants.MASTER_OPEN_REGION_THREADS, 1682 HConstants.MASTER_OPEN_REGION_THREADS_DEFAULT); 1683 executorService.startExecutorService(executorService.new ExecutorConfig() 1684 .setExecutorType(ExecutorType.MASTER_OPEN_REGION).setCorePoolSize(masterOpenRegionPoolSize)); 1685 final int masterCloseRegionPoolSize = conf.getInt(HConstants.MASTER_CLOSE_REGION_THREADS, 1686 HConstants.MASTER_CLOSE_REGION_THREADS_DEFAULT); 1687 executorService.startExecutorService( 1688 executorService.new ExecutorConfig().setExecutorType(ExecutorType.MASTER_CLOSE_REGION) 1689 .setCorePoolSize(masterCloseRegionPoolSize)); 1690 final int masterServerOpThreads = conf.getInt(HConstants.MASTER_SERVER_OPERATIONS_THREADS, 1691 HConstants.MASTER_SERVER_OPERATIONS_THREADS_DEFAULT); 1692 executorService.startExecutorService( 1693 executorService.new ExecutorConfig().setExecutorType(ExecutorType.MASTER_SERVER_OPERATIONS) 1694 .setCorePoolSize(masterServerOpThreads)); 1695 final int masterServerMetaOpsThreads = 1696 conf.getInt(HConstants.MASTER_META_SERVER_OPERATIONS_THREADS, 1697 HConstants.MASTER_META_SERVER_OPERATIONS_THREADS_DEFAULT); 1698 executorService.startExecutorService(executorService.new ExecutorConfig() 1699 .setExecutorType(ExecutorType.MASTER_META_SERVER_OPERATIONS) 1700 .setCorePoolSize(masterServerMetaOpsThreads)); 1701 final int masterLogReplayThreads = conf.getInt(HConstants.MASTER_LOG_REPLAY_OPS_THREADS, 1702 HConstants.MASTER_LOG_REPLAY_OPS_THREADS_DEFAULT); 1703 executorService.startExecutorService(executorService.new ExecutorConfig() 1704 .setExecutorType(ExecutorType.M_LOG_REPLAY_OPS).setCorePoolSize(masterLogReplayThreads)); 1705 final int masterSnapshotThreads = conf.getInt(SnapshotManager.SNAPSHOT_POOL_THREADS_KEY, 1706 SnapshotManager.SNAPSHOT_POOL_THREADS_DEFAULT); 1707 executorService.startExecutorService( 1708 executorService.new ExecutorConfig().setExecutorType(ExecutorType.MASTER_SNAPSHOT_OPERATIONS) 1709 .setCorePoolSize(masterSnapshotThreads).setAllowCoreThreadTimeout(true)); 1710 final int masterMergeDispatchThreads = conf.getInt(HConstants.MASTER_MERGE_DISPATCH_THREADS, 1711 HConstants.MASTER_MERGE_DISPATCH_THREADS_DEFAULT); 1712 executorService.startExecutorService( 1713 executorService.new ExecutorConfig().setExecutorType(ExecutorType.MASTER_MERGE_OPERATIONS) 1714 .setCorePoolSize(masterMergeDispatchThreads).setAllowCoreThreadTimeout(true)); 1715 1716 // We depend on there being only one instance of this executor running 1717 // at a time. To do concurrency, would need fencing of enable/disable of 1718 // tables. 1719 // Any time changing this maxThreads to > 1, pls see the comment at 1720 // AccessController#postCompletedCreateTableAction 1721 executorService.startExecutorService(executorService.new ExecutorConfig() 1722 .setExecutorType(ExecutorType.MASTER_TABLE_OPERATIONS).setCorePoolSize(1)); 1723 startProcedureExecutor(); 1724 1725 // Create log cleaner thread pool 1726 logCleanerPool = DirScanPool.getLogCleanerScanPool(conf); 1727 Map<String, Object> params = new HashMap<>(); 1728 params.put(MASTER, this); 1729 // Start log cleaner thread 1730 int cleanerInterval = 1731 conf.getInt(HBASE_MASTER_CLEANER_INTERVAL, DEFAULT_HBASE_MASTER_CLEANER_INTERVAL); 1732 this.logCleaner = 1733 new LogCleaner(cleanerInterval, this, conf, getMasterWalManager().getFileSystem(), 1734 getMasterWalManager().getOldLogDir(), logCleanerPool, params); 1735 getChoreService().scheduleChore(logCleaner); 1736 1737 Path archiveDir = HFileArchiveUtil.getArchivePath(conf); 1738 1739 // Create custom archive hfile cleaners 1740 String[] paths = conf.getStrings(HFileCleaner.HFILE_CLEANER_CUSTOM_PATHS); 1741 // todo: handle the overlap issues for the custom paths 1742 1743 if (paths != null && paths.length > 0) { 1744 if (conf.getStrings(HFileCleaner.HFILE_CLEANER_CUSTOM_PATHS_PLUGINS) == null) { 1745 Set<String> cleanerClasses = new HashSet<>(); 1746 String[] cleaners = conf.getStrings(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS); 1747 if (cleaners != null) { 1748 Collections.addAll(cleanerClasses, cleaners); 1749 } 1750 conf.setStrings(HFileCleaner.HFILE_CLEANER_CUSTOM_PATHS_PLUGINS, 1751 cleanerClasses.toArray(new String[cleanerClasses.size()])); 1752 LOG.info("Archive custom cleaner paths: {}, plugins: {}", Arrays.asList(paths), 1753 cleanerClasses); 1754 } 1755 // share the hfile cleaner pool in custom paths 1756 sharedHFileCleanerPool = DirScanPool.getHFileCleanerScanPool(conf.get(CUSTOM_POOL_SIZE, "6")); 1757 for (int i = 0; i < paths.length; i++) { 1758 Path path = new Path(paths[i].trim()); 1759 HFileCleaner cleaner = 1760 new HFileCleaner("ArchiveCustomHFileCleaner-" + path.getName(), cleanerInterval, this, 1761 conf, getMasterFileSystem().getFileSystem(), new Path(archiveDir, path), 1762 HFileCleaner.HFILE_CLEANER_CUSTOM_PATHS_PLUGINS, sharedHFileCleanerPool, params, null); 1763 hfileCleaners.add(cleaner); 1764 hfileCleanerPaths.add(path); 1765 } 1766 } 1767 1768 // Create the whole archive dir cleaner thread pool 1769 exclusiveHFileCleanerPool = DirScanPool.getHFileCleanerScanPool(conf); 1770 hfileCleaners.add(0, 1771 new HFileCleaner(cleanerInterval, this, conf, getMasterFileSystem().getFileSystem(), 1772 archiveDir, exclusiveHFileCleanerPool, params, hfileCleanerPaths)); 1773 hfileCleanerPaths.add(0, archiveDir); 1774 // Schedule all the hfile cleaners 1775 for (HFileCleaner hFileCleaner : hfileCleaners) { 1776 getChoreService().scheduleChore(hFileCleaner); 1777 } 1778 1779 // Regions Reopen based on very high storeFileRefCount is considered enabled 1780 // only if hbase.regions.recovery.store.file.ref.count has value > 0 1781 final int maxStoreFileRefCount = conf.getInt(HConstants.STORE_FILE_REF_COUNT_THRESHOLD, 1782 HConstants.DEFAULT_STORE_FILE_REF_COUNT_THRESHOLD); 1783 if (maxStoreFileRefCount > 0) { 1784 this.regionsRecoveryChore = new RegionsRecoveryChore(this, conf, this); 1785 getChoreService().scheduleChore(this.regionsRecoveryChore); 1786 } else { 1787 LOG.info( 1788 "Reopening regions with very high storeFileRefCount is disabled. " 1789 + "Provide threshold value > 0 for {} to enable it.", 1790 HConstants.STORE_FILE_REF_COUNT_THRESHOLD); 1791 } 1792 1793 this.regionsRecoveryConfigManager = new RegionsRecoveryConfigManager(this); 1794 1795 replicationBarrierCleaner = 1796 new ReplicationBarrierCleaner(conf, this, getConnection(), replicationPeerManager); 1797 getChoreService().scheduleChore(replicationBarrierCleaner); 1798 1799 final boolean isSnapshotChoreEnabled = this.snapshotCleanupStateStore.get(); 1800 this.snapshotCleanerChore = new SnapshotCleanerChore(this, conf, getSnapshotManager()); 1801 if (isSnapshotChoreEnabled) { 1802 getChoreService().scheduleChore(this.snapshotCleanerChore); 1803 } else { 1804 if (LOG.isTraceEnabled()) { 1805 LOG.trace("Snapshot Cleaner Chore is disabled. Not starting up the chore.."); 1806 } 1807 } 1808 serviceStarted = true; 1809 if (LOG.isTraceEnabled()) { 1810 LOG.trace("Started service threads"); 1811 } 1812 } 1813 1814 protected void stopServiceThreads() { 1815 if (masterJettyServer != null) { 1816 LOG.info("Stopping master jetty server"); 1817 try { 1818 masterJettyServer.stop(); 1819 } catch (Exception e) { 1820 LOG.error("Failed to stop master jetty server", e); 1821 } 1822 } 1823 stopChoreService(); 1824 stopExecutorService(); 1825 if (exclusiveHFileCleanerPool != null) { 1826 exclusiveHFileCleanerPool.shutdownNow(); 1827 exclusiveHFileCleanerPool = null; 1828 } 1829 if (logCleanerPool != null) { 1830 logCleanerPool.shutdownNow(); 1831 logCleanerPool = null; 1832 } 1833 if (sharedHFileCleanerPool != null) { 1834 sharedHFileCleanerPool.shutdownNow(); 1835 sharedHFileCleanerPool = null; 1836 } 1837 if (maintenanceRegionServer != null) { 1838 maintenanceRegionServer.getRegionServer().stop(HBASE_MASTER_CLEANER_INTERVAL); 1839 } 1840 1841 LOG.debug("Stopping service threads"); 1842 // stop procedure executor prior to other services such as server manager and assignment 1843 // manager, as these services are important for some running procedures. See HBASE-24117 for 1844 // example. 1845 stopProcedureExecutor(); 1846 1847 if (regionNormalizerManager != null) { 1848 regionNormalizerManager.stop(); 1849 } 1850 if (this.quotaManager != null) { 1851 this.quotaManager.stop(); 1852 } 1853 1854 if (this.activeMasterManager != null) { 1855 this.activeMasterManager.stop(); 1856 } 1857 if (this.serverManager != null) { 1858 this.serverManager.stop(); 1859 } 1860 if (this.assignmentManager != null) { 1861 this.assignmentManager.stop(); 1862 } 1863 1864 if (masterRegion != null) { 1865 masterRegion.close(isAborted()); 1866 } 1867 if (this.walManager != null) { 1868 this.walManager.stop(); 1869 } 1870 if (this.fileSystemManager != null) { 1871 this.fileSystemManager.stop(); 1872 } 1873 if (this.mpmHost != null) { 1874 this.mpmHost.stop("server shutting down."); 1875 } 1876 if (this.regionServerTracker != null) { 1877 this.regionServerTracker.stop(); 1878 } 1879 } 1880 1881 private void createProcedureExecutor() throws IOException { 1882 final String procedureDispatcherClassName = 1883 conf.get(HBASE_MASTER_RSPROC_DISPATCHER_CLASS, DEFAULT_HBASE_MASTER_RSPROC_DISPATCHER_CLASS); 1884 final RSProcedureDispatcher procedureDispatcher = ReflectionUtils.instantiateWithCustomCtor( 1885 procedureDispatcherClassName, new Class[] { MasterServices.class }, new Object[] { this }); 1886 final MasterProcedureEnv procEnv = new MasterProcedureEnv(this, procedureDispatcher); 1887 procedureStore = new RegionProcedureStore(this, masterRegion, 1888 new MasterProcedureEnv.FsUtilsLeaseRecovery(this)); 1889 procedureStore.registerListener(new ProcedureStoreListener() { 1890 1891 @Override 1892 public void abortProcess() { 1893 abort("The Procedure Store lost the lease", null); 1894 } 1895 }); 1896 MasterProcedureScheduler procedureScheduler = procEnv.getProcedureScheduler(); 1897 procedureExecutor = new ProcedureExecutor<>(conf, procEnv, procedureStore, procedureScheduler); 1898 configurationManager.registerObserver(procEnv); 1899 1900 int cpus = Runtime.getRuntime().availableProcessors(); 1901 int defaultNumThreads = Math.max((cpus > 0 ? cpus / 4 : 0), 1902 MasterProcedureConstants.DEFAULT_MIN_MASTER_PROCEDURE_THREADS); 1903 int numThreads = 1904 conf.getInt(MasterProcedureConstants.MASTER_PROCEDURE_THREADS, defaultNumThreads); 1905 if (numThreads <= 0) { 1906 LOG.warn("{} is set to {}, which is invalid, using default value {} instead", 1907 MasterProcedureConstants.MASTER_PROCEDURE_THREADS, numThreads, defaultNumThreads); 1908 numThreads = defaultNumThreads; 1909 } 1910 final boolean abortOnCorruption = 1911 conf.getBoolean(MasterProcedureConstants.EXECUTOR_ABORT_ON_CORRUPTION, 1912 MasterProcedureConstants.DEFAULT_EXECUTOR_ABORT_ON_CORRUPTION); 1913 procedureStore.start(numThreads); 1914 // Just initialize it but do not start the workers, we will start the workers later by calling 1915 // startProcedureExecutor. See the javadoc for finishActiveMasterInitialization for more 1916 // details. 1917 procedureExecutor.init(numThreads, abortOnCorruption); 1918 if (!procEnv.getRemoteDispatcher().start()) { 1919 throw new HBaseIOException("Failed start of remote dispatcher"); 1920 } 1921 } 1922 1923 // will be override in UT 1924 protected void startProcedureExecutor() throws IOException { 1925 procedureExecutor.startWorkers(); 1926 } 1927 1928 /** 1929 * Turn on/off Snapshot Cleanup Chore 1930 * @param on indicates whether Snapshot Cleanup Chore is to be run 1931 */ 1932 void switchSnapshotCleanup(final boolean on, final boolean synchronous) throws IOException { 1933 if (synchronous) { 1934 synchronized (this.snapshotCleanerChore) { 1935 switchSnapshotCleanup(on); 1936 } 1937 } else { 1938 switchSnapshotCleanup(on); 1939 } 1940 } 1941 1942 private void switchSnapshotCleanup(final boolean on) throws IOException { 1943 snapshotCleanupStateStore.set(on); 1944 if (on) { 1945 getChoreService().scheduleChore(this.snapshotCleanerChore); 1946 } else { 1947 this.snapshotCleanerChore.cancel(); 1948 } 1949 } 1950 1951 private void stopProcedureExecutor() { 1952 if (procedureExecutor != null) { 1953 configurationManager.deregisterObserver(procedureExecutor.getEnvironment()); 1954 procedureExecutor.getEnvironment().getRemoteDispatcher().stop(); 1955 procedureExecutor.stop(); 1956 procedureExecutor.join(); 1957 procedureExecutor = null; 1958 } 1959 1960 if (procedureStore != null) { 1961 procedureStore.stop(isAborted()); 1962 procedureStore = null; 1963 } 1964 } 1965 1966 protected void stopChores() { 1967 shutdownChore(mobFileCleanerChore); 1968 shutdownChore(mobFileCompactionChore); 1969 shutdownChore(balancerChore); 1970 if (regionNormalizerManager != null) { 1971 shutdownChore(regionNormalizerManager.getRegionNormalizerChore()); 1972 } 1973 shutdownChore(clusterStatusChore); 1974 shutdownChore(catalogJanitorChore); 1975 shutdownChore(clusterStatusPublisherChore); 1976 shutdownChore(snapshotQuotaChore); 1977 shutdownChore(logCleaner); 1978 if (hfileCleaners != null) { 1979 for (ScheduledChore chore : hfileCleaners) { 1980 chore.shutdown(); 1981 } 1982 hfileCleaners = null; 1983 } 1984 shutdownChore(replicationBarrierCleaner); 1985 shutdownChore(snapshotCleanerChore); 1986 shutdownChore(hbckChore); 1987 shutdownChore(regionsRecoveryChore); 1988 shutdownChore(rollingUpgradeChore); 1989 shutdownChore(oldWALsDirSizeChore); 1990 } 1991 1992 /** Returns Get remote side's InetAddress */ 1993 InetAddress getRemoteInetAddress(final int port, final long serverStartCode) 1994 throws UnknownHostException { 1995 // Do it out here in its own little method so can fake an address when 1996 // mocking up in tests. 1997 InetAddress ia = RpcServer.getRemoteIp(); 1998 1999 // The call could be from the local regionserver, 2000 // in which case, there is no remote address. 2001 if (ia == null && serverStartCode == startcode) { 2002 InetSocketAddress isa = rpcServices.getSocketAddress(); 2003 if (isa != null && isa.getPort() == port) { 2004 ia = isa.getAddress(); 2005 } 2006 } 2007 return ia; 2008 } 2009 2010 /** Returns Maximum time we should run balancer for */ 2011 private int getMaxBalancingTime() { 2012 // if max balancing time isn't set, defaulting it to period time 2013 int maxBalancingTime = 2014 getConfiguration().getInt(HConstants.HBASE_BALANCER_MAX_BALANCING, getConfiguration() 2015 .getInt(HConstants.HBASE_BALANCER_PERIOD, HConstants.DEFAULT_HBASE_BALANCER_PERIOD)); 2016 return maxBalancingTime; 2017 } 2018 2019 /** Returns Maximum number of regions in transition */ 2020 private int getMaxRegionsInTransition() { 2021 int numRegions = this.assignmentManager.getRegionStates().getRegionAssignments().size(); 2022 return Math.max((int) Math.floor(numRegions * this.maxRitPercent), 1); 2023 } 2024 2025 /** 2026 * It first sleep to the next balance plan start time. Meanwhile, throttling by the max number 2027 * regions in transition to protect availability. 2028 * @param nextBalanceStartTime The next balance plan start time 2029 * @param maxRegionsInTransition max number of regions in transition 2030 * @param cutoffTime when to exit balancer 2031 */ 2032 private void balanceThrottling(long nextBalanceStartTime, int maxRegionsInTransition, 2033 long cutoffTime) { 2034 boolean interrupted = false; 2035 2036 // Sleep to next balance plan start time 2037 // But if there are zero regions in transition, it can skip sleep to speed up. 2038 while ( 2039 !interrupted && EnvironmentEdgeManager.currentTime() < nextBalanceStartTime 2040 && this.assignmentManager.getRegionTransitScheduledCount() > 0 2041 ) { 2042 try { 2043 Thread.sleep(100); 2044 } catch (InterruptedException ie) { 2045 interrupted = true; 2046 } 2047 } 2048 2049 // Throttling by max number regions in transition 2050 while ( 2051 !interrupted && maxRegionsInTransition > 0 2052 && this.assignmentManager.getRegionTransitScheduledCount() >= maxRegionsInTransition 2053 && EnvironmentEdgeManager.currentTime() <= cutoffTime 2054 ) { 2055 try { 2056 // sleep if the number of regions in transition exceeds the limit 2057 Thread.sleep(100); 2058 } catch (InterruptedException ie) { 2059 interrupted = true; 2060 } 2061 } 2062 2063 if (interrupted) Thread.currentThread().interrupt(); 2064 } 2065 2066 public BalanceResponse balance() throws IOException { 2067 return balance(BalanceRequest.defaultInstance()); 2068 } 2069 2070 /** 2071 * Trigger a normal balance, see {@link HMaster#balance()} . If the balance is not executed this 2072 * time, the metrics related to the balance will be updated. When balance is running, related 2073 * metrics will be updated at the same time. But if some checking logic failed and cause the 2074 * balancer exit early, we lost the chance to update balancer metrics. This will lead to user 2075 * missing the latest balancer info. 2076 */ 2077 public BalanceResponse balanceOrUpdateMetrics() throws IOException { 2078 synchronized (this.balancer) { 2079 BalanceResponse response = balance(); 2080 if (!response.isBalancerRan()) { 2081 Map<TableName, Map<ServerName, List<RegionInfo>>> assignments = 2082 this.assignmentManager.getRegionStates().getAssignmentsForBalancer(this.tableStateManager, 2083 this.serverManager.getOnlineServersList()); 2084 for (Map<ServerName, List<RegionInfo>> serverMap : assignments.values()) { 2085 serverMap.keySet().removeAll(this.serverManager.getDrainingServersList()); 2086 } 2087 this.balancer.updateBalancerLoadInfo(assignments); 2088 } 2089 return response; 2090 } 2091 } 2092 2093 /** 2094 * Checks master state before initiating action over region topology. 2095 * @param action the name of the action under consideration, for logging. 2096 * @return {@code true} when the caller should exit early, {@code false} otherwise. 2097 */ 2098 @Override 2099 public boolean skipRegionManagementAction(final String action) { 2100 // Note: this method could be `default` on MasterServices if but for logging. 2101 if (!isInitialized()) { 2102 LOG.debug("Master has not been initialized, don't run {}.", action); 2103 return true; 2104 } 2105 if (this.getServerManager().isClusterShutdown()) { 2106 LOG.info("Cluster is shutting down, don't run {}.", action); 2107 return true; 2108 } 2109 if (isInMaintenanceMode()) { 2110 LOG.info("Master is in maintenance mode, don't run {}.", action); 2111 return true; 2112 } 2113 return false; 2114 } 2115 2116 public BalanceResponse balance(BalanceRequest request) throws IOException { 2117 checkInitialized(); 2118 2119 BalanceResponse.Builder responseBuilder = BalanceResponse.newBuilder(); 2120 2121 if (loadBalancerStateStore == null || !(loadBalancerStateStore.get() || request.isDryRun())) { 2122 return responseBuilder.build(); 2123 } 2124 2125 if (skipRegionManagementAction("balancer")) { 2126 return responseBuilder.build(); 2127 } 2128 2129 synchronized (this.balancer) { 2130 try { 2131 this.balancer.onBalancingStart(); 2132 // Only allow one balance run at at time. 2133 if (this.assignmentManager.getRegionTransitScheduledCount() > 0) { 2134 List<RegionStateNode> regionsInTransition = assignmentManager.getRegionsInTransition(); 2135 // if hbase:meta region is in transition, result of assignment cannot be recorded 2136 // ignore the force flag in that case 2137 boolean metaInTransition = assignmentManager.isMetaRegionInTransition(); 2138 List<RegionStateNode> toPrint = regionsInTransition; 2139 int max = 5; 2140 boolean truncated = false; 2141 if (regionsInTransition.size() > max) { 2142 toPrint = regionsInTransition.subList(0, max); 2143 truncated = true; 2144 } 2145 2146 if (!request.isIgnoreRegionsInTransition() || metaInTransition) { 2147 LOG.info("Not running balancer (ignoreRIT=false" + ", metaRIT=" + metaInTransition 2148 + ") because " + assignmentManager.getRegionTransitScheduledCount() 2149 + " region(s) are scheduled to transit " + toPrint 2150 + (truncated ? "(truncated list)" : "")); 2151 return responseBuilder.build(); 2152 } 2153 } 2154 if (this.serverManager.areDeadServersInProgress()) { 2155 LOG.info("Not running balancer because processing dead regionserver(s): " 2156 + this.serverManager.getDeadServers()); 2157 return responseBuilder.build(); 2158 } 2159 2160 if (this.cpHost != null) { 2161 try { 2162 if (this.cpHost.preBalance(request)) { 2163 LOG.debug("Coprocessor bypassing balancer request"); 2164 return responseBuilder.build(); 2165 } 2166 } catch (IOException ioe) { 2167 LOG.error("Error invoking master coprocessor preBalance()", ioe); 2168 return responseBuilder.build(); 2169 } 2170 } 2171 2172 Map<TableName, Map<ServerName, List<RegionInfo>>> assignments = 2173 this.assignmentManager.getRegionStates().getAssignmentsForBalancer(tableStateManager, 2174 this.serverManager.getOnlineServersList()); 2175 for (Map<ServerName, List<RegionInfo>> serverMap : assignments.values()) { 2176 serverMap.keySet().removeAll(this.serverManager.getDrainingServersList()); 2177 } 2178 2179 // Give the balancer the current cluster state. 2180 this.balancer.updateClusterMetrics(getClusterMetricsWithoutCoprocessor()); 2181 2182 List<RegionPlan> plans = this.balancer.balanceCluster(assignments); 2183 2184 responseBuilder.setBalancerRan(true).setMovesCalculated(plans == null ? 0 : plans.size()); 2185 2186 if (skipRegionManagementAction("balancer")) { 2187 // make one last check that the cluster isn't shutting down before proceeding. 2188 return responseBuilder.build(); 2189 } 2190 2191 // For dry run we don't actually want to execute the moves, but we do want 2192 // to execute the coprocessor below 2193 List<RegionPlan> sucRPs = 2194 request.isDryRun() ? Collections.emptyList() : executeRegionPlansWithThrottling(plans); 2195 2196 if (this.cpHost != null) { 2197 try { 2198 this.cpHost.postBalance(request, sucRPs); 2199 } catch (IOException ioe) { 2200 // balancing already succeeded so don't change the result 2201 LOG.error("Error invoking master coprocessor postBalance()", ioe); 2202 } 2203 } 2204 2205 responseBuilder.setMovesExecuted(sucRPs.size()); 2206 } finally { 2207 this.balancer.onBalancingComplete(); 2208 } 2209 } 2210 2211 // If LoadBalancer did not generate any plans, it means the cluster is already balanced. 2212 // Return true indicating a success. 2213 return responseBuilder.build(); 2214 } 2215 2216 /** 2217 * Execute region plans with throttling 2218 * @param plans to execute 2219 * @return succeeded plans 2220 */ 2221 public List<RegionPlan> executeRegionPlansWithThrottling(List<RegionPlan> plans) { 2222 List<RegionPlan> successRegionPlans = new ArrayList<>(); 2223 int maxRegionsInTransition = getMaxRegionsInTransition(); 2224 long balanceStartTime = EnvironmentEdgeManager.currentTime(); 2225 long cutoffTime = balanceStartTime + this.maxBalancingTime; 2226 int rpCount = 0; // number of RegionPlans balanced so far 2227 if (plans != null && !plans.isEmpty()) { 2228 int balanceInterval = this.maxBalancingTime / plans.size(); 2229 LOG.info( 2230 "Balancer plans size is " + plans.size() + ", the balance interval is " + balanceInterval 2231 + " ms, and the max number regions in transition is " + maxRegionsInTransition); 2232 2233 for (RegionPlan plan : plans) { 2234 LOG.info("balance " + plan); 2235 // TODO: bulk assign 2236 try { 2237 this.assignmentManager.balance(plan); 2238 this.balancer.updateClusterMetrics(getClusterMetricsWithoutCoprocessor()); 2239 this.balancer.throttle(plan); 2240 } catch (HBaseIOException hioe) { 2241 // should ignore failed plans here, avoiding the whole balance plans be aborted 2242 // later calls of balance() can fetch up the failed and skipped plans 2243 LOG.warn("Failed balance plan {}, skipping...", plan, hioe); 2244 } catch (Exception e) { 2245 LOG.warn("Failed throttling assigning a new plan.", e); 2246 } 2247 // rpCount records balance plans processed, does not care if a plan succeeds 2248 rpCount++; 2249 successRegionPlans.add(plan); 2250 2251 if (this.maxBalancingTime > 0) { 2252 balanceThrottling(balanceStartTime + rpCount * balanceInterval, maxRegionsInTransition, 2253 cutoffTime); 2254 } 2255 2256 // if performing next balance exceeds cutoff time, exit the loop 2257 if ( 2258 this.maxBalancingTime > 0 && rpCount < plans.size() 2259 && EnvironmentEdgeManager.currentTime() > cutoffTime 2260 ) { 2261 // TODO: After balance, there should not be a cutoff time (keeping it as 2262 // a security net for now) 2263 LOG.debug( 2264 "No more balancing till next balance run; maxBalanceTime=" + this.maxBalancingTime); 2265 break; 2266 } 2267 } 2268 } 2269 LOG.debug("Balancer is going into sleep until next period in {}ms", getConfiguration() 2270 .getInt(HConstants.HBASE_BALANCER_PERIOD, HConstants.DEFAULT_HBASE_BALANCER_PERIOD)); 2271 return successRegionPlans; 2272 } 2273 2274 @Override 2275 public RegionNormalizerManager getRegionNormalizerManager() { 2276 return regionNormalizerManager; 2277 } 2278 2279 @Override 2280 public boolean normalizeRegions(final NormalizeTableFilterParams ntfp, 2281 final boolean isHighPriority) throws IOException { 2282 if (regionNormalizerManager == null || !regionNormalizerManager.isNormalizerOn()) { 2283 LOG.debug("Region normalization is disabled, don't run region normalizer."); 2284 return false; 2285 } 2286 if (skipRegionManagementAction("region normalizer")) { 2287 return false; 2288 } 2289 if (assignmentManager.getRegionTransitScheduledCount() > 0) { 2290 return false; 2291 } 2292 2293 final Set<TableName> matchingTables = getTableDescriptors(new LinkedList<>(), 2294 ntfp.getNamespace(), ntfp.getRegex(), ntfp.getTableNames(), false).stream() 2295 .map(TableDescriptor::getTableName).collect(Collectors.toSet()); 2296 final Set<TableName> allEnabledTables = 2297 tableStateManager.getTablesInStates(TableState.State.ENABLED); 2298 final List<TableName> targetTables = 2299 new ArrayList<>(Sets.intersection(matchingTables, allEnabledTables)); 2300 Collections.shuffle(targetTables); 2301 return regionNormalizerManager.normalizeRegions(targetTables, isHighPriority); 2302 } 2303 2304 /** Returns Client info for use as prefix on an audit log string; who did an action */ 2305 @Override 2306 public String getClientIdAuditPrefix() { 2307 return "Client=" + RpcServer.getRequestUserName().orElse(null) + "/" 2308 + RpcServer.getRemoteAddress().orElse(null); 2309 } 2310 2311 /** 2312 * Switch for the background CatalogJanitor thread. Used for testing. The thread will continue to 2313 * run. It will just be a noop if disabled. 2314 * @param b If false, the catalog janitor won't do anything. 2315 */ 2316 public void setCatalogJanitorEnabled(final boolean b) { 2317 this.catalogJanitorChore.setEnabled(b); 2318 } 2319 2320 @Override 2321 public long mergeRegions(final RegionInfo[] regionsToMerge, final boolean forcible, final long ng, 2322 final long nonce) throws IOException { 2323 checkInitialized(); 2324 2325 final String regionNamesToLog = RegionInfo.getShortNameToLog(regionsToMerge); 2326 2327 if (!isSplitOrMergeEnabled(MasterSwitchType.MERGE)) { 2328 LOG.warn("Merge switch is off! skip merge of " + regionNamesToLog); 2329 throw new DoNotRetryIOException( 2330 "Merge of " + regionNamesToLog + " failed because merge switch is off"); 2331 } 2332 2333 if (!getTableDescriptors().get(regionsToMerge[0].getTable()).isMergeEnabled()) { 2334 LOG.warn("Merge is disabled for the table! Skipping merge of {}", regionNamesToLog); 2335 throw new DoNotRetryIOException( 2336 "Merge of " + regionNamesToLog + " failed as region merge is disabled for the table"); 2337 } 2338 2339 return MasterProcedureUtil.submitProcedure(new NonceProcedureRunnable(this, ng, nonce) { 2340 @Override 2341 protected void run() throws IOException { 2342 getMaster().getMasterCoprocessorHost().preMergeRegions(regionsToMerge); 2343 String aid = getClientIdAuditPrefix(); 2344 LOG.info("{} merge regions {}", aid, regionNamesToLog); 2345 submitProcedure(new MergeTableRegionsProcedure(procedureExecutor.getEnvironment(), 2346 regionsToMerge, forcible)); 2347 getMaster().getMasterCoprocessorHost().postMergeRegions(regionsToMerge); 2348 } 2349 2350 @Override 2351 protected String getDescription() { 2352 return "MergeTableProcedure"; 2353 } 2354 }); 2355 } 2356 2357 @Override 2358 public long splitRegion(final RegionInfo regionInfo, final byte[] splitRow, final long nonceGroup, 2359 final long nonce) throws IOException { 2360 checkInitialized(); 2361 2362 if (!isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { 2363 LOG.warn("Split switch is off! skip split of " + regionInfo); 2364 throw new DoNotRetryIOException( 2365 "Split region " + regionInfo.getRegionNameAsString() + " failed due to split switch off"); 2366 } 2367 2368 if (!getTableDescriptors().get(regionInfo.getTable()).isSplitEnabled()) { 2369 LOG.warn("Split is disabled for the table! Skipping split of {}", regionInfo); 2370 throw new DoNotRetryIOException("Split region " + regionInfo.getRegionNameAsString() 2371 + " failed as region split is disabled for the table"); 2372 } 2373 2374 return MasterProcedureUtil 2375 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2376 @Override 2377 protected void run() throws IOException { 2378 getMaster().getMasterCoprocessorHost().preSplitRegion(regionInfo.getTable(), splitRow); 2379 LOG.info(getClientIdAuditPrefix() + " split " + regionInfo.getRegionNameAsString()); 2380 2381 // Execute the operation asynchronously 2382 submitProcedure(getAssignmentManager().createSplitProcedure(regionInfo, splitRow)); 2383 } 2384 2385 @Override 2386 protected String getDescription() { 2387 return "SplitTableProcedure"; 2388 } 2389 }); 2390 } 2391 2392 private void warmUpRegion(ServerName server, RegionInfo region) { 2393 FutureUtils.addListener(asyncClusterConnection.getRegionServerAdmin(server) 2394 .warmupRegion(RequestConverter.buildWarmupRegionRequest(region)), (r, e) -> { 2395 if (e != null) { 2396 LOG.warn("Failed to warm up region {} on server {}", region, server, e); 2397 } 2398 }); 2399 } 2400 2401 // Public so can be accessed by tests. Blocks until move is done. 2402 // Replace with an async implementation from which you can get 2403 // a success/failure result. 2404 @InterfaceAudience.Private 2405 public void move(final byte[] encodedRegionName, byte[] destServerName) throws IOException { 2406 RegionState regionState = 2407 assignmentManager.getRegionStates().getRegionState(Bytes.toString(encodedRegionName)); 2408 2409 RegionInfo hri; 2410 if (regionState != null) { 2411 hri = regionState.getRegion(); 2412 } else { 2413 throw new UnknownRegionException(Bytes.toStringBinary(encodedRegionName)); 2414 } 2415 2416 ServerName dest; 2417 List<ServerName> exclude = hri.getTable().isSystemTable() 2418 ? assignmentManager.getExcludedServersForSystemTable() 2419 : new ArrayList<>(1); 2420 if ( 2421 destServerName != null && exclude.contains(ServerName.valueOf(Bytes.toString(destServerName))) 2422 ) { 2423 LOG.info(Bytes.toString(encodedRegionName) + " can not move to " 2424 + Bytes.toString(destServerName) + " because the server is in exclude list"); 2425 destServerName = null; 2426 } 2427 if (destServerName == null || destServerName.length == 0) { 2428 LOG.info("Passed destination servername is null/empty so " + "choosing a server at random"); 2429 exclude.add(regionState.getServerName()); 2430 final List<ServerName> destServers = this.serverManager.createDestinationServersList(exclude); 2431 dest = balancer.randomAssignment(hri, destServers); 2432 if (dest == null) { 2433 LOG.debug("Unable to determine a plan to assign " + hri); 2434 return; 2435 } 2436 } else { 2437 ServerName candidate = ServerName.valueOf(Bytes.toString(destServerName)); 2438 dest = balancer.randomAssignment(hri, Lists.newArrayList(candidate)); 2439 if (dest == null) { 2440 LOG.debug("Unable to determine a plan to assign " + hri); 2441 return; 2442 } 2443 // TODO: deal with table on master for rs group. 2444 if (dest.equals(serverName)) { 2445 // To avoid unnecessary region moving later by balancer. Don't put user 2446 // regions on master. 2447 LOG.debug("Skipping move of region " + hri.getRegionNameAsString() 2448 + " to avoid unnecessary region moving later by load balancer," 2449 + " because it should not be on master"); 2450 return; 2451 } 2452 } 2453 2454 if (dest.equals(regionState.getServerName())) { 2455 LOG.debug("Skipping move of region " + hri.getRegionNameAsString() 2456 + " because region already assigned to the same server " + dest + "."); 2457 return; 2458 } 2459 2460 // Now we can do the move 2461 RegionPlan rp = new RegionPlan(hri, regionState.getServerName(), dest); 2462 assert rp.getDestination() != null : rp.toString() + " " + dest; 2463 2464 try { 2465 checkInitialized(); 2466 if (this.cpHost != null) { 2467 this.cpHost.preMove(hri, rp.getSource(), rp.getDestination()); 2468 } 2469 2470 TransitRegionStateProcedure proc = 2471 this.assignmentManager.createMoveRegionProcedure(rp.getRegionInfo(), rp.getDestination()); 2472 if (conf.getBoolean(WARMUP_BEFORE_MOVE, DEFAULT_WARMUP_BEFORE_MOVE)) { 2473 // Warmup the region on the destination before initiating the move. 2474 // A region server could reject the close request because it either does not 2475 // have the specified region or the region is being split. 2476 LOG.info(getClientIdAuditPrefix() + " move " + rp + ", warming up region on " 2477 + rp.getDestination()); 2478 warmUpRegion(rp.getDestination(), hri); 2479 } 2480 LOG.info(getClientIdAuditPrefix() + " move " + rp + ", running balancer"); 2481 Future<byte[]> future = ProcedureSyncWait.submitProcedure(this.procedureExecutor, proc); 2482 try { 2483 // Is this going to work? Will we throw exception on error? 2484 // TODO: CompletableFuture rather than this stunted Future. 2485 future.get(); 2486 } catch (InterruptedException | ExecutionException e) { 2487 throw new HBaseIOException(e); 2488 } 2489 if (this.cpHost != null) { 2490 this.cpHost.postMove(hri, rp.getSource(), rp.getDestination()); 2491 } 2492 } catch (IOException ioe) { 2493 if (ioe instanceof HBaseIOException) { 2494 throw (HBaseIOException) ioe; 2495 } 2496 throw new HBaseIOException(ioe); 2497 } 2498 } 2499 2500 @Override 2501 public long createTable(final TableDescriptor tableDescriptor, final byte[][] splitKeys, 2502 final long nonceGroup, final long nonce) throws IOException { 2503 checkInitialized(); 2504 TableDescriptor desc = getMasterCoprocessorHost().preCreateTableRegionsInfos(tableDescriptor); 2505 if (desc == null) { 2506 throw new IOException("Creation for " + tableDescriptor + " is canceled by CP"); 2507 } 2508 String namespace = desc.getTableName().getNamespaceAsString(); 2509 this.clusterSchemaService.getNamespace(namespace); 2510 2511 RegionInfo[] newRegions = ModifyRegionUtils.createRegionInfos(desc, splitKeys); 2512 TableDescriptorChecker.sanityCheck(conf, desc); 2513 2514 return MasterProcedureUtil 2515 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2516 @Override 2517 protected void run() throws IOException { 2518 getMaster().getMasterCoprocessorHost().preCreateTable(desc, newRegions); 2519 2520 LOG.info(getClientIdAuditPrefix() + " create " + desc); 2521 2522 // TODO: We can handle/merge duplicate requests, and differentiate the case of 2523 // TableExistsException by saying if the schema is the same or not. 2524 // 2525 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2526 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2527 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 2528 submitProcedure( 2529 new CreateTableProcedure(procedureExecutor.getEnvironment(), desc, newRegions, latch)); 2530 latch.await(); 2531 2532 getMaster().getMasterCoprocessorHost().postCreateTable(desc, newRegions); 2533 } 2534 2535 @Override 2536 protected String getDescription() { 2537 return "CreateTableProcedure"; 2538 } 2539 }); 2540 } 2541 2542 @Override 2543 public long createSystemTable(final TableDescriptor tableDescriptor) throws IOException { 2544 return createSystemTable(tableDescriptor, false); 2545 } 2546 2547 private long createSystemTable(final TableDescriptor tableDescriptor, final boolean isCritical) 2548 throws IOException { 2549 if (isStopped()) { 2550 throw new MasterNotRunningException(); 2551 } 2552 2553 TableName tableName = tableDescriptor.getTableName(); 2554 if (!(tableName.isSystemTable())) { 2555 throw new IllegalArgumentException( 2556 "Only system table creation can use this createSystemTable API"); 2557 } 2558 2559 RegionInfo[] newRegions = ModifyRegionUtils.createRegionInfos(tableDescriptor, null); 2560 2561 LOG.info(getClientIdAuditPrefix() + " create " + tableDescriptor); 2562 2563 // This special create table is called locally to master. Therefore, no RPC means no need 2564 // to use nonce to detect duplicated RPC call. 2565 CreateTableProcedure proc = 2566 new CreateTableProcedure(procedureExecutor.getEnvironment(), tableDescriptor, newRegions); 2567 proc.setCriticalSystemTable(isCritical); 2568 return this.procedureExecutor.submitProcedure(proc); 2569 } 2570 2571 private void startActiveMasterManager(int infoPort) throws KeeperException { 2572 String backupZNode = ZNodePaths.joinZNode(zooKeeper.getZNodePaths().backupMasterAddressesZNode, 2573 serverName.toString()); 2574 /* 2575 * Add a ZNode for ourselves in the backup master directory since we may not become the active 2576 * master. If so, we want the actual active master to know we are backup masters, so that it 2577 * won't assign regions to us if so configured. If we become the active master later, 2578 * ActiveMasterManager will delete this node explicitly. If we crash before then, ZooKeeper will 2579 * delete this node for us since it is ephemeral. 2580 */ 2581 LOG.info("Adding backup master ZNode " + backupZNode); 2582 if (!MasterAddressTracker.setMasterAddress(zooKeeper, backupZNode, serverName, infoPort)) { 2583 LOG.warn("Failed create of " + backupZNode + " by " + serverName); 2584 } 2585 this.activeMasterManager.setInfoPort(infoPort); 2586 int timeout = conf.getInt(HConstants.ZK_SESSION_TIMEOUT, HConstants.DEFAULT_ZK_SESSION_TIMEOUT); 2587 // If we're a backup master, stall until a primary to write this address 2588 if (conf.getBoolean(HConstants.MASTER_TYPE_BACKUP, HConstants.DEFAULT_MASTER_TYPE_BACKUP)) { 2589 LOG.debug("HMaster started in backup mode. Stalling until master znode is written."); 2590 // This will only be a minute or so while the cluster starts up, 2591 // so don't worry about setting watches on the parent znode 2592 while (!activeMasterManager.hasActiveMaster()) { 2593 LOG.debug("Waiting for master address and cluster state znode to be written."); 2594 Threads.sleep(timeout); 2595 } 2596 } 2597 2598 // Here for the master startup process, we use TaskGroup to monitor the whole progress. 2599 // The UI is similar to how Hadoop designed the startup page for the NameNode. 2600 // See HBASE-21521 for more details. 2601 // We do not cleanup the startupTaskGroup, let the startup progress information 2602 // be permanent in the MEM. 2603 startupTaskGroup = TaskMonitor.createTaskGroup(true, "Master startup"); 2604 try { 2605 if (activeMasterManager.blockUntilBecomingActiveMaster(timeout, startupTaskGroup)) { 2606 finishActiveMasterInitialization(); 2607 } 2608 } catch (Throwable t) { 2609 startupTaskGroup.abort("Failed to become active master due to:" + t.getMessage()); 2610 LOG.error(HBaseMarkers.FATAL, "Failed to become active master", t); 2611 // HBASE-5680: Likely hadoop23 vs hadoop 20.x/1.x incompatibility 2612 if ( 2613 t instanceof NoClassDefFoundError 2614 && t.getMessage().contains("org/apache/hadoop/hdfs/protocol/HdfsConstants$SafeModeAction") 2615 ) { 2616 // improved error message for this special case 2617 abort("HBase is having a problem with its Hadoop jars. You may need to recompile " 2618 + "HBase against Hadoop version " + org.apache.hadoop.util.VersionInfo.getVersion() 2619 + " or change your hadoop jars to start properly", t); 2620 } else { 2621 abort("Unhandled exception. Starting shutdown.", t); 2622 } 2623 } 2624 } 2625 2626 private static boolean isCatalogTable(final TableName tableName) { 2627 return tableName.equals(TableName.META_TABLE_NAME); 2628 } 2629 2630 @Override 2631 public long deleteTable(final TableName tableName, final long nonceGroup, final long nonce) 2632 throws IOException { 2633 checkInitialized(); 2634 2635 return MasterProcedureUtil 2636 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2637 @Override 2638 protected void run() throws IOException { 2639 getMaster().getMasterCoprocessorHost().preDeleteTable(tableName); 2640 2641 LOG.info(getClientIdAuditPrefix() + " delete " + tableName); 2642 2643 // TODO: We can handle/merge duplicate request 2644 // 2645 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2646 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2647 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 2648 submitProcedure( 2649 new DeleteTableProcedure(procedureExecutor.getEnvironment(), tableName, latch)); 2650 latch.await(); 2651 2652 getMaster().getMasterCoprocessorHost().postDeleteTable(tableName); 2653 } 2654 2655 @Override 2656 protected String getDescription() { 2657 return "DeleteTableProcedure"; 2658 } 2659 }); 2660 } 2661 2662 @Override 2663 public long truncateTable(final TableName tableName, final boolean preserveSplits, 2664 final long nonceGroup, final long nonce) throws IOException { 2665 checkInitialized(); 2666 2667 return MasterProcedureUtil 2668 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2669 @Override 2670 protected void run() throws IOException { 2671 getMaster().getMasterCoprocessorHost().preTruncateTable(tableName); 2672 2673 LOG.info(getClientIdAuditPrefix() + " truncate " + tableName); 2674 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createLatch(2, 0); 2675 submitProcedure(new TruncateTableProcedure(procedureExecutor.getEnvironment(), tableName, 2676 preserveSplits, latch)); 2677 latch.await(); 2678 2679 getMaster().getMasterCoprocessorHost().postTruncateTable(tableName); 2680 } 2681 2682 @Override 2683 protected String getDescription() { 2684 return "TruncateTableProcedure"; 2685 } 2686 }); 2687 } 2688 2689 @Override 2690 public long truncateRegion(final RegionInfo regionInfo, final long nonceGroup, final long nonce) 2691 throws IOException { 2692 checkInitialized(); 2693 2694 return MasterProcedureUtil 2695 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2696 @Override 2697 protected void run() throws IOException { 2698 getMaster().getMasterCoprocessorHost().preTruncateRegion(regionInfo); 2699 2700 LOG.info( 2701 getClientIdAuditPrefix() + " truncate region " + regionInfo.getRegionNameAsString()); 2702 2703 // Execute the operation asynchronously 2704 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createLatch(2, 0); 2705 submitProcedure( 2706 new TruncateRegionProcedure(procedureExecutor.getEnvironment(), regionInfo, latch)); 2707 latch.await(); 2708 2709 getMaster().getMasterCoprocessorHost().postTruncateRegion(regionInfo); 2710 } 2711 2712 @Override 2713 protected String getDescription() { 2714 return "TruncateRegionProcedure"; 2715 } 2716 }); 2717 } 2718 2719 @Override 2720 public long addColumn(final TableName tableName, final ColumnFamilyDescriptor column, 2721 final long nonceGroup, final long nonce) throws IOException { 2722 checkInitialized(); 2723 checkTableExists(tableName); 2724 2725 return modifyTable(tableName, new TableDescriptorGetter() { 2726 2727 @Override 2728 public TableDescriptor get() throws IOException { 2729 TableDescriptor old = getTableDescriptors().get(tableName); 2730 if (old.hasColumnFamily(column.getName())) { 2731 throw new InvalidFamilyOperationException("Column family '" + column.getNameAsString() 2732 + "' in table '" + tableName + "' already exists so cannot be added"); 2733 } 2734 2735 return TableDescriptorBuilder.newBuilder(old).setColumnFamily(column).build(); 2736 } 2737 }, nonceGroup, nonce, true); 2738 } 2739 2740 /** 2741 * Implement to return TableDescriptor after pre-checks 2742 */ 2743 protected interface TableDescriptorGetter { 2744 TableDescriptor get() throws IOException; 2745 } 2746 2747 @Override 2748 public long modifyColumn(final TableName tableName, final ColumnFamilyDescriptor descriptor, 2749 final long nonceGroup, final long nonce) throws IOException { 2750 checkInitialized(); 2751 checkTableExists(tableName); 2752 return modifyTable(tableName, new TableDescriptorGetter() { 2753 2754 @Override 2755 public TableDescriptor get() throws IOException { 2756 TableDescriptor old = getTableDescriptors().get(tableName); 2757 if (!old.hasColumnFamily(descriptor.getName())) { 2758 throw new InvalidFamilyOperationException("Family '" + descriptor.getNameAsString() 2759 + "' does not exist, so it cannot be modified"); 2760 } 2761 2762 return TableDescriptorBuilder.newBuilder(old).modifyColumnFamily(descriptor).build(); 2763 } 2764 }, nonceGroup, nonce, true); 2765 } 2766 2767 @Override 2768 public long modifyColumnStoreFileTracker(TableName tableName, byte[] family, String dstSFT, 2769 long nonceGroup, long nonce) throws IOException { 2770 checkInitialized(); 2771 return MasterProcedureUtil 2772 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2773 2774 @Override 2775 protected void run() throws IOException { 2776 String sft = getMaster().getMasterCoprocessorHost() 2777 .preModifyColumnFamilyStoreFileTracker(tableName, family, dstSFT); 2778 LOG.info("{} modify column {} store file tracker of table {} to {}", 2779 getClientIdAuditPrefix(), Bytes.toStringBinary(family), tableName, sft); 2780 submitProcedure(new ModifyColumnFamilyStoreFileTrackerProcedure( 2781 procedureExecutor.getEnvironment(), tableName, family, sft)); 2782 getMaster().getMasterCoprocessorHost().postModifyColumnFamilyStoreFileTracker(tableName, 2783 family, dstSFT); 2784 } 2785 2786 @Override 2787 protected String getDescription() { 2788 return "ModifyColumnFamilyStoreFileTrackerProcedure"; 2789 } 2790 }); 2791 } 2792 2793 @Override 2794 public long deleteColumn(final TableName tableName, final byte[] columnName, 2795 final long nonceGroup, final long nonce) throws IOException { 2796 checkInitialized(); 2797 checkTableExists(tableName); 2798 2799 return modifyTable(tableName, new TableDescriptorGetter() { 2800 2801 @Override 2802 public TableDescriptor get() throws IOException { 2803 TableDescriptor old = getTableDescriptors().get(tableName); 2804 2805 if (!old.hasColumnFamily(columnName)) { 2806 throw new InvalidFamilyOperationException( 2807 "Family '" + Bytes.toString(columnName) + "' does not exist, so it cannot be deleted"); 2808 } 2809 if (old.getColumnFamilyCount() == 1) { 2810 throw new InvalidFamilyOperationException("Family '" + Bytes.toString(columnName) 2811 + "' is the only column family in the table, so it cannot be deleted"); 2812 } 2813 return TableDescriptorBuilder.newBuilder(old).removeColumnFamily(columnName).build(); 2814 } 2815 }, nonceGroup, nonce, true); 2816 } 2817 2818 @Override 2819 public long enableTable(final TableName tableName, final long nonceGroup, final long nonce) 2820 throws IOException { 2821 checkInitialized(); 2822 2823 return MasterProcedureUtil 2824 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2825 @Override 2826 protected void run() throws IOException { 2827 getMaster().getMasterCoprocessorHost().preEnableTable(tableName); 2828 2829 // Normally, it would make sense for this authorization check to exist inside 2830 // AccessController, but because the authorization check is done based on internal state 2831 // (rather than explicit permissions) we'll do the check here instead of in the 2832 // coprocessor. 2833 MasterQuotaManager quotaManager = getMasterQuotaManager(); 2834 if (quotaManager != null) { 2835 if (quotaManager.isQuotaInitialized()) { 2836 // skip checking quotas for system tables, see: 2837 // https://issues.apache.org/jira/browse/HBASE-28183 2838 if (!tableName.isSystemTable()) { 2839 SpaceQuotaSnapshot currSnapshotOfTable = 2840 QuotaTableUtil.getCurrentSnapshotFromQuotaTable(getConnection(), tableName); 2841 if (currSnapshotOfTable != null) { 2842 SpaceQuotaStatus quotaStatus = currSnapshotOfTable.getQuotaStatus(); 2843 if ( 2844 quotaStatus.isInViolation() 2845 && SpaceViolationPolicy.DISABLE == quotaStatus.getPolicy().orElse(null) 2846 ) { 2847 throw new AccessDeniedException("Enabling the table '" + tableName 2848 + "' is disallowed due to a violated space quota."); 2849 } 2850 } 2851 } 2852 } else if (LOG.isTraceEnabled()) { 2853 LOG 2854 .trace("Unable to check for space quotas as the MasterQuotaManager is not enabled"); 2855 } 2856 } 2857 2858 LOG.info(getClientIdAuditPrefix() + " enable " + tableName); 2859 2860 // Execute the operation asynchronously - client will check the progress of the operation 2861 // In case the request is from a <1.1 client before returning, 2862 // we want to make sure that the table is prepared to be 2863 // enabled (the table is locked and the table state is set). 2864 // Note: if the procedure throws exception, we will catch it and rethrow. 2865 final ProcedurePrepareLatch prepareLatch = ProcedurePrepareLatch.createLatch(); 2866 submitProcedure( 2867 new EnableTableProcedure(procedureExecutor.getEnvironment(), tableName, prepareLatch)); 2868 prepareLatch.await(); 2869 2870 getMaster().getMasterCoprocessorHost().postEnableTable(tableName); 2871 } 2872 2873 @Override 2874 protected String getDescription() { 2875 return "EnableTableProcedure"; 2876 } 2877 }); 2878 } 2879 2880 @Override 2881 public long disableTable(final TableName tableName, final long nonceGroup, final long nonce) 2882 throws IOException { 2883 checkInitialized(); 2884 2885 return MasterProcedureUtil 2886 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2887 @Override 2888 protected void run() throws IOException { 2889 getMaster().getMasterCoprocessorHost().preDisableTable(tableName); 2890 2891 LOG.info(getClientIdAuditPrefix() + " disable " + tableName); 2892 2893 // Execute the operation asynchronously - client will check the progress of the operation 2894 // In case the request is from a <1.1 client before returning, 2895 // we want to make sure that the table is prepared to be 2896 // enabled (the table is locked and the table state is set). 2897 // Note: if the procedure throws exception, we will catch it and rethrow. 2898 // 2899 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2900 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2901 final ProcedurePrepareLatch prepareLatch = ProcedurePrepareLatch.createBlockingLatch(); 2902 submitProcedure(new DisableTableProcedure(procedureExecutor.getEnvironment(), tableName, 2903 false, prepareLatch)); 2904 prepareLatch.await(); 2905 2906 getMaster().getMasterCoprocessorHost().postDisableTable(tableName); 2907 } 2908 2909 @Override 2910 protected String getDescription() { 2911 return "DisableTableProcedure"; 2912 } 2913 }); 2914 } 2915 2916 private long modifyTable(final TableName tableName, 2917 final TableDescriptorGetter newDescriptorGetter, final long nonceGroup, final long nonce, 2918 final boolean shouldCheckDescriptor) throws IOException { 2919 return modifyTable(tableName, newDescriptorGetter, nonceGroup, nonce, shouldCheckDescriptor, 2920 true); 2921 } 2922 2923 private long modifyTable(final TableName tableName, 2924 final TableDescriptorGetter newDescriptorGetter, final long nonceGroup, final long nonce, 2925 final boolean shouldCheckDescriptor, final boolean reopenRegions) throws IOException { 2926 return MasterProcedureUtil 2927 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2928 @Override 2929 protected void run() throws IOException { 2930 TableDescriptor oldDescriptor = getMaster().getTableDescriptors().get(tableName); 2931 TableDescriptor newDescriptor = getMaster().getMasterCoprocessorHost() 2932 .preModifyTable(tableName, oldDescriptor, newDescriptorGetter.get()); 2933 TableDescriptorChecker.sanityCheck(conf, newDescriptor); 2934 LOG.info("{} modify table {} from {} to {}", getClientIdAuditPrefix(), tableName, 2935 oldDescriptor, newDescriptor); 2936 2937 // Execute the operation synchronously - wait for the operation completes before 2938 // continuing. 2939 // 2940 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2941 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2942 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 2943 submitProcedure(new ModifyTableProcedure(procedureExecutor.getEnvironment(), 2944 newDescriptor, latch, oldDescriptor, shouldCheckDescriptor, reopenRegions)); 2945 latch.await(); 2946 2947 getMaster().getMasterCoprocessorHost().postModifyTable(tableName, oldDescriptor, 2948 newDescriptor); 2949 } 2950 2951 @Override 2952 protected String getDescription() { 2953 return "ModifyTableProcedure"; 2954 } 2955 }); 2956 2957 } 2958 2959 @Override 2960 public long modifyTable(final TableName tableName, final TableDescriptor newDescriptor, 2961 final long nonceGroup, final long nonce, final boolean reopenRegions) throws IOException { 2962 checkInitialized(); 2963 return modifyTable(tableName, new TableDescriptorGetter() { 2964 @Override 2965 public TableDescriptor get() throws IOException { 2966 return newDescriptor; 2967 } 2968 }, nonceGroup, nonce, false, reopenRegions); 2969 2970 } 2971 2972 @Override 2973 public long modifyTableStoreFileTracker(TableName tableName, String dstSFT, long nonceGroup, 2974 long nonce) throws IOException { 2975 checkInitialized(); 2976 return MasterProcedureUtil 2977 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2978 2979 @Override 2980 protected void run() throws IOException { 2981 String sft = getMaster().getMasterCoprocessorHost() 2982 .preModifyTableStoreFileTracker(tableName, dstSFT); 2983 LOG.info("{} modify table store file tracker of table {} to {}", getClientIdAuditPrefix(), 2984 tableName, sft); 2985 submitProcedure(new ModifyTableStoreFileTrackerProcedure( 2986 procedureExecutor.getEnvironment(), tableName, sft)); 2987 getMaster().getMasterCoprocessorHost().postModifyTableStoreFileTracker(tableName, sft); 2988 } 2989 2990 @Override 2991 protected String getDescription() { 2992 return "ModifyTableStoreFileTrackerProcedure"; 2993 } 2994 }); 2995 } 2996 2997 public long restoreSnapshot(final SnapshotDescription snapshotDesc, final long nonceGroup, 2998 final long nonce, final boolean restoreAcl, final String customSFT) throws IOException { 2999 checkInitialized(); 3000 getSnapshotManager().checkSnapshotSupport(); 3001 3002 // Ensure namespace exists. Will throw exception if non-known NS. 3003 final TableName dstTable = TableName.valueOf(snapshotDesc.getTable()); 3004 getClusterSchema().getNamespace(dstTable.getNamespaceAsString()); 3005 3006 return MasterProcedureUtil 3007 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 3008 @Override 3009 protected void run() throws IOException { 3010 setProcId(getSnapshotManager().restoreOrCloneSnapshot(snapshotDesc, getNonceKey(), 3011 restoreAcl, customSFT)); 3012 } 3013 3014 @Override 3015 protected String getDescription() { 3016 return "RestoreSnapshotProcedure"; 3017 } 3018 }); 3019 } 3020 3021 private void checkTableExists(final TableName tableName) 3022 throws IOException, TableNotFoundException { 3023 if (!tableDescriptors.exists(tableName)) { 3024 throw new TableNotFoundException(tableName); 3025 } 3026 } 3027 3028 @Override 3029 public void checkTableModifiable(final TableName tableName) 3030 throws IOException, TableNotFoundException, TableNotDisabledException { 3031 if (isCatalogTable(tableName)) { 3032 throw new IOException("Can't modify catalog tables"); 3033 } 3034 checkTableExists(tableName); 3035 TableState ts = getTableStateManager().getTableState(tableName); 3036 if (!ts.isDisabled()) { 3037 throw new TableNotDisabledException("Not DISABLED; " + ts); 3038 } 3039 } 3040 3041 public void reloadRegionServerQuotas() { 3042 // multiple reloads are harmless, so no need for NonceProcedureRunnable 3043 getLiveRegionServers() 3044 .forEach(sn -> procedureExecutor.submitProcedure(new ReloadQuotasProcedure(sn))); 3045 } 3046 3047 public ClusterMetrics getClusterMetricsWithoutCoprocessor() throws InterruptedIOException { 3048 return getClusterMetricsWithoutCoprocessor(EnumSet.allOf(Option.class)); 3049 } 3050 3051 public ClusterMetrics getClusterMetricsWithoutCoprocessor(EnumSet<Option> options) 3052 throws InterruptedIOException { 3053 ClusterMetricsBuilder builder = ClusterMetricsBuilder.newBuilder(); 3054 // given that hbase1 can't submit the request with Option, 3055 // we return all information to client if the list of Option is empty. 3056 if (options.isEmpty()) { 3057 options = EnumSet.allOf(Option.class); 3058 } 3059 3060 // TASKS and/or LIVE_SERVERS will populate this map, which will be given to the builder if 3061 // not null after option processing completes. 3062 Map<ServerName, ServerMetrics> serverMetricsMap = null; 3063 3064 for (Option opt : options) { 3065 switch (opt) { 3066 case HBASE_VERSION: 3067 builder.setHBaseVersion(VersionInfo.getVersion()); 3068 break; 3069 case CLUSTER_ID: 3070 builder.setClusterId(getClusterId()); 3071 break; 3072 case MASTER: 3073 builder.setMasterName(getServerName()); 3074 break; 3075 case BACKUP_MASTERS: 3076 builder.setBackerMasterNames(getBackupMasters()); 3077 break; 3078 case TASKS: { 3079 // Master tasks 3080 builder.setMasterTasks(TaskMonitor.get().getTasks().stream() 3081 .map(task -> ServerTaskBuilder.newBuilder().setDescription(task.getDescription()) 3082 .setStatus(task.getStatus()) 3083 .setState(ServerTask.State.valueOf(task.getState().name())) 3084 .setStartTime(task.getStartTime()).setCompletionTime(task.getCompletionTimestamp()) 3085 .build()) 3086 .collect(Collectors.toList())); 3087 // TASKS is also synonymous with LIVE_SERVERS for now because task information for 3088 // regionservers is carried in ServerLoad. 3089 // Add entries to serverMetricsMap for all live servers, if we haven't already done so 3090 if (serverMetricsMap == null) { 3091 serverMetricsMap = getOnlineServers(); 3092 } 3093 break; 3094 } 3095 case LIVE_SERVERS: { 3096 // Add entries to serverMetricsMap for all live servers, if we haven't already done so 3097 if (serverMetricsMap == null) { 3098 serverMetricsMap = getOnlineServers(); 3099 } 3100 break; 3101 } 3102 case DEAD_SERVERS: { 3103 if (serverManager != null) { 3104 builder.setDeadServerNames( 3105 new ArrayList<>(serverManager.getDeadServers().copyServerNames())); 3106 } 3107 break; 3108 } 3109 case UNKNOWN_SERVERS: { 3110 if (serverManager != null) { 3111 builder.setUnknownServerNames(getUnknownServers()); 3112 } 3113 break; 3114 } 3115 case MASTER_COPROCESSORS: { 3116 if (cpHost != null) { 3117 builder.setMasterCoprocessorNames(Arrays.asList(getMasterCoprocessors())); 3118 } 3119 break; 3120 } 3121 case REGIONS_IN_TRANSITION: { 3122 if (assignmentManager != null) { 3123 builder.setRegionsInTransition( 3124 new ArrayList<>(assignmentManager.getRegionsStateInTransition())); 3125 } 3126 break; 3127 } 3128 case BALANCER_ON: { 3129 if (loadBalancerStateStore != null) { 3130 builder.setBalancerOn(loadBalancerStateStore.get()); 3131 } 3132 break; 3133 } 3134 case MASTER_INFO_PORT: { 3135 if (infoServer != null) { 3136 builder.setMasterInfoPort(infoServer.getPort()); 3137 } 3138 break; 3139 } 3140 case SERVERS_NAME: { 3141 if (serverManager != null) { 3142 builder.setServerNames(serverManager.getOnlineServersList()); 3143 } 3144 break; 3145 } 3146 case TABLE_TO_REGIONS_COUNT: { 3147 if (isActiveMaster() && isInitialized() && assignmentManager != null) { 3148 try { 3149 Map<TableName, RegionStatesCount> tableRegionStatesCountMap = new HashMap<>(); 3150 List<TableDescriptor> tableDescriptors = listTableDescriptors(null, null, null, true); 3151 for (TableDescriptor tableDescriptor : tableDescriptors) { 3152 TableName tableName = tableDescriptor.getTableName(); 3153 RegionStatesCount regionStatesCount = 3154 assignmentManager.getRegionStatesCount(tableName); 3155 tableRegionStatesCountMap.put(tableName, regionStatesCount); 3156 } 3157 builder.setTableRegionStatesCount(tableRegionStatesCountMap); 3158 } catch (IOException e) { 3159 LOG.error("Error while populating TABLE_TO_REGIONS_COUNT for Cluster Metrics..", e); 3160 } 3161 } 3162 break; 3163 } 3164 case DECOMMISSIONED_SERVERS: { 3165 if (serverManager != null) { 3166 builder.setDecommissionedServerNames(serverManager.getDrainingServersList()); 3167 } 3168 break; 3169 } 3170 } 3171 } 3172 3173 if (serverMetricsMap != null) { 3174 builder.setLiveServerMetrics(serverMetricsMap); 3175 } 3176 3177 return builder.build(); 3178 } 3179 3180 private List<ServerName> getUnknownServers() { 3181 if (serverManager != null) { 3182 final Set<ServerName> serverNames = getAssignmentManager().getRegionStates().getRegionStates() 3183 .stream().map(RegionState::getServerName).collect(Collectors.toSet()); 3184 final List<ServerName> unknownServerNames = serverNames.stream() 3185 .filter(sn -> sn != null && serverManager.isServerUnknown(sn)).collect(Collectors.toList()); 3186 return unknownServerNames; 3187 } 3188 return null; 3189 } 3190 3191 private Map<ServerName, ServerMetrics> getOnlineServers() { 3192 if (serverManager != null) { 3193 final Map<ServerName, ServerMetrics> map = new HashMap<>(); 3194 serverManager.getOnlineServers().entrySet().forEach(e -> map.put(e.getKey(), e.getValue())); 3195 return map; 3196 } 3197 return null; 3198 } 3199 3200 /** Returns cluster status */ 3201 public ClusterMetrics getClusterMetrics() throws IOException { 3202 return getClusterMetrics(EnumSet.allOf(Option.class)); 3203 } 3204 3205 public ClusterMetrics getClusterMetrics(EnumSet<Option> options) throws IOException { 3206 if (cpHost != null) { 3207 cpHost.preGetClusterMetrics(); 3208 } 3209 ClusterMetrics status = getClusterMetricsWithoutCoprocessor(options); 3210 if (cpHost != null) { 3211 cpHost.postGetClusterMetrics(status); 3212 } 3213 return status; 3214 } 3215 3216 /** Returns info port of active master or 0 if any exception occurs. */ 3217 public int getActiveMasterInfoPort() { 3218 return activeMasterManager.getActiveMasterInfoPort(); 3219 } 3220 3221 /** 3222 * @param sn is ServerName of the backup master 3223 * @return info port of backup master or 0 if any exception occurs. 3224 */ 3225 public int getBackupMasterInfoPort(final ServerName sn) { 3226 return activeMasterManager.getBackupMasterInfoPort(sn); 3227 } 3228 3229 /** 3230 * The set of loaded coprocessors is stored in a static set. Since it's statically allocated, it 3231 * does not require that HMaster's cpHost be initialized prior to accessing it. 3232 * @return a String representation of the set of names of the loaded coprocessors. 3233 */ 3234 public static String getLoadedCoprocessors() { 3235 return CoprocessorHost.getLoadedCoprocessors().toString(); 3236 } 3237 3238 /** Returns timestamp in millis when HMaster was started. */ 3239 public long getMasterStartTime() { 3240 return startcode; 3241 } 3242 3243 /** Returns timestamp in millis when HMaster became the active master. */ 3244 @Override 3245 public long getMasterActiveTime() { 3246 return masterActiveTime; 3247 } 3248 3249 /** Returns timestamp in millis when HMaster finished becoming the active master */ 3250 public long getMasterFinishedInitializationTime() { 3251 return masterFinishedInitializationTime; 3252 } 3253 3254 public int getNumWALFiles() { 3255 return 0; 3256 } 3257 3258 public ProcedureStore getProcedureStore() { 3259 return procedureStore; 3260 } 3261 3262 public int getRegionServerInfoPort(final ServerName sn) { 3263 int port = this.serverManager.getInfoPort(sn); 3264 return port == 0 3265 ? conf.getInt(HConstants.REGIONSERVER_INFO_PORT, HConstants.DEFAULT_REGIONSERVER_INFOPORT) 3266 : port; 3267 } 3268 3269 @Override 3270 public String getRegionServerVersion(ServerName sn) { 3271 // Will return "0.0.0" if the server is not online to prevent move system region to unknown 3272 // version RS. 3273 return this.serverManager.getVersion(sn); 3274 } 3275 3276 @Override 3277 public void checkIfShouldMoveSystemRegionAsync() { 3278 assignmentManager.checkIfShouldMoveSystemRegionAsync(); 3279 } 3280 3281 /** Returns array of coprocessor SimpleNames. */ 3282 public String[] getMasterCoprocessors() { 3283 Set<String> masterCoprocessors = getMasterCoprocessorHost().getCoprocessors(); 3284 return masterCoprocessors.toArray(new String[masterCoprocessors.size()]); 3285 } 3286 3287 @Override 3288 public void abort(String reason, Throwable cause) { 3289 if (!setAbortRequested() || isStopped()) { 3290 LOG.debug("Abort called but aborted={}, stopped={}", isAborted(), isStopped()); 3291 return; 3292 } 3293 if (cpHost != null) { 3294 // HBASE-4014: dump a list of loaded coprocessors. 3295 LOG.error(HBaseMarkers.FATAL, 3296 "Master server abort: loaded coprocessors are: " + getLoadedCoprocessors()); 3297 } 3298 String msg = "***** ABORTING master " + this + ": " + reason + " *****"; 3299 if (cause != null) { 3300 LOG.error(HBaseMarkers.FATAL, msg, cause); 3301 } else { 3302 LOG.error(HBaseMarkers.FATAL, msg); 3303 } 3304 3305 try { 3306 stopMaster(); 3307 } catch (IOException e) { 3308 LOG.error("Exception occurred while stopping master", e); 3309 } 3310 } 3311 3312 @Override 3313 public MasterCoprocessorHost getMasterCoprocessorHost() { 3314 return cpHost; 3315 } 3316 3317 @Override 3318 public MasterQuotaManager getMasterQuotaManager() { 3319 return quotaManager; 3320 } 3321 3322 @Override 3323 public ProcedureExecutor<MasterProcedureEnv> getMasterProcedureExecutor() { 3324 return procedureExecutor; 3325 } 3326 3327 @Override 3328 public ServerName getServerName() { 3329 return this.serverName; 3330 } 3331 3332 @Override 3333 public AssignmentManager getAssignmentManager() { 3334 return this.assignmentManager; 3335 } 3336 3337 @Override 3338 public CatalogJanitor getCatalogJanitor() { 3339 return this.catalogJanitorChore; 3340 } 3341 3342 public MemoryBoundedLogMessageBuffer getRegionServerFatalLogBuffer() { 3343 return rsFatals; 3344 } 3345 3346 public TaskGroup getStartupProgress() { 3347 return startupTaskGroup; 3348 } 3349 3350 /** 3351 * Shutdown the cluster. Master runs a coordinated stop of all RegionServers and then itself. 3352 */ 3353 public void shutdown() throws IOException { 3354 TraceUtil.trace(() -> { 3355 if (cpHost != null) { 3356 cpHost.preShutdown(); 3357 } 3358 3359 // Tell the servermanager cluster shutdown has been called. This makes it so when Master is 3360 // last running server, it'll stop itself. Next, we broadcast the cluster shutdown by setting 3361 // the cluster status as down. RegionServers will notice this change in state and will start 3362 // shutting themselves down. When last has exited, Master can go down. 3363 if (this.serverManager != null) { 3364 this.serverManager.shutdownCluster(); 3365 } 3366 if (this.clusterStatusTracker != null) { 3367 try { 3368 this.clusterStatusTracker.setClusterDown(); 3369 } catch (KeeperException e) { 3370 LOG.error("ZooKeeper exception trying to set cluster as down in ZK", e); 3371 } 3372 } 3373 // Stop the procedure executor. Will stop any ongoing assign, unassign, server crash etc., 3374 // processing so we can go down. 3375 if (this.procedureExecutor != null) { 3376 this.procedureExecutor.stop(); 3377 } 3378 // Shutdown our cluster connection. This will kill any hosted RPCs that might be going on; 3379 // this is what we want especially if the Master is in startup phase doing call outs to 3380 // hbase:meta, etc. when cluster is down. Without ths connection close, we'd have to wait on 3381 // the rpc to timeout. 3382 if (this.asyncClusterConnection != null) { 3383 this.asyncClusterConnection.close(); 3384 } 3385 }, "HMaster.shutdown"); 3386 } 3387 3388 public void stopMaster() throws IOException { 3389 if (cpHost != null) { 3390 cpHost.preStopMaster(); 3391 } 3392 stop("Stopped by " + Thread.currentThread().getName()); 3393 } 3394 3395 @Override 3396 public void stop(String msg) { 3397 if (!this.stopped) { 3398 LOG.info("***** STOPPING master '" + this + "' *****"); 3399 this.stopped = true; 3400 LOG.info("STOPPED: " + msg); 3401 // Wakes run() if it is sleeping 3402 sleeper.skipSleepCycle(); 3403 if (this.activeMasterManager != null) { 3404 this.activeMasterManager.stop(); 3405 } 3406 } 3407 } 3408 3409 protected void checkServiceStarted() throws ServerNotRunningYetException { 3410 if (!serviceStarted) { 3411 throw new ServerNotRunningYetException("Server is not running yet"); 3412 } 3413 } 3414 3415 void checkInitialized() throws PleaseHoldException, ServerNotRunningYetException, 3416 MasterNotRunningException, MasterStoppedException { 3417 checkServiceStarted(); 3418 if (!isInitialized()) { 3419 throw new PleaseHoldException("Master is initializing"); 3420 } 3421 if (isStopped()) { 3422 throw new MasterStoppedException(); 3423 } 3424 } 3425 3426 /** 3427 * Report whether this master is currently the active master or not. If not active master, we are 3428 * parked on ZK waiting to become active. This method is used for testing. 3429 * @return true if active master, false if not. 3430 */ 3431 @Override 3432 public boolean isActiveMaster() { 3433 return activeMaster; 3434 } 3435 3436 /** 3437 * Report whether this master has completed with its initialization and is ready. If ready, the 3438 * master is also the active master. A standby master is never ready. This method is used for 3439 * testing. 3440 * @return true if master is ready to go, false if not. 3441 */ 3442 @Override 3443 public boolean isInitialized() { 3444 return initialized.isReady(); 3445 } 3446 3447 /** 3448 * Report whether this master is started This method is used for testing. 3449 * @return true if master is ready to go, false if not. 3450 */ 3451 public boolean isOnline() { 3452 return serviceStarted; 3453 } 3454 3455 /** 3456 * Report whether this master is in maintenance mode. 3457 * @return true if master is in maintenanceMode 3458 */ 3459 @Override 3460 public boolean isInMaintenanceMode() { 3461 return maintenanceMode; 3462 } 3463 3464 public void setInitialized(boolean isInitialized) { 3465 procedureExecutor.getEnvironment().setEventReady(initialized, isInitialized); 3466 } 3467 3468 /** 3469 * Mainly used in procedure related tests, where we will restart ProcedureExecutor and 3470 * AssignmentManager, but we do not want to restart master(to speed up the test), so we need to 3471 * disable rpc for a while otherwise some critical rpc requests such as 3472 * reportRegionStateTransition could fail and cause region server to abort. 3473 */ 3474 @RestrictedApi(explanation = "Should only be called in tests", link = "", 3475 allowedOnPath = ".*/src/test/.*") 3476 public void setServiceStarted(boolean started) { 3477 this.serviceStarted = started; 3478 } 3479 3480 @Override 3481 public ProcedureEvent<?> getInitializedEvent() { 3482 return initialized; 3483 } 3484 3485 /** 3486 * Compute the average load across all region servers. Currently, this uses a very naive 3487 * computation - just uses the number of regions being served, ignoring stats about number of 3488 * requests. 3489 * @return the average load 3490 */ 3491 public double getAverageLoad() { 3492 if (this.assignmentManager == null) { 3493 return 0; 3494 } 3495 3496 RegionStates regionStates = this.assignmentManager.getRegionStates(); 3497 if (regionStates == null) { 3498 return 0; 3499 } 3500 return regionStates.getAverageLoad(); 3501 } 3502 3503 @Override 3504 public boolean registerService(Service instance) { 3505 /* 3506 * No stacking of instances is allowed for a single service name 3507 */ 3508 Descriptors.ServiceDescriptor serviceDesc = instance.getDescriptorForType(); 3509 String serviceName = CoprocessorRpcUtils.getServiceName(serviceDesc); 3510 if (coprocessorServiceHandlers.containsKey(serviceName)) { 3511 LOG.error("Coprocessor service " + serviceName 3512 + " already registered, rejecting request from " + instance); 3513 return false; 3514 } 3515 3516 coprocessorServiceHandlers.put(serviceName, instance); 3517 if (LOG.isDebugEnabled()) { 3518 LOG.debug("Registered master coprocessor service: service=" + serviceName); 3519 } 3520 return true; 3521 } 3522 3523 /** 3524 * Utility for constructing an instance of the passed HMaster class. 3525 * @return HMaster instance. 3526 */ 3527 public static HMaster constructMaster(Class<? extends HMaster> masterClass, 3528 final Configuration conf) { 3529 try { 3530 Constructor<? extends HMaster> c = masterClass.getConstructor(Configuration.class); 3531 return c.newInstance(conf); 3532 } catch (Exception e) { 3533 Throwable error = e; 3534 if ( 3535 e instanceof InvocationTargetException 3536 && ((InvocationTargetException) e).getTargetException() != null 3537 ) { 3538 error = ((InvocationTargetException) e).getTargetException(); 3539 } 3540 throw new RuntimeException("Failed construction of Master: " + masterClass.toString() + ". ", 3541 error); 3542 } 3543 } 3544 3545 /** 3546 * @see org.apache.hadoop.hbase.master.HMasterCommandLine 3547 */ 3548 public static void main(String[] args) { 3549 LOG.info("STARTING service " + HMaster.class.getSimpleName()); 3550 VersionInfo.logVersion(); 3551 new HMasterCommandLine(HMaster.class).doMain(args); 3552 } 3553 3554 public HFileCleaner getHFileCleaner() { 3555 return this.hfileCleaners.get(0); 3556 } 3557 3558 public List<HFileCleaner> getHFileCleaners() { 3559 return this.hfileCleaners; 3560 } 3561 3562 public LogCleaner getLogCleaner() { 3563 return this.logCleaner; 3564 } 3565 3566 /** Returns the underlying snapshot manager */ 3567 @Override 3568 public SnapshotManager getSnapshotManager() { 3569 return this.snapshotManager; 3570 } 3571 3572 /** Returns the underlying MasterProcedureManagerHost */ 3573 @Override 3574 public MasterProcedureManagerHost getMasterProcedureManagerHost() { 3575 return mpmHost; 3576 } 3577 3578 @Override 3579 public ClusterSchema getClusterSchema() { 3580 return this.clusterSchemaService; 3581 } 3582 3583 /** 3584 * Create a new Namespace. 3585 * @param namespaceDescriptor descriptor for new Namespace 3586 * @param nonceGroup Identifier for the source of the request, a client or process. 3587 * @param nonce A unique identifier for this operation from the client or process 3588 * identified by <code>nonceGroup</code> (the source must ensure each 3589 * operation gets a unique id). 3590 * @return procedure id 3591 */ 3592 long createNamespace(final NamespaceDescriptor namespaceDescriptor, final long nonceGroup, 3593 final long nonce) throws IOException { 3594 checkInitialized(); 3595 3596 TableName.isLegalNamespaceName(Bytes.toBytes(namespaceDescriptor.getName())); 3597 3598 return MasterProcedureUtil 3599 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 3600 @Override 3601 protected void run() throws IOException { 3602 getMaster().getMasterCoprocessorHost().preCreateNamespace(namespaceDescriptor); 3603 // We need to wait for the procedure to potentially fail due to "prepare" sanity 3604 // checks. This will block only the beginning of the procedure. See HBASE-19953. 3605 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 3606 LOG.info(getClientIdAuditPrefix() + " creating " + namespaceDescriptor); 3607 // Execute the operation synchronously - wait for the operation to complete before 3608 // continuing. 3609 setProcId(getClusterSchema().createNamespace(namespaceDescriptor, getNonceKey(), latch)); 3610 latch.await(); 3611 getMaster().getMasterCoprocessorHost().postCreateNamespace(namespaceDescriptor); 3612 } 3613 3614 @Override 3615 protected String getDescription() { 3616 return "CreateNamespaceProcedure"; 3617 } 3618 }); 3619 } 3620 3621 /** 3622 * Modify an existing Namespace. 3623 * @param nonceGroup Identifier for the source of the request, a client or process. 3624 * @param nonce A unique identifier for this operation from the client or process identified 3625 * by <code>nonceGroup</code> (the source must ensure each operation gets a 3626 * unique id). 3627 * @return procedure id 3628 */ 3629 long modifyNamespace(final NamespaceDescriptor newNsDescriptor, final long nonceGroup, 3630 final long nonce) throws IOException { 3631 checkInitialized(); 3632 3633 TableName.isLegalNamespaceName(Bytes.toBytes(newNsDescriptor.getName())); 3634 3635 return MasterProcedureUtil 3636 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 3637 @Override 3638 protected void run() throws IOException { 3639 NamespaceDescriptor oldNsDescriptor = getNamespace(newNsDescriptor.getName()); 3640 getMaster().getMasterCoprocessorHost().preModifyNamespace(oldNsDescriptor, 3641 newNsDescriptor); 3642 // We need to wait for the procedure to potentially fail due to "prepare" sanity 3643 // checks. This will block only the beginning of the procedure. See HBASE-19953. 3644 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 3645 LOG.info(getClientIdAuditPrefix() + " modify " + newNsDescriptor); 3646 // Execute the operation synchronously - wait for the operation to complete before 3647 // continuing. 3648 setProcId(getClusterSchema().modifyNamespace(newNsDescriptor, getNonceKey(), latch)); 3649 latch.await(); 3650 getMaster().getMasterCoprocessorHost().postModifyNamespace(oldNsDescriptor, 3651 newNsDescriptor); 3652 } 3653 3654 @Override 3655 protected String getDescription() { 3656 return "ModifyNamespaceProcedure"; 3657 } 3658 }); 3659 } 3660 3661 /** 3662 * Delete an existing Namespace. Only empty Namespaces (no tables) can be removed. 3663 * @param nonceGroup Identifier for the source of the request, a client or process. 3664 * @param nonce A unique identifier for this operation from the client or process identified 3665 * by <code>nonceGroup</code> (the source must ensure each operation gets a 3666 * unique id). 3667 * @return procedure id 3668 */ 3669 long deleteNamespace(final String name, final long nonceGroup, final long nonce) 3670 throws IOException { 3671 checkInitialized(); 3672 3673 return MasterProcedureUtil 3674 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 3675 @Override 3676 protected void run() throws IOException { 3677 getMaster().getMasterCoprocessorHost().preDeleteNamespace(name); 3678 LOG.info(getClientIdAuditPrefix() + " delete " + name); 3679 // Execute the operation synchronously - wait for the operation to complete before 3680 // continuing. 3681 // 3682 // We need to wait for the procedure to potentially fail due to "prepare" sanity 3683 // checks. This will block only the beginning of the procedure. See HBASE-19953. 3684 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 3685 setProcId(submitProcedure( 3686 new DeleteNamespaceProcedure(procedureExecutor.getEnvironment(), name, latch))); 3687 latch.await(); 3688 // Will not be invoked in the face of Exception thrown by the Procedure's execution 3689 getMaster().getMasterCoprocessorHost().postDeleteNamespace(name); 3690 } 3691 3692 @Override 3693 protected String getDescription() { 3694 return "DeleteNamespaceProcedure"; 3695 } 3696 }); 3697 } 3698 3699 /** 3700 * Get a Namespace 3701 * @param name Name of the Namespace 3702 * @return Namespace descriptor for <code>name</code> 3703 */ 3704 NamespaceDescriptor getNamespace(String name) throws IOException { 3705 checkInitialized(); 3706 if (this.cpHost != null) this.cpHost.preGetNamespaceDescriptor(name); 3707 NamespaceDescriptor nsd = this.clusterSchemaService.getNamespace(name); 3708 if (this.cpHost != null) this.cpHost.postGetNamespaceDescriptor(nsd); 3709 return nsd; 3710 } 3711 3712 /** 3713 * Get all Namespaces 3714 * @return All Namespace descriptors 3715 */ 3716 List<NamespaceDescriptor> getNamespaces() throws IOException { 3717 checkInitialized(); 3718 final List<NamespaceDescriptor> nsds = new ArrayList<>(); 3719 if (cpHost != null) { 3720 cpHost.preListNamespaceDescriptors(nsds); 3721 } 3722 nsds.addAll(this.clusterSchemaService.getNamespaces()); 3723 if (this.cpHost != null) { 3724 this.cpHost.postListNamespaceDescriptors(nsds); 3725 } 3726 return nsds; 3727 } 3728 3729 /** 3730 * List namespace names 3731 * @return All namespace names 3732 */ 3733 public List<String> listNamespaces() throws IOException { 3734 checkInitialized(); 3735 List<String> namespaces = new ArrayList<>(); 3736 if (cpHost != null) { 3737 cpHost.preListNamespaces(namespaces); 3738 } 3739 for (NamespaceDescriptor namespace : clusterSchemaService.getNamespaces()) { 3740 namespaces.add(namespace.getName()); 3741 } 3742 if (cpHost != null) { 3743 cpHost.postListNamespaces(namespaces); 3744 } 3745 return namespaces; 3746 } 3747 3748 @Override 3749 public List<TableName> listTableNamesByNamespace(String name) throws IOException { 3750 checkInitialized(); 3751 return listTableNames(name, null, true); 3752 } 3753 3754 @Override 3755 public List<TableDescriptor> listTableDescriptorsByNamespace(String name) throws IOException { 3756 checkInitialized(); 3757 return listTableDescriptors(name, null, null, true); 3758 } 3759 3760 @Override 3761 public boolean abortProcedure(final long procId, final boolean mayInterruptIfRunning) 3762 throws IOException { 3763 if (cpHost != null) { 3764 cpHost.preAbortProcedure(this.procedureExecutor, procId); 3765 } 3766 3767 final boolean result = this.procedureExecutor.abort(procId, mayInterruptIfRunning); 3768 3769 if (cpHost != null) { 3770 cpHost.postAbortProcedure(); 3771 } 3772 3773 return result; 3774 } 3775 3776 @Override 3777 public List<Procedure<?>> getProcedures() throws IOException { 3778 if (cpHost != null) { 3779 cpHost.preGetProcedures(); 3780 } 3781 3782 @SuppressWarnings({ "unchecked", "rawtypes" }) 3783 List<Procedure<?>> procList = (List) this.procedureExecutor.getProcedures(); 3784 3785 if (cpHost != null) { 3786 cpHost.postGetProcedures(procList); 3787 } 3788 3789 return procList; 3790 } 3791 3792 @Override 3793 public List<LockedResource> getLocks() throws IOException { 3794 if (cpHost != null) { 3795 cpHost.preGetLocks(); 3796 } 3797 3798 MasterProcedureScheduler procedureScheduler = 3799 procedureExecutor.getEnvironment().getProcedureScheduler(); 3800 3801 final List<LockedResource> lockedResources = procedureScheduler.getLocks(); 3802 3803 if (cpHost != null) { 3804 cpHost.postGetLocks(lockedResources); 3805 } 3806 3807 return lockedResources; 3808 } 3809 3810 /** 3811 * Returns the list of table descriptors that match the specified request 3812 * @param namespace the namespace to query, or null if querying for all 3813 * @param regex The regular expression to match against, or null if querying for all 3814 * @param tableNameList the list of table names, or null if querying for all 3815 * @param includeSysTables False to match only against userspace tables 3816 * @return the list of table descriptors 3817 */ 3818 public List<TableDescriptor> listTableDescriptors(final String namespace, final String regex, 3819 final List<TableName> tableNameList, final boolean includeSysTables) throws IOException { 3820 List<TableDescriptor> htds = new ArrayList<>(); 3821 if (cpHost != null) { 3822 cpHost.preGetTableDescriptors(tableNameList, htds, regex); 3823 } 3824 htds = getTableDescriptors(htds, namespace, regex, tableNameList, includeSysTables); 3825 if (cpHost != null) { 3826 cpHost.postGetTableDescriptors(tableNameList, htds, regex); 3827 } 3828 return htds; 3829 } 3830 3831 /** 3832 * Returns the list of table names that match the specified request 3833 * @param regex The regular expression to match against, or null if querying for all 3834 * @param namespace the namespace to query, or null if querying for all 3835 * @param includeSysTables False to match only against userspace tables 3836 * @return the list of table names 3837 */ 3838 public List<TableName> listTableNames(final String namespace, final String regex, 3839 final boolean includeSysTables) throws IOException { 3840 List<TableDescriptor> htds = new ArrayList<>(); 3841 if (cpHost != null) { 3842 cpHost.preGetTableNames(htds, regex); 3843 } 3844 htds = getTableDescriptors(htds, namespace, regex, null, includeSysTables); 3845 if (cpHost != null) { 3846 cpHost.postGetTableNames(htds, regex); 3847 } 3848 List<TableName> result = new ArrayList<>(htds.size()); 3849 for (TableDescriptor htd : htds) 3850 result.add(htd.getTableName()); 3851 return result; 3852 } 3853 3854 /** 3855 * Return a list of table descriptors after applying any provided filter parameters. Note that the 3856 * user-facing description of this filter logic is presented on the class-level javadoc of 3857 * {@link NormalizeTableFilterParams}. 3858 */ 3859 private List<TableDescriptor> getTableDescriptors(final List<TableDescriptor> htds, 3860 final String namespace, final String regex, final List<TableName> tableNameList, 3861 final boolean includeSysTables) throws IOException { 3862 if (tableNameList == null || tableNameList.isEmpty()) { 3863 // request for all TableDescriptors 3864 Collection<TableDescriptor> allHtds; 3865 if (namespace != null && namespace.length() > 0) { 3866 // Do a check on the namespace existence. Will fail if it does not exist. 3867 this.clusterSchemaService.getNamespace(namespace); 3868 allHtds = tableDescriptors.getByNamespace(namespace).values(); 3869 } else { 3870 allHtds = tableDescriptors.getAll().values(); 3871 } 3872 for (TableDescriptor desc : allHtds) { 3873 if ( 3874 tableStateManager.isTablePresent(desc.getTableName()) 3875 && (includeSysTables || !desc.getTableName().isSystemTable()) 3876 ) { 3877 htds.add(desc); 3878 } 3879 } 3880 } else { 3881 for (TableName s : tableNameList) { 3882 if (tableStateManager.isTablePresent(s)) { 3883 TableDescriptor desc = tableDescriptors.get(s); 3884 if (desc != null) { 3885 htds.add(desc); 3886 } 3887 } 3888 } 3889 } 3890 3891 // Retains only those matched by regular expression. 3892 if (regex != null) filterTablesByRegex(htds, Pattern.compile(regex)); 3893 return htds; 3894 } 3895 3896 /** 3897 * Removes the table descriptors that don't match the pattern. 3898 * @param descriptors list of table descriptors to filter 3899 * @param pattern the regex to use 3900 */ 3901 private static void filterTablesByRegex(final Collection<TableDescriptor> descriptors, 3902 final Pattern pattern) { 3903 final String defaultNS = NamespaceDescriptor.DEFAULT_NAMESPACE_NAME_STR; 3904 Iterator<TableDescriptor> itr = descriptors.iterator(); 3905 while (itr.hasNext()) { 3906 TableDescriptor htd = itr.next(); 3907 String tableName = htd.getTableName().getNameAsString(); 3908 boolean matched = pattern.matcher(tableName).matches(); 3909 if (!matched && htd.getTableName().getNamespaceAsString().equals(defaultNS)) { 3910 matched = pattern.matcher(defaultNS + TableName.NAMESPACE_DELIM + tableName).matches(); 3911 } 3912 if (!matched) { 3913 itr.remove(); 3914 } 3915 } 3916 } 3917 3918 @Override 3919 public long getLastMajorCompactionTimestamp(TableName table) throws IOException { 3920 return getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS)) 3921 .getLastMajorCompactionTimestamp(table); 3922 } 3923 3924 @Override 3925 public long getLastMajorCompactionTimestampForRegion(byte[] regionName) throws IOException { 3926 return getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS)) 3927 .getLastMajorCompactionTimestamp(regionName); 3928 } 3929 3930 /** 3931 * Gets the mob file compaction state for a specific table. Whether all the mob files are selected 3932 * is known during the compaction execution, but the statistic is done just before compaction 3933 * starts, it is hard to know the compaction type at that time, so the rough statistics are chosen 3934 * for the mob file compaction. Only two compaction states are available, 3935 * CompactionState.MAJOR_AND_MINOR and CompactionState.NONE. 3936 * @param tableName The current table name. 3937 * @return If a given table is in mob file compaction now. 3938 */ 3939 public GetRegionInfoResponse.CompactionState getMobCompactionState(TableName tableName) { 3940 AtomicInteger compactionsCount = mobCompactionStates.get(tableName); 3941 if (compactionsCount != null && compactionsCount.get() != 0) { 3942 return GetRegionInfoResponse.CompactionState.MAJOR_AND_MINOR; 3943 } 3944 return GetRegionInfoResponse.CompactionState.NONE; 3945 } 3946 3947 public void reportMobCompactionStart(TableName tableName) throws IOException { 3948 IdLock.Entry lockEntry = null; 3949 try { 3950 lockEntry = mobCompactionLock.getLockEntry(tableName.hashCode()); 3951 AtomicInteger compactionsCount = mobCompactionStates.get(tableName); 3952 if (compactionsCount == null) { 3953 compactionsCount = new AtomicInteger(0); 3954 mobCompactionStates.put(tableName, compactionsCount); 3955 } 3956 compactionsCount.incrementAndGet(); 3957 } finally { 3958 if (lockEntry != null) { 3959 mobCompactionLock.releaseLockEntry(lockEntry); 3960 } 3961 } 3962 } 3963 3964 public void reportMobCompactionEnd(TableName tableName) throws IOException { 3965 IdLock.Entry lockEntry = null; 3966 try { 3967 lockEntry = mobCompactionLock.getLockEntry(tableName.hashCode()); 3968 AtomicInteger compactionsCount = mobCompactionStates.get(tableName); 3969 if (compactionsCount != null) { 3970 int count = compactionsCount.decrementAndGet(); 3971 // remove the entry if the count is 0. 3972 if (count == 0) { 3973 mobCompactionStates.remove(tableName); 3974 } 3975 } 3976 } finally { 3977 if (lockEntry != null) { 3978 mobCompactionLock.releaseLockEntry(lockEntry); 3979 } 3980 } 3981 } 3982 3983 /** 3984 * Queries the state of the {@link LoadBalancerStateStore}. If the balancer is not initialized, 3985 * false is returned. 3986 * @return The state of the load balancer, or false if the load balancer isn't defined. 3987 */ 3988 public boolean isBalancerOn() { 3989 return !isInMaintenanceMode() && loadBalancerStateStore != null && loadBalancerStateStore.get(); 3990 } 3991 3992 /** 3993 * Queries the state of the {@link RegionNormalizerStateStore}. If it's not initialized, false is 3994 * returned. 3995 */ 3996 public boolean isNormalizerOn() { 3997 return !isInMaintenanceMode() && getRegionNormalizerManager().isNormalizerOn(); 3998 } 3999 4000 /** 4001 * Queries the state of the {@link SplitOrMergeStateStore}. If it is not initialized, false is 4002 * returned. If switchType is illegal, false will return. 4003 * @param switchType see {@link org.apache.hadoop.hbase.client.MasterSwitchType} 4004 * @return The state of the switch 4005 */ 4006 @Override 4007 public boolean isSplitOrMergeEnabled(MasterSwitchType switchType) { 4008 return !isInMaintenanceMode() && splitOrMergeStateStore != null 4009 && splitOrMergeStateStore.isSplitOrMergeEnabled(switchType); 4010 } 4011 4012 /** 4013 * Fetch the configured {@link LoadBalancer} class name. If none is set, a default is returned. 4014 * <p/> 4015 * Notice that, the base load balancer will always be {@link RSGroupBasedLoadBalancer} now, so 4016 * this method will return the balancer used inside each rs group. 4017 * @return The name of the {@link LoadBalancer} in use. 4018 */ 4019 public String getLoadBalancerClassName() { 4020 return conf.get(HConstants.HBASE_MASTER_LOADBALANCER_CLASS, 4021 LoadBalancerFactory.getDefaultLoadBalancerClass().getName()); 4022 } 4023 4024 public SplitOrMergeStateStore getSplitOrMergeStateStore() { 4025 return splitOrMergeStateStore; 4026 } 4027 4028 @Override 4029 public RSGroupBasedLoadBalancer getLoadBalancer() { 4030 return balancer; 4031 } 4032 4033 @Override 4034 public FavoredNodesManager getFavoredNodesManager() { 4035 return balancer.getFavoredNodesManager(); 4036 } 4037 4038 private long executePeerProcedure(AbstractPeerProcedure<?> procedure) throws IOException { 4039 if (!isReplicationPeerModificationEnabled()) { 4040 throw new IOException("Replication peer modification disabled"); 4041 } 4042 long procId = procedureExecutor.submitProcedure(procedure); 4043 procedure.getLatch().await(); 4044 return procId; 4045 } 4046 4047 @Override 4048 public long addReplicationPeer(String peerId, ReplicationPeerConfig peerConfig, boolean enabled) 4049 throws ReplicationException, IOException { 4050 LOG.info(getClientIdAuditPrefix() + " creating replication peer, id=" + peerId + ", config=" 4051 + peerConfig + ", state=" + (enabled ? "ENABLED" : "DISABLED")); 4052 return executePeerProcedure(new AddPeerProcedure(peerId, peerConfig, enabled)); 4053 } 4054 4055 @Override 4056 public long removeReplicationPeer(String peerId) throws ReplicationException, IOException { 4057 LOG.info(getClientIdAuditPrefix() + " removing replication peer, id=" + peerId); 4058 return executePeerProcedure(new RemovePeerProcedure(peerId)); 4059 } 4060 4061 @Override 4062 public long enableReplicationPeer(String peerId) throws ReplicationException, IOException { 4063 LOG.info(getClientIdAuditPrefix() + " enable replication peer, id=" + peerId); 4064 return executePeerProcedure(new EnablePeerProcedure(peerId)); 4065 } 4066 4067 @Override 4068 public long disableReplicationPeer(String peerId) throws ReplicationException, IOException { 4069 LOG.info(getClientIdAuditPrefix() + " disable replication peer, id=" + peerId); 4070 return executePeerProcedure(new DisablePeerProcedure(peerId)); 4071 } 4072 4073 @Override 4074 public ReplicationPeerConfig getReplicationPeerConfig(String peerId) 4075 throws ReplicationException, IOException { 4076 if (cpHost != null) { 4077 cpHost.preGetReplicationPeerConfig(peerId); 4078 } 4079 LOG.info(getClientIdAuditPrefix() + " get replication peer config, id=" + peerId); 4080 ReplicationPeerConfig peerConfig = this.replicationPeerManager.getPeerConfig(peerId) 4081 .orElseThrow(() -> new ReplicationPeerNotFoundException(peerId)); 4082 if (cpHost != null) { 4083 cpHost.postGetReplicationPeerConfig(peerId); 4084 } 4085 return peerConfig; 4086 } 4087 4088 @Override 4089 public long updateReplicationPeerConfig(String peerId, ReplicationPeerConfig peerConfig) 4090 throws ReplicationException, IOException { 4091 LOG.info(getClientIdAuditPrefix() + " update replication peer config, id=" + peerId 4092 + ", config=" + peerConfig); 4093 return executePeerProcedure(new UpdatePeerConfigProcedure(peerId, peerConfig)); 4094 } 4095 4096 @Override 4097 public List<ReplicationPeerDescription> listReplicationPeers(String regex) 4098 throws ReplicationException, IOException { 4099 if (cpHost != null) { 4100 cpHost.preListReplicationPeers(regex); 4101 } 4102 LOG.debug("{} list replication peers, regex={}", getClientIdAuditPrefix(), regex); 4103 Pattern pattern = regex == null ? null : Pattern.compile(regex); 4104 List<ReplicationPeerDescription> peers = this.replicationPeerManager.listPeers(pattern); 4105 if (cpHost != null) { 4106 cpHost.postListReplicationPeers(regex); 4107 } 4108 return peers; 4109 } 4110 4111 @Override 4112 public long transitReplicationPeerSyncReplicationState(String peerId, SyncReplicationState state) 4113 throws ReplicationException, IOException { 4114 LOG.info( 4115 getClientIdAuditPrefix() 4116 + " transit current cluster state to {} in a synchronous replication peer id={}", 4117 state, peerId); 4118 return executePeerProcedure(new TransitPeerSyncReplicationStateProcedure(peerId, state)); 4119 } 4120 4121 @Override 4122 public boolean replicationPeerModificationSwitch(boolean on) throws IOException { 4123 return replicationPeerModificationStateStore.set(on); 4124 } 4125 4126 @Override 4127 public boolean isReplicationPeerModificationEnabled() { 4128 return replicationPeerModificationStateStore.get(); 4129 } 4130 4131 /** 4132 * Mark region server(s) as decommissioned (previously called 'draining') to prevent additional 4133 * regions from getting assigned to them. Also unload the regions on the servers asynchronously.0 4134 * @param servers Region servers to decommission. 4135 */ 4136 public void decommissionRegionServers(final List<ServerName> servers, final boolean offload) 4137 throws IOException { 4138 List<ServerName> serversAdded = new ArrayList<>(servers.size()); 4139 // Place the decommission marker first. 4140 String parentZnode = getZooKeeper().getZNodePaths().drainingZNode; 4141 for (ServerName server : servers) { 4142 try { 4143 String node = ZNodePaths.joinZNode(parentZnode, server.getServerName()); 4144 ZKUtil.createAndFailSilent(getZooKeeper(), node); 4145 } catch (KeeperException ke) { 4146 throw new HBaseIOException( 4147 this.zooKeeper.prefix("Unable to decommission '" + server.getServerName() + "'."), ke); 4148 } 4149 if (this.serverManager.addServerToDrainList(server)) { 4150 serversAdded.add(server); 4151 } 4152 } 4153 // Move the regions off the decommissioned servers. 4154 if (offload) { 4155 final List<ServerName> destServers = this.serverManager.createDestinationServersList(); 4156 for (ServerName server : serversAdded) { 4157 final List<RegionInfo> regionsOnServer = this.assignmentManager.getRegionsOnServer(server); 4158 for (RegionInfo hri : regionsOnServer) { 4159 ServerName dest = balancer.randomAssignment(hri, destServers); 4160 if (dest == null) { 4161 throw new HBaseIOException("Unable to determine a plan to move " + hri); 4162 } 4163 RegionPlan rp = new RegionPlan(hri, server, dest); 4164 this.assignmentManager.moveAsync(rp); 4165 } 4166 } 4167 } 4168 } 4169 4170 /** 4171 * List region servers marked as decommissioned (previously called 'draining') to not get regions 4172 * assigned to them. 4173 * @return List of decommissioned servers. 4174 */ 4175 public List<ServerName> listDecommissionedRegionServers() { 4176 return this.serverManager.getDrainingServersList(); 4177 } 4178 4179 /** 4180 * Remove decommission marker (previously called 'draining') from a region server to allow regions 4181 * assignments. Load regions onto the server asynchronously if a list of regions is given 4182 * @param server Region server to remove decommission marker from. 4183 */ 4184 public void recommissionRegionServer(final ServerName server, 4185 final List<byte[]> encodedRegionNames) throws IOException { 4186 // Remove the server from decommissioned (draining) server list. 4187 String parentZnode = getZooKeeper().getZNodePaths().drainingZNode; 4188 String node = ZNodePaths.joinZNode(parentZnode, server.getServerName()); 4189 try { 4190 ZKUtil.deleteNodeFailSilent(getZooKeeper(), node); 4191 } catch (KeeperException ke) { 4192 throw new HBaseIOException( 4193 this.zooKeeper.prefix("Unable to recommission '" + server.getServerName() + "'."), ke); 4194 } 4195 this.serverManager.removeServerFromDrainList(server); 4196 4197 // Load the regions onto the server if we are given a list of regions. 4198 if (encodedRegionNames == null || encodedRegionNames.isEmpty()) { 4199 return; 4200 } 4201 if (!this.serverManager.isServerOnline(server)) { 4202 return; 4203 } 4204 for (byte[] encodedRegionName : encodedRegionNames) { 4205 RegionState regionState = 4206 assignmentManager.getRegionStates().getRegionState(Bytes.toString(encodedRegionName)); 4207 if (regionState == null) { 4208 LOG.warn("Unknown region " + Bytes.toStringBinary(encodedRegionName)); 4209 continue; 4210 } 4211 RegionInfo hri = regionState.getRegion(); 4212 if (server.equals(regionState.getServerName())) { 4213 LOG.info("Skipping move of region " + hri.getRegionNameAsString() 4214 + " because region already assigned to the same server " + server + "."); 4215 continue; 4216 } 4217 RegionPlan rp = new RegionPlan(hri, regionState.getServerName(), server); 4218 this.assignmentManager.moveAsync(rp); 4219 } 4220 } 4221 4222 @Override 4223 public LockManager getLockManager() { 4224 return lockManager; 4225 } 4226 4227 public QuotaObserverChore getQuotaObserverChore() { 4228 return this.quotaObserverChore; 4229 } 4230 4231 public SpaceQuotaSnapshotNotifier getSpaceQuotaSnapshotNotifier() { 4232 return this.spaceQuotaSnapshotNotifier; 4233 } 4234 4235 @SuppressWarnings("unchecked") 4236 private RemoteProcedure<MasterProcedureEnv, ?> getRemoteProcedure(long procId) { 4237 Procedure<?> procedure = procedureExecutor.getProcedure(procId); 4238 if (procedure == null) { 4239 return null; 4240 } 4241 assert procedure instanceof RemoteProcedure; 4242 return (RemoteProcedure<MasterProcedureEnv, ?>) procedure; 4243 } 4244 4245 public void remoteProcedureCompleted(long procId, byte[] remoteResultData) { 4246 LOG.debug("Remote procedure done, pid={}", procId); 4247 RemoteProcedure<MasterProcedureEnv, ?> procedure = getRemoteProcedure(procId); 4248 if (procedure != null) { 4249 procedure.remoteOperationCompleted(procedureExecutor.getEnvironment(), remoteResultData); 4250 } 4251 } 4252 4253 public void remoteProcedureFailed(long procId, RemoteProcedureException error) { 4254 LOG.debug("Remote procedure failed, pid={}", procId, error); 4255 RemoteProcedure<MasterProcedureEnv, ?> procedure = getRemoteProcedure(procId); 4256 if (procedure != null) { 4257 procedure.remoteOperationFailed(procedureExecutor.getEnvironment(), error); 4258 } 4259 } 4260 4261 /** 4262 * Reopen regions provided in the argument 4263 * @param tableName The current table name 4264 * @param regionNames The region names of the regions to reopen 4265 * @param nonceGroup Identifier for the source of the request, a client or process 4266 * @param nonce A unique identifier for this operation from the client or process identified 4267 * by <code>nonceGroup</code> (the source must ensure each operation gets a 4268 * unique id). 4269 * @return procedure Id 4270 * @throws IOException if reopening region fails while running procedure 4271 */ 4272 long reopenRegions(final TableName tableName, final List<byte[]> regionNames, 4273 final long nonceGroup, final long nonce) throws IOException { 4274 4275 return MasterProcedureUtil 4276 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4277 4278 @Override 4279 protected void run() throws IOException { 4280 submitProcedure(new ReopenTableRegionsProcedure(tableName, regionNames)); 4281 } 4282 4283 @Override 4284 protected String getDescription() { 4285 return "ReopenTableRegionsProcedure"; 4286 } 4287 4288 }); 4289 4290 } 4291 4292 /** 4293 * Reopen regions provided in the argument. Applies throttling to the procedure to avoid 4294 * overwhelming the system. This is used by the reopenTableRegions methods in the Admin API via 4295 * HMaster. 4296 * @param tableName The current table name 4297 * @param regionNames The region names of the regions to reopen 4298 * @param nonceGroup Identifier for the source of the request, a client or process 4299 * @param nonce A unique identifier for this operation from the client or process identified 4300 * by <code>nonceGroup</code> (the source must ensure each operation gets a 4301 * unique id). 4302 * @return procedure Id 4303 * @throws IOException if reopening region fails while running procedure 4304 */ 4305 long reopenRegionsThrottled(final TableName tableName, final List<byte[]> regionNames, 4306 final long nonceGroup, final long nonce) throws IOException { 4307 4308 checkInitialized(); 4309 4310 if (!tableStateManager.isTablePresent(tableName)) { 4311 throw new TableNotFoundException(tableName); 4312 } 4313 4314 return MasterProcedureUtil 4315 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4316 @Override 4317 protected void run() throws IOException { 4318 ReopenTableRegionsProcedure proc; 4319 if (regionNames.isEmpty()) { 4320 proc = ReopenTableRegionsProcedure.throttled(getConfiguration(), 4321 getTableDescriptors().get(tableName)); 4322 } else { 4323 proc = ReopenTableRegionsProcedure.throttled(getConfiguration(), 4324 getTableDescriptors().get(tableName), regionNames); 4325 } 4326 4327 LOG.info("{} throttled reopening {} regions for table {}", getClientIdAuditPrefix(), 4328 regionNames.isEmpty() ? "all" : regionNames.size(), tableName); 4329 4330 submitProcedure(proc); 4331 } 4332 4333 @Override 4334 protected String getDescription() { 4335 return "Throttled ReopenTableRegionsProcedure for " + tableName; 4336 } 4337 }); 4338 } 4339 4340 @Override 4341 public ReplicationPeerManager getReplicationPeerManager() { 4342 return replicationPeerManager; 4343 } 4344 4345 @Override 4346 public ReplicationLogCleanerBarrier getReplicationLogCleanerBarrier() { 4347 return replicationLogCleanerBarrier; 4348 } 4349 4350 @Override 4351 public Semaphore getSyncReplicationPeerLock() { 4352 return syncReplicationPeerLock; 4353 } 4354 4355 public HashMap<String, List<Pair<ServerName, ReplicationLoadSource>>> 4356 getReplicationLoad(ServerName[] serverNames) { 4357 List<ReplicationPeerDescription> peerList = this.getReplicationPeerManager().listPeers(null); 4358 if (peerList == null) { 4359 return null; 4360 } 4361 HashMap<String, List<Pair<ServerName, ReplicationLoadSource>>> replicationLoadSourceMap = 4362 new HashMap<>(peerList.size()); 4363 peerList.stream() 4364 .forEach(peer -> replicationLoadSourceMap.put(peer.getPeerId(), new ArrayList<>())); 4365 for (ServerName serverName : serverNames) { 4366 List<ReplicationLoadSource> replicationLoadSources = 4367 getServerManager().getLoad(serverName).getReplicationLoadSourceList(); 4368 for (ReplicationLoadSource replicationLoadSource : replicationLoadSources) { 4369 List<Pair<ServerName, ReplicationLoadSource>> replicationLoadSourceList = 4370 replicationLoadSourceMap.get(replicationLoadSource.getPeerID()); 4371 if (replicationLoadSourceList == null) { 4372 LOG.debug("{} does not exist, but it exists " 4373 + "in znode(/hbase/replication/rs). when the rs restarts, peerId is deleted, so " 4374 + "we just need to ignore it", replicationLoadSource.getPeerID()); 4375 continue; 4376 } 4377 replicationLoadSourceList.add(new Pair<>(serverName, replicationLoadSource)); 4378 } 4379 } 4380 for (List<Pair<ServerName, ReplicationLoadSource>> loads : replicationLoadSourceMap.values()) { 4381 if (loads.size() > 0) { 4382 loads.sort(Comparator.comparingLong(load -> (-1) * load.getSecond().getReplicationLag())); 4383 } 4384 } 4385 return replicationLoadSourceMap; 4386 } 4387 4388 /** 4389 * This method modifies the master's configuration in order to inject replication-related features 4390 */ 4391 @InterfaceAudience.Private 4392 public static void decorateMasterConfiguration(Configuration conf) { 4393 String plugins = conf.get(HBASE_MASTER_LOGCLEANER_PLUGINS); 4394 String cleanerClass = ReplicationLogCleaner.class.getCanonicalName(); 4395 if (plugins == null || !plugins.contains(cleanerClass)) { 4396 conf.set(HBASE_MASTER_LOGCLEANER_PLUGINS, plugins + "," + cleanerClass); 4397 } 4398 if (ReplicationUtils.isReplicationForBulkLoadDataEnabled(conf)) { 4399 plugins = conf.get(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS); 4400 cleanerClass = ReplicationHFileCleaner.class.getCanonicalName(); 4401 if (!plugins.contains(cleanerClass)) { 4402 conf.set(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS, plugins + "," + cleanerClass); 4403 } 4404 } 4405 } 4406 4407 public SnapshotQuotaObserverChore getSnapshotQuotaObserverChore() { 4408 return this.snapshotQuotaChore; 4409 } 4410 4411 public ActiveMasterManager getActiveMasterManager() { 4412 return activeMasterManager; 4413 } 4414 4415 @Override 4416 public SyncReplicationReplayWALManager getSyncReplicationReplayWALManager() { 4417 return this.syncReplicationReplayWALManager; 4418 } 4419 4420 @Override 4421 public HbckChore getHbckChore() { 4422 return this.hbckChore; 4423 } 4424 4425 @Override 4426 public void runReplicationBarrierCleaner() { 4427 ReplicationBarrierCleaner rbc = this.replicationBarrierCleaner; 4428 if (rbc != null) { 4429 rbc.chore(); 4430 } 4431 } 4432 4433 @Override 4434 public RSGroupInfoManager getRSGroupInfoManager() { 4435 return rsGroupInfoManager; 4436 } 4437 4438 /** 4439 * Get the compaction state of the table 4440 * @param tableName The table name 4441 * @return CompactionState Compaction state of the table 4442 */ 4443 public CompactionState getCompactionState(final TableName tableName) { 4444 CompactionState compactionState = CompactionState.NONE; 4445 try { 4446 List<RegionInfo> regions = assignmentManager.getRegionStates().getRegionsOfTable(tableName); 4447 for (RegionInfo regionInfo : regions) { 4448 ServerName serverName = 4449 assignmentManager.getRegionStates().getRegionServerOfRegion(regionInfo); 4450 if (serverName == null) { 4451 continue; 4452 } 4453 ServerMetrics sl = serverManager.getLoad(serverName); 4454 if (sl == null) { 4455 continue; 4456 } 4457 RegionMetrics regionMetrics = sl.getRegionMetrics().get(regionInfo.getRegionName()); 4458 if (regionMetrics == null) { 4459 LOG.warn("Can not get compaction details for the region: {} , it may be not online.", 4460 regionInfo.getRegionNameAsString()); 4461 continue; 4462 } 4463 if (regionMetrics.getCompactionState() == CompactionState.MAJOR) { 4464 if (compactionState == CompactionState.MINOR) { 4465 compactionState = CompactionState.MAJOR_AND_MINOR; 4466 } else { 4467 compactionState = CompactionState.MAJOR; 4468 } 4469 } else if (regionMetrics.getCompactionState() == CompactionState.MINOR) { 4470 if (compactionState == CompactionState.MAJOR) { 4471 compactionState = CompactionState.MAJOR_AND_MINOR; 4472 } else { 4473 compactionState = CompactionState.MINOR; 4474 } 4475 } 4476 } 4477 } catch (Exception e) { 4478 compactionState = null; 4479 LOG.error("Exception when get compaction state for " + tableName.getNameAsString(), e); 4480 } 4481 return compactionState; 4482 } 4483 4484 @Override 4485 public MetaLocationSyncer getMetaLocationSyncer() { 4486 return metaLocationSyncer; 4487 } 4488 4489 @RestrictedApi(explanation = "Should only be called in tests", link = "", 4490 allowedOnPath = ".*/src/test/.*") 4491 public MasterRegion getMasterRegion() { 4492 return masterRegion; 4493 } 4494 4495 /** 4496 * Dynamically updates HMaster's configuration. Since HMaster inherits from 4497 * {@link HBaseServerBase}, the {@code updatedConf} parameter references the same 4498 * {@link Configuration} object as HMaster's {@code this.conf} instance variable in a real HBase 4499 * deployment. This isn't necessarily the case in unit tests. 4500 * @param updatedConf the dynamically updated configuration 4501 */ 4502 @Override 4503 public void onConfigurationChange(Configuration updatedConf) { 4504 try { 4505 Superusers.initialize(updatedConf); 4506 } catch (IOException e) { 4507 LOG.warn("Failed to initialize SuperUsers on reloading of the configuration"); 4508 } 4509 // append the quotas observer back to the master coprocessor key 4510 setQuotasObserver(updatedConf); 4511 4512 boolean originalIsReadOnlyEnabled = CoprocessorConfigurationUtil 4513 .areReadOnlyCoprocessorsLoaded(this.conf, CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY); 4514 4515 // updatedConf and this.conf reference the same Configuration object in an actual HBase 4516 // deployment. However, in unit test cases they reference different Configuration objects, so 4517 // this.conf needs to be updated. 4518 CoprocessorConfigurationUtil.maybeUpdateCoprocessors(updatedConf, this.conf, 4519 originalIsReadOnlyEnabled, this.cpHost, CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, 4520 this.maintenanceMode, this.toString(), this::initializeCoprocessorHost); 4521 4522 boolean maybeUpdatedReadOnlyMode = CoprocessorConfigurationUtil 4523 .areReadOnlyCoprocessorsLoaded(this.conf, CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY); 4524 4525 if (maybeUpdatedReadOnlyMode != originalIsReadOnlyEnabled) { 4526 AbstractReadOnlyController.manageActiveClusterIdFile(maybeUpdatedReadOnlyMode, 4527 this.getMasterFileSystem()); 4528 } 4529 } 4530 4531 @Override 4532 protected NamedQueueRecorder createNamedQueueRecord() { 4533 final boolean isBalancerDecisionRecording = 4534 conf.getBoolean(BaseLoadBalancer.BALANCER_DECISION_BUFFER_ENABLED, 4535 BaseLoadBalancer.DEFAULT_BALANCER_DECISION_BUFFER_ENABLED); 4536 final boolean isBalancerRejectionRecording = 4537 conf.getBoolean(BaseLoadBalancer.BALANCER_REJECTION_BUFFER_ENABLED, 4538 BaseLoadBalancer.DEFAULT_BALANCER_REJECTION_BUFFER_ENABLED); 4539 if (isBalancerDecisionRecording || isBalancerRejectionRecording) { 4540 return NamedQueueRecorder.getInstance(conf); 4541 } else { 4542 return null; 4543 } 4544 } 4545 4546 @Override 4547 protected boolean clusterMode() { 4548 return true; 4549 } 4550 4551 public String getClusterId() { 4552 if (activeMaster) { 4553 return clusterId; 4554 } 4555 return cachedClusterId.getFromCacheOrFetch(); 4556 } 4557 4558 public Optional<ServerName> getActiveMaster() { 4559 return activeMasterManager.getActiveMasterServerName(); 4560 } 4561 4562 public List<ServerName> getBackupMasters() { 4563 return activeMasterManager.getBackupMasters(); 4564 } 4565 4566 @Override 4567 public Iterator<ServerName> getBootstrapNodes() { 4568 return regionServerTracker.getRegionServers().iterator(); 4569 } 4570 4571 @Override 4572 public List<HRegionLocation> getMetaLocations() { 4573 return metaRegionLocationCache.getMetaRegionLocations(); 4574 } 4575 4576 @Override 4577 public void flushMasterStore() throws IOException { 4578 LOG.info("Force flush master local region."); 4579 if (this.cpHost != null) { 4580 try { 4581 cpHost.preMasterStoreFlush(); 4582 } catch (IOException ioe) { 4583 LOG.error("Error invoking master coprocessor preMasterStoreFlush()", ioe); 4584 } 4585 } 4586 masterRegion.flush(true); 4587 if (this.cpHost != null) { 4588 try { 4589 cpHost.postMasterStoreFlush(); 4590 } catch (IOException ioe) { 4591 LOG.error("Error invoking master coprocessor postMasterStoreFlush()", ioe); 4592 } 4593 } 4594 } 4595 4596 public Collection<ServerName> getLiveRegionServers() { 4597 return regionServerTracker.getRegionServers(); 4598 } 4599 4600 @RestrictedApi(explanation = "Should only be called in tests", link = "", 4601 allowedOnPath = ".*/src/test/.*") 4602 void setLoadBalancer(RSGroupBasedLoadBalancer loadBalancer) { 4603 this.balancer = loadBalancer; 4604 } 4605 4606 @RestrictedApi(explanation = "Should only be called in tests", link = "", 4607 allowedOnPath = ".*/src/test/.*") 4608 void setAssignmentManager(AssignmentManager assignmentManager) { 4609 this.assignmentManager = assignmentManager; 4610 } 4611 4612 @RestrictedApi(explanation = "Should only be called in tests", link = "", 4613 allowedOnPath = ".*/src/test/.*") 4614 static void setDisableBalancerChoreForTest(boolean disable) { 4615 disableBalancerChoreForTest = disable; 4616 } 4617 4618 private void setQuotasObserver(Configuration conf) { 4619 // Add the Observer to delete quotas on table deletion before starting all CPs by 4620 // default with quota support, avoiding if user specifically asks to not load this Observer. 4621 if (QuotaUtil.isQuotaEnabled(conf)) { 4622 updateConfigurationForQuotasObserver(conf); 4623 } 4624 } 4625 4626 private void initializeCoprocessorHost(Configuration conf) { 4627 // initialize master side coprocessors before we start handling requests 4628 this.cpHost = new MasterCoprocessorHost(this, conf); 4629 } 4630 4631 @Override 4632 public long flushTable(TableName tableName, List<byte[]> columnFamilies, long nonceGroup, 4633 long nonce) throws IOException { 4634 checkInitialized(); 4635 4636 if ( 4637 !getConfiguration().getBoolean(MasterFlushTableProcedureManager.FLUSH_PROCEDURE_ENABLED, 4638 MasterFlushTableProcedureManager.FLUSH_PROCEDURE_ENABLED_DEFAULT) 4639 ) { 4640 throw new DoNotRetryIOException("FlushTableProcedureV2 is DISABLED"); 4641 } 4642 4643 return MasterProcedureUtil 4644 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4645 @Override 4646 protected void run() throws IOException { 4647 getMaster().getMasterCoprocessorHost().preTableFlush(tableName); 4648 LOG.info("{} flush {}", getClientIdAuditPrefix(), tableName); 4649 submitProcedure( 4650 new FlushTableProcedure(procedureExecutor.getEnvironment(), tableName, columnFamilies)); 4651 getMaster().getMasterCoprocessorHost().postTableFlush(tableName); 4652 } 4653 4654 @Override 4655 protected String getDescription() { 4656 return "FlushTableProcedure"; 4657 } 4658 }); 4659 } 4660 4661 @Override 4662 public long rollAllWALWriters(long nonceGroup, long nonce) throws IOException { 4663 return MasterProcedureUtil 4664 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4665 @Override 4666 protected void run() { 4667 LOG.info("{} roll all wal writers", getClientIdAuditPrefix()); 4668 submitProcedure(new LogRollProcedure()); 4669 } 4670 4671 @Override 4672 protected String getDescription() { 4673 return "RollAllWALWriters"; 4674 } 4675 }); 4676 } 4677 4678 @RestrictedApi(explanation = "Should only be called in tests", link = "", 4679 allowedOnPath = ".*/src/test/.*") 4680 public MobFileCleanerChore getMobFileCleanerChore() { 4681 return mobFileCleanerChore; 4682 } 4683 4684 public Long refreshMeta(long nonceGroup, long nonce) throws IOException { 4685 return MasterProcedureUtil 4686 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4687 @Override 4688 protected void run() throws IOException { 4689 LOG.info("Submitting RefreshMetaProcedure"); 4690 submitProcedure(new RefreshMetaProcedure(procedureExecutor.getEnvironment())); 4691 } 4692 4693 @Override 4694 protected String getDescription() { 4695 return "RefreshMetaProcedure"; 4696 } 4697 }); 4698 } 4699 4700 public Long refreshHfiles(final TableName tableName, final long nonceGroup, final long nonce) 4701 throws IOException { 4702 checkInitialized(); 4703 4704 if (!tableDescriptors.exists(tableName)) { 4705 LOG.info("RefreshHfilesProcedure failed because table {} does not exist", 4706 tableName.getNameAsString()); 4707 throw new TableNotFoundException(tableName); 4708 } 4709 4710 return MasterProcedureUtil 4711 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4712 @Override 4713 protected void run() throws IOException { 4714 LOG.info("Submitting RefreshHfilesTableProcedure for table {}", 4715 tableName.getNameAsString()); 4716 submitProcedure( 4717 new RefreshHFilesTableProcedure(procedureExecutor.getEnvironment(), tableName)); 4718 } 4719 4720 @Override 4721 protected String getDescription() { 4722 return "RefreshHfilesProcedure for a table"; 4723 } 4724 }); 4725 } 4726 4727 public Long refreshHfiles(final String namespace, final long nonceGroup, final long nonce) 4728 throws IOException { 4729 checkInitialized(); 4730 4731 try { 4732 this.clusterSchemaService.getNamespace(namespace); 4733 } catch (IOException e) { 4734 LOG.info("RefreshHfilesProcedure failed because namespace {} does not exist", namespace); 4735 throw new NamespaceNotFoundException(namespace); 4736 } 4737 4738 return MasterProcedureUtil 4739 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4740 @Override 4741 protected void run() throws IOException { 4742 LOG.info("Submitting RefreshHfilesProcedure for namespace {}", namespace); 4743 submitProcedure( 4744 new RefreshHFilesTableProcedure(procedureExecutor.getEnvironment(), namespace)); 4745 } 4746 4747 @Override 4748 protected String getDescription() { 4749 return "RefreshHfilesProcedure for namespace"; 4750 } 4751 }); 4752 } 4753 4754 public Long refreshHfiles(final long nonceGroup, final long nonce) throws IOException { 4755 checkInitialized(); 4756 4757 return MasterProcedureUtil 4758 .submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 4759 @Override 4760 protected void run() throws IOException { 4761 LOG.info("Submitting RefreshHfilesProcedure for all tables"); 4762 submitProcedure(new RefreshHFilesTableProcedure(procedureExecutor.getEnvironment())); 4763 } 4764 4765 @Override 4766 protected String getDescription() { 4767 return "RefreshHfilesProcedure for all tables"; 4768 } 4769 }); 4770 } 4771}