HDFS------hadoop namenode -format

       集群搭建好了以后,通常我们会输入命令:/bin/hadoop namenode -format对hdfs进行格式化,那究竟格式化都做些什么具体的工作呢,怀着好奇心到源码里一探究竟。

首先从这行命令/bin/hadoop namenode -format 可以判断出会调用NameNode的main方法,到源码里一看,果然如此:

在org.apache.hadoop.hdfs.server.namenode包有个类NameNode,它的main方法如下:

---------------------------------------------------------------------------------------------------------------------------------

 public static void main(String argv[]) throws Exception {
    try {
      StringUtils.startupShutdownMessage(NameNode.class, argv, LOG);
      NameNode namenode = createNameNode(argv, null);
      if (namenode != null)
        namenode.join();
    } catch (Throwable e) {
      LOG.error(StringUtils.stringifyException(e));
      System.exit(-1);
    }
  }

---------------------------------------------------------------------------------------------------------------------------------

    其中  NameNode namenode = createNameNode(argv, null);用来创建namenode,进入方法中:

public static NameNode createNameNode(String argv[],
                                 Configuration conf) throws IOException {
    if (conf == null)
      conf = new Configuration();
    StartupOption startOpt = parseArguments(argv);
    if (startOpt == null) {
      printUsage();
      return null;
    }
    setStartupOption(conf, startOpt);

    switch (startOpt) {
      case FORMAT:
        boolean aborted = format(conf, true);
        System.exit(aborted ? 1 : 0);

      case FINALIZE:
        aborted = finalize(conf, true);
        System.exit(aborted ? 1 : 0);
      default:
    }
    DefaultMetricsSystem.initialize("NameNode");
    NameNode namenode = new NameNode(conf);
    return namenode;
  }

其中FORMAT即为我们在命令行输入的-format,此时会调用format方法,下面集中看这个方法做了哪些工作:

===========================================================================================

