1.找到bin目录,下面有elasticSearch的sh文件,查看执行过程

  exec \"$JAVA" \$ES_JAVA_OPTS \-Des.path.home="$ES_HOME" \-Des.path.conf="$ES_PATH_CONF" \-Des.distribution.flavor="$ES_DISTRIBUTION_FLAVOR" \-Des.distribution.type="$ES_DISTRIBUTION_TYPE" \-cp "$ES_CLASSPATH" \org.elasticsearch.bootstrap.Elasticsearch \"$@"

可以看到主类的名称为:

Elasticsearch

2.主类Elasticsearch

找到main方法,父类

Command的execute()方法,ElasticSearch重写了该方法
    @Overrideprotected void execute(Terminal terminal, OptionSet options, Environment env) throws UserException {if (options.nonOptionArguments().isEmpty() == false) {throw new UserException(ExitCodes.USAGE, "Positional arguments not allowed, found " + options.nonOptionArguments());}if (options.has(versionOption)) {final String versionOutput = String.format(Locale.ROOT,"Version: %s, Build: %s/%s/%s/%s, JVM: %s",Version.displayVersion(Version.CURRENT, Build.CURRENT.isSnapshot()),Build.CURRENT.flavor().displayName(),Build.CURRENT.type().displayName(),Build.CURRENT.shortHash(),Build.CURRENT.date(),JvmInfo.jvmInfo().version());terminal.println(versionOutput);return;}final boolean daemonize = options.has(daemonizeOption);final Path pidFile = pidfileOption.value(options);final boolean quiet = options.has(quietOption);// a misconfigured java.io.tmpdir can cause hard-to-diagnose problems later, so reject it immediatelytry {env.validateTmpFile();} catch (IOException e) {throw new UserException(ExitCodes.CONFIG, e.getMessage());}try {init(daemonize, pidFile, quiet, env);} catch (NodeValidationException e) {throw new UserException(ExitCodes.CONFIG, e.getMessage());}}void init(final boolean daemonize, final Path pidFile, final boolean quiet, Environment initialEnv)throws NodeValidationException, UserException {try {Bootstrap.init(!daemonize, pidFile, quiet, initialEnv);} catch (BootstrapException | RuntimeException e) {// format exceptions to the console in a special way// to avoid 2MB stacktraces from guice, etc.throw new StartupException(e);}}

2.启动类Bootstrap

init方法

  /*** This method is invoked by {@link Elasticsearch#main(String[])} to startup elasticsearch.*/static 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 installed
        BootstrapInfo.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 (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 jars
            checkLucene();// 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 construction
                IOUtils.close(keystore);} catch (IOException e) {throw new BootstrapException(e);}INSTANCE.start();if (closeStandardStreams) {closeSysError();}} catch (NodeValidationException | RuntimeException e) {// disable console logging, so user does not see the exception twice (jvm will show it already)final Logger rootLogger = LogManager.getRootLogger();final Appender maybeConsoleAppender = Loggers.findAppender(rootLogger, ConsoleAppender.class);if (foreground && maybeConsoleAppender != null) {Loggers.removeAppender(rootLogger, maybeConsoleAppender);}Logger logger = LogManager.getLogger(Bootstrap.class);// HACK, it sucks to do this, but we will run users out of disk space otherwiseif (e instanceof CreationException) {// guice: log the shortened exc to the log fileByteArrayOutputStream os = new ByteArrayOutputStream();PrintStream ps = null;try {ps = new PrintStream(os, false, "UTF-8");} catch (UnsupportedEncodingException uee) {assert false;e.addSuppressed(uee);}new StartupException(e).printStackTrace(ps);ps.flush();try {logger.error("Guice Exception: {}", os.toString("UTF-8"));} catch (UnsupportedEncodingException uee) {assert false;e.addSuppressed(uee);}} else if (e instanceof NodeValidationException) {logger.error("node validation exception\n{}", e.getMessage());} else {// full exceptionlogger.error("Exception", e);}// re-enable it if appropriate, so they can see any logging during the shutdown processif (foreground && maybeConsoleAppender != null) {Loggers.addAppender(rootLogger, maybeConsoleAppender);}throw e;}}

找到红色的启动方法start,进去看,是Node的start方法

    private void start() throws NodeValidationException {node.start();keepAliveThread.start();}

3.节点启动Node

start方法

  /*** Start the node. If the node is already started, this method is no-op.*/public 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(RoutingService.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);injector.getInstance(ResourceWatcherService.class).start();injector.getInstance(GatewayService.class).start();Discovery discovery = injector.getInstance(Discovery.class);clusterService.getMasterService().setClusterStatePublisher(discovery::publish);// Start the transport service now so the publish address will be added to the local disco node in ClusterServiceTransportService transportService = injector.getInstance(TransportService.class);transportService.getTaskManager().setTaskResultsService(injector.getInstance(TaskResultsService.class));transportService.start();assert localNodeFactory.getNode() != null;assert transportService.getLocalNode().equals(localNodeFactory.getNode()): "transportService has a different local node than the factory provided";final MetaData onDiskMetadata;try {// we load the global state here (the persistent part of the cluster state stored on disk) to// pass it to the bootstrap checks to allow plugins to enforce certain preconditions based on the recovered state.if (DiscoveryNode.isMasterNode(settings) || DiscoveryNode.isDataNode(settings)) {onDiskMetadata = injector.getInstance(GatewayMetaState.class).loadMetaState();} else {onDiskMetadata = MetaData.EMPTY_META_DATA;}assert onDiskMetadata != null : "metadata is null but shouldn't"; // this is never null} catch (IOException e) {throw new UncheckedIOException(e);}validateNodeBeforeAcceptingRequests(new BootstrapContext(settings, onDiskMetadata), transportService.boundAddress(), pluginsService.filterPlugins(Plugin.class).stream().flatMap(p -> p.getBootstrapChecks().stream()).collect(Collectors.toList()));clusterService.addStateApplier(transportService.getTaskManager());// start after transport service so the local disco is knowndiscovery.start(); // start before cluster service so that it can set initial state on ClusterApplierService
        clusterService.start();assert clusterService.localNode().equals(localNodeFactory.getNode()): "clusterService has a different local node than the factory provided";transportService.acceptIncomingRequests();discovery.startInitialJoin();final TimeValue initialStateTimeout = DiscoverySettings.INITIAL_STATE_TIMEOUT_SETTING.get(settings);if (initialStateTimeout.millis() > 0) {final ThreadPool thread = injector.getInstance(ThreadPool.class);ClusterState clusterState = clusterService.state();ClusterStateObserver observer = new ClusterStateObserver(clusterState, clusterService, null, logger, thread.getThreadContext());if (clusterState.nodes().getMasterNodeId() == null) {logger.debug("waiting to join the cluster. timeout [{}]", initialStateTimeout);final CountDownLatch latch = new CountDownLatch(1);observer.waitForNextChange(new ClusterStateObserver.Listener() {@Overridepublic void onNewClusterState(ClusterState state) { latch.countDown(); }@Overridepublic void onClusterServiceClose() {latch.countDown();}@Overridepublic void onTimeout(TimeValue timeout) {logger.warn("timed out while waiting for initial discovery state - timeout: {}",initialStateTimeout);latch.countDown();}}, state -> state.nodes().getMasterNodeId() != null, initialStateTimeout);try {latch.await();} catch (InterruptedException e) {throw new ElasticsearchTimeoutException("Interrupted while waiting for initial discovery state");}}}injector.getInstance(HttpServerTransport.class).start();if (WRITE_PORTS_FILE_SETTING.get(settings)) {TransportService transport = injector.getInstance(TransportService.class);writePortsFile("transport", transport.boundAddress());HttpServerTransport http = injector.getInstance(HttpServerTransport.class);writePortsFile("http", http.boundAddress());}logger.info("started");pluginsService.filterPlugins(ClusterPlugin.class).forEach(ClusterPlugin::onNodeStarted);return this;}

