(三)elasticsearch 源码之启动流程分析

https://www.cnblogs.com/darcy-yuan/p/17007635.html

1.前面我们在《(一)elasticsearch 编译和启动》和 《(二)elasticsearch 源码目录 》简单了解下es(elasticsearch,下同),现在我们来看下启动代码

下面是启动流程图,我们按照流程图的顺序依次描述

2.启动流程

org.elasticsearch.bootstrap.Elasticsearchpublic static void main(final String[] args) throws Exception {overrideDnsCachePolicyProperties();/** We want the JVM to think there is a security manager installed so that if internal policy decisions that would be based on the* presence of a security manager or lack thereof act as if there is a security manager present (e.g., DNS cache policy). This* forces such policies to take effect immediately.*/System.setSecurityManager(new SecurityManager() {@Overridepublic void checkPermission(Permission perm) {// grant all permissions so that we can later set the security manager to the one that we want}});LogConfigurator.registerErrorListener();final Elasticsearch elasticsearch = new Elasticsearch();int status = main(args, elasticsearch, Terminal.DEFAULT);if (status != ExitCodes.OK) {exit(status);}}

后续执行 Elasticsearch.execute -> Elasticsearch.init -> Bootstrap.init

org.elasticsearch.bootstrap.Bootstrapstatic void init(final boolean foreground,final Path pidFile,final boolean quiet,final Environment initialEnv) throws BootstrapException, NodeValidationException, UserException {// force the class initializer for BootstrapInfo to run before// the security manager is installedBootstrapInfo.init();INSTANCE = new Bootstrap();// 安全配置文件final SecureSettings keystore = loadSecureSettings(initialEnv);final Environment environment = createEnvironment(pidFile, keystore, initialEnv.settings(), initialEnv.configFile());LogConfigurator.setNodeName(Node.NODE_NAME_SETTING.get(environment.settings()));try {LogConfigurator.configure(environment);} catch (IOException e) {throw new BootstrapException(e);}if (JavaVersion.current().compareTo(JavaVersion.parse("11")) < 0) {final String message = String.format(Locale.ROOT,"future versions of Elasticsearch will require Java 11; " +"your Java version from [%s] does not meet this requirement",System.getProperty("java.home"));new DeprecationLogger(LogManager.getLogger(Bootstrap.class)).deprecated(message);}// 处理pidFileif (environment.pidFile() != null) {try {PidFile.create(environment.pidFile(), true);} catch (IOException e) {throw new BootstrapException(e);}}// 如果是后台启动,则不打印日志final boolean closeStandardStreams = (foreground == false) || quiet;try {if (closeStandardStreams) {final Logger rootLogger = LogManager.getRootLogger();final Appender maybeConsoleAppender = Loggers.findAppender(rootLogger, ConsoleAppender.class);if (maybeConsoleAppender != null) {Loggers.removeAppender(rootLogger, maybeConsoleAppender);}closeSystOut();}// fail if somebody replaced the lucene jarscheckLucene();// 通用异常捕获// install the default uncaught exception handler; must be done before security is// initialized as we do not want to grant the runtime permission// setDefaultUncaughtExceptionHandlerThread.setDefaultUncaughtExceptionHandler(new ElasticsearchUncaughtExceptionHandler());INSTANCE.setup(true, environment);try {// any secure settings must be read during node constructionIOUtils.close(keystore);} catch (IOException e) {throw new BootstrapException(e);}INSTANCE.start();if (closeStandardStreams) {closeSysError();}}

这里我们可以关注下  INSTANCE.setup(true, environment);

org.elasticsearch.bootstrap.Bootstrapprivate void setup(boolean addShutdownHook, Environment environment) throws BootstrapException {Settings settings = environment.settings();try {spawner.spawnNativeControllers(environment);} catch (IOException e) {throw new BootstrapException(e);}// 检查一些mlock设定initializeNatives(environment.tmpFile(),BootstrapSettings.MEMORY_LOCK_SETTING.get(settings),BootstrapSettings.SYSTEM_CALL_FILTER_SETTING.get(settings),BootstrapSettings.CTRLHANDLER_SETTING.get(settings));// 探针// initialize probes before the security manager is installedinitializeProbes();if (addShutdownHook) {Runtime.getRuntime().addShutdownHook(new Thread() {@Overridepublic void run() {try {IOUtils.close(node, spawner);LoggerContext context = (LoggerContext) LogManager.getContext(false);Configurator.shutdown(context);if (node != null && node.awaitClose(10, TimeUnit.SECONDS) == false) {throw new IllegalStateException("Node didn't stop within 10 seconds. " +"Any outstanding requests or tasks might get killed.");}} catch (IOException ex) {throw new ElasticsearchException("failed to stop node", ex);} catch (InterruptedException e) {LogManager.getLogger(Bootstrap.class).warn("Thread got interrupted while waiting for the node to shutdown.");Thread.currentThread().interrupt();}}});}try {// 检查类加载的一些问题// look for jar hellfinal Logger logger = LogManager.getLogger(JarHell.class);JarHell.checkJarHell(logger::debug);} catch (IOException | URISyntaxException e) {throw new BootstrapException(e);}// Log ifconfig output before SecurityManager is installedIfConfig.logIfNecessary();// 安全处理// install SM after natives, shutdown hooks, etc.try {Security.configure(environment, BootstrapSettings.SECURITY_FILTER_BAD_DEFAULTS_SETTING.get(settings));} catch (IOException | NoSuchAlgorithmException e) {throw new BootstrapException(e);}node = new Node(environment) {@Overrideprotected void validateNodeBeforeAcceptingRequests(final BootstrapContext context,final BoundTransportAddress boundTransportAddress, List<BootstrapCheck> checks) throws NodeValidationException {BootstrapChecks.check(context, boundTransportAddress, checks);}};}

最后一句 node = new Node(environment) 初始化了节点,里面做了许多工作

org.elasticsearch.node.Nodeprotected Node(final Environment environment, Collection<Class<? extends Plugin>> classpathPlugins, boolean forbidPrivateIndexSettings) {...// 打印jvm信息final JvmInfo jvmInfo = JvmInfo.jvmInfo();logger.info("version[{}], pid[{}], build[{}/{}/{}/{}], OS[{}/{}/{}], JVM[{}/{}/{}/{}]",Build.CURRENT.getQualifiedVersion(),jvmInfo.pid(),Build.CURRENT.flavor().displayName(),Build.CURRENT.type().displayName(),Build.CURRENT.hash(),Build.CURRENT.date(),Constants.OS_NAME,Constants.OS_VERSION,Constants.OS_ARCH,Constants.JVM_VENDOR,Constants.JVM_NAME,Constants.JAVA_VERSION,Constants.JVM_VERSION);
...// 初始化各类服务,以及他们相关的依赖this.pluginsService = new PluginsService(tmpSettings, environment.configFile(), environment.modulesFile(),environment.pluginsFile(), classpathPlugins);final Settings settings = pluginsService.updatedSettings();final Set<DiscoveryNodeRole> possibleRoles = Stream.concat(DiscoveryNodeRole.BUILT_IN_ROLES.stream(),pluginsService.filterPlugins(Plugin.class).stream().map(Plugin::getRoles).flatMap(Set::stream)).collect(Collectors.toSet());DiscoveryNode.setPossibleRoles(possibleRoles);localNodeFactory = new LocalNodeFactory(settings, nodeEnvironment.nodeId());
...// guice注入modules.add(b -> {b.bind(Node.class).toInstance(this);b.bind(NodeService.class).toInstance(nodeService);b.bind(NamedXContentRegistry.class).toInstance(xContentRegistry);b.bind(PluginsService.class).toInstance(pluginsService);b.bind(Client.class).toInstance(client);b.bind(NodeClient.class).toInstance(client);b.bind(Environment.class).toInstance(this.environment);b.bind(ThreadPool.class).toInstance(threadPool);

es 使用 guice注入框架,guice是个非常轻量级的依赖注入框架,既然各个组件都已经注入好了,我们现在可以启动了。

INSTANCE.start -> Bootstrap.start

org.elasticsearch.bootstrap.Bootstrapprivate void start() throws NodeValidationException {node.start();keepAliveThread.start();}

 node.start中启动各个组件。es中的各个组件继承了 AbstractLifecycleComponent。start方法会调用组件的doStart方法。

org.elasticsearch.node.Nodepublic Node start() throws NodeValidationException {if (!lifecycle.moveToStarted()) {return this;}logger.info("starting ...");pluginLifecycleComponents.forEach(LifecycleComponent::start);injector.getInstance(MappingUpdatedAction.class).setClient(client);injector.getInstance(IndicesService.class).start();injector.getInstance(IndicesClusterStateService.class).start();injector.getInstance(SnapshotsService.class).start();injector.getInstance(SnapshotShardsService.class).start();injector.getInstance(SearchService.class).start();nodeService.getMonitorService().start();final ClusterService clusterService = injector.getInstance(ClusterService.class);final NodeConnectionsService nodeConnectionsService = injector.getInstance(NodeConnectionsService.class);nodeConnectionsService.start();clusterService.setNodeConnectionsService(nodeConnectionsService);...

具体的我们看两个比较重要的服务  transportService.start();

org.elasticsearch.transport.TransportService@Overrideprotected void doStart() {transport.setMessageListener(this);connectionManager.addListener(this);// 建立网络连接transport.start();if (transport.boundAddress() != null && logger.isInfoEnabled()) {logger.info("{}", transport.boundAddress());for (Map.Entry<String, BoundTransportAddress> entry : transport.profileBoundAddresses().entrySet()) {logger.info("profile [{}]: {}", entry.getKey(), entry.getValue());}}localNode = localNodeFactory.apply(transport.boundAddress());if (connectToRemoteCluster) {// here we start to connect to the remote clustersremoteClusterService.initializeRemoteClusters();}}

启动transport的实现类是 SecurityNetty4HttpServerTransport

 另一个比较重要的服务,discovery.start(),具体实现类是 Coordinator

org.elasticsearch.cluster.coordination.Coordinator@Overrideprotected void doStart() {synchronized (mutex) {CoordinationState.PersistedState persistedState = persistedStateSupplier.get();coordinationState.set(new CoordinationState(getLocalNode(), persistedState, electionStrategy));peerFinder.setCurrentTerm(getCurrentTerm());configuredHostsResolver.start();final ClusterState lastAcceptedState = coordinationState.get().getLastAcceptedState();if (lastAcceptedState.metaData().clusterUUIDCommitted()) {logger.info("cluster UUID [{}]", lastAcceptedState.metaData().clusterUUID());}final VotingConfiguration votingConfiguration = lastAcceptedState.getLastCommittedConfiguration();if (singleNodeDiscovery &&votingConfiguration.isEmpty() == false &&votingConfiguration.hasQuorum(Collections.singleton(getLocalNode().getId())) == false) {throw new IllegalStateException("cannot start with [" + DiscoveryModule.DISCOVERY_TYPE_SETTING.getKey() + "] set to [" +DiscoveryModule.SINGLE_NODE_DISCOVERY_TYPE + "] when local node " + getLocalNode() +" does not have quorum in voting configuration " + votingConfiguration);}...

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/672151.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

IP风险画像在企业网络统计与安全防范中应用

随着企业在数字化时代的迅速发展&#xff0c;网络安全问题变得尤为突出。IP风险画像作为一种全面的网络安全工具&#xff0c;在企业网络统计与安全防范中展现出卓越的应用价值。本文将以一个实际案例为例&#xff0c;深入探讨IP风险画像在企业网络中的成功应用&#xff0c;以及…

SPSS基础操作:对数据进行加权处理

对数据进行加权处理是我们使用SPSS提供某些分析方法的重要前提。对数据进行加权后&#xff0c;当前的权重将被保存在数据中。当进行相应的分析时&#xff0c;用户无须再次进行加权操作。本节以对广告的效果观测为例&#xff0c;讲解数据的加权操作。本例给出了消费者购买行为与…

Arthas使用教程—— 阿里开源线上监控诊断产品

文章目录 1 简介2背景3 图形界面工具 arthas 阿里开源3.1 &#xff1a;启动 arthas3.2 help :查看arthas所有命令3.3 查看 dashboard3.4 thread 列出当前进程所有线程占用CPU和内存情况3.5 jvm 查看该进程的各项参数 &#xff08;类比 jinfo&#xff09;3.6 通过 jad 来反编译 …

端口扫描神器:御剑 保姆级教程(附链接)

一、介绍 御剑&#xff08;YooScan&#xff09;是一款网络安全工具&#xff0c;主要用于进行端口扫描。它具有直观的用户界面&#xff0c;方便用户进行端口扫描和信息收集。以下是御剑端口扫描工具的一些主要特点和功能&#xff1a; 图形用户界面&#xff1a; 御剑提供直观的图…

10分钟快速入门正则表达式

在力扣上看了一本付费书籍&#xff0c;终于让我入门了正则表达事... 问题&#xff1a; "^1[3-9]\\d{9}$" 是啥意思 读完本篇小笔记&#xff0c;你就知道&#xff0c;啥是"^1[3-9]\\d{9}$" 这个是啥意思了。 首先&#xff0c;正则表达式&#xff0c;这个名…

告别mPDF迎来TCPDF和中文打印遇到的问题

mPDF是一个用PHP编写的开源PDF生成库。它最初由Claus Holler创建&#xff0c;于2004年发布。原来用开源软件打印中文没有问题&#xff0c;最近发现新的软件包中mPDF被TCPDF代替了&#xff0c;当然如果只用西文的PDF是没有发现问题&#xff0c;但要打印中文就有点抓瞎了如图1&am…

为什么深仇大恨可以刻骨铭心?背诵课文有哪些方法?为什么这么难记住?历史上有没有过目不忘的人或好的记忆方案?超级学习方法1刻脑

为什么深仇大恨可以刻骨铭心&#xff1f; 深仇大恨能刻骨铭心主要是因为强烈的情绪体验对人的记忆有着深远的影响。这种现象可以从心理学和神经科学的角度来解释&#xff1a; 心理学视角 情绪加强记忆&#xff1a;情绪激烈的事件比那些情绪中性的事件更容易被记住。这是因为强…

我的PyTorch模型比内存还大,怎么训练呀?

原文&#xff1a;我的PyTorch模型比内存还大&#xff0c;怎么训练呀&#xff1f; - 知乎 看了一篇比较老&#xff08;21年4月文章&#xff09;的不大可能训练优化方案&#xff0c;保存起来以后研究一下。 随着深度学习的飞速发展&#xff0c;模型越来越臃肿&#xff0c;哦不&a…

vue element 组件 form深层 :prop 验证失效问题解决

此图源自官网 借鉴。 当我们简单单层验证的时候发现是没有问题的&#xff0c;但是有的时候可能会涉及到深层prop&#xff0c;发现在去绑定的时候就不生效了。例如我们在form单里面循环验证&#xff0c;在去循环数据验证。 就如下图的写法了 :prop"pumplist. i .device…

Redis缓存设计及优化

缓存设计 缓存穿透 缓存穿透是指查询一个根本不存在的数据&#xff0c; 缓存层和存储层都不会命中&#xff0c; 通常出于容错的考虑&#xff0c; 如果从存储层查不到数据则不写入缓存层。 缓存穿透将导致不存在的数据每次请求都要到存储层去查询&#xff0c; 失去了缓存保护后…

Pandas 对带有 Multi-column(多列名称) 的数据排序并写入 Excel 中

Pandas 从Excel 中读取带有 Multi-column的数据 正文 正文 我们使用如下方式写入数据&#xff1a; import pandas as pd import numpy as npdf pd.DataFrame(np.array([[10, 2, 0], [6, 1, 3], [8, 10, 7], [1, 3, 7]]), columns[[Number, Name, Name, ], [col 1, col 2, co…

Spring Cloud Netflix Eureka的参数调优

下面主要分为Client端和Server端两大类进行简述&#xff0c;Eureka的几个核心参数 客户端参数 Client端的核心参数 参数默认值说明eureka.client.availability-zones告知Client有哪些region以及availability-zones&#xff0c;支持配置修改运行时生效eureka.client.filter-o…

数据结构——C/栈和队列

&#x1f308;个人主页&#xff1a;慢了半拍 &#x1f525; 创作专栏&#xff1a;《史上最强算法分析》 | 《无味生》 |《史上最强C语言讲解》 | 《史上最强C练习解析》 &#x1f3c6;我的格言&#xff1a;一切只是时间问题。 ​ 1.栈 1.1栈的概念及结构 栈&#xff1a;一种特…

WPF是不是垂垂老矣啦?平替它的框架还有哪些

WPF&#xff08;Windows Presentation Foundation&#xff09;是微软推出的一种用于创建 Windows 应用程序的用户界面框架。WPF最初是在2006年11月推出的&#xff0c;它是.NET Framework 3.0的一部分&#xff0c;为开发人员提供了一种基于 XAML 的方式来构建丰富的用户界面。 W…

你的代码很丑吗?试试这款高颜值代码字体

Monaspace 是有 GitHub 开源的代码字体&#xff0c;包含 5 种变形字体的等宽代码字体家族&#xff0c;颜值 Up&#xff0c;很难不喜欢。 来看一下这 5 种字体分别是&#xff1a; 1️⃣ Radon 手写风格字体 2️⃣ Krypton 机械风格字体 3️⃣ Xenon 衬线风格字体 4️⃣ Argon…

【高频SQL题目】1731.每位经理的下属员工数量

题目&#xff1a; Table: Employees ----------------------- | Column Name | Type | ----------------------- | employee_id | int | | name | varchar | | reports_to | int | | age | int | ----------------------- employee_id 是…

【C++二维前缀和】黑格覆盖

题目描述 在一张由 M * N 个小正方形格子组成的矩形纸张上&#xff0c;有 k 个格子被涂成了黑色。给你一张由 m * n 个同样小正方形组成的矩形卡片&#xff0c;请问该卡片最多能一次性覆盖多少个黑格子&#xff1f; 输入 输入共 k1 行&#xff1a; 第 1 行为 5 个整数 M、N、…

LeetCode每日一题 | LCP 30. 魔塔游戏

文章目录 题目描述问题分析程序代码 题目描述 原题链接 小扣当前位于魔塔游戏第一层&#xff0c;共有 N 个房间&#xff0c;编号为 0 ~ N-1。每个房间的补血道具/怪物对于血量影响记于数组 nums&#xff0c;其中正数表示道具补血数值&#xff0c;即血量增加对应数值&#xff1b…

C#的Char 结构的IsLetterOrDigit(Char)的方法

目录 一、Char 结构的方法 二、Char.IsLetterOrDigit 方法 1.Char.IsLetterOrDigit(Char)用法 2.IsLetterOrDigit(String, Int32)方法 三、Char.IsLetter 方法 1.IsLetter(Char) 2.IsLetter(String, Int32) 四、Char.IsDigit 方法 1. IsDigit(String, Int32) 2.IsDig…

【ES数据可视化】kibana实现数据大屏

目录 1.概述 2.绘制数据大屏 2.1.准备数据 2.2.绘制大屏 3.嵌入项目中 1.概述 再来重新认识一下kibana&#xff1a; Kibana 是一个用于数据可视化和分析的开源工具&#xff0c;是 Elastic Stack&#xff08;以前称为 ELK Stack&#xff09;中的一部分&#xff0c;由 Ela…