(三)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.hqwc.cn/news/456605.html

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

相关文章

MySQL数据库④_表的约束(主键_自增长_唯一键_外键等)

目录 1. 约束概念和常见的约束 2. 空属性null/not null 2. 默认值default 3. 列描述comment 4. 自动填充zerofill 5. 主键primary key ​​​​​​​5.1 主键 5.2 复合主键​​​​​​​​​​​​​​ 6. 自增长auto_increment 7. 唯一键unique key 8. 外键forei…

「刷题」二叉树的题刷不动?快进来拓展解题思路!

&#x1f387;个人主页&#xff1a;Ice_Sugar_7 &#x1f387;所属专栏&#xff1a;数据结构刷题 &#x1f387;欢迎点赞收藏加关注哦&#xff01; 题单 &#x1f349;对称二叉树&#x1f349;层序遍历二叉树&#x1f349;由前序、中序遍历构造二叉树 &#x1f349;对称二叉树 …

three.js 向量方向(归一化.normalize)

效果&#xff1a; <template><div><el-container><el-main><div class"box-card-left"><div id"threejs" style"border: 1px solid red"></div><div><p><el-button type"primary…

代码随想录算法训练营29期|day42 任务以及具体任务

第九章 动态规划part04 01背包问题&#xff0c;你该了解这些&#xff01; 动态规划&#xff1a;01背包理论基础 本题力扣上没有原题&#xff0c;大家可以去卡码网第46题 (opens new window)去练习&#xff0c;题意是一样的。 #算法公开课 《代码随想录》算法视频公开课 (opens…

C语言数组练习以及场景练习题

写了那么久的知识点梳理&#xff0c;今天来写点自己觉得不错的练习题来分享&#xff0c;顺便来巩固自己的知识点&#xff0c;和加强题型的解决方法的记忆。今天给大家带来的有数组的找数字题目&#xff0c;以及场景找凶手的题目&#xff0c;下面让我们来看看今天的第一道题目。…

Linux进程信号处理:深入理解与应用(3)

&#x1f3ac;慕斯主页&#xff1a;修仙—别有洞天 ♈️今日夜电波&#xff1a;its 6pm but I miss u already.—bbbluelee 0:01━━━━━━️&#x1f49f;──────── 3:18 &#x1f504; ◀️…

CSDN2024年我的创作纪念日1024天|不忘初心|努力上进|积极向前

CSDN2024年我的创作纪念日1024天| 学习成长机遇&#xff1a;学习成长收获&#xff1a;2023年度总结数据&#xff1a;2024新领域的探索&#xff1a;日常和自己的感慨&#xff1a;2024憧憬和规划&#xff1a;创作纪念日总结&#xff1a; 学习成长机遇&#xff1a; 大家好&#x…

QT安装与helloworld

文章目录 QT安装与helloworld1.概念&#xff1a;2.安装QT3.配置环境变量4.创建项目5.运行效果 QT安装与helloworld 1.概念&#xff1a; Qt Creator是一个用于Qt开发的轻量级跨平台集成开发环境。Qt Creator可带来两大关键益处&#xff1a;提供首个专为支持跨平台开发而设计的…

Figma怎么设置中文,Figma有中文版吗?

不是很多人不想用 Figma&#xff0c;真是因为纯英文界面而头疼。这就是为什么有人会到处搜索 Figma 如何设置中文这样的问题。 然后我们直接快刀斩乱麻&#xff0c;Figma 没有中文版&#xff0c;但是我们还有其他的方法&#xff1a;例如&#xff0c; Figma 添加一个插件来解决…

2024年考PMP还有什么用?

PMP 是项目管理专业人士资格认证的意思&#xff0c;也是项目管理领域通用的证书&#xff0c; 做项目的基本都会去考。 要说 PMP 有啥作用&#xff1f; 个人感觉 PMP 证书更多的是跳槽、转行的敲门砖的作用&#xff0c;因为现在很多公司都要 PMP 证书&#xff0c;有了可以加分…

axios下载文件打开失败解决

在axios的then中创建了a标签下载文件完成之后&#xff0c;发现下载的文件打不开。 解决方法 设置responseType: blob 注意&#xff01;&#xff01;&#xff01;这个是和headers同级别的&#xff0c;不是在headers里面的

2024最新msvcp140.dll丢失的解决方法,总结5种有效的方法

msvcp140.dll文件的丢失可能会引发一系列潜在问题并对计算机系统产生多方面的影响。首先&#xff0c;这个文件是Microsoft Visual C Redistributable Package的一部分&#xff0c;对于许多基于Windows的应用程序运行至关重要。一旦丢失&#xff0c;可能会导致部分软件无法正常启…