1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.master;
21
22 import java.io.IOException;
23 import java.lang.reflect.Constructor;
24 import java.lang.reflect.InvocationTargetException;
25 import java.net.InetSocketAddress;
26 import java.net.UnknownHostException;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.concurrent.atomic.AtomicReference;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.apache.hadoop.conf.Configuration;
35 import org.apache.hadoop.hbase.Chore;
36 import org.apache.hadoop.hbase.ClusterStatus;
37 import org.apache.hadoop.hbase.HColumnDescriptor;
38 import org.apache.hadoop.hbase.HConstants;
39 import org.apache.hadoop.hbase.HMsg;
40 import org.apache.hadoop.hbase.HRegionInfo;
41 import org.apache.hadoop.hbase.HServerAddress;
42 import org.apache.hadoop.hbase.HServerInfo;
43 import org.apache.hadoop.hbase.HTableDescriptor;
44 import org.apache.hadoop.hbase.MasterNotRunningException;
45 import org.apache.hadoop.hbase.NotAllMetaRegionsOnlineException;
46 import org.apache.hadoop.hbase.Server;
47 import org.apache.hadoop.hbase.TableExistsException;
48 import org.apache.hadoop.hbase.TableNotDisabledException;
49 import org.apache.hadoop.hbase.TableNotFoundException;
50 import org.apache.hadoop.hbase.UnknownRegionException;
51 import org.apache.hadoop.hbase.catalog.CatalogTracker;
52 import org.apache.hadoop.hbase.catalog.MetaEditor;
53 import org.apache.hadoop.hbase.catalog.MetaReader;
54 import org.apache.hadoop.hbase.client.HConnection;
55 import org.apache.hadoop.hbase.client.HConnectionManager;
56 import org.apache.hadoop.hbase.client.MetaScanner;
57 import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitor;
58 import org.apache.hadoop.hbase.client.Result;
59 import org.apache.hadoop.hbase.executor.ExecutorService;
60 import org.apache.hadoop.hbase.executor.ExecutorService.ExecutorType;
61 import org.apache.hadoop.hbase.ipc.HBaseRPC;
62 import org.apache.hadoop.hbase.ipc.HBaseRPCProtocolVersion;
63 import org.apache.hadoop.hbase.ipc.HBaseServer;
64 import org.apache.hadoop.hbase.ipc.HMasterInterface;
65 import org.apache.hadoop.hbase.ipc.HMasterRegionInterface;
66 import org.apache.hadoop.hbase.master.LoadBalancer.RegionPlan;
67 import org.apache.hadoop.hbase.master.handler.DeleteTableHandler;
68 import org.apache.hadoop.hbase.master.handler.DisableTableHandler;
69 import org.apache.hadoop.hbase.master.handler.EnableTableHandler;
70 import org.apache.hadoop.hbase.master.handler.ModifyTableHandler;
71 import org.apache.hadoop.hbase.master.handler.TableAddFamilyHandler;
72 import org.apache.hadoop.hbase.master.handler.TableDeleteFamilyHandler;
73 import org.apache.hadoop.hbase.master.handler.TableModifyFamilyHandler;
74 import org.apache.hadoop.hbase.master.metrics.MasterMetrics;
75 import org.apache.hadoop.hbase.regionserver.HRegion;
76 import org.apache.hadoop.hbase.replication.regionserver.Replication;
77 import org.apache.hadoop.hbase.security.User;
78 import org.apache.hadoop.hbase.util.Bytes;
79 import org.apache.hadoop.hbase.util.InfoServer;
80 import org.apache.hadoop.hbase.util.Pair;
81 import org.apache.hadoop.hbase.util.Sleeper;
82 import org.apache.hadoop.hbase.util.Strings;
83 import org.apache.hadoop.hbase.util.Threads;
84 import org.apache.hadoop.hbase.util.VersionInfo;
85 import org.apache.hadoop.hbase.zookeeper.ClusterStatusTracker;
86 import org.apache.hadoop.hbase.zookeeper.RegionServerTracker;
87 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
88 import org.apache.hadoop.io.MapWritable;
89 import org.apache.hadoop.io.Text;
90 import org.apache.hadoop.net.DNS;
91 import org.apache.zookeeper.KeeperException;
92 import org.apache.zookeeper.Watcher;
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111 public class HMaster extends Thread
112 implements HMasterInterface, HMasterRegionInterface, MasterServices, Server {
113 private static final Log LOG = LogFactory.getLog(HMaster.class.getName());
114
115
116
117 public static final String MASTER = "master";
118
119
120 private final Configuration conf;
121
122 private InfoServer infoServer;
123
124
125 private ZooKeeperWatcher zooKeeper;
126
127 private ActiveMasterManager activeMasterManager;
128
129 private RegionServerTracker regionServerTracker;
130
131
132 private final HBaseServer rpcServer;
133
134 private final HServerAddress address;
135
136 private final MasterMetrics metrics;
137
138 private MasterFileSystem fileSystemManager;
139
140 private HConnection connection;
141
142
143 private ServerManager serverManager;
144
145
146 AssignmentManager assignmentManager;
147
148 private CatalogTracker catalogTracker;
149
150 private ClusterStatusTracker clusterStatusTracker;
151
152
153
154 private volatile boolean stopped = false;
155
156 private volatile boolean abort = false;
157
158 private volatile boolean isActiveMaster = false;
159
160 private volatile boolean initialized = false;
161
162
163 ExecutorService executorService;
164
165 private LoadBalancer balancer;
166 private Thread balancerChore;
167
168 private volatile boolean balanceSwitch = true;
169
170 private Thread catalogJanitorChore;
171 private LogCleaner logCleaner;
172
173
174
175
176
177
178
179
180
181
182
183
184
185 public HMaster(final Configuration conf)
186 throws IOException, KeeperException, InterruptedException {
187 this.conf = conf;
188
189
190
191
192
193 HServerAddress a = new HServerAddress(getMyAddress(this.conf));
194 int numHandlers = conf.getInt("hbase.regionserver.handler.count", 10);
195 this.rpcServer = HBaseRPC.getServer(this,
196 new Class<?>[]{HMasterInterface.class, HMasterRegionInterface.class},
197 a.getBindAddress(), a.getPort(),
198 numHandlers,
199 0,
200 false, conf,
201 0);
202 this.address = new HServerAddress(rpcServer.getListenerAddress());
203
204
205 User.login(conf, "hbase.master.keytab.file",
206 "hbase.master.kerberos.principal", this.address.getHostname());
207
208
209 setName(MASTER + "-" + this.address);
210
211 Replication.decorateMasterConfiguration(this.conf);
212
213 this.rpcServer.startThreads();
214
215
216
217 if (this.conf.get("mapred.task.id") == null) {
218 this.conf.set("mapred.task.id", "hb_m_" + this.address.toString() +
219 "_" + System.currentTimeMillis());
220 }
221
222 this.zooKeeper = new ZooKeeperWatcher(conf, MASTER + ":" +
223 address.getPort(), this);
224
225 this.metrics = new MasterMetrics(getServerName());
226 }
227
228
229
230
231
232
233
234
235 private static void stallIfBackupMaster(final Configuration c,
236 final ActiveMasterManager amm)
237 throws InterruptedException {
238
239 if (!c.getBoolean(HConstants.MASTER_TYPE_BACKUP,
240 HConstants.DEFAULT_MASTER_TYPE_BACKUP)) {
241 return;
242 }
243 LOG.debug("HMaster started in backup mode. " +
244 "Stalling until master znode is written.");
245
246
247 while (!amm.isActiveMaster()) {
248 LOG.debug("Waiting for master address ZNode to be written " +
249 "(Also watching cluster state node)");
250 Thread.sleep(c.getInt("zookeeper.session.timeout", 180 * 1000));
251 }
252 }
253
254
255
256
257
258
259
260
261
262
263 @Override
264 public void run() {
265 try {
266
267
268
269
270
271
272
273
274
275
276 this.activeMasterManager = new ActiveMasterManager(zooKeeper, address, this);
277 this.zooKeeper.registerListener(activeMasterManager);
278 stallIfBackupMaster(this.conf, this.activeMasterManager);
279 this.activeMasterManager.blockUntilBecomingActiveMaster();
280
281 if (!this.stopped) {
282 finishInitialization();
283 loop();
284 }
285 } catch (Throwable t) {
286 abort("Unhandled exception. Starting shutdown.", t);
287 } finally {
288 stopChores();
289
290
291 if (!this.abort && this.serverManager != null &&
292 this.serverManager.isClusterShutdown()) {
293 this.serverManager.letRegionServersShutdown();
294 }
295 stopServiceThreads();
296
297 if (this.activeMasterManager != null) this.activeMasterManager.stop();
298 if (this.catalogTracker != null) this.catalogTracker.stop();
299 if (this.serverManager != null) this.serverManager.stop();
300 if (this.assignmentManager != null) this.assignmentManager.stop();
301 HConnectionManager.deleteConnection(this.conf, true);
302 this.zooKeeper.close();
303 }
304 LOG.info("HMaster main thread exiting");
305 }
306
307 private void loop() {
308
309 Sleeper sleeper = new Sleeper(1000, this);
310 while (!this.stopped) {
311 sleeper.sleep();
312 }
313 }
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334 private void finishInitialization()
335 throws IOException, InterruptedException, KeeperException {
336
337 isActiveMaster = true;
338
339
340
341
342
343
344
345
346 this.fileSystemManager = new MasterFileSystem(this, metrics);
347 this.connection = HConnectionManager.getConnection(conf);
348 this.executorService = new ExecutorService(getServerName());
349
350 this.serverManager = new ServerManager(this, this, metrics);
351
352 this.catalogTracker = new CatalogTracker(this.zooKeeper, this.connection,
353 this, conf.getInt("hbase.master.catalog.timeout", Integer.MAX_VALUE));
354 this.catalogTracker.start();
355
356 this.assignmentManager = new AssignmentManager(this, serverManager,
357 this.catalogTracker, this.executorService);
358 this.balancer = new LoadBalancer(conf);
359 zooKeeper.registerListenerFirst(assignmentManager);
360
361 this.regionServerTracker = new RegionServerTracker(zooKeeper, this,
362 this.serverManager);
363 this.regionServerTracker.start();
364
365
366
367 this.clusterStatusTracker = new ClusterStatusTracker(getZooKeeper(), this);
368 this.clusterStatusTracker.start();
369 boolean wasUp = this.clusterStatusTracker.isClusterUp();
370 if (!wasUp) this.clusterStatusTracker.setClusterUp();
371
372 LOG.info("Server active/primary master; " + this.address +
373 ", sessionid=0x" +
374 Long.toHexString(this.zooKeeper.getZooKeeper().getSessionId()) +
375 ", cluster-up flag was=" + wasUp);
376
377
378 startServiceThreads();
379
380
381 int regionCount = this.serverManager.waitForRegionServers();
382
383
384 this.fileSystemManager.
385 splitLogAfterStartup(this.serverManager.getOnlineServers());
386
387
388 assignRootAndMeta();
389
390
391
392
393
394
395 if (regionCount == 0) {
396 LOG.info("Master startup proceeding: cluster startup");
397 this.assignmentManager.cleanoutUnassigned();
398 this.assignmentManager.assignAllUserRegions();
399 } else {
400 LOG.info("Master startup proceeding: master failover");
401 this.assignmentManager.processFailover();
402 }
403
404
405
406 this.balancerChore = getAndStartBalancerChore(this);
407 this.catalogJanitorChore =
408 Threads.setDaemonThreadRunning(new CatalogJanitor(this, this));
409
410 LOG.info("Master has completed initialization");
411 initialized = true;
412 }
413
414
415
416
417
418
419
420
421
422 int assignRootAndMeta()
423 throws InterruptedException, IOException, KeeperException {
424 int assigned = 0;
425 long timeout = this.conf.getLong("hbase.catalog.verification.timeout", 1000);
426
427
428 boolean rit = this.assignmentManager.
429 processRegionInTransitionAndBlockUntilAssigned(HRegionInfo.ROOT_REGIONINFO);
430 if (!catalogTracker.verifyRootRegionLocation(timeout)) {
431 this.assignmentManager.assignRoot();
432 this.catalogTracker.waitForRoot();
433 assigned++;
434 }
435 LOG.info("-ROOT- assigned=" + assigned + ", rit=" + rit +
436 ", location=" + catalogTracker.getRootLocation());
437
438
439 rit = this.assignmentManager.
440 processRegionInTransitionAndBlockUntilAssigned(HRegionInfo.FIRST_META_REGIONINFO);
441 if (!this.catalogTracker.verifyMetaRegionLocation(timeout)) {
442 this.assignmentManager.assignMeta();
443 this.catalogTracker.waitForMeta();
444
445
446 this.assignmentManager.waitForAssignment(HRegionInfo.FIRST_META_REGIONINFO);
447 assigned++;
448 }
449 LOG.info(".META. assigned=" + assigned + ", rit=" + rit +
450 ", location=" + catalogTracker.getMetaLocation());
451 return assigned;
452 }
453
454
455
456
457
458 private static String getMyAddress(final Configuration c)
459 throws UnknownHostException {
460
461 String s = Strings.domainNamePointerToHostName(DNS.getDefaultHost(c.get(
462 "hbase.master.dns.interface", "default"), c.get(
463 "hbase.master.dns.nameserver", "default")));
464 s += ":" + c.get(HConstants.MASTER_PORT,
465 Integer.toString(HConstants.DEFAULT_MASTER_PORT));
466 return s;
467 }
468
469
470 public HServerAddress getMasterAddress() {
471 return this.address;
472 }
473
474 public long getProtocolVersion(String protocol, long clientVersion) {
475 return HBaseRPCProtocolVersion.versionID;
476 }
477
478
479 public InfoServer getInfoServer() {
480 return this.infoServer;
481 }
482
483 @Override
484 public Configuration getConfiguration() {
485 return this.conf;
486 }
487
488 @Override
489 public ServerManager getServerManager() {
490 return this.serverManager;
491 }
492
493 @Override
494 public ExecutorService getExecutorService() {
495 return this.executorService;
496 }
497
498 @Override
499 public MasterFileSystem getMasterFileSystem() {
500 return this.fileSystemManager;
501 }
502
503
504
505
506
507 public ZooKeeperWatcher getZooKeeperWatcher() {
508 return this.zooKeeper;
509 }
510
511
512
513
514
515
516
517
518 private void startServiceThreads() throws IOException{
519
520
521 this.executorService.startExecutorService(ExecutorType.MASTER_OPEN_REGION,
522 conf.getInt("hbase.master.executor.openregion.threads", 5));
523 this.executorService.startExecutorService(ExecutorType.MASTER_CLOSE_REGION,
524 conf.getInt("hbase.master.executor.closeregion.threads", 5));
525 this.executorService.startExecutorService(ExecutorType.MASTER_SERVER_OPERATIONS,
526 conf.getInt("hbase.master.executor.serverops.threads", 3));
527 this.executorService.startExecutorService(ExecutorType.MASTER_META_SERVER_OPERATIONS,
528 conf.getInt("hbase.master.executor.serverops.threads", 5));
529
530
531
532
533 this.executorService.startExecutorService(ExecutorType.MASTER_TABLE_OPERATIONS, 1);
534
535
536 String n = Thread.currentThread().getName();
537 this.logCleaner =
538 new LogCleaner(conf.getInt("hbase.master.cleaner.interval", 60 * 1000),
539 this, conf, getMasterFileSystem().getFileSystem(),
540 getMasterFileSystem().getOldLogDir());
541 Threads.setDaemonThreadRunning(logCleaner, n + ".oldLogCleaner");
542
543
544 int port = this.conf.getInt("hbase.master.info.port", 60010);
545 if (port >= 0) {
546 String a = this.conf.get("hbase.master.info.bindAddress", "0.0.0.0");
547 this.infoServer = new InfoServer(MASTER, a, port, false);
548 this.infoServer.setAttribute(MASTER, this);
549 this.infoServer.start();
550 }
551
552
553 this.rpcServer.openServer();
554 if (LOG.isDebugEnabled()) {
555 LOG.debug("Started service threads");
556 }
557
558 }
559
560 private void stopServiceThreads() {
561 if (LOG.isDebugEnabled()) {
562 LOG.debug("Stopping service threads");
563 }
564 if (this.rpcServer != null) this.rpcServer.stop();
565
566 if (this.logCleaner!= null) this.logCleaner.interrupt();
567 if (this.infoServer != null) {
568 LOG.info("Stopping infoServer");
569 try {
570 this.infoServer.stop();
571 } catch (Exception ex) {
572 ex.printStackTrace();
573 }
574 }
575 if (this.executorService != null) this.executorService.shutdown();
576 }
577
578 private static Thread getAndStartBalancerChore(final HMaster master) {
579 String name = master.getServerName() + "-BalancerChore";
580 int period = master.getConfiguration().getInt("hbase.balancer.period", 300000);
581
582 Chore chore = new Chore(name, period, master) {
583 @Override
584 protected void chore() {
585 master.balance();
586 }
587 };
588 return Threads.setDaemonThreadRunning(chore);
589 }
590
591 private void stopChores() {
592 if (this.balancerChore != null) {
593 this.balancerChore.interrupt();
594 }
595 if (this.catalogJanitorChore != null) {
596 this.catalogJanitorChore.interrupt();
597 }
598 }
599
600 @Override
601 public MapWritable regionServerStartup(final HServerInfo serverInfo,
602 final long serverCurrentTime)
603 throws IOException {
604
605
606
607
608
609 InetSocketAddress address = new InetSocketAddress(
610 HBaseServer.getRemoteIp().getHostName(),
611 serverInfo.getServerAddress().getPort());
612 serverInfo.setServerAddress(new HServerAddress(address));
613
614
615 this.serverManager.regionServerStartup(serverInfo, serverCurrentTime);
616
617 MapWritable mw = createConfigurationSubset();
618 mw.put(new Text("hbase.regionserver.address"),
619 serverInfo.getServerAddress());
620 return mw;
621 }
622
623
624
625
626
627 protected MapWritable createConfigurationSubset() {
628 MapWritable mw = addConfig(new MapWritable(), HConstants.HBASE_DIR);
629 return addConfig(mw, "fs.default.name");
630 }
631
632 private MapWritable addConfig(final MapWritable mw, final String key) {
633 mw.put(new Text(key), new Text(this.conf.get(key)));
634 return mw;
635 }
636
637 @Override
638 public HMsg [] regionServerReport(HServerInfo serverInfo, HMsg msgs[],
639 HRegionInfo[] mostLoadedRegions)
640 throws IOException {
641 return adornRegionServerAnswer(serverInfo,
642 this.serverManager.regionServerReport(serverInfo, msgs, mostLoadedRegions));
643 }
644
645
646
647
648
649
650
651
652 protected HMsg [] adornRegionServerAnswer(final HServerInfo hsi,
653 final HMsg [] msgs) throws IOException {
654 return msgs;
655 }
656
657 public boolean isMasterRunning() {
658 return !isStopped();
659 }
660
661 @Override
662 public boolean balance() {
663
664 if (!this.balanceSwitch) return false;
665 synchronized (this.balancer) {
666
667 if (this.assignmentManager.isRegionsInTransition()) {
668 LOG.debug("Not running balancer because " +
669 this.assignmentManager.getRegionsInTransition().size() +
670 " region(s) in transition: " +
671 org.apache.commons.lang.StringUtils.
672 abbreviate(this.assignmentManager.getRegionsInTransition().toString(), 256));
673 return false;
674 }
675 if (this.serverManager.areDeadServersInProgress()) {
676 LOG.debug("Not running balancer because processing dead regionserver(s): " +
677 this.serverManager.getDeadServers());
678 return false;
679 }
680 Map<HServerInfo, List<HRegionInfo>> assignments =
681 this.assignmentManager.getAssignments();
682
683 for (Map.Entry<String, HServerInfo> e:
684 this.serverManager.getOnlineServers().entrySet()) {
685 HServerInfo hsi = e.getValue();
686 if (!assignments.containsKey(hsi)) {
687 assignments.put(hsi, new ArrayList<HRegionInfo>());
688 }
689 }
690 List<RegionPlan> plans = this.balancer.balanceCluster(assignments);
691 if (plans != null && !plans.isEmpty()) {
692 for (RegionPlan plan: plans) {
693 LOG.info("balance " + plan);
694 this.assignmentManager.balance(plan);
695 }
696 }
697 }
698 return true;
699 }
700
701 @Override
702 public boolean balanceSwitch(final boolean b) {
703 boolean oldValue = this.balanceSwitch;
704 this.balanceSwitch = b;
705 LOG.info("Balance=" + b);
706 return oldValue;
707 }
708
709
710
711
712
713
714
715 public void setCatalogJanitorEnabled(final boolean b) {
716 ((CatalogJanitor)this.catalogJanitorChore).setEnabled(b);
717 }
718
719 @Override
720 public void move(final byte[] encodedRegionName, final byte[] destServerName)
721 throws UnknownRegionException {
722 Pair<HRegionInfo, HServerInfo> p =
723 this.assignmentManager.getAssignment(encodedRegionName);
724 if (p == null)
725 throw new UnknownRegionException(Bytes.toStringBinary(encodedRegionName));
726 HRegionInfo hri = p.getFirst();
727 HServerInfo dest = null;
728 if (destServerName == null || destServerName.length == 0) {
729 LOG.info("Passed destination servername is null/empty so " +
730 "choosing a server at random");
731 this.assignmentManager.clearRegionPlan(hri);
732
733 this.assignmentManager.unassign(hri);
734 } else {
735 dest = this.serverManager.getServerInfo(new String(destServerName));
736 RegionPlan rp = new RegionPlan(p.getFirst(), p.getSecond(), dest);
737 this.assignmentManager.balance(rp);
738 }
739 }
740
741 public void createTable(HTableDescriptor desc, byte [][] splitKeys)
742 throws IOException {
743 createTable(desc, splitKeys, false);
744 }
745
746 public void createTable(HTableDescriptor desc, byte [][] splitKeys,
747 boolean sync)
748 throws IOException {
749 if (!isMasterRunning()) {
750 throw new MasterNotRunningException();
751 }
752 HRegionInfo [] newRegions = null;
753 if(splitKeys == null || splitKeys.length == 0) {
754 newRegions = new HRegionInfo [] { new HRegionInfo(desc, null, null) };
755 } else {
756 int numRegions = splitKeys.length + 1;
757 newRegions = new HRegionInfo[numRegions];
758 byte [] startKey = null;
759 byte [] endKey = null;
760 for(int i=0;i<numRegions;i++) {
761 endKey = (i == splitKeys.length) ? null : splitKeys[i];
762 newRegions[i] = new HRegionInfo(desc, startKey, endKey);
763 startKey = endKey;
764 }
765 }
766 int timeout = conf.getInt("hbase.client.catalog.timeout", 10000);
767
768 try {
769 if(catalogTracker.waitForMeta(timeout) == null) {
770 throw new NotAllMetaRegionsOnlineException();
771 }
772 } catch (InterruptedException e) {
773 LOG.warn("Interrupted waiting for meta availability", e);
774 throw new IOException(e);
775 }
776 createTable(newRegions, sync);
777 }
778
779 private synchronized void createTable(final HRegionInfo [] newRegions,
780 final boolean sync)
781 throws IOException {
782 String tableName = newRegions[0].getTableDesc().getNameAsString();
783 if(MetaReader.tableExists(catalogTracker, tableName)) {
784 throw new TableExistsException(tableName);
785 }
786 for (HRegionInfo newRegion : newRegions) {
787
788 try {
789 assignmentManager.getZKTable().setEnabledTable(tableName);
790 } catch (KeeperException e) {
791 throw new IOException("Unable to ensure that the table will be" +
792 " enabled because of a ZooKeeper issue", e);
793 }
794
795
796 HRegion region = HRegion.createHRegion(newRegion,
797 fileSystemManager.getRootDir(), conf);
798
799
800 MetaEditor.addRegionToMeta(catalogTracker, region.getRegionInfo());
801
802
803 region.close();
804 region.getLog().closeAndDelete();
805 }
806
807
808 if (newRegions.length == 1) {
809 this.assignmentManager.assign(newRegions[0], true);
810 } else {
811 List<HServerInfo> servers = serverManager.getOnlineServersList();
812 this.assignmentManager.bulkAssignUserRegions(newRegions, servers, sync);
813 }
814
815
816 if (sync) {
817 LOG.debug("Waiting for " + newRegions.length + " region(s) to be assigned");
818 for (HRegionInfo regionInfo : newRegions) {
819 try {
820 this.assignmentManager.waitForAssignment(regionInfo);
821 } catch (InterruptedException e) {
822 LOG.info("Interrupted waiting for region to be assigned during " +
823 "create table call", e);
824 Thread.currentThread().interrupt();
825 return;
826 }
827 }
828 }
829 }
830
831 private static boolean isCatalogTable(final byte [] tableName) {
832 return Bytes.equals(tableName, HConstants.ROOT_TABLE_NAME) ||
833 Bytes.equals(tableName, HConstants.META_TABLE_NAME);
834 }
835
836 public void deleteTable(final byte [] tableName) throws IOException {
837 this.executorService.submit(new DeleteTableHandler(tableName, this, this));
838 }
839
840 public void addColumn(byte [] tableName, HColumnDescriptor column)
841 throws IOException {
842 new TableAddFamilyHandler(tableName, column, this, this).process();
843 }
844
845 public void modifyColumn(byte [] tableName, HColumnDescriptor descriptor)
846 throws IOException {
847 new TableModifyFamilyHandler(tableName, descriptor, this, this).process();
848 }
849
850 public void deleteColumn(final byte [] tableName, final byte [] c)
851 throws IOException {
852 new TableDeleteFamilyHandler(tableName, c, this, this).process();
853 }
854
855 public void enableTable(final byte [] tableName) throws IOException {
856 this.executorService.submit(new EnableTableHandler(this, tableName,
857 catalogTracker, assignmentManager));
858 }
859
860 public void disableTable(final byte [] tableName) throws IOException {
861 this.executorService.submit(new DisableTableHandler(this, tableName,
862 catalogTracker, assignmentManager));
863 }
864
865
866
867
868
869
870
871 Pair<HRegionInfo,HServerAddress> getTableRegionForRow(
872 final byte [] tableName, final byte [] rowKey)
873 throws IOException {
874 final AtomicReference<Pair<HRegionInfo, HServerAddress>> result =
875 new AtomicReference<Pair<HRegionInfo, HServerAddress>>(null);
876
877 MetaScannerVisitor visitor =
878 new MetaScannerVisitor() {
879 @Override
880 public boolean processRow(Result data) throws IOException {
881 if (data == null || data.size() <= 0) {
882 return true;
883 }
884 Pair<HRegionInfo, HServerAddress> pair =
885 MetaReader.metaRowToRegionPair(data);
886 if (pair == null) {
887 return false;
888 }
889 if (!Bytes.equals(pair.getFirst().getTableDesc().getName(),
890 tableName)) {
891 return false;
892 }
893 result.set(pair);
894 return true;
895 }
896 };
897
898 MetaScanner.metaScan(conf, visitor, tableName, rowKey, 1);
899 return result.get();
900 }
901
902 @Override
903 public void modifyTable(final byte[] tableName, HTableDescriptor htd)
904 throws IOException {
905 this.executorService.submit(new ModifyTableHandler(tableName, htd, this, this));
906 }
907
908 @Override
909 public void checkTableModifiable(final byte [] tableName)
910 throws IOException {
911 String tableNameStr = Bytes.toString(tableName);
912 if (isCatalogTable(tableName)) {
913 throw new IOException("Can't modify catalog tables");
914 }
915 if (!MetaReader.tableExists(getCatalogTracker(), tableNameStr)) {
916 throw new TableNotFoundException(tableNameStr);
917 }
918 if (!getAssignmentManager().getZKTable().
919 isDisabledTable(Bytes.toString(tableName))) {
920 throw new TableNotDisabledException(tableName);
921 }
922 }
923
924 public void clearFromTransition(HRegionInfo hri) {
925 if (this.assignmentManager.isRegionInTransition(hri) != null) {
926 this.assignmentManager.clearRegionFromTransition(hri);
927 }
928 }
929
930
931
932 public ClusterStatus getClusterStatus() {
933 ClusterStatus status = new ClusterStatus();
934 status.setHBaseVersion(VersionInfo.getVersion());
935 status.setServerInfo(serverManager.getOnlineServers().values());
936 status.setDeadServers(serverManager.getDeadServers());
937 status.setRegionsInTransition(assignmentManager.getRegionsInTransition());
938 return status;
939 }
940
941 @Override
942 public void abort(final String msg, final Throwable t) {
943 if (t != null) LOG.fatal(msg, t);
944 else LOG.fatal(msg);
945 this.abort = true;
946 stop("Aborting");
947 }
948
949 @Override
950 public ZooKeeperWatcher getZooKeeper() {
951 return zooKeeper;
952 }
953
954 @Override
955 public String getServerName() {
956 return address.toString();
957 }
958
959 @Override
960 public CatalogTracker getCatalogTracker() {
961 return catalogTracker;
962 }
963
964 @Override
965 public AssignmentManager getAssignmentManager() {
966 return this.assignmentManager;
967 }
968
969 @Override
970 public void shutdown() {
971 this.serverManager.shutdownCluster();
972 try {
973 this.clusterStatusTracker.setClusterDown();
974 } catch (KeeperException e) {
975 LOG.error("ZooKeeper exception trying to set cluster as down in ZK", e);
976 }
977 }
978
979 @Override
980 public void stopMaster() {
981 stop("Stopped by " + Thread.currentThread().getName());
982 }
983
984 @Override
985 public void stop(final String why) {
986 LOG.info(why);
987 this.stopped = true;
988
989 synchronized (this.activeMasterManager.clusterHasActiveMaster) {
990 this.activeMasterManager.clusterHasActiveMaster.notifyAll();
991 }
992 }
993
994 @Override
995 public boolean isStopped() {
996 return this.stopped;
997 }
998
999
1000
1001
1002
1003
1004
1005
1006
1007 public boolean isActiveMaster() {
1008 return isActiveMaster;
1009 }
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020 public boolean isInitialized() {
1021 return initialized;
1022 }
1023
1024 @Override
1025 public void assign(final byte [] regionName, final boolean force)
1026 throws IOException {
1027 Pair<HRegionInfo, HServerAddress> pair =
1028 MetaReader.getRegion(this.catalogTracker, regionName);
1029 if (pair == null) throw new UnknownRegionException(Bytes.toString(regionName));
1030 assignRegion(pair.getFirst());
1031 }
1032
1033 public void assignRegion(HRegionInfo hri) {
1034 assignmentManager.assign(hri, true);
1035 }
1036
1037 @Override
1038 public void unassign(final byte [] regionName, final boolean force)
1039 throws IOException {
1040 Pair<HRegionInfo, HServerAddress> pair =
1041 MetaReader.getRegion(this.catalogTracker, regionName);
1042 if (pair == null) throw new UnknownRegionException(Bytes.toStringBinary(regionName));
1043 HRegionInfo hri = pair.getFirst();
1044 if (force) this.assignmentManager.clearRegionFromTransition(hri);
1045 this.assignmentManager.unassign(hri, force);
1046 }
1047
1048
1049
1050
1051
1052
1053
1054 public static HMaster constructMaster(Class<? extends HMaster> masterClass,
1055 final Configuration conf) {
1056 try {
1057 Constructor<? extends HMaster> c =
1058 masterClass.getConstructor(Configuration.class);
1059 return c.newInstance(conf);
1060 } catch (InvocationTargetException ite) {
1061 Throwable target = ite.getTargetException() != null?
1062 ite.getTargetException(): ite;
1063 if (target.getCause() != null) target = target.getCause();
1064 throw new RuntimeException("Failed construction of Master: " +
1065 masterClass.toString(), target);
1066 } catch (Exception e) {
1067 throw new RuntimeException("Failed construction of Master: " +
1068 masterClass.toString() + ((e.getCause() != null)?
1069 e.getCause().getMessage(): ""), e);
1070 }
1071 }
1072
1073
1074
1075
1076
1077 public static void main(String [] args) throws Exception {
1078 new HMasterCommandLine(HMaster.class).doMain(args);
1079 }
1080 }