四、大数据技术之Hadoop(HDFS)

大数据技术之Hadoop(HDFS)

文章目录

一、HDFS 概述

1.1 HDFS 产出背景及定义

1)HDFS 产生背景

随着数据量越来越大,在一个操作系统存不下所有的数据,那么就分配到更多的操作系统管理的磁盘中,但是不方便管理和维护,迫切需要一种系统来管理多台机器上的文件,这就是分布式文件管理系统。HDFS 只是分布式文件管理系统中的一种

2)HDFS 定义

HDFS(Hadoop Distributed File System),它是一个文件系统,用于存储文件,通过目录树来定位文件; 其次,它是分布式的,由很多服务器联合起来实现其功能,集群中的服务器有各自的角色。HDFS 的使用场景:适合一次写入,多次读出的场景。一个文件经过创建、写入和关闭之后就不需要改变。

HDFS 的使用场景:适合一次写入,多次读出的场景。一个文件经过创建、写入和关闭之后就不需要改变

1.2 HDFS 优缺点

HDFS优点

1)高容错性

  • 数据自动保存多个副本。它通过增加副本的形式,提高容错性。
  • 某一个副本丢失以后,它可以自动恢复。

2)适合处理大数据

  • 数据规模:能够处理数据规模达到GB、TB、甚至PB级别的数据;
  • 文件规模:能够处理百万规模以上的文件数量,数量相当之大。

3)可构建在廉价机器上,通过多副本机制,提高可靠性。

HDFS缺点

1)不适合低延时数据访问,比如毫秒级的存储数据,是做不到的。

2)无法高效的对大量小文件进行存储。

  • 存储大量小文件的话,它会占用NameNode大量的内存来存储文件目录和块信息。这样是不可取的,因为NameNode的内存总是有限的;
  • 小文件存储的寻址时间会超过读取时间,它违反了HDFS的设计目标。
  • HDFS的block大小可以设置,默认为128M,一个文件块目录都是占用150字节,128M能存储9亿个小文件目录信息

3)不支持并发写入、文件随机修改。

  • 一个文件只能有一个写,不允许多个线程同时写
  • 仅支持数据append(追加),不支持文件的随机修改。

1.3 HDFS 组成架构

1)NameNode(nn):就是Master,它是一个主管、管理者。
(1)管理HDFS的名称空间;
(2)配置副本策略;
(3)管理数据块(Block)映射信息;
(4)处理客户端读写请求。

2)DataNode:就是Slave。NameNode下达命令,DataNode执行实际的操作。
(1)存储实际的数据块;
(2)执行数据块的读/写操作。

3)Client:就是客户端。
(1)文件切分。文件上传HDFS的时候,Client将文件切分成一个一个的Block,然后进行上传;
(2)与NameNode交互,获取文件的位置信息;
(3)与DataNode交互,读取或者写入数据;
(4)Client提供一些命令来管理HDFS,比如NameNode格式化;
(5)Client可以通过一些命令来访问HDFS,比如对HDFS增删查改操作;

4)SecondaryNameNode:并非NameNode的热备。当NameNode挂掉的时候,它并不能马上替换NameNode并提供服务。

(1)辅助NameNode,分担其工作量,比如定期合并Fsimage和Edits,并推送给NameNode ;
(2)在紧急情况下,可辅助恢复NameNode。

1.4 HDFS 文件块大小(面试重点)

HDFS 中的文件在物理上是分块存储 (Block ) , 块的大小可以通过配置参数( dfs.blocksize)来规定,默认大小在Hadoop2.x/3.x版本中是128M,1.x版本中是64M。

思考:为什么块的大小不能设置太小,也不能设置太大?

(1)HDFS的块设置太小,会增加寻址时间,程序一直在找块的开始位置;

(2)如果块设置的太大,从磁盘传输数据的时间会明显大于定位这个块开始位置所需的时间。导致程序在处理这块数据时,会非常慢。

总结:HDFS块的大小设置主要取决于磁盘传输速率。对于一般硬盘来说,传输速率为100M/s,一般设置块的大小128M,因为128是2的7次方,最接近于100M。固态硬盘一般传输速率为200M/s~300M/s,可以设置块大小为256M。在企业,128M和256M是常用的块大小。

二、HDFS 的 Shell 操作

2.1 基本语法

1
hadoop fs  具体命令

或者

1
hdfs dfs  具体命令

两个是完全相同的。

2.2 命令大全

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
[wxler@wxler1 ~]$ cd /opt/module/hadoop-3.1.3/
[wxler@wxler1 hadoop-3.1.3]$ bin/hadoop fs
Usage: hadoop fs [generic options]
[-appendToFile <localsrc> ... <dst>]
[-cat [-ignoreCrc] <src> ...]
[-checksum <src> ...]
[-chgrp [-R] GROUP PATH...]
[-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...]
[-chown [-R] [OWNER][:[GROUP]] PATH...]
[-copyFromLocal [-f] [-p] [-l] [-d] [-t <thread count>] <localsrc> ... <dst>]
[-copyToLocal [-f] [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]
[-count [-q] [-h] [-v] [-t [<storage type>]] [-u] [-x] [-e] <path> ...]
[-cp [-f] [-p | -p[topax]] [-d] <src> ... <dst>]
[-createSnapshot <snapshotDir> [<snapshotName>]]
[-deleteSnapshot <snapshotDir> <snapshotName>]
[-df [-h] [<path> ...]]
[-du [-s] [-h] [-v] [-x] <path> ...]
[-expunge]
[-find <path> ... <expression> ...]
[-get [-f] [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]
[-getfacl [-R] <path>]
[-getfattr [-R] {-n name | -d} [-e en] <path>]
[-getmerge [-nl] [-skip-empty-file] <src> <localdst>]
[-head <file>]
[-help [cmd ...]]
[-ls [-C] [-d] [-h] [-q] [-R] [-t] [-S] [-r] [-u] [-e] [<path> ...]]
[-mkdir [-p] <path> ...]
[-moveFromLocal <localsrc> ... <dst>]
[-moveToLocal <src> <localdst>]
[-mv <src> ... <dst>]
[-put [-f] [-p] [-l] [-d] <localsrc> ... <dst>]
[-renameSnapshot <snapshotDir> <oldName> <newName>]
[-rm [-f] [-r|-R] [-skipTrash] [-safely] <src> ...]
[-rmdir [--ignore-fail-on-non-empty] <dir> ...]
[-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec> <path>]]
[-setfattr {-n name [-v value] | -x name} <path>]
[-setrep [-R] [-w] <rep> <path> ...]
[-stat [format] <path> ...]
[-tail [-f] [-s <sleep interval>] <file>]
[-test -[defsz] <path>]
[-text [-ignoreCrc] <src> ...]
[-touch [-a] [-m] [-t TIMESTAMP ] [-c] <path> ...]
[-touchz <path> ...]
[-truncate [-w] <length> <path> ...]
[-usage [cmd ...]]

Generic options supported are:
-conf <configuration file> specify an application configuration file
-D <property=value> define a value for a given property
-fs <file:///|hdfs://namenode:port> specify default filesystem URL to use, overrides 'fs.defaultFS' property from configurations.
-jt <local|resourcemanager:port> specify a ResourceManager
-files <file1,...> specify a comma-separated list of files to be copied to the map reduce cluster
-libjars <jar1,...> specify a comma-separated list of jar files to be included in the classpath
-archives <archive1,...> specify a comma-separated list of archives to be unarchived on the compute machines

The general command line syntax is:
command [genericOptions] [commandOptions]

[wxler@wxler1 hadoop-3.1.3]$

2.3 常用命令实操

2.3.1 准备工作

1)启动 Hadoop 集群(方便后续的测试)

