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

  1. exec \
  2. "$JAVA" \
  3. $ES_JAVA_OPTS \
  4. -Des.path.home="$ES_HOME" \
  5. -Des.path.conf="$ES_PATH_CONF" \
  6. -Des.distribution.flavor="$ES_DISTRIBUTION_FLAVOR" \
  7. -Des.distribution.type="$ES_DISTRIBUTION_TYPE" \
  8. -cp "$ES_CLASSPATH" \
  9. org.elasticsearch.bootstrap.Elasticsearch \
  10. "$@"

可以看到主类的名称为:

  1. Elasticsearch

2.主类Elasticsearch

找到main方法,父类

  1. Commandexecute()方法,ElasticSearch重写了该方法
  1. @Override
  2. protected void execute(Terminal terminal, OptionSet options, Environment env) throws UserException {
  3. if (options.nonOptionArguments().isEmpty() == false) {
  4. throw new UserException(ExitCodes.USAGE, "Positional arguments not allowed, found " + options.nonOptionArguments());
  5. }
  6. if (options.has(versionOption)) {
  7. final String versionOutput = String.format(
  8. Locale.ROOT,
  9. "Version: %s, Build: %s/%s/%s/%s, JVM: %s",
  10. Version.displayVersion(Version.CURRENT, Build.CURRENT.isSnapshot()),
  11. Build.CURRENT.flavor().displayName(),
  12. Build.CURRENT.type().displayName(),
  13. Build.CURRENT.shortHash(),
  14. Build.CURRENT.date(),
  15. JvmInfo.jvmInfo().version());
  16. terminal.println(versionOutput);
  17. return;
  18. }
  19.  
  20. final boolean daemonize = options.has(daemonizeOption);
  21. final Path pidFile = pidfileOption.value(options);
  22. final boolean quiet = options.has(quietOption);
  23.  
  24. // a misconfigured java.io.tmpdir can cause hard-to-diagnose problems later, so reject it immediately
  25. try {
  26. env.validateTmpFile();
  27. } catch (IOException e) {
  28. throw new UserException(ExitCodes.CONFIG, e.getMessage());
  29. }
  30.  
  31. try {
  32. init(daemonize, pidFile, quiet, env);
  33. } catch (NodeValidationException e) {
  34. throw new UserException(ExitCodes.CONFIG, e.getMessage());
  35. }
  36. }
  37.  
  38. void init(final boolean daemonize, final Path pidFile, final boolean quiet, Environment initialEnv)
  39. throws NodeValidationException, UserException {
  40. try {
  41. Bootstrap.init(!daemonize, pidFile, quiet, initialEnv);
  42. } catch (BootstrapException | RuntimeException e) {
  43. // format exceptions to the console in a special way
  44. // to avoid 2MB stacktraces from guice, etc.
  45. throw new StartupException(e);
  46. }
  47. }

2.启动类Bootstrap