private static boolean format(Configuration conf,
                                boolean isConfirmationNeeded
                                ) throws IOException {

/******dirsToFormat是我们在配置文件中dfs.name.dir的value,这个value默认是在/tmp/hadoop/dfs/name目录下******/
    Collection<File> dirsToFormat = FSNamesystem.getNamespaceDirs(conf);
    Collection<File> editDirsToFormat =
                 FSNamesystem.getNamespaceEditsDirs(conf);
    for(Iterator<File> it = dirsToFormat.iterator(); it.hasNext();) {
      File curDir = it.next();
      if (!curDir.exists())
        continue;
      if (isConfirmationNeeded) {
        System.err.print("Re-format filesystem in " + curDir +" ? (Y or N) ");
        if (!(System.in.read() == 'Y')) {
          System.err.println("Format aborted in "+ curDir);
          return true;
        }
        while(System.in.read() != '\n'); // discard the enter-key
      }
    }

/*******构建一个FSNamesystem,构建一个FSImage,然后把FSImage传给了FSNamesystem,其它的先不要管,我们先来看下

*******FSImage的构建。
    FSNamesystem nsys = new FSNamesystem(new FSImage(dirsToFormat,
                                         editDirsToFormat), conf);
    nsys.dir.fsImage.format();
    return false;
  }   
===========================================================================================

FSImage里做的工作很简单就是绑定dirsToFormat(默认为/tmp/hadoop/dfs/name)和editDirsToFormat(默认为/tmp/hadoop/dfs/name)

在FSImage的构造函数里会调用setStorageDirectories方法,它的作用是将dfs.name.dir和dfs.name.edits.dir这两个变量所设置的目录去重,然后将其目录以及目录的类型NameNodeDirType设定到FSImage中去。

回到nsys.dir.fsImage.format();这行代码其实调用的就是我们刚刚创建的FSImage,它的format方法。format的主要工作也是由这个方法来完成的。

====================================================================================================================

  public void format() throws IOException {
    this.layoutVersion = FSConstants.LAYOUT_VERSION;
    this.namespaceID = newNamespaceID();
    this.cTime = 0L;
    this.checkpointTime = FSNamesystem.now();
    for (Iterator<StorageDirectory> it =
                           dirIterator(); it.hasNext();) {
      StorageDirectory sd = it.next();
      format(sd);
    }
  }

======================================================================================================================

format方法里首先把设置一些fsimage的变量,例如:layoutVersion,namespaceID,time,checkpointtime等,然后遍历storageDirs,依次进行format

  /** Create new dfs name directory.  Caution: this destroys all files
   * in this filesystem. */
  void format(StorageDirectory sd) throws IOException {
    sd.clearDirectory(); // create currrent dir
    sd.lock();
    try {
      saveCurrent(sd);
    } finally {
      sd.unlock();
    }
    LOG.info("Storage directory " + sd.getRoot()
             + " has been successfully formatted.");
  }

可以看到,首先将current目录删除(如果有的话),然后调用 saveCurrent(sd);

  protected void saveCurrent(StorageDirectory sd) throws IOException {
    File curDir = sd.getCurrentDir();
    NameNodeDirType dirType = (NameNodeDirType)sd.getStorageDirType();
    // save new image or new edits
    if (!curDir.exists() && !curDir.mkdir())
      throw new IOException("Cannot create directory " + curDir);
    if (dirType.isOfType(NameNodeDirType.IMAGE))
      saveFSImage(getImageFile(sd, NameNodeFile.IMAGE));
    if (dirType.isOfType(NameNodeDirType.EDITS))
      editLog.createEditLogFile(getImageFile(sd, NameNodeFile.EDITS));
    // write version and time files
    sd.write();
  }


saveCurrent方法中首先获取这个storageDir的current目录,如果它的current不存在则先创建current,然后根据storageDir的type,来决定创建fsimage文件或者使edits文件。最后是创建version文件和time文件。

下面一张截图是我从自己的测试机上截取下来的,可以看到current目录下面的四个文件:


======================================================================================

那这四个文件里面具体都写的是哪些数据呢,再此怀着好奇心,去看看到底写的什么,先看fsimage这个文件,

void saveFSImage(File newFile) throws IOException {
    FSNamesystem fsNamesys = FSNamesystem.getFSNamesystem();
    FSDirectory fsDir = fsNamesys.dir;
    long startTime = FSNamesystem.now();
    //
    // Write out data
    //
    DataOutputStream out = new DataOutputStream(
                                                new BufferedOutputStream(
                                                                         new FileOutputStream(newFile)));
    try {
      out.writeInt(FSConstants.LAYOUT_VERSION);                   =============写入布局版本id

      out.writeInt(namespaceID);                                                   =============写入命名空间id

      out.writeLong(fsDir.rootDir.numItemsInTree());                     =============写入根目录(这里指的是dfs.name.dir)
      out.writeLong(fsNamesys.getGenerationStamp());               =============写入创建文件系统时间戳
      byte[] byteStore = new byte[4*FSConstants.MAX_PATH_LENGTH];
      ByteBuffer strbuf = ByteBuffer.wrap(byteStore);
      // save the root
      saveINode2Image(strbuf, fsDir.rootDir, out);                         =============写入文件或者目录的元数据信息,包括复制级别,修改时间,访问时间,块信息等
      // save the rest of the nodes
      saveImage(strbuf, 0, fsDir.rootDir, out);
      fsNamesys.saveFilesUnderConstruction(out);
      fsNamesys.saveSecretManagerState(out);
      strbuf = null;
    } finally {
      out.close();
    }

    LOG.info("Image file of size " + newFile.length() + " saved in "
        + (FSNamesystem.now() - startTime)/1000 + " seconds.");
  }

=========================================================

可以看到,采用了递归调用的方式(saveINode2Image,saveImage)将root目录树结构存储了起来。

最后来看下saveINode2Image这个方法:

private static void saveINode2Image(ByteBuffer name,
                                      INode node,
                                      DataOutputStream out) throws IOException {
    int nameLen = name.position();
    out.writeShort(nameLen);
    out.write(name.array(), name.arrayOffset(), nameLen);
    if (!node.isDirectory()) {  // write file inode
      INodeFile fileINode = (INodeFile)node;
      out.writeShort(fileINode.getReplication());
      out.writeLong(fileINode.getModificationTime());
      out.writeLong(fileINode.getAccessTime());
      out.writeLong(fileINode.getPreferredBlockSize());
      Block[] blocks = fileINode.getBlocks();
      out.writeInt(blocks.length);
      for (Block blk : blocks)
        blk.write(out);
      FILE_PERM.fromShort(fileINode.getFsPermissionShort());
      PermissionStatus.write(out, fileINode.getUserName(),
                             fileINode.getGroupName(),
                             FILE_PERM);
    } else {   // write directory inode
      out.writeShort(0);  // replication
      out.writeLong(node.getModificationTime());
      out.writeLong(0);   // access time
      out.writeLong(0);   // preferred block size
      out.writeInt(-1);    // # of blocks
      out.writeLong(node.getNsQuota());
      out.writeLong(node.getDsQuota());
      FILE_PERM.fromShort(node.getFsPermissionShort());
      PermissionStatus.write(out, node.getUserName(),
                             node.getGroupName(),
                             FILE_PERM);
    }
  }

这个方法很明显,分为文件和目录两个部分,如果使文件的话,记录的信息包括文件的块大小,一个文件包括哪些块(块id,块的数量等),如果是目录,大多属性都设置为0








### HDFS NameNode 格式化时的常见报错及其解决方案 在配置和初始化 Hadoop 集群的过程中,NameNode 的格式化是一个重要的步骤。如果 `hdfs namenode -format` 命令执行失败,则可能是由于多种原因引起的,例如权限问题、目录冲突或配置文件错误。 以下是可能导致该命令报错的原因分析及对应的解决方法: #### 1. 权限不足 当运行 `hdfs namenode -format` 时,如果没有足够的权限访问指定的存储路径(通常由 `dfs.namenode.name.dir` 参数定义),则会引发权限拒绝错误。 - **解决方法**: 确保当前用户具有对 `dfs.namenode.name.dir` 所指向的所有本地目录的读写权限。可以通过以下命令更改目录权限: ```bash sudo chown -R hadoop_user:hadoop_group /path/to/namenode/directory ``` 此操作应针对所有指定的名称节点目录重复进行[^1]。 --- #### 2. 存储目录已存在数据 如果目标存储目录已经包含旧的数据或者之前未清理干净的日志文件,可能会阻止重新格式化的尝试。 - **解决方法**: 删除现有的存储目录并再次尝试格式化。注意,在生产环境中务必小心处理这些数据以防误删重要信息。 ```bash rm -rf /path/to/namenode/directory/* hdfs namenode -format ``` 上述命令中的 `/path/to/namenode/directory/` 应替换为实际使用的路径。 --- #### 3. 配置参数不匹配 Hadoop 使用多个 XML 文件来保存集群设置,默认情况下包括 core-site.xml 和 hdfs-site.xml 。 如果这两个文件内的某些键值配对不当也可能引起异常情况发生。 - **验证与修正**: - 检查 `core-site.xml` 中是否有如下条目正确设定 fs.defaultFS 属性; ```xml <property> <name>fs.defaultFS</name> <value>hdfs://localhost:9000</value> </property> ``` - 同样确认 `hdfs-site.xml` 是否设置了合适的 name directories 地址列表比如下面这样子的例子展示出来如何声明多副本机制下的名字空间位置分布状况等等细节方面的东西都需要注意哦! ```xml <configuration> <property> <name>dfs.replication</name> <value>3</value> </property> <property> <name>dfs.namenode.name.dir</name> <value>/usr/local/hadoop/data/name,/another/path/to/store</value> </property> </configuration> ``` 确保以上属性均按照实际情况调整完毕后再试一次格式化进程即可. --- #### 4. 日志级别过高影响诊断 有时候日志记录等级设得太高以至于掩盖了一些潜在的关键提示消息使得我们难以快速定位具体哪里出了差错. - **降低日志阈值以便获取更多调试线索** 修改 log4j.properties 或者其他相关联的日志框架配置文档把 level 设置成 DEBUG 这样的低优先级从而可以观察到更详尽的过程描述进而辅助排查工作开展下去. ```properties log4j.rootLogger=DEBUG, consoleAppender ``` 完成之后再回到终端界面重跑一遍同样的命名看看能否捕捉新的有用情报啦! --- ### 总结 通过逐一排除上述几个方面的可能性——即检查操作系统层面的安全策略是否允许正常操作;核实物理磁盘分区状态无残留干扰物存在;审阅软件内部逻辑控制结构里的各项开关选项有没有被合理激活启用最后再加上适当程度上的跟踪监控手段相结合运用便有很大几率成功克服这个难题咯! ```python # 示例 Python 脚本用于自动化部分流程 (可选) import os def format_namenode(): try: dir_path = "/path/to/namenode" if not os.path.exists(dir_path): raise Exception(f"Directory {dir_path} does not exist.") # 清理旧数据 cleanup_command = f"rm -r {dir_path}/*" os.system(cleanup_command) # 执行格式化命令 format_command = "hdfs namenode -format" result = os.system(format_command) return True if result == 0 else False except Exception as e: print(e) return False if __name__ == "__main__": success = format_namenode() if success: print("Namenode formatted successfully!") else: print("Failed to format Namenode.") ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值