1
2
[wxler@wxler1 hadoop-3.1.3]$  sbin/start-dfs.sh
[wxler@wxler2 hadoop-3.1.3]$ sbin/start-yarn.sh

或者

1
jpsall

2)-help:输出这个命令参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[wxler@wxler1 hadoop-3.1.3]$ hadoop fs -help rm
-rm [-f] [-r|-R] [-skipTrash] [-safely] <src> ... :
Delete all files that match the specified file pattern. Equivalent to the Unix
command "rm <src>"

-f If the file does not exist, do not display a diagnostic message or
modify the exit status to reflect an error.
-[rR] Recursively deletes directories.
-skipTrash option bypasses trash, if enabled, and immediately deletes <src>.
-safely option requires safety confirmation, if enabled, requires
confirmation before deleting large directory with more than
<hadoop.shell.delete.limit.num.files> files. Delay is expected when
walking over large directory recursively to count the number of
files to be deleted before the confirmation.

3)创建/sanguo 文件夹

1
2
[wxler@wxler1 hadoop-3.1.3]$ hadoop fs -mkdir /sanguo
[wxler@wxler1 hadoop-3.1.3]$ hadoop fs -mkdir /jinguo

2.3.2 上传

1)-moveFromLocal:从本地移动粘贴到 HDFS

1
2
3
4
[wxler@wxler1 hadoop-3.1.3]$ vim shuguo.txt
输入:
shuguo
[wxler@wxler1 hadoop-3.1.3]$ hadoop fs -moveFromLocal ./shuguo.txt /sanguo

如果移动到的/sanguo目录存在,则移动到该目录下,否则,将/sanguo作为移动后的文件,以下所有命令均如此。

2)-copyFromLocal:从本地文件系统中拷贝文件到 HDFS 路径去

1
2
3
4
[wxler@wxler1 hadoop-3.1.3]$ vim weiguo.txt
输入:
weiguo
[wxler@wxler1 hadoop-3.1.3]$ hadoop fs -copyFromLocal weiguo.txt /sanguo

3)-put:等同于 copyFromLocal,生产环境更习惯用 put

1
2
3
4
[wxler@wxler1 hadoop-3.1.3]$ vim weiguo.txt
输入:
weiguo
[wxler@wxler1 hadoop-3.1.3]$ hadoop fs -put weiguo.txt /sanguo

4)-appendToFile:将一个文件中的内容追加到已经存在的文件末尾

1
2
3
4
[wxler@wxler1 hadoop-3.1.3]$ vim liubei.txt
输入:
liubei
[atguigu@hadoop102 hadoop-3.1.3]$ hadoop fs -appendToFile liubei.txt /sanguo/shuguo.txt

2.3.3 下载

1)-copyToLocal:从 HDFS 拷贝到本地

1
hadoop fs -copyToLocal /sanguo/shuguo.txt ./

2)-get:等同于 copyToLocal,生产环境更习惯用 get

1
hadoop fs -get /sanguo/shuguo.txt ./

2.3.4 HDFS 直接操作

1)-ls: 显示目录信息

1
hadoop fs -ls /sanguo

2)-cat:显示文件内容

1
hadoop fs -cat /sanguo/shuguo.txt

3)-chgrp、-chmod、-chown:Linux 文件系统中的用法一样,修改文件所属权限

1
2
hadoop fs  -chmod 666 /sanguo/shuguo.txt
hadoop fs -chown wxler:wxler /sanguo/shuguo.txt

4)-mkdir:创建路径

1
hadoop fs -mkdir /jinguo

5)-cp:从 HDFS 的一个路径拷贝到 HDFS 的另一个路径

1
hadoop fs -cp /sanguo/shuguo.txt /jinguo

6)-mv:在 HDFS 目录中移动文件

1
2
hadoop fs -mv /sanguo/wuguo.txt /jinguo
hadoop fs -mv /sanguo/weiguo.txt /jinguo

7)-tail:显示一个文件的末尾 1kb 的数据

1
hadoop fs -tail /sanguo/shuguo.txt

8)-rm:删除文件或文件夹

1
hadoop fs -rm /sanguo/shuguo.txt

9)-rm -r:递归删除目录及目录里面内容

1
hadoop fs -rm -r /sanguo

10)-du 统计文件夹的大小信息

1
2
3
4
5
6
[wxler@wxler1 hadoop-3.1.3]$ hadoop fs -du -s -h /jinguo
13 39 /jinguo

