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