编写自定义 REST 插件并集成到 Kibana
解读
在国内中大型企业的 Elasticsearch 面试里,这道题常被用来区分“只会用”与“能改造”的候选人。
它要求候选人同时掌握 Elasticsearch 插件扩展机制、Kibana 前后端二次开发流程 以及 Elastic 商业合规边界(阿里云、腾讯云、华为云均要求自研插件不得违反 Elastic 许可证)。
面试官期望听到:
- 如何用 Gradle + ES Plugin 规范 构建一个 自定义 REST Action;
- 怎样把插件打包为 zip 分发包 并 热插拔到线上集群;
- 如何在 Kibana 插件脚手架 里调用该 REST 接口,并把结果渲染到 React 前端;
- 如何兼容 安全认证(RBAC、API Key、SAML)与 多租户隔离;
- 如何在国内云厂商的 内核加固环境 下做 签名验证 与 灰度发布。
知识点
- Elasticsearch 插件类型:REST Action Plugin、Transport Action Plugin、Ingest Plugin、Script Plugin、Search Plugin
- 扩展点:BaseRestHandler、RestChannel、RestRequest、RestResponse、XContentBuilder
- 构建体系:Gradle 7.x + Elasticsearch 8.x plugin-applier、plugin-descriptor.properties、plugin-security.policy
- Kibana 插件体系:Kibana Platform Plugin、server 端 route、common 端 type、public 端 React component、data plugin 的 search interceptor
- 安全集成:RoleDescriptor、PrivilegesInterceptor、SecurityFilter、API Key Service、SAML realm
- 国内合规:Elastic License 2.0 与 SSPL 区别,阿里云 Logstash 托管版 禁止上传含 GPL 依赖的 jar
- 灰度与回滚:cluster.routing.allocation.exclude._plugin、Plugin Bundle 的 sha512 校验、蓝绿双集群 + 网关流量镜像
答案
1. 创建 Elasticsearch REST 插件
项目结构
custom-rest-plugin/
├─ build.gradle
├─ src/main/java/com/demo/plugin/
│ ├─ CustomRestPlugin.java
│ ├─ RestCustomAction.java
│ └─ CustomResponse.java
└─ src/main/plugin-metadata/plugin-descriptor.properties
build.gradle(Gradle 7.6,ES 8.11)
plugins {
id 'java'
id 'elasticsearch.es-plugin' version '8.11.0'
}
esplugin {
name 'custom-rest'
classname 'com.demo.plugin.CustomRestPlugin'
licenseFile rootProject.file('LICENSE')
noticeFile rootProject.file('NOTICE')
}
dependencies {
compileOnly "org.elasticsearch:elasticsearch:8.11.0"
}
CustomRestPlugin.java
public class CustomRestPlugin extends Plugin implements ActionPlugin {
@Override
public List<RestHandler> getRestHandlers(...) {
return List.of(new RestCustomAction());
}
}
RestCustomAction.java
public class RestCustomAction extends BaseRestHandler {
@Override
public String getName() { return "custom_api"; }
@Override
public List<Route> routes() {
return List.of(new Route(GET, "/_custom/search"));
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest req, NodeClient client) {
return channel -> {
var resp = new CustomResponse("hello", System.currentTimeMillis());
channel.sendResponse(new BytesRestResponse(OK, resp.toXContent(channel.newBuilder(), EMPTY_PARAMS)));
};
}
}
打包
./gradlew clean assemble
生成 build/distributions/custom-rest-8.11.0.zip
2. 安装与验证
在 国内自建集群(CentOS 7 + JDK 17)
sudo bin/elasticsearch-plugin install file:///opt/custom-rest-8.11.0.zip --batch
sudo systemctl restart elasticsearch
curl -u elastic:xxx http://node1:9200/_custom/search
返回
{"message":"hello","timestamp":1710000000000}
3. 创建 Kibana 插件
使用 官方脚手架(Node 18,Kibana 8.11)
yarn kbn bootstrap
node scripts/generate-plugin.js customKibanaPlugin
server/plugin.ts
import { PluginInitializerContext, CoreSetup } from '@kbn/core/server';
export class CustomKibanaPlugin implements Plugin {
setup(core: CoreSetup) {
core.http.createRouter().get(
{ path: '/api/custom/proxy', validate: false },
async (ctx, req, res) => {
const es = (await ctx.core).elasticsearch.client.asCurrentUser;
const { body } = await es.transport.request({ method: 'GET', path: '/_custom/search' });
return res.ok({ body });
}
);
}
}
public/components/app.tsx
import React, { useEffect, useState } from 'react';
import { http } from '../services';
export const App = () => {
const [data, setData] = useState<any>({});
useEffect(() => { http.get('/api/custom/proxy').then(setData); }, []);
return <div>消息:<b>{data.message}</b> 时间戳:{data.timestamp}</div>;
};
打包
yarn build
生成 build/customKibanaPlugin-8.11.0.zip,通过 Kibana 控制台上传 或 挂载到 docker /usr/share/kibana/plugins。
4. 安全加固
- 在 elasticsearch.yml 增加
xpack.security.authc.realms.saml.saml1.order: 2 - 在 Kibana 端 使用 built-in role
custom_role并设置cluster: [ "monitor", "custom" ] - 插件内部用 ThreadContext.stashWithOrigin 绕过用户权限,以 _system 身份调用敏感接口,避免 越权漏洞。
5. 国内云厂商上线 checklist
- 依赖包不得含 GPL v3,需提供 第三方许可证报告;
- zip 包需 国密 SM3 摘要 并上传至 对象存储 OSS;
- 通过 灰度标签
cluster.metadata.custom_plugin_version: 1.0.0做 分片级灰度; - 回滚脚本
bin/elasticsearch-plugin remove custom-rest && sudo rpm -Uvh elasticsearch-rollback-8.11.0.rpm
拓展思考
- 如果集群规模 >200 节点,如何做到 插件滚动升级零中断?(提示:利用 分片分配延迟、网关层流量双写、节点级重启顺序)
- 当 Kibana 8.x 强制开启 Content-Security-Policy 时,如何把插件的 React 懒加载 chunk 注入到 Kibana 的 webpack runtime 而不触发 script-src unsafe-inline?
- 在 信创环境(鲲鹏 + 麒麟 V10)下,transport-netty4 模块 使用 毕昇 JDK 17 出现 epoll 不可用,应如何 回退到 NIO 并重新编译 native 库?
- 若需求升级为 写入侧插件(自定义 Ingest Pipeline),如何与 REST 插件 共享 内存缓存 并保证 跨节点一致性?(提示:**IndicesService 注入 + Plugin.createComponents + 使用 **Elasticsearch 的 NamedWriteable 机制)