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