[wxler@wxler1 hadoop-3.1.3]$ hadoop fs -du -h /jinguo
7 21 /jinguo/shuguo.txt
6 18 /jinguo/wuguo.txt

11)-setrep:设置 HDFS 中文件的副本数量

1
2
[wxler@wxler1 hadoop-3.1.3]$ hadoop fs -setrep 10 /jinguo/shuguo.txt
Replication 10 set: /jinguo/shuguo.txt

这里设置的副本数只是记录在 NameNode 的元数据中,是否真的会有这么多副本,还得看DataNode 的数量。因为目前只有 3 台设备,最多也就 3 个副本,只有节点数的增加到 10台时,副本数才能达到 10。

三、HDFS 的 API 操作

3.1 客户端环境准备

1) 找到资料包路径下的 Windows 依赖文件夹, 拷贝 hadoop-3.1.0 到非中文路径 (比如 d:\) 。
2)配置 HADOOP_HOME 环境变量

在这里插入图片描述
3)配置 Path 环境变量。
注意:如果环境变量不起作用,可以重启电脑试试。
在这里插入图片描述
验证 Hadoop 环境变量是否正常。双击 winutils.exe,如果报如下错误。说明缺少微软运行库 (正版系统往往有这个问题)。再资料包里面有对应的微软运行库安装包双击安装即可。

4)在 IDEA 中创建一个 Maven 工程 HdfsClientDemo,并导入相应的依赖坐标+日志添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.1.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
</dependencies>

在项目的 src/main/resources 目录下,新建一个文件,命名为“log4j.properties”,在文件中填入

1
2
3
4
5
6
7
8
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

5)创建包名:com.layne.hdfs

6)创建 HdfsClient 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private FileSystem fs;

@Before
public void init() throws URISyntaxException, IOException, InterruptedException {
// 连接的集群nn地址,一定要获取NameNode的地址
URI uri = new URI("hdfs://wxler1:8020");
// 创建一个配置文件
Configuration configuration = new Configuration();
//configuration.set("dfs.replication", "2");
// 用户
String user = "wxler";

// 1 获取到了客户端对象
fs = FileSystem.get(uri, configuration, user);
}

@After
public void close() throws IOException {
// 3 关闭资源
fs.close();
}

// 创建目录
@Test
public void testmkdir() throws URISyntaxException, IOException, InterruptedException {
// 2 创建一个文件夹
fs.mkdirs(new Path("/xiyou/huaguoshan1"));
}

7)执行程序

客户端去操作 HDFS 时,是有一个用户身份的。默认情况下, HDFS 客户端 API 会从采用 Windows 默认用户访问 HDFS,会报权限异常错误。所以在访问 HDFS 时,一定要配置用户。

1
org.apache.hadoop.security.AccessControlException: Permission denied: user=56576, access=WRITE, inode="/xiyou/huaguoshan":atguigu:supergroup:drwxr-xr-x

3.2 HDFS 的 API 案例实操

3.2.1 HDFS 文件上传(测试参数优先级)

1)编写源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 参数优先级: 低=》高
* hdfs-default.xml => hdfs-site.xml=> 在项目资源目录下的配置文件 =》代码里面的配置
*
* @throws IOException
*/
@Test
public void testPut() throws IOException {
// 参数解读:参数一:表示删除原数据; 参数二:是否允许覆盖;参数三:原数据路径; 参数四:目的地路径
fs.copyFromLocalFile(false, true, new Path("D:\\test\\sunwukong.txt"), new Path("hdfs://wxler1/xiyou/huaguoshan"));
}

@Test
public void testPut2() throws IOException {
//如果目录不存在会自动创建目录,并把最后一级目录(这里为testhello)作为文件名
FSDataOutputStream fos = fs.create(new Path("/test/testHello"));

fos.write("hello world".getBytes());
}

2)resources 资源目录下新建hdfs-site.xml设置如下内容

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
</configuration>

3)参数优先级
参数优先级排序: (1) 客户端代码中设置的值 > (2) ClassPath 下的用户自定义配置文件 > (3) 然后是服务器的自定义配置 (xxx-site.xml) > (4)服务器的默认配置 (xxx-default.xml)

3.2.3 HDFS 文件下载

1
2
3
4
5
6
7
8
// 文件下载
@Test
public void testGet() throws IOException {
// 参数的解读:参数一:原文件是否删除;参数二:原文件路径HDFS; 参数三:目标地址路径Win ; 参数四:false开启校验,true不开启校验
fs.copyToLocalFile(false, new Path("/input/word.txt"), new Path("D:\\test\\"), false);
//这里path的hdfs://wxler1/前缀加不加都行
//fs.copyToLocalFile(false, new Path("hdfs://wxler1/input/word.txt"), new Path("D:\\test\\"), false);
}

注意:如果执行上面代码,下载不了文件,有可能是你电脑的微软支持的运行库少,需要安装一下微软运行库。

3.2.3 HDFS 文件更名和移动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 文件的更名和移动
@Test
public void testmv() throws IOException {
// 参数解读:参数1 :原文件路径; 参数2 :目标文件路径
// 对文件名称的修改
//fs.rename(new Path("/input/word.txt"), new Path("/input/ss.txt"));

// 文件的移动和更名
//fs.rename(new Path("/input/ss.txt"),new Path("/cls.txt"));

// 目录更名
fs.rename(new Path("/input"), new Path("/output"));

}

3.2.4 HDFS 删除文件和目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 删除
@Test
public void testRm() throws IOException {

// 参数解读:参数1:要删除的路径; 参数2 : 是否递归删除
// 删除文件
//fs.delete(new Path("/jdk-8u212-linux-x64.tar.gz"),false);

// 删除空目录
//fs.delete(new Path("/xiyou"), false);

// 删除非空目录
fs.delete(new Path("/jinguo"), true);
}

3.2.5 HDFS 文件详情查看

查看文件名称、权限、长度、块信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 获取文件详细信息
@Test
public void fileDetail() throws IOException {

// 获取所有文件信息
RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);

