Grafana的Datasource插件開發實踐一中介紹了開發datasource須要知道的基本內容。這篇文章中將介紹在項目中具體的開發實踐。html
與Grafana的其他部分進行交互,插件文件須要導出如下5個模塊:數據庫
Datasource // Required
QueryCtrl // Required
ConfigCtrl // Required
QueryOptionsCtrl //
AnnotationsQueryCtrl //
複製代碼
datasource插件與數據源通訊,並將數據轉換爲時間序列。 數據源有如下功能:json
query(options) // 用於panel查詢數據
testDatasource() // 用於自定義數據源的頁面,測試當前配置的數據源是可用的
annotationQuery(options) // 用於dashboard獲取註釋信息
metricFindQuery(options) // used by query editor to get metric suggestions.
複製代碼
constructor函數傳入的參數有:api
constructor(instanceSettings, $q, backendSrv, templateSrv) {}
// instanceSettings對象爲:
{
id: 5,
jsonData: {
keepCookies: [],
tlsAuth: false,
tlsAuthWithCACert: false,
tlsSkipVerify: false,
},
meta: {
alerting: false,
annotations: true,
baseUrl: "public/plugins/grafana-server-datasource",
dependencies: {
grafanaVersion: "3.x.x",
plugins: [],
},
id: "grafana-server-datasource",
includes: null,
info: {
author: {
name:"liuchunhui",
url:"https://grafana.com",
},
description: "代理服務端做爲數據源",
links: [
{name: "Github", url: ""},
{name: "MIT License", url: ""}
],
logos: {
large:"public/plugins/grafana-server-datasource/img/server-logo.png",
small:"public/plugins/grafana-server-datasource/img/server-logo.png"
},
screenshots:null
updated:"2018-04-23"
version:"1.0.0"
},
metrics: true,
module: "plugins/grafana-server-datasource/module",
name: "代理服務端",
routes: null,
type: "datasource",
}
name:"代理服務端數據源",
type:"grafana-server-datasource",
url:"/api/datasources/proxy/5",
}
// $q 是個函數
// backendSrv對象爲:
{
$http: ƒ p(e),
$q: ƒ M(t),
$timeout: ƒ o(o,s,u),
HTTP_REQUEST_CANCELLED: -1,
alertSrv: {
$rootScope: object,
$timeout: ƒ o(o,s,u)
list: []
}
contextSrv: {
isEditor: true,
isGrafanaAdmin: true,
isSignedIn: true,
sidemenu: true,
sidemenuSmallBreakpoint: false,
user: { // 當前登陸的用戶信息
email:"admin@localhost",
gravatarUrl:"/avatar/46d229b033af06a191ff2267bca9ae56",
helpFlags1:0,
id:1,
isGrafanaAdmin:true,
isSignedIn:true,
lightTheme:true,
locale:"zh-CN",
login:"admin",
name:"admin",
orgCount:1,
orgId:1,
orgName:"Main Org.",
orgRole:"Admin",
timezone:"browser",
},
version:"5.0.1",
},
inFlightRequests:{},
noBackendCache:true,
}
// templateSrv對象爲:
{
builtIns: {
__interval:{text: "1s", value: "1s"},
__interval_ms:{text: "100", value: "100"}
},
grafanaVariables: {},
index:{},
regex:/\$(\w+)|\[\[([\s\S]+?)(?::(\w+))?\]\]|\${(\w+)(?::(\w+))?}/g
}
複製代碼
真正去查詢數據時要調用的函數。官方提供的數據源有兩種不一樣的結果,time series
和table
,目前grafana官方全部數據源和麪板都支持time series
格式,table
格式僅由InfluxDB數據源和表格面板支持。 咱們開發插件時能夠自定義類型值,可是要作到開發的datasource插件也適配官方自帶的panel插件,那麼定義datasource返回的數據格式和grafana的一致。 datasource.query的time series
類型響應格式:cookie
[{
"target":"upper_75",
"datapoints":[
[622, 1450754160000],
[365, 1450754220000]
]
}, {
"target":"upper_90",
"datapoints":[
[861, 1450754160000],
[767, 1450754220000]
]
}]
複製代碼
datasource.query的table
類型響應格式:app
[{
"columns": [{
"text": "Time",
"type": "time",
"sort": true,
"desc": true,
}, {
"text": "mean",
}, {
"text": "sum",
}],
"rows": [[
1457425380000,
null,
null
], [
1457425370000,
1002.76215352,
1002.76215352
]],
"type": "table"
}]
複製代碼
傳遞給datasource.query
函數的請求對象:ide
{
"range": {
"from": moment, // 全局時間篩選起始日期
"raw": {from: "now-7d", to: "now"},
"to": moment, // 全局時間篩選結束日期
},
"rangeRaw": {
"from": "now-7d",
"to": "now",
},
"interval": "15m",
"intervalMs": 900000,
"targets": [{ // 定義的查詢條件們
"refId": "A",
"target": "upper_75"
}, {
"refId": "B",
"target": "upper_90"
}],
"format": "json",
"maxDataPoints": 2495, //decided by the panel
"cacheTimeout": undefined,
"panelId": 2,
"timezone": "browser"
}
複製代碼
query函數示例:函數
query(options) { // 返回的結果數據,panel插件會經過監聽'data-received'獲取到
const params = { // 封裝http請求參數
from: options.range.from.format('x'),
to: options.range.to.format('x'),
targets: options.queries,
};
return this.doRequest({ // 發起http請求並返回結果
url: this.url + '/card-data', // 要制定公共接口規範
method: 'POST',
data: params
});
}
doRequest(options) {
options.withCredentials = this.withCredentials;
options.headers = this.headers;
return this.backendSrv.datasourceRequest(options); // datasourceRequest()是grafana提供的請求datasource函數
}
複製代碼
當用戶在添加新數據源時點擊Save&Test
按鈕,詳細信息首先保存到數據庫,而後testDatasource
調用數據源插件中定義的函數。 此函數向數據源發出查詢,驗證數據源是否配置的正確可用,確保當用戶在新儀表板中編寫查詢時,數據源已正確配置。 函數示例:post
/** * 當保存並測試數據源時會調用該函數 * 測試數據源是否正常工 * return { status: "", message: "", title: "" } */
testDatasource() {
return this.doRequest({
url: this.url + '/',
method: 'GET',
}).then(response => {
if (response.status === 200) {
return { status: "success", message: "Data source is working", title: "Success" };
}
});
}
複製代碼
註釋查詢,傳遞給datasource.annotationQuery函數的請求對象:測試
{
"range": {
"from": "2016-03-04T04:07:55.144Z",
"to": "2016-03-04T07:07:55.144Z" },
"rangeRaw": {
"from": "now-3h",
"to": "now"
},
"annotation": {
"datasource": "generic datasource",
"enable": true,
"name": "annotation name"
}
}
複製代碼
datasource.annotationQuery的預期結果:
[{
"annotation": {
"name": "annotation name", //should match the annotation name in grafana
"enabled": true,
"datasource": "generic datasource",
},
"title": "Cluster outage",
"time": 1457075272576,
"text": "Joe causes brain split",
"tags": "joe, cluster, failure"
}]
複製代碼
可使用grafana平臺的數據庫存取'註釋'
當用戶編輯或建立此類型的新數據源時,該類將被實例化並視爲Angular控制器。 該類須要一個靜態模板或templateUrl變量,該模板或變量將被渲染爲此控制器的視圖。 ConfigCtrl類中的this對象內容爲:
{
current: {
name: "代理服務端數據源", // 數據源名稱
isDefault: true, // 是不是默認
type: "grafana-server-datasource", // 數據源插件的id值
url: "http://localhost:3001", // HTTP:數據源對應的url
access: "proxy", // HTTP:鏈接數據源類型,有'direct'和'proxy'兩種類型可選
basicAuth: true, // Auth:Basic Auth選項
basicAuthUser: "basic auth user", // Basic Auth Details:User選項,當basicAuth爲true時有效
basicAuthPassword:"basic auth password", // Basic Auth Details:Password選項,當basicAuth爲true時有效
withCredentials: true, // Auth:With Credentials選項
jsonData: {
tlsAuth: true, // Auth:TLS Client Auth選項
tlsAuthWithCACert: true, // Auth: With CA Cert選項
tlsSkipVerify: true, // Auth: Skip TLS Verification (Insecure)選項值
keepCookies: ["Advanced Cookoe"], // Advanced HTTP Settings: cookie的白名單
},
secureJsonData: {
tlsCACert: "TLS Auth CA Cert", // TLS Auth Details:CA Cert選項,當jsonData下的tlsAuthWithCACert值爲true時有效
tlsClientCert: "TLS Auth Client Cert", // TLS Auth Details:Client Cert選項,當jsonData下的tlsAuth值爲true時有效
tlsClientKey: "TLS Auth Client Key", // TLS Auth Details:Client Key選項,當jsonData下的tlsAuth值爲true時有效
},
secureJsonFields: {},
},
meta: {
baseUrl: "public/plugins/grafana-server-datasource",
defaultNavUrl: "",
dependencies: {
grafanaVersion: "3.x.x",
plugins: [],
},
enabled: false,
hasUpdate: false,
id: "grafana-server-datasource",
includes: null,
info: { // plugin.json中配置的信息
author: {
name: "liuchunhui",
url: "https://grafana.com"
},
description: "代理服務端做爲數據源",
links: [
{name: "Github", url: ""},
{name: "MIT License", url: ""}
],
logos: {
large:"public/plugins/grafana-server-datasource/img/server-logo.png",
small:"public/plugins/grafana-server-datasource/img/server-logo.png"
},
screenshots:null,
updated:"2018-04-23",
version:"1.0.0"
},
jsonData: null,
latestVersion: "",
module: "plugins/grafana-server-datasource/module",
name: "代理服務端",
pinned: false
state: "",
type: "datasource",
}
複製代碼
模板頁面中使用grafana封裝的angular組件,傳入this的current
對象,實現HTTP、Auth兩個模塊的定義:
<datasource-http-settings current="ctrl.current"></datasource-http-settings>
複製代碼
一個JavaScript類,當用戶在面板中編輯指標時,它將被實例化並做爲Angular控制器處理。 該類必須從app/plugins/sdk.QueryCtrl
類繼承。 該類須要一個靜態模板或templateUrl變量,該模板或變量將被渲染爲此控制器的視圖。 當用戶在panel面板下,切回到Metrics
模塊時,會初始化該類。因此咱們能夠在構造函數中作一些咱們本身的事情。好比獲取指標維度列表,做爲用戶篩選的展現條件。
import { QueryCtrl } from 'app/plugins/sdk';
export default class GenericQueryCtrl extends QueryCtrl {
constructor($scope, $injector) {
super($scope, $injector);
// 獲取參數列表請求
this.requestParams().then(response => {
const targets = response.data.target;
this.options = response.data.options;
this.text = response.data.text;
this.keys = Object.keys(targets);
for (let key in targets) {
this.target[key] = this.target[key] || targets[key];
}
});
}
requestParams() { // 請求獲取參數列表
const params = {
header: {
'Content-Type': 'application/json'
},
method: 'GET',
retry: 0,
url: this.datasource.url + '/param-list'
};
return this.datasource.backendSrv.datasourceRequest(params); // 使用grafana提供的http請求函數
}
onChangeInternal() { // 刷新面板
this.panelCtrl.refresh(); // grafana自帶方法使面板更新數據
}
toggleEditorMode() { // 是否開啓編輯模式
this.target.rawQuery = !this.target.rawQuery;
}
}
GenericQueryCtrl.templateUrl = './page/query.html';
複製代碼
QueryCtrl控制器的query.html模板:
<query-editor-row query-ctrl="ctrl" has-text-edit-mode="true">
<div class="gf-form" ng-if="!ctrl.target.rawQuery" ng-repeat="key in ctrl.keys">
<span class="gf-form-label width-7">
{{ctrl.text[key]}}
</span>
<select class="gf-form-input width-25" ng-model="ctrl.target[key]" ng-change="ctrl.onChangeInternal()">
<option ng-repeat="option in ctrl.options[key]" value="{{option.name}}">
{{option.desc}}
</option>
</select>
</div>
<div ng-if="ctrl.target.rawQuery">
<textarea class="gf-form-input" rows="5" spellcheck="false" ng-blur="ctrl.onChangeInternal()" />
</div>
</query-editor-row>
複製代碼
<query-editor-row query-ctrl="ctrl">
標籤的內容會加入到Add Query
模板中,標籤中的has-text-edit-mode="true"屬性,能開啓Toggle Edit Mode
功能。 QueryCtrl控制器中的target.rawQuery參數,標記着兩種編輯模式的切換,可是這兩種模式須要寫代碼定義。
當用戶在datasource的模板菜單中選擇這種類型的數據源時,將被實例化並做爲Angular控制器處理的JavaScript類。 此類須要一個靜態模板或templateUrl變量,該模板或變量將被渲染爲此控制器的視圖。 綁定到此控制器的字段隨後會發送到數據庫對象annotationQuery函數。 在開發插件時能自定義dashboard的Built in query
的條件。 AnnotationQueryCtrl代碼:
export default class GenericAnnotationsQueryCtrl {}
GenericAnnotationsQueryCtrl.templateUrl = './page/annotationsQuery.html';
複製代碼
annotationsQuery.html代碼:
<h5 class="section-heading">註解查詢條件設定</h5>
<div class="gf-form-group">
<div class="gf-form">
<input type="text" class="gf-form-input" ng-model='ctrl.annotation.query' placeholder="" />
</div>
</div>
複製代碼
一個JavaScript類,當用戶在面板中編輯指標時,它將被實例化並做爲Angular控制器處理。 此控制器負責處理數據源的面板範圍設置,如間隔,速率和聚合(若是須要)。 此類須要一個靜態模板或templateUrl變量,該模板或變量將被渲染爲此控制器的視圖。
QueryOptionsCtrl代碼:
export default class GenericQueryOptionsCtrl {}
GenericQueryOptionsCtrl.templateUrl = './page/queryOptions.html';
複製代碼
queryOptions.html代碼:
<section class="grafana-metric-options" >
<div class="gf-form"></div>
</section>
複製代碼