init方法

  1. /**
  2. * This method is invoked by {@link Elasticsearch#main(String[])} to startup elasticsearch.
  3. */
  4. static void init(
  5. final boolean foreground,
  6. final Path pidFile,
  7. final boolean quiet,
  8. final Environment initialEnv) throws BootstrapException, NodeValidationException, UserException {
  9. // force the class initializer for BootstrapInfo to run before
  10. // the security manager is installed
  11. BootstrapInfo.init();
  12.  
  13. INSTANCE = new Bootstrap();
  14.  
  15. final SecureSettings keystore = loadSecureSettings(initialEnv);
  16. final Environment environment = createEnvironment(pidFile, keystore, initialEnv.settings(), initialEnv.configFile());
  17.  
  18. LogConfigurator.setNodeName(Node.NODE_NAME_SETTING.get(environment.settings()));
  19. try {
  20. LogConfigurator.configure(environment);
  21. } catch (IOException e) {
  22. throw new BootstrapException(e);
  23. }
  24. if (environment.pidFile() != null) {
  25. try {
  26. PidFile.create(environment.pidFile(), true);
  27. } catch (IOException e) {
  28. throw new BootstrapException(e);
  29. }
  30. }
  31.  
  32. final boolean closeStandardStreams = (foreground == false) || quiet;
  33. try {
  34. if (closeStandardStreams) {
  35. final Logger rootLogger = LogManager.getRootLogger();
  36. final Appender maybeConsoleAppender = Loggers.findAppender(rootLogger, ConsoleAppender.class);
  37. if (maybeConsoleAppender != null) {
  38. Loggers.removeAppender(rootLogger, maybeConsoleAppender);
  39. }
  40. closeSystOut();
  41. }
  42.  
  43. // fail if somebody replaced the lucene jars
  44. checkLucene();
  45.  
  46. // install the default uncaught exception handler; must be done before security is
  47. // initialized as we do not want to grant the runtime permission
  48. // setDefaultUncaughtExceptionHandler
  49. Thread.setDefaultUncaughtExceptionHandler(new ElasticsearchUncaughtExceptionHandler());
  50.  
  51. INSTANCE.setup(true, environment);
  52.  
  53. try {
  54. // any secure settings must be read during node construction
  55. IOUtils.close(keystore);
  56. } catch (IOException e) {
  57. throw new BootstrapException(e);
  58. }
  59.  
  60. INSTANCE.start();
  61.  
  62. if (closeStandardStreams) {
  63. closeSysError();
  64. }
  65. } catch (NodeValidationException | RuntimeException e) {
  66. // disable console logging, so user does not see the exception twice (jvm will show it already)
  67. final Logger rootLogger = LogManager.getRootLogger();
  68. final Appender maybeConsoleAppender = Loggers.findAppender(rootLogger, ConsoleAppender.class);
  69. if (foreground && maybeConsoleAppender != null) {
  70. Loggers.removeAppender(rootLogger, maybeConsoleAppender);
  71. }
  72. Logger logger = LogManager.getLogger(Bootstrap.class);
  73. // HACK, it sucks to do this, but we will run users out of disk space otherwise
  74. if (e instanceof CreationException) {
  75. // guice: log the shortened exc to the log file
  76. ByteArrayOutputStream os = new ByteArrayOutputStream();
  77. PrintStream ps = null;
  78. try {
  79. ps = new PrintStream(os, false, "UTF-8");
  80. } catch (UnsupportedEncodingException uee) {
  81. assert false;
  82. e.addSuppressed(uee);
  83. }
  84. new StartupException(e).printStackTrace(ps);
  85. ps.flush();
  86. try {
  87. logger.error("Guice Exception: {}", os.toString("UTF-8"));
  88. } catch (UnsupportedEncodingException uee) {
  89. assert false;
  90. e.addSuppressed(uee);
  91. }
  92. } else if (e instanceof NodeValidationException) {
  93. logger.error("node validation exception\n{}", e.getMessage());
  94. } else {
  95. // full exception
  96. logger.error("Exception", e);
  97. }
  98. // re-enable it if appropriate, so they can see any logging during the shutdown process
  99. if (foreground && maybeConsoleAppender != null) {
  100. Loggers.addAppender(rootLogger, maybeConsoleAppender);
  101. }
  102.  
  103. throw e;
  104. }
  105. }

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

  1. private void start() throws NodeValidationException {
  2. node.start();
  3. keepAliveThread.start();
  4. }

3.节点启动Node