// 遍历文件
while (listFiles.hasNext()) {
LocatedFileStatus fileStatus = listFiles.next();

System.out.println("==========" + fileStatus.getPath() + "=========");
System.out.println(fileStatus.getPermission());
System.out.println(fileStatus.getOwner());
System.out.println(fileStatus.getGroup());
System.out.println(fileStatus.getLen());
System.out.println(fileStatus.getModificationTime());
System.out.println(fileStatus.getReplication());
System.out.println(fileStatus.getBlockSize());
System.out.println(fileStatus.getPath().getName());

// 获取块信息
BlockLocation[] blockLocations = fileStatus.getBlockLocations();

System.out.println(Arrays.toString(blockLocations));

}
}

3.2.6 HDFS 文件和文件夹判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 判断是文件夹还是文件
@Test
public void testFile() throws IOException {

FileStatus[] listStatus = fs.listStatus(new Path("/"));

for (FileStatus status : listStatus) {

if (status.isFile()) {
System.out.println("文件:" + status.getPath().getName());
} else {
System.out.println("目录:" + status.getPath().getName());
}
}
}

四.、HDFS 写数据流程

4.1 剖析文件写入

在这里插入图片描述
(1)客户端通过 DistributedFileSystem 模块(或对象)向 NameNode 请求上传文件,NameNode 检查目标文件是否已存在,父目录是否存在。
(2)NameNode 返回是否可以上传。
(3)客户端请求第一个 Block 上传到哪几个 DataNode 服务器上。
(4)NameNode 返回 3 个 DataNode 节点,分别为 dn1、dn2、dn3。(这一步要考虑服务器是否可用、距离最近原则、DataNode负载均衡)
(5) 客户端通过 FSDataOutputStream 模块请求 dn1(即DataNode1) 上传数据, dn1 收到请求会继续调用dn2,然后 dn2 调用 dn3,将这个通信管道建立完成
(6)dn1、dn2、dn3 逐级应答客户端
(7) 客户端开始往 dn1 上传第一个 Block (先从磁盘读取数据放到一个本地内存缓存),以 Packet 为单位,dn1 收到一个 Packet 就会传给 dn2,dn2 传给 dn3。【这里传输的packet大小是64K,这个64K的packet包含多个(chunk和chunksum),一个chunk是512byte,其校验码chunksum是4byte】。dn1 每传一个 packet会放入一个应答队列等待应答,当所有的DataNode应答成功后,会将该packet从应答队列中移除。
(8) 当一个 Block 传输完成之后,客户端再次请求 NameNode 上传第二个 Block 的服务
器。(重复执行 3-7 步)。

4.2 网络拓扑-节点距离计算

在 HDFS 写数据的过程中,NameNode 会选择距离待上传数据最近距离的 DataNode 接收数据。那么这个最近距离怎么计算呢?

节点距离:两个节点到达最近的共同祖先的距离总和(其实就是数路径个数)。

在这里插入图片描述
例如,假设有数据中心 d1 机架 r1 中的节点 n1。该节点可以表示为/d1/r1/n1。利用这种标记,上图给出四种距离描述。

大家算一算每两个节点之间的距离。
在这里插入图片描述

  • 9和3的距离是3
  • 10和4的距离是3
  • 9和6的距离是2

4.3 机架感知(副本存储节点选择)

1)机架感知说明
(1)官方说明
http://hadoop.apache.org/docs/r3.1.3/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html#Data_Replication

For the common case, when the replication factor is three, HDFS’s placement policy is to put one replica on the local machine if the writer is on a datanode, otherwise on a random datanode, another replica on a node in a different (remote) rack, and the last on a different node in the same remote rack. This policy cuts the inter-rack write traffic which generally improves write performance. The chance of rack failure is far less than that of node failure; this policy does not impact data reliability and availability guarantees. However, it does reduce the aggregate network bandwidth used when reading data since a block is placed in only two unique racks rather than three. With this policy, the replicas of a file do not evenly distribute across the racks. One third of replicas are on one node, two thirds of replicas are on one rack, and the other third are evenly distributed across the remaining racks. This policy improves write performance without compromising data reliability or read performance.

(2)源码说明
Crtl + n 查找 BlockPlacementPolicyDefault,在该类中查找 chooseTargetInOrder 方法。

2)Hadoop3.1.3 副本节点选择

在这里插入图片描述

  • 第一个副本在Client所处的节点上。如果客户端在集群外,随机选一个。
  • 第二个副本在另一个机架的随机一个节点
  • 第三个副本在第二个副本所在机架的随机节点

五、HDFS 读数据流程

在这里插入图片描述
(1)客户端通过 DistributedFileSystem (对象或模块)向 NameNode 请求下载文件,NameNode 通过查询元数据,找到文件块所在的 DataNode 地址。
(2)挑选一台 DataNode(就近原则,然后随机)服务器,请求读取数据。(这一步要考虑就近原则,负载均衡)
(3)DataNode 开始传输数据给客户端(从磁盘里面读取数据输入流,以 Packet 为单位来做校验),串行读取,即先读取第一个块,再读取第二个块拼接到上一个块后面。
(4)客户端以 Packet 为单位接收,先在本地缓存,然后写入目标文件。

六、NameNode 和 SecondaryNameNode

6.1 NN 和 2NN 工作机制

思考:NameNode 中的元数据是存储在哪里的?
首先,我们做个假设,如果存储在 NameNode 节点的磁盘中,因为经常需要进行随机访问,还有响应客户请求,必然是效率过低。因此,元数据需要存放在内存中。但如果只存在内存中,一旦断电,元数据丢失,整个集群就无法工作了。 因此产生在磁盘中备份元数据的FsImage

这样又会带来新的问题,当在内存中的元数据更新时,如果同时更新 FsImage,就会导致效率过低,但如果不更新,就会发生一致性问题,一旦 NameNode 节点断电,就会产生数据丢失。因此,引入Edits 文件(只进行追加操作,效率很高)。每当元数据有更新或者添加元数据时,修改内存中的元数据并追加到 Edits中。这样,一旦 NameNode 节点断电,可以通过 FsImage 和 Edits 的合并,合成元数据。

