搭建环境&创建项目
npm install -g @grafana/toolkit grafana-toolkit plugin:create my-grafana-plugin
一个典型的 Grafana 插件项目包含以下主要文件和目录: src:包含插件的源代码。 module.ts:用于导入和导出插件模块。 plugin.ts:插件的主要实现文件,通常包含 PanelPlugin 或 DataSourcePlugin 的定义。 components:存储 React 组件的目录。 types.ts:定义插件使用的数据类型和接口。 dist:包含构建后的插件文件,通常在构建过程中生成。 README.md:插件的说明文档。
开发面板插件
1.module.ts
import { PanelPlugin } from '@grafana/data';
import { MyPanel } from 'MyPanel';
export const plugin = new PanelPlugin(MyPanel).setPanelOptions((builder) => {
return builder..addTextInput({
path: 'text',
name: 'test',
description: 'Enter some text',
defaultValue: 'test',
})
});
2.MyPanel.tsx
import React from 'react';
import { getAppEvents,RefreshEvent,TimeRangeUpdatedEvent } from '@grafana/runtime';
import {PanelProps } from '@grafana/data';
type State = {
query: any
from:number
to:number
}
export class MyPanel extends React.Component<PanelProps, State> {
private subscription:any;
private subscription1:any;
constructor(props: {} |any) {
super(props);
this.state = {
query: {},
start:0,
end:0,
};
}
async componentDidMount() {
//时间范围更新
this.subscription = this.props.eventBus.getStream(TimeRangeUpdatedEvent).subscribe((event) => {
const payload = event.payload;
const start = payload.from.unix()*1000;
const end = payload.to.unix()*1000;
this.setState({
start: start,
end:end
})
});
//重新加载数据或执行刷新操作
this.subscription1 = this.props.eventBus.getStream(RefreshEvent).subscribe((event) => {
console.log(`Received event: ${event.type}`);
cosnt Variable = this.props.replaceVariables('${Variable}');
//const start = this.props.timeRange.from.unix()*1000;
this.setState({
query: Variable,
})
});
}
componentWillUnmount() {
// 取消订阅,防止内存泄漏
if (this.subscription) {
this.subscription.unsubscribe();
}
if (this.subscription1) {
this.subscription1.unsubscribe();
}
}
render() {
const {
width,
height,
} = this.props;
return (
<>
<div style={{ position: 'absolute', width: `${width}px`, height: `${height}px` }}>
<p> test:{this.props.options.test}</p>
<p> query:{this.state.query}</p>
<p> from:{this.state.start} to:{this.state.end}</p>
</div>
</>
);
}
}
安装依赖&编译
yarn install yarn build
添加插件
修改defaults.ini
[plugins] allow_loading_unsigned_plugins = <plugin-id-1>,<plugin-id-2> [plugin.my-panel] path = /home/grafame/plugins/my-panel
posted on
浙公网安备 33010602011771号