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