但是,如果长时间添加数据到 Edits 中,会导致该文件数据过大,效率降低,而且一旦断电,恢复元数据需要的时间过长。因此,需要定期进行 FsImage 和 Edits 的合并,如果这个操作由 NameNode 节点完成,又会效率过低。 因此,引入一个新的节点 SecondaryNamenode,专门用于 FsImage 和 Edits 的合并。

NameNode工作机制
在这里插入图片描述
1)第一阶段:NameNode 启动
(1)第一次启动 NameNode 格式化后,创建 fsimage 和 edits_inprogress_001 文件。如果不是第一次启动,直接加载编辑日志和镜像文件到内存。
(2)客户端对元数据进行增删改的请求。
(3)NameNode 记录操作日志,更新滚动日志(即先将客户端的操作追加到edits_inprogress_001 中)。
(4)NameNode 在内存中对元数据进行增删改(然后再对元数据进行修改)。

2)第二阶段:Secondary NameNode 工作
(1)Secondary NameNode 询问 NameNode 是否需要 CheckPoint。直接带回 NameNode是否检查结果。
(2)Secondary NameNode 请求执行 CheckPoint(即请求服务)。
(3)NameNode 滚动正在写的 edits_inprogress_001 日志,将其命名为edits_001,并生产新的日志文件edits_inprogress_002,以后再有客户端操作,日志将记录到edits_inprogress_002中。
(4)将滚动前的编辑日志edits_001和镜像文件fsimage拷贝到 SecondaryNameNode。
(5)Secondary NameNode 加载编辑日志和镜像文件到内存,并合并。
(6)生成新的镜像文件 fsimage.chkpoint。
(7)拷贝 fsimage.chkpoint 到 NameNode。
(8)NameNode 将 fsimage.chkpoint 重新命名成 fsimage。

6.2 Fsimage 和 Edits 解析

NameNode被格式化之后,将在/opt/module/hadoop-3.1.3/data/dfs/name/current目录中产生如下文件
在这里插入图片描述

(1)Fsimage文件:HDFS文件系统元数据的一个永久性的检查点,其中包含HDFS文件系统的所有目录和文件inode的序列化信息(保存的是文件目录信息、文件目录和文件的关系,文件和目录的拥有者和权限等信息,并不存储每个文件的block在哪个节点的哪个位置)。
(2)Edits文件:存放HDFS文件系统的所有更新操作的路径,文件系统客户端执行的所有写操作首先会被记录到Edits文件中。
(3)seen_txid文件保存的是一个数字,就是最后一个edits_的数字

1)oiv 查看 Fsimage 文件
(1)查看 oiv 和 oev 命令

1
2
3
4
5
6
7
8
9
10
11
[wxler@wxler1 current]$ hdfs oiv
Usage: bin/hdfs oiv [OPTIONS] -i INPUTFILE -o OUTPUTFILE
Offline Image Viewer
View a Hadoop fsimage INPUTFILE using the specified PROCESSOR,
saving the results in OUTPUTFILE.

[wxler@wxler1 current]$ hdfs oev
Usage: bin/hdfs oev [OPTIONS] -i INPUT_FILE -o OUTPUT_FILE
Offline edits viewer
Parse a Hadoop edits log file INPUT_FILE and save results
in OUTPUT_FILE.

(2)基本语法

1
hdfs oiv -p  输出后的件类型  -i 镜像文件  -o  转换后文件输出路径

(3)案例实操

1
2
3
4
[wxler@wxler1 current]$ pwd
/opt/module/hadoop-3.1.3/data/dfs/name/current
[wxler@wxler1 current]$ hdfs oiv -p XML -i fsimage_0000000000000000785 -o /opt/software/fsimage.xml
2021-04-01 15:27:49,788 INFO offlineImageViewer.FSImageHandler: Loading 3 strings

将显示的 xml 文件内容拷贝到 Idea 中创建的 xml 文件中,并格式化。显示结果如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?xml version="1.0"?>
<fsimage><version><layoutVersion>-64</layoutVersion><onDiskVersion>1</onDiskVersion><oivRevision>ba631c436b806728f8ec2f54ab1e289526c90579</oivRevision></version>
<NameSection><namespaceId>1997025465</namespaceId><genstampV1>1000</genstampV1><genstampV2>1088</genstampV2><genstampV1Limit>0</genstampV1Limit><lastAllocatedBlockId>1073741910</lastAllocatedBlockId><txid>785</txid></NameSection>
<ErasureCodingSection>
<erasureCodingPolicy>
<policyId>1</policyId><policyName>RS-6-3-1024k</policyName><cellSize>1048576</cellSize><policyState>DISABLED</policyState><ecSchema>
<codecName>rs</codecName><dataUnits>6</dataUnits><parityUnits>3</parityUnits></ecSchema>
</erasureCodingPolicy>

<erasureCodingPolicy>
<policyId>2</policyId><policyName>RS-3-2-1024k</policyName><cellSize>1048576</cellSize><policyState>DISABLED</policyState><ecSchema>
<codecName>rs</codecName><dataUnits>3</dataUnits><parityUnits>2</parityUnits></ecSchema>
</erasureCodingPolicy>

<erasureCodingPolicy>
<policyId>3</policyId><policyName>RS-LEGACY-6-3-1024k</policyName><cellSize>1048576</cellSize><policyState>DISABLED</policyState><ecSchema>
<codecName>rs-legacy</codecName><dataUnits>6</dataUnits><parityUnits>3</parityUnits></ecSchema>
</erasureCodingPolicy>

<erasureCodingPolicy>
<policyId>4</policyId><policyName>XOR-2-1-1024k</policyName><cellSize>1048576</cellSize><policyState>DISABLED</policyState><ecSchema>
<codecName>xor</codecName><dataUnits>2</dataUnits><parityUnits>1</parityUnits></ecSchema>
</erasureCodingPolicy>

