【Elasticsearch源码】 节点关闭分析
带着疑问学源码,第六篇:Elasticsearch 节点关闭分析
代码分析基于:https://github.com/jiankunking/elasticsearch
Elasticsearch 8.0.0-SNAPSHOT
目的
在看源码之前先梳理一下,自己对于节点关闭流程疑惑的点:
- 节点关闭都做了哪些检查?
- kill ES进程来关闭节点是否安全?
- 普通节点关闭与Master节点关闭有什么区别?
- 正在写入数据的节点,在关闭的时候,会发生什么?
源码分析
在节点启动过程中,Bootstrap#setup方法中添加了shutdown hook,当进程收到系统SIGTERM(kill命令默认信号 15)或SIGINT(2)信号时,调用Node#close方法,执行节点关闭流程。
每个模块的Service中都实现了doStop和doClose,用于处理这个模块的正常关闭流程。节点总的关闭流程位于Node#close,在close方法的实现中,先调用一遍各个模块的doStop,然后再次遍历各个模块执行doClose。
1 | // During concurrent close() calls we want to make sure that all of them return after the node has completed it's shutdown cycle. |
各模块的关闭有一定的顺序关系,以 doStop 为例,按下表所示的 顺序调用各模块 doStop方法。
| 服务 | 简介 |
|---|---|
| ResourceWatcherService | 通用资源监视服务 |
| HttpServerTransport | HTTP 传输服务,提供REST接口服务 |
| SnapshotsService | 快照服务 |
| SnapshotShardsService | 负责启动和停止shard级快照 |
| RepositoriesService | Service responsible for maintaining and providing access to snapshot repositories on nodes |
| IndicesClusterStateService | 收到集群状态信息后,处理其中索引相关操作 |
| Discovery | 集群拓扑管理 |
| ClusterService | 集群管理服务,主要处理集群任务,发布集群状态 |
| NodeConnectionsService | 节点连接管理服务 |
| FsHealthService | Runs periodically and attempts to create a temp file to see if the filesystem is writable. If not then it marks the path as unhealthy |
| MonitorService | 提供进程级、系统级、文件系统和 JVM 的监控服务 |
| GatewayService | 负责集群元数据持久化与恢复 |
| SearchService | 处理搜索请求 |
| TransportService | 底层传输服务 |
| plugins | 当前的所有插件 |
| IndicesService | 负责创建、删除索引等索引操作 |
综合来看,关闭顺序大致如下∶
- 关闭快照和HTTPServer,不再响应用户REST请求。
- 关闭集群拓扑管理,不再响应ping请求。
- 关闭网络模块,让节点离线。
- 执行各个插件的关闭流程。
- 关闭IndicesService。
最后才关闭IndicesService,是因为这期间需要等待释放的资源最多,时间最长。
下面着重看一下IndicesService的doStop:
1 | @Override |
那什么时候会导致removeIndex执行一直无法返回呢?
1 | IndicesService removeIndex(final Index index, final IndexRemovalReason reason, final String extraInfo)=> |
下面具体看一下flushAndClose():
1 | /** |
总结
kill -15/-2 ElasticSearch是可以正常退出的。
正在写入数据的节点,在关闭的时候,需要等待数据写入完成或者超时。
主节点被关闭时,没有想象中的特殊处理,节点正常执行关闭流程,当TransportService模块被关闭后,集群重新选举新Master。因此,滚动重启期间会有一段时间处于无主状态。
该部分等看集群选举部分的时候,再细看一下。
📚 系列文章 · Elasticsearch 源码分析