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