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