里面一个非常重要的对象Injector,我们看看它的定义:

/*** Builds the graphs of objects that make up your application. The injector tracks the dependencies* for each type and uses bindings to inject them. This is the core of Guice, although you rarely* interact with it directly. This "behind-the-scenes" operation is what distinguishes dependency* injection from its cousin, the service locator pattern.* <p>* Contains several default bindings:* <ul>* <li>This {@link Injector} instance itself* <li>A {@code Provider<T>} for each binding of type {@code T}* <li>The {@link java.util.logging.Logger} for the class being injected* <li>The {@link Stage} in which the Injector was created* </ul>* <p>* Injectors are created using the facade class {@link Guice}.* <p>* An injector can also {@link #injectMembers(Object) inject the dependencies} of* already-constructed instances. This can be used to interoperate with objects created by other* frameworks or services.** @author crazybob@google.com (Bob Lee)* @author jessewilson@google.com (Jesse Wilson)*/

简单的说,Injector是一个实例管理器,和spring中IOC的beanfactory功能相当。

需要启动的服务如下:

后续会针对每个服务做单独的分析

转载于:https://www.cnblogs.com/davidwang456/p/10038579.html

elasticSearch6源码分析(1)启动过程相关推荐

  1. Nimbus三Storm源码分析--Nimbus启动过程

    Nimbus server, 首先从启动命令开始, 同样是使用storm命令"storm nimbus"来启动 看下源码, 此处和上面client不同, jvmtype=" ...

  2. 飞鸽传书源码分析-程序启动过程

    本文章是在飞鸽传书的2.06源码基础上分析 飞鸽传书源码运行流程如下,本篇文章只说明了飞鸽传书的启动过程,对于飞鸽伟书的消息机制及菜单加载等功能都不在本篇文章范围之内. 1. WinMain函数 [c ...

  3. workerman源码分析之启动过程

    2019独角兽企业重金招聘Python工程师标准>>> http://www.cnblogs.com/CpNice/p/4714182.html 转载于:https://my.osc ...

  4. Hyperledger Fabric从源码分析背书提案过程

    在之前的文章中 Hyperledger Fabric从源码分析链码安装过程 Hyperledger Fabric从源码分析链码实例化过程 Hyperledger Fabric从源码分析链码查询与调用 ...

  5. Wifi模块—源码分析Wifi启动2(Android P)

    一 前言 在上一篇分析了wifi启动的流程,从Android应用层一直分析到了Java框架层,这次我们接着往下走流程.如果没有看上一篇的建议先回头看看   Wifi模块-源码分析Wifi启动1(And ...

  6. Linux内核源码分析--内核启动之(3)Image内核启动(C语言部分)(Linux-3.0 ARMv7) 【转】...

    原文地址:Linux内核源码分析--内核启动之(3)Image内核启动(C语言部分)(Linux-3.0 ARMv7) 作者:tekkamanninja 转自:http://blog.chinauni ...

  7. Linux内核源码分析--内核启动之(4)Image内核启动(setup_arch函数)(Linux-3.0 ARMv7)【转】...

    原文地址:Linux内核源码分析--内核启动之(4)Image内核启动(setup_arch函数)(Linux-3.0 ARMv7) 作者:tekkamanninja 转自:http://blog.c ...

  8. Wifi模块—源码分析Wifi启动(Android P)

    一.前言 Android P在wifi这块改动挺大的,Wifi到AndoidO之后不再使用jni,所以AndroidP也一样不再使用jni来实现Java代码与本地的C/C++代码交互,而是使用HIDL ...

  9. 【四】Spring源码分析之启动主流程---AbstractApplicationContext的refresh方法

    入口: 在SpringBoot启动的时候,SpringApplication的run方法中 refreshContext(context); 里面最终调用的是AbstractApplicationCo ...

最新文章

  1. 给SAP Spartacus开源项目提交代码时的注意事项
  2. jedispool redis哨兵_Redis详解(九)------ 哨兵(Sentinel)模式详解
  3. eoeAndroid开发者大会
  4. Java核心技术 卷II 高级特性 原书第9版pdf
  5. 加密用户向阿桑奇捐赠超40万美元的BTC用于法律辩护
  6. Linux远程桌面工具Xming+Putty的搭建
  7. 南昌航空大学961数据结构真题答案
  8. Dlink dwl-122 ver c1在windows 2003下的驱动安装
  9. Swift之属性的使用和实例展示
  10. 使用iptables-persistent永久保存iptables规则
  11. 阿里云RDS的内存一直增加
  12. 安智市场发展史:刷机产业链的”中间商”
  13. linux服务器做301跳转,什么是301转向,如何去做301跳转
  14. js中使用btoa和atob进行Base64的编码和解码
  15. 0428-项目再开发2.0
  16. 深度学习入门笔记(一):深度学习引言
  17. vps建网站python_如何使用python搭建一个小网站 ?
  18. 看美剧学英语 看一部大片胜过在美生活十天
  19. 求近似数最值_人教版小学数学四年级上册亿以内数的认识公开课优质课课件教案视频...
  20. 代码质量检测神器——SonarQube

热门文章

  1. mysql范围查找性能_MYSQL(四)查询性能优化
  2. cordova 不打开浏览器_[Cordova inAppBrowser 在App内打开浏览器]
  3. java如何构造ajax回调参数,jQuery实现ajax回调函数带入参数的方法示例
  4. gridcontrol 验证错误_值得品读的人生感悟句子,生气,是拿别人的错误惩罚自己...
  5. pass在python中啥意思_python3中的pass是什么意思
  6. spark 统计汉字字数_版面字数和实际字数一样吗
  7. php elasticsearch ik,elasticsearch和analysis-ik的安装使用
  8. mysql 锁机制 mvcc_轻松理解MYSQL MVCC 实现机制
  9. pytorch运行遇到的问题_如何解决吸塑机在运行中遇到真空度的问题
  10. 帝豪gl车机系统降级_从拥有帝豪GL开始,出行的好伴侣,说说感受