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