Elasticsearch源码编译运行

3,438 阅读2分钟

一、源码环境

1. es源码地址:github.com/elastic/ela…,建议fork一份到自己仓库,后面阅读代码写注释可以推到自己的仓库。

2.JDK:1.8

3.gradle:4.10 由于es基于gradle构建代码,所以提前装好gradle。

4.os:mac

二、开始编译

1. git checkout -b 6.5.4 v6.5.4。 本系列文章都是基于6.5.4版本的,所以源码当然也是从6.5.4版本入手了。

2.在当前目录执行:gradle idea。编译时间可能有点长,当最后出现 BUILD SUCCESSFUL,编译完成。

3.导入idea。

三、运行调试

运行org.elasticsearch.bootstrap.Elasticsear

ch

启动的时候会出现一些问题:

1.配置文件问题:

ERROR: the system property [es.path.conf] must be set

在启动类中添加配置config配置路径:

-Des.path.conf=/Users/zjb/code/mine/commit/elasticsearch/myconfig,可以把elasticsearch.yml丢在改文件下,如果没有的话,读取默认配置

重新运行后出现错误

Exception in thread "main" java.lang.IllegalStateException: path.home is not configured

需要在启动参数添加配置:

-Des.path.home=/Users/zjb/code/mine/commit/elasticsearch/data

2.java.security问题

配置好启动参数后,再次运行出现报错:

2019-07-26 19:51:12,943 main ERROR Could not register mbeans java.security.AccessControlException: access denied ("javax.management.MBeanTrustPermission" "register")

新建一个elasticsearch.policy文件,内容为:

grant{   permission javax.management.MBeanTrustPermission "register";   
permission javax.management.MBeanServerPermission "createMBeanServer";
};

然后再启动参数中指定新的policy文件:

-Djava.security.policy=/Users/zjb/code/mine/commit/elasticsearch/elasticsearch.policy

3.log4j2配置问题

配置好新的安全策略后,重新启动。出现:

ERROR: no log4j2.properties found; tried [/Users/zjb/code/mine/commit/elasticsearch/myconfig] and its subdirectories

这个错误主要是没有配置文件引起的,可以将distribution模块下src/config/log4j2.properties放到配置文件myconfig目录下

4.modules缺失

配置好log的问题后,又出现了

org.elasticsearch.bootstrap.StartupException: java.lang.IllegalStateException: modules directory [/Users/zjb/code/mine/commit/elasticsearch/data/modules] not found

这个问题主要是由于,没有检测到对应的modules引起的,这个问题最简单的办法就是下一个与源码版本号一只的Elasticsearch的bin版本,讲里面对应的modules拷贝到配置的path.home目录下。

5.编译项修改

将modules拷贝过来后,重新启动es。出现

java.lang.NoClassDefFoundError: org/elasticsearch/plugins/ExtendedPluginsClassLoader

这是因为server模块显得build.gradle编译项为compileOnly project(':libs:plugin-classloader')

修改compileOnly 为compile 重新编译

6.RuntimePermission问题

重新启动后又出现permission的问题

org.elasticsearch.bootstrap.StartupException: java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "createClassLoader") 

利用三.2中的思路,在elasticsearch.yml中添加配置项:

permission java.lang.RuntimePermission "createClassLoader";

然后重新启动。

7.终于启动

启动后,访问http://localhost:9200/

启动成功,大功告成,终于可以debug

四、总结

Elasticsearch的源码编译和启动过程会遇到一些问题,可能每个版本会有细微的差别,再用此文章编译运行的时候,最好选择和笔者相同的ES版本。