View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.master;
20  
21  import java.io.IOException;
22  import java.io.InterruptedIOException;
23  import java.lang.reflect.Constructor;
24  import java.lang.reflect.InvocationTargetException;
25  import java.net.InetAddress;
26  import java.net.InetSocketAddress;
27  import java.net.UnknownHostException;
28  import java.util.ArrayList;
29  import java.util.Collection;
30  import java.util.Collections;
31  import java.util.Comparator;
32  import java.util.HashSet;
33  import java.util.Iterator;
34  import java.util.List;
35  import java.util.Map;
36  import java.util.Set;
37  import java.util.concurrent.TimeUnit;
38  import java.util.concurrent.atomic.AtomicReference;
39  import java.util.regex.Pattern;
40  
41  import javax.servlet.ServletException;
42  import javax.servlet.http.HttpServlet;
43  import javax.servlet.http.HttpServletRequest;
44  import javax.servlet.http.HttpServletResponse;
45  
46  import org.apache.commons.logging.Log;
47  import org.apache.commons.logging.LogFactory;
48  import org.apache.hadoop.conf.Configuration;
49  import org.apache.hadoop.fs.Path;
50  import org.apache.hadoop.hbase.ClusterStatus;
51  import org.apache.hadoop.hbase.CoordinatedStateException;
52  import org.apache.hadoop.hbase.CoordinatedStateManager;
53  import org.apache.hadoop.hbase.DoNotRetryIOException;
54  import org.apache.hadoop.hbase.HBaseIOException;
55  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
56  import org.apache.hadoop.hbase.HColumnDescriptor;
57  import org.apache.hadoop.hbase.HConstants;
58  import org.apache.hadoop.hbase.HRegionInfo;
59  import org.apache.hadoop.hbase.HTableDescriptor;
60  import org.apache.hadoop.hbase.MasterNotRunningException;
61  import org.apache.hadoop.hbase.MetaMigrationConvertingToPB;
62  import org.apache.hadoop.hbase.MetaTableAccessor;
63  import org.apache.hadoop.hbase.NamespaceDescriptor;
64  import org.apache.hadoop.hbase.NamespaceNotFoundException;
65  import org.apache.hadoop.hbase.PleaseHoldException;
66  import org.apache.hadoop.hbase.Server;
67  import org.apache.hadoop.hbase.ServerLoad;
68  import org.apache.hadoop.hbase.ServerName;
69  import org.apache.hadoop.hbase.TableDescriptors;
70  import org.apache.hadoop.hbase.TableName;
71  import org.apache.hadoop.hbase.TableNotDisabledException;
72  import org.apache.hadoop.hbase.TableNotFoundException;
73  import org.apache.hadoop.hbase.UnknownRegionException;
74  import org.apache.hadoop.hbase.classification.InterfaceAudience;
75  import org.apache.hadoop.hbase.client.MetaScanner;
76  import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitor;
77  import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitorBase;
78  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
79  import org.apache.hadoop.hbase.client.Result;
80  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
81  import org.apache.hadoop.hbase.exceptions.DeserializationException;
82  import org.apache.hadoop.hbase.executor.ExecutorType;
83  import org.apache.hadoop.hbase.ipc.RpcServer;
84  import org.apache.hadoop.hbase.ipc.ServerNotRunningYetException;
85  import org.apache.hadoop.hbase.master.MasterRpcServices.BalanceSwitchMode;
86  import org.apache.hadoop.hbase.master.RegionState.State;
87  import org.apache.hadoop.hbase.master.balancer.BalancerChore;
88  import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer;
89  import org.apache.hadoop.hbase.master.balancer.ClusterStatusChore;
90  import org.apache.hadoop.hbase.master.balancer.LoadBalancerFactory;
91  import org.apache.hadoop.hbase.master.cleaner.HFileCleaner;
92  import org.apache.hadoop.hbase.master.cleaner.LogCleaner;
93  import org.apache.hadoop.hbase.master.handler.CreateTableHandler;
94  import org.apache.hadoop.hbase.master.handler.DeleteTableHandler;
95  import org.apache.hadoop.hbase.master.handler.DisableTableHandler;
96  import org.apache.hadoop.hbase.master.handler.DispatchMergingRegionHandler;
97  import org.apache.hadoop.hbase.master.handler.EnableTableHandler;
98  import org.apache.hadoop.hbase.master.handler.ModifyTableHandler;
99  import org.apache.hadoop.hbase.master.handler.TableAddFamilyHandler;
100 import org.apache.hadoop.hbase.master.handler.TableDeleteFamilyHandler;
101 import org.apache.hadoop.hbase.master.handler.TableModifyFamilyHandler;
102 import org.apache.hadoop.hbase.master.handler.TruncateTableHandler;
103 import org.apache.hadoop.hbase.master.procedure.AddColumnFamilyProcedure;
104 import org.apache.hadoop.hbase.master.procedure.CreateTableProcedure;
105 import org.apache.hadoop.hbase.master.procedure.DeleteColumnFamilyProcedure;
106 import org.apache.hadoop.hbase.master.procedure.DeleteTableProcedure;
107 import org.apache.hadoop.hbase.master.procedure.DisableTableProcedure;
108 import org.apache.hadoop.hbase.master.procedure.EnableTableProcedure;
109 import org.apache.hadoop.hbase.master.procedure.MasterProcedureConstants;
110 import org.apache.hadoop.hbase.master.procedure.MasterProcedureEnv;
111 import org.apache.hadoop.hbase.master.procedure.ModifyColumnFamilyProcedure;
112 import org.apache.hadoop.hbase.master.procedure.ModifyTableProcedure;
113 import org.apache.hadoop.hbase.master.procedure.ProcedurePrepareLatch;
114 import org.apache.hadoop.hbase.master.procedure.ProcedureSyncWait;
115 import org.apache.hadoop.hbase.master.procedure.TruncateTableProcedure;
116 import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
117 import org.apache.hadoop.hbase.monitoring.MemoryBoundedLogMessageBuffer;
118 import org.apache.hadoop.hbase.monitoring.MonitoredTask;
119 import org.apache.hadoop.hbase.monitoring.TaskMonitor;
120 import org.apache.hadoop.hbase.procedure.MasterProcedureManagerHost;
121 import org.apache.hadoop.hbase.procedure.flush.MasterFlushTableProcedureManager;
122 import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
123 import org.apache.hadoop.hbase.procedure2.store.wal.WALProcedureStore;
124 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionServerInfo;
125 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
126 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
127 import org.apache.hadoop.hbase.quotas.MasterQuotaManager;
128 import org.apache.hadoop.hbase.quotas.RegionStateListener;
129 import org.apache.hadoop.hbase.regionserver.HRegionServer;
130 import org.apache.hadoop.hbase.regionserver.RSRpcServices;
131 import org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost;
132 import org.apache.hadoop.hbase.regionserver.RegionSplitPolicy;
133 import org.apache.hadoop.hbase.replication.regionserver.Replication;
134 import org.apache.hadoop.hbase.security.UserProvider;
135 import org.apache.hadoop.hbase.util.Addressing;
136 import org.apache.hadoop.hbase.util.Bytes;
137 import org.apache.hadoop.hbase.util.CompressionTest;
138 import org.apache.hadoop.hbase.util.ConfigUtil;
139 import org.apache.hadoop.hbase.util.EncryptionTest;
140 import org.apache.hadoop.hbase.util.FSUtils;
141 import org.apache.hadoop.hbase.util.HFileArchiveUtil;
142 import org.apache.hadoop.hbase.util.HasThread;
143 import org.apache.hadoop.hbase.util.ModifyRegionUtils;
144 import org.apache.hadoop.hbase.util.Pair;
145 import org.apache.hadoop.hbase.util.Threads;
146 import org.apache.hadoop.hbase.util.VersionInfo;
147 import org.apache.hadoop.hbase.zookeeper.DrainingServerTracker;
148 import org.apache.hadoop.hbase.zookeeper.LoadBalancerTracker;
149 import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker;
150 import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
151 import org.apache.hadoop.hbase.zookeeper.RegionServerTracker;
152 import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
153 import org.apache.hadoop.hbase.zookeeper.ZKUtil;
154 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
155 import org.apache.zookeeper.KeeperException;
156 import org.mortbay.jetty.Connector;
157 import org.mortbay.jetty.nio.SelectChannelConnector;
158 import org.mortbay.jetty.servlet.Context;
159 
160 import com.google.common.annotations.VisibleForTesting;
161 import com.google.common.collect.Maps;
162 import com.google.protobuf.Descriptors;
163 import com.google.protobuf.Service;
164 
165 /**
166  * HMaster is the "master server" for HBase. An HBase cluster has one active
167  * master.  If many masters are started, all compete.  Whichever wins goes on to
168  * run the cluster.  All others park themselves in their constructor until
169  * master or cluster shutdown or until the active master loses its lease in
170  * zookeeper.  Thereafter, all running master jostle to take over master role.
171  *
172  * <p>The Master can be asked shutdown the cluster. See {@link #shutdown()}.  In
173  * this case it will tell all regionservers to go down and then wait on them
174  * all reporting in that they are down.  This master will then shut itself down.
175  *
176  * <p>You can also shutdown just this master.  Call {@link #stopMaster()}.
177  *
178  * @see org.apache.zookeeper.Watcher
179  */
180 @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
181 @SuppressWarnings("deprecation")
182 public class HMaster extends HRegionServer implements MasterServices, Server {
183   private static final Log LOG = LogFactory.getLog(HMaster.class.getName());
184 
185   /**
186    * Protection against zombie master. Started once Master accepts active responsibility and
187    * starts taking over responsibilities. Allows a finite time window before giving up ownership.
188    */
189   private static class InitializationMonitor extends HasThread {
190     /** The amount of time in milliseconds to sleep before checking initialization status. */
191     public static final String TIMEOUT_KEY = "hbase.master.initializationmonitor.timeout";
192     public static final long TIMEOUT_DEFAULT = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
193 
194     /**
195      * When timeout expired and initialization has not complete, call {@link System#exit(int)} when
196      * true, do nothing otherwise.
197      */
198     public static final String HALT_KEY = "hbase.master.initializationmonitor.haltontimeout";
199     public static final boolean HALT_DEFAULT = false;
200 
201     private final HMaster master;
202     private final long timeout;
203     private final boolean haltOnTimeout;
204 
205     /** Creates a Thread that monitors the {@link #isInitialized()} state. */
206     InitializationMonitor(HMaster master) {
207       super("MasterInitializationMonitor");
208       this.master = master;
209       this.timeout = master.getConfiguration().getLong(TIMEOUT_KEY, TIMEOUT_DEFAULT);
210       this.haltOnTimeout = master.getConfiguration().getBoolean(HALT_KEY, HALT_DEFAULT);
211       this.setDaemon(true);
212     }
213 
214     @Override
215     public void run() {
216       try {
217         while (!master.isStopped() && master.isActiveMaster()) {
218           Thread.sleep(timeout);
219           if (master.isInitialized()) {
220             LOG.debug("Initialization completed within allotted tolerance. Monitor exiting.");
221           } else {
222             LOG.error("Master failed to complete initialization after " + timeout + "ms. Please"
223                 + " consider submitting a bug report including a thread dump of this process.");
224             if (haltOnTimeout) {
225               LOG.error("Zombie Master exiting. Thread dump to stdout");
226               Threads.printThreadInfo(System.out, "Zombie HMaster");
227               System.exit(-1);
228             }
229           }
230         }
231       } catch (InterruptedException ie) {
232         LOG.trace("InitMonitor thread interrupted. Existing.");
233       }
234     }
235   }
236 
237   // MASTER is name of the webapp and the attribute name used stuffing this
238   //instance into web context.
239   public static final String MASTER = "master";
240 
241   // Manager and zk listener for master election
242   private final ActiveMasterManager activeMasterManager;
243   // Region server tracker
244   RegionServerTracker regionServerTracker;
245   // Draining region server tracker
246   private DrainingServerTracker drainingServerTracker;
247   // Tracker for load balancer state
248   LoadBalancerTracker loadBalancerTracker;
249 
250   /** Namespace stuff */
251   private TableNamespaceManager tableNamespaceManager;
252 
253   // Metrics for the HMaster
254   final MetricsMaster metricsMaster;
255   // file system manager for the master FS operations
256   private MasterFileSystem fileSystemManager;
257 
258   // server manager to deal with region server info
259   volatile ServerManager serverManager;
260 
261   // manager of assignment nodes in zookeeper
262   AssignmentManager assignmentManager;
263 
264   // buffer for "fatal error" notices from region servers
265   // in the cluster. This is only used for assisting
266   // operations/debugging.
267   MemoryBoundedLogMessageBuffer rsFatals;
268 
269   // flag set after we become the active master (used for testing)
270   private volatile boolean isActiveMaster = false;
271 
272   // flag set after we complete initialization once active,
273   // it is not private since it's used in unit tests
274   volatile boolean initialized = false;
275 
276   // flag set after master services are started,
277   // initialization may have not completed yet.
278   volatile boolean serviceStarted = false;
279 
280   // flag set after we complete assignMeta.
281   private volatile boolean serverShutdownHandlerEnabled = false;
282 
283   LoadBalancer balancer;
284   private BalancerChore balancerChore;
285   private ClusterStatusChore clusterStatusChore;
286   private ClusterStatusPublisher clusterStatusPublisherChore = null;
287 
288   CatalogJanitor catalogJanitorChore;
289   private LogCleaner logCleaner;
290   private HFileCleaner hfileCleaner;
291 
292   MasterCoprocessorHost cpHost;
293 
294   private final boolean preLoadTableDescriptors;
295 
296   // Time stamps for when a hmaster became active
297   private long masterActiveTime;
298 
299   //should we check the compression codec type at master side, default true, HBASE-6370
300   private final boolean masterCheckCompression;
301 
302   //should we check encryption settings at master side, default true
303   private final boolean masterCheckEncryption;
304 
305   // This is for fallback to use the code from 1.0 release.
306   private enum ProcedureConf {
307     PROCEDURE_ENABLED, // default
308     HANDLER_USED, // handler code executed in DDL, procedure executor still start
309     PROCEDURE_FULLY_DISABLED, // procedure fully disabled
310   }
311   private final ProcedureConf procedureConf;
312 
313   Map<String, Service> coprocessorServiceHandlers = Maps.newHashMap();
314 
315   // monitor for snapshot of hbase tables
316   SnapshotManager snapshotManager;
317   // monitor for distributed procedures
318   MasterProcedureManagerHost mpmHost;
319   
320   // it is assigned after 'initialized' guard set to true, so should be volatile
321   private volatile MasterQuotaManager quotaManager;
322 
323   private ProcedureExecutor<MasterProcedureEnv> procedureExecutor;
324   private WALProcedureStore procedureStore;
325 
326   /** flag used in test cases in order to simulate RS failures during master initialization */
327   private volatile boolean initializationBeforeMetaAssignment = false;
328 
329   /** jetty server for master to redirect requests to regionserver infoServer */
330   private org.mortbay.jetty.Server masterJettyServer;
331 
332   public static class RedirectServlet extends HttpServlet {
333     private static final long serialVersionUID = 2894774810058302472L;
334     private static int regionServerInfoPort;
335 
336     @Override
337     public void doGet(HttpServletRequest request,
338         HttpServletResponse response) throws ServletException, IOException {
339       String redirectUrl = request.getScheme() + "://"
340         + request.getServerName() + ":" + regionServerInfoPort
341         + request.getRequestURI();
342       response.sendRedirect(redirectUrl);
343     }
344   }
345 
346   /**
347    * Initializes the HMaster. The steps are as follows:
348    * <p>
349    * <ol>
350    * <li>Initialize the local HRegionServer
351    * <li>Start the ActiveMasterManager.
352    * </ol>
353    * <p>
354    * Remaining steps of initialization occur in
355    * #finishActiveMasterInitialization(MonitoredTask) after
356    * the master becomes the active one.
357    *
358    * @throws InterruptedException
359    * @throws KeeperException
360    * @throws IOException
361    */
362   public HMaster(final Configuration conf, CoordinatedStateManager csm)
363       throws IOException, KeeperException, InterruptedException {
364     super(conf, csm);
365     this.rsFatals = new MemoryBoundedLogMessageBuffer(
366       conf.getLong("hbase.master.buffer.for.rs.fatals", 1*1024*1024));
367 
368     LOG.info("hbase.rootdir=" + FSUtils.getRootDir(this.conf) +
369         ", hbase.cluster.distributed=" + this.conf.getBoolean(HConstants.CLUSTER_DISTRIBUTED, false));
370 
371     // Disable usage of meta replicas in the master
372     this.conf.setBoolean(HConstants.USE_META_REPLICAS, false);
373 
374     Replication.decorateMasterConfiguration(this.conf);
375 
376     // Hack! Maps DFSClient => Master for logs.  HDFS made this
377     // config param for task trackers, but we can piggyback off of it.
378     if (this.conf.get("mapreduce.task.attempt.id") == null) {
379       this.conf.set("mapreduce.task.attempt.id", "hb_m_" + this.serverName.toString());
380     }
381 
382     // should we check the compression codec type at master side, default true, HBASE-6370
383     this.masterCheckCompression = conf.getBoolean("hbase.master.check.compression", true);
384 
385     // should we check encryption settings at master side, default true
386     this.masterCheckEncryption = conf.getBoolean("hbase.master.check.encryption", true);
387 
388     this.metricsMaster = new MetricsMaster( new MetricsMasterWrapperImpl(this));
389 
390     // Check configuration to see whether procedure is disabled (not execute at all),
391     // unused (not used to execute DDL, but executor starts to complete unfinished operations
392     // in procedure store, or enabled (default behavior).
393     String procedureConfString = conf.get("hbase.master.procedure.tableddl", "enabled");
394     if (procedureConfString.equalsIgnoreCase("disabled")) {
395       LOG.info("Master will use handler for new table DDL"
396         + " and all unfinished table DDLs in procedure store will be disgarded.");
397       this.procedureConf = ProcedureConf.PROCEDURE_FULLY_DISABLED;
398     } else if (procedureConfString.equalsIgnoreCase("unused")) {
399       LOG.info("Master will use handler for new table DDL"
400         + " and all unfinished table DDLs in procedure store will continue to execute.");
401       this.procedureConf = ProcedureConf.HANDLER_USED;
402     } else {
403       this.procedureConf = ProcedureConf.PROCEDURE_ENABLED;
404     }
405     // preload table descriptor at startup
406     this.preLoadTableDescriptors = conf.getBoolean("hbase.master.preload.tabledescriptors", true);
407 
408     // Do we publish the status?
409 
410     boolean shouldPublish = conf.getBoolean(HConstants.STATUS_PUBLISHED,
411         HConstants.STATUS_PUBLISHED_DEFAULT);
412     Class<? extends ClusterStatusPublisher.Publisher> publisherClass =
413         conf.getClass(ClusterStatusPublisher.STATUS_PUBLISHER_CLASS,
414             ClusterStatusPublisher.DEFAULT_STATUS_PUBLISHER_CLASS,
415             ClusterStatusPublisher.Publisher.class);
416 
417     if (shouldPublish) {
418       if (publisherClass == null) {
419         LOG.warn(HConstants.STATUS_PUBLISHED + " is true, but " +
420             ClusterStatusPublisher.DEFAULT_STATUS_PUBLISHER_CLASS +
421             " is not set - not publishing status");
422       } else {
423         clusterStatusPublisherChore = new ClusterStatusPublisher(this, conf, publisherClass);
424         getChoreService().scheduleChore(clusterStatusPublisherChore);
425       }
426     }
427 
428     // Some unit tests don't need a cluster, so no zookeeper at all
429     if (!conf.getBoolean("hbase.testing.nocluster", false)) {
430       activeMasterManager = new ActiveMasterManager(zooKeeper, this.serverName, this);
431       int infoPort = putUpJettyServer();
432       startActiveMasterManager(infoPort);
433     } else {
434       activeMasterManager = null;
435     }
436   }
437 
438   // return the actual infoPort, -1 means disable info server.
439   private int putUpJettyServer() throws IOException {
440     if (!conf.getBoolean("hbase.master.infoserver.redirect", true)) {
441       return -1;
442     }
443     int infoPort = conf.getInt("hbase.master.info.port.orig",
444       HConstants.DEFAULT_MASTER_INFOPORT);
445     // -1 is for disabling info server, so no redirecting
446     if (infoPort < 0 || infoServer == null) {
447       return -1;
448     }
449     String addr = conf.get("hbase.master.info.bindAddress", "0.0.0.0");
450     if (!Addressing.isLocalAddress(InetAddress.getByName(addr))) {
451       String msg =
452           "Failed to start redirecting jetty server. Address " + addr
453               + " does not belong to this host. Correct configuration parameter: "
454               + "hbase.master.info.bindAddress";
455       LOG.error(msg);
456       throw new IOException(msg);
457     }
458 
459     RedirectServlet.regionServerInfoPort = infoServer.getPort();
460     if(RedirectServlet.regionServerInfoPort == infoPort) {
461       return infoPort;
462     }
463     masterJettyServer = new org.mortbay.jetty.Server();
464     Connector connector = new SelectChannelConnector();
465     connector.setHost(addr);
466     connector.setPort(infoPort);
467     masterJettyServer.addConnector(connector);
468     masterJettyServer.setStopAtShutdown(true);
469     Context context = new Context(masterJettyServer, "/", Context.NO_SESSIONS);
470     context.addServlet(RedirectServlet.class, "/*");
471     try {
472       masterJettyServer.start();
473     } catch (Exception e) {
474       throw new IOException("Failed to start redirecting jetty server", e);
475     }
476     return connector.getLocalPort();
477   }
478 
479   /**
480    * For compatibility, if failed with regionserver credentials, try the master one
481    */
482   @Override
483   protected void login(UserProvider user, String host) throws IOException {
484     try {
485       super.login(user, host);
486     } catch (IOException ie) {
487       user.login("hbase.master.keytab.file",
488         "hbase.master.kerberos.principal", host);
489     }
490   }
491 
492   /**
493    * If configured to put regions on active master,
494    * wait till a backup master becomes active.
495    * Otherwise, loop till the server is stopped or aborted.
496    */
497   @Override
498   protected void waitForMasterActive(){
499     boolean tablesOnMaster = BaseLoadBalancer.tablesOnMaster(conf);
500     while (!(tablesOnMaster && isActiveMaster)
501         && !isStopped() && !isAborted()) {
502       sleeper.sleep();
503     }
504   }
505 
506   @VisibleForTesting
507   public MasterRpcServices getMasterRpcServices() {
508     return (MasterRpcServices)rpcServices;
509   }
510 
511   public boolean balanceSwitch(final boolean b) throws IOException {
512     return getMasterRpcServices().switchBalancer(b, BalanceSwitchMode.ASYNC);
513   }
514 
515   @Override
516   protected String getProcessName() {
517     return MASTER;
518   }
519 
520   @Override
521   protected boolean canCreateBaseZNode() {
522     return true;
523   }
524 
525   @Override
526   protected boolean canUpdateTableDescriptor() {
527     return true;
528   }
529 
530   @Override
531   protected RSRpcServices createRpcServices() throws IOException {
532     return new MasterRpcServices(this);
533   }
534 
535   @Override
536   protected void configureInfoServer() {
537     infoServer.addServlet("master-status", "/master-status", MasterStatusServlet.class);
538     infoServer.setAttribute(MASTER, this);
539     if (BaseLoadBalancer.tablesOnMaster(conf)) {
540       super.configureInfoServer();
541     }
542   }
543 
544   @Override
545   protected Class<? extends HttpServlet> getDumpServlet() {
546     return MasterDumpServlet.class;
547   }
548 
549   /**
550    * Emit the HMaster metrics, such as region in transition metrics.
551    * Surrounding in a try block just to be sure metrics doesn't abort HMaster.
552    */
553   @Override
554   protected void doMetrics() {
555     try {
556       if (assignmentManager != null) {
557         assignmentManager.updateRegionsInTransitionMetrics();
558       }
559     } catch (Throwable e) {
560       LOG.error("Couldn't update metrics: " + e.getMessage());
561     }
562   }
563 
564   MetricsMaster getMasterMetrics() {
565     return metricsMaster;
566   }
567 
568   /**
569    * Initialize all ZK based system trackers.
570    * @throws IOException
571    * @throws InterruptedException
572    * @throws KeeperException
573    * @throws CoordinatedStateException
574    */
575   void initializeZKBasedSystemTrackers() throws IOException,
576       InterruptedException, KeeperException, CoordinatedStateException {
577     this.balancer = LoadBalancerFactory.getLoadBalancer(conf);
578     this.loadBalancerTracker = new LoadBalancerTracker(zooKeeper, this);
579     this.loadBalancerTracker.start();
580     this.assignmentManager = new AssignmentManager(this, serverManager,
581       this.balancer, this.service, this.metricsMaster,
582       this.tableLockManager);
583     zooKeeper.registerListenerFirst(assignmentManager);
584 
585     this.regionServerTracker = new RegionServerTracker(zooKeeper, this,
586         this.serverManager);
587     this.regionServerTracker.start();
588 
589     this.drainingServerTracker = new DrainingServerTracker(zooKeeper, this,
590       this.serverManager);
591     this.drainingServerTracker.start();
592 
593     // Set the cluster as up.  If new RSs, they'll be waiting on this before
594     // going ahead with their startup.
595     boolean wasUp = this.clusterStatusTracker.isClusterUp();
596     if (!wasUp) this.clusterStatusTracker.setClusterUp();
597 
598     LOG.info("Server active/primary master=" + this.serverName +
599         ", sessionid=0x" +
600         Long.toHexString(this.zooKeeper.getRecoverableZooKeeper().getSessionId()) +
601         ", setting cluster-up flag (Was=" + wasUp + ")");
602 
603     // create/initialize the snapshot manager and other procedure managers
604     this.snapshotManager = new SnapshotManager();
605     this.mpmHost = new MasterProcedureManagerHost();
606     this.mpmHost.register(this.snapshotManager);
607     this.mpmHost.register(new MasterFlushTableProcedureManager());
608     this.mpmHost.loadProcedures(conf);
609     this.mpmHost.initialize(this, this.metricsMaster);
610   }
611 
612   /**
613    * Finish initialization of HMaster after becoming the primary master.
614    *
615    * <ol>
616    * <li>Initialize master components - file system manager, server manager,
617    *     assignment manager, region server tracker, etc</li>
618    * <li>Start necessary service threads - balancer, catalog janior,
619    *     executor services, etc</li>
620    * <li>Set cluster as UP in ZooKeeper</li>
621    * <li>Wait for RegionServers to check-in</li>
622    * <li>Split logs and perform data recovery, if necessary</li>
623    * <li>Ensure assignment of meta/namespace regions<li>
624    * <li>Handle either fresh cluster start or master failover</li>
625    * </ol>
626    *
627    * @throws IOException
628    * @throws InterruptedException
629    * @throws KeeperException
630    * @throws CoordinatedStateException
631    */
632   private void finishActiveMasterInitialization(MonitoredTask status)
633       throws IOException, InterruptedException, KeeperException, CoordinatedStateException {
634 
635     isActiveMaster = true;
636     Thread zombieDetector = new Thread(new InitializationMonitor(this));
637     zombieDetector.start();
638 
639     /*
640      * We are active master now... go initialize components we need to run.
641      * Note, there may be dross in zk from previous runs; it'll get addressed
642      * below after we determine if cluster startup or failover.
643      */
644 
645     status.setStatus("Initializing Master file system");
646 
647     this.masterActiveTime = System.currentTimeMillis();
648     // TODO: Do this using Dependency Injection, using PicoContainer, Guice or Spring.
649     this.fileSystemManager = new MasterFileSystem(this, this);
650 
651     // enable table descriptors cache
652     this.tableDescriptors.setCacheOn();
653     // set the META's descriptor to the correct replication
654     this.tableDescriptors.get(TableName.META_TABLE_NAME).setRegionReplication(
655         conf.getInt(HConstants.META_REPLICAS_NUM, HConstants.DEFAULT_META_REPLICA_NUM));
656     // warm-up HTDs cache on master initialization
657     if (preLoadTableDescriptors) {
658       status.setStatus("Pre-loading table descriptors");
659       this.tableDescriptors.getAll();
660     }
661 
662     // publish cluster ID
663     status.setStatus("Publishing Cluster ID in ZooKeeper");
664     ZKClusterId.setClusterId(this.zooKeeper, fileSystemManager.getClusterId());
665     this.serverManager = createServerManager(this, this);
666 
667     setupClusterConnection();
668 
669     // Invalidate all write locks held previously
670     this.tableLockManager.reapWriteLocks();
671 
672     status.setStatus("Initializing ZK system trackers");
673     initializeZKBasedSystemTrackers();
674 
675     // initialize master side coprocessors before we start handling requests
676     status.setStatus("Initializing master coprocessors");
677     this.cpHost = new MasterCoprocessorHost(this, this.conf);
678 
679     // start up all service threads.
680     status.setStatus("Initializing master service threads");
681     startServiceThreads();
682 
683     // Wake up this server to check in
684     sleeper.skipSleepCycle();
685 
686     // Wait for region servers to report in
687     this.serverManager.waitForRegionServers(status);
688     // Check zk for region servers that are up but didn't register
689     for (ServerName sn: this.regionServerTracker.getOnlineServers()) {
690       // The isServerOnline check is opportunistic, correctness is handled inside
691       if (!this.serverManager.isServerOnline(sn)
692           && serverManager.checkAndRecordNewServer(sn, ServerLoad.EMPTY_SERVERLOAD)) {
693         LOG.info("Registered server found up in zk but who has not yet reported in: " + sn);
694       }
695     }
696 
697     // get a list for previously failed RS which need log splitting work
698     // we recover hbase:meta region servers inside master initialization and
699     // handle other failed servers in SSH in order to start up master node ASAP
700     Set<ServerName> previouslyFailedServers = this.fileSystemManager
701         .getFailedServersFromLogFolders();
702 
703     // remove stale recovering regions from previous run
704     this.fileSystemManager.removeStaleRecoveringRegionsFromZK(previouslyFailedServers);
705 
706     // log splitting for hbase:meta server
707     ServerName oldMetaServerLocation = metaTableLocator.getMetaRegionLocation(this.getZooKeeper());
708     if (oldMetaServerLocation != null && previouslyFailedServers.contains(oldMetaServerLocation)) {
709       splitMetaLogBeforeAssignment(oldMetaServerLocation);
710       // Note: we can't remove oldMetaServerLocation from previousFailedServers list because it
711       // may also host user regions
712     }
713     Set<ServerName> previouslyFailedMetaRSs = getPreviouselyFailedMetaServersFromZK();
714     // need to use union of previouslyFailedMetaRSs recorded in ZK and previouslyFailedServers
715     // instead of previouslyFailedMetaRSs alone to address the following two situations:
716     // 1) the chained failure situation(recovery failed multiple times in a row).
717     // 2) master get killed right before it could delete the recovering hbase:meta from ZK while the
718     // same server still has non-meta wals to be replayed so that
719     // removeStaleRecoveringRegionsFromZK can't delete the stale hbase:meta region
720     // Passing more servers into splitMetaLog is all right. If a server doesn't have hbase:meta wal,
721     // there is no op for the server.
722     previouslyFailedMetaRSs.addAll(previouslyFailedServers);
723 
724     this.initializationBeforeMetaAssignment = true;
725 
726     // Wait for regionserver to finish initialization.
727     if (BaseLoadBalancer.tablesOnMaster(conf)) {
728       waitForServerOnline();
729     }
730 
731     //initialize load balancer
732     this.balancer.setClusterStatus(getClusterStatus());
733     this.balancer.setMasterServices(this);
734     this.balancer.initialize();
735 
736     // Check if master is shutting down because of some issue
737     // in initializing the regionserver or the balancer.
738     if(isStopped()) return;
739 
740     // Make sure meta assigned before proceeding.
741     status.setStatus("Assigning Meta Region");
742     assignMeta(status, previouslyFailedMetaRSs, HRegionInfo.DEFAULT_REPLICA_ID);
743     // check if master is shutting down because above assignMeta could return even hbase:meta isn't
744     // assigned when master is shutting down
745     if(isStopped()) return;
746 
747     status.setStatus("Submitting log splitting work for previously failed region servers");
748     // Master has recovered hbase:meta region server and we put
749     // other failed region servers in a queue to be handled later by SSH
750     for (ServerName tmpServer : previouslyFailedServers) {
751       this.serverManager.processDeadServer(tmpServer, true);
752     }
753 
754     // Update meta with new PB serialization if required. i.e migrate all HRI to PB serialization
755     // in meta. This must happen before we assign all user regions or else the assignment will
756     // fail.
757     if (this.conf.getBoolean("hbase.MetaMigrationConvertingToPB", true)) {
758       MetaMigrationConvertingToPB.updateMetaIfNecessary(this);
759     }
760 
761     // Fix up assignment manager status
762     status.setStatus("Starting assignment manager");
763     this.assignmentManager.joinCluster();
764 
765     //set cluster status again after user regions are assigned
766     this.balancer.setClusterStatus(getClusterStatus());
767 
768     // Start balancer and meta catalog janitor after meta and regions have
769     // been assigned.
770     status.setStatus("Starting balancer and catalog janitor");
771     this.clusterStatusChore = new ClusterStatusChore(this, balancer);
772     getChoreService().scheduleChore(clusterStatusChore);
773     this.balancerChore = new BalancerChore(this);
774     getChoreService().scheduleChore(balancerChore);
775     this.catalogJanitorChore = new CatalogJanitor(this, this);
776     getChoreService().scheduleChore(catalogJanitorChore);
777 
778     status.setStatus("Starting namespace manager");
779     initNamespace();
780     
781     if (this.cpHost != null) {
782       try {
783         this.cpHost.preMasterInitialization();
784       } catch (IOException e) {
785         LOG.error("Coprocessor preMasterInitialization() hook failed", e);
786       }
787     }
788 
789     status.markComplete("Initialization successful");
790     LOG.info("Master has completed initialization");
791     configurationManager.registerObserver(this.balancer);
792     initialized = true;
793     
794     status.setStatus("Starting quota manager");
795     initQuotaManager();
796 
797     // assign the meta replicas
798     Set<ServerName> EMPTY_SET = new HashSet<ServerName>();
799     int numReplicas = conf.getInt(HConstants.META_REPLICAS_NUM,
800            HConstants.DEFAULT_META_REPLICA_NUM);
801     for (int i = 1; i < numReplicas; i++) {
802       assignMeta(status, EMPTY_SET, i);
803     }
804     unassignExcessMetaReplica(zooKeeper, numReplicas);
805 
806     // clear the dead servers with same host name and port of online server because we are not
807     // removing dead server with same hostname and port of rs which is trying to check in before
808     // master initialization. See HBASE-5916.
809     this.serverManager.clearDeadServersWithSameHostNameAndPortOfOnlineServer();
810 
811     if (this.cpHost != null) {
812       // don't let cp initialization errors kill the master
813       try {
814         this.cpHost.postStartMaster();
815       } catch (IOException ioe) {
816         LOG.error("Coprocessor postStartMaster() hook failed", ioe);
817       }
818     }
819 
820     zombieDetector.interrupt();
821   }
822 
823   private void initQuotaManager() throws IOException {
824     quotaManager = new MasterQuotaManager(this);
825     this.assignmentManager.setRegionStateListener((RegionStateListener) quotaManager);
826     quotaManager.start();
827   }
828 
829   /**
830    * Create a {@link ServerManager} instance.
831    * @param master
832    * @param services
833    * @return An instance of {@link ServerManager}
834    * @throws org.apache.hadoop.hbase.ZooKeeperConnectionException
835    * @throws IOException
836    */
837   ServerManager createServerManager(final Server master,
838       final MasterServices services)
839   throws IOException {
840     // We put this out here in a method so can do a Mockito.spy and stub it out
841     // w/ a mocked up ServerManager.
842     return new ServerManager(master, services);
843   }
844 
845   private void unassignExcessMetaReplica(ZooKeeperWatcher zkw, int numMetaReplicasConfigured) {
846     // unassign the unneeded replicas (for e.g., if the previous master was configured
847     // with a replication of 3 and now it is 2, we need to unassign the 1 unneeded replica)
848     try {
849       List<String> metaReplicaZnodes = zooKeeper.getMetaReplicaNodes();
850       for (String metaReplicaZnode : metaReplicaZnodes) {
851         int replicaId = zooKeeper.getMetaReplicaIdFromZnode(metaReplicaZnode);
852         if (replicaId >= numMetaReplicasConfigured) {
853           RegionState r = MetaTableLocator.getMetaRegionState(zkw, replicaId);
854           LOG.info("Closing excess replica of meta region " + r.getRegion());
855           // send a close and wait for a max of 30 seconds
856           ServerManager.closeRegionSilentlyAndWait(getConnection(), r.getServerName(),
857               r.getRegion(), 30000);
858           ZKUtil.deleteNode(zkw, zkw.getZNodeForReplica(replicaId));
859         }
860       }
861     } catch (Exception ex) {
862       // ignore the exception since we don't want the master to be wedged due to potential
863       // issues in the cleanup of the extra regions. We can do that cleanup via hbck or manually
864       LOG.warn("Ignoring exception " + ex);
865     }
866   }
867 
868   /**
869    * Check <code>hbase:meta</code> is assigned. If not, assign it.
870    * @param status MonitoredTask
871    * @param previouslyFailedMetaRSs
872    * @param replicaId
873    * @throws InterruptedException
874    * @throws IOException
875    * @throws KeeperException
876    */
877   void assignMeta(MonitoredTask status, Set<ServerName> previouslyFailedMetaRSs, int replicaId)
878       throws InterruptedException, IOException, KeeperException {
879     // Work on meta region
880     int assigned = 0;
881     long timeout = this.conf.getLong("hbase.catalog.verification.timeout", 1000);
882     if (replicaId == HRegionInfo.DEFAULT_REPLICA_ID) {
883       status.setStatus("Assigning hbase:meta region");
884     } else {
885       status.setStatus("Assigning hbase:meta region, replicaId " + replicaId);
886     }
887     // Get current meta state from zk.
888     RegionStates regionStates = assignmentManager.getRegionStates();
889     RegionState metaState = MetaTableLocator.getMetaRegionState(getZooKeeper(), replicaId);
890     HRegionInfo hri = RegionReplicaUtil.getRegionInfoForReplica(HRegionInfo.FIRST_META_REGIONINFO,
891         replicaId);
892     ServerName currentMetaServer = metaState.getServerName();
893     if (!ConfigUtil.useZKForAssignment(conf)) {
894       regionStates.createRegionState(hri, metaState.getState(),
895         currentMetaServer, null);
896     } else {
897       regionStates.createRegionState(hri);
898     }
899     boolean rit = this.assignmentManager.
900       processRegionInTransitionAndBlockUntilAssigned(hri);
901     boolean metaRegionLocation = metaTableLocator.verifyMetaRegionLocation(
902       this.getConnection(), this.getZooKeeper(), timeout, replicaId);
903     if (!metaRegionLocation || !metaState.isOpened()) {
904       // Meta location is not verified. It should be in transition, or offline.
905       // We will wait for it to be assigned in enableSSHandWaitForMeta below.
906       assigned++;
907       if (!ConfigUtil.useZKForAssignment(conf)) {
908         assignMetaZkLess(regionStates, metaState, timeout, previouslyFailedMetaRSs);
909       } else if (!rit) {
910         // Assign meta since not already in transition
911         if (currentMetaServer != null) {
912           // If the meta server is not known to be dead or online,
913           // just split the meta log, and don't expire it since this
914           // could be a full cluster restart. Otherwise, we will think
915           // this is a failover and lose previous region locations.
916           // If it is really a failover case, AM will find out in rebuilding
917           // user regions. Otherwise, we are good since all logs are split
918           // or known to be replayed before user regions are assigned.
919           if (serverManager.isServerOnline(currentMetaServer)) {
920             LOG.info("Forcing expire of " + currentMetaServer);
921             serverManager.expireServer(currentMetaServer);
922           }
923           if (replicaId == HRegionInfo.DEFAULT_REPLICA_ID) {
924             splitMetaLogBeforeAssignment(currentMetaServer);
925             previouslyFailedMetaRSs.add(currentMetaServer);
926           }
927         }
928         assignmentManager.assignMeta(hri);
929       }
930     } else {
931       // Region already assigned. We didn't assign it. Add to in-memory state.
932       regionStates.updateRegionState(
933         HRegionInfo.FIRST_META_REGIONINFO, State.OPEN, currentMetaServer);
934       this.assignmentManager.regionOnline(
935         HRegionInfo.FIRST_META_REGIONINFO, currentMetaServer);
936     }
937 
938     if (replicaId == HRegionInfo.DEFAULT_REPLICA_ID) enableMeta(TableName.META_TABLE_NAME);
939 
940     if ((RecoveryMode.LOG_REPLAY == this.getMasterFileSystem().getLogRecoveryMode())
941         && (!previouslyFailedMetaRSs.isEmpty())) {
942       // replay WAL edits mode need new hbase:meta RS is assigned firstly
943       status.setStatus("replaying log for Meta Region");
944       this.fileSystemManager.splitMetaLog(previouslyFailedMetaRSs);
945     }
946 
947     // Make sure a hbase:meta location is set. We need to enable SSH here since
948     // if the meta region server is died at this time, we need it to be re-assigned
949     // by SSH so that system tables can be assigned.
950     // No need to wait for meta is assigned = 0 when meta is just verified.
951     if (replicaId == HRegionInfo.DEFAULT_REPLICA_ID) enableServerShutdownHandler(assigned != 0);
952     LOG.info("hbase:meta with replicaId " + replicaId + " assigned=" + assigned + ", rit=" + rit +
953       ", location=" + metaTableLocator.getMetaRegionLocation(this.getZooKeeper(), replicaId));
954     status.setStatus("META assigned.");
955   }
956 
957   private void assignMetaZkLess(RegionStates regionStates, RegionState regionState, long timeout,
958       Set<ServerName> previouslyFailedRs) throws IOException, KeeperException {
959     ServerName currentServer = regionState.getServerName();
960     if (serverManager.isServerOnline(currentServer)) {
961       LOG.info("Meta was in transition on " + currentServer);
962       assignmentManager.processRegionInTransitionZkLess();
963     } else {
964       if (currentServer != null) {
965         if (regionState.getRegion().getReplicaId() == HRegionInfo.DEFAULT_REPLICA_ID) {
966           splitMetaLogBeforeAssignment(currentServer);
967           regionStates.logSplit(HRegionInfo.FIRST_META_REGIONINFO);
968           previouslyFailedRs.add(currentServer);
969         }
970       }
971       LOG.info("Re-assigning hbase:meta, it was on " + currentServer);
972       regionStates.updateRegionState(regionState.getRegion(), State.OFFLINE);
973       assignmentManager.assignMeta(regionState.getRegion());
974     }
975   }
976 
977   void initNamespace() throws IOException {
978     //create namespace manager
979     tableNamespaceManager = new TableNamespaceManager(this);
980     tableNamespaceManager.start();
981   }
982 
983   boolean isCatalogJanitorEnabled() {
984     return catalogJanitorChore != null ?
985       catalogJanitorChore.getEnabled() : false;
986   }
987 
988   private void splitMetaLogBeforeAssignment(ServerName currentMetaServer) throws IOException {
989     if (RecoveryMode.LOG_REPLAY == this.getMasterFileSystem().getLogRecoveryMode()) {
990       // In log replay mode, we mark hbase:meta region as recovering in ZK
991       Set<HRegionInfo> regions = new HashSet<HRegionInfo>();
992       regions.add(HRegionInfo.FIRST_META_REGIONINFO);
993       this.fileSystemManager.prepareLogReplay(currentMetaServer, regions);
994     } else {
995       // In recovered.edits mode: create recovered edits file for hbase:meta server
996       this.fileSystemManager.splitMetaLog(currentMetaServer);
997     }
998   }
999 
1000   private void enableServerShutdownHandler(
1001       final boolean waitForMeta) throws IOException, InterruptedException {
1002     // If ServerShutdownHandler is disabled, we enable it and expire those dead
1003     // but not expired servers. This is required so that if meta is assigning to
1004     // a server which dies after assignMeta starts assignment,
1005     // SSH can re-assign it. Otherwise, we will be
1006     // stuck here waiting forever if waitForMeta is specified.
1007     if (!serverShutdownHandlerEnabled) {
1008       serverShutdownHandlerEnabled = true;
1009       this.serverManager.processQueuedDeadServers();
1010     }
1011 
1012     if (waitForMeta) {
1013       metaTableLocator.waitMetaRegionLocation(this.getZooKeeper());
1014       // Above check waits for general meta availability but this does not
1015       // guarantee that the transition has completed
1016       this.assignmentManager.waitForAssignment(HRegionInfo.FIRST_META_REGIONINFO);
1017     }
1018   }
1019 
1020   private void enableMeta(TableName metaTableName) {
1021     if (!this.assignmentManager.getTableStateManager().isTableState(metaTableName,
1022         ZooKeeperProtos.Table.State.ENABLED)) {
1023       this.assignmentManager.setEnabledTable(metaTableName);
1024     }
1025   }
1026 
1027   /**
1028    * This function returns a set of region server names under hbase:meta recovering region ZK node
1029    * @return Set of meta server names which were recorded in ZK
1030    * @throws KeeperException
1031    */
1032   private Set<ServerName> getPreviouselyFailedMetaServersFromZK() throws KeeperException {
1033     Set<ServerName> result = new HashSet<ServerName>();
1034     String metaRecoveringZNode = ZKUtil.joinZNode(zooKeeper.recoveringRegionsZNode,
1035       HRegionInfo.FIRST_META_REGIONINFO.getEncodedName());
1036     List<String> regionFailedServers = ZKUtil.listChildrenNoWatch(zooKeeper, metaRecoveringZNode);
1037     if (regionFailedServers == null) return result;
1038 
1039     for(String failedServer : regionFailedServers) {
1040       ServerName server = ServerName.parseServerName(failedServer);
1041       result.add(server);
1042     }
1043     return result;
1044   }
1045 
1046   @Override
1047   public TableDescriptors getTableDescriptors() {
1048     return this.tableDescriptors;
1049   }
1050 
1051   @Override
1052   public ServerManager getServerManager() {
1053     return this.serverManager;
1054   }
1055 
1056   @Override
1057   public MasterFileSystem getMasterFileSystem() {
1058     return this.fileSystemManager;
1059   }
1060 
1061   /*
1062    * Start up all services. If any of these threads gets an unhandled exception
1063    * then they just die with a logged message.  This should be fine because
1064    * in general, we do not expect the master to get such unhandled exceptions
1065    *  as OOMEs; it should be lightly loaded. See what HRegionServer does if
1066    *  need to install an unexpected exception handler.
1067    */
1068   private void startServiceThreads() throws IOException{
1069    // Start the executor service pools
1070    this.service.startExecutorService(ExecutorType.MASTER_OPEN_REGION,
1071       conf.getInt("hbase.master.executor.openregion.threads", 5));
1072    this.service.startExecutorService(ExecutorType.MASTER_CLOSE_REGION,
1073       conf.getInt("hbase.master.executor.closeregion.threads", 5));
1074    this.service.startExecutorService(ExecutorType.MASTER_SERVER_OPERATIONS,
1075       conf.getInt("hbase.master.executor.serverops.threads", 5));
1076    this.service.startExecutorService(ExecutorType.MASTER_META_SERVER_OPERATIONS,
1077       conf.getInt("hbase.master.executor.serverops.threads", 5));
1078    this.service.startExecutorService(ExecutorType.M_LOG_REPLAY_OPS,
1079       conf.getInt("hbase.master.executor.logreplayops.threads", 10));
1080 
1081    // We depend on there being only one instance of this executor running
1082    // at a time.  To do concurrency, would need fencing of enable/disable of
1083    // tables.
1084    // Any time changing this maxThreads to > 1, pls see the comment at
1085    // AccessController#postCreateTableHandler
1086    this.service.startExecutorService(ExecutorType.MASTER_TABLE_OPERATIONS, 1);
1087    startProcedureExecutor();
1088 
1089    // Start log cleaner thread
1090    int cleanerInterval = conf.getInt("hbase.master.cleaner.interval", 60 * 1000);
1091    this.logCleaner =
1092       new LogCleaner(cleanerInterval,
1093          this, conf, getMasterFileSystem().getFileSystem(),
1094          getMasterFileSystem().getOldLogDir());
1095     getChoreService().scheduleChore(logCleaner);
1096 
1097    //start the hfile archive cleaner thread
1098     Path archiveDir = HFileArchiveUtil.getArchivePath(conf);
1099     this.hfileCleaner = new HFileCleaner(cleanerInterval, this, conf, getMasterFileSystem()
1100         .getFileSystem(), archiveDir);
1101     getChoreService().scheduleChore(hfileCleaner);
1102     serviceStarted = true;
1103     if (LOG.isTraceEnabled()) {
1104       LOG.trace("Started service threads");
1105     }
1106   }
1107 
1108   @Override
1109   protected void sendShutdownInterrupt() {
1110     super.sendShutdownInterrupt();
1111     stopProcedureExecutor();
1112   }
1113 
1114   @Override
1115   protected void stopServiceThreads() {
1116     if (masterJettyServer != null) {
1117       LOG.info("Stopping master jetty server");
1118       try {
1119         masterJettyServer.stop();
1120       } catch (Exception e) {
1121         LOG.error("Failed to stop master jetty server", e);
1122       }
1123     }
1124     super.stopServiceThreads();
1125     stopChores();
1126 
1127     // Wait for all the remaining region servers to report in IFF we were
1128     // running a cluster shutdown AND we were NOT aborting.
1129     if (!isAborted() && this.serverManager != null &&
1130         this.serverManager.isClusterShutdown()) {
1131       this.serverManager.letRegionServersShutdown();
1132     }
1133     if (LOG.isDebugEnabled()) {
1134       LOG.debug("Stopping service threads");
1135     }
1136     // Clean up and close up shop
1137     if (this.logCleaner != null) this.logCleaner.cancel(true);
1138     if (this.hfileCleaner != null) this.hfileCleaner.cancel(true);
1139     if (this.quotaManager != null) this.quotaManager.stop();
1140     if (this.activeMasterManager != null) this.activeMasterManager.stop();
1141     if (this.serverManager != null) this.serverManager.stop();
1142     if (this.assignmentManager != null) this.assignmentManager.stop();
1143     if (this.fileSystemManager != null) this.fileSystemManager.stop();
1144     if (this.mpmHost != null) this.mpmHost.stop("server shutting down.");
1145   }
1146 
1147   /**
1148    * Check whether the procedure executor is enabled
1149    */
1150   @Override
1151   public boolean isMasterProcedureExecutorEnabled() {
1152     return (this.procedureConf == ProcedureConf.PROCEDURE_ENABLED);
1153   }
1154 
1155   private void startProcedureExecutor() throws IOException {
1156     final MasterProcedureEnv procEnv = new MasterProcedureEnv(this);
1157     final Path logDir = new Path(fileSystemManager.getRootDir(),
1158         MasterProcedureConstants.MASTER_PROCEDURE_LOGDIR);
1159 
1160     if (this.procedureConf == ProcedureConf.PROCEDURE_FULLY_DISABLED) {
1161       // Clean up the procedure store so that we will in a clean state when procedure
1162       // is enabled later.
1163       // Note: hbck might needed for uncompleted procedures.
1164       try {
1165         fs.delete(logDir, true);
1166         LOG.warn("Procedure executor is disabled from configuartion. " +
1167             "All the state logs from procedure store were removed." +
1168             "You should check the cluster state using HBCK.");
1169       } catch (Exception e) {
1170         // Ignore exception and move on.
1171         LOG.error("Removing all the state logs from procedure store failed." +
1172             "You should check the cluster state using HBCK.");
1173       }
1174       return;
1175     }
1176 
1177     procedureStore = new WALProcedureStore(conf, fileSystemManager.getFileSystem(), logDir,
1178         new MasterProcedureEnv.WALStoreLeaseRecovery(this));
1179 
1180     procedureStore.registerListener(new MasterProcedureEnv.MasterProcedureStoreListener(this));
1181     procedureExecutor = new ProcedureExecutor(conf, procEnv, procedureStore,
1182         procEnv.getProcedureQueue());
1183 
1184     final int numThreads = conf.getInt(MasterProcedureConstants.MASTER_PROCEDURE_THREADS,
1185         Math.max(Runtime.getRuntime().availableProcessors(),
1186           MasterProcedureConstants.DEFAULT_MIN_MASTER_PROCEDURE_THREADS));
1187     procedureStore.start(numThreads);
1188     procedureExecutor.start(numThreads);
1189   }
1190 
1191   private void stopProcedureExecutor() {
1192     if (procedureExecutor != null) {
1193       procedureExecutor.stop();
1194     }
1195 
1196     if (procedureStore != null) {
1197       procedureStore.stop(isAborted());
1198     }
1199   }
1200 
1201   private void stopChores() {
1202     if (this.balancerChore != null) {
1203       this.balancerChore.cancel(true);
1204     }
1205     if (this.clusterStatusChore != null) {
1206       this.clusterStatusChore.cancel(true);
1207     }
1208     if (this.catalogJanitorChore != null) {
1209       this.catalogJanitorChore.cancel(true);
1210     }
1211     if (this.clusterStatusPublisherChore != null){
1212       clusterStatusPublisherChore.cancel(true);
1213     }
1214   }
1215 
1216   /**
1217    * @return Get remote side's InetAddress
1218    * @throws UnknownHostException
1219    */
1220   InetAddress getRemoteInetAddress(final int port,
1221       final long serverStartCode) throws UnknownHostException {
1222     // Do it out here in its own little method so can fake an address when
1223     // mocking up in tests.
1224     InetAddress ia = RpcServer.getRemoteIp();
1225 
1226     // The call could be from the local regionserver,
1227     // in which case, there is no remote address.
1228     if (ia == null && serverStartCode == startcode) {
1229       InetSocketAddress isa = rpcServices.getSocketAddress();
1230       if (isa != null && isa.getPort() == port) {
1231         ia = isa.getAddress();
1232       }
1233     }
1234     return ia;
1235   }
1236 
1237   /**
1238    * @return Maximum time we should run balancer for
1239    */
1240   private int getBalancerCutoffTime() {
1241     int balancerCutoffTime =
1242       getConfiguration().getInt("hbase.balancer.max.balancing", -1);
1243     if (balancerCutoffTime == -1) {
1244       // No time period set so create one
1245       int balancerPeriod =
1246         getConfiguration().getInt("hbase.balancer.period", 300000);
1247       balancerCutoffTime = balancerPeriod;
1248       // If nonsense period, set it to balancerPeriod
1249       if (balancerCutoffTime <= 0) balancerCutoffTime = balancerPeriod;
1250     }
1251     return balancerCutoffTime;
1252   }
1253 
1254   public boolean balance() throws IOException {
1255     // if master not initialized, don't run balancer.
1256     if (!this.initialized) {
1257       LOG.debug("Master has not been initialized, don't run balancer.");
1258       return false;
1259     }
1260     // Do this call outside of synchronized block.
1261     int maximumBalanceTime = getBalancerCutoffTime();
1262     synchronized (this.balancer) {
1263       // If balance not true, don't run balancer.
1264       if (!this.loadBalancerTracker.isBalancerOn()) return false;
1265       // Only allow one balance run at at time.
1266       if (this.assignmentManager.getRegionStates().isRegionsInTransition()) {
1267         Map<String, RegionState> regionsInTransition =
1268           this.assignmentManager.getRegionStates().getRegionsInTransition();
1269         LOG.debug("Not running balancer because " + regionsInTransition.size() +
1270           " region(s) in transition: " + org.apache.commons.lang.StringUtils.
1271             abbreviate(regionsInTransition.toString(), 256));
1272         return false;
1273       }
1274       if (this.serverManager.areDeadServersInProgress()) {
1275         LOG.debug("Not running balancer because processing dead regionserver(s): " +
1276           this.serverManager.getDeadServers());
1277         return false;
1278       }
1279 
1280       if (this.cpHost != null) {
1281         try {
1282           if (this.cpHost.preBalance()) {
1283             LOG.debug("Coprocessor bypassing balancer request");
1284             return false;
1285           }
1286         } catch (IOException ioe) {
1287           LOG.error("Error invoking master coprocessor preBalance()", ioe);
1288           return false;
1289         }
1290       }
1291 
1292       Map<TableName, Map<ServerName, List<HRegionInfo>>> assignmentsByTable =
1293         this.assignmentManager.getRegionStates().getAssignmentsByTable();
1294 
1295       List<RegionPlan> plans = new ArrayList<RegionPlan>();
1296       //Give the balancer the current cluster state.
1297       this.balancer.setClusterStatus(getClusterStatus());
1298       for (Map<ServerName, List<HRegionInfo>> assignments : assignmentsByTable.values()) {
1299         List<RegionPlan> partialPlans = this.balancer.balanceCluster(assignments);
1300         if (partialPlans != null) plans.addAll(partialPlans);
1301       }
1302       long cutoffTime = System.currentTimeMillis() + maximumBalanceTime;
1303       int rpCount = 0;  // number of RegionPlans balanced so far
1304       long totalRegPlanExecTime = 0;
1305       if (plans != null && !plans.isEmpty()) {
1306         for (RegionPlan plan: plans) {
1307           LOG.info("balance " + plan);
1308           long balStartTime = System.currentTimeMillis();
1309           //TODO: bulk assign
1310           this.assignmentManager.balance(plan);
1311           totalRegPlanExecTime += System.currentTimeMillis()-balStartTime;
1312           rpCount++;
1313           if (rpCount < plans.size() &&
1314               // if performing next balance exceeds cutoff time, exit the loop
1315               (System.currentTimeMillis() + (totalRegPlanExecTime / rpCount)) > cutoffTime) {
1316             //TODO: After balance, there should not be a cutoff time (keeping it as a security net for now)
1317             LOG.debug("No more balancing till next balance run; maximumBalanceTime=" +
1318               maximumBalanceTime);
1319             break;
1320           }
1321         }
1322       }
1323       if (this.cpHost != null) {
1324         try {
1325           this.cpHost.postBalance(rpCount < plans.size() ? plans.subList(0, rpCount) : plans);
1326         } catch (IOException ioe) {
1327           // balancing already succeeded so don't change the result
1328           LOG.error("Error invoking master coprocessor postBalance()", ioe);
1329         }
1330       }
1331     }
1332     // If LoadBalancer did not generate any plans, it means the cluster is already balanced.
1333     // Return true indicating a success.
1334     return true;
1335   }
1336 
1337   /**
1338    * @return Client info for use as prefix on an audit log string; who did an action
1339    */
1340   String getClientIdAuditPrefix() {
1341     return "Client=" + RpcServer.getRequestUserName() + "/" + RpcServer.getRemoteAddress();
1342   }
1343 
1344   /**
1345    * Switch for the background CatalogJanitor thread.
1346    * Used for testing.  The thread will continue to run.  It will just be a noop
1347    * if disabled.
1348    * @param b If false, the catalog janitor won't do anything.
1349    */
1350   public void setCatalogJanitorEnabled(final boolean b) {
1351     this.catalogJanitorChore.setEnabled(b);
1352   }
1353 
1354   @Override
1355   public void dispatchMergingRegions(final HRegionInfo region_a,
1356       final HRegionInfo region_b, final boolean forcible) throws IOException {
1357     checkInitialized();
1358     this.service.submit(new DispatchMergingRegionHandler(this,
1359         this.catalogJanitorChore, region_a, region_b, forcible));
1360   }
1361 
1362   void move(final byte[] encodedRegionName,
1363       final byte[] destServerName) throws HBaseIOException {
1364     RegionState regionState = assignmentManager.getRegionStates().
1365       getRegionState(Bytes.toString(encodedRegionName));
1366     if (regionState == null) {
1367       throw new UnknownRegionException(Bytes.toStringBinary(encodedRegionName));
1368     }
1369 
1370     HRegionInfo hri = regionState.getRegion();
1371     ServerName dest;
1372     if (destServerName == null || destServerName.length == 0) {
1373       LOG.info("Passed destination servername is null/empty so " +
1374         "choosing a server at random");
1375       final List<ServerName> destServers = this.serverManager.createDestinationServersList(
1376         regionState.getServerName());
1377       dest = balancer.randomAssignment(hri, destServers);
1378       if (dest == null) {
1379         LOG.debug("Unable to determine a plan to assign " + hri);
1380         return;
1381       }
1382     } else {
1383       dest = ServerName.valueOf(Bytes.toString(destServerName));
1384       if (dest.equals(serverName) && balancer instanceof BaseLoadBalancer
1385           && !((BaseLoadBalancer)balancer).shouldBeOnMaster(hri)) {
1386         // To avoid unnecessary region moving later by balancer. Don't put user
1387         // regions on master. Regions on master could be put on other region
1388         // server intentionally by test however.
1389         LOG.debug("Skipping move of region " + hri.getRegionNameAsString()
1390           + " to avoid unnecessary region moving later by load balancer,"
1391           + " because it should not be on master");
1392         return;
1393       }
1394     }
1395 
1396     if (dest.equals(regionState.getServerName())) {
1397       LOG.debug("Skipping move of region " + hri.getRegionNameAsString()
1398         + " because region already assigned to the same server " + dest + ".");
1399       return;
1400     }
1401 
1402     // Now we can do the move
1403     RegionPlan rp = new RegionPlan(hri, regionState.getServerName(), dest);
1404 
1405     try {
1406       checkInitialized();
1407       if (this.cpHost != null) {
1408         if (this.cpHost.preMove(hri, rp.getSource(), rp.getDestination())) {
1409           return;
1410         }
1411       }
1412       // warmup the region on the destination before initiating the move. this call
1413       // is synchronous and takes some time. doing it before the source region gets
1414       // closed
1415       serverManager.sendRegionWarmup(rp.getDestination(), hri);
1416 
1417       LOG.info(getClientIdAuditPrefix() + " move " + rp + ", running balancer");
1418       this.assignmentManager.balance(rp);
1419       if (this.cpHost != null) {
1420         this.cpHost.postMove(hri, rp.getSource(), rp.getDestination());
1421       }
1422     } catch (IOException ioe) {
1423       if (ioe instanceof HBaseIOException) {
1424         throw (HBaseIOException)ioe;
1425       }
1426       throw new HBaseIOException(ioe);
1427     }
1428   }
1429 
1430   @Override
1431   public long createTable(HTableDescriptor hTableDescriptor,
1432       byte [][] splitKeys) throws IOException {
1433     if (isStopped()) {
1434       throw new MasterNotRunningException();
1435     }
1436 
1437     TableName tableName = hTableDescriptor.getTableName();
1438     String namespace = tableName.getNamespaceAsString();
1439     ensureNamespaceExists(namespace);
1440 
1441     HRegionInfo[] newRegions = ModifyRegionUtils.createHRegionInfos(hTableDescriptor, splitKeys);
1442     checkInitialized();
1443     sanityCheckTableDescriptor(hTableDescriptor);
1444     if (cpHost != null) {
1445       cpHost.preCreateTable(hTableDescriptor, newRegions);
1446     }
1447     LOG.info(getClientIdAuditPrefix() + " create " + hTableDescriptor);
1448 
1449     long procId = -1;
1450     if (isMasterProcedureExecutorEnabled()) {
1451       // TODO: We can handle/merge duplicate requests, and differentiate the case of
1452       //       TableExistsException by saying if the schema is the same or not.
1453       ProcedurePrepareLatch latch = ProcedurePrepareLatch.createLatch();
1454       procId = this.procedureExecutor.submitProcedure(
1455         new CreateTableProcedure(procedureExecutor.getEnvironment(),
1456           hTableDescriptor, newRegions, latch));
1457       latch.await();
1458     } else {
1459       try {
1460         this.quotaManager.checkNamespaceTableAndRegionQuota(tableName, newRegions.length);
1461         this.service.submit(new CreateTableHandler(this, this.fileSystemManager, hTableDescriptor,
1462             conf, newRegions, this).prepare());
1463       } catch (IOException e) {
1464         this.quotaManager.removeTableFromNamespaceQuota(tableName);
1465         LOG.error("Exception occurred while creating the table " + tableName.getNameAsString(), e);
1466         throw e;
1467       }
1468     }
1469 
1470     if (cpHost != null) {
1471       cpHost.postCreateTable(hTableDescriptor, newRegions);
1472     }
1473 
1474     return procId;
1475   }
1476 
1477   /**
1478    * Checks whether the table conforms to some sane limits, and configured
1479    * values (compression, etc) work. Throws an exception if something is wrong.
1480    * @throws IOException
1481    */
1482   private void sanityCheckTableDescriptor(final HTableDescriptor htd) throws IOException {
1483     final String CONF_KEY = "hbase.table.sanity.checks";
1484     boolean logWarn = false;
1485     if (!conf.getBoolean(CONF_KEY, true)) {
1486       logWarn = true;
1487     }
1488     String tableVal = htd.getConfigurationValue(CONF_KEY);
1489     if (tableVal != null && !Boolean.valueOf(tableVal)) {
1490       logWarn = true;
1491     }
1492 
1493     // check max file size
1494     long maxFileSizeLowerLimit = 2 * 1024 * 1024L; // 2M is the default lower limit
1495     long maxFileSize = htd.getMaxFileSize();
1496     if (maxFileSize < 0) {
1497       maxFileSize = conf.getLong(HConstants.HREGION_MAX_FILESIZE, maxFileSizeLowerLimit);
1498     }
1499     if (maxFileSize < conf.getLong("hbase.hregion.max.filesize.limit", maxFileSizeLowerLimit)) {
1500       String message = "MAX_FILESIZE for table descriptor or "
1501           + "\"hbase.hregion.max.filesize\" (" + maxFileSize
1502           + ") is too small, which might cause over splitting into unmanageable "
1503           + "number of regions.";
1504       warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null);
1505     }
1506 
1507     // check flush size
1508     long flushSizeLowerLimit = 1024 * 1024L; // 1M is the default lower limit
1509     long flushSize = htd.getMemStoreFlushSize();
1510     if (flushSize < 0) {
1511       flushSize = conf.getLong(HConstants.HREGION_MEMSTORE_FLUSH_SIZE, flushSizeLowerLimit);
1512     }
1513     if (flushSize < conf.getLong("hbase.hregion.memstore.flush.size.limit", flushSizeLowerLimit)) {
1514       String message = "MEMSTORE_FLUSHSIZE for table descriptor or "
1515           + "\"hbase.hregion.memstore.flush.size\" ("+flushSize+") is too small, which might cause"
1516           + " very frequent flushing.";
1517       warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null);
1518     }
1519 
1520     // check that coprocessors and other specified plugin classes can be loaded
1521     try {
1522       checkClassLoading(conf, htd);
1523     } catch (Exception ex) {
1524       warnOrThrowExceptionForFailure(logWarn, CONF_KEY, ex.getMessage(), null);
1525     }
1526 
1527     // check compression can be loaded
1528     try {
1529       checkCompression(htd);
1530     } catch (IOException e) {
1531       warnOrThrowExceptionForFailure(logWarn, CONF_KEY, e.getMessage(), e);
1532     }
1533 
1534     // check encryption can be loaded
1535     try {
1536       checkEncryption(conf, htd);
1537     } catch (IOException e) {
1538       warnOrThrowExceptionForFailure(logWarn, CONF_KEY, e.getMessage(), e);
1539     }
1540 
1541     // check that we have at least 1 CF
1542     if (htd.getColumnFamilies().length == 0) {
1543       String message = "Table should have at least one column family.";
1544       warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null);
1545     }
1546 
1547     for (HColumnDescriptor hcd : htd.getColumnFamilies()) {
1548       if (hcd.getTimeToLive() <= 0) {
1549         String message = "TTL for column family " + hcd.getNameAsString() + " must be positive.";
1550         warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null);
1551       }
1552 
1553       // check blockSize
1554       if (hcd.getBlocksize() < 1024 || hcd.getBlocksize() > 16 * 1024 * 1024) {
1555         String message = "Block size for column family " + hcd.getNameAsString()
1556             + "  must be between 1K and 16MB.";
1557         warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null);
1558       }
1559 
1560       // check versions
1561       if (hcd.getMinVersions() < 0) {
1562         String message = "Min versions for column family " + hcd.getNameAsString()
1563           + "  must be positive.";
1564         warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null);
1565       }
1566       // max versions already being checked
1567 
1568       // check replication scope
1569       if (hcd.getScope() < 0) {
1570         String message = "Replication scope for column family "
1571           + hcd.getNameAsString() + "  must be positive.";
1572         warnOrThrowExceptionForFailure(logWarn, CONF_KEY, message, null);
1573       }
1574 
1575       // TODO: should we check coprocessors and encryption ?
1576     }
1577   }
1578 
1579   // HBASE-13350 - Helper method to log warning on sanity check failures if checks disabled.
1580   private static void warnOrThrowExceptionForFailure(boolean logWarn, String confKey,
1581       String message, Exception cause) throws IOException {
1582     if (!logWarn) {
1583       throw new DoNotRetryIOException(message + " Set " + confKey +
1584           " to false at conf or table descriptor if you want to bypass sanity checks", cause);
1585     }
1586     LOG.warn(message);
1587   }
1588 
1589   private void startActiveMasterManager(int infoPort) throws KeeperException {
1590     String backupZNode = ZKUtil.joinZNode(
1591       zooKeeper.backupMasterAddressesZNode, serverName.toString());
1592     /*
1593     * Add a ZNode for ourselves in the backup master directory since we
1594     * may not become the active master. If so, we want the actual active
1595     * master to know we are backup masters, so that it won't assign
1596     * regions to us if so configured.
1597     *
1598     * If we become the active master later, ActiveMasterManager will delete
1599     * this node explicitly.  If we crash before then, ZooKeeper will delete
1600     * this node for us since it is ephemeral.
1601     */
1602     LOG.info("Adding backup master ZNode " + backupZNode);
1603     if (!MasterAddressTracker.setMasterAddress(zooKeeper, backupZNode,
1604         serverName, infoPort)) {
1605       LOG.warn("Failed create of " + backupZNode + " by " + serverName);
1606     }
1607 
1608     activeMasterManager.setInfoPort(infoPort);
1609     // Start a thread to try to become the active master, so we won't block here
1610     Threads.setDaemonThreadRunning(new Thread(new Runnable() {
1611       @Override
1612       public void run() {
1613         int timeout = conf.getInt(HConstants.ZK_SESSION_TIMEOUT,
1614           HConstants.DEFAULT_ZK_SESSION_TIMEOUT);
1615         // If we're a backup master, stall until a primary to writes his address
1616         if (conf.getBoolean(HConstants.MASTER_TYPE_BACKUP,
1617             HConstants.DEFAULT_MASTER_TYPE_BACKUP)) {
1618           LOG.debug("HMaster started in backup mode. "
1619             + "Stalling until master znode is written.");
1620           // This will only be a minute or so while the cluster starts up,
1621           // so don't worry about setting watches on the parent znode
1622           while (!activeMasterManager.hasActiveMaster()) {
1623             LOG.debug("Waiting for master address ZNode to be written "
1624               + "(Also watching cluster state node)");
1625             Threads.sleep(timeout);
1626           }
1627         }
1628         MonitoredTask status = TaskMonitor.get().createStatus("Master startup");
1629         status.setDescription("Master startup");
1630         try {
1631           if (activeMasterManager.blockUntilBecomingActiveMaster(timeout, status)) {
1632             finishActiveMasterInitialization(status);
1633           }
1634         } catch (Throwable t) {
1635           status.setStatus("Failed to become active: " + t.getMessage());
1636           LOG.fatal("Failed to become active master", t);
1637           // HBASE-5680: Likely hadoop23 vs hadoop 20.x/1.x incompatibility
1638           if (t instanceof NoClassDefFoundError &&
1639               t.getMessage().contains("org/apache/hadoop/hdfs/protocol/FSConstants$SafeModeAction")) {
1640             // improved error message for this special case
1641             abort("HBase is having a problem with its Hadoop jars.  You may need to "
1642               + "recompile HBase against Hadoop version "
1643               +  org.apache.hadoop.util.VersionInfo.getVersion()
1644               + " or change your hadoop jars to start properly", t);
1645           } else {
1646             abort("Unhandled exception. Starting shutdown.", t);
1647           }
1648         } finally {
1649           status.cleanup();
1650         }
1651       }
1652     }, getServerName().toShortString() + ".activeMasterManager"));
1653   }
1654 
1655   private void checkCompression(final HTableDescriptor htd)
1656   throws IOException {
1657     if (!this.masterCheckCompression) return;
1658     for (HColumnDescriptor hcd : htd.getColumnFamilies()) {
1659       checkCompression(hcd);
1660     }
1661   }
1662 
1663   private void checkCompression(final HColumnDescriptor hcd)
1664   throws IOException {
1665     if (!this.masterCheckCompression) return;
1666     CompressionTest.testCompression(hcd.getCompression());
1667     CompressionTest.testCompression(hcd.getCompactionCompression());
1668   }
1669 
1670   private void checkEncryption(final Configuration conf, final HTableDescriptor htd)
1671   throws IOException {
1672     if (!this.masterCheckEncryption) return;
1673     for (HColumnDescriptor hcd : htd.getColumnFamilies()) {
1674       checkEncryption(conf, hcd);
1675     }
1676   }
1677 
1678   private void checkEncryption(final Configuration conf, final HColumnDescriptor hcd)
1679   throws IOException {
1680     if (!this.masterCheckEncryption) return;
1681     EncryptionTest.testEncryption(conf, hcd.getEncryptionType(), hcd.getEncryptionKey());
1682   }
1683 
1684   private void checkClassLoading(final Configuration conf, final HTableDescriptor htd)
1685   throws IOException {
1686     RegionSplitPolicy.getSplitPolicyClass(htd, conf);
1687     RegionCoprocessorHost.testTableCoprocessorAttrs(conf, htd);
1688   }
1689 
1690   private static boolean isCatalogTable(final TableName tableName) {
1691     return tableName.equals(TableName.META_TABLE_NAME);
1692   }
1693 
1694   @Override
1695   public long deleteTable(final TableName tableName) throws IOException {
1696     checkInitialized();
1697     if (cpHost != null) {
1698       cpHost.preDeleteTable(tableName);
1699     }
1700     LOG.info(getClientIdAuditPrefix() + " delete " + tableName);
1701 
1702     long procId = -1;
1703     if (isMasterProcedureExecutorEnabled()) {
1704       // TODO: We can handle/merge duplicate request
1705       ProcedurePrepareLatch latch = ProcedurePrepareLatch.createLatch();
1706       procId = this.procedureExecutor.submitProcedure(
1707         new DeleteTableProcedure(procedureExecutor.getEnvironment(), tableName, latch));
1708       latch.await();
1709     } else {
1710       this.service.submit(new DeleteTableHandler(tableName, this, this).prepare());
1711     }
1712 
1713     if (cpHost != null) {
1714       cpHost.postDeleteTable(tableName);
1715     }
1716 
1717     return procId;
1718   }
1719 
1720   @Override
1721   public void truncateTable(TableName tableName, boolean preserveSplits) throws IOException {
1722     checkInitialized();
1723     if (cpHost != null) {
1724       cpHost.preTruncateTable(tableName);
1725     }
1726     LOG.info(getClientIdAuditPrefix() + " truncate " + tableName);
1727 
1728     if (isMasterProcedureExecutorEnabled()) {
1729       long procId = this.procedureExecutor.submitProcedure(
1730         new TruncateTableProcedure(procedureExecutor.getEnvironment(), tableName, preserveSplits));
1731       ProcedureSyncWait.waitForProcedureToComplete(procedureExecutor, procId);
1732     } else {
1733       TruncateTableHandler handler =
1734           new TruncateTableHandler(tableName, this, this, preserveSplits);
1735       handler.prepare();
1736       handler.process();
1737     }
1738 
1739     if (cpHost != null) {
1740       cpHost.postTruncateTable(tableName);
1741     }
1742   }
1743 
1744   @Override
1745   public void addColumn(final TableName tableName, final HColumnDescriptor columnDescriptor)
1746       throws IOException {
1747     checkInitialized();
1748     checkCompression(columnDescriptor);
1749     checkEncryption(conf, columnDescriptor);
1750     if (cpHost != null) {
1751       if (cpHost.preAddColumn(tableName, columnDescriptor)) {
1752         return;
1753       }
1754     }
1755     LOG.info(getClientIdAuditPrefix() + " add " + columnDescriptor);
1756 
1757     if (isMasterProcedureExecutorEnabled()) {
1758       // Execute the operation synchronously - wait for the operation to complete before continuing.
1759       long procId =
1760         this.procedureExecutor.submitProcedure(new AddColumnFamilyProcedure(procedureExecutor
1761             .getEnvironment(), tableName, columnDescriptor));
1762       ProcedureSyncWait.waitForProcedureToComplete(procedureExecutor, procId);
1763     } else {
1764       new TableAddFamilyHandler(tableName, columnDescriptor, this, this).prepare().process();
1765     }
1766     if (cpHost != null) {
1767       cpHost.postAddColumn(tableName, columnDescriptor);
1768     }
1769   }
1770 
1771   @Override
1772   public void modifyColumn(TableName tableName, HColumnDescriptor descriptor)
1773       throws IOException {
1774     checkInitialized();
1775     checkCompression(descriptor);
1776     checkEncryption(conf, descriptor);
1777     if (cpHost != null) {
1778       if (cpHost.preModifyColumn(tableName, descriptor)) {
1779         return;
1780       }
1781     }
1782     LOG.info(getClientIdAuditPrefix() + " modify " + descriptor);
1783 
1784     if (isMasterProcedureExecutorEnabled()) {
1785       // Execute the operation synchronously - wait for the operation to complete before continuing.
1786       long procId =
1787         this.procedureExecutor.submitProcedure(new ModifyColumnFamilyProcedure(procedureExecutor
1788             .getEnvironment(), tableName, descriptor));
1789       ProcedureSyncWait.waitForProcedureToComplete(procedureExecutor, procId);
1790     } else {
1791       new TableModifyFamilyHandler(tableName, descriptor, this, this).prepare().process();
1792     }
1793 
1794     if (cpHost != null) {
1795       cpHost.postModifyColumn(tableName, descriptor);
1796     }
1797   }
1798 
1799   @Override
1800   public void deleteColumn(final TableName tableName, final byte[] columnName)
1801       throws IOException {
1802     checkInitialized();
1803     if (cpHost != null) {
1804       if (cpHost.preDeleteColumn(tableName, columnName)) {
1805         return;
1806       }
1807     }
1808     LOG.info(getClientIdAuditPrefix() + " delete " + Bytes.toString(columnName));
1809 
1810     if (isMasterProcedureExecutorEnabled()) {
1811       // Execute the operation synchronously - wait for the operation to complete before continuing.
1812       long procId =
1813         this.procedureExecutor.submitProcedure(new DeleteColumnFamilyProcedure(procedureExecutor
1814             .getEnvironment(), tableName, columnName));
1815       ProcedureSyncWait.waitForProcedureToComplete(procedureExecutor, procId);
1816     } else {
1817       new TableDeleteFamilyHandler(tableName, columnName, this, this).prepare().process();
1818     }
1819 
1820     if (cpHost != null) {
1821       cpHost.postDeleteColumn(tableName, columnName);
1822     }
1823   }
1824 
1825   @Override
1826   public long enableTable(final TableName tableName) throws IOException {
1827     checkInitialized();
1828     if (cpHost != null) {
1829       cpHost.preEnableTable(tableName);
1830     }
1831     LOG.info(getClientIdAuditPrefix() + " enable " + tableName);
1832 
1833     long procId = -1;
1834     if (isMasterProcedureExecutorEnabled()) {
1835       // Execute the operation asynchronously - client will check the progress of the operation
1836       final ProcedurePrepareLatch prepareLatch = ProcedurePrepareLatch.createLatch();
1837       procId =
1838           this.procedureExecutor.submitProcedure(new EnableTableProcedure(procedureExecutor
1839             .getEnvironment(), tableName, false, prepareLatch));
1840       // Before returning to client, we want to make sure that the table is prepared to be
1841       // enabled (the table is locked and the table state is set).
1842       //
1843       // Note: if the procedure throws exception, we will catch it and rethrow.
1844       prepareLatch.await();
1845     } else {
1846       this.service.submit(new EnableTableHandler(this, tableName,
1847         assignmentManager, tableLockManager, false).prepare());
1848     }
1849 
1850     if (cpHost != null) {
1851       cpHost.postEnableTable(tableName);
1852     }
1853 
1854     return procId;
1855   }
1856 
1857   @Override
1858   public long disableTable(final TableName tableName) throws IOException {
1859     checkInitialized();
1860     if (cpHost != null) {
1861       cpHost.preDisableTable(tableName);
1862     }
1863     LOG.info(getClientIdAuditPrefix() + " disable " + tableName);
1864 
1865     long procId = -1;
1866     if (isMasterProcedureExecutorEnabled()) {
1867       // Execute the operation asynchronously - client will check the progress of the operation
1868       final ProcedurePrepareLatch prepareLatch = ProcedurePrepareLatch.createLatch();
1869       procId =
1870           this.procedureExecutor.submitProcedure(new DisableTableProcedure(procedureExecutor
1871             .getEnvironment(), tableName, false, prepareLatch));
1872       // Before returning to client, we want to make sure that the table is prepared to be
1873       // enabled (the table is locked and the table state is set).
1874       //
1875       // Note: if the procedure throws exception, we will catch it and rethrow.
1876       prepareLatch.await();
1877     } else {
1878       this.service.submit(new DisableTableHandler(this, tableName,
1879         assignmentManager, tableLockManager, false).prepare());
1880     }
1881 
1882     if (cpHost != null) {
1883       cpHost.postDisableTable(tableName);
1884     }
1885 
1886     return procId;
1887   }
1888 
1889   /**
1890    * Return the region and current deployment for the region containing
1891    * the given row. If the region cannot be found, returns null. If it
1892    * is found, but not currently deployed, the second element of the pair
1893    * may be null.
1894    */
1895   @VisibleForTesting // Used by TestMaster.
1896   Pair<HRegionInfo, ServerName> getTableRegionForRow(
1897       final TableName tableName, final byte [] rowKey)
1898   throws IOException {
1899     final AtomicReference<Pair<HRegionInfo, ServerName>> result =
1900       new AtomicReference<Pair<HRegionInfo, ServerName>>(null);
1901 
1902     MetaScannerVisitor visitor =
1903       new MetaScannerVisitorBase() {
1904         @Override
1905         public boolean processRow(Result data) throws IOException {
1906           if (data == null || data.size() <= 0) {
1907             return true;
1908           }
1909           Pair<HRegionInfo, ServerName> pair = HRegionInfo.getHRegionInfoAndServerName(data);
1910           if (pair == null) {
1911             return false;
1912           }
1913           if (!pair.getFirst().getTable().equals(tableName)) {
1914             return false;
1915           }
1916           result.set(pair);
1917           return true;
1918         }
1919     };
1920 
1921     MetaScanner.metaScan(clusterConnection, visitor, tableName, rowKey, 1);
1922     return result.get();
1923   }
1924 
1925   @Override
1926   public void modifyTable(final TableName tableName, final HTableDescriptor descriptor)
1927       throws IOException {
1928     checkInitialized();
1929     sanityCheckTableDescriptor(descriptor);
1930     if (cpHost != null) {
1931       cpHost.preModifyTable(tableName, descriptor);
1932     }
1933 
1934     LOG.info(getClientIdAuditPrefix() + " modify " + tableName);
1935 
1936     if (isMasterProcedureExecutorEnabled()) {
1937       // Execute the operation synchronously - wait for the operation completes before continuing.
1938       long procId = this.procedureExecutor.submitProcedure(
1939         new ModifyTableProcedure(procedureExecutor.getEnvironment(), descriptor));
1940 
1941       ProcedureSyncWait.waitForProcedureToComplete(procedureExecutor, procId);
1942     } else {
1943       new ModifyTableHandler(tableName, descriptor, this, this).prepare().process();
1944     }
1945 
1946     if (cpHost != null) {
1947       cpHost.postModifyTable(tableName, descriptor);
1948     }
1949   }
1950 
1951   @Override
1952   public void checkTableModifiable(final TableName tableName)
1953       throws IOException, TableNotFoundException, TableNotDisabledException {
1954     if (isCatalogTable(tableName)) {
1955       throw new IOException("Can't modify catalog tables");
1956     }
1957     if (!MetaTableAccessor.tableExists(getConnection(), tableName)) {
1958       throw new TableNotFoundException(tableName);
1959     }
1960     if (!getAssignmentManager().getTableStateManager().
1961         isTableState(tableName, ZooKeeperProtos.Table.State.DISABLED)) {
1962       throw new TableNotDisabledException(tableName);
1963     }
1964   }
1965 
1966   /**
1967    * @return cluster status
1968    */
1969   public ClusterStatus getClusterStatus() throws InterruptedIOException {
1970     // Build Set of backup masters from ZK nodes
1971     List<String> backupMasterStrings;
1972     try {
1973       backupMasterStrings = ZKUtil.listChildrenNoWatch(this.zooKeeper,
1974         this.zooKeeper.backupMasterAddressesZNode);
1975     } catch (KeeperException e) {
1976       LOG.warn(this.zooKeeper.prefix("Unable to list backup servers"), e);
1977       backupMasterStrings = null;
1978     }
1979 
1980     List<ServerName> backupMasters = null;
1981     if (backupMasterStrings != null && !backupMasterStrings.isEmpty()) {
1982       backupMasters = new ArrayList<ServerName>(backupMasterStrings.size());
1983       for (String s: backupMasterStrings) {
1984         try {
1985           byte [] bytes;
1986           try {
1987             bytes = ZKUtil.getData(this.zooKeeper, ZKUtil.joinZNode(
1988                 this.zooKeeper.backupMasterAddressesZNode, s));
1989           } catch (InterruptedException e) {
1990             throw new InterruptedIOException();
1991           }
1992           if (bytes != null) {
1993             ServerName sn;
1994             try {
1995               sn = ServerName.parseFrom(bytes);
1996             } catch (DeserializationException e) {
1997               LOG.warn("Failed parse, skipping registering backup server", e);
1998               continue;
1999             }
2000             backupMasters.add(sn);
2001           }
2002         } catch (KeeperException e) {
2003           LOG.warn(this.zooKeeper.prefix("Unable to get information about " +
2004                    "backup servers"), e);
2005         }
2006       }
2007       Collections.sort(backupMasters, new Comparator<ServerName>() {
2008         @Override
2009         public int compare(ServerName s1, ServerName s2) {
2010           return s1.getServerName().compareTo(s2.getServerName());
2011         }});
2012     }
2013 
2014     String clusterId = fileSystemManager != null ?
2015       fileSystemManager.getClusterId().toString() : null;
2016     Map<String, RegionState> regionsInTransition = assignmentManager != null ?
2017       assignmentManager.getRegionStates().getRegionsInTransition() : null;
2018     String[] coprocessors = cpHost != null ? getMasterCoprocessors() : null;
2019     boolean balancerOn = loadBalancerTracker != null ?
2020       loadBalancerTracker.isBalancerOn() : false;
2021     Map<ServerName, ServerLoad> onlineServers = null;
2022     Set<ServerName> deadServers = null;
2023     if (serverManager != null) {
2024       deadServers = serverManager.getDeadServers().copyServerNames();
2025       onlineServers = serverManager.getOnlineServers();
2026     }
2027     return new ClusterStatus(VersionInfo.getVersion(), clusterId,
2028       onlineServers, deadServers, serverName, backupMasters,
2029       regionsInTransition, coprocessors, balancerOn);
2030   }
2031 
2032   /**
2033    * The set of loaded coprocessors is stored in a static set. Since it's
2034    * statically allocated, it does not require that HMaster's cpHost be
2035    * initialized prior to accessing it.
2036    * @return a String representation of the set of names of the loaded
2037    * coprocessors.
2038    */
2039   public static String getLoadedCoprocessors() {
2040     return CoprocessorHost.getLoadedCoprocessors().toString();
2041   }
2042 
2043   /**
2044    * @return timestamp in millis when HMaster was started.
2045    */
2046   public long getMasterStartTime() {
2047     return startcode;
2048   }
2049 
2050   /**
2051    * @return timestamp in millis when HMaster became the active master.
2052    */
2053   public long getMasterActiveTime() {
2054     return masterActiveTime;
2055   }
2056 
2057   public int getRegionServerInfoPort(final ServerName sn) {
2058     RegionServerInfo info = this.regionServerTracker.getRegionServerInfo(sn);
2059     if (info == null || info.getInfoPort() == 0) {
2060       return conf.getInt(HConstants.REGIONSERVER_INFO_PORT,
2061         HConstants.DEFAULT_REGIONSERVER_INFOPORT);
2062     }
2063     return info.getInfoPort();
2064   }
2065 
2066   /**
2067    * @return array of coprocessor SimpleNames.
2068    */
2069   public String[] getMasterCoprocessors() {
2070     Set<String> masterCoprocessors = getMasterCoprocessorHost().getCoprocessors();
2071     return masterCoprocessors.toArray(new String[masterCoprocessors.size()]);
2072   }
2073 
2074   @Override
2075   public void abort(final String msg, final Throwable t) {
2076     if (isAborted() || isStopped()) {
2077       return;
2078     }
2079     if (cpHost != null) {
2080       // HBASE-4014: dump a list of loaded coprocessors.
2081       LOG.fatal("Master server abort: loaded coprocessors are: " +
2082           getLoadedCoprocessors());
2083     }
2084     if (t != null) LOG.fatal(msg, t);
2085     stop(msg);
2086   }
2087 
2088   @Override
2089   public ZooKeeperWatcher getZooKeeper() {
2090     return zooKeeper;
2091   }
2092 
2093   @Override
2094   public MasterCoprocessorHost getMasterCoprocessorHost() {
2095     return cpHost;
2096   }
2097   
2098   @Override
2099   public MasterQuotaManager getMasterQuotaManager() {
2100     return quotaManager;
2101   }
2102 
2103   @Override
2104   public ProcedureExecutor<MasterProcedureEnv> getMasterProcedureExecutor() {
2105     return procedureExecutor;
2106   }
2107 
2108   @Override
2109   public ServerName getServerName() {
2110     return this.serverName;
2111   }
2112 
2113   @Override
2114   public AssignmentManager getAssignmentManager() {
2115     return this.assignmentManager;
2116   }
2117 
2118   public MemoryBoundedLogMessageBuffer getRegionServerFatalLogBuffer() {
2119     return rsFatals;
2120   }
2121 
2122   public void shutdown() {
2123     if (cpHost != null) {
2124       try {
2125         cpHost.preShutdown();
2126       } catch (IOException ioe) {
2127         LOG.error("Error call master coprocessor preShutdown()", ioe);
2128       }
2129     }
2130 
2131     if (this.serverManager != null) {
2132       this.serverManager.shutdownCluster();
2133     }
2134     if (this.clusterStatusTracker != null){
2135       try {
2136         this.clusterStatusTracker.setClusterDown();
2137       } catch (KeeperException e) {
2138         LOG.error("ZooKeeper exception trying to set cluster as down in ZK", e);
2139       }
2140     }
2141   }
2142 
2143   public void stopMaster() {
2144     if (cpHost != null) {
2145       try {
2146         cpHost.preStopMaster();
2147       } catch (IOException ioe) {
2148         LOG.error("Error call master coprocessor preStopMaster()", ioe);
2149       }
2150     }
2151     stop("Stopped by " + Thread.currentThread().getName());
2152   }
2153 
2154   void checkServiceStarted() throws ServerNotRunningYetException {
2155     if (!serviceStarted) {
2156       throw new ServerNotRunningYetException("Server is not running yet");
2157     }
2158   }
2159 
2160   void checkInitialized() throws PleaseHoldException, ServerNotRunningYetException {
2161     checkServiceStarted();
2162     if (!this.initialized) {
2163       throw new PleaseHoldException("Master is initializing");
2164     }
2165   }
2166 
2167   void checkNamespaceManagerReady() throws IOException {
2168     checkInitialized();
2169     if (tableNamespaceManager == null ||
2170         !tableNamespaceManager.isTableAvailableAndInitialized()) {
2171       throw new IOException("Table Namespace Manager not ready yet, try again later");
2172     }
2173   }
2174   /**
2175    * Report whether this master is currently the active master or not.
2176    * If not active master, we are parked on ZK waiting to become active.
2177    *
2178    * This method is used for testing.
2179    *
2180    * @return true if active master, false if not.
2181    */
2182   public boolean isActiveMaster() {
2183     return isActiveMaster;
2184   }
2185 
2186   /**
2187    * Report whether this master has completed with its initialization and is
2188    * ready.  If ready, the master is also the active master.  A standby master
2189    * is never ready.
2190    *
2191    * This method is used for testing.
2192    *
2193    * @return true if master is ready to go, false if not.
2194    */
2195   @Override
2196   public boolean isInitialized() {
2197     return initialized;
2198   }
2199 
2200   /**
2201    * ServerShutdownHandlerEnabled is set false before completing
2202    * assignMeta to prevent processing of ServerShutdownHandler.
2203    * @return true if assignMeta has completed;
2204    */
2205   @Override
2206   public boolean isServerShutdownHandlerEnabled() {
2207     return this.serverShutdownHandlerEnabled;
2208   }
2209 
2210   /**
2211    * Report whether this master has started initialization and is about to do meta region assignment
2212    * @return true if master is in initialization & about to assign hbase:meta regions
2213    */
2214   public boolean isInitializationStartsMetaRegionAssignment() {
2215     return this.initializationBeforeMetaAssignment;
2216   }
2217 
2218   public void assignRegion(HRegionInfo hri) {
2219     assignmentManager.assign(hri, true);
2220   }
2221 
2222   /**
2223    * Compute the average load across all region servers.
2224    * Currently, this uses a very naive computation - just uses the number of
2225    * regions being served, ignoring stats about number of requests.
2226    * @return the average load
2227    */
2228   public double getAverageLoad() {
2229     if (this.assignmentManager == null) {
2230       return 0;
2231     }
2232 
2233     RegionStates regionStates = this.assignmentManager.getRegionStates();
2234     if (regionStates == null) {
2235       return 0;
2236     }
2237     return regionStates.getAverageLoad();
2238   }
2239 
2240   @Override
2241   public boolean registerService(Service instance) {
2242     /*
2243      * No stacking of instances is allowed for a single service name
2244      */
2245     Descriptors.ServiceDescriptor serviceDesc = instance.getDescriptorForType();
2246     if (coprocessorServiceHandlers.containsKey(serviceDesc.getFullName())) {
2247       LOG.error("Coprocessor service "+serviceDesc.getFullName()+
2248           " already registered, rejecting request from "+instance
2249       );
2250       return false;
2251     }
2252 
2253     coprocessorServiceHandlers.put(serviceDesc.getFullName(), instance);
2254     if (LOG.isDebugEnabled()) {
2255       LOG.debug("Registered master coprocessor service: service="+serviceDesc.getFullName());
2256     }
2257     return true;
2258   }
2259 
2260   /**
2261    * Utility for constructing an instance of the passed HMaster class.
2262    * @param masterClass
2263    * @param conf
2264    * @return HMaster instance.
2265    */
2266   public static HMaster constructMaster(Class<? extends HMaster> masterClass,
2267       final Configuration conf, final CoordinatedStateManager cp)  {
2268     try {
2269       Constructor<? extends HMaster> c =
2270         masterClass.getConstructor(Configuration.class, CoordinatedStateManager.class);
2271       return c.newInstance(conf, cp);
2272     } catch (InvocationTargetException ite) {
2273       Throwable target = ite.getTargetException() != null?
2274         ite.getTargetException(): ite;
2275       if (target.getCause() != null) target = target.getCause();
2276       throw new RuntimeException("Failed construction of Master: " +
2277         masterClass.toString(), target);
2278     } catch (Exception e) {
2279       throw new RuntimeException("Failed construction of Master: " +
2280         masterClass.toString() + ((e.getCause() != null)?
2281           e.getCause().getMessage(): ""), e);
2282     }
2283   }
2284 
2285   /**
2286    * @see org.apache.hadoop.hbase.master.HMasterCommandLine
2287    */
2288   public static void main(String [] args) {
2289     VersionInfo.logVersion();
2290     new HMasterCommandLine(HMaster.class).doMain(args);
2291   }
2292 
2293   public HFileCleaner getHFileCleaner() {
2294     return this.hfileCleaner;
2295   }
2296 
2297   /**
2298    * Exposed for TESTING!
2299    * @return the underlying snapshot manager
2300    */
2301   public SnapshotManager getSnapshotManagerForTesting() {
2302     return this.snapshotManager;
2303   }
2304 
2305   @Override
2306   public void createNamespace(NamespaceDescriptor descriptor) throws IOException {
2307     TableName.isLegalNamespaceName(Bytes.toBytes(descriptor.getName()));
2308     checkNamespaceManagerReady();
2309     if (cpHost != null) {
2310       if (cpHost.preCreateNamespace(descriptor)) {
2311         return;
2312       }
2313     }
2314     LOG.info(getClientIdAuditPrefix() + " creating " + descriptor);
2315     tableNamespaceManager.create(descriptor);
2316     if (cpHost != null) {
2317       cpHost.postCreateNamespace(descriptor);
2318     }
2319   }
2320 
2321   @Override
2322   public void modifyNamespace(NamespaceDescriptor descriptor) throws IOException {
2323     TableName.isLegalNamespaceName(Bytes.toBytes(descriptor.getName()));
2324     checkNamespaceManagerReady();
2325     if (cpHost != null) {
2326       if (cpHost.preModifyNamespace(descriptor)) {
2327         return;
2328       }
2329     }
2330     LOG.info(getClientIdAuditPrefix() + " modify " + descriptor);
2331     tableNamespaceManager.update(descriptor);
2332     if (cpHost != null) {
2333       cpHost.postModifyNamespace(descriptor);
2334     }
2335   }
2336 
2337   @Override
2338   public void deleteNamespace(String name) throws IOException {
2339     checkNamespaceManagerReady();
2340     if (cpHost != null) {
2341       if (cpHost.preDeleteNamespace(name)) {
2342         return;
2343       }
2344     }
2345     LOG.info(getClientIdAuditPrefix() + " delete " + name);
2346     tableNamespaceManager.remove(name);
2347     if (cpHost != null) {
2348       cpHost.postDeleteNamespace(name);
2349     }
2350   }
2351 
2352   /**
2353    * Ensure that the specified namespace exists, otherwise throws a NamespaceNotFoundException
2354    *
2355    * @param name the namespace to check
2356    * @throws IOException if the namespace manager is not ready yet.
2357    * @throws NamespaceNotFoundException if the namespace does not exists
2358    */
2359   private void ensureNamespaceExists(final String name)
2360       throws IOException, NamespaceNotFoundException {
2361     checkNamespaceManagerReady();
2362     NamespaceDescriptor nsd = tableNamespaceManager.get(name);
2363     if (nsd == null) {
2364       throw new NamespaceNotFoundException(name);
2365     }
2366   }
2367 
2368   @Override
2369   public NamespaceDescriptor getNamespaceDescriptor(String name) throws IOException {
2370     checkNamespaceManagerReady();
2371 
2372     if (cpHost != null) {
2373       cpHost.preGetNamespaceDescriptor(name);
2374     }
2375 
2376     NamespaceDescriptor nsd = tableNamespaceManager.get(name);
2377     if (nsd == null) {
2378       throw new NamespaceNotFoundException(name);
2379     }
2380 
2381     if (cpHost != null) {
2382       cpHost.postGetNamespaceDescriptor(nsd);
2383     }
2384 
2385     return nsd;
2386   }
2387 
2388   @Override
2389   public List<NamespaceDescriptor> listNamespaceDescriptors() throws IOException {
2390     checkNamespaceManagerReady();
2391 
2392     final List<NamespaceDescriptor> descriptors = new ArrayList<NamespaceDescriptor>();
2393     boolean bypass = false;
2394     if (cpHost != null) {
2395       bypass = cpHost.preListNamespaceDescriptors(descriptors);
2396     }
2397 
2398     if (!bypass) {
2399       descriptors.addAll(tableNamespaceManager.list());
2400 
2401       if (cpHost != null) {
2402         cpHost.postListNamespaceDescriptors(descriptors);
2403       }
2404     }
2405     return descriptors;
2406   }
2407 
2408   @Override
2409   public List<HTableDescriptor> listTableDescriptorsByNamespace(String name) throws IOException {
2410     ensureNamespaceExists(name);
2411     return listTableDescriptors(name, null, null, true);
2412   }
2413 
2414   @Override
2415   public List<TableName> listTableNamesByNamespace(String name) throws IOException {
2416     ensureNamespaceExists(name);
2417     return listTableNames(name, null, true);
2418   }
2419 
2420   /**
2421    * Returns the list of table descriptors that match the specified request
2422    *
2423    * @param namespace the namespace to query, or null if querying for all
2424    * @param regex The regular expression to match against, or null if querying for all
2425    * @param tableNameList the list of table names, or null if querying for all
2426    * @param includeSysTables False to match only against userspace tables
2427    * @return the list of table descriptors
2428    */
2429   public List<HTableDescriptor> listTableDescriptors(final String namespace, final String regex,
2430       final List<TableName> tableNameList, final boolean includeSysTables)
2431       throws IOException {
2432     final List<HTableDescriptor> descriptors = new ArrayList<HTableDescriptor>();
2433 
2434     boolean bypass = false;
2435     if (cpHost != null) {
2436       bypass = cpHost.preGetTableDescriptors(tableNameList, descriptors);
2437       // method required for AccessController.
2438       bypass |= cpHost.preGetTableDescriptors(tableNameList, descriptors, regex);
2439     }
2440 
2441     if (!bypass) {
2442       if (tableNameList == null || tableNameList.size() == 0) {
2443         // request for all TableDescriptors
2444         Collection<HTableDescriptor> htds;
2445         if (namespace != null && namespace.length() > 0) {
2446           htds = tableDescriptors.getByNamespace(namespace).values();
2447         } else {
2448           htds = tableDescriptors.getAll().values();
2449         }
2450 
2451         for (HTableDescriptor desc: htds) {
2452           if (includeSysTables || !desc.getTableName().isSystemTable()) {
2453             descriptors.add(desc);
2454           }
2455         }
2456       } else {
2457         for (TableName s: tableNameList) {
2458           HTableDescriptor desc = tableDescriptors.get(s);
2459           if (desc != null) {
2460             descriptors.add(desc);
2461           }
2462         }
2463       }
2464 
2465       // Retains only those matched by regular expression.
2466       if (regex != null) {
2467         filterTablesByRegex(descriptors, Pattern.compile(regex));
2468       }
2469 
2470       if (cpHost != null) {
2471         cpHost.postGetTableDescriptors(descriptors);
2472         // method required for AccessController.
2473         cpHost.postGetTableDescriptors(tableNameList, descriptors, regex);
2474       }
2475     }
2476     return descriptors;
2477   }
2478 
2479   /**
2480    * Returns the list of table names that match the specified request
2481    * @param regex The regular expression to match against, or null if querying for all
2482    * @param namespace the namespace to query, or null if querying for all
2483    * @param includeSysTables False to match only against userspace tables
2484    * @return the list of table names
2485    */
2486   public List<TableName> listTableNames(final String namespace, final String regex,
2487       final boolean includeSysTables) throws IOException {
2488     final List<HTableDescriptor> descriptors = new ArrayList<HTableDescriptor>();
2489 
2490     boolean bypass = false;
2491     if (cpHost != null) {
2492       bypass = cpHost.preGetTableNames(descriptors, regex);
2493     }
2494 
2495     if (!bypass) {
2496       // get all descriptors
2497       Collection<HTableDescriptor> htds;
2498       if (namespace != null && namespace.length() > 0) {
2499         htds = tableDescriptors.getByNamespace(namespace).values();
2500       } else {
2501         htds = tableDescriptors.getAll().values();
2502       }
2503 
2504       for (HTableDescriptor htd: htds) {
2505         if (includeSysTables || !htd.getTableName().isSystemTable()) {
2506           descriptors.add(htd);
2507         }
2508       }
2509 
2510       // Retains only those matched by regular expression.
2511       if (regex != null) {
2512         filterTablesByRegex(descriptors, Pattern.compile(regex));
2513       }
2514 
2515       if (cpHost != null) {
2516         cpHost.postGetTableNames(descriptors, regex);
2517       }
2518     }
2519 
2520     List<TableName> result = new ArrayList<TableName>(descriptors.size());
2521     for (HTableDescriptor htd: descriptors) {
2522       result.add(htd.getTableName());
2523     }
2524     return result;
2525   }
2526 
2527 
2528   /**
2529    * Removes the table descriptors that don't match the pattern.
2530    * @param descriptors list of table descriptors to filter
2531    * @param pattern the regex to use
2532    */
2533   private static void filterTablesByRegex(final Collection<HTableDescriptor> descriptors,
2534       final Pattern pattern) {
2535     final String defaultNS = NamespaceDescriptor.DEFAULT_NAMESPACE_NAME_STR;
2536     Iterator<HTableDescriptor> itr = descriptors.iterator();
2537     while (itr.hasNext()) {
2538       HTableDescriptor htd = itr.next();
2539       String tableName = htd.getTableName().getNameAsString();
2540       boolean matched = pattern.matcher(tableName).matches();
2541       if (!matched && htd.getTableName().getNamespaceAsString().equals(defaultNS)) {
2542         matched = pattern.matcher(defaultNS + TableName.NAMESPACE_DELIM + tableName).matches();
2543       }
2544       if (!matched) {
2545         itr.remove();
2546       }
2547     }
2548   }
2549 
2550   @Override
2551   public long getLastMajorCompactionTimestamp(TableName table) throws IOException {
2552     return getClusterStatus().getLastMajorCompactionTsForTable(table);
2553   }
2554 
2555   @Override
2556   public long getLastMajorCompactionTimestampForRegion(byte[] regionName) throws IOException {
2557     return getClusterStatus().getLastMajorCompactionTsForRegion(regionName);
2558   }
2559 
2560   /**
2561    * Queries the state of the {@link LoadBalancerTracker}. If the balancer is not initialized,
2562    * false is returned.
2563    *
2564    * @return The state of the load balancer, or false if the load balancer isn't defined.
2565    */
2566   public boolean isBalancerOn() {
2567     if (null == loadBalancerTracker) return false;
2568     return loadBalancerTracker.isBalancerOn();
2569   }
2570 
2571   /**
2572    * Fetch the configured {@link LoadBalancer} class name. If none is set, a default is returned.
2573    *
2574    * @return The name of the {@link LoadBalancer} in use.
2575    */
2576   public String getLoadBalancerClassName() {
2577     return conf.get(HConstants.HBASE_MASTER_LOADBALANCER_CLASS, LoadBalancerFactory
2578         .getDefaultLoadBalancerClass().getName());
2579   }
2580 }