001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018 package org.apache.hadoop.hdfs.server.namenode;
019
020 import java.io.File;
021 import java.io.IOException;
022 import java.io.PrintStream;
023 import java.net.InetSocketAddress;
024 import java.net.URI;
025 import java.security.PrivilegedExceptionAction;
026 import java.util.ArrayList;
027 import java.util.Arrays;
028 import java.util.Collection;
029 import java.util.Iterator;
030 import java.util.List;
031 import org.apache.commons.logging.Log;
032 import org.apache.commons.logging.LogFactory;
033 import org.apache.hadoop.HadoopIllegalArgumentException;
034 import org.apache.hadoop.classification.InterfaceAudience;
035 import org.apache.hadoop.conf.Configuration;
036 import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
037 import org.apache.hadoop.ha.HAServiceProtocol.StateChangeRequestInfo;
038 import org.apache.hadoop.ha.HAServiceStatus;
039 import org.apache.hadoop.ha.HealthCheckFailedException;
040 import org.apache.hadoop.ha.ServiceFailedException;
041 import org.apache.hadoop.fs.FileSystem;
042 import org.apache.hadoop.fs.FileUtil;
043 import org.apache.hadoop.fs.Trash;
044 import static org.apache.hadoop.hdfs.DFSConfigKeys.*;
045 import static org.apache.hadoop.util.ExitUtil.terminate;
046 import static org.apache.hadoop.util.ToolRunner.confirmPrompt;
047
048 import org.apache.hadoop.hdfs.DFSConfigKeys;
049 import org.apache.hadoop.hdfs.DFSUtil;
050 import org.apache.hadoop.hdfs.HAUtil;
051 import org.apache.hadoop.hdfs.HdfsConfiguration;
052 import org.apache.hadoop.hdfs.protocol.ClientProtocol;
053 import org.apache.hadoop.hdfs.protocol.HdfsConstants;
054 import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NamenodeRole;
055 import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
056 import org.apache.hadoop.hdfs.server.namenode.ha.ActiveState;
057 import org.apache.hadoop.hdfs.server.namenode.ha.BootstrapStandby;
058 import org.apache.hadoop.hdfs.server.namenode.ha.HAContext;
059 import org.apache.hadoop.hdfs.server.namenode.ha.HAState;
060 import org.apache.hadoop.hdfs.server.namenode.ha.StandbyState;
061 import org.apache.hadoop.hdfs.server.namenode.metrics.NameNodeMetrics;
062 import org.apache.hadoop.hdfs.server.protocol.DatanodeProtocol;
063 import org.apache.hadoop.hdfs.server.protocol.JournalProtocol;
064 import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
065 import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
066 import org.apache.hadoop.hdfs.server.protocol.NamenodeRegistration;
067 import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
068 import org.apache.hadoop.ipc.Server;
069 import org.apache.hadoop.ipc.StandbyException;
070 import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
071 import org.apache.hadoop.net.NetUtils;
072 import org.apache.hadoop.security.AccessControlException;
073 import org.apache.hadoop.security.RefreshUserMappingsProtocol;
074 import org.apache.hadoop.security.SecurityUtil;
075 import org.apache.hadoop.security.UserGroupInformation;
076 import org.apache.hadoop.security.authorize.RefreshAuthorizationPolicyProtocol;
077 import org.apache.hadoop.tools.GetUserMappingsProtocol;
078 import org.apache.hadoop.util.ExitUtil.ExitException;
079 import org.apache.hadoop.util.ServicePlugin;
080 import org.apache.hadoop.util.StringUtils;
081
082 import com.google.common.annotations.VisibleForTesting;
083 import com.google.common.base.Joiner;
084 import com.google.common.base.Preconditions;
085 import com.google.common.collect.Lists;
086
087 /**********************************************************
088 * NameNode serves as both directory namespace manager and
089 * "inode table" for the Hadoop DFS. There is a single NameNode
090 * running in any DFS deployment. (Well, except when there
091 * is a second backup/failover NameNode, or when using federated NameNodes.)
092 *
093 * The NameNode controls two critical tables:
094 * 1) filename->blocksequence (namespace)
095 * 2) block->machinelist ("inodes")
096 *
097 * The first table is stored on disk and is very precious.
098 * The second table is rebuilt every time the NameNode comes up.
099 *
100 * 'NameNode' refers to both this class as well as the 'NameNode server'.
101 * The 'FSNamesystem' class actually performs most of the filesystem
102 * management. The majority of the 'NameNode' class itself is concerned
103 * with exposing the IPC interface and the HTTP server to the outside world,
104 * plus some configuration management.
105 *
106 * NameNode implements the
107 * {@link org.apache.hadoop.hdfs.protocol.ClientProtocol} interface, which
108 * allows clients to ask for DFS services.
109 * {@link org.apache.hadoop.hdfs.protocol.ClientProtocol} is not designed for
110 * direct use by authors of DFS client code. End-users should instead use the
111 * {@link org.apache.hadoop.fs.FileSystem} class.
112 *
113 * NameNode also implements the
114 * {@link org.apache.hadoop.hdfs.server.protocol.DatanodeProtocol} interface,
115 * used by DataNodes that actually store DFS data blocks. These
116 * methods are invoked repeatedly and automatically by all the
117 * DataNodes in a DFS deployment.
118 *
119 * NameNode also implements the
120 * {@link org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol} interface,
121 * used by secondary namenodes or rebalancing processes to get partial
122 * NameNode state, for example partial blocksMap etc.
123 **********************************************************/
124 @InterfaceAudience.Private
125 public class NameNode {
126 static{
127 HdfsConfiguration.init();
128 }
129
130 /**
131 * Categories of operations supported by the namenode.
132 */
133 public static enum OperationCategory {
134 /** Operations that are state agnostic */
135 UNCHECKED,
136 /** Read operation that does not change the namespace state */
137 READ,
138 /** Write operation that changes the namespace state */
139 WRITE,
140 /** Operations related to checkpointing */
141 CHECKPOINT,
142 /** Operations related to {@link JournalProtocol} */
143 JOURNAL
144 }
145
146 /**
147 * HDFS configuration can have three types of parameters:
148 * <ol>
149 * <li>Parameters that are common for all the name services in the cluster.</li>
150 * <li>Parameters that are specific to a name service. These keys are suffixed
151 * with nameserviceId in the configuration. For example,
152 * "dfs.namenode.rpc-address.nameservice1".</li>
153 * <li>Parameters that are specific to a single name node. These keys are suffixed
154 * with nameserviceId and namenodeId in the configuration. for example,
155 * "dfs.namenode.rpc-address.nameservice1.namenode1"</li>
156 * </ol>
157 *
158 * In the latter cases, operators may specify the configuration without
159 * any suffix, with a nameservice suffix, or with a nameservice and namenode
160 * suffix. The more specific suffix will take precedence.
161 *
162 * These keys are specific to a given namenode, and thus may be configured
163 * globally, for a nameservice, or for a specific namenode within a nameservice.
164 */
165 public static final String[] NAMENODE_SPECIFIC_KEYS = {
166 DFS_NAMENODE_RPC_ADDRESS_KEY,
167 DFS_NAMENODE_NAME_DIR_KEY,
168 DFS_NAMENODE_EDITS_DIR_KEY,
169 DFS_NAMENODE_SHARED_EDITS_DIR_KEY,
170 DFS_NAMENODE_CHECKPOINT_DIR_KEY,
171 DFS_NAMENODE_CHECKPOINT_EDITS_DIR_KEY,
172 DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY,
173 DFS_NAMENODE_HTTP_ADDRESS_KEY,
174 DFS_NAMENODE_KEYTAB_FILE_KEY,
175 DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY,
176 DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
177 DFS_NAMENODE_BACKUP_ADDRESS_KEY,
178 DFS_NAMENODE_BACKUP_HTTP_ADDRESS_KEY,
179 DFS_NAMENODE_BACKUP_SERVICE_RPC_ADDRESS_KEY,
180 DFS_NAMENODE_USER_NAME_KEY,
181 DFS_HA_FENCE_METHODS_KEY,
182 DFS_HA_ZKFC_PORT_KEY,
183 DFS_HA_FENCE_METHODS_KEY
184 };
185
186 /**
187 * @see #NAMENODE_SPECIFIC_KEYS
188 * These keys are specific to a nameservice, but may not be overridden
189 * for a specific namenode.
190 */
191 public static final String[] NAMESERVICE_SPECIFIC_KEYS = {
192 DFS_HA_AUTO_FAILOVER_ENABLED_KEY
193 };
194
195 private static final String USAGE = "Usage: java NameNode ["
196 + StartupOption.BACKUP.getName() + "] | ["
197 + StartupOption.CHECKPOINT.getName() + "] | ["
198 + StartupOption.FORMAT.getName() + " ["
199 + StartupOption.CLUSTERID.getName() + " cid ] ["
200 + StartupOption.FORCE.getName() + "] ["
201 + StartupOption.NONINTERACTIVE.getName() + "] ] | ["
202 + StartupOption.UPGRADE.getName() + "] | ["
203 + StartupOption.ROLLBACK.getName() + "] | ["
204 + StartupOption.FINALIZE.getName() + "] | ["
205 + StartupOption.IMPORT.getName() + "] | ["
206 + StartupOption.INITIALIZESHAREDEDITS.getName() + "] | ["
207 + StartupOption.BOOTSTRAPSTANDBY.getName() + "] | ["
208 + StartupOption.RECOVER.getName() + " [ " + StartupOption.FORCE.getName()
209 + " ] ]";
210
211 public long getProtocolVersion(String protocol,
212 long clientVersion) throws IOException {
213 if (protocol.equals(ClientProtocol.class.getName())) {
214 return ClientProtocol.versionID;
215 } else if (protocol.equals(DatanodeProtocol.class.getName())){
216 return DatanodeProtocol.versionID;
217 } else if (protocol.equals(NamenodeProtocol.class.getName())){
218 return NamenodeProtocol.versionID;
219 } else if (protocol.equals(RefreshAuthorizationPolicyProtocol.class.getName())){
220 return RefreshAuthorizationPolicyProtocol.versionID;
221 } else if (protocol.equals(RefreshUserMappingsProtocol.class.getName())){
222 return RefreshUserMappingsProtocol.versionID;
223 } else if (protocol.equals(GetUserMappingsProtocol.class.getName())){
224 return GetUserMappingsProtocol.versionID;
225 } else {
226 throw new IOException("Unknown protocol to name node: " + protocol);
227 }
228 }
229
230 public static final int DEFAULT_PORT = 8020;
231 public static final Log LOG = LogFactory.getLog(NameNode.class.getName());
232 public static final Log stateChangeLog = LogFactory.getLog("org.apache.hadoop.hdfs.StateChange");
233 public static final Log blockStateChangeLog = LogFactory.getLog("BlockStateChange");
234 public static final HAState ACTIVE_STATE = new ActiveState();
235 public static final HAState STANDBY_STATE = new StandbyState();
236
237 protected FSNamesystem namesystem;
238 protected final Configuration conf;
239 protected NamenodeRole role;
240 private volatile HAState state;
241 private final boolean haEnabled;
242 private final HAContext haContext;
243 protected boolean allowStaleStandbyReads;
244
245
246 /** httpServer */
247 protected NameNodeHttpServer httpServer;
248 private Thread emptier;
249 /** only used for testing purposes */
250 protected boolean stopRequested = false;
251 /** Registration information of this name-node */
252 protected NamenodeRegistration nodeRegistration;
253 /** Activated plug-ins. */
254 private List<ServicePlugin> plugins;
255
256 private NameNodeRpcServer rpcServer;
257
258 /** Format a new filesystem. Destroys any filesystem that may already
259 * exist at this location. **/
260 public static void format(Configuration conf) throws IOException {
261 format(conf, true, true);
262 }
263
264 static NameNodeMetrics metrics;
265
266 /** Return the {@link FSNamesystem} object.
267 * @return {@link FSNamesystem} object.
268 */
269 public FSNamesystem getNamesystem() {
270 return namesystem;
271 }
272
273 public NamenodeProtocols getRpcServer() {
274 return rpcServer;
275 }
276
277 static void initMetrics(Configuration conf, NamenodeRole role) {
278 metrics = NameNodeMetrics.create(conf, role);
279 }
280
281 public static NameNodeMetrics getNameNodeMetrics() {
282 return metrics;
283 }
284
285 public static InetSocketAddress getAddress(String address) {
286 return NetUtils.createSocketAddr(address, DEFAULT_PORT);
287 }
288
289 /**
290 * Set the configuration property for the service rpc address
291 * to address
292 */
293 public static void setServiceAddress(Configuration conf,
294 String address) {
295 LOG.info("Setting ADDRESS " + address);
296 conf.set(DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY, address);
297 }
298
299 /**
300 * Fetches the address for services to use when connecting to namenode
301 * based on the value of fallback returns null if the special
302 * address is not specified or returns the default namenode address
303 * to be used by both clients and services.
304 * Services here are datanodes, backup node, any non client connection
305 */
306 public static InetSocketAddress getServiceAddress(Configuration conf,
307 boolean fallback) {
308 String addr = conf.get(DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY);
309 if (addr == null || addr.isEmpty()) {
310 return fallback ? getAddress(conf) : null;
311 }
312 return getAddress(addr);
313 }
314
315 public static InetSocketAddress getAddress(Configuration conf) {
316 URI filesystemURI = FileSystem.getDefaultUri(conf);
317 return getAddress(filesystemURI);
318 }
319
320
321 /**
322 * TODO:FEDERATION
323 * @param filesystemURI
324 * @return address of file system
325 */
326 public static InetSocketAddress getAddress(URI filesystemURI) {
327 String authority = filesystemURI.getAuthority();
328 if (authority == null) {
329 throw new IllegalArgumentException(String.format(
330 "Invalid URI for NameNode address (check %s): %s has no authority.",
331 FileSystem.FS_DEFAULT_NAME_KEY, filesystemURI.toString()));
332 }
333 if (!HdfsConstants.HDFS_URI_SCHEME.equalsIgnoreCase(
334 filesystemURI.getScheme())) {
335 throw new IllegalArgumentException(String.format(
336 "Invalid URI for NameNode address (check %s): %s is not of scheme '%s'.",
337 FileSystem.FS_DEFAULT_NAME_KEY, filesystemURI.toString(),
338 HdfsConstants.HDFS_URI_SCHEME));
339 }
340 return getAddress(authority);
341 }
342
343 public static URI getUri(InetSocketAddress namenode) {
344 int port = namenode.getPort();
345 String portString = port == DEFAULT_PORT ? "" : (":"+port);
346 return URI.create(HdfsConstants.HDFS_URI_SCHEME + "://"
347 + namenode.getHostName()+portString);
348 }
349
350 //
351 // Common NameNode methods implementation for the active name-node role.
352 //
353 public NamenodeRole getRole() {
354 return role;
355 }
356
357 boolean isRole(NamenodeRole that) {
358 return role.equals(that);
359 }
360
361 /**
362 * Given a configuration get the address of the service rpc server
363 * If the service rpc is not configured returns null
364 */
365 protected InetSocketAddress getServiceRpcServerAddress(Configuration conf) {
366 return NameNode.getServiceAddress(conf, false);
367 }
368
369 protected InetSocketAddress getRpcServerAddress(Configuration conf) {
370 return getAddress(conf);
371 }
372
373 /**
374 * Modifies the configuration passed to contain the service rpc address setting
375 */
376 protected void setRpcServiceServerAddress(Configuration conf,
377 InetSocketAddress serviceRPCAddress) {
378 setServiceAddress(conf, NetUtils.getHostPortString(serviceRPCAddress));
379 }
380
381 protected void setRpcServerAddress(Configuration conf,
382 InetSocketAddress rpcAddress) {
383 FileSystem.setDefaultUri(conf, getUri(rpcAddress));
384 }
385
386 protected InetSocketAddress getHttpServerAddress(Configuration conf) {
387 return getHttpAddress(conf);
388 }
389
390 /** @return the NameNode HTTP address set in the conf. */
391 public static InetSocketAddress getHttpAddress(Configuration conf) {
392 return NetUtils.createSocketAddr(
393 conf.get(DFS_NAMENODE_HTTP_ADDRESS_KEY, DFS_NAMENODE_HTTP_ADDRESS_DEFAULT));
394 }
395
396 protected void setHttpServerAddress(Configuration conf) {
397 String hostPort = NetUtils.getHostPortString(getHttpAddress());
398 conf.set(DFS_NAMENODE_HTTP_ADDRESS_KEY, hostPort);
399 LOG.info("Web-server up at: " + hostPort);
400 }
401
402 protected void loadNamesystem(Configuration conf) throws IOException {
403 this.namesystem = FSNamesystem.loadFromDisk(conf);
404 }
405
406 NamenodeRegistration getRegistration() {
407 return nodeRegistration;
408 }
409
410 NamenodeRegistration setRegistration() {
411 nodeRegistration = new NamenodeRegistration(
412 NetUtils.getHostPortString(rpcServer.getRpcAddress()),
413 NetUtils.getHostPortString(getHttpAddress()),
414 getFSImage().getStorage(), getRole());
415 return nodeRegistration;
416 }
417
418 /**
419 * Login as the configured user for the NameNode.
420 */
421 void loginAsNameNodeUser(Configuration conf) throws IOException {
422 InetSocketAddress socAddr = getRpcServerAddress(conf);
423 SecurityUtil.login(conf, DFS_NAMENODE_KEYTAB_FILE_KEY,
424 DFS_NAMENODE_USER_NAME_KEY, socAddr.getHostName());
425 }
426
427 /**
428 * Initialize name-node.
429 *
430 * @param conf the configuration
431 */
432 protected void initialize(Configuration conf) throws IOException {
433 UserGroupInformation.setConfiguration(conf);
434 loginAsNameNodeUser(conf);
435
436 NameNode.initMetrics(conf, this.getRole());
437 loadNamesystem(conf);
438
439 rpcServer = createRpcServer(conf);
440
441 try {
442 validateConfigurationSettings(conf);
443 } catch (IOException e) {
444 LOG.fatal(e.toString());
445 throw e;
446 }
447
448 startCommonServices(conf);
449 }
450
451 /**
452 * Create the RPC server implementation. Used as an extension point for the
453 * BackupNode.
454 */
455 protected NameNodeRpcServer createRpcServer(Configuration conf)
456 throws IOException {
457 return new NameNodeRpcServer(conf, this);
458 }
459
460 /**
461 * Verifies that the final Configuration Settings look ok for the NameNode to
462 * properly start up
463 * Things to check for include:
464 * - HTTP Server Port does not equal the RPC Server Port
465 * @param conf
466 * @throws IOException
467 */
468 protected void validateConfigurationSettings(final Configuration conf)
469 throws IOException {
470 // check to make sure the web port and rpc port do not match
471 if(getHttpServerAddress(conf).getPort()
472 == getRpcServerAddress(conf).getPort()) {
473 String errMsg = "dfs.namenode.rpc-address " +
474 "("+ getRpcServerAddress(conf) + ") and " +
475 "dfs.namenode.http-address ("+ getHttpServerAddress(conf) + ") " +
476 "configuration keys are bound to the same port, unable to start " +
477 "NameNode. Port: " + getRpcServerAddress(conf).getPort();
478 throw new IOException(errMsg);
479 }
480 }
481
482 /** Start the services common to active and standby states */
483 private void startCommonServices(Configuration conf) throws IOException {
484 namesystem.startCommonServices(conf, haContext);
485 startHttpServer(conf);
486 rpcServer.start();
487 plugins = conf.getInstances(DFS_NAMENODE_PLUGINS_KEY,
488 ServicePlugin.class);
489 for (ServicePlugin p: plugins) {
490 try {
491 p.start(this);
492 } catch (Throwable t) {
493 LOG.warn("ServicePlugin " + p + " could not be started", t);
494 }
495 }
496 LOG.info(getRole() + " RPC up at: " + rpcServer.getRpcAddress());
497 if (rpcServer.getServiceRpcAddress() != null) {
498 LOG.info(getRole() + " service RPC up at: "
499 + rpcServer.getServiceRpcAddress());
500 }
501 }
502
503 private void stopCommonServices() {
504 if(namesystem != null) namesystem.close();
505 if(rpcServer != null) rpcServer.stop();
506 if (plugins != null) {
507 for (ServicePlugin p : plugins) {
508 try {
509 p.stop();
510 } catch (Throwable t) {
511 LOG.warn("ServicePlugin " + p + " could not be stopped", t);
512 }
513 }
514 }
515 stopHttpServer();
516 }
517
518 private void startTrashEmptier(final Configuration conf) throws IOException {
519 long trashInterval =
520 conf.getLong(FS_TRASH_INTERVAL_KEY, FS_TRASH_INTERVAL_DEFAULT);
521 if (trashInterval == 0) {
522 return;
523 } else if (trashInterval < 0) {
524 throw new IOException("Cannot start tresh emptier with negative interval."
525 + " Set " + FS_TRASH_INTERVAL_KEY + " to a positive value.");
526 }
527
528 // This may be called from the transitionToActive code path, in which
529 // case the current user is the administrator, not the NN. The trash
530 // emptier needs to run as the NN. See HDFS-3972.
531 FileSystem fs = SecurityUtil.doAsLoginUser(
532 new PrivilegedExceptionAction<FileSystem>() {
533 @Override
534 public FileSystem run() throws IOException {
535 return FileSystem.get(conf);
536 }
537 });
538 this.emptier = new Thread(new Trash(fs, conf).getEmptier(), "Trash Emptier");
539 this.emptier.setDaemon(true);
540 this.emptier.start();
541 }
542
543 private void stopTrashEmptier() {
544 if (this.emptier != null) {
545 emptier.interrupt();
546 emptier = null;
547 }
548 }
549
550 private void startHttpServer(final Configuration conf) throws IOException {
551 httpServer = new NameNodeHttpServer(conf, this, getHttpServerAddress(conf));
552 httpServer.start();
553 setHttpServerAddress(conf);
554 }
555
556 private void stopHttpServer() {
557 try {
558 if (httpServer != null) httpServer.stop();
559 } catch (Exception e) {
560 LOG.error("Exception while stopping httpserver", e);
561 }
562 }
563
564 /**
565 * Start NameNode.
566 * <p>
567 * The name-node can be started with one of the following startup options:
568 * <ul>
569 * <li>{@link StartupOption#REGULAR REGULAR} - normal name node startup</li>
570 * <li>{@link StartupOption#FORMAT FORMAT} - format name node</li>
571 * <li>{@link StartupOption#BACKUP BACKUP} - start backup node</li>
572 * <li>{@link StartupOption#CHECKPOINT CHECKPOINT} - start checkpoint node</li>
573 * <li>{@link StartupOption#UPGRADE UPGRADE} - start the cluster
574 * upgrade and create a snapshot of the current file system state</li>
575 * <li>{@link StartupOption#RECOVERY RECOVERY} - recover name node
576 * metadata</li>
577 * <li>{@link StartupOption#ROLLBACK ROLLBACK} - roll the
578 * cluster back to the previous state</li>
579 * <li>{@link StartupOption#FINALIZE FINALIZE} - finalize
580 * previous upgrade</li>
581 * <li>{@link StartupOption#IMPORT IMPORT} - import checkpoint</li>
582 * </ul>
583 * The option is passed via configuration field:
584 * <tt>dfs.namenode.startup</tt>
585 *
586 * The conf will be modified to reflect the actual ports on which
587 * the NameNode is up and running if the user passes the port as
588 * <code>zero</code> in the conf.
589 *
590 * @param conf confirguration
591 * @throws IOException
592 */
593 public NameNode(Configuration conf) throws IOException {
594 this(conf, NamenodeRole.NAMENODE);
595 }
596
597 protected NameNode(Configuration conf, NamenodeRole role)
598 throws IOException {
599 this.conf = conf;
600 this.role = role;
601 String nsId = getNameServiceId(conf);
602 String namenodeId = HAUtil.getNameNodeId(conf, nsId);
603 this.haEnabled = HAUtil.isHAEnabled(conf, nsId);
604 state = createHAState();
605 this.allowStaleStandbyReads = HAUtil.shouldAllowStandbyReads(conf);
606 this.haContext = createHAContext();
607 try {
608 initializeGenericKeys(conf, nsId, namenodeId);
609 initialize(conf);
610 state.prepareToEnterState(haContext);
611 state.enterState(haContext);
612 } catch (IOException e) {
613 this.stop();
614 throw e;
615 } catch (HadoopIllegalArgumentException e) {
616 this.stop();
617 throw e;
618 }
619 }
620
621 protected HAState createHAState() {
622 return !haEnabled ? ACTIVE_STATE : STANDBY_STATE;
623 }
624
625 protected HAContext createHAContext() {
626 return new NameNodeHAContext();
627 }
628
629 /**
630 * Wait for service to finish.
631 * (Normally, it runs forever.)
632 */
633 public void join() {
634 try {
635 rpcServer.join();
636 } catch (InterruptedException ie) {
637 LOG.info("Caught interrupted exception ", ie);
638 }
639 }
640
641 /**
642 * Stop all NameNode threads and wait for all to finish.
643 */
644 public void stop() {
645 synchronized(this) {
646 if (stopRequested)
647 return;
648 stopRequested = true;
649 }
650 try {
651 if (state != null) {
652 state.exitState(haContext);
653 }
654 } catch (ServiceFailedException e) {
655 LOG.warn("Encountered exception while exiting state ", e);
656 }
657 stopCommonServices();
658 if (metrics != null) {
659 metrics.shutdown();
660 }
661 if (namesystem != null) {
662 namesystem.shutdown();
663 }
664 }
665
666 synchronized boolean isStopRequested() {
667 return stopRequested;
668 }
669
670 /**
671 * Is the cluster currently in safe mode?
672 */
673 public boolean isInSafeMode() {
674 return namesystem.isInSafeMode();
675 }
676
677 /** get FSImage */
678 FSImage getFSImage() {
679 return namesystem.dir.fsImage;
680 }
681
682 /**
683 * @return NameNode RPC address
684 */
685 public InetSocketAddress getNameNodeAddress() {
686 return rpcServer.getRpcAddress();
687 }
688
689 /**
690 * @return NameNode RPC address in "host:port" string form
691 */
692 public String getNameNodeAddressHostPortString() {
693 return NetUtils.getHostPortString(rpcServer.getRpcAddress());
694 }
695
696 /**
697 * @return NameNode service RPC address if configured, the
698 * NameNode RPC address otherwise
699 */
700 public InetSocketAddress getServiceRpcAddress() {
701 final InetSocketAddress serviceAddr = rpcServer.getServiceRpcAddress();
702 return serviceAddr == null ? rpcServer.getRpcAddress() : serviceAddr;
703 }
704
705 /**
706 * @return NameNode HTTP address, used by the Web UI, image transfer,
707 * and HTTP-based file system clients like Hftp and WebHDFS
708 */
709 public InetSocketAddress getHttpAddress() {
710 return httpServer.getHttpAddress();
711 }
712
713 /**
714 * Verify that configured directories exist, then
715 * Interactively confirm that formatting is desired
716 * for each existing directory and format them.
717 *
718 * @param conf
719 * @param force
720 * @return true if formatting was aborted, false otherwise
721 * @throws IOException
722 */
723 private static boolean format(Configuration conf, boolean force,
724 boolean isInteractive) throws IOException {
725 String nsId = DFSUtil.getNamenodeNameServiceId(conf);
726 String namenodeId = HAUtil.getNameNodeId(conf, nsId);
727 initializeGenericKeys(conf, nsId, namenodeId);
728 checkAllowFormat(conf);
729
730 if (UserGroupInformation.isSecurityEnabled()) {
731 InetSocketAddress socAddr = getAddress(conf);
732 SecurityUtil.login(conf, DFS_NAMENODE_KEYTAB_FILE_KEY,
733 DFS_NAMENODE_USER_NAME_KEY, socAddr.getHostName());
734 }
735
736 Collection<URI> nameDirsToFormat = FSNamesystem.getNamespaceDirs(conf);
737 List<URI> sharedDirs = FSNamesystem.getSharedEditsDirs(conf);
738 List<URI> dirsToPrompt = new ArrayList<URI>();
739 dirsToPrompt.addAll(nameDirsToFormat);
740 dirsToPrompt.addAll(sharedDirs);
741 List<URI> editDirsToFormat =
742 FSNamesystem.getNamespaceEditsDirs(conf);
743
744 // if clusterID is not provided - see if you can find the current one
745 String clusterId = StartupOption.FORMAT.getClusterId();
746 if(clusterId == null || clusterId.equals("")) {
747 //Generate a new cluster id
748 clusterId = NNStorage.newClusterID();
749 }
750 System.out.println("Formatting using clusterid: " + clusterId);
751
752 FSImage fsImage = new FSImage(conf, nameDirsToFormat, editDirsToFormat);
753 FSNamesystem fsn = new FSNamesystem(conf, fsImage);
754 fsImage.getEditLog().initJournalsForWrite();
755
756 if (!fsImage.confirmFormat(force, isInteractive)) {
757 return true; // aborted
758 }
759
760 fsImage.format(fsn, clusterId);
761 return false;
762 }
763
764 public static void checkAllowFormat(Configuration conf) throws IOException {
765 if (!conf.getBoolean(DFS_NAMENODE_SUPPORT_ALLOW_FORMAT_KEY,
766 DFS_NAMENODE_SUPPORT_ALLOW_FORMAT_DEFAULT)) {
767 throw new IOException("The option " + DFS_NAMENODE_SUPPORT_ALLOW_FORMAT_KEY
768 + " is set to false for this filesystem, so it "
769 + "cannot be formatted. You will need to set "
770 + DFS_NAMENODE_SUPPORT_ALLOW_FORMAT_KEY +" parameter "
771 + "to true in order to format this filesystem");
772 }
773 }
774
775 @VisibleForTesting
776 public static boolean initializeSharedEdits(Configuration conf) throws IOException {
777 return initializeSharedEdits(conf, true);
778 }
779
780 @VisibleForTesting
781 public static boolean initializeSharedEdits(Configuration conf,
782 boolean force) throws IOException {
783 return initializeSharedEdits(conf, force, false);
784 }
785
786 /**
787 * Clone the supplied configuration but remove the shared edits dirs.
788 *
789 * @param conf Supplies the original configuration.
790 * @return Cloned configuration without the shared edit dirs.
791 * @throws IOException on failure to generate the configuration.
792 */
793 private static Configuration getConfigurationWithoutSharedEdits(
794 Configuration conf)
795 throws IOException {
796 List<URI> editsDirs = FSNamesystem.getNamespaceEditsDirs(conf, false);
797 String editsDirsString = Joiner.on(",").join(editsDirs);
798
799 Configuration confWithoutShared = new Configuration(conf);
800 confWithoutShared.unset(DFSConfigKeys.DFS_NAMENODE_SHARED_EDITS_DIR_KEY);
801 confWithoutShared.setStrings(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY,
802 editsDirsString);
803 return confWithoutShared;
804 }
805
806 /**
807 * Format a new shared edits dir and copy in enough edit log segments so that
808 * the standby NN can start up.
809 *
810 * @param conf configuration
811 * @param force format regardless of whether or not the shared edits dir exists
812 * @param interactive prompt the user when a dir exists
813 * @return true if the command aborts, false otherwise
814 */
815 private static boolean initializeSharedEdits(Configuration conf,
816 boolean force, boolean interactive) throws IOException {
817 String nsId = DFSUtil.getNamenodeNameServiceId(conf);
818 String namenodeId = HAUtil.getNameNodeId(conf, nsId);
819 initializeGenericKeys(conf, nsId, namenodeId);
820
821 if (conf.get(DFSConfigKeys.DFS_NAMENODE_SHARED_EDITS_DIR_KEY) == null) {
822 LOG.fatal("No shared edits directory configured for namespace " +
823 nsId + " namenode " + namenodeId);
824 return false;
825 }
826
827 if (UserGroupInformation.isSecurityEnabled()) {
828 InetSocketAddress socAddr = getAddress(conf);
829 SecurityUtil.login(conf, DFS_NAMENODE_KEYTAB_FILE_KEY,
830 DFS_NAMENODE_USER_NAME_KEY, socAddr.getHostName());
831 }
832
833 NNStorage existingStorage = null;
834 try {
835 FSNamesystem fsns =
836 FSNamesystem.loadFromDisk(getConfigurationWithoutSharedEdits(conf));
837
838 existingStorage = fsns.getFSImage().getStorage();
839 NamespaceInfo nsInfo = existingStorage.getNamespaceInfo();
840
841 List<URI> sharedEditsDirs = FSNamesystem.getSharedEditsDirs(conf);
842
843 FSImage sharedEditsImage = new FSImage(conf,
844 Lists.<URI>newArrayList(),
845 sharedEditsDirs);
846 sharedEditsImage.getEditLog().initJournalsForWrite();
847
848 if (!sharedEditsImage.confirmFormat(force, interactive)) {
849 return true; // abort
850 }
851
852 NNStorage newSharedStorage = sharedEditsImage.getStorage();
853 // Call Storage.format instead of FSImage.format here, since we don't
854 // actually want to save a checkpoint - just prime the dirs with
855 // the existing namespace info
856 newSharedStorage.format(nsInfo);
857 sharedEditsImage.getEditLog().formatNonFileJournals(nsInfo);
858
859 // Need to make sure the edit log segments are in good shape to initialize
860 // the shared edits dir.
861 fsns.getFSImage().getEditLog().close();
862 fsns.getFSImage().getEditLog().initJournalsForWrite();
863 fsns.getFSImage().getEditLog().recoverUnclosedStreams();
864
865 copyEditLogSegmentsToSharedDir(fsns, sharedEditsDirs, newSharedStorage,
866 conf);
867 } catch (IOException ioe) {
868 LOG.error("Could not initialize shared edits dir", ioe);
869 return true; // aborted
870 } finally {
871 // Have to unlock storage explicitly for the case when we're running in a
872 // unit test, which runs in the same JVM as NNs.
873 if (existingStorage != null) {
874 try {
875 existingStorage.unlockAll();
876 } catch (IOException ioe) {
877 LOG.warn("Could not unlock storage directories", ioe);
878 return true; // aborted
879 }
880 }
881 }
882 return false; // did not abort
883 }
884
885 private static void copyEditLogSegmentsToSharedDir(FSNamesystem fsns,
886 Collection<URI> sharedEditsDirs, NNStorage newSharedStorage,
887 Configuration conf) throws IOException {
888 Preconditions.checkArgument(!sharedEditsDirs.isEmpty(),
889 "No shared edits specified");
890 // Copy edit log segments into the new shared edits dir.
891 List<URI> sharedEditsUris = new ArrayList<URI>(sharedEditsDirs);
892 FSEditLog newSharedEditLog = new FSEditLog(conf, newSharedStorage,
893 sharedEditsUris);
894 newSharedEditLog.initJournalsForWrite();
895 newSharedEditLog.recoverUnclosedStreams();
896
897 FSEditLog sourceEditLog = fsns.getFSImage().editLog;
898
899 long fromTxId = fsns.getFSImage().getMostRecentCheckpointTxId();
900 Collection<EditLogInputStream> streams = sourceEditLog.selectInputStreams(
901 fromTxId+1, 0);
902
903 // Set the nextTxid to the CheckpointTxId+1
904 newSharedEditLog.setNextTxId(fromTxId + 1);
905
906 // Copy all edits after last CheckpointTxId to shared edits dir
907 for (EditLogInputStream stream : streams) {
908 LOG.debug("Beginning to copy stream " + stream + " to shared edits");
909 FSEditLogOp op;
910 boolean segmentOpen = false;
911 while ((op = stream.readOp()) != null) {
912 if (LOG.isTraceEnabled()) {
913 LOG.trace("copying op: " + op);
914 }
915 if (!segmentOpen) {
916 newSharedEditLog.startLogSegment(op.txid, false);
917 segmentOpen = true;
918 }
919
920 newSharedEditLog.logEdit(op);
921
922 if (op.opCode == FSEditLogOpCodes.OP_END_LOG_SEGMENT) {
923 newSharedEditLog.logSync();
924 newSharedEditLog.endCurrentLogSegment(false);
925 LOG.debug("ending log segment because of END_LOG_SEGMENT op in " + stream);
926 segmentOpen = false;
927 }
928 }
929
930 if (segmentOpen) {
931 LOG.debug("ending log segment because of end of stream in " + stream);
932 newSharedEditLog.logSync();
933 newSharedEditLog.endCurrentLogSegment(false);
934 segmentOpen = false;
935 }
936 }
937 }
938
939 private static boolean finalize(Configuration conf,
940 boolean isConfirmationNeeded
941 ) throws IOException {
942 String nsId = DFSUtil.getNamenodeNameServiceId(conf);
943 String namenodeId = HAUtil.getNameNodeId(conf, nsId);
944 initializeGenericKeys(conf, nsId, namenodeId);
945
946 FSNamesystem nsys = new FSNamesystem(conf, new FSImage(conf));
947 System.err.print(
948 "\"finalize\" will remove the previous state of the files system.\n"
949 + "Recent upgrade will become permanent.\n"
950 + "Rollback option will not be available anymore.\n");
951 if (isConfirmationNeeded) {
952 if (!confirmPrompt("Finalize filesystem state?")) {
953 System.err.println("Finalize aborted.");
954 return true;
955 }
956 }
957 nsys.dir.fsImage.finalizeUpgrade();
958 return false;
959 }
960
961 private static void printUsage(PrintStream out) {
962 out.println(USAGE + "\n");
963 }
964
965 private static StartupOption parseArguments(String args[]) {
966 int argsLen = (args == null) ? 0 : args.length;
967 StartupOption startOpt = StartupOption.REGULAR;
968 for(int i=0; i < argsLen; i++) {
969 String cmd = args[i];
970 if (StartupOption.FORMAT.getName().equalsIgnoreCase(cmd)) {
971 startOpt = StartupOption.FORMAT;
972 for (i = i + 1; i < argsLen; i++) {
973 if (args[i].equalsIgnoreCase(StartupOption.CLUSTERID.getName())) {
974 i++;
975 if (i >= argsLen) {
976 // if no cluster id specified, return null
977 LOG.fatal("Must specify a valid cluster ID after the "
978 + StartupOption.CLUSTERID.getName() + " flag");
979 return null;
980 }
981 String clusterId = args[i];
982 // Make sure an id is specified and not another flag
983 if (clusterId.isEmpty() ||
984 clusterId.equalsIgnoreCase(StartupOption.FORCE.getName()) ||
985 clusterId.equalsIgnoreCase(
986 StartupOption.NONINTERACTIVE.getName())) {
987 LOG.fatal("Must specify a valid cluster ID after the "
988 + StartupOption.CLUSTERID.getName() + " flag");
989 return null;
990 }
991 startOpt.setClusterId(clusterId);
992 }
993
994 if (args[i].equalsIgnoreCase(StartupOption.FORCE.getName())) {
995 startOpt.setForceFormat(true);
996 }
997
998 if (args[i].equalsIgnoreCase(StartupOption.NONINTERACTIVE.getName())) {
999 startOpt.setInteractiveFormat(false);
1000 }
1001 }
1002 } else if (StartupOption.GENCLUSTERID.getName().equalsIgnoreCase(cmd)) {
1003 startOpt = StartupOption.GENCLUSTERID;
1004 } else if (StartupOption.REGULAR.getName().equalsIgnoreCase(cmd)) {
1005 startOpt = StartupOption.REGULAR;
1006 } else if (StartupOption.BACKUP.getName().equalsIgnoreCase(cmd)) {
1007 startOpt = StartupOption.BACKUP;
1008 } else if (StartupOption.CHECKPOINT.getName().equalsIgnoreCase(cmd)) {
1009 startOpt = StartupOption.CHECKPOINT;
1010 } else if (StartupOption.UPGRADE.getName().equalsIgnoreCase(cmd)) {
1011 startOpt = StartupOption.UPGRADE;
1012 // might be followed by two args
1013 if (i + 2 < argsLen
1014 && args[i + 1].equalsIgnoreCase(StartupOption.CLUSTERID.getName())) {
1015 i += 2;
1016 startOpt.setClusterId(args[i]);
1017 }
1018 } else if (StartupOption.ROLLBACK.getName().equalsIgnoreCase(cmd)) {
1019 startOpt = StartupOption.ROLLBACK;
1020 } else if (StartupOption.FINALIZE.getName().equalsIgnoreCase(cmd)) {
1021 startOpt = StartupOption.FINALIZE;
1022 } else if (StartupOption.IMPORT.getName().equalsIgnoreCase(cmd)) {
1023 startOpt = StartupOption.IMPORT;
1024 } else if (StartupOption.BOOTSTRAPSTANDBY.getName().equalsIgnoreCase(cmd)) {
1025 startOpt = StartupOption.BOOTSTRAPSTANDBY;
1026 return startOpt;
1027 } else if (StartupOption.INITIALIZESHAREDEDITS.getName().equalsIgnoreCase(cmd)) {
1028 startOpt = StartupOption.INITIALIZESHAREDEDITS;
1029 for (i = i + 1 ; i < argsLen; i++) {
1030 if (StartupOption.NONINTERACTIVE.getName().equals(args[i])) {
1031 startOpt.setInteractiveFormat(false);
1032 } else if (StartupOption.FORCE.getName().equals(args[i])) {
1033 startOpt.setForceFormat(true);
1034 } else {
1035 LOG.fatal("Invalid argument: " + args[i]);
1036 return null;
1037 }
1038 }
1039 return startOpt;
1040 } else if (StartupOption.RECOVER.getName().equalsIgnoreCase(cmd)) {
1041 if (startOpt != StartupOption.REGULAR) {
1042 throw new RuntimeException("Can't combine -recover with " +
1043 "other startup options.");
1044 }
1045 startOpt = StartupOption.RECOVER;
1046 while (++i < argsLen) {
1047 if (args[i].equalsIgnoreCase(
1048 StartupOption.FORCE.getName())) {
1049 startOpt.setForce(MetaRecoveryContext.FORCE_FIRST_CHOICE);
1050 } else {
1051 throw new RuntimeException("Error parsing recovery options: " +
1052 "can't understand option \"" + args[i] + "\"");
1053 }
1054 }
1055 } else {
1056 return null;
1057 }
1058 }
1059 return startOpt;
1060 }
1061
1062 private static void setStartupOption(Configuration conf, StartupOption opt) {
1063 conf.set(DFS_NAMENODE_STARTUP_KEY, opt.toString());
1064 }
1065
1066 static StartupOption getStartupOption(Configuration conf) {
1067 return StartupOption.valueOf(conf.get(DFS_NAMENODE_STARTUP_KEY,
1068 StartupOption.REGULAR.toString()));
1069 }
1070
1071 private static void doRecovery(StartupOption startOpt, Configuration conf)
1072 throws IOException {
1073 String nsId = DFSUtil.getNamenodeNameServiceId(conf);
1074 String namenodeId = HAUtil.getNameNodeId(conf, nsId);
1075 initializeGenericKeys(conf, nsId, namenodeId);
1076 if (startOpt.getForce() < MetaRecoveryContext.FORCE_ALL) {
1077 if (!confirmPrompt("You have selected Metadata Recovery mode. " +
1078 "This mode is intended to recover lost metadata on a corrupt " +
1079 "filesystem. Metadata recovery mode often permanently deletes " +
1080 "data from your HDFS filesystem. Please back up your edit log " +
1081 "and fsimage before trying this!\n\n" +
1082 "Are you ready to proceed? (Y/N)\n")) {
1083 System.err.println("Recovery aborted at user request.\n");
1084 return;
1085 }
1086 }
1087 MetaRecoveryContext.LOG.info("starting recovery...");
1088 UserGroupInformation.setConfiguration(conf);
1089 NameNode.initMetrics(conf, startOpt.toNodeRole());
1090 FSNamesystem fsn = null;
1091 try {
1092 fsn = FSNamesystem.loadFromDisk(conf);
1093 fsn.saveNamespace();
1094 MetaRecoveryContext.LOG.info("RECOVERY COMPLETE");
1095 } catch (IOException e) {
1096 MetaRecoveryContext.LOG.info("RECOVERY FAILED: caught exception", e);
1097 throw e;
1098 } catch (RuntimeException e) {
1099 MetaRecoveryContext.LOG.info("RECOVERY FAILED: caught exception", e);
1100 throw e;
1101 } finally {
1102 if (fsn != null)
1103 fsn.close();
1104 }
1105 }
1106
1107 public static NameNode createNameNode(String argv[], Configuration conf)
1108 throws IOException {
1109 if (conf == null)
1110 conf = new HdfsConfiguration();
1111 StartupOption startOpt = parseArguments(argv);
1112 if (startOpt == null) {
1113 printUsage(System.err);
1114 return null;
1115 }
1116 setStartupOption(conf, startOpt);
1117
1118 if (HAUtil.isHAEnabled(conf, DFSUtil.getNamenodeNameServiceId(conf)) &&
1119 (startOpt == StartupOption.UPGRADE ||
1120 startOpt == StartupOption.ROLLBACK ||
1121 startOpt == StartupOption.FINALIZE)) {
1122 throw new HadoopIllegalArgumentException("Invalid startup option. " +
1123 "Cannot perform DFS upgrade with HA enabled.");
1124 }
1125
1126 switch (startOpt) {
1127 case FORMAT: {
1128 boolean aborted = format(conf, startOpt.getForceFormat(),
1129 startOpt.getInteractiveFormat());
1130 terminate(aborted ? 1 : 0);
1131 return null; // avoid javac warning
1132 }
1133 case GENCLUSTERID: {
1134 System.err.println("Generating new cluster id:");
1135 System.out.println(NNStorage.newClusterID());
1136 terminate(0);
1137 return null;
1138 }
1139 case FINALIZE: {
1140 boolean aborted = finalize(conf, true);
1141 terminate(aborted ? 1 : 0);
1142 return null; // avoid javac warning
1143 }
1144 case BOOTSTRAPSTANDBY: {
1145 String toolArgs[] = Arrays.copyOfRange(argv, 1, argv.length);
1146 int rc = BootstrapStandby.run(toolArgs, conf);
1147 terminate(rc);
1148 return null; // avoid warning
1149 }
1150 case INITIALIZESHAREDEDITS: {
1151 boolean aborted = initializeSharedEdits(conf,
1152 startOpt.getForceFormat(),
1153 startOpt.getInteractiveFormat());
1154 terminate(aborted ? 1 : 0);
1155 return null; // avoid warning
1156 }
1157 case BACKUP:
1158 case CHECKPOINT: {
1159 NamenodeRole role = startOpt.toNodeRole();
1160 DefaultMetricsSystem.initialize(role.toString().replace(" ", ""));
1161 return new BackupNode(conf, role);
1162 }
1163 case RECOVER: {
1164 NameNode.doRecovery(startOpt, conf);
1165 return null;
1166 }
1167 default: {
1168 DefaultMetricsSystem.initialize("NameNode");
1169 return new NameNode(conf);
1170 }
1171 }
1172 }
1173
1174 /**
1175 * In federation configuration is set for a set of
1176 * namenode and secondary namenode/backup/checkpointer, which are
1177 * grouped under a logical nameservice ID. The configuration keys specific
1178 * to them have suffix set to configured nameserviceId.
1179 *
1180 * This method copies the value from specific key of format key.nameserviceId
1181 * to key, to set up the generic configuration. Once this is done, only
1182 * generic version of the configuration is read in rest of the code, for
1183 * backward compatibility and simpler code changes.
1184 *
1185 * @param conf
1186 * Configuration object to lookup specific key and to set the value
1187 * to the key passed. Note the conf object is modified
1188 * @param nameserviceId name service Id (to distinguish federated NNs)
1189 * @param namenodeId the namenode ID (to distinguish HA NNs)
1190 * @see DFSUtil#setGenericConf(Configuration, String, String, String...)
1191 */
1192 public static void initializeGenericKeys(Configuration conf,
1193 String nameserviceId, String namenodeId) {
1194 if ((nameserviceId != null && !nameserviceId.isEmpty()) ||
1195 (namenodeId != null && !namenodeId.isEmpty())) {
1196 if (nameserviceId != null) {
1197 conf.set(DFS_NAMESERVICE_ID, nameserviceId);
1198 }
1199 if (namenodeId != null) {
1200 conf.set(DFS_HA_NAMENODE_ID_KEY, namenodeId);
1201 }
1202
1203 DFSUtil.setGenericConf(conf, nameserviceId, namenodeId,
1204 NAMENODE_SPECIFIC_KEYS);
1205 DFSUtil.setGenericConf(conf, nameserviceId, null,
1206 NAMESERVICE_SPECIFIC_KEYS);
1207 }
1208
1209 // If the RPC address is set use it to (re-)configure the default FS
1210 if (conf.get(DFS_NAMENODE_RPC_ADDRESS_KEY) != null) {
1211 URI defaultUri = URI.create(HdfsConstants.HDFS_URI_SCHEME + "://"
1212 + conf.get(DFS_NAMENODE_RPC_ADDRESS_KEY));
1213 conf.set(FS_DEFAULT_NAME_KEY, defaultUri.toString());
1214 LOG.debug("Setting " + FS_DEFAULT_NAME_KEY + " to " + defaultUri.toString());
1215 }
1216 }
1217
1218 /**
1219 * Get the name service Id for the node
1220 * @return name service Id or null if federation is not configured
1221 */
1222 protected String getNameServiceId(Configuration conf) {
1223 return DFSUtil.getNamenodeNameServiceId(conf);
1224 }
1225
1226 /**
1227 */
1228 public static void main(String argv[]) throws Exception {
1229 if (DFSUtil.parseHelpArgument(argv, NameNode.USAGE, System.out, true)) {
1230 System.exit(0);
1231 }
1232
1233 try {
1234 StringUtils.startupShutdownMessage(NameNode.class, argv, LOG);
1235 NameNode namenode = createNameNode(argv, null);
1236 if (namenode != null) {
1237 namenode.join();
1238 }
1239 } catch (Throwable e) {
1240 LOG.fatal("Exception in namenode join", e);
1241 terminate(1, e);
1242 }
1243 }
1244
1245 synchronized void monitorHealth()
1246 throws HealthCheckFailedException, AccessControlException {
1247 namesystem.checkSuperuserPrivilege();
1248 if (!haEnabled) {
1249 return; // no-op, if HA is not enabled
1250 }
1251 getNamesystem().checkAvailableResources();
1252 if (!getNamesystem().nameNodeHasResourcesAvailable()) {
1253 throw new HealthCheckFailedException(
1254 "The NameNode has no resources available");
1255 }
1256 }
1257
1258 synchronized void transitionToActive()
1259 throws ServiceFailedException, AccessControlException {
1260 namesystem.checkSuperuserPrivilege();
1261 if (!haEnabled) {
1262 throw new ServiceFailedException("HA for namenode is not enabled");
1263 }
1264 state.setState(haContext, ACTIVE_STATE);
1265 }
1266
1267 synchronized void transitionToStandby()
1268 throws ServiceFailedException, AccessControlException {
1269 namesystem.checkSuperuserPrivilege();
1270 if (!haEnabled) {
1271 throw new ServiceFailedException("HA for namenode is not enabled");
1272 }
1273 state.setState(haContext, STANDBY_STATE);
1274 }
1275
1276 synchronized HAServiceStatus getServiceStatus()
1277 throws ServiceFailedException, AccessControlException {
1278 namesystem.checkSuperuserPrivilege();
1279 if (!haEnabled) {
1280 throw new ServiceFailedException("HA for namenode is not enabled");
1281 }
1282 if (state == null) {
1283 return new HAServiceStatus(HAServiceState.INITIALIZING);
1284 }
1285 HAServiceState retState = state.getServiceState();
1286 HAServiceStatus ret = new HAServiceStatus(retState);
1287 if (retState == HAServiceState.STANDBY) {
1288 String safemodeTip = namesystem.getSafeModeTip();
1289 if (!safemodeTip.isEmpty()) {
1290 ret.setNotReadyToBecomeActive(
1291 "The NameNode is in safemode. " +
1292 safemodeTip);
1293 } else {
1294 ret.setReadyToBecomeActive();
1295 }
1296 } else if (retState == HAServiceState.ACTIVE) {
1297 ret.setReadyToBecomeActive();
1298 } else {
1299 ret.setNotReadyToBecomeActive("State is " + state);
1300 }
1301 return ret;
1302 }
1303
1304 synchronized HAServiceState getServiceState() {
1305 if (state == null) {
1306 return HAServiceState.INITIALIZING;
1307 }
1308 return state.getServiceState();
1309 }
1310
1311 /**
1312 * Shutdown the NN immediately in an ungraceful way. Used when it would be
1313 * unsafe for the NN to continue operating, e.g. during a failed HA state
1314 * transition.
1315 *
1316 * @param t exception which warrants the shutdown. Printed to the NN log
1317 * before exit.
1318 * @throws ExitException thrown only for testing.
1319 */
1320 protected synchronized void doImmediateShutdown(Throwable t)
1321 throws ExitException {
1322 String message = "Error encountered requiring NN shutdown. " +
1323 "Shutting down immediately.";
1324 try {
1325 LOG.fatal(message, t);
1326 } catch (Throwable ignored) {
1327 // This is unlikely to happen, but there's nothing we can do if it does.
1328 }
1329 terminate(1, t);
1330 }
1331
1332 /**
1333 * Class used to expose {@link NameNode} as context to {@link HAState}
1334 */
1335 protected class NameNodeHAContext implements HAContext {
1336 @Override
1337 public void setState(HAState s) {
1338 state = s;
1339 }
1340
1341 @Override
1342 public HAState getState() {
1343 return state;
1344 }
1345
1346 @Override
1347 public void startActiveServices() throws IOException {
1348 try {
1349 namesystem.startActiveServices();
1350 startTrashEmptier(conf);
1351 } catch (Throwable t) {
1352 doImmediateShutdown(t);
1353 }
1354 }
1355
1356 @Override
1357 public void stopActiveServices() throws IOException {
1358 try {
1359 if (namesystem != null) {
1360 namesystem.stopActiveServices();
1361 }
1362 stopTrashEmptier();
1363 } catch (Throwable t) {
1364 doImmediateShutdown(t);
1365 }
1366 }
1367
1368 @Override
1369 public void startStandbyServices() throws IOException {
1370 try {
1371 namesystem.startStandbyServices(conf);
1372 } catch (Throwable t) {
1373 doImmediateShutdown(t);
1374 }
1375 }
1376
1377 @Override
1378 public void prepareToStopStandbyServices() throws ServiceFailedException {
1379 try {
1380 namesystem.prepareToStopStandbyServices();
1381 } catch (Throwable t) {
1382 doImmediateShutdown(t);
1383 }
1384 }
1385
1386 @Override
1387 public void stopStandbyServices() throws IOException {
1388 try {
1389 if (namesystem != null) {
1390 namesystem.stopStandbyServices();
1391 }
1392 } catch (Throwable t) {
1393 doImmediateShutdown(t);
1394 }
1395 }
1396
1397 @Override
1398 public void writeLock() {
1399 namesystem.writeLock();
1400 }
1401
1402 @Override
1403 public void writeUnlock() {
1404 namesystem.writeUnlock();
1405 }
1406
1407 /** Check if an operation of given category is allowed */
1408 @Override
1409 public void checkOperation(final OperationCategory op)
1410 throws StandbyException {
1411 state.checkOperation(haContext, op);
1412 }
1413
1414 @Override
1415 public boolean allowStaleReads() {
1416 return allowStaleStandbyReads;
1417 }
1418
1419 }
1420
1421 public boolean isStandbyState() {
1422 return (state.equals(STANDBY_STATE));
1423 }
1424
1425 /**
1426 * Check that a request to change this node's HA state is valid.
1427 * In particular, verifies that, if auto failover is enabled, non-forced
1428 * requests from the HAAdmin CLI are rejected, and vice versa.
1429 *
1430 * @param req the request to check
1431 * @throws AccessControlException if the request is disallowed
1432 */
1433 void checkHaStateChange(StateChangeRequestInfo req)
1434 throws AccessControlException {
1435 boolean autoHaEnabled = conf.getBoolean(DFS_HA_AUTO_FAILOVER_ENABLED_KEY,
1436 DFS_HA_AUTO_FAILOVER_ENABLED_DEFAULT);
1437 switch (req.getSource()) {
1438 case REQUEST_BY_USER:
1439 if (autoHaEnabled) {
1440 throw new AccessControlException(
1441 "Manual HA control for this NameNode is disallowed, because " +
1442 "automatic HA is enabled.");
1443 }
1444 break;
1445 case REQUEST_BY_USER_FORCED:
1446 if (autoHaEnabled) {
1447 LOG.warn("Allowing manual HA control from " +
1448 Server.getRemoteAddress() +
1449 " even though automatic HA is enabled, because the user " +
1450 "specified the force flag");
1451 }
1452 break;
1453 case REQUEST_BY_ZKFC:
1454 if (!autoHaEnabled) {
1455 throw new AccessControlException(
1456 "Request from ZK failover controller at " +
1457 Server.getRemoteAddress() + " denied since automatic HA " +
1458 "is not enabled");
1459 }
1460 break;
1461 }
1462 }
1463 }