<erasureCodingPolicy>
<policyId>5</policyId><policyName>RS-10-4-1024k</policyName><cellSize>1048576</cellSize><policyState>DISABLED</policyState><ecSchema>
<codecName>rs</codecName><dataUnits>10</dataUnits><parityUnits>4</parityUnits></ecSchema>
</erasureCodingPolicy>

</ErasureCodingSection>

<INodeSection><lastInodeId>16577</lastInodeId><numInodes>42</numInodes><inode><id>16385</id><type>DIRECTORY</type><name></name><mtime>1617241935401</mtime><permission>wxler:supergroup:0755</permission><nsquota>9223372036854775807</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16386</id><type>DIRECTORY</type><name>input</name><mtime>1617179030778</mtime><permission>wxler:supergroup:0755</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16387</id><type>FILE</type><name>word.txt</name><replication>3</replication><mtime>1617179030747</mtime><atime>1617241762636</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0644</permission><blocks><block><id>1073741825</id><genstamp>1001</genstamp><numBytes>41</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16388</id><type>FILE</type><name>jdk-8u212-linux-x64.tar.gz</name><replication>3</replication><mtime>1617179195102</mtime><atime>1617200154241</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0644</permission><blocks><block><id>1073741826</id><genstamp>1002</genstamp><numBytes>134217728</numBytes></block>
<block><id>1073741827</id><genstamp>1003</genstamp><numBytes>60795424</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16481</id><type>DIRECTORY</type><name>tmp</name><mtime>1617193613381</mtime><permission>wxler:supergroup:0700</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16482</id><type>DIRECTORY</type><name>hadoop-yarn</name><mtime>1617183460322</mtime><permission>wxler:supergroup:0700</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16483</id><type>DIRECTORY</type><name>staging</name><mtime>1617183479242</mtime><permission>wxler:supergroup:0700</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16484</id><type>DIRECTORY</type><name>wxler</name><mtime>1617183460322</mtime><permission>wxler:supergroup:0700</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16485</id><type>DIRECTORY</type><name>.staging</name><mtime>1617193660199</mtime><permission>wxler:supergroup:0700</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16491</id><type>DIRECTORY</type><name>history</name><mtime>1617192501743</mtime><permission>wxler:supergroup:0755</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16492</id><type>DIRECTORY</type><name>done_intermediate</name><mtime>1617183479283</mtime><permission>wxler:supergroup:1777</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16493</id><type>DIRECTORY</type><name>wxler</name><mtime>1617193668311</mtime><permission>wxler:supergroup:0770</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16506</id><type>FILE</type><name>job_1617183364434_0001-1617183465062-wxler-word+count-1617183512363-1-1-SUCCEEDED-default-1617183485850.jhist</name><replication>3</replication><mtime>1617183512613</mtime><atime>1617192833535</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0770</permission><blocks><block><id>1073741873</id><genstamp>1049</genstamp><numBytes>22313</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16507</id><type>FILE</type><name>job_1617183364434_0001_conf.xml</name><replication>3</replication><mtime>1617183512745</mtime><atime>1617183512638</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0770</permission><blocks><block><id>1073741874</id><genstamp>1050</genstamp><numBytes>214438</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16508</id><type>DIRECTORY</type><name>done</name><mtime>1617192683004</mtime><permission>wxler:supergroup:0770</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16509</id><type>DIRECTORY</type><name>2021</name><mtime>1617192683004</mtime><permission>wxler:supergroup:0770</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16510</id><type>DIRECTORY</type><name>03</name><mtime>1617192683004</mtime><permission>wxler:supergroup:0770</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16511</id><type>DIRECTORY</type><name>31</name><mtime>1617192683004</mtime><permission>wxler:supergroup:0770</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16512</id><type>DIRECTORY</type><name>000000</name><mtime>1617193668311</mtime><permission>wxler:supergroup:0770</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16530</id><type>FILE</type><name>job_1617183364434_0002-1617192796187-wxler-word+count-1617192836116-1-1-SUCCEEDED-default-1617192808343.jhist</name><replication>3</replication><mtime>1617192837231</mtime><atime>1617192837151</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0770</permission><blocks><block><id>1073741883</id><genstamp>1059</genstamp><numBytes>22312</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16531</id><type>FILE</type><name>job_1617183364434_0002_conf.xml</name><replication>3</replication><mtime>1617192837335</mtime><atime>1617192837251</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0770</permission><blocks><block><id>1073741884</id><genstamp>1060</genstamp><numBytes>214430</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16537</id><type>DIRECTORY</type><name>logs</name><mtime>1617193613519</mtime><permission>wxler:wxler:1777</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16538</id><type>DIRECTORY</type><name>wxler</name><mtime>1617193613527</mtime><permission>wxler:wxler:0770</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16539</id><type>DIRECTORY</type><name>logs-tfile</name><mtime>1617193613532</mtime><permission>wxler:wxler:0770</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16540</id><type>DIRECTORY</type><name>application_1617193351532_0001</name><mtime>1617193667187</mtime><permission>wxler:wxler:0770</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16542</id><type>DIRECTORY</type><name>output</name><mtime>1617193657742</mtime><permission>wxler:supergroup:0755</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16548</id><type>FILE</type><name>part-r-00000</name><replication>3</replication><mtime>1617193657514</mtime><atime>1617193657020</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0644</permission><blocks><block><id>1073741891</id><genstamp>1067</genstamp><numBytes>36</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16550</id><type>FILE</type><name>_SUCCESS</name><replication>3</replication><mtime>1617193657756</mtime><atime>1617193657742</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0644</permission><storagePolicyId>0</storagePolicyId></inode>
<inode><id>16553</id><type>FILE</type><name>job_1617193351532_0001-1617193609664-wxler-word+count-1617193657905-1-1-SUCCEEDED-default-1617193629222.jhist</name><replication>3</replication><mtime>1617193658493</mtime><atime>1617193658335</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0770</permission><blocks><block><id>1073741893</id><genstamp>1069</genstamp><numBytes>22312</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16554</id><type>FILE</type><name>job_1617193351532_0001_conf.xml</name><replication>3</replication><mtime>1617193658907</mtime><atime>1617193658550</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0770</permission><blocks><block><id>1073741894</id><genstamp>1070</genstamp><numBytes>214605</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16555</id><type>FILE</type><name>wxler2_38923</name><replication>3</replication><mtime>1617193667153</mtime><atime>1617193666741</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:wxler:0640</permission><blocks><block><id>1073741895</id><genstamp>1071</genstamp><numBytes>133415</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16562</id><type>DIRECTORY</type><name>sanguo</name><mtime>1617202922040</mtime><permission>wxler:supergroup:0755</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16564</id><type>DIRECTORY</type><name>jinguo</name><mtime>1617202922040</mtime><permission>wxler:supergroup:0755</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16565</id><type>FILE</type><name>shuguo.txt</name><replication>10</replication><mtime>1617202640991</mtime><atime>1617202640469</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0644</permission><blocks><block><id>1073741902</id><genstamp>1080</genstamp><numBytes>7</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16566</id><type>FILE</type><name>wuguo.txt</name><replication>3</replication><mtime>1617202754263</mtime><atime>1617202753913</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0644</permission><blocks><block><id>1073741903</id><genstamp>1081</genstamp><numBytes>6</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16567</id><type>FILE</type><name>weibo.txt</name><replication>3</replication><mtime>1617202773064</mtime><atime>1617202772773</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0644</permission><blocks><block><id>1073741904</id><genstamp>1082</genstamp><numBytes>6</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16568</id><type>DIRECTORY</type><name>xiyou</name><mtime>1617241702332</mtime><permission>wxler:supergroup:0755</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16571</id><type>DIRECTORY</type><name>huaguoshan</name><mtime>1617243483208</mtime><permission>wxler:supergroup:0755</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16572</id><type>FILE</type><name>sanguo.txt</name><replication>3</replication><mtime>1617241739247</mtime><atime>1617246645971</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0644</permission><blocks><block><id>1073741906</id><genstamp>1084</genstamp><numBytes>6</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16574</id><type>DIRECTORY</type><name>test</name><mtime>1617241935402</mtime><permission>wxler:supergroup:0755</permission><nsquota>-1</nsquota><dsquota>-1</dsquota></inode>
<inode><id>16575</id><type>FILE</type><name>testHello</name><replication>3</replication><mtime>1617241935843</mtime><atime>1617241935402</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0644</permission><blocks><block><id>1073741908</id><genstamp>1086</genstamp><numBytes>11</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
<inode><id>16577</id><type>FILE</type><name>sunwukong.txt</name><replication>2</replication><mtime>1617243483601</mtime><atime>1617243483208</atime><preferredBlockSize>134217728</preferredBlockSize><permission>wxler:supergroup:0644</permission><blocks><block><id>1073741910</id><genstamp>1088</genstamp><numBytes>9</numBytes></block>
</blocks>
<storagePolicyId>0</storagePolicyId></inode>
</INodeSection>
<INodeReferenceSection></INodeReferenceSection><SnapshotSection><snapshotCounter>0</snapshotCounter><numSnapshots>0</numSnapshots></SnapshotSection>
<INodeDirectorySection><directory><parent>16385</parent><child>16386</child><child>16388</child><child>16564</child><child>16542</child><child>16562</child><child>16574</child><child>16481</child><child>16568</child></directory>
<directory><parent>16386</parent><child>16387</child></directory>
<directory><parent>16481</parent><child>16482</child><child>16537</child></directory>
<directory><parent>16482</parent><child>16483</child></directory>
<directory><parent>16483</parent><child>16491</child><child>16484</child></directory>
<directory><parent>16484</parent><child>16485</child></directory>
<directory><parent>16491</parent><child>16508</child><child>16492</child></directory>
<directory><parent>16492</parent><child>16493</child></directory>
<directory><parent>16508</parent><child>16509</child></directory>
<directory><parent>16509</parent><child>16510</child></directory>
<directory><parent>16510</parent><child>16511</child></directory>
<directory><parent>16511</parent><child>16512</child></directory>
<directory><parent>16512</parent><child>16506</child><child>16507</child><child>16530</child><child>16531</child><child>16553</child><child>16554</child></directory>
<directory><parent>16537</parent><child>16538</child></directory>
<directory><parent>16538</parent><child>16539</child></directory>
<directory><parent>16539</parent><child>16540</child></directory>
<directory><parent>16540</parent><child>16555</child></directory>
<directory><parent>16542</parent><child>16550</child><child>16548</child></directory>
<directory><parent>16562</parent><child>16567</child></directory>
<directory><parent>16564</parent><child>16565</child><child>16566</child></directory>
<directory><parent>16568</parent><child>16571</child></directory>
<directory><parent>16571</parent><child>16572</child><child>16577</child></directory>
<directory><parent>16574</parent><child>16575</child></directory>
</INodeDirectorySection>
<FileUnderConstructionSection></FileUnderConstructionSection>
<SecretManagerSection><currentId>0</currentId><tokenSequenceNumber>0</tokenSequenceNumber><numDelegationKeys>0</numDelegationKeys><numTokens>0</numTokens></SecretManagerSection><CacheManagerSection><nextDirectiveId>1</nextDirectiveId><numDirectives>0</numDirectives><numPools>0</numPools></CacheManagerSection>
</fsimage>

