forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFN_DataSource.ts
366 lines (332 loc) · 11.8 KB
/
FN_DataSource.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import _ from 'lodash';
import { isEqual } from 'lodash';
import defaults from 'lodash/defaults';
import {
AnnotationEvent,
AnnotationQueryRequest,
DataQueryRequest,
DataQueryResponse,
MetricFindValue,
DataSourceInstanceSettings,
ScopedVars,
TimeRange,
} from '@grafana/data';
import { dateTime, MutableDataFrame, FieldType, DataFrame } from '@grafana/data';
import { getTemplateSrv, DataSourceWithBackend } from '@grafana/runtime';
import { BackendSrv, getBackendSrv } from 'app/core/services/backend_srv';
import { BackendSrvRequest } from '../../../../../packages/grafana-runtime/src/services/backendSrv';
import {
MyQuery,
MyDataSourceOptions,
defaultQuery,
MyVariableQuery,
MultiValueVariable,
TextValuePair,
} from './types';
import { flatten, isRFC3339_ISO6801 } from './util';
const supportedVariableTypes = ['constant', 'custom', 'query', 'textbox'];
export class FN_DataSource extends DataSourceWithBackend<MyQuery, MyDataSourceOptions> {
basicAuth: string | undefined;
withCredentials: boolean | undefined;
url: string | undefined;
backendSrv: BackendSrv;
constructor(instanceSettings: DataSourceInstanceSettings<MyDataSourceOptions>) {
super(instanceSettings);
this.basicAuth = instanceSettings.basicAuth;
this.withCredentials = instanceSettings.withCredentials;
console.log({instanceSettings})
const url = instanceSettings.jsonData["connection.url"]
// const url = "http://localhost:8081/api/query"
this.url = url;
this.backendSrv = getBackendSrv();
}
private request(data: string) {
const options: BackendSrvRequest = {
url: this.url as string,
method: 'POST',
data: {
query: data,
},
};
if (this.basicAuth || this.withCredentials) {
options.withCredentials = true;
}
if (this.basicAuth) {
options.headers = {
Authorization: this.basicAuth,
};
}
return this.backendSrv.datasourceRequest(options);
}
private postQuery(query: Partial<MyQuery>, payload: string) {
return this.request(payload)
.then((results: any) => {
return { query, results };
})
.catch((err: any) => {
if (err.data && err.data.error) {
throw {
message: 'GraphQL error: ' + err.data.error.reason,
error: err.data.error,
};
}
throw err;
});
}
private createQuery(query: MyQuery, range: TimeRange | undefined, scopedVars: ScopedVars | undefined = undefined) {
let payload = getTemplateSrv().replace(query.queryText, {
...scopedVars,
timeFrom: { text: 'from', value: range?.from.valueOf() },
timeTo: { text: 'to', value: range?.to.valueOf() },
});
//console.log(payload);
return this.postQuery(query, payload);
}
private static getDocs(resultsData: any, dataPath: string): any[] {
if (!resultsData) {
throw 'resultsData was null or undefined';
}
let data = dataPath.split('.').reduce((d: any, p: any) => {
if (!d) {
return null;
}
return d[p];
}, resultsData.data);
if (!data) {
const errors: any[] = resultsData.errors;
if (errors && errors.length !== 0) {
throw errors[0];
}
throw 'Your data path did not exist! dataPath: ' + dataPath;
}
if (resultsData.errors) {
// There can still be errors even if there is data
console.log('Got GraphQL errors:');
console.log(resultsData.errors);
}
const docs: any[] = [];
let pushDoc = (originalDoc: object) => {
docs.push(flatten(originalDoc));
};
if (Array.isArray(data)) {
for (const element of data) {
pushDoc(element);
}
} else {
pushDoc(data);
}
return docs;
}
private static getDataPathArray(dataPathString: string): string[] {
const dataPathArray: string[] = [];
for (const dataPath of dataPathString.split(',')) {
const trimmed = dataPath.trim();
if (trimmed) {
dataPathArray.push(trimmed);
}
}
if (!dataPathArray) {
throw 'data path is empty!';
}
return dataPathArray;
}
async query(options: DataQueryRequest<MyQuery>): Promise<DataQueryResponse> {
return Promise.all(
options.targets.map((target) => {
return this.createQuery(defaults(target, defaultQuery), options.range, options.scopedVars);
})
).then((results: any) => {
const dataFrameArray: DataFrame[] = [];
for (let res of results) {
const dataPathArray: string[] = FN_DataSource.getDataPathArray(res.query.dataPath);
const { timePath, timeFormat, groupBy, aliasBy } = res.query;
const split = groupBy.split(',');
const groupByList: string[] = [];
for (const element of split) {
const trimmed = element.trim();
if (trimmed) {
groupByList.push(trimmed);
}
}
for (const dataPath of dataPathArray) {
const docs: any[] = FN_DataSource.getDocs(res.results.data, dataPath);
const dataFrameMap = new Map<string, MutableDataFrame>();
for (const doc of docs) {
if (timePath in doc) {
doc[timePath] = dateTime(doc[timePath], timeFormat);
}
const identifiers: string[] = [];
for (const groupByElement of groupByList) {
identifiers.push(doc[groupByElement]);
}
const identifiersString = identifiers.toString();
let dataFrame = dataFrameMap.get(identifiersString);
if (!dataFrame) {
// we haven't initialized the dataFrame for this specific identifier that we group by yet
dataFrame = new MutableDataFrame({ fields: [] });
const generalReplaceObject: any = {};
for (const fieldName in doc) {
generalReplaceObject['field_' + fieldName] = doc[fieldName];
}
for (const fieldName in doc) {
let t: FieldType = FieldType.string;
if (fieldName === timePath || isRFC3339_ISO6801(String(doc[fieldName]))) {
t = FieldType.time;
} else if (_.isNumber(doc[fieldName])) {
t = FieldType.number;
}
let title;
if (identifiers.length !== 0) {
// if we have any identifiers
title = identifiersString + '_' + fieldName;
} else {
title = fieldName;
}
if (aliasBy) {
title = aliasBy;
const replaceObject = { ...generalReplaceObject };
replaceObject['fieldName'] = fieldName;
for (const replaceKey in replaceObject) {
const replaceValue = replaceObject[replaceKey];
const regex = new RegExp('\\$' + replaceKey, 'g');
title = title.replace(regex, replaceValue);
}
title = getTemplateSrv().replace(title, options.scopedVars);
}
dataFrame.addField({
name: fieldName,
type: t,
config: { displayName: title },
}).parse = (v: any) => {
return v || '';
};
}
dataFrameMap.set(identifiersString, dataFrame);
}
dataFrame.add(doc);
}
for (const dataFrame of dataFrameMap.values()) {
dataFrameArray.push(dataFrame);
}
}
}
return { data: dataFrameArray };
});
}
annotationQuery(options: AnnotationQueryRequest<MyQuery>): Promise<AnnotationEvent[]> {
const query = defaults(options.annotation, defaultQuery);
return Promise.all([this.createQuery(query, options.range)]).then((results: any) => {
const r: AnnotationEvent[] = [];
for (const res of results) {
const { timePath, endTimePath, timeFormat } = res.query;
const dataPathArray: string[] = FN_DataSource.getDataPathArray(res.query.dataPath);
for (const dataPath of dataPathArray) {
const docs: any[] = FN_DataSource.getDocs(res.results.data, dataPath);
for (const doc of docs) {
const annotation: AnnotationEvent = {};
if (timePath in doc) {
annotation.time = dateTime(doc[timePath], timeFormat).valueOf();
}
if (endTimePath in doc) {
annotation.isRegion = true;
annotation.timeEnd = dateTime(doc[endTimePath], timeFormat).valueOf();
}
let title = query.annotationTitle;
let text = query.annotationText;
let tags = query.annotationTags;
for (const fieldName in doc) {
const fieldValue = doc[fieldName];
const replaceKey = 'field_' + fieldName;
const regex = new RegExp('\\$' + replaceKey, 'g');
title = title.replace(regex, fieldValue);
text = text.replace(regex, fieldValue);
tags = tags.replace(regex, fieldValue);
}
annotation.title = title;
annotation.text = text;
const tagsList: string[] = [];
for (const element of tags.split(',')) {
const trimmed = element.trim();
if (trimmed) {
tagsList.push(trimmed);
}
}
annotation.tags = tagsList;
r.push(annotation);
}
}
}
return r;
});
}
testDatasource() {
const q = `{
__schema{
queryType{name}
}
}`;
return this.postQuery(defaultQuery, q).then(
(res: any) => {
if (res.errors) {
console.log(res.errors);
return {
status: 'error',
message: 'GraphQL Error: ' + res.errors[0].message,
};
}
return {
status: 'success',
message: 'Success',
};
},
(err: any) => {
console.log(err);
return {
status: 'error',
message: 'HTTP Response ' + err.status + ': ' + err.statusText,
};
}
);
}
async metricFindQuery(query: MyVariableQuery, options?: any) {
const metricFindValues: MetricFindValue[] = [];
query = defaults(query, defaultQuery);
let payload = query.queryText;
payload = getTemplateSrv().replace(payload, { ...this.getVariables });
const response = await this.postQuery(query, payload);
const docs: any[] = FN_DataSource.getDocs(response.results.data, query.dataPath);
for (const doc of docs) {
if ('__text' in doc && '__value' in doc) {
metricFindValues.push({ text: doc['__text'], value: doc['__value'] });
} else {
for (const fieldName in doc) {
metricFindValues.push({ text: doc[fieldName] });
}
}
}
return metricFindValues;
}
getVariables() {
const variables: { [id: string]: TextValuePair } = {};
Object.values(getTemplateSrv().getVariables()).forEach((variable) => {
if (!supportedVariableTypes.includes(variable.type)) {
console.warn(`Variable of type "${variable.type}" is not supported`);
return;
}
const supportedVariable = variable as MultiValueVariable;
let variableValue = supportedVariable.current.value;
if (variableValue === '$__all' || isEqual(variableValue, ['$__all'])) {
if (supportedVariable.allValue === null || supportedVariable.allValue === '') {
variableValue = supportedVariable.options.slice(1).map((textValuePair) => textValuePair.value);
} else {
variableValue = supportedVariable.allValue;
}
}
variables[supportedVariable.id] = {
text: supportedVariable.current.text,
value: variableValue,
};
});
return variables;
}
}