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.HBASE_MASTER_LOGCLEANER_PLUGINS; 021 022import com.google.protobuf.Descriptors; 023import com.google.protobuf.Service; 024import java.io.IOException; 025import java.io.InterruptedIOException; 026import java.lang.reflect.Constructor; 027import java.lang.reflect.InvocationTargetException; 028import java.net.InetAddress; 029import java.net.InetSocketAddress; 030import java.net.UnknownHostException; 031import java.util.ArrayList; 032import java.util.Arrays; 033import java.util.Collection; 034import java.util.Collections; 035import java.util.Comparator; 036import java.util.EnumSet; 037import java.util.HashMap; 038import java.util.Iterator; 039import java.util.List; 040import java.util.Map; 041import java.util.Map.Entry; 042import java.util.Objects; 043import java.util.Set; 044import java.util.concurrent.ExecutionException; 045import java.util.concurrent.Future; 046import java.util.concurrent.TimeUnit; 047import java.util.concurrent.TimeoutException; 048import java.util.concurrent.atomic.AtomicInteger; 049import java.util.concurrent.atomic.AtomicReference; 050import java.util.function.Function; 051import java.util.regex.Pattern; 052import java.util.stream.Collectors; 053import javax.servlet.ServletException; 054import javax.servlet.http.HttpServlet; 055import javax.servlet.http.HttpServletRequest; 056import javax.servlet.http.HttpServletResponse; 057import org.apache.commons.lang3.StringUtils; 058import org.apache.hadoop.conf.Configuration; 059import org.apache.hadoop.fs.Path; 060import org.apache.hadoop.hbase.ClusterId; 061import org.apache.hadoop.hbase.ClusterMetrics; 062import org.apache.hadoop.hbase.ClusterMetrics.Option; 063import org.apache.hadoop.hbase.ClusterMetricsBuilder; 064import org.apache.hadoop.hbase.DoNotRetryIOException; 065import org.apache.hadoop.hbase.HBaseIOException; 066import org.apache.hadoop.hbase.HBaseInterfaceAudience; 067import org.apache.hadoop.hbase.HConstants; 068import org.apache.hadoop.hbase.InvalidFamilyOperationException; 069import org.apache.hadoop.hbase.MasterNotRunningException; 070import org.apache.hadoop.hbase.MetaTableAccessor; 071import org.apache.hadoop.hbase.NamespaceDescriptor; 072import org.apache.hadoop.hbase.PleaseHoldException; 073import org.apache.hadoop.hbase.ServerMetricsBuilder; 074import org.apache.hadoop.hbase.ServerName; 075import org.apache.hadoop.hbase.TableDescriptors; 076import org.apache.hadoop.hbase.TableName; 077import org.apache.hadoop.hbase.TableNotDisabledException; 078import org.apache.hadoop.hbase.TableNotFoundException; 079import org.apache.hadoop.hbase.UnknownRegionException; 080import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; 081import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; 082import org.apache.hadoop.hbase.client.MasterSwitchType; 083import org.apache.hadoop.hbase.client.RegionInfo; 084import org.apache.hadoop.hbase.client.Result; 085import org.apache.hadoop.hbase.client.TableDescriptor; 086import org.apache.hadoop.hbase.client.TableDescriptorBuilder; 087import org.apache.hadoop.hbase.client.TableState; 088import org.apache.hadoop.hbase.coprocessor.CoprocessorHost; 089import org.apache.hadoop.hbase.exceptions.DeserializationException; 090import org.apache.hadoop.hbase.exceptions.MergeRegionException; 091import org.apache.hadoop.hbase.executor.ExecutorType; 092import org.apache.hadoop.hbase.favored.FavoredNodesManager; 093import org.apache.hadoop.hbase.favored.FavoredNodesPromoter; 094import org.apache.hadoop.hbase.http.InfoServer; 095import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils; 096import org.apache.hadoop.hbase.ipc.RpcServer; 097import org.apache.hadoop.hbase.ipc.ServerNotRunningYetException; 098import org.apache.hadoop.hbase.log.HBaseMarkers; 099import org.apache.hadoop.hbase.master.MasterRpcServices.BalanceSwitchMode; 100import org.apache.hadoop.hbase.master.assignment.AssignmentManager; 101import org.apache.hadoop.hbase.master.assignment.MergeTableRegionsProcedure; 102import org.apache.hadoop.hbase.master.assignment.RegionStates; 103import org.apache.hadoop.hbase.master.assignment.RegionStates.RegionStateNode; 104import org.apache.hadoop.hbase.master.balancer.BalancerChore; 105import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer; 106import org.apache.hadoop.hbase.master.balancer.ClusterStatusChore; 107import org.apache.hadoop.hbase.master.balancer.LoadBalancerFactory; 108import org.apache.hadoop.hbase.master.cleaner.HFileCleaner; 109import org.apache.hadoop.hbase.master.cleaner.LogCleaner; 110import org.apache.hadoop.hbase.master.cleaner.ReplicationZKNodeCleaner; 111import org.apache.hadoop.hbase.master.cleaner.ReplicationZKNodeCleanerChore; 112import org.apache.hadoop.hbase.master.locking.LockManager; 113import org.apache.hadoop.hbase.master.normalizer.NormalizationPlan; 114import org.apache.hadoop.hbase.master.normalizer.NormalizationPlan.PlanType; 115import org.apache.hadoop.hbase.master.normalizer.RegionNormalizer; 116import org.apache.hadoop.hbase.master.normalizer.RegionNormalizerChore; 117import org.apache.hadoop.hbase.master.normalizer.RegionNormalizerFactory; 118import org.apache.hadoop.hbase.master.procedure.CreateTableProcedure; 119import org.apache.hadoop.hbase.master.procedure.DeleteNamespaceProcedure; 120import org.apache.hadoop.hbase.master.procedure.DeleteTableProcedure; 121import org.apache.hadoop.hbase.master.procedure.DisableTableProcedure; 122import org.apache.hadoop.hbase.master.procedure.EnableTableProcedure; 123import org.apache.hadoop.hbase.master.procedure.MasterProcedureConstants; 124import org.apache.hadoop.hbase.master.procedure.MasterProcedureEnv; 125import org.apache.hadoop.hbase.master.procedure.MasterProcedureScheduler; 126import org.apache.hadoop.hbase.master.procedure.MasterProcedureUtil; 127import org.apache.hadoop.hbase.master.procedure.ModifyTableProcedure; 128import org.apache.hadoop.hbase.master.procedure.ProcedurePrepareLatch; 129import org.apache.hadoop.hbase.master.procedure.RecoverMetaProcedure; 130import org.apache.hadoop.hbase.master.procedure.TruncateTableProcedure; 131import org.apache.hadoop.hbase.master.replication.ReplicationManager; 132import org.apache.hadoop.hbase.master.snapshot.SnapshotManager; 133import org.apache.hadoop.hbase.mob.MobConstants; 134import org.apache.hadoop.hbase.monitoring.MemoryBoundedLogMessageBuffer; 135import org.apache.hadoop.hbase.monitoring.MonitoredTask; 136import org.apache.hadoop.hbase.monitoring.TaskMonitor; 137import org.apache.hadoop.hbase.procedure.MasterProcedureManagerHost; 138import org.apache.hadoop.hbase.procedure.flush.MasterFlushTableProcedureManager; 139import org.apache.hadoop.hbase.procedure2.LockedResource; 140import org.apache.hadoop.hbase.procedure2.Procedure; 141import org.apache.hadoop.hbase.procedure2.ProcedureEvent; 142import org.apache.hadoop.hbase.procedure2.ProcedureExecutor; 143import org.apache.hadoop.hbase.procedure2.store.wal.WALProcedureStore; 144import org.apache.hadoop.hbase.quotas.MasterQuotaManager; 145import org.apache.hadoop.hbase.quotas.MasterSpaceQuotaObserver; 146import org.apache.hadoop.hbase.quotas.QuotaObserverChore; 147import org.apache.hadoop.hbase.quotas.QuotaUtil; 148import org.apache.hadoop.hbase.quotas.SnapshotQuotaObserverChore; 149import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshotNotifier; 150import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshotNotifierFactory; 151import org.apache.hadoop.hbase.regionserver.DefaultStoreEngine; 152import org.apache.hadoop.hbase.regionserver.HRegionServer; 153import org.apache.hadoop.hbase.regionserver.HStore; 154import org.apache.hadoop.hbase.regionserver.RSRpcServices; 155import org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost; 156import org.apache.hadoop.hbase.regionserver.RegionSplitPolicy; 157import org.apache.hadoop.hbase.regionserver.compactions.ExploringCompactionPolicy; 158import org.apache.hadoop.hbase.regionserver.compactions.FIFOCompactionPolicy; 159import org.apache.hadoop.hbase.replication.ReplicationException; 160import org.apache.hadoop.hbase.replication.ReplicationPeerConfig; 161import org.apache.hadoop.hbase.replication.ReplicationPeerDescription; 162import org.apache.hadoop.hbase.replication.ReplicationUtils; 163import org.apache.hadoop.hbase.replication.master.ReplicationHFileCleaner; 164import org.apache.hadoop.hbase.replication.master.ReplicationLogCleaner; 165import org.apache.hadoop.hbase.replication.master.ReplicationPeerConfigUpgrader; 166import org.apache.hadoop.hbase.security.AccessDeniedException; 167import org.apache.hadoop.hbase.security.UserProvider; 168import org.apache.hadoop.hbase.trace.TraceUtil; 169import org.apache.hadoop.hbase.util.Addressing; 170import org.apache.hadoop.hbase.util.Bytes; 171import org.apache.hadoop.hbase.util.CompressionTest; 172import org.apache.hadoop.hbase.util.EncryptionTest; 173import org.apache.hadoop.hbase.util.HFileArchiveUtil; 174import org.apache.hadoop.hbase.util.HasThread; 175import org.apache.hadoop.hbase.util.IdLock; 176import org.apache.hadoop.hbase.util.ModifyRegionUtils; 177import org.apache.hadoop.hbase.util.Pair; 178import org.apache.hadoop.hbase.util.Threads; 179import org.apache.hadoop.hbase.util.VersionInfo; 180import org.apache.hadoop.hbase.zookeeper.LoadBalancerTracker; 181import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker; 182import org.apache.hadoop.hbase.zookeeper.MasterMaintenanceModeTracker; 183import org.apache.hadoop.hbase.zookeeper.RegionNormalizerTracker; 184import org.apache.hadoop.hbase.zookeeper.ZKClusterId; 185import org.apache.hadoop.hbase.zookeeper.ZKUtil; 186import org.apache.hadoop.hbase.zookeeper.ZKWatcher; 187import org.apache.hadoop.hbase.zookeeper.ZNodePaths; 188import org.apache.yetus.audience.InterfaceAudience; 189import org.apache.zookeeper.KeeperException; 190import org.eclipse.jetty.server.Server; 191import org.eclipse.jetty.server.ServerConnector; 192import org.eclipse.jetty.servlet.ServletHolder; 193import org.eclipse.jetty.webapp.WebAppContext; 194import org.slf4j.Logger; 195import org.slf4j.LoggerFactory; 196 197import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting; 198import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 199import org.apache.hbase.thirdparty.com.google.common.collect.Maps; 200 201import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 202import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoResponse.CompactionState; 203import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.RegionServerInfo; 204import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.Quotas; 205import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.SpaceViolationPolicy; 206import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos.SnapshotDescription; 207import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos; 208 209/** 210 * HMaster is the "master server" for HBase. An HBase cluster has one active 211 * master. If many masters are started, all compete. Whichever wins goes on to 212 * run the cluster. All others park themselves in their constructor until 213 * master or cluster shutdown or until the active master loses its lease in 214 * zookeeper. Thereafter, all running master jostle to take over master role. 215 * 216 * <p>The Master can be asked shutdown the cluster. See {@link #shutdown()}. In 217 * this case it will tell all regionservers to go down and then wait on them 218 * all reporting in that they are down. This master will then shut itself down. 219 * 220 * <p>You can also shutdown just this master. Call {@link #stopMaster()}. 221 * 222 * @see org.apache.zookeeper.Watcher 223 */ 224@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS) 225@SuppressWarnings("deprecation") 226public class HMaster extends HRegionServer implements MasterServices { 227 private static Logger LOG = LoggerFactory.getLogger(HMaster.class.getName()); 228 229 /** 230 * Protection against zombie master. Started once Master accepts active responsibility and 231 * starts taking over responsibilities. Allows a finite time window before giving up ownership. 232 */ 233 private static class InitializationMonitor extends HasThread { 234 /** The amount of time in milliseconds to sleep before checking initialization status. */ 235 public static final String TIMEOUT_KEY = "hbase.master.initializationmonitor.timeout"; 236 public static final long TIMEOUT_DEFAULT = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES); 237 238 /** 239 * When timeout expired and initialization has not complete, call {@link System#exit(int)} when 240 * true, do nothing otherwise. 241 */ 242 public static final String HALT_KEY = "hbase.master.initializationmonitor.haltontimeout"; 243 public static final boolean HALT_DEFAULT = false; 244 245 private final HMaster master; 246 private final long timeout; 247 private final boolean haltOnTimeout; 248 249 /** Creates a Thread that monitors the {@link #isInitialized()} state. */ 250 InitializationMonitor(HMaster master) { 251 super("MasterInitializationMonitor"); 252 this.master = master; 253 this.timeout = master.getConfiguration().getLong(TIMEOUT_KEY, TIMEOUT_DEFAULT); 254 this.haltOnTimeout = master.getConfiguration().getBoolean(HALT_KEY, HALT_DEFAULT); 255 this.setDaemon(true); 256 } 257 258 @Override 259 public void run() { 260 try { 261 while (!master.isStopped() && master.isActiveMaster()) { 262 Thread.sleep(timeout); 263 if (master.isInitialized()) { 264 LOG.debug("Initialization completed within allotted tolerance. Monitor exiting."); 265 } else { 266 LOG.error("Master failed to complete initialization after " + timeout + "ms. Please" 267 + " consider submitting a bug report including a thread dump of this process."); 268 if (haltOnTimeout) { 269 LOG.error("Zombie Master exiting. Thread dump to stdout"); 270 Threads.printThreadInfo(System.out, "Zombie HMaster"); 271 System.exit(-1); 272 } 273 } 274 } 275 } catch (InterruptedException ie) { 276 LOG.trace("InitMonitor thread interrupted. Existing."); 277 } 278 } 279 } 280 281 // MASTER is name of the webapp and the attribute name used stuffing this 282 //instance into web context. 283 public static final String MASTER = "master"; 284 285 // Manager and zk listener for master election 286 private final ActiveMasterManager activeMasterManager; 287 // Region server tracker 288 RegionServerTracker regionServerTracker; 289 // Draining region server tracker 290 private DrainingServerTracker drainingServerTracker; 291 // Tracker for load balancer state 292 LoadBalancerTracker loadBalancerTracker; 293 294 // Tracker for split and merge state 295 private SplitOrMergeTracker splitOrMergeTracker; 296 297 // Tracker for region normalizer state 298 private RegionNormalizerTracker regionNormalizerTracker; 299 300 //Tracker for master maintenance mode setting 301 private MasterMaintenanceModeTracker maintenanceModeTracker; 302 303 private ClusterSchemaService clusterSchemaService; 304 305 public static final String HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS = 306 "hbase.master.wait.on.service.seconds"; 307 public static final int DEFAULT_HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS = 5 * 60; 308 309 // Metrics for the HMaster 310 final MetricsMaster metricsMaster; 311 // file system manager for the master FS operations 312 private MasterFileSystem fileSystemManager; 313 private MasterWalManager walManager; 314 315 // server manager to deal with region server info 316 private volatile ServerManager serverManager; 317 318 // manager of assignment nodes in zookeeper 319 private AssignmentManager assignmentManager; 320 321 // manager of replication 322 private ReplicationManager replicationManager; 323 324 // buffer for "fatal error" notices from region servers 325 // in the cluster. This is only used for assisting 326 // operations/debugging. 327 MemoryBoundedLogMessageBuffer rsFatals; 328 329 // flag set after we become the active master (used for testing) 330 private volatile boolean activeMaster = false; 331 332 // flag set after we complete initialization once active, 333 // it is not private since it's used in unit tests 334 private final ProcedureEvent initialized = new ProcedureEvent("master initialized"); 335 336 // flag set after master services are started, 337 // initialization may have not completed yet. 338 volatile boolean serviceStarted = false; 339 340 // flag set after we complete assignMeta. 341 private final ProcedureEvent serverCrashProcessingEnabled = 342 new ProcedureEvent("server crash processing"); 343 344 // Maximum time we should run balancer for 345 private final int maxBlancingTime; 346 // Maximum percent of regions in transition when balancing 347 private final double maxRitPercent; 348 349 private final LockManager lockManager = new LockManager(this); 350 351 private LoadBalancer balancer; 352 private RegionNormalizer normalizer; 353 private BalancerChore balancerChore; 354 private RegionNormalizerChore normalizerChore; 355 private ClusterStatusChore clusterStatusChore; 356 private ClusterStatusPublisher clusterStatusPublisherChore = null; 357 358 CatalogJanitor catalogJanitorChore; 359 360 private ReplicationZKNodeCleanerChore replicationZKNodeCleanerChore; 361 private LogCleaner logCleaner; 362 private HFileCleaner hfileCleaner; 363 private ExpiredMobFileCleanerChore expiredMobFileCleanerChore; 364 private MobCompactionChore mobCompactChore; 365 private MasterMobCompactionThread mobCompactThread; 366 // used to synchronize the mobCompactionStates 367 private final IdLock mobCompactionLock = new IdLock(); 368 // save the information of mob compactions in tables. 369 // the key is table name, the value is the number of compactions in that table. 370 private Map<TableName, AtomicInteger> mobCompactionStates = Maps.newConcurrentMap(); 371 372 MasterCoprocessorHost cpHost; 373 374 private final boolean preLoadTableDescriptors; 375 376 // Time stamps for when a hmaster became active 377 private long masterActiveTime; 378 379 // Time stamp for when HMaster finishes becoming Active Master 380 private long masterFinishedInitializationTime; 381 382 //should we check the compression codec type at master side, default true, HBASE-6370 383 private final boolean masterCheckCompression; 384 385 //should we check encryption settings at master side, default true 386 private final boolean masterCheckEncryption; 387 388 Map<String, Service> coprocessorServiceHandlers = Maps.newHashMap(); 389 390 // monitor for snapshot of hbase tables 391 SnapshotManager snapshotManager; 392 // monitor for distributed procedures 393 private MasterProcedureManagerHost mpmHost; 394 395 // it is assigned after 'initialized' guard set to true, so should be volatile 396 private volatile MasterQuotaManager quotaManager; 397 private SpaceQuotaSnapshotNotifier spaceQuotaSnapshotNotifier; 398 private QuotaObserverChore quotaObserverChore; 399 private SnapshotQuotaObserverChore snapshotQuotaChore; 400 401 private ProcedureExecutor<MasterProcedureEnv> procedureExecutor; 402 private WALProcedureStore procedureStore; 403 404 // handle table states 405 private TableStateManager tableStateManager; 406 407 private long splitPlanCount; 408 private long mergePlanCount; 409 410 /* Handle favored nodes information */ 411 private FavoredNodesManager favoredNodesManager; 412 413 /** jetty server for master to redirect requests to regionserver infoServer */ 414 private Server masterJettyServer; 415 416 public static class RedirectServlet extends HttpServlet { 417 private static final long serialVersionUID = 2894774810058302473L; 418 private final int regionServerInfoPort; 419 private final String regionServerHostname; 420 421 /** 422 * @param infoServer that we're trying to send all requests to 423 * @param hostname may be null. if given, will be used for redirects instead of host from client. 424 */ 425 public RedirectServlet(InfoServer infoServer, String hostname) { 426 regionServerInfoPort = infoServer.getPort(); 427 regionServerHostname = hostname; 428 } 429 430 @Override 431 public void doGet(HttpServletRequest request, 432 HttpServletResponse response) throws ServletException, IOException { 433 String redirectHost = regionServerHostname; 434 if(redirectHost == null) { 435 redirectHost = request.getServerName(); 436 if(!Addressing.isLocalAddress(InetAddress.getByName(redirectHost))) { 437 LOG.warn("Couldn't resolve '" + redirectHost + "' as an address local to this node and '" + 438 MASTER_HOSTNAME_KEY + "' is not set; client will get a HTTP 400 response. If " + 439 "your HBase deployment relies on client accessible names that the region server process " + 440 "can't resolve locally, then you should set the previously mentioned configuration variable " + 441 "to an appropriate hostname."); 442 // no sending client provided input back to the client, so the goal host is just in the logs. 443 response.sendError(400, "Request was to a host that I can't resolve for any of the network interfaces on " + 444 "this node. If this is due to an intermediary such as an HTTP load balancer or other proxy, your HBase " + 445 "administrator can set '" + MASTER_HOSTNAME_KEY + "' to point to the correct hostname."); 446 return; 447 } 448 } 449 // TODO this scheme should come from looking at the scheme registered in the infoserver's http server for the 450 // host and port we're using, but it's buried way too deep to do that ATM. 451 String redirectUrl = request.getScheme() + "://" 452 + redirectHost + ":" + regionServerInfoPort 453 + request.getRequestURI(); 454 response.sendRedirect(redirectUrl); 455 } 456 } 457 458 /** 459 * Initializes the HMaster. The steps are as follows: 460 * <p> 461 * <ol> 462 * <li>Initialize the local HRegionServer 463 * <li>Start the ActiveMasterManager. 464 * </ol> 465 * <p> 466 * Remaining steps of initialization occur in 467 * #finishActiveMasterInitialization(MonitoredTask) after 468 * the master becomes the active one. 469 */ 470 public HMaster(final Configuration conf) 471 throws IOException, KeeperException { 472 super(conf); 473 TraceUtil.initTracer(conf); 474 try { 475 this.rsFatals = new MemoryBoundedLogMessageBuffer( 476 conf.getLong("hbase.master.buffer.for.rs.fatals", 1 * 1024 * 1024)); 477 LOG.info("hbase.rootdir=" + getRootDir() + 478 ", hbase.cluster.distributed=" + this.conf.getBoolean(HConstants.CLUSTER_DISTRIBUTED, false)); 479 480 // Disable usage of meta replicas in the master 481 this.conf.setBoolean(HConstants.USE_META_REPLICAS, false); 482 483 decorateMasterConfiguration(this.conf); 484 485 // Hack! Maps DFSClient => Master for logs. HDFS made this 486 // config param for task trackers, but we can piggyback off of it. 487 if (this.conf.get("mapreduce.task.attempt.id") == null) { 488 this.conf.set("mapreduce.task.attempt.id", "hb_m_" + this.serverName.toString()); 489 } 490 491 // should we check the compression codec type at master side, default true, HBASE-6370 492 this.masterCheckCompression = conf.getBoolean("hbase.master.check.compression", true); 493 494 // should we check encryption settings at master side, default true 495 this.masterCheckEncryption = conf.getBoolean("hbase.master.check.encryption", true); 496 497 this.metricsMaster = new MetricsMaster(new MetricsMasterWrapperImpl(this)); 498 499 // preload table descriptor at startup 500 this.preLoadTableDescriptors = conf.getBoolean("hbase.master.preload.tabledescriptors", true); 501 502 this.maxBlancingTime = getMaxBalancingTime(); 503 this.maxRitPercent = conf.getDouble(HConstants.HBASE_MASTER_BALANCER_MAX_RIT_PERCENT, 504 HConstants.DEFAULT_HBASE_MASTER_BALANCER_MAX_RIT_PERCENT); 505 506 // Do we publish the status? 507 508 boolean shouldPublish = conf.getBoolean(HConstants.STATUS_PUBLISHED, 509 HConstants.STATUS_PUBLISHED_DEFAULT); 510 Class<? extends ClusterStatusPublisher.Publisher> publisherClass = 511 conf.getClass(ClusterStatusPublisher.STATUS_PUBLISHER_CLASS, 512 ClusterStatusPublisher.DEFAULT_STATUS_PUBLISHER_CLASS, 513 ClusterStatusPublisher.Publisher.class); 514 515 if (shouldPublish) { 516 if (publisherClass == null) { 517 LOG.warn(HConstants.STATUS_PUBLISHED + " is true, but " + 518 ClusterStatusPublisher.DEFAULT_STATUS_PUBLISHER_CLASS + 519 " is not set - not publishing status"); 520 } else { 521 clusterStatusPublisherChore = new ClusterStatusPublisher(this, conf, publisherClass); 522 getChoreService().scheduleChore(clusterStatusPublisherChore); 523 } 524 } 525 526 // Some unit tests don't need a cluster, so no zookeeper at all 527 if (!conf.getBoolean("hbase.testing.nocluster", false)) { 528 this.activeMasterManager = new ActiveMasterManager(zooKeeper, this.serverName, this); 529 } else { 530 this.activeMasterManager = null; 531 } 532 } catch (Throwable t) { 533 // Make sure we log the exception. HMaster is often started via reflection and the 534 // cause of failed startup is lost. 535 LOG.error("Failed construction of Master", t); 536 throw t; 537 } 538 } 539 540 @Override 541 protected String getUseThisHostnameInstead(Configuration conf) { 542 return conf.get(MASTER_HOSTNAME_KEY); 543 } 544 545 // Main run loop. Calls through to the regionserver run loop AFTER becoming active Master; will 546 // block in here until then. 547 @Override 548 public void run() { 549 try { 550 if (!conf.getBoolean("hbase.testing.nocluster", false)) { 551 try { 552 int infoPort = putUpJettyServer(); 553 startActiveMasterManager(infoPort); 554 } catch (Throwable t) { 555 // Make sure we log the exception. 556 String error = "Failed to become Active Master"; 557 LOG.error(error, t); 558 // Abort should have been called already. 559 if (!isAborted()) { 560 abort(error, t); 561 } 562 } 563 } 564 // Fall in here even if we have been aborted. Need to run the shutdown services and 565 // the super run call will do this for us. 566 super.run(); 567 } finally { 568 if (this.clusterSchemaService != null) { 569 // If on way out, then we are no longer active master. 570 this.clusterSchemaService.stopAsync(); 571 try { 572 this.clusterSchemaService.awaitTerminated( 573 getConfiguration().getInt(HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS, 574 DEFAULT_HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS), TimeUnit.SECONDS); 575 } catch (TimeoutException te) { 576 LOG.warn("Failed shutdown of clusterSchemaService", te); 577 } 578 } 579 this.activeMaster = false; 580 } 581 } 582 583 // return the actual infoPort, -1 means disable info server. 584 private int putUpJettyServer() throws IOException { 585 if (!conf.getBoolean("hbase.master.infoserver.redirect", true)) { 586 return -1; 587 } 588 final int infoPort = conf.getInt("hbase.master.info.port.orig", 589 HConstants.DEFAULT_MASTER_INFOPORT); 590 // -1 is for disabling info server, so no redirecting 591 if (infoPort < 0 || infoServer == null) { 592 return -1; 593 } 594 if(infoPort == infoServer.getPort()) { 595 return infoPort; 596 } 597 final String addr = conf.get("hbase.master.info.bindAddress", "0.0.0.0"); 598 if (!Addressing.isLocalAddress(InetAddress.getByName(addr))) { 599 String msg = 600 "Failed to start redirecting jetty server. Address " + addr 601 + " does not belong to this host. Correct configuration parameter: " 602 + "hbase.master.info.bindAddress"; 603 LOG.error(msg); 604 throw new IOException(msg); 605 } 606 607 // TODO I'm pretty sure we could just add another binding to the InfoServer run by 608 // the RegionServer and have it run the RedirectServlet instead of standing up 609 // a second entire stack here. 610 masterJettyServer = new Server(); 611 final ServerConnector connector = new ServerConnector(masterJettyServer); 612 connector.setHost(addr); 613 connector.setPort(infoPort); 614 masterJettyServer.addConnector(connector); 615 masterJettyServer.setStopAtShutdown(true); 616 617 final String redirectHostname = 618 StringUtils.isBlank(useThisHostnameInstead) ? null : useThisHostnameInstead; 619 620 final RedirectServlet redirect = new RedirectServlet(infoServer, redirectHostname); 621 final WebAppContext context = new WebAppContext(null, "/", null, null, null, null, WebAppContext.NO_SESSIONS); 622 context.addServlet(new ServletHolder(redirect), "/*"); 623 context.setServer(masterJettyServer); 624 625 try { 626 masterJettyServer.start(); 627 } catch (Exception e) { 628 throw new IOException("Failed to start redirecting jetty server", e); 629 } 630 return connector.getLocalPort(); 631 } 632 633 @Override 634 protected Function<TableDescriptorBuilder, TableDescriptorBuilder> getMetaTableObserver() { 635 return builder -> builder.setRegionReplication(conf.getInt(HConstants.META_REPLICAS_NUM, HConstants.DEFAULT_META_REPLICA_NUM)); 636 } 637 /** 638 * For compatibility, if failed with regionserver credentials, try the master one 639 */ 640 @Override 641 protected void login(UserProvider user, String host) throws IOException { 642 try { 643 super.login(user, host); 644 } catch (IOException ie) { 645 user.login("hbase.master.keytab.file", 646 "hbase.master.kerberos.principal", host); 647 } 648 } 649 650 /** 651 * If configured to put regions on active master, 652 * wait till a backup master becomes active. 653 * Otherwise, loop till the server is stopped or aborted. 654 */ 655 @Override 656 protected void waitForMasterActive(){ 657 boolean tablesOnMaster = LoadBalancer.isTablesOnMaster(conf); 658 while (!(tablesOnMaster && activeMaster) && !isStopped() && !isAborted()) { 659 sleeper.sleep(); 660 } 661 } 662 663 @VisibleForTesting 664 public MasterRpcServices getMasterRpcServices() { 665 return (MasterRpcServices)rpcServices; 666 } 667 668 public boolean balanceSwitch(final boolean b) throws IOException { 669 return getMasterRpcServices().switchBalancer(b, BalanceSwitchMode.ASYNC); 670 } 671 672 @Override 673 protected String getProcessName() { 674 return MASTER; 675 } 676 677 @Override 678 protected boolean canCreateBaseZNode() { 679 return true; 680 } 681 682 @Override 683 protected boolean canUpdateTableDescriptor() { 684 return true; 685 } 686 687 @Override 688 protected RSRpcServices createRpcServices() throws IOException { 689 return new MasterRpcServices(this); 690 } 691 692 @Override 693 protected void configureInfoServer() { 694 infoServer.addServlet("master-status", "/master-status", MasterStatusServlet.class); 695 infoServer.setAttribute(MASTER, this); 696 if (LoadBalancer.isTablesOnMaster(conf)) { 697 super.configureInfoServer(); 698 } 699 } 700 701 @Override 702 protected Class<? extends HttpServlet> getDumpServlet() { 703 return MasterDumpServlet.class; 704 } 705 706 @Override 707 public MetricsMaster getMasterMetrics() { 708 return metricsMaster; 709 } 710 711 /** 712 * Initialize all ZK based system trackers. 713 */ 714 void initializeZKBasedSystemTrackers() throws IOException, 715 InterruptedException, KeeperException { 716 this.balancer = LoadBalancerFactory.getLoadBalancer(conf); 717 this.normalizer = RegionNormalizerFactory.getRegionNormalizer(conf); 718 this.normalizer.setMasterServices(this); 719 this.normalizer.setMasterRpcServices((MasterRpcServices)rpcServices); 720 this.loadBalancerTracker = new LoadBalancerTracker(zooKeeper, this); 721 this.loadBalancerTracker.start(); 722 723 this.regionNormalizerTracker = new RegionNormalizerTracker(zooKeeper, this); 724 this.regionNormalizerTracker.start(); 725 726 this.splitOrMergeTracker = new SplitOrMergeTracker(zooKeeper, conf, this); 727 this.splitOrMergeTracker.start(); 728 729 // Create Assignment Manager 730 this.assignmentManager = new AssignmentManager(this); 731 this.assignmentManager.start(); 732 733 this.replicationManager = new ReplicationManager(conf, zooKeeper, this); 734 735 this.regionServerTracker = new RegionServerTracker(zooKeeper, this, this.serverManager); 736 this.regionServerTracker.start(); 737 738 this.drainingServerTracker = new DrainingServerTracker(zooKeeper, this, this.serverManager); 739 this.drainingServerTracker.start(); 740 741 this.maintenanceModeTracker = new MasterMaintenanceModeTracker(zooKeeper); 742 this.maintenanceModeTracker.start(); 743 744 // Set the cluster as up. If new RSs, they'll be waiting on this before 745 // going ahead with their startup. 746 boolean wasUp = this.clusterStatusTracker.isClusterUp(); 747 if (!wasUp) this.clusterStatusTracker.setClusterUp(); 748 749 LOG.info("Active/primary master=" + this.serverName + 750 ", sessionid=0x" + 751 Long.toHexString(this.zooKeeper.getRecoverableZooKeeper().getSessionId()) + 752 ", setting cluster-up flag (Was=" + wasUp + ")"); 753 754 // create/initialize the snapshot manager and other procedure managers 755 this.snapshotManager = new SnapshotManager(); 756 this.mpmHost = new MasterProcedureManagerHost(); 757 this.mpmHost.register(this.snapshotManager); 758 this.mpmHost.register(new MasterFlushTableProcedureManager()); 759 this.mpmHost.loadProcedures(conf); 760 this.mpmHost.initialize(this, this.metricsMaster); 761 } 762 763 /** 764 * Finish initialization of HMaster after becoming the primary master. 765 * 766 * <ol> 767 * <li>Initialize master components - file system manager, server manager, 768 * assignment manager, region server tracker, etc</li> 769 * <li>Start necessary service threads - balancer, catalog janior, 770 * executor services, etc</li> 771 * <li>Set cluster as UP in ZooKeeper</li> 772 * <li>Wait for RegionServers to check-in</li> 773 * <li>Split logs and perform data recovery, if necessary</li> 774 * <li>Ensure assignment of meta/namespace regions<li> 775 * <li>Handle either fresh cluster start or master failover</li> 776 * </ol> 777 */ 778 private void finishActiveMasterInitialization(MonitoredTask status) 779 throws IOException, InterruptedException, KeeperException { 780 781 Thread zombieDetector = new Thread(new InitializationMonitor(this), 782 "ActiveMasterInitializationMonitor-" + System.currentTimeMillis()); 783 zombieDetector.setDaemon(true); 784 zombieDetector.start(); 785 786 /* 787 * We are active master now... go initialize components we need to run. 788 */ 789 status.setStatus("Initializing Master file system"); 790 791 this.masterActiveTime = System.currentTimeMillis(); 792 // TODO: Do this using Dependency Injection, using PicoContainer, Guice or Spring. 793 // Initialize the chunkCreator 794 initializeMemStoreChunkCreator(); 795 this.fileSystemManager = new MasterFileSystem(conf); 796 this.walManager = new MasterWalManager(this); 797 798 // enable table descriptors cache 799 this.tableDescriptors.setCacheOn(); 800 801 // warm-up HTDs cache on master initialization 802 if (preLoadTableDescriptors) { 803 status.setStatus("Pre-loading table descriptors"); 804 this.tableDescriptors.getAll(); 805 } 806 807 // Publish cluster ID; set it in Master too. The superclass RegionServer does this later but 808 // only after it has checked in with the Master. At least a few tests ask Master for clusterId 809 // before it has called its run method and before RegionServer has done the reportForDuty. 810 ClusterId clusterId = fileSystemManager.getClusterId(); 811 status.setStatus("Publishing Cluster ID " + clusterId + " in ZooKeeper"); 812 ZKClusterId.setClusterId(this.zooKeeper, fileSystemManager.getClusterId()); 813 this.clusterId = clusterId.toString(); 814 815 this.serverManager = createServerManager(this); 816 817 // This manager is started AFTER hbase:meta is confirmed on line. 818 // See inside metaBootstrap.recoverMeta(); below. Shouldn't be so cryptic! 819 // hbase.mirror.table.state.to.zookeeper is so hbase1 clients can connect. They read table 820 // state from zookeeper while hbase2 reads it from hbase:meta. Disable if no hbase1 clients. 821 this.tableStateManager = 822 this.conf.getBoolean(MirroringTableStateManager.MIRROR_TABLE_STATE_TO_ZK_KEY, true)? 823 new MirroringTableStateManager(this): 824 new TableStateManager(this); 825 826 status.setStatus("Initializing ZK system trackers"); 827 initializeZKBasedSystemTrackers(); 828 // Set ourselves as active Master now our claim has succeeded up in zk. 829 this.activeMaster = true; 830 831 // This is for backwards compatibility 832 // See HBASE-11393 833 status.setStatus("Update TableCFs node in ZNode"); 834 ReplicationPeerConfigUpgrader tableCFsUpdater = new ReplicationPeerConfigUpgrader(zooKeeper, 835 conf, this.clusterConnection); 836 tableCFsUpdater.copyTableCFs(); 837 838 // Add the Observer to delete space quotas on table deletion before starting all CPs by 839 // default with quota support, avoiding if user specifically asks to not load this Observer. 840 if (QuotaUtil.isQuotaEnabled(conf)) { 841 updateConfigurationForSpaceQuotaObserver(conf); 842 } 843 // initialize master side coprocessors before we start handling requests 844 status.setStatus("Initializing master coprocessors"); 845 this.cpHost = new MasterCoprocessorHost(this, this.conf); 846 847 // start up all service threads. 848 status.setStatus("Initializing master service threads"); 849 startServiceThreads(); 850 851 // Wake up this server to check in 852 sleeper.skipSleepCycle(); 853 854 // Wait for region servers to report in. 855 // With this as part of master initialization, it precludes our being able to start a single 856 // server that is both Master and RegionServer. Needs more thought. TODO. 857 String statusStr = "Wait for region servers to report in"; 858 status.setStatus(statusStr); 859 LOG.info(Objects.toString(status)); 860 waitForRegionServers(status); 861 862 if (this.balancer instanceof FavoredNodesPromoter) { 863 favoredNodesManager = new FavoredNodesManager(this); 864 } 865 866 //initialize load balancer 867 this.balancer.setMasterServices(this); 868 this.balancer.setClusterMetrics(getClusterMetricsWithoutCoprocessor()); 869 this.balancer.initialize(); 870 871 // Make sure meta assigned before proceeding. 872 status.setStatus("Recovering Meta Region"); 873 874 // Check if master is shutting down because issue initializing regionservers or balancer. 875 if (isStopped()) { 876 return; 877 } 878 879 // Bring up hbase:meta. recoverMeta is a blocking call waiting until hbase:meta is deployed. 880 // It also starts the TableStateManager. 881 MasterMetaBootstrap metaBootstrap = createMetaBootstrap(); 882 metaBootstrap.recoverMeta(); 883 884 //Initialize after meta as it scans meta 885 if (favoredNodesManager != null) { 886 SnapshotOfRegionAssignmentFromMeta snapshotOfRegionAssignment = 887 new SnapshotOfRegionAssignmentFromMeta(getConnection()); 888 snapshotOfRegionAssignment.initialize(); 889 favoredNodesManager.initialize(snapshotOfRegionAssignment); 890 } 891 892 status.setStatus("Submitting log splitting work for previously failed region servers"); 893 metaBootstrap.processDeadServers(); 894 895 // Fix up assignment manager status 896 status.setStatus("Starting assignment manager"); 897 this.assignmentManager.joinCluster(); 898 899 // set cluster status again after user regions are assigned 900 this.balancer.setClusterMetrics(getClusterMetricsWithoutCoprocessor()); 901 902 // Start balancer and meta catalog janitor after meta and regions have been assigned. 903 status.setStatus("Starting balancer and catalog janitor"); 904 this.clusterStatusChore = new ClusterStatusChore(this, balancer); 905 getChoreService().scheduleChore(clusterStatusChore); 906 this.balancerChore = new BalancerChore(this); 907 getChoreService().scheduleChore(balancerChore); 908 this.normalizerChore = new RegionNormalizerChore(this); 909 getChoreService().scheduleChore(normalizerChore); 910 this.catalogJanitorChore = new CatalogJanitor(this); 911 getChoreService().scheduleChore(catalogJanitorChore); 912 913 status.setStatus("Starting cluster schema service"); 914 initClusterSchemaService(); 915 916 if (this.cpHost != null) { 917 try { 918 this.cpHost.preMasterInitialization(); 919 } catch (IOException e) { 920 LOG.error("Coprocessor preMasterInitialization() hook failed", e); 921 } 922 } 923 924 status.markComplete("Initialization successful"); 925 LOG.info(String.format("Master has completed initialization %.3fsec", 926 (System.currentTimeMillis() - masterActiveTime) / 1000.0f)); 927 this.masterFinishedInitializationTime = System.currentTimeMillis(); 928 configurationManager.registerObserver(this.balancer); 929 configurationManager.registerObserver(this.hfileCleaner); 930 configurationManager.registerObserver(this.logCleaner); 931 // Set master as 'initialized'. 932 setInitialized(true); 933 assignmentManager.checkIfShouldMoveSystemRegionAsync(); 934 status.setStatus("Assign meta replicas"); 935 metaBootstrap.assignMetaReplicas(); 936 status.setStatus("Starting quota manager"); 937 initQuotaManager(); 938 if (QuotaUtil.isQuotaEnabled(conf)) { 939 // Create the quota snapshot notifier 940 spaceQuotaSnapshotNotifier = createQuotaSnapshotNotifier(); 941 spaceQuotaSnapshotNotifier.initialize(getClusterConnection()); 942 this.quotaObserverChore = new QuotaObserverChore(this, getMasterMetrics()); 943 // Start the chore to read the region FS space reports and act on them 944 getChoreService().scheduleChore(quotaObserverChore); 945 946 this.snapshotQuotaChore = new SnapshotQuotaObserverChore(this, getMasterMetrics()); 947 // Start the chore to read snapshots and add their usage to table/NS quotas 948 getChoreService().scheduleChore(snapshotQuotaChore); 949 } 950 951 // clear the dead servers with same host name and port of online server because we are not 952 // removing dead server with same hostname and port of rs which is trying to check in before 953 // master initialization. See HBASE-5916. 954 this.serverManager.clearDeadServersWithSameHostNameAndPortOfOnlineServer(); 955 956 // Check and set the znode ACLs if needed in case we are overtaking a non-secure configuration 957 status.setStatus("Checking ZNode ACLs"); 958 zooKeeper.checkAndSetZNodeAcls(); 959 960 status.setStatus("Initializing MOB Cleaner"); 961 initMobCleaner(); 962 963 status.setStatus("Calling postStartMaster coprocessors"); 964 if (this.cpHost != null) { 965 // don't let cp initialization errors kill the master 966 try { 967 this.cpHost.postStartMaster(); 968 } catch (IOException ioe) { 969 LOG.error("Coprocessor postStartMaster() hook failed", ioe); 970 } 971 } 972 973 zombieDetector.interrupt(); 974 975 /* 976 * After master has started up, lets do balancer post startup initialization. Since this runs 977 * in activeMasterManager thread, it should be fine. 978 */ 979 long start = System.currentTimeMillis(); 980 this.balancer.postMasterStartupInitialize(); 981 if (LOG.isDebugEnabled()) { 982 LOG.debug("Balancer post startup initialization complete, took " + ( 983 (System.currentTimeMillis() - start) / 1000) + " seconds"); 984 } 985 } 986 987 /** 988 * Adds the {@code MasterSpaceQuotaObserver} to the list of configured Master observers to 989 * automatically remove space quotas for a table when that table is deleted. 990 */ 991 @VisibleForTesting 992 public void updateConfigurationForSpaceQuotaObserver(Configuration conf) { 993 // We're configured to not delete quotas on table deletion, so we don't need to add the obs. 994 if (!conf.getBoolean( 995 MasterSpaceQuotaObserver.REMOVE_QUOTA_ON_TABLE_DELETE, 996 MasterSpaceQuotaObserver.REMOVE_QUOTA_ON_TABLE_DELETE_DEFAULT)) { 997 return; 998 } 999 String[] masterCoprocs = conf.getStrings(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY); 1000 final int length = null == masterCoprocs ? 0 : masterCoprocs.length; 1001 String[] updatedCoprocs = new String[length + 1]; 1002 if (length > 0) { 1003 System.arraycopy(masterCoprocs, 0, updatedCoprocs, 0, masterCoprocs.length); 1004 } 1005 updatedCoprocs[length] = MasterSpaceQuotaObserver.class.getName(); 1006 conf.setStrings(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, updatedCoprocs); 1007 } 1008 1009 private void initMobCleaner() { 1010 this.expiredMobFileCleanerChore = new ExpiredMobFileCleanerChore(this); 1011 getChoreService().scheduleChore(expiredMobFileCleanerChore); 1012 1013 int mobCompactionPeriod = conf.getInt(MobConstants.MOB_COMPACTION_CHORE_PERIOD, 1014 MobConstants.DEFAULT_MOB_COMPACTION_CHORE_PERIOD); 1015 if (mobCompactionPeriod > 0) { 1016 this.mobCompactChore = new MobCompactionChore(this, mobCompactionPeriod); 1017 getChoreService().scheduleChore(mobCompactChore); 1018 } else { 1019 LOG 1020 .info("The period is " + mobCompactionPeriod + " seconds, MobCompactionChore is disabled"); 1021 } 1022 this.mobCompactThread = new MasterMobCompactionThread(this); 1023 } 1024 1025 /** 1026 * <p> 1027 * Create a {@link MasterMetaBootstrap} instance. 1028 * </p> 1029 * <p> 1030 * Will be overridden in tests. 1031 * </p> 1032 */ 1033 @VisibleForTesting 1034 protected MasterMetaBootstrap createMetaBootstrap() { 1035 // We put this out here in a method so can do a Mockito.spy and stub it out 1036 // w/ a mocked up MasterMetaBootstrap. 1037 return new MasterMetaBootstrap(this); 1038 } 1039 1040 /** 1041 * Create a {@link ServerManager} instance. 1042 */ 1043 ServerManager createServerManager(final MasterServices master) throws IOException { 1044 // We put this out here in a method so can do a Mockito.spy and stub it out 1045 // w/ a mocked up ServerManager. 1046 setupClusterConnection(); 1047 return new ServerManager(master); 1048 } 1049 1050 private void waitForRegionServers(final MonitoredTask status) 1051 throws IOException, InterruptedException { 1052 this.serverManager.waitForRegionServers(status); 1053 // Check zk for region servers that are up but didn't register 1054 for (ServerName sn: this.regionServerTracker.getOnlineServers()) { 1055 // The isServerOnline check is opportunistic, correctness is handled inside 1056 if (!this.serverManager.isServerOnline(sn) && 1057 serverManager.checkAndRecordNewServer(sn, ServerMetricsBuilder.of(sn))) { 1058 LOG.info("Registered server found up in zk but who has not yet reported in: " + sn); 1059 } 1060 } 1061 } 1062 1063 void initClusterSchemaService() throws IOException, InterruptedException { 1064 this.clusterSchemaService = new ClusterSchemaServiceImpl(this); 1065 this.clusterSchemaService.startAsync(); 1066 try { 1067 this.clusterSchemaService.awaitRunning(getConfiguration().getInt( 1068 HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS, 1069 DEFAULT_HBASE_MASTER_WAIT_ON_SERVICE_IN_SECONDS), TimeUnit.SECONDS); 1070 } catch (TimeoutException toe) { 1071 throw new IOException("Timedout starting ClusterSchemaService", toe); 1072 } 1073 } 1074 1075 void initQuotaManager() throws IOException { 1076 MasterQuotaManager quotaManager = new MasterQuotaManager(this); 1077 this.assignmentManager.setRegionStateListener(quotaManager); 1078 quotaManager.start(); 1079 this.quotaManager = quotaManager; 1080 } 1081 1082 SpaceQuotaSnapshotNotifier createQuotaSnapshotNotifier() { 1083 SpaceQuotaSnapshotNotifier notifier = 1084 SpaceQuotaSnapshotNotifierFactory.getInstance().create(getConfiguration()); 1085 return notifier; 1086 } 1087 1088 boolean isCatalogJanitorEnabled() { 1089 return catalogJanitorChore != null ? 1090 catalogJanitorChore.getEnabled() : false; 1091 } 1092 1093 boolean isCleanerChoreEnabled() { 1094 boolean hfileCleanerFlag = true, logCleanerFlag = true; 1095 1096 if (hfileCleaner != null) { 1097 hfileCleanerFlag = hfileCleaner.getEnabled(); 1098 } 1099 1100 if (logCleaner != null) { 1101 logCleanerFlag = logCleaner.getEnabled(); 1102 } 1103 1104 return (hfileCleanerFlag && logCleanerFlag); 1105 } 1106 1107 @Override 1108 public TableDescriptors getTableDescriptors() { 1109 return this.tableDescriptors; 1110 } 1111 1112 @Override 1113 public ServerManager getServerManager() { 1114 return this.serverManager; 1115 } 1116 1117 @Override 1118 public MasterFileSystem getMasterFileSystem() { 1119 return this.fileSystemManager; 1120 } 1121 1122 @Override 1123 public MasterWalManager getMasterWalManager() { 1124 return this.walManager; 1125 } 1126 1127 @Override 1128 public TableStateManager getTableStateManager() { 1129 return tableStateManager; 1130 } 1131 1132 /* 1133 * Start up all services. If any of these threads gets an unhandled exception 1134 * then they just die with a logged message. This should be fine because 1135 * in general, we do not expect the master to get such unhandled exceptions 1136 * as OOMEs; it should be lightly loaded. See what HRegionServer does if 1137 * need to install an unexpected exception handler. 1138 */ 1139 private void startServiceThreads() throws IOException{ 1140 // Start the executor service pools 1141 this.executorService.startExecutorService(ExecutorType.MASTER_OPEN_REGION, 1142 conf.getInt("hbase.master.executor.openregion.threads", 5)); 1143 this.executorService.startExecutorService(ExecutorType.MASTER_CLOSE_REGION, 1144 conf.getInt("hbase.master.executor.closeregion.threads", 5)); 1145 this.executorService.startExecutorService(ExecutorType.MASTER_SERVER_OPERATIONS, 1146 conf.getInt("hbase.master.executor.serverops.threads", 5)); 1147 this.executorService.startExecutorService(ExecutorType.MASTER_META_SERVER_OPERATIONS, 1148 conf.getInt("hbase.master.executor.meta.serverops.threads", 5)); 1149 this.executorService.startExecutorService(ExecutorType.M_LOG_REPLAY_OPS, 1150 conf.getInt("hbase.master.executor.logreplayops.threads", 10)); 1151 1152 // We depend on there being only one instance of this executor running 1153 // at a time. To do concurrency, would need fencing of enable/disable of 1154 // tables. 1155 // Any time changing this maxThreads to > 1, pls see the comment at 1156 // AccessController#postCompletedCreateTableAction 1157 this.executorService.startExecutorService(ExecutorType.MASTER_TABLE_OPERATIONS, 1); 1158 startProcedureExecutor(); 1159 1160 // Start log cleaner thread 1161 int cleanerInterval = conf.getInt("hbase.master.cleaner.interval", 600 * 1000); 1162 this.logCleaner = 1163 new LogCleaner(cleanerInterval, 1164 this, conf, getMasterWalManager().getFileSystem(), 1165 getMasterWalManager().getOldLogDir()); 1166 getChoreService().scheduleChore(logCleaner); 1167 1168 //start the hfile archive cleaner thread 1169 Path archiveDir = HFileArchiveUtil.getArchivePath(conf); 1170 Map<String, Object> params = new HashMap<>(); 1171 params.put(MASTER, this); 1172 this.hfileCleaner = new HFileCleaner(cleanerInterval, this, conf, getMasterFileSystem() 1173 .getFileSystem(), archiveDir, params); 1174 getChoreService().scheduleChore(hfileCleaner); 1175 serviceStarted = true; 1176 if (LOG.isTraceEnabled()) { 1177 LOG.trace("Started service threads"); 1178 } 1179 // Start replication zk node cleaner 1180 try { 1181 replicationZKNodeCleanerChore = new ReplicationZKNodeCleanerChore(this, cleanerInterval, 1182 new ReplicationZKNodeCleaner(this.conf, this.getZooKeeper(), this)); 1183 getChoreService().scheduleChore(replicationZKNodeCleanerChore); 1184 } catch (Exception e) { 1185 LOG.error("start replicationZKNodeCleanerChore failed", e); 1186 } 1187 } 1188 1189 @Override 1190 protected void stopServiceThreads() { 1191 if (masterJettyServer != null) { 1192 LOG.info("Stopping master jetty server"); 1193 try { 1194 masterJettyServer.stop(); 1195 } catch (Exception e) { 1196 LOG.error("Failed to stop master jetty server", e); 1197 } 1198 } 1199 super.stopServiceThreads(); 1200 stopChores(); 1201 1202 if (LOG.isDebugEnabled()) { 1203 LOG.debug("Stopping service threads"); 1204 } 1205 1206 // Clean up and close up shop 1207 if (this.logCleaner != null) this.logCleaner.cancel(true); 1208 if (this.hfileCleaner != null) this.hfileCleaner.cancel(true); 1209 if (this.replicationZKNodeCleanerChore != null) this.replicationZKNodeCleanerChore.cancel(true); 1210 if (this.quotaManager != null) this.quotaManager.stop(); 1211 1212 if (this.activeMasterManager != null) this.activeMasterManager.stop(); 1213 if (this.serverManager != null) this.serverManager.stop(); 1214 if (this.assignmentManager != null) this.assignmentManager.stop(); 1215 1216 stopProcedureExecutor(); 1217 1218 if (this.walManager != null) this.walManager.stop(); 1219 if (this.fileSystemManager != null) this.fileSystemManager.stop(); 1220 if (this.mpmHost != null) this.mpmHost.stop("server shutting down."); 1221 } 1222 1223 private void startProcedureExecutor() throws IOException { 1224 final MasterProcedureEnv procEnv = new MasterProcedureEnv(this); 1225 procedureStore = new WALProcedureStore(conf, 1226 new MasterProcedureEnv.WALStoreLeaseRecovery(this)); 1227 procedureStore.registerListener(new MasterProcedureEnv.MasterProcedureStoreListener(this)); 1228 MasterProcedureScheduler procedureScheduler = procEnv.getProcedureScheduler(); 1229 procedureExecutor = new ProcedureExecutor<>(conf, procEnv, procedureStore, procedureScheduler); 1230 configurationManager.registerObserver(procEnv); 1231 1232 int cpus = Runtime.getRuntime().availableProcessors(); 1233 final int numThreads = conf.getInt(MasterProcedureConstants.MASTER_PROCEDURE_THREADS, Math.max( 1234 (cpus > 0 ? cpus / 4 : 0), MasterProcedureConstants.DEFAULT_MIN_MASTER_PROCEDURE_THREADS)); 1235 final boolean abortOnCorruption = 1236 conf.getBoolean(MasterProcedureConstants.EXECUTOR_ABORT_ON_CORRUPTION, 1237 MasterProcedureConstants.DEFAULT_EXECUTOR_ABORT_ON_CORRUPTION); 1238 procedureStore.start(numThreads); 1239 procedureExecutor.start(numThreads, abortOnCorruption); 1240 procEnv.getRemoteDispatcher().start(); 1241 } 1242 1243 private void stopProcedureExecutor() { 1244 if (procedureExecutor != null) { 1245 configurationManager.deregisterObserver(procedureExecutor.getEnvironment()); 1246 procedureExecutor.getEnvironment().getRemoteDispatcher().stop(); 1247 procedureExecutor.stop(); 1248 procedureExecutor.join(); 1249 procedureExecutor = null; 1250 } 1251 1252 if (procedureStore != null) { 1253 procedureStore.stop(isAborted()); 1254 procedureStore = null; 1255 } 1256 } 1257 1258 private void stopChores() { 1259 if (this.expiredMobFileCleanerChore != null) { 1260 this.expiredMobFileCleanerChore.cancel(true); 1261 } 1262 if (this.mobCompactChore != null) { 1263 this.mobCompactChore.cancel(true); 1264 } 1265 if (this.balancerChore != null) { 1266 this.balancerChore.cancel(true); 1267 } 1268 if (this.normalizerChore != null) { 1269 this.normalizerChore.cancel(true); 1270 } 1271 if (this.clusterStatusChore != null) { 1272 this.clusterStatusChore.cancel(true); 1273 } 1274 if (this.catalogJanitorChore != null) { 1275 this.catalogJanitorChore.cancel(true); 1276 } 1277 if (this.clusterStatusPublisherChore != null){ 1278 clusterStatusPublisherChore.cancel(true); 1279 } 1280 if (this.mobCompactThread != null) { 1281 this.mobCompactThread.close(); 1282 } 1283 1284 if (this.quotaObserverChore != null) { 1285 quotaObserverChore.cancel(); 1286 } 1287 if (this.snapshotQuotaChore != null) { 1288 snapshotQuotaChore.cancel(); 1289 } 1290 } 1291 1292 /** 1293 * @return Get remote side's InetAddress 1294 */ 1295 InetAddress getRemoteInetAddress(final int port, 1296 final long serverStartCode) throws UnknownHostException { 1297 // Do it out here in its own little method so can fake an address when 1298 // mocking up in tests. 1299 InetAddress ia = RpcServer.getRemoteIp(); 1300 1301 // The call could be from the local regionserver, 1302 // in which case, there is no remote address. 1303 if (ia == null && serverStartCode == startcode) { 1304 InetSocketAddress isa = rpcServices.getSocketAddress(); 1305 if (isa != null && isa.getPort() == port) { 1306 ia = isa.getAddress(); 1307 } 1308 } 1309 return ia; 1310 } 1311 1312 /** 1313 * @return Maximum time we should run balancer for 1314 */ 1315 private int getMaxBalancingTime() { 1316 int maxBalancingTime = getConfiguration().getInt(HConstants.HBASE_BALANCER_MAX_BALANCING, -1); 1317 if (maxBalancingTime == -1) { 1318 // if max balancing time isn't set, defaulting it to period time 1319 maxBalancingTime = getConfiguration().getInt(HConstants.HBASE_BALANCER_PERIOD, 1320 HConstants.DEFAULT_HBASE_BALANCER_PERIOD); 1321 } 1322 return maxBalancingTime; 1323 } 1324 1325 /** 1326 * @return Maximum number of regions in transition 1327 */ 1328 private int getMaxRegionsInTransition() { 1329 int numRegions = this.assignmentManager.getRegionStates().getRegionAssignments().size(); 1330 return Math.max((int) Math.floor(numRegions * this.maxRitPercent), 1); 1331 } 1332 1333 /** 1334 * It first sleep to the next balance plan start time. Meanwhile, throttling by the max 1335 * number regions in transition to protect availability. 1336 * @param nextBalanceStartTime The next balance plan start time 1337 * @param maxRegionsInTransition max number of regions in transition 1338 * @param cutoffTime when to exit balancer 1339 */ 1340 private void balanceThrottling(long nextBalanceStartTime, int maxRegionsInTransition, 1341 long cutoffTime) { 1342 boolean interrupted = false; 1343 1344 // Sleep to next balance plan start time 1345 // But if there are zero regions in transition, it can skip sleep to speed up. 1346 while (!interrupted && System.currentTimeMillis() < nextBalanceStartTime 1347 && this.assignmentManager.getRegionStates().hasRegionsInTransition()) { 1348 try { 1349 Thread.sleep(100); 1350 } catch (InterruptedException ie) { 1351 interrupted = true; 1352 } 1353 } 1354 1355 // Throttling by max number regions in transition 1356 while (!interrupted 1357 && maxRegionsInTransition > 0 1358 && this.assignmentManager.getRegionStates().getRegionsInTransitionCount() 1359 >= maxRegionsInTransition && System.currentTimeMillis() <= cutoffTime) { 1360 try { 1361 // sleep if the number of regions in transition exceeds the limit 1362 Thread.sleep(100); 1363 } catch (InterruptedException ie) { 1364 interrupted = true; 1365 } 1366 } 1367 1368 if (interrupted) Thread.currentThread().interrupt(); 1369 } 1370 1371 public boolean balance() throws IOException { 1372 return balance(false); 1373 } 1374 1375 public boolean balance(boolean force) throws IOException { 1376 // if master not initialized, don't run balancer. 1377 if (!isInitialized()) { 1378 LOG.debug("Master has not been initialized, don't run balancer."); 1379 return false; 1380 } 1381 1382 if (isInMaintenanceMode()) { 1383 LOG.info("Master is in maintenanceMode mode, don't run balancer."); 1384 return false; 1385 } 1386 1387 int maxRegionsInTransition = getMaxRegionsInTransition(); 1388 synchronized (this.balancer) { 1389 // If balance not true, don't run balancer. 1390 if (!this.loadBalancerTracker.isBalancerOn()) return false; 1391 // Only allow one balance run at at time. 1392 if (this.assignmentManager.hasRegionsInTransition()) { 1393 List<RegionStateNode> regionsInTransition = assignmentManager.getRegionsInTransition(); 1394 // if hbase:meta region is in transition, result of assignment cannot be recorded 1395 // ignore the force flag in that case 1396 boolean metaInTransition = assignmentManager.isMetaRegionInTransition(); 1397 String prefix = force && !metaInTransition ? "R" : "Not r"; 1398 List<RegionStateNode> toPrint = regionsInTransition; 1399 int max = 5; 1400 boolean truncated = false; 1401 if (regionsInTransition.size() > max) { 1402 toPrint = regionsInTransition.subList(0, max); 1403 truncated = true; 1404 } 1405 LOG.info(prefix + "unning balancer because " + regionsInTransition.size() + 1406 " region(s) in transition: " + toPrint + (truncated? "(truncated list)": "")); 1407 if (!force || metaInTransition) return false; 1408 } 1409 if (this.serverManager.areDeadServersInProgress()) { 1410 LOG.info("Not running balancer because processing dead regionserver(s): " + 1411 this.serverManager.getDeadServers()); 1412 return false; 1413 } 1414 1415 if (this.cpHost != null) { 1416 try { 1417 if (this.cpHost.preBalance()) { 1418 LOG.debug("Coprocessor bypassing balancer request"); 1419 return false; 1420 } 1421 } catch (IOException ioe) { 1422 LOG.error("Error invoking master coprocessor preBalance()", ioe); 1423 return false; 1424 } 1425 } 1426 1427 boolean isByTable = getConfiguration().getBoolean("hbase.master.loadbalance.bytable", false); 1428 Map<TableName, Map<ServerName, List<RegionInfo>>> assignmentsByTable = 1429 this.assignmentManager.getRegionStates().getAssignmentsByTable(!isByTable); 1430 1431 List<RegionPlan> plans = new ArrayList<>(); 1432 1433 //Give the balancer the current cluster state. 1434 this.balancer.setClusterMetrics(getClusterMetricsWithoutCoprocessor()); 1435 this.balancer.setClusterLoad(assignmentsByTable); 1436 1437 for (Map<ServerName, List<RegionInfo>> serverMap : assignmentsByTable.values()) { 1438 serverMap.keySet().removeAll(this.serverManager.getDrainingServersList()); 1439 } 1440 for (Entry<TableName, Map<ServerName, List<RegionInfo>>> e : assignmentsByTable.entrySet()) { 1441 List<RegionPlan> partialPlans = this.balancer.balanceCluster(e.getKey(), e.getValue()); 1442 if (partialPlans != null) plans.addAll(partialPlans); 1443 } 1444 1445 long balanceStartTime = System.currentTimeMillis(); 1446 long cutoffTime = balanceStartTime + this.maxBlancingTime; 1447 int rpCount = 0; // number of RegionPlans balanced so far 1448 if (plans != null && !plans.isEmpty()) { 1449 int balanceInterval = this.maxBlancingTime / plans.size(); 1450 LOG.info("Balancer plans size is " + plans.size() + ", the balance interval is " 1451 + balanceInterval + " ms, and the max number regions in transition is " 1452 + maxRegionsInTransition); 1453 1454 for (RegionPlan plan: plans) { 1455 LOG.info("balance " + plan); 1456 //TODO: bulk assign 1457 this.assignmentManager.moveAsync(plan); 1458 rpCount++; 1459 1460 balanceThrottling(balanceStartTime + rpCount * balanceInterval, maxRegionsInTransition, 1461 cutoffTime); 1462 1463 // if performing next balance exceeds cutoff time, exit the loop 1464 if (rpCount < plans.size() && System.currentTimeMillis() > cutoffTime) { 1465 // TODO: After balance, there should not be a cutoff time (keeping it as 1466 // a security net for now) 1467 LOG.debug("No more balancing till next balance run; maxBalanceTime=" 1468 + this.maxBlancingTime); 1469 break; 1470 } 1471 } 1472 } 1473 1474 if (this.cpHost != null) { 1475 try { 1476 this.cpHost.postBalance(rpCount < plans.size() ? plans.subList(0, rpCount) : plans); 1477 } catch (IOException ioe) { 1478 // balancing already succeeded so don't change the result 1479 LOG.error("Error invoking master coprocessor postBalance()", ioe); 1480 } 1481 } 1482 } 1483 // If LoadBalancer did not generate any plans, it means the cluster is already balanced. 1484 // Return true indicating a success. 1485 return true; 1486 } 1487 1488 @Override 1489 @VisibleForTesting 1490 public RegionNormalizer getRegionNormalizer() { 1491 return this.normalizer; 1492 } 1493 1494 /** 1495 * Perform normalization of cluster (invoked by {@link RegionNormalizerChore}). 1496 * 1497 * @return true if normalization step was performed successfully, false otherwise 1498 * (specifically, if HMaster hasn't been initialized properly or normalization 1499 * is globally disabled) 1500 */ 1501 public boolean normalizeRegions() throws IOException { 1502 if (!isInitialized()) { 1503 LOG.debug("Master has not been initialized, don't run region normalizer."); 1504 return false; 1505 } 1506 1507 if (isInMaintenanceMode()) { 1508 LOG.info("Master is in maintenance mode, don't run region normalizer."); 1509 return false; 1510 } 1511 1512 if (!this.regionNormalizerTracker.isNormalizerOn()) { 1513 LOG.debug("Region normalization is disabled, don't run region normalizer."); 1514 return false; 1515 } 1516 1517 synchronized (this.normalizer) { 1518 // Don't run the normalizer concurrently 1519 List<TableName> allEnabledTables = new ArrayList<>( 1520 this.tableStateManager.getTablesInStates(TableState.State.ENABLED)); 1521 1522 Collections.shuffle(allEnabledTables); 1523 1524 for (TableName table : allEnabledTables) { 1525 if (isInMaintenanceMode()) { 1526 LOG.debug("Master is in maintenance mode, stop running region normalizer."); 1527 return false; 1528 } 1529 1530 TableDescriptor tblDesc = getTableDescriptors().get(table); 1531 if (table.isSystemTable() || (tblDesc != null && 1532 !tblDesc.isNormalizationEnabled())) { 1533 LOG.trace("Skipping normalization for {}, as it's either system" 1534 + " table or doesn't have auto normalization turned on", table); 1535 continue; 1536 } 1537 List<NormalizationPlan> plans = this.normalizer.computePlanForTable(table); 1538 if (plans != null) { 1539 for (NormalizationPlan plan : plans) { 1540 plan.execute(clusterConnection.getAdmin()); 1541 if (plan.getType() == PlanType.SPLIT) { 1542 splitPlanCount++; 1543 } else if (plan.getType() == PlanType.MERGE) { 1544 mergePlanCount++; 1545 } 1546 } 1547 } 1548 } 1549 } 1550 // If Region did not generate any plans, it means the cluster is already balanced. 1551 // Return true indicating a success. 1552 return true; 1553 } 1554 1555 /** 1556 * @return Client info for use as prefix on an audit log string; who did an action 1557 */ 1558 @Override 1559 public String getClientIdAuditPrefix() { 1560 return "Client=" + RpcServer.getRequestUserName().orElse(null) 1561 + "/" + RpcServer.getRemoteAddress().orElse(null); 1562 } 1563 1564 /** 1565 * Switch for the background CatalogJanitor thread. 1566 * Used for testing. The thread will continue to run. It will just be a noop 1567 * if disabled. 1568 * @param b If false, the catalog janitor won't do anything. 1569 */ 1570 public void setCatalogJanitorEnabled(final boolean b) { 1571 this.catalogJanitorChore.setEnabled(b); 1572 } 1573 1574 @Override 1575 public long mergeRegions( 1576 final RegionInfo[] regionsToMerge, 1577 final boolean forcible, 1578 final long nonceGroup, 1579 final long nonce) throws IOException { 1580 checkInitialized(); 1581 1582 assert(regionsToMerge.length == 2); 1583 1584 TableName tableName = regionsToMerge[0].getTable(); 1585 if (tableName == null || regionsToMerge[1].getTable() == null) { 1586 throw new UnknownRegionException ("Can't merge regions without table associated"); 1587 } 1588 1589 if (!tableName.equals(regionsToMerge[1].getTable())) { 1590 throw new IOException ( 1591 "Cannot merge regions from two different tables " + regionsToMerge[0].getTable() 1592 + " and " + regionsToMerge[1].getTable()); 1593 } 1594 1595 if (RegionInfo.COMPARATOR.compare(regionsToMerge[0], regionsToMerge[1]) == 0) { 1596 throw new MergeRegionException( 1597 "Cannot merge a region to itself " + regionsToMerge[0] + ", " + regionsToMerge[1]); 1598 } 1599 1600 return MasterProcedureUtil.submitProcedure( 1601 new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 1602 @Override 1603 protected void run() throws IOException { 1604 getMaster().getMasterCoprocessorHost().preMergeRegions(regionsToMerge); 1605 1606 LOG.info(getClientIdAuditPrefix() + " Merge regions " + 1607 regionsToMerge[0].getEncodedName() + " and " + regionsToMerge[1].getEncodedName()); 1608 1609 submitProcedure(new MergeTableRegionsProcedure(procedureExecutor.getEnvironment(), 1610 regionsToMerge, forcible)); 1611 1612 getMaster().getMasterCoprocessorHost().postMergeRegions(regionsToMerge); 1613 } 1614 1615 @Override 1616 protected String getDescription() { 1617 return "MergeTableProcedure"; 1618 } 1619 }); 1620 } 1621 1622 @Override 1623 public long splitRegion(final RegionInfo regionInfo, final byte[] splitRow, 1624 final long nonceGroup, final long nonce) 1625 throws IOException { 1626 checkInitialized(); 1627 return MasterProcedureUtil.submitProcedure( 1628 new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 1629 @Override 1630 protected void run() throws IOException { 1631 getMaster().getMasterCoprocessorHost().preSplitRegion(regionInfo.getTable(), splitRow); 1632 LOG.info(getClientIdAuditPrefix() + " split " + regionInfo.getRegionNameAsString()); 1633 1634 // Execute the operation asynchronously 1635 submitProcedure(getAssignmentManager().createSplitProcedure(regionInfo, splitRow)); 1636 } 1637 1638 @Override 1639 protected String getDescription() { 1640 return "SplitTableProcedure"; 1641 } 1642 }); 1643 } 1644 1645 // Public so can be accessed by tests. Blocks until move is done. 1646 // Replace with an async implementation from which you can get 1647 // a success/failure result. 1648 @VisibleForTesting 1649 public void move(final byte[] encodedRegionName, byte[] destServerName) throws HBaseIOException { 1650 RegionState regionState = assignmentManager.getRegionStates(). 1651 getRegionState(Bytes.toString(encodedRegionName)); 1652 1653 RegionInfo hri; 1654 if (regionState != null) { 1655 hri = regionState.getRegion(); 1656 } else { 1657 throw new UnknownRegionException(Bytes.toStringBinary(encodedRegionName)); 1658 } 1659 1660 ServerName dest; 1661 List<ServerName> exclude = hri.getTable().isSystemTable() ? assignmentManager.getExcludedServersForSystemTable() 1662 : new ArrayList<>(1); 1663 if (destServerName != null && exclude.contains(ServerName.valueOf(Bytes.toString(destServerName)))) { 1664 LOG.info( 1665 Bytes.toString(encodedRegionName) + " can not move to " + Bytes.toString(destServerName) 1666 + " because the server is in exclude list"); 1667 destServerName = null; 1668 } 1669 if (destServerName == null || destServerName.length == 0) { 1670 LOG.info("Passed destination servername is null/empty so " + 1671 "choosing a server at random"); 1672 exclude.add(regionState.getServerName()); 1673 final List<ServerName> destServers = this.serverManager.createDestinationServersList(exclude); 1674 dest = balancer.randomAssignment(hri, destServers); 1675 if (dest == null) { 1676 LOG.debug("Unable to determine a plan to assign " + hri); 1677 return; 1678 } 1679 } else { 1680 ServerName candidate = ServerName.valueOf(Bytes.toString(destServerName)); 1681 dest = balancer.randomAssignment(hri, Lists.newArrayList(candidate)); 1682 if (dest == null) { 1683 LOG.debug("Unable to determine a plan to assign " + hri); 1684 return; 1685 } 1686 // TODO: What is this? I don't get it. 1687 if (dest.equals(serverName) && balancer instanceof BaseLoadBalancer 1688 && !((BaseLoadBalancer)balancer).shouldBeOnMaster(hri)) { 1689 // To avoid unnecessary region moving later by balancer. Don't put user 1690 // regions on master. 1691 LOG.debug("Skipping move of region " + hri.getRegionNameAsString() 1692 + " to avoid unnecessary region moving later by load balancer," 1693 + " because it should not be on master"); 1694 return; 1695 } 1696 } 1697 1698 if (dest.equals(regionState.getServerName())) { 1699 LOG.debug("Skipping move of region " + hri.getRegionNameAsString() 1700 + " because region already assigned to the same server " + dest + "."); 1701 return; 1702 } 1703 1704 // Now we can do the move 1705 RegionPlan rp = new RegionPlan(hri, regionState.getServerName(), dest); 1706 assert rp.getDestination() != null: rp.toString() + " " + dest; 1707 1708 try { 1709 checkInitialized(); 1710 if (this.cpHost != null) { 1711 this.cpHost.preMove(hri, rp.getSource(), rp.getDestination()); 1712 } 1713 // Warmup the region on the destination before initiating the move. this call 1714 // is synchronous and takes some time. doing it before the source region gets 1715 // closed 1716 serverManager.sendRegionWarmup(rp.getDestination(), hri); 1717 1718 LOG.info(getClientIdAuditPrefix() + " move " + rp + ", running balancer"); 1719 Future<byte []> future = this.assignmentManager.moveAsync(rp); 1720 try { 1721 // Is this going to work? Will we throw exception on error? 1722 // TODO: CompletableFuture rather than this stunted Future. 1723 future.get(); 1724 } catch (InterruptedException | ExecutionException e) { 1725 throw new HBaseIOException(e); 1726 } 1727 if (this.cpHost != null) { 1728 this.cpHost.postMove(hri, rp.getSource(), rp.getDestination()); 1729 } 1730 } catch (IOException ioe) { 1731 if (ioe instanceof HBaseIOException) { 1732 throw (HBaseIOException)ioe; 1733 } 1734 throw new HBaseIOException(ioe); 1735 } 1736 } 1737 1738 @Override 1739 public long createTable( 1740 final TableDescriptor tableDescriptor, 1741 final byte [][] splitKeys, 1742 final long nonceGroup, 1743 final long nonce) throws IOException { 1744 checkInitialized(); 1745 1746 String namespace = tableDescriptor.getTableName().getNamespaceAsString(); 1747 this.clusterSchemaService.getNamespace(namespace); 1748 1749 RegionInfo[] newRegions = ModifyRegionUtils.createRegionInfos(tableDescriptor, splitKeys); 1750 sanityCheckTableDescriptor(tableDescriptor); 1751 1752 return MasterProcedureUtil.submitProcedure( 1753 new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 1754 @Override 1755 protected void run() throws IOException { 1756 getMaster().getMasterCoprocessorHost().preCreateTable(tableDescriptor, newRegions); 1757 1758 LOG.info(getClientIdAuditPrefix() + " create " + tableDescriptor); 1759 1760 // TODO: We can handle/merge duplicate requests, and differentiate the case of 1761 // TableExistsException by saying if the schema is the same or not. 1762 // 1763 // We need to wait for the procedure to potentially fail due to "prepare" sanity 1764 // checks. This will block only the beginning of the procedure. See HBASE-19953. 1765 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 1766 submitProcedure(new CreateTableProcedure( 1767 procedureExecutor.getEnvironment(), tableDescriptor, newRegions, latch)); 1768 latch.await(); 1769 1770 getMaster().getMasterCoprocessorHost().postCreateTable(tableDescriptor, newRegions); 1771 } 1772 1773 @Override 1774 protected String getDescription() { 1775 return "CreateTableProcedure"; 1776 } 1777 }); 1778 } 1779 1780 @Override 1781 public long createSystemTable(final TableDescriptor tableDescriptor) throws IOException { 1782 if (isStopped()) { 1783 throw new MasterNotRunningException(); 1784 } 1785 1786 TableName tableName = tableDescriptor.getTableName(); 1787 if (!(tableName.isSystemTable())) { 1788 throw new IllegalArgumentException( 1789 "Only system table creation can use this createSystemTable API"); 1790 } 1791 1792 RegionInfo[] newRegions = ModifyRegionUtils.createRegionInfos(tableDescriptor, null); 1793 1794 LOG.info(getClientIdAuditPrefix() + " create " + tableDescriptor); 1795 1796 // This special create table is called locally to master. Therefore, no RPC means no need 1797 // to use nonce to detect duplicated RPC call. 1798 long procId = this.procedureExecutor.submitProcedure( 1799 new CreateTableProcedure(procedureExecutor.getEnvironment(), tableDescriptor, newRegions)); 1800 1801 return procId; 1802 } 1803 1804 /** 1805 * Checks whether the table conforms to some sane limits, and configured 1806 * values (compression, etc) work. Throws an exception if something is wrong. 1807 * @throws IOException 1808 */ 1809 private void sanityCheckTableDescriptor(final TableDescriptor htd) throws IOException { 1810 final String CONF_KEY = "hbase.table.sanity.checks"; 1811 boolean logWarn = false; 1812 if (!conf.getBoolean(CONF_KEY, true)) { 1813 logWarn = true; 1814 } 1815 String tableVal = htd.getValue(CONF_KEY); 1816 if (tableVal != null && !Boolean.valueOf(tableVal)) { 1817 logWarn = true; 1818 } 1819 1820 // check max file size 1821 long maxFileSizeLowerLimit = 2 * 1024 * 1024L; // 2M is the default lower limit 1822 long maxFileSize = htd.getMaxFileSize(); 1823 if (maxFileSize < 0) { 1824 maxFileSize = conf.getLong(HConstants.HREGION_MAX_FILESIZE, maxFileSizeLowerLimit); 1825 } 1826 if (maxFileSize < conf.getLong("hbase.hregion.max.filesize.limit", maxFileSizeLowerLimit)) { 1827 String message = "MAX_FILESIZE for table descriptor or " 1828 + "\"hbase.hregion.max.filesize\" (" + maxFileSize 1829 + ") is too small, which might cause over splitting into unmanageable " 1830 + "number of regions."; 1831 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null); 1832 } 1833 1834 // check flush size 1835 long flushSizeLowerLimit = 1024 * 1024L; // 1M is the default lower limit 1836 long flushSize = htd.getMemStoreFlushSize(); 1837 if (flushSize < 0) { 1838 flushSize = conf.getLong(HConstants.HREGION_MEMSTORE_FLUSH_SIZE, flushSizeLowerLimit); 1839 } 1840 if (flushSize < conf.getLong("hbase.hregion.memstore.flush.size.limit", flushSizeLowerLimit)) { 1841 String message = "MEMSTORE_FLUSHSIZE for table descriptor or " 1842 + "\"hbase.hregion.memstore.flush.size\" ("+flushSize+") is too small, which might cause" 1843 + " very frequent flushing."; 1844 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null); 1845 } 1846 1847 // check that coprocessors and other specified plugin classes can be loaded 1848 try { 1849 checkClassLoading(conf, htd); 1850 } catch (Exception ex) { 1851 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, ex.getMessage(), null); 1852 } 1853 1854 // check compression can be loaded 1855 try { 1856 checkCompression(htd); 1857 } catch (IOException e) { 1858 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, e.getMessage(), e); 1859 } 1860 1861 // check encryption can be loaded 1862 try { 1863 checkEncryption(conf, htd); 1864 } catch (IOException e) { 1865 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, e.getMessage(), e); 1866 } 1867 // Verify compaction policy 1868 try{ 1869 checkCompactionPolicy(conf, htd); 1870 } catch(IOException e){ 1871 warnOrThrowExceptionForFailure(false, CONF_KEY, e.getMessage(), e); 1872 } 1873 // check that we have at least 1 CF 1874 if (htd.getColumnFamilyCount() == 0) { 1875 String message = "Table should have at least one column family."; 1876 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null); 1877 } 1878 1879 for (ColumnFamilyDescriptor hcd : htd.getColumnFamilies()) { 1880 if (hcd.getTimeToLive() <= 0) { 1881 String message = "TTL for column family " + hcd.getNameAsString() + " must be positive."; 1882 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null); 1883 } 1884 1885 // check blockSize 1886 if (hcd.getBlocksize() < 1024 || hcd.getBlocksize() > 16 * 1024 * 1024) { 1887 String message = "Block size for column family " + hcd.getNameAsString() 1888 + " must be between 1K and 16MB."; 1889 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null); 1890 } 1891 1892 // check versions 1893 if (hcd.getMinVersions() < 0) { 1894 String message = "Min versions for column family " + hcd.getNameAsString() 1895 + " must be positive."; 1896 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null); 1897 } 1898 // max versions already being checked 1899 1900 // HBASE-13776 Setting illegal versions for ColumnFamilyDescriptor 1901 // does not throw IllegalArgumentException 1902 // check minVersions <= maxVerions 1903 if (hcd.getMinVersions() > hcd.getMaxVersions()) { 1904 String message = "Min versions for column family " + hcd.getNameAsString() 1905 + " must be less than the Max versions."; 1906 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null); 1907 } 1908 1909 // check replication scope 1910 checkReplicationScope(hcd); 1911 1912 // check data replication factor, it can be 0(default value) when user has not explicitly 1913 // set the value, in this case we use default replication factor set in the file system. 1914 if (hcd.getDFSReplication() < 0) { 1915 String message = "HFile Replication for column family " + hcd.getNameAsString() 1916 + " must be greater than zero."; 1917 warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null); 1918 } 1919 1920 // TODO: should we check coprocessors and encryption ? 1921 } 1922 } 1923 1924 private void checkReplicationScope(ColumnFamilyDescriptor hcd) throws IOException{ 1925 // check replication scope 1926 WALProtos.ScopeType scop = WALProtos.ScopeType.valueOf(hcd.getScope()); 1927 if (scop == null) { 1928 String message = "Replication scope for column family " 1929 + hcd.getNameAsString() + " is " + hcd.getScope() + " which is invalid."; 1930 1931 LOG.error(message); 1932 throw new DoNotRetryIOException(message); 1933 } 1934 } 1935 1936 private void checkCompactionPolicy(Configuration conf, TableDescriptor htd) 1937 throws IOException { 1938 // FIFO compaction has some requirements 1939 // Actually FCP ignores periodic major compactions 1940 String className = htd.getValue(DefaultStoreEngine.DEFAULT_COMPACTION_POLICY_CLASS_KEY); 1941 if (className == null) { 1942 className = 1943 conf.get(DefaultStoreEngine.DEFAULT_COMPACTION_POLICY_CLASS_KEY, 1944 ExploringCompactionPolicy.class.getName()); 1945 } 1946 1947 int blockingFileCount = HStore.DEFAULT_BLOCKING_STOREFILE_COUNT; 1948 String sv = htd.getValue(HStore.BLOCKING_STOREFILES_KEY); 1949 if (sv != null) { 1950 blockingFileCount = Integer.parseInt(sv); 1951 } else { 1952 blockingFileCount = conf.getInt(HStore.BLOCKING_STOREFILES_KEY, blockingFileCount); 1953 } 1954 1955 for (ColumnFamilyDescriptor hcd : htd.getColumnFamilies()) { 1956 String compactionPolicy = 1957 hcd.getConfigurationValue(DefaultStoreEngine.DEFAULT_COMPACTION_POLICY_CLASS_KEY); 1958 if (compactionPolicy == null) { 1959 compactionPolicy = className; 1960 } 1961 if (!compactionPolicy.equals(FIFOCompactionPolicy.class.getName())) { 1962 continue; 1963 } 1964 // FIFOCompaction 1965 String message = null; 1966 1967 // 1. Check TTL 1968 if (hcd.getTimeToLive() == ColumnFamilyDescriptorBuilder.DEFAULT_TTL) { 1969 message = "Default TTL is not supported for FIFO compaction"; 1970 throw new IOException(message); 1971 } 1972 1973 // 2. Check min versions 1974 if (hcd.getMinVersions() > 0) { 1975 message = "MIN_VERSION > 0 is not supported for FIFO compaction"; 1976 throw new IOException(message); 1977 } 1978 1979 // 3. blocking file count 1980 sv = hcd.getConfigurationValue(HStore.BLOCKING_STOREFILES_KEY); 1981 if (sv != null) { 1982 blockingFileCount = Integer.parseInt(sv); 1983 } 1984 if (blockingFileCount < 1000) { 1985 message = 1986 "Blocking file count '" + HStore.BLOCKING_STOREFILES_KEY + "' " + blockingFileCount 1987 + " is below recommended minimum of 1000 for column family "+ hcd.getNameAsString(); 1988 throw new IOException(message); 1989 } 1990 } 1991 } 1992 1993 // HBASE-13350 - Helper method to log warning on sanity check failures if checks disabled. 1994 private static void warnOrThrowExceptionForFailure(boolean logWarn, String confKey, 1995 String message, Exception cause) throws IOException { 1996 if (!logWarn) { 1997 throw new DoNotRetryIOException(message + " Set " + confKey + 1998 " to false at conf or table descriptor if you want to bypass sanity checks", cause); 1999 } 2000 LOG.warn(message); 2001 } 2002 2003 private void startActiveMasterManager(int infoPort) throws KeeperException { 2004 String backupZNode = ZNodePaths.joinZNode( 2005 zooKeeper.znodePaths.backupMasterAddressesZNode, serverName.toString()); 2006 /* 2007 * Add a ZNode for ourselves in the backup master directory since we 2008 * may not become the active master. If so, we want the actual active 2009 * master to know we are backup masters, so that it won't assign 2010 * regions to us if so configured. 2011 * 2012 * If we become the active master later, ActiveMasterManager will delete 2013 * this node explicitly. If we crash before then, ZooKeeper will delete 2014 * this node for us since it is ephemeral. 2015 */ 2016 LOG.info("Adding backup master ZNode " + backupZNode); 2017 if (!MasterAddressTracker.setMasterAddress(zooKeeper, backupZNode, serverName, infoPort)) { 2018 LOG.warn("Failed create of " + backupZNode + " by " + serverName); 2019 } 2020 this.activeMasterManager.setInfoPort(infoPort); 2021 int timeout = conf.getInt(HConstants.ZK_SESSION_TIMEOUT, HConstants.DEFAULT_ZK_SESSION_TIMEOUT); 2022 // If we're a backup master, stall until a primary to write this address 2023 if (conf.getBoolean(HConstants.MASTER_TYPE_BACKUP, HConstants.DEFAULT_MASTER_TYPE_BACKUP)) { 2024 LOG.debug("HMaster started in backup mode. Stalling until master znode is written."); 2025 // This will only be a minute or so while the cluster starts up, 2026 // so don't worry about setting watches on the parent znode 2027 while (!activeMasterManager.hasActiveMaster()) { 2028 LOG.debug("Waiting for master address and cluster state znode to be written."); 2029 Threads.sleep(timeout); 2030 } 2031 } 2032 MonitoredTask status = TaskMonitor.get().createStatus("Master startup"); 2033 status.setDescription("Master startup"); 2034 try { 2035 if (activeMasterManager.blockUntilBecomingActiveMaster(timeout, status)) { 2036 finishActiveMasterInitialization(status); 2037 } 2038 } catch (Throwable t) { 2039 status.setStatus("Failed to become active: " + t.getMessage()); 2040 LOG.error(HBaseMarkers.FATAL, "Failed to become active master", t); 2041 // HBASE-5680: Likely hadoop23 vs hadoop 20.x/1.x incompatibility 2042 if (t instanceof NoClassDefFoundError && t.getMessage(). 2043 contains("org/apache/hadoop/hdfs/protocol/HdfsConstants$SafeModeAction")) { 2044 // improved error message for this special case 2045 abort("HBase is having a problem with its Hadoop jars. You may need to recompile " + 2046 "HBase against Hadoop version " + org.apache.hadoop.util.VersionInfo.getVersion() + 2047 " or change your hadoop jars to start properly", t); 2048 } else { 2049 abort("Unhandled exception. Starting shutdown.", t); 2050 } 2051 } finally { 2052 status.cleanup(); 2053 } 2054 } 2055 2056 private void checkCompression(final TableDescriptor htd) 2057 throws IOException { 2058 if (!this.masterCheckCompression) return; 2059 for (ColumnFamilyDescriptor hcd : htd.getColumnFamilies()) { 2060 checkCompression(hcd); 2061 } 2062 } 2063 2064 private void checkCompression(final ColumnFamilyDescriptor hcd) 2065 throws IOException { 2066 if (!this.masterCheckCompression) return; 2067 CompressionTest.testCompression(hcd.getCompressionType()); 2068 CompressionTest.testCompression(hcd.getCompactionCompressionType()); 2069 } 2070 2071 private void checkEncryption(final Configuration conf, final TableDescriptor htd) 2072 throws IOException { 2073 if (!this.masterCheckEncryption) return; 2074 for (ColumnFamilyDescriptor hcd : htd.getColumnFamilies()) { 2075 checkEncryption(conf, hcd); 2076 } 2077 } 2078 2079 private void checkEncryption(final Configuration conf, final ColumnFamilyDescriptor hcd) 2080 throws IOException { 2081 if (!this.masterCheckEncryption) return; 2082 EncryptionTest.testEncryption(conf, hcd.getEncryptionType(), hcd.getEncryptionKey()); 2083 } 2084 2085 private void checkClassLoading(final Configuration conf, final TableDescriptor htd) 2086 throws IOException { 2087 RegionSplitPolicy.getSplitPolicyClass(htd, conf); 2088 RegionCoprocessorHost.testTableCoprocessorAttrs(conf, htd); 2089 } 2090 2091 private static boolean isCatalogTable(final TableName tableName) { 2092 return tableName.equals(TableName.META_TABLE_NAME); 2093 } 2094 2095 @Override 2096 public long deleteTable( 2097 final TableName tableName, 2098 final long nonceGroup, 2099 final long nonce) throws IOException { 2100 checkInitialized(); 2101 2102 return MasterProcedureUtil.submitProcedure( 2103 new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2104 @Override 2105 protected void run() throws IOException { 2106 getMaster().getMasterCoprocessorHost().preDeleteTable(tableName); 2107 2108 LOG.info(getClientIdAuditPrefix() + " delete " + tableName); 2109 2110 // TODO: We can handle/merge duplicate request 2111 // 2112 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2113 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2114 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 2115 submitProcedure(new DeleteTableProcedure(procedureExecutor.getEnvironment(), 2116 tableName, latch)); 2117 latch.await(); 2118 2119 getMaster().getMasterCoprocessorHost().postDeleteTable(tableName); 2120 } 2121 2122 @Override 2123 protected String getDescription() { 2124 return "DeleteTableProcedure"; 2125 } 2126 }); 2127 } 2128 2129 @Override 2130 public long truncateTable( 2131 final TableName tableName, 2132 final boolean preserveSplits, 2133 final long nonceGroup, 2134 final long nonce) throws IOException { 2135 checkInitialized(); 2136 2137 return MasterProcedureUtil.submitProcedure( 2138 new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2139 @Override 2140 protected void run() throws IOException { 2141 getMaster().getMasterCoprocessorHost().preTruncateTable(tableName); 2142 2143 LOG.info(getClientIdAuditPrefix() + " truncate " + tableName); 2144 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createLatch(2, 0); 2145 submitProcedure(new TruncateTableProcedure(procedureExecutor.getEnvironment(), 2146 tableName, preserveSplits, latch)); 2147 latch.await(); 2148 2149 getMaster().getMasterCoprocessorHost().postTruncateTable(tableName); 2150 } 2151 2152 @Override 2153 protected String getDescription() { 2154 return "TruncateTableProcedure"; 2155 } 2156 }); 2157 } 2158 2159 @Override 2160 public long addColumn( 2161 final TableName tableName, 2162 final ColumnFamilyDescriptor column, 2163 final long nonceGroup, 2164 final long nonce) 2165 throws IOException { 2166 checkInitialized(); 2167 checkTableExists(tableName); 2168 2169 TableDescriptor old = getTableDescriptors().get(tableName); 2170 if (old.hasColumnFamily(column.getName())) { 2171 throw new InvalidFamilyOperationException("Column family '" + column.getNameAsString() 2172 + "' in table '" + tableName + "' already exists so cannot be added"); 2173 } 2174 2175 TableDescriptor newDesc = TableDescriptorBuilder 2176 .newBuilder(old).setColumnFamily(column).build(); 2177 return modifyTable(tableName, newDesc, nonceGroup, nonce); 2178 } 2179 2180 @Override 2181 public long modifyColumn( 2182 final TableName tableName, 2183 final ColumnFamilyDescriptor descriptor, 2184 final long nonceGroup, 2185 final long nonce) 2186 throws IOException { 2187 checkInitialized(); 2188 checkTableExists(tableName); 2189 2190 TableDescriptor old = getTableDescriptors().get(tableName); 2191 if (! old.hasColumnFamily(descriptor.getName())) { 2192 throw new InvalidFamilyOperationException("Family '" + descriptor.getNameAsString() 2193 + "' does not exist, so it cannot be modified"); 2194 } 2195 2196 TableDescriptor td = TableDescriptorBuilder 2197 .newBuilder(old) 2198 .modifyColumnFamily(descriptor) 2199 .build(); 2200 2201 return modifyTable(tableName, td, nonceGroup, nonce); 2202 } 2203 2204 @Override 2205 public long deleteColumn( 2206 final TableName tableName, 2207 final byte[] columnName, 2208 final long nonceGroup, 2209 final long nonce) 2210 throws IOException { 2211 checkInitialized(); 2212 checkTableExists(tableName); 2213 2214 TableDescriptor old = getTableDescriptors().get(tableName); 2215 2216 if (! old.hasColumnFamily(columnName)) { 2217 throw new InvalidFamilyOperationException("Family '" + Bytes.toString(columnName) 2218 + "' does not exist, so it cannot be deleted"); 2219 } 2220 if (old.getColumnFamilyCount() == 1) { 2221 throw new InvalidFamilyOperationException("Family '" + Bytes.toString(columnName) 2222 + "' is the only column family in the table, so it cannot be deleted"); 2223 } 2224 2225 TableDescriptor td = TableDescriptorBuilder 2226 .newBuilder(old).removeColumnFamily(columnName).build(); 2227 return modifyTable(tableName, td, nonceGroup, nonce); 2228 } 2229 2230 @Override 2231 public long enableTable(final TableName tableName, final long nonceGroup, final long nonce) 2232 throws IOException { 2233 checkInitialized(); 2234 2235 return MasterProcedureUtil.submitProcedure( 2236 new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2237 @Override 2238 protected void run() throws IOException { 2239 getMaster().getMasterCoprocessorHost().preEnableTable(tableName); 2240 2241 // Normally, it would make sense for this authorization check to exist inside 2242 // AccessController, but because the authorization check is done based on internal state 2243 // (rather than explicit permissions) we'll do the check here instead of in the 2244 // coprocessor. 2245 MasterQuotaManager quotaManager = getMasterQuotaManager(); 2246 if (quotaManager != null) { 2247 if (quotaManager.isQuotaInitialized()) { 2248 Quotas quotaForTable = QuotaUtil.getTableQuota(getConnection(), tableName); 2249 if (quotaForTable != null && quotaForTable.hasSpace()) { 2250 SpaceViolationPolicy policy = quotaForTable.getSpace().getViolationPolicy(); 2251 if (SpaceViolationPolicy.DISABLE == policy) { 2252 throw new AccessDeniedException("Enabling the table '" + tableName 2253 + "' is disallowed due to a violated space quota."); 2254 } 2255 } 2256 } else if (LOG.isTraceEnabled()) { 2257 LOG.trace("Unable to check for space quotas as the MasterQuotaManager is not enabled"); 2258 } 2259 } 2260 2261 LOG.info(getClientIdAuditPrefix() + " enable " + tableName); 2262 2263 // Execute the operation asynchronously - client will check the progress of the operation 2264 // In case the request is from a <1.1 client before returning, 2265 // we want to make sure that the table is prepared to be 2266 // enabled (the table is locked and the table state is set). 2267 // Note: if the procedure throws exception, we will catch it and rethrow. 2268 final ProcedurePrepareLatch prepareLatch = ProcedurePrepareLatch.createLatch(); 2269 submitProcedure(new EnableTableProcedure(procedureExecutor.getEnvironment(), 2270 tableName, false, prepareLatch)); 2271 prepareLatch.await(); 2272 2273 getMaster().getMasterCoprocessorHost().postEnableTable(tableName); 2274 } 2275 2276 @Override 2277 protected String getDescription() { 2278 return "EnableTableProcedure"; 2279 } 2280 }); 2281 } 2282 2283 @Override 2284 public long disableTable(final TableName tableName, final long nonceGroup, final long nonce) 2285 throws IOException { 2286 checkInitialized(); 2287 2288 return MasterProcedureUtil.submitProcedure( 2289 new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2290 @Override 2291 protected void run() throws IOException { 2292 getMaster().getMasterCoprocessorHost().preDisableTable(tableName); 2293 2294 LOG.info(getClientIdAuditPrefix() + " disable " + tableName); 2295 2296 // Execute the operation asynchronously - client will check the progress of the operation 2297 // In case the request is from a <1.1 client before returning, 2298 // we want to make sure that the table is prepared to be 2299 // enabled (the table is locked and the table state is set). 2300 // Note: if the procedure throws exception, we will catch it and rethrow. 2301 // 2302 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2303 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2304 final ProcedurePrepareLatch prepareLatch = ProcedurePrepareLatch.createBlockingLatch(); 2305 submitProcedure(new DisableTableProcedure(procedureExecutor.getEnvironment(), 2306 tableName, false, prepareLatch)); 2307 prepareLatch.await(); 2308 2309 getMaster().getMasterCoprocessorHost().postDisableTable(tableName); 2310 } 2311 2312 @Override 2313 protected String getDescription() { 2314 return "DisableTableProcedure"; 2315 } 2316 }); 2317 } 2318 2319 /** 2320 * Return the region and current deployment for the region containing 2321 * the given row. If the region cannot be found, returns null. If it 2322 * is found, but not currently deployed, the second element of the pair 2323 * may be null. 2324 */ 2325 @VisibleForTesting // Used by TestMaster. 2326 Pair<RegionInfo, ServerName> getTableRegionForRow( 2327 final TableName tableName, final byte [] rowKey) 2328 throws IOException { 2329 final AtomicReference<Pair<RegionInfo, ServerName>> result = new AtomicReference<>(null); 2330 2331 MetaTableAccessor.Visitor visitor = new MetaTableAccessor.Visitor() { 2332 @Override 2333 public boolean visit(Result data) throws IOException { 2334 if (data == null || data.size() <= 0) { 2335 return true; 2336 } 2337 Pair<RegionInfo, ServerName> pair = 2338 new Pair(MetaTableAccessor.getRegionInfo(data), 2339 MetaTableAccessor.getServerName(data,0)); 2340 if (pair == null) { 2341 return false; 2342 } 2343 if (!pair.getFirst().getTable().equals(tableName)) { 2344 return false; 2345 } 2346 result.set(pair); 2347 return true; 2348 } 2349 }; 2350 2351 MetaTableAccessor.scanMeta(clusterConnection, visitor, tableName, rowKey, 1); 2352 return result.get(); 2353 } 2354 2355 @Override 2356 public long modifyTable(final TableName tableName, final TableDescriptor newDescriptor, 2357 final long nonceGroup, final long nonce) throws IOException { 2358 checkInitialized(); 2359 sanityCheckTableDescriptor(newDescriptor); 2360 2361 return MasterProcedureUtil.submitProcedure( 2362 new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2363 @Override 2364 protected void run() throws IOException { 2365 TableDescriptor oldDescriptor = getMaster().getTableDescriptors().get(tableName); 2366 getMaster().getMasterCoprocessorHost() 2367 .preModifyTable(tableName, oldDescriptor, newDescriptor); 2368 2369 LOG.info(getClientIdAuditPrefix() + " modify " + tableName); 2370 2371 // Execute the operation synchronously - wait for the operation completes before continuing. 2372 // 2373 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2374 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2375 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 2376 submitProcedure( 2377 new ModifyTableProcedure(procedureExecutor.getEnvironment(), newDescriptor, latch)); 2378 latch.await(); 2379 2380 getMaster().getMasterCoprocessorHost() 2381 .postModifyTable(tableName, oldDescriptor, newDescriptor); 2382 } 2383 2384 @Override 2385 protected String getDescription() { 2386 return "ModifyTableProcedure"; 2387 } 2388 }); 2389 } 2390 2391 public long restoreSnapshot(final SnapshotDescription snapshotDesc, 2392 final long nonceGroup, final long nonce, final boolean restoreAcl) throws IOException { 2393 checkInitialized(); 2394 getSnapshotManager().checkSnapshotSupport(); 2395 2396 // Ensure namespace exists. Will throw exception if non-known NS. 2397 final TableName dstTable = TableName.valueOf(snapshotDesc.getTable()); 2398 getClusterSchema().getNamespace(dstTable.getNamespaceAsString()); 2399 2400 return MasterProcedureUtil.submitProcedure( 2401 new MasterProcedureUtil.NonceProcedureRunnable(this, nonceGroup, nonce) { 2402 @Override 2403 protected void run() throws IOException { 2404 setProcId( 2405 getSnapshotManager().restoreOrCloneSnapshot(snapshotDesc, getNonceKey(), restoreAcl)); 2406 } 2407 2408 @Override 2409 protected String getDescription() { 2410 return "RestoreSnapshotProcedure"; 2411 } 2412 }); 2413 } 2414 2415 private void checkTableExists(final TableName tableName) 2416 throws IOException, TableNotFoundException { 2417 if (!MetaTableAccessor.tableExists(getConnection(), tableName)) { 2418 throw new TableNotFoundException(tableName); 2419 } 2420 } 2421 2422 @Override 2423 public void checkTableModifiable(final TableName tableName) 2424 throws IOException, TableNotFoundException, TableNotDisabledException { 2425 if (isCatalogTable(tableName)) { 2426 throw new IOException("Can't modify catalog tables"); 2427 } 2428 checkTableExists(tableName); 2429 TableState ts = getTableStateManager().getTableState(tableName); 2430 if (!ts.isDisabled()) { 2431 throw new TableNotDisabledException("Not DISABLED; " + ts); 2432 } 2433 } 2434 2435 public ClusterMetrics getClusterMetricsWithoutCoprocessor() throws InterruptedIOException { 2436 return getClusterMetricsWithoutCoprocessor(EnumSet.allOf(Option.class)); 2437 } 2438 2439 public ClusterMetrics getClusterMetricsWithoutCoprocessor(EnumSet<Option> options) 2440 throws InterruptedIOException { 2441 ClusterMetricsBuilder builder = ClusterMetricsBuilder.newBuilder(); 2442 // given that hbase1 can't submit the request with Option, 2443 // we return all information to client if the list of Option is empty. 2444 if (options.isEmpty()) { 2445 options = EnumSet.allOf(Option.class); 2446 } 2447 2448 for (Option opt : options) { 2449 switch (opt) { 2450 case HBASE_VERSION: builder.setHBaseVersion(VersionInfo.getVersion()); break; 2451 case CLUSTER_ID: builder.setClusterId(getClusterId()); break; 2452 case MASTER: builder.setMasterName(getServerName()); break; 2453 case BACKUP_MASTERS: builder.setBackerMasterNames(getBackupMasters()); break; 2454 case LIVE_SERVERS: { 2455 if (serverManager != null) { 2456 builder.setLiveServerMetrics(serverManager.getOnlineServers().entrySet().stream() 2457 .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()))); 2458 } 2459 break; 2460 } 2461 case DEAD_SERVERS: { 2462 if (serverManager != null) { 2463 builder.setDeadServerNames(new ArrayList<>( 2464 serverManager.getDeadServers().copyServerNames())); 2465 } 2466 break; 2467 } 2468 case MASTER_COPROCESSORS: { 2469 if (cpHost != null) { 2470 builder.setMasterCoprocessorNames(Arrays.asList(getMasterCoprocessors())); 2471 } 2472 break; 2473 } 2474 case REGIONS_IN_TRANSITION: { 2475 if (assignmentManager != null) { 2476 builder.setRegionsInTransition(assignmentManager.getRegionStates() 2477 .getRegionsStateInTransition()); 2478 } 2479 break; 2480 } 2481 case BALANCER_ON: { 2482 if (loadBalancerTracker != null) { 2483 builder.setBalancerOn(loadBalancerTracker.isBalancerOn()); 2484 } 2485 break; 2486 } 2487 case MASTER_INFO_PORT: { 2488 if (infoServer != null) { 2489 builder.setMasterInfoPort(infoServer.getPort()); 2490 } 2491 break; 2492 } 2493 } 2494 } 2495 return builder.build(); 2496 } 2497 2498 /** 2499 * @return cluster status 2500 */ 2501 public ClusterMetrics getClusterMetrics() throws IOException { 2502 return getClusterMetrics(EnumSet.allOf(Option.class)); 2503 } 2504 2505 public ClusterMetrics getClusterMetrics(EnumSet<Option> options) throws IOException { 2506 if (cpHost != null) { 2507 cpHost.preGetClusterMetrics(); 2508 } 2509 ClusterMetrics status = getClusterMetricsWithoutCoprocessor(options); 2510 if (cpHost != null) { 2511 cpHost.postGetClusterMetrics(status); 2512 } 2513 return status; 2514 } 2515 2516 private List<ServerName> getBackupMasters() throws InterruptedIOException { 2517 // Build Set of backup masters from ZK nodes 2518 List<String> backupMasterStrings; 2519 try { 2520 backupMasterStrings = ZKUtil.listChildrenNoWatch(this.zooKeeper, 2521 this.zooKeeper.znodePaths.backupMasterAddressesZNode); 2522 } catch (KeeperException e) { 2523 LOG.warn(this.zooKeeper.prefix("Unable to list backup servers"), e); 2524 backupMasterStrings = null; 2525 } 2526 2527 List<ServerName> backupMasters = Collections.emptyList(); 2528 if (backupMasterStrings != null && !backupMasterStrings.isEmpty()) { 2529 backupMasters = new ArrayList<>(backupMasterStrings.size()); 2530 for (String s: backupMasterStrings) { 2531 try { 2532 byte [] bytes; 2533 try { 2534 bytes = ZKUtil.getData(this.zooKeeper, ZNodePaths.joinZNode( 2535 this.zooKeeper.znodePaths.backupMasterAddressesZNode, s)); 2536 } catch (InterruptedException e) { 2537 throw new InterruptedIOException(); 2538 } 2539 if (bytes != null) { 2540 ServerName sn; 2541 try { 2542 sn = ProtobufUtil.parseServerNameFrom(bytes); 2543 } catch (DeserializationException e) { 2544 LOG.warn("Failed parse, skipping registering backup server", e); 2545 continue; 2546 } 2547 backupMasters.add(sn); 2548 } 2549 } catch (KeeperException e) { 2550 LOG.warn(this.zooKeeper.prefix("Unable to get information about " + 2551 "backup servers"), e); 2552 } 2553 } 2554 Collections.sort(backupMasters, new Comparator<ServerName>() { 2555 @Override 2556 public int compare(ServerName s1, ServerName s2) { 2557 return s1.getServerName().compareTo(s2.getServerName()); 2558 }}); 2559 } 2560 return backupMasters; 2561 } 2562 2563 /** 2564 * The set of loaded coprocessors is stored in a static set. Since it's 2565 * statically allocated, it does not require that HMaster's cpHost be 2566 * initialized prior to accessing it. 2567 * @return a String representation of the set of names of the loaded coprocessors. 2568 */ 2569 public static String getLoadedCoprocessors() { 2570 return CoprocessorHost.getLoadedCoprocessors().toString(); 2571 } 2572 2573 /** 2574 * @return timestamp in millis when HMaster was started. 2575 */ 2576 public long getMasterStartTime() { 2577 return startcode; 2578 } 2579 2580 /** 2581 * @return timestamp in millis when HMaster became the active master. 2582 */ 2583 public long getMasterActiveTime() { 2584 return masterActiveTime; 2585 } 2586 2587 /** 2588 * @return timestamp in millis when HMaster finished becoming the active master 2589 */ 2590 public long getMasterFinishedInitializationTime() { 2591 return masterFinishedInitializationTime; 2592 } 2593 2594 public int getNumWALFiles() { 2595 return procedureStore != null ? procedureStore.getActiveLogs().size() : 0; 2596 } 2597 2598 public WALProcedureStore getWalProcedureStore() { 2599 return procedureStore; 2600 } 2601 2602 public int getRegionServerInfoPort(final ServerName sn) { 2603 RegionServerInfo info = this.regionServerTracker.getRegionServerInfo(sn); 2604 if (info == null || info.getInfoPort() == 0) { 2605 return conf.getInt(HConstants.REGIONSERVER_INFO_PORT, 2606 HConstants.DEFAULT_REGIONSERVER_INFOPORT); 2607 } 2608 return info.getInfoPort(); 2609 } 2610 2611 @Override 2612 public String getRegionServerVersion(final ServerName sn) { 2613 RegionServerInfo info = this.regionServerTracker.getRegionServerInfo(sn); 2614 if (info != null && info.hasVersionInfo()) { 2615 return info.getVersionInfo().getVersion(); 2616 } 2617 return "0.0.0"; //Lowest version to prevent move system region to unknown version RS. 2618 } 2619 2620 @Override 2621 public void checkIfShouldMoveSystemRegionAsync() { 2622 assignmentManager.checkIfShouldMoveSystemRegionAsync(); 2623 } 2624 2625 /** 2626 * @return array of coprocessor SimpleNames. 2627 */ 2628 public String[] getMasterCoprocessors() { 2629 Set<String> masterCoprocessors = getMasterCoprocessorHost().getCoprocessors(); 2630 return masterCoprocessors.toArray(new String[masterCoprocessors.size()]); 2631 } 2632 2633 @Override 2634 public void abort(String reason, Throwable cause) { 2635 if (isAborted() || isStopped()) { 2636 return; 2637 } 2638 if (cpHost != null) { 2639 // HBASE-4014: dump a list of loaded coprocessors. 2640 LOG.error(HBaseMarkers.FATAL, "Master server abort: loaded coprocessors are: " + 2641 getLoadedCoprocessors()); 2642 } 2643 String msg = "***** ABORTING master " + this + ": " + reason + " *****"; 2644 if (cause != null) { 2645 LOG.error(HBaseMarkers.FATAL, msg, cause); 2646 } else { 2647 LOG.error(HBaseMarkers.FATAL, msg); 2648 } 2649 2650 try { 2651 stopMaster(); 2652 } catch (IOException e) { 2653 LOG.error("Exception occurred while stopping master", e); 2654 } 2655 } 2656 2657 @Override 2658 public ZKWatcher getZooKeeper() { 2659 return zooKeeper; 2660 } 2661 2662 @Override 2663 public MasterCoprocessorHost getMasterCoprocessorHost() { 2664 return cpHost; 2665 } 2666 2667 @Override 2668 public MasterQuotaManager getMasterQuotaManager() { 2669 return quotaManager; 2670 } 2671 2672 @Override 2673 public ProcedureExecutor<MasterProcedureEnv> getMasterProcedureExecutor() { 2674 return procedureExecutor; 2675 } 2676 2677 @Override 2678 public ServerName getServerName() { 2679 return this.serverName; 2680 } 2681 2682 @Override 2683 public AssignmentManager getAssignmentManager() { 2684 return this.assignmentManager; 2685 } 2686 2687 @Override 2688 public CatalogJanitor getCatalogJanitor() { 2689 return this.catalogJanitorChore; 2690 } 2691 2692 public MemoryBoundedLogMessageBuffer getRegionServerFatalLogBuffer() { 2693 return rsFatals; 2694 } 2695 2696 /** 2697 * Shutdown the cluster. 2698 * Master runs a coordinated stop of all RegionServers and then itself. 2699 */ 2700 public void shutdown() throws IOException { 2701 if (cpHost != null) { 2702 cpHost.preShutdown(); 2703 } 2704 // Tell the servermanager cluster shutdown has been called. This makes it so when Master is 2705 // last running server, it'll stop itself. Next, we broadcast the cluster shutdown by setting 2706 // the cluster status as down. RegionServers will notice this change in state and will start 2707 // shutting themselves down. When last has exited, Master can go down. 2708 if (this.serverManager != null) { 2709 this.serverManager.shutdownCluster(); 2710 } 2711 if (this.clusterStatusTracker != null) { 2712 try { 2713 this.clusterStatusTracker.setClusterDown(); 2714 } catch (KeeperException e) { 2715 LOG.error("ZooKeeper exception trying to set cluster as down in ZK", e); 2716 } 2717 } 2718 // Stop the procedure executor. Will stop any ongoing assign, unassign, server crash etc., 2719 // processing so we can go down. 2720 if (this.procedureExecutor != null) { 2721 this.procedureExecutor.stop(); 2722 } 2723 // Shutdown our cluster connection. This will kill any hosted RPCs that might be going on; 2724 // this is what we want especially if the Master is in startup phase doing call outs to 2725 // hbase:meta, etc. when cluster is down. Without ths connection close, we'd have to wait on 2726 // the rpc to timeout. 2727 if (this.clusterConnection != null) { 2728 this.clusterConnection.close(); 2729 } 2730 } 2731 2732 public void stopMaster() throws IOException { 2733 if (cpHost != null) { 2734 cpHost.preStopMaster(); 2735 } 2736 stop("Stopped by " + Thread.currentThread().getName()); 2737 } 2738 2739 @Override 2740 public void stop(String msg) { 2741 if (!isStopped()) { 2742 super.stop(msg); 2743 if (this.activeMasterManager != null) { 2744 this.activeMasterManager.stop(); 2745 } 2746 } 2747 } 2748 2749 void checkServiceStarted() throws ServerNotRunningYetException { 2750 if (!serviceStarted) { 2751 throw new ServerNotRunningYetException("Server is not running yet"); 2752 } 2753 } 2754 2755 public static class MasterStoppedException extends DoNotRetryIOException { 2756 MasterStoppedException() { 2757 super(); 2758 } 2759 } 2760 2761 void checkInitialized() throws PleaseHoldException, ServerNotRunningYetException, 2762 MasterNotRunningException, MasterStoppedException { 2763 checkServiceStarted(); 2764 if (!isInitialized()) { 2765 throw new PleaseHoldException("Master is initializing"); 2766 } 2767 if (isStopped()) { 2768 throw new MasterStoppedException(); 2769 } 2770 } 2771 2772 /** 2773 * Report whether this master is currently the active master or not. 2774 * If not active master, we are parked on ZK waiting to become active. 2775 * 2776 * This method is used for testing. 2777 * 2778 * @return true if active master, false if not. 2779 */ 2780 @Override 2781 public boolean isActiveMaster() { 2782 return activeMaster; 2783 } 2784 2785 /** 2786 * Report whether this master has completed with its initialization and is 2787 * ready. If ready, the master is also the active master. A standby master 2788 * is never ready. 2789 * 2790 * This method is used for testing. 2791 * 2792 * @return true if master is ready to go, false if not. 2793 */ 2794 @Override 2795 public boolean isInitialized() { 2796 return initialized.isReady(); 2797 } 2798 2799 /** 2800 * Report whether this master is in maintenance mode. 2801 * 2802 * @return true if master is in maintenanceMode 2803 */ 2804 @Override 2805 public boolean isInMaintenanceMode() throws IOException { 2806 if (!isInitialized()) { 2807 throw new PleaseHoldException("Master is initializing"); 2808 } 2809 return maintenanceModeTracker.isInMaintenanceMode(); 2810 } 2811 2812 @VisibleForTesting 2813 public void setInitialized(boolean isInitialized) { 2814 procedureExecutor.getEnvironment().setEventReady(initialized, isInitialized); 2815 } 2816 2817 @Override 2818 public ProcedureEvent getInitializedEvent() { 2819 return initialized; 2820 } 2821 2822 /** 2823 * ServerCrashProcessingEnabled is set false before completing assignMeta to prevent processing 2824 * of crashed servers. 2825 * @return true if assignMeta has completed; 2826 */ 2827 @Override 2828 public boolean isServerCrashProcessingEnabled() { 2829 return serverCrashProcessingEnabled.isReady(); 2830 } 2831 2832 @VisibleForTesting 2833 public void setServerCrashProcessingEnabled(final boolean b) { 2834 procedureExecutor.getEnvironment().setEventReady(serverCrashProcessingEnabled, b); 2835 } 2836 2837 public ProcedureEvent getServerCrashProcessingEnabledEvent() { 2838 return serverCrashProcessingEnabled; 2839 } 2840 2841 /** 2842 * Compute the average load across all region servers. 2843 * Currently, this uses a very naive computation - just uses the number of 2844 * regions being served, ignoring stats about number of requests. 2845 * @return the average load 2846 */ 2847 public double getAverageLoad() { 2848 if (this.assignmentManager == null) { 2849 return 0; 2850 } 2851 2852 RegionStates regionStates = this.assignmentManager.getRegionStates(); 2853 if (regionStates == null) { 2854 return 0; 2855 } 2856 return regionStates.getAverageLoad(); 2857 } 2858 2859 /* 2860 * @return the count of region split plans executed 2861 */ 2862 public long getSplitPlanCount() { 2863 return splitPlanCount; 2864 } 2865 2866 /* 2867 * @return the count of region merge plans executed 2868 */ 2869 public long getMergePlanCount() { 2870 return mergePlanCount; 2871 } 2872 2873 @Override 2874 public boolean registerService(Service instance) { 2875 /* 2876 * No stacking of instances is allowed for a single service name 2877 */ 2878 Descriptors.ServiceDescriptor serviceDesc = instance.getDescriptorForType(); 2879 String serviceName = CoprocessorRpcUtils.getServiceName(serviceDesc); 2880 if (coprocessorServiceHandlers.containsKey(serviceName)) { 2881 LOG.error("Coprocessor service "+serviceName+ 2882 " already registered, rejecting request from "+instance 2883 ); 2884 return false; 2885 } 2886 2887 coprocessorServiceHandlers.put(serviceName, instance); 2888 if (LOG.isDebugEnabled()) { 2889 LOG.debug("Registered master coprocessor service: service="+serviceName); 2890 } 2891 return true; 2892 } 2893 2894 /** 2895 * Utility for constructing an instance of the passed HMaster class. 2896 * @param masterClass 2897 * @return HMaster instance. 2898 */ 2899 public static HMaster constructMaster(Class<? extends HMaster> masterClass, 2900 final Configuration conf) { 2901 try { 2902 Constructor<? extends HMaster> c = masterClass.getConstructor(Configuration.class); 2903 return c.newInstance(conf); 2904 } catch(Exception e) { 2905 Throwable error = e; 2906 if (e instanceof InvocationTargetException && 2907 ((InvocationTargetException)e).getTargetException() != null) { 2908 error = ((InvocationTargetException)e).getTargetException(); 2909 } 2910 throw new RuntimeException("Failed construction of Master: " + masterClass.toString() + ". " 2911 , error); 2912 } 2913 } 2914 2915 /** 2916 * @see org.apache.hadoop.hbase.master.HMasterCommandLine 2917 */ 2918 public static void main(String [] args) { 2919 LOG.info("STARTING service " + HMaster.class.getSimpleName()); 2920 VersionInfo.logVersion(); 2921 new HMasterCommandLine(HMaster.class).doMain(args); 2922 } 2923 2924 public HFileCleaner getHFileCleaner() { 2925 return this.hfileCleaner; 2926 } 2927 2928 public LogCleaner getLogCleaner() { 2929 return this.logCleaner; 2930 } 2931 2932 /** 2933 * @return the underlying snapshot manager 2934 */ 2935 @Override 2936 public SnapshotManager getSnapshotManager() { 2937 return this.snapshotManager; 2938 } 2939 2940 /** 2941 * @return the underlying MasterProcedureManagerHost 2942 */ 2943 @Override 2944 public MasterProcedureManagerHost getMasterProcedureManagerHost() { 2945 return mpmHost; 2946 } 2947 2948 @Override 2949 public ClusterSchema getClusterSchema() { 2950 return this.clusterSchemaService; 2951 } 2952 2953 /** 2954 * Create a new Namespace. 2955 * @param namespaceDescriptor descriptor for new Namespace 2956 * @param nonceGroup Identifier for the source of the request, a client or process. 2957 * @param nonce A unique identifier for this operation from the client or process identified by 2958 * <code>nonceGroup</code> (the source must ensure each operation gets a unique id). 2959 * @return procedure id 2960 */ 2961 long createNamespace(final NamespaceDescriptor namespaceDescriptor, final long nonceGroup, 2962 final long nonce) throws IOException { 2963 checkInitialized(); 2964 2965 TableName.isLegalNamespaceName(Bytes.toBytes(namespaceDescriptor.getName())); 2966 2967 return MasterProcedureUtil.submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, 2968 nonceGroup, nonce) { 2969 @Override 2970 protected void run() throws IOException { 2971 getMaster().getMasterCoprocessorHost().preCreateNamespace(namespaceDescriptor); 2972 // We need to wait for the procedure to potentially fail due to "prepare" sanity 2973 // checks. This will block only the beginning of the procedure. See HBASE-19953. 2974 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 2975 LOG.info(getClientIdAuditPrefix() + " creating " + namespaceDescriptor); 2976 // Execute the operation synchronously - wait for the operation to complete before 2977 // continuing. 2978 setProcId(getClusterSchema().createNamespace(namespaceDescriptor, getNonceKey(), latch)); 2979 latch.await(); 2980 getMaster().getMasterCoprocessorHost().postCreateNamespace(namespaceDescriptor); 2981 } 2982 2983 @Override 2984 protected String getDescription() { 2985 return "CreateNamespaceProcedure"; 2986 } 2987 }); 2988 } 2989 2990 /** 2991 * Modify an existing Namespace. 2992 * @param nonceGroup Identifier for the source of the request, a client or process. 2993 * @param nonce A unique identifier for this operation from the client or process identified by 2994 * <code>nonceGroup</code> (the source must ensure each operation gets a unique id). 2995 * @return procedure id 2996 */ 2997 long modifyNamespace(final NamespaceDescriptor newNsDescriptor, final long nonceGroup, 2998 final long nonce) throws IOException { 2999 checkInitialized(); 3000 3001 TableName.isLegalNamespaceName(Bytes.toBytes(newNsDescriptor.getName())); 3002 3003 return MasterProcedureUtil.submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, 3004 nonceGroup, nonce) { 3005 @Override 3006 protected void run() throws IOException { 3007 NamespaceDescriptor oldNsDescriptor = getNamespace(newNsDescriptor.getName()); 3008 getMaster().getMasterCoprocessorHost().preModifyNamespace(oldNsDescriptor, newNsDescriptor); 3009 // We need to wait for the procedure to potentially fail due to "prepare" sanity 3010 // checks. This will block only the beginning of the procedure. See HBASE-19953. 3011 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 3012 LOG.info(getClientIdAuditPrefix() + " modify " + newNsDescriptor); 3013 // Execute the operation synchronously - wait for the operation to complete before 3014 // continuing. 3015 setProcId(getClusterSchema().modifyNamespace(newNsDescriptor, getNonceKey(), latch)); 3016 latch.await(); 3017 getMaster().getMasterCoprocessorHost().postModifyNamespace(oldNsDescriptor, 3018 newNsDescriptor); 3019 } 3020 3021 @Override 3022 protected String getDescription() { 3023 return "ModifyNamespaceProcedure"; 3024 } 3025 }); 3026 } 3027 3028 /** 3029 * Delete an existing Namespace. Only empty Namespaces (no tables) can be removed. 3030 * @param nonceGroup Identifier for the source of the request, a client or process. 3031 * @param nonce A unique identifier for this operation from the client or process identified by 3032 * <code>nonceGroup</code> (the source must ensure each operation gets a unique id). 3033 * @return procedure id 3034 */ 3035 long deleteNamespace(final String name, final long nonceGroup, final long nonce) 3036 throws IOException { 3037 checkInitialized(); 3038 3039 return MasterProcedureUtil.submitProcedure(new MasterProcedureUtil.NonceProcedureRunnable(this, 3040 nonceGroup, nonce) { 3041 @Override 3042 protected void run() throws IOException { 3043 getMaster().getMasterCoprocessorHost().preDeleteNamespace(name); 3044 LOG.info(getClientIdAuditPrefix() + " delete " + name); 3045 // Execute the operation synchronously - wait for the operation to complete before 3046 // continuing. 3047 // 3048 // We need to wait for the procedure to potentially fail due to "prepare" sanity 3049 // checks. This will block only the beginning of the procedure. See HBASE-19953. 3050 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createBlockingLatch(); 3051 setProcId(submitProcedure( 3052 new DeleteNamespaceProcedure(procedureExecutor.getEnvironment(), name, latch))); 3053 latch.await(); 3054 // Will not be invoked in the face of Exception thrown by the Procedure's execution 3055 getMaster().getMasterCoprocessorHost().postDeleteNamespace(name); 3056 } 3057 3058 @Override 3059 protected String getDescription() { 3060 return "DeleteNamespaceProcedure"; 3061 } 3062 }); 3063 } 3064 3065 /** 3066 * Get a Namespace 3067 * @param name Name of the Namespace 3068 * @return Namespace descriptor for <code>name</code> 3069 */ 3070 NamespaceDescriptor getNamespace(String name) throws IOException { 3071 checkInitialized(); 3072 if (this.cpHost != null) this.cpHost.preGetNamespaceDescriptor(name); 3073 NamespaceDescriptor nsd = this.clusterSchemaService.getNamespace(name); 3074 if (this.cpHost != null) this.cpHost.postGetNamespaceDescriptor(nsd); 3075 return nsd; 3076 } 3077 3078 /** 3079 * Get all Namespaces 3080 * @return All Namespace descriptors 3081 */ 3082 List<NamespaceDescriptor> getNamespaces() throws IOException { 3083 checkInitialized(); 3084 final List<NamespaceDescriptor> nsds = new ArrayList<>(); 3085 if (cpHost != null) { 3086 cpHost.preListNamespaceDescriptors(nsds); 3087 } 3088 nsds.addAll(this.clusterSchemaService.getNamespaces()); 3089 if (this.cpHost != null) { 3090 this.cpHost.postListNamespaceDescriptors(nsds); 3091 } 3092 return nsds; 3093 } 3094 3095 @Override 3096 public List<TableName> listTableNamesByNamespace(String name) throws IOException { 3097 checkInitialized(); 3098 return listTableNames(name, null, true); 3099 } 3100 3101 @Override 3102 public List<TableDescriptor> listTableDescriptorsByNamespace(String name) throws IOException { 3103 checkInitialized(); 3104 return listTableDescriptors(name, null, null, true); 3105 } 3106 3107 @Override 3108 public boolean abortProcedure(final long procId, final boolean mayInterruptIfRunning) 3109 throws IOException { 3110 if (cpHost != null) { 3111 cpHost.preAbortProcedure(this.procedureExecutor, procId); 3112 } 3113 3114 final boolean result = this.procedureExecutor.abort(procId, mayInterruptIfRunning); 3115 3116 if (cpHost != null) { 3117 cpHost.postAbortProcedure(); 3118 } 3119 3120 return result; 3121 } 3122 3123 @Override 3124 public List<Procedure<?>> getProcedures() throws IOException { 3125 if (cpHost != null) { 3126 cpHost.preGetProcedures(); 3127 } 3128 3129 final List<Procedure<?>> procList = this.procedureExecutor.getProcedures(); 3130 3131 if (cpHost != null) { 3132 cpHost.postGetProcedures(procList); 3133 } 3134 3135 return procList; 3136 } 3137 3138 @Override 3139 public List<LockedResource> getLocks() throws IOException { 3140 if (cpHost != null) { 3141 cpHost.preGetLocks(); 3142 } 3143 3144 MasterProcedureScheduler procedureScheduler = 3145 procedureExecutor.getEnvironment().getProcedureScheduler(); 3146 3147 final List<LockedResource> lockedResources = procedureScheduler.getLocks(); 3148 3149 if (cpHost != null) { 3150 cpHost.postGetLocks(lockedResources); 3151 } 3152 3153 return lockedResources; 3154 } 3155 3156 /** 3157 * Returns the list of table descriptors that match the specified request 3158 * @param namespace the namespace to query, or null if querying for all 3159 * @param regex The regular expression to match against, or null if querying for all 3160 * @param tableNameList the list of table names, or null if querying for all 3161 * @param includeSysTables False to match only against userspace tables 3162 * @return the list of table descriptors 3163 */ 3164 public List<TableDescriptor> listTableDescriptors(final String namespace, final String regex, 3165 final List<TableName> tableNameList, final boolean includeSysTables) 3166 throws IOException { 3167 List<TableDescriptor> htds = new ArrayList<>(); 3168 if (cpHost != null) { 3169 cpHost.preGetTableDescriptors(tableNameList, htds, regex); 3170 } 3171 htds = getTableDescriptors(htds, namespace, regex, tableNameList, includeSysTables); 3172 if (cpHost != null) { 3173 cpHost.postGetTableDescriptors(tableNameList, htds, regex); 3174 } 3175 return htds; 3176 } 3177 3178 /** 3179 * Returns the list of table names that match the specified request 3180 * @param regex The regular expression to match against, or null if querying for all 3181 * @param namespace the namespace to query, or null if querying for all 3182 * @param includeSysTables False to match only against userspace tables 3183 * @return the list of table names 3184 */ 3185 public List<TableName> listTableNames(final String namespace, final String regex, 3186 final boolean includeSysTables) throws IOException { 3187 List<TableDescriptor> htds = new ArrayList<>(); 3188 if (cpHost != null) { 3189 cpHost.preGetTableNames(htds, regex); 3190 } 3191 htds = getTableDescriptors(htds, namespace, regex, null, includeSysTables); 3192 if (cpHost != null) { 3193 cpHost.postGetTableNames(htds, regex); 3194 } 3195 List<TableName> result = new ArrayList<>(htds.size()); 3196 for (TableDescriptor htd: htds) result.add(htd.getTableName()); 3197 return result; 3198 } 3199 3200 /** 3201 * @return list of table table descriptors after filtering by regex and whether to include system 3202 * tables, etc. 3203 * @throws IOException 3204 */ 3205 private List<TableDescriptor> getTableDescriptors(final List<TableDescriptor> htds, 3206 final String namespace, final String regex, final List<TableName> tableNameList, 3207 final boolean includeSysTables) 3208 throws IOException { 3209 if (tableNameList == null || tableNameList.isEmpty()) { 3210 // request for all TableDescriptors 3211 Collection<TableDescriptor> allHtds; 3212 if (namespace != null && namespace.length() > 0) { 3213 // Do a check on the namespace existence. Will fail if does not exist. 3214 this.clusterSchemaService.getNamespace(namespace); 3215 allHtds = tableDescriptors.getByNamespace(namespace).values(); 3216 } else { 3217 allHtds = tableDescriptors.getAll().values(); 3218 } 3219 for (TableDescriptor desc: allHtds) { 3220 if (tableStateManager.isTablePresent(desc.getTableName()) 3221 && (includeSysTables || !desc.getTableName().isSystemTable())) { 3222 htds.add(desc); 3223 } 3224 } 3225 } else { 3226 for (TableName s: tableNameList) { 3227 if (tableStateManager.isTablePresent(s)) { 3228 TableDescriptor desc = tableDescriptors.get(s); 3229 if (desc != null) { 3230 htds.add(desc); 3231 } 3232 } 3233 } 3234 } 3235 3236 // Retains only those matched by regular expression. 3237 if (regex != null) filterTablesByRegex(htds, Pattern.compile(regex)); 3238 return htds; 3239 } 3240 3241 /** 3242 * Removes the table descriptors that don't match the pattern. 3243 * @param descriptors list of table descriptors to filter 3244 * @param pattern the regex to use 3245 */ 3246 private static void filterTablesByRegex(final Collection<TableDescriptor> descriptors, 3247 final Pattern pattern) { 3248 final String defaultNS = NamespaceDescriptor.DEFAULT_NAMESPACE_NAME_STR; 3249 Iterator<TableDescriptor> itr = descriptors.iterator(); 3250 while (itr.hasNext()) { 3251 TableDescriptor htd = itr.next(); 3252 String tableName = htd.getTableName().getNameAsString(); 3253 boolean matched = pattern.matcher(tableName).matches(); 3254 if (!matched && htd.getTableName().getNamespaceAsString().equals(defaultNS)) { 3255 matched = pattern.matcher(defaultNS + TableName.NAMESPACE_DELIM + tableName).matches(); 3256 } 3257 if (!matched) { 3258 itr.remove(); 3259 } 3260 } 3261 } 3262 3263 @Override 3264 public long getLastMajorCompactionTimestamp(TableName table) throws IOException { 3265 return getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS)) 3266 .getLastMajorCompactionTimestamp(table); 3267 } 3268 3269 @Override 3270 public long getLastMajorCompactionTimestampForRegion(byte[] regionName) throws IOException { 3271 return getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS)) 3272 .getLastMajorCompactionTimestamp(regionName); 3273 } 3274 3275 /** 3276 * Gets the mob file compaction state for a specific table. 3277 * Whether all the mob files are selected is known during the compaction execution, but 3278 * the statistic is done just before compaction starts, it is hard to know the compaction 3279 * type at that time, so the rough statistics are chosen for the mob file compaction. Only two 3280 * compaction states are available, CompactionState.MAJOR_AND_MINOR and CompactionState.NONE. 3281 * @param tableName The current table name. 3282 * @return If a given table is in mob file compaction now. 3283 */ 3284 public CompactionState getMobCompactionState(TableName tableName) { 3285 AtomicInteger compactionsCount = mobCompactionStates.get(tableName); 3286 if (compactionsCount != null && compactionsCount.get() != 0) { 3287 return CompactionState.MAJOR_AND_MINOR; 3288 } 3289 return CompactionState.NONE; 3290 } 3291 3292 public void reportMobCompactionStart(TableName tableName) throws IOException { 3293 IdLock.Entry lockEntry = null; 3294 try { 3295 lockEntry = mobCompactionLock.getLockEntry(tableName.hashCode()); 3296 AtomicInteger compactionsCount = mobCompactionStates.get(tableName); 3297 if (compactionsCount == null) { 3298 compactionsCount = new AtomicInteger(0); 3299 mobCompactionStates.put(tableName, compactionsCount); 3300 } 3301 compactionsCount.incrementAndGet(); 3302 } finally { 3303 if (lockEntry != null) { 3304 mobCompactionLock.releaseLockEntry(lockEntry); 3305 } 3306 } 3307 } 3308 3309 public void reportMobCompactionEnd(TableName tableName) throws IOException { 3310 IdLock.Entry lockEntry = null; 3311 try { 3312 lockEntry = mobCompactionLock.getLockEntry(tableName.hashCode()); 3313 AtomicInteger compactionsCount = mobCompactionStates.get(tableName); 3314 if (compactionsCount != null) { 3315 int count = compactionsCount.decrementAndGet(); 3316 // remove the entry if the count is 0. 3317 if (count == 0) { 3318 mobCompactionStates.remove(tableName); 3319 } 3320 } 3321 } finally { 3322 if (lockEntry != null) { 3323 mobCompactionLock.releaseLockEntry(lockEntry); 3324 } 3325 } 3326 } 3327 3328 /** 3329 * Requests mob compaction. 3330 * @param tableName The table the compact. 3331 * @param columns The compacted columns. 3332 * @param allFiles Whether add all mob files into the compaction. 3333 */ 3334 public void requestMobCompaction(TableName tableName, 3335 List<ColumnFamilyDescriptor> columns, boolean allFiles) throws IOException { 3336 mobCompactThread.requestMobCompaction(conf, fs, tableName, columns, allFiles); 3337 } 3338 3339 /** 3340 * Queries the state of the {@link LoadBalancerTracker}. If the balancer is not initialized, 3341 * false is returned. 3342 * 3343 * @return The state of the load balancer, or false if the load balancer isn't defined. 3344 */ 3345 public boolean isBalancerOn() { 3346 try { 3347 if (null == loadBalancerTracker || isInMaintenanceMode()) { 3348 return false; 3349 } 3350 } catch (IOException e) { 3351 return false; 3352 } 3353 return loadBalancerTracker.isBalancerOn(); 3354 } 3355 3356 /** 3357 * Queries the state of the {@link RegionNormalizerTracker}. If it's not initialized, 3358 * false is returned. 3359 */ 3360 public boolean isNormalizerOn() { 3361 try { 3362 return (null == regionNormalizerTracker || isInMaintenanceMode()) ? 3363 false: regionNormalizerTracker.isNormalizerOn(); 3364 } catch (IOException e) { 3365 return false; 3366 } 3367 } 3368 3369 /** 3370 * Queries the state of the {@link SplitOrMergeTracker}. If it is not initialized, 3371 * false is returned. If switchType is illegal, false will return. 3372 * @param switchType see {@link org.apache.hadoop.hbase.client.MasterSwitchType} 3373 * @return The state of the switch 3374 */ 3375 @Override 3376 public boolean isSplitOrMergeEnabled(MasterSwitchType switchType) { 3377 try { 3378 if (null == splitOrMergeTracker || isInMaintenanceMode()) { 3379 return false; 3380 } 3381 } catch (IOException e) { 3382 return false; 3383 } 3384 return splitOrMergeTracker.isSplitOrMergeEnabled(switchType); 3385 } 3386 3387 /** 3388 * Fetch the configured {@link LoadBalancer} class name. If none is set, a default is returned. 3389 * 3390 * @return The name of the {@link LoadBalancer} in use. 3391 */ 3392 public String getLoadBalancerClassName() { 3393 return conf.get(HConstants.HBASE_MASTER_LOADBALANCER_CLASS, LoadBalancerFactory 3394 .getDefaultLoadBalancerClass().getName()); 3395 } 3396 3397 /** 3398 * @return RegionNormalizerTracker instance 3399 */ 3400 public RegionNormalizerTracker getRegionNormalizerTracker() { 3401 return regionNormalizerTracker; 3402 } 3403 3404 public SplitOrMergeTracker getSplitOrMergeTracker() { 3405 return splitOrMergeTracker; 3406 } 3407 3408 @Override 3409 public LoadBalancer getLoadBalancer() { 3410 return balancer; 3411 } 3412 3413 @Override 3414 public FavoredNodesManager getFavoredNodesManager() { 3415 return favoredNodesManager; 3416 } 3417 3418 @Override 3419 public void addReplicationPeer(String peerId, ReplicationPeerConfig peerConfig, boolean enabled) 3420 throws ReplicationException, IOException { 3421 if (cpHost != null) { 3422 cpHost.preAddReplicationPeer(peerId, peerConfig); 3423 } 3424 LOG.info(getClientIdAuditPrefix() + " creating replication peer, id=" + peerId + ", config=" 3425 + peerConfig + ", state=" + (enabled ? "ENABLED" : "DISABLED")); 3426 this.replicationManager.addReplicationPeer(peerId, peerConfig, enabled); 3427 if (cpHost != null) { 3428 cpHost.postAddReplicationPeer(peerId, peerConfig); 3429 } 3430 } 3431 3432 @Override 3433 public void removeReplicationPeer(String peerId) throws ReplicationException, IOException { 3434 if (cpHost != null) { 3435 cpHost.preRemoveReplicationPeer(peerId); 3436 } 3437 LOG.info(getClientIdAuditPrefix() + " removing replication peer, id=" + peerId); 3438 this.replicationManager.removeReplicationPeer(peerId); 3439 if (cpHost != null) { 3440 cpHost.postRemoveReplicationPeer(peerId); 3441 } 3442 } 3443 3444 @Override 3445 public void enableReplicationPeer(String peerId) throws ReplicationException, IOException { 3446 if (cpHost != null) { 3447 cpHost.preEnableReplicationPeer(peerId); 3448 } 3449 LOG.info(getClientIdAuditPrefix() + " enable replication peer, id=" + peerId); 3450 this.replicationManager.enableReplicationPeer(peerId); 3451 if (cpHost != null) { 3452 cpHost.postEnableReplicationPeer(peerId); 3453 } 3454 } 3455 3456 @Override 3457 public void disableReplicationPeer(String peerId) throws ReplicationException, IOException { 3458 if (cpHost != null) { 3459 cpHost.preDisableReplicationPeer(peerId); 3460 } 3461 LOG.info(getClientIdAuditPrefix() + " disable replication peer, id=" + peerId); 3462 this.replicationManager.disableReplicationPeer(peerId); 3463 if (cpHost != null) { 3464 cpHost.postDisableReplicationPeer(peerId); 3465 } 3466 } 3467 3468 @Override 3469 public ReplicationPeerConfig getReplicationPeerConfig(String peerId) throws ReplicationException, 3470 IOException { 3471 if (cpHost != null) { 3472 cpHost.preGetReplicationPeerConfig(peerId); 3473 } 3474 final ReplicationPeerConfig peerConfig = this.replicationManager.getPeerConfig(peerId); 3475 LOG.info(getClientIdAuditPrefix() + " get replication peer config, id=" + peerId + ", config=" 3476 + peerConfig); 3477 if (cpHost != null) { 3478 cpHost.postGetReplicationPeerConfig(peerId); 3479 } 3480 return peerConfig; 3481 } 3482 3483 @Override 3484 public void updateReplicationPeerConfig(String peerId, ReplicationPeerConfig peerConfig) 3485 throws ReplicationException, IOException { 3486 if (cpHost != null) { 3487 cpHost.preUpdateReplicationPeerConfig(peerId, peerConfig); 3488 } 3489 LOG.info(getClientIdAuditPrefix() + " update replication peer config, id=" + peerId 3490 + ", config=" + peerConfig); 3491 this.replicationManager.updatePeerConfig(peerId, peerConfig); 3492 if (cpHost != null) { 3493 cpHost.postUpdateReplicationPeerConfig(peerId, peerConfig); 3494 } 3495 } 3496 3497 @Override 3498 public List<ReplicationPeerDescription> listReplicationPeers(String regex) 3499 throws ReplicationException, IOException { 3500 if (cpHost != null) { 3501 cpHost.preListReplicationPeers(regex); 3502 } 3503 LOG.info(getClientIdAuditPrefix() + " list replication peers, regex=" + regex); 3504 Pattern pattern = regex == null ? null : Pattern.compile(regex); 3505 List<ReplicationPeerDescription> peers = this.replicationManager.listReplicationPeers(pattern); 3506 if (cpHost != null) { 3507 cpHost.postListReplicationPeers(regex); 3508 } 3509 return peers; 3510 } 3511 3512 /** 3513 * Mark region server(s) as decommissioned (previously called 'draining') to prevent additional 3514 * regions from getting assigned to them. Also unload the regions on the servers asynchronously.0 3515 * @param servers Region servers to decommission. 3516 * @throws HBaseIOException 3517 */ 3518 public void decommissionRegionServers(final List<ServerName> servers, final boolean offload) 3519 throws HBaseIOException { 3520 List<ServerName> serversAdded = new ArrayList<>(servers.size()); 3521 // Place the decommission marker first. 3522 String parentZnode = getZooKeeper().znodePaths.drainingZNode; 3523 for (ServerName server : servers) { 3524 try { 3525 String node = ZNodePaths.joinZNode(parentZnode, server.getServerName()); 3526 ZKUtil.createAndFailSilent(getZooKeeper(), node); 3527 } catch (KeeperException ke) { 3528 throw new HBaseIOException( 3529 this.zooKeeper.prefix("Unable to decommission '" + server.getServerName() + "'."), ke); 3530 } 3531 if (this.serverManager.addServerToDrainList(server)) { 3532 serversAdded.add(server); 3533 }; 3534 } 3535 // Move the regions off the decommissioned servers. 3536 if (offload) { 3537 final List<ServerName> destServers = this.serverManager.createDestinationServersList(); 3538 for (ServerName server : serversAdded) { 3539 final List<RegionInfo> regionsOnServer = 3540 this.assignmentManager.getRegionStates().getServerRegionInfoSet(server); 3541 for (RegionInfo hri : regionsOnServer) { 3542 ServerName dest = balancer.randomAssignment(hri, destServers); 3543 if (dest == null) { 3544 throw new HBaseIOException("Unable to determine a plan to move " + hri); 3545 } 3546 RegionPlan rp = new RegionPlan(hri, server, dest); 3547 this.assignmentManager.moveAsync(rp); 3548 } 3549 } 3550 } 3551 } 3552 3553 /** 3554 * List region servers marked as decommissioned (previously called 'draining') to not get regions 3555 * assigned to them. 3556 * @return List of decommissioned servers. 3557 */ 3558 public List<ServerName> listDecommissionedRegionServers() { 3559 return this.serverManager.getDrainingServersList(); 3560 } 3561 3562 /** 3563 * Remove decommission marker (previously called 'draining') from a region server to allow regions 3564 * assignments. Load regions onto the server asynchronously if a list of regions is given 3565 * @param server Region server to remove decommission marker from. 3566 * @throws HBaseIOException 3567 */ 3568 public void recommissionRegionServer(final ServerName server, 3569 final List<byte[]> encodedRegionNames) throws HBaseIOException { 3570 // Remove the server from decommissioned (draining) server list. 3571 String parentZnode = getZooKeeper().znodePaths.drainingZNode; 3572 String node = ZNodePaths.joinZNode(parentZnode, server.getServerName()); 3573 try { 3574 ZKUtil.deleteNodeFailSilent(getZooKeeper(), node); 3575 } catch (KeeperException ke) { 3576 throw new HBaseIOException( 3577 this.zooKeeper.prefix("Unable to recommission '" + server.getServerName() + "'."), ke); 3578 } 3579 this.serverManager.removeServerFromDrainList(server); 3580 3581 // Load the regions onto the server if we are given a list of regions. 3582 if (encodedRegionNames == null || encodedRegionNames.isEmpty()) { 3583 return; 3584 } 3585 if (!this.serverManager.isServerOnline(server)) { 3586 return; 3587 } 3588 for (byte[] encodedRegionName : encodedRegionNames) { 3589 RegionState regionState = 3590 assignmentManager.getRegionStates().getRegionState(Bytes.toString(encodedRegionName)); 3591 if (regionState == null) { 3592 LOG.warn("Unknown region " + Bytes.toStringBinary(encodedRegionName)); 3593 continue; 3594 } 3595 RegionInfo hri = regionState.getRegion(); 3596 if (server.equals(regionState.getServerName())) { 3597 LOG.info("Skipping move of region " + hri.getRegionNameAsString() 3598 + " because region already assigned to the same server " + server + "."); 3599 continue; 3600 } 3601 RegionPlan rp = new RegionPlan(hri, regionState.getServerName(), server); 3602 this.assignmentManager.moveAsync(rp); 3603 } 3604 } 3605 3606 @Override 3607 public LockManager getLockManager() { 3608 return lockManager; 3609 } 3610 3611 @Override 3612 public boolean recoverMeta() throws IOException { 3613 // we need to block here so the latch should be greater than the current version to make sure 3614 // that we will block. 3615 ProcedurePrepareLatch latch = ProcedurePrepareLatch.createLatch(Integer.MAX_VALUE, 0); 3616 procedureExecutor.submitProcedure(new RecoverMetaProcedure(null, true, latch)); 3617 latch.await(); 3618 LOG.info("hbase:meta deployed at={}", 3619 getMetaTableLocator().getMetaRegionLocation(getZooKeeper())); 3620 return assignmentManager.isMetaInitialized(); 3621 } 3622 3623 public QuotaObserverChore getQuotaObserverChore() { 3624 return this.quotaObserverChore; 3625 } 3626 3627 public SpaceQuotaSnapshotNotifier getSpaceQuotaSnapshotNotifier() { 3628 return this.spaceQuotaSnapshotNotifier; 3629 } 3630 3631 /** 3632 * This method modifies the master's configuration in order to inject replication-related features 3633 */ 3634 @VisibleForTesting 3635 public static void decorateMasterConfiguration(Configuration conf) { 3636 String plugins = conf.get(HBASE_MASTER_LOGCLEANER_PLUGINS); 3637 String cleanerClass = ReplicationLogCleaner.class.getCanonicalName(); 3638 if (!plugins.contains(cleanerClass)) { 3639 conf.set(HBASE_MASTER_LOGCLEANER_PLUGINS, plugins + "," + cleanerClass); 3640 } 3641 if (ReplicationUtils.isReplicationForBulkLoadDataEnabled(conf)) { 3642 plugins = conf.get(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS); 3643 cleanerClass = ReplicationHFileCleaner.class.getCanonicalName(); 3644 if (!plugins.contains(cleanerClass)) { 3645 conf.set(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS, plugins + "," + cleanerClass); 3646 } 3647 } 3648 } 3649}