思考:可以看出,Fsimage 中没有记录块所对应 DataNode,为什么?

在集群启动后,要求 DataNode 上报数据块信息,并间隔一段时间后再次上报。

2)oev 查看 Edits 文件
(1)基本语法

1
hdfs oev -p  转换后的文件类型  -i 编辑日志  -o  转换后文件输出路径

(2)案例实操

1
2
3
[wxler@wxler1 current]$ hdfs oev -p XML -i edits_inprogress_0000000000000000786 -o /opt/software/edits.xml
[wxler@wxler1 current]$ pwd
/opt/module/hadoop-3.1.3/data/dfs/name/current

将显示的 xml 文件内容拷贝到 Idea 中创建的 xml 文件中,并格式化。显示结果如下。

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<EDITS>
<EDITS_VERSION>-64</EDITS_VERSION>
<RECORD>
<OPCODE>OP_START_LOG_SEGMENT</OPCODE>
<DATA>
<TXID>786</TXID>
</DATA>
</RECORD>
</EDITS>

可以看到,edits记录了操作,只不过这段时间操作比较少。

思考:NameNode 如何确定下次开机启动的时候合并哪些 Edits?
可以根据seen_txid文件保存的是一个数字,seen_txid保存的就是最后一个edits_的数字,是最新的edits。

