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