start方法

  1. /**
  2. * Start the node. If the node is already started, this method is no-op.
  3. */
  4. public Node start() throws NodeValidationException {
  5. if (!lifecycle.moveToStarted()) {
  6. return this;
  7. }
  8.  
  9. logger.info("starting ...");
  10. pluginLifecycleComponents.forEach(LifecycleComponent::start);
  11.  
  12. injector.getInstance(MappingUpdatedAction.class).setClient(client);
  13. injector.getInstance(IndicesService.class).start();
  14. injector.getInstance(IndicesClusterStateService.class).start();
  15. injector.getInstance(SnapshotsService.class).start();
  16. injector.getInstance(SnapshotShardsService.class).start();
  17. injector.getInstance(RoutingService.class).start();
  18. injector.getInstance(SearchService.class).start();
  19. nodeService.getMonitorService().start();
  20.  
  21. final ClusterService clusterService = injector.getInstance(ClusterService.class);
  22.  
  23. final NodeConnectionsService nodeConnectionsService = injector.getInstance(NodeConnectionsService.class);
  24. nodeConnectionsService.start();
  25. clusterService.setNodeConnectionsService(nodeConnectionsService);
  26.  
  27. injector.getInstance(ResourceWatcherService.class).start();
  28. injector.getInstance(GatewayService.class).start();
  29. Discovery discovery = injector.getInstance(Discovery.class);
  30. clusterService.getMasterService().setClusterStatePublisher(discovery::publish);
  31.  
  32. // Start the transport service now so the publish address will be added to the local disco node in ClusterService
  33. TransportService transportService = injector.getInstance(TransportService.class);
  34. transportService.getTaskManager().setTaskResultsService(injector.getInstance(TaskResultsService.class));
  35. transportService.start();
  36. assert localNodeFactory.getNode() != null;
  37. assert transportService.getLocalNode().equals(localNodeFactory.getNode())
  38. : "transportService has a different local node than the factory provided";
  39. final MetaData onDiskMetadata;
  40. try {
  41. // we load the global state here (the persistent part of the cluster state stored on disk) to
  42. // pass it to the bootstrap checks to allow plugins to enforce certain preconditions based on the recovered state.
  43. if (DiscoveryNode.isMasterNode(settings) || DiscoveryNode.isDataNode(settings)) {
  44. onDiskMetadata = injector.getInstance(GatewayMetaState.class).loadMetaState();
  45. } else {
  46. onDiskMetadata = MetaData.EMPTY_META_DATA;
  47. }
  48. assert onDiskMetadata != null : "metadata is null but shouldn't"; // this is never null
  49. } catch (IOException e) {
  50. throw new UncheckedIOException(e);
  51. }
  52. validateNodeBeforeAcceptingRequests(new BootstrapContext(settings, onDiskMetadata), transportService.boundAddress(), pluginsService
  53. .filterPlugins(Plugin
  54. .class)
  55. .stream()
  56. .flatMap(p -> p.getBootstrapChecks().stream()).collect(Collectors.toList()));
  57.  
  58. clusterService.addStateApplier(transportService.getTaskManager());
  59. // start after transport service so the local disco is known
  60. discovery.start(); // start before cluster service so that it can set initial state on ClusterApplierService
  61. clusterService.start();
  62. assert clusterService.localNode().equals(localNodeFactory.getNode())
  63. : "clusterService has a different local node than the factory provided";
  64. transportService.acceptIncomingRequests();
  65. discovery.startInitialJoin();
  66. final TimeValue initialStateTimeout = DiscoverySettings.INITIAL_STATE_TIMEOUT_SETTING.get(settings);
  67. if (initialStateTimeout.millis() > 0) {
  68. final ThreadPool thread = injector.getInstance(ThreadPool.class);
  69. ClusterState clusterState = clusterService.state();
  70. ClusterStateObserver observer = new ClusterStateObserver(clusterState, clusterService, null, logger, thread.getThreadContext());
  71. if (clusterState.nodes().getMasterNodeId() == null) {
  72. logger.debug("waiting to join the cluster. timeout [{}]", initialStateTimeout);
  73. final CountDownLatch latch = new CountDownLatch(1);
  74. observer.waitForNextChange(new ClusterStateObserver.Listener() {
  75. @Override
  76. public void onNewClusterState(ClusterState state) { latch.countDown(); }
  77.  
  78. @Override
  79. public void onClusterServiceClose() {
  80. latch.countDown();
  81. }
  82.  
  83. @Override
  84. public void onTimeout(TimeValue timeout) {
  85. logger.warn("timed out while waiting for initial discovery state - timeout: {}",
  86. initialStateTimeout);
  87. latch.countDown();
  88. }
  89. }, state -> state.nodes().getMasterNodeId() != null, initialStateTimeout);
  90.  
  91. try {
  92. latch.await();
  93. } catch (InterruptedException e) {
  94. throw new ElasticsearchTimeoutException("Interrupted while waiting for initial discovery state");
  95. }
  96. }
  97. }
  98.  
  99. injector.getInstance(HttpServerTransport.class).start();
  100.  
  101. if (WRITE_PORTS_FILE_SETTING.get(settings)) {
  102. TransportService transport = injector.getInstance(TransportService.class);
  103. writePortsFile("transport", transport.boundAddress());
  104. HttpServerTransport http = injector.getInstance(HttpServerTransport.class);
  105. writePortsFile("http", http.boundAddress());
  106. }
  107.  
  108. logger.info("started");
  109.  
  110. pluginsService.filterPlugins(ClusterPlugin.class).forEach(ClusterPlugin::onNodeStarted);
  111.  
  112. return this;
  113. }

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

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

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

需要启动的服务如下:

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

elasticSearch6源码分析(1)启动过程的更多相关文章

  1. mybatis源码分析:启动过程

    mybatis在开发中作为一个ORM框架使用的比较多,所谓ORM指的是Object Relation Mapping,直译过来就是对象关系映射,这个映射指的是java中的对象和数据库中的记录的映射,也 ...

  2. Nimbus<三>Storm源码分析--Nimbus启动过程

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

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

    PHP一直以来以草根示人,它简单,易学,被大量应用于web开发,非常可惜的是大部分开发都在简单的增删改查,或者加上pdo,redis等客户端甚至分布式,以及规避语言本身的缺陷.然而这实在太委屈PHP了 ...

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

    http://blog.chinaunix.net/uid-20543672-id-3157283.html Linux内核源码分析--内核启动之(3)Image内核启动(C语言部分)(Linux-3 ...

  5. SOFA 源码分析 —— 服务引用过程

    前言 在前面的 SOFA 源码分析 -- 服务发布过程 文章中,我们分析了 SOFA 的服务发布过程,一个完整的 RPC 除了发布服务,当然还需要引用服务. So,今天就一起来看看 SOFA 是如何引 ...

  6. Dubbo 源码分析 - 服务调用过程

    注: 本系列文章已捐赠给 Dubbo 社区,你也可以在 Dubbo 官方文档中阅读本系列文章. 1. 简介 在前面的文章中,我们分析了 Dubbo SPI.服务导出与引入.以及集群容错方面的代码.经过 ...

  7. u-boot 源码分析(1) 启动过程分析

    u-boot 源码分析(1) 启动过程分析 文章目录 u-boot 源码分析(1) 启动过程分析 前言 配置 源码结构 api arch board common cmd drivers fs Kbu ...

  8. v87.01 鸿蒙内核源码分析 (内核启动篇) | 从汇编到 main () | 百篇博客分析 OpenHarmony 源码

    本篇关键词:内核重定位.MMU.SVC栈.热启动.内核映射表 内核汇编相关篇为: v74.01 鸿蒙内核源码分析(编码方式) | 机器指令是如何编码的 v75.03 鸿蒙内核源码分析(汇编基础) | ...

  9. Appium Server 源码分析之启动运行Express http服务器

    通过上一个系列Appium Android Bootstrap源码分析我们了解到了appium在安卓目标机器上是如何通过bootstrap这个服务来接收appium从pc端发送过来的命令,并最终使用u ...

随机推荐

  1. Android 显示确认对话框

      AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("你确定要退出吗?" ...

  2. DAC--使用DAC来导出数据库脚本

    //============================================== //功能介绍:使用DAC来导出数据库脚本 //注意事项: //1.本程序涉及到的DLL有: //  - ...

  3. c# WPF客户端调用WebAPI并转换成List

    利用HttpClient.JsonConvert实现. 引用Newtonsoft.Json.dll和System.Net.Http. 举个例子:从webapi中获取设备列表. public parti ...

  4. Day 38 Semaphore ,Event ,队列

    什么是信号量(multiprocess.Semaphore) 互斥锁同时只允许一个线程更改数据,而信号量semaphore是同时允许一定数量的线程更改数据. 假设商场里有4个迷你唱吧 ,所以通过同时可 ...

  5. PHP 单点登录实现方案

    单点登录SSO(Single Sign On)说得简单点就是在一个多系统共存的环境下,用户在一处登录后,就不用在其他系统中登录,也就是用户的一次登录能得到其他所有系统的信任.单点登录在大型网站里使用得 ...

  6. Map-560. Subarray Sum Equals K

    Given an array of integers and an integer k, you need to find the total number of continuous subarra ...

  7. Flask 实现 WebSocket 通讯---群聊和私聊

    一.WebSocket介绍 WebSocket是一种在单个TCP连接实现了服务端和客户端进行双向文本或二进制数据通信的一种通信的协议. WebSocket使得客户端和服务器之间的数据交换变得更加简单, ...

  8. poj3026

    Borg Maze Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 12952   Accepted: 4227 Descri ...

  9. 对数组排序三种方式sort、asort与ksort

    关联数组是 键值(key)=>值(value)形式. sort只对值进行排序,键值不参与排序: asort对值进行排序,键值参与排序: ksort对键值进行排序,值参与排序: 实例,比如数组: ...

  10. 二,mysql优化——sql优化基本概念

    1,SQL优化的一般步骤 (1)通过show status命令了解各种SQL执行效率. (2)通过执行效率较低的SQL语句(重点select). (3)通过explain分析低效率的SQL语句的执行情 ...