6.3 CheckPoint 时间设置

1)通常情况下,SecondaryNameNode 每隔一小时执行一次,或每执行一百万次事务执行一次(每隔60s检查一次事务操作次数)。
查看hdfs-default.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<property>
<name>dfs.namenode.checkpoint.period</name>
<value>3600s</value>
<description>
The number of seconds between two periodic checkpoints.
Support multiple time unit suffix(case insensitive), as described
in dfs.heartbeat.interval.
</description>
</property>

<property>
<name>dfs.namenode.checkpoint.txns</name>
<value>1000000</value>
<description>The Secondary NameNode or CheckpointNode will create a checkpoint
of the namespace every 'dfs.namenode.checkpoint.txns' transactions, regardless
of whether 'dfs.namenode.checkpoint.period' has expired.
</description>
</property>

<property>
<name>dfs.namenode.checkpoint.check.period</name>
<value>60s</value>
<description>The SecondaryNameNode and CheckpointNode will poll the NameNode
every 'dfs.namenode.checkpoint.check.period' seconds to query the number
of uncheckpointed transactions. Support multiple time unit suffix(case insensitive),
as described in dfs.heartbeat.interval.
</description>
</property>

可以在hdfs-site.xml里进行修改

七、DataNode

7.1 DataNode 工作机制

在这里插入图片描述

(1)一个数据块在 DataNode 上以文件形式存储在磁盘上,包括两个文件,一个是数据本身,一个是元数据包括数据块的长度,块数据的校验和,以及时间戳。
(2) DataNode 启动后向 NameNode 注册,通过后,周期性(6 小时) 的向 NameNode 上报所有的块信息。

DN 扫描自己节点块信息列表的时间,默认 6 小时,目的是查好DN中的块是否完好

1
2
3
4
5
6
7
8
9
<property>
<name>dfs.datanode.directoryscan.interval</name>
<value>21600s</value>
<description>Interval in seconds for Datanode to scan data directories and
reconcile the difference between blocks in memory and on the disk.
Support multiple time unit suffix(case insensitive), as described
in dfs.heartbeat.interval.
</description>
</property>

DN 向 NN 汇报当前解读信息的时间间隔(将完好的块信息报告给NN),默认 6 小时;

1
2
3
4
5
<property>
<name>dfs.blockreport.intervalMsec</name>
<value>21600000</value>
<description>Determines block reporting interval in milliseconds.</description>
</property>

(3)心跳是每 3 秒一次,心跳返回结果带有 NameNode 给该 DataNode 的命令如复制块数据到另一台机器,或删除某个数据块。 如果超过 10 分钟 + 30s 没有收到某个 DataNode 的心跳,则认为该节点不可用。

(4)集群运行中可以安全加入和退出一些机器。

7.2 数据完整性

思考:如果电脑磁盘里面存储的数据是控制高铁信号灯的红灯信号 (1)和绿灯信号 (0) ,但是存储该数据的磁盘坏了,一直显示是绿灯,是否很危险?同理 DataNode 节点上的数据损坏了,却没有发现,是否也很危险,那么如何解决呢?

思考:如果电脑磁盘里面存储的数据是控制高铁信号灯的红灯信号 (1)和绿灯信号 (0) ,但是存储该数据的磁盘坏了,一直显示是绿灯,是否很危险?同理 DataNode 节点上的数据损坏了,却没有发现,是否也很危险,那么如何解决呢?
如下是 DataNode 节点保证数据完整性的方法。
(1)当 DataNode 读取 Block 的时候,它会计算 CheckSum。
(2)如果计算后的 CheckSum,与 Block 创建时值不一样,说明 Block 已经损坏。
(3)Client 读取其他 DataNode 上的 Block。
(4)常见的校验算法 crc(32),md5(128),sha1(160),hadoop采用的是crc(32校验)
(5)DataNode 在其文件创建后周期验证 CheckSum。

循环冗余校验补充

在发送端,先把数据划分为组,假定每组k个比特。现假定待传送的数据M=101001(k=6). CRC运算就是在数据M的后面添加供差错检测用的n位冗余码,然后构成一个帧发送出去,一共发送(k+n)位。在所要发送的数据后面增加n位的冗余码,虽然增大了数据传输的开销,但却可以进行差错检测。 当传输可能出现差错时,付出这种代价往往是很值得的。

在接收端把接收到的数据以帧为单位进行 CRC 检验: 把收到的每一个帧都除以同样的除数P(模2运算),然后检查得到的余数R。如果在传输过程中无差错,那么经过CRC 检验后得出的余数R肯定是0(读者可以自己验算一下。被除数现在是101001001,而除数是P=1101,看余数R是否为0)。
但如果出现误码,那么余数 R 仍等于零的概率是非常非常小的。

7.3 掉线时限参数设置

在这里插入图片描述

需要注意的是 hdfs-site.xml 配置文件中的 heartbeat.recheck.interval 的单位为毫秒,dfs.heartbeat.interval 的单位为秒。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<property>
<name>dfs.namenode.heartbeat.recheck-interval</name>
<value>300000</value>
<description>
This time decides the interval to check for expired datanodes.
With this value and dfs.heartbeat.interval, the interval of
deciding the datanode is stale or not is also calculated.
The unit of this configuration is millisecond.
</description>
</property>

<property>
<name>dfs.heartbeat.interval</name>
<value>3s</value>
<description>
Determines datanode heartbeat interval in seconds.
Can use the following suffix (case insensitive):
ms(millis), s(sec), m(min), h(hour), d(day)
to specify the time (such as 2s, 2m, 1h, etc.).
Or provide complete number in seconds (such as 30 for 30 seconds).
</description>
</property>