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