-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathdatasource.ts
277 lines (235 loc) · 8.28 KB
/
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
import _ from 'lodash';
import { isValid, parseISO } from 'date-fns';
import { JSONPath } from 'jsonpath-plus';
import {
DataQueryRequest,
DataQueryResponse,
DataSourceApi,
DataSourceInstanceSettings,
toDataFrame,
MetricFindValue,
FieldType,
ScopedVars,
TimeRange,
} from '@grafana/data';
import { getTemplateSrv } from '@grafana/runtime';
import API from './api';
import { JsonApiQuery, JsonApiDataSourceOptions, Pair } from './types';
export class JsonDataSource extends DataSourceApi<JsonApiQuery, JsonApiDataSourceOptions> {
api: API;
constructor(instanceSettings: DataSourceInstanceSettings<JsonApiDataSourceOptions>) {
super(instanceSettings);
this.api = new API(instanceSettings.url!, instanceSettings.jsonData.queryParams || '');
}
/**
* metadataRequest is used by the language provider to return the JSON
* document to generate suggestions for the QueryField.
*
* This is a custom method and is not part of the DataSourceApi, feel free to
* name it as you like.
*/
async metadataRequest(query: JsonApiQuery, range?: TimeRange) {
return this.requestJson(query, replace({}, range));
}
async query(request: DataQueryRequest<JsonApiQuery>): Promise<DataQueryResponse> {
const promises = request.targets.map((query) => this.doRequest(query, request.range, request.scopedVars));
// Wait for all queries to finish before returning the result.
return Promise.all(promises).then((data) => ({ data }));
}
/**
* Returns values for a Query variable.
*
* @param query
*/
async metricFindQuery?(query: JsonApiQuery): Promise<MetricFindValue[]> {
const frame = await this.doRequest(query);
return frame.fields[0].values.toArray().map((_) => ({ text: _ }));
}
/**
* This line adds support for annotation queries in >=7.2.
*/
annotations = {};
/**
* Checks whether we can connect to the API.
*/
async testDatasource() {
const defaultErrorMessage = 'Cannot connect to API';
try {
const response = await this.api.test();
if (response.status === 200) {
return {
status: 'success',
message: 'Success',
};
} else {
return {
status: 'error',
message: response.statusText ? response.statusText : defaultErrorMessage,
};
}
} catch (err) {
if (_.isString(err)) {
return {
status: 'error',
message: err,
};
} else {
let message = 'JSON API: ';
message += err.statusText ? err.statusText : defaultErrorMessage;
if (err.data && err.data.error && err.data.error.code) {
message += ': ' + err.data.error.code + '. ' + err.data.error.message;
}
return {
status: 'error',
message,
};
}
}
}
async doRequest(query: JsonApiQuery, range?: TimeRange, scopedVars?: ScopedVars) {
const replaceWithVars = replace(scopedVars, range);
const json = await this.requestJson(query, replaceWithVars);
if (!json) {
throw new Error('Query returned empty data');
}
const fields = query.fields
.filter((field) => field.jsonPath)
.map((field) => {
const path = replaceWithVars(field.jsonPath);
const values = JSONPath({ path, json });
// Get the path for automatic setting of the field name.
//
// Casted to any due to typing issues with JSONPath-Plus
const paths = (JSONPath as any).toPathArray(path);
const propertyType = field.type ? field.type : detectFieldType(values);
const typedValues = parseValues(values, propertyType);
return {
name: paths[paths.length - 1],
type: propertyType,
values: typedValues,
};
});
const fieldLengths = fields.map((field) => field.values.length);
const uniqueFieldLengths = Array.from(new Set(fieldLengths)).length;
// All fields need to have the same length for the data frame to be valid.
if (uniqueFieldLengths > 1) {
throw new Error('Fields have different lengths');
}
return toDataFrame({
name: query.refId,
refId: query.refId,
fields: fields,
});
}
async requestJson(query: JsonApiQuery, interpolate: (text: string) => string) {
const interpolateKeyValue = ([key, value]: Pair<string, string>): Pair<string, string> => {
return [interpolate(key), interpolate(value)];
};
return await this.api.cachedGet(
query.cacheDurationSeconds,
query.method,
interpolate(query.urlPath),
(query.params ?? []).map(interpolateKeyValue),
(query.headers ?? []).map(interpolateKeyValue),
interpolate(query.body)
);
}
}
const replace = (scopedVars?: any, range?: TimeRange) => (str: string): string => {
return replaceMacros(getTemplateSrv().replace(str, scopedVars), range);
};
// replaceMacros substitutes all available macros with their current value.
const replaceMacros = (str: string, range?: TimeRange) => {
return range
? str
.replace(/\$__unixEpochFrom\(\)/g, range.from.unix().toString())
.replace(/\$__unixEpochTo\(\)/g, range.to.unix().toString())
: str;
};
/**
* Detects the field type from an array of values.
*/
export const detectFieldType = (values: any[]): FieldType => {
// If all values are null, default to strings.
if (values.every((_) => _ === null)) {
return FieldType.string;
}
// If all values are valid ISO 8601, then assume that it's a time field.
const isValidISO = values
.filter((value) => value !== null)
.every((value) => value.length >= 10 && isValid(parseISO(value)));
if (isValidISO) {
return FieldType.time;
}
if (values.every((value) => typeof value === 'number')) {
const uniqueLengths = Array.from(new Set(values.map((value) => Math.round(value).toString().length)));
const hasSameLength = uniqueLengths.length === 1;
// If all the values have the same length of either 10 (seconds) or 13
// (milliseconds), assume it's a time field. This is not always true, so we
// might need to add an option to disable detection of time fields.
if (hasSameLength) {
if (uniqueLengths[0] === 13) {
return FieldType.time;
}
if (uniqueLengths[0] === 10) {
return FieldType.time;
}
}
return FieldType.number;
}
if (values.every((value) => typeof value === 'boolean')) {
return FieldType.boolean;
}
return FieldType.string;
};
/**
* parseValues converts values to the given field type.
*/
export const parseValues = (values: any[], type: FieldType): any[] => {
switch (type) {
case FieldType.time:
// For time field, values are expected to be numbers representing a Unix
// epoch in milliseconds.
if (values.filter((_) => _).every((value) => typeof value === 'string')) {
return values.map((_) => (_ !== null ? parseISO(_).valueOf() : _));
}
if (values.filter((_) => _).every((value) => typeof value === 'number')) {
const ms = 1_000_000_000_000;
// If there are no "big" numbers, assume seconds.
if (values.filter((_) => _).every((_) => _ < ms)) {
return values.map((_) => (_ !== null ? _ * 1000.0 : _));
}
// ... otherwise assume milliseconds.
return values;
}
throw new Error('Unsupported time property');
case FieldType.string:
return values.every((_) => typeof _ === 'string') ? values : values.map((_) => (_ !== null ? _.toString() : _));
case FieldType.number:
return values.every((_) => typeof _ === 'number') ? values : values.map((_) => (_ !== null ? parseFloat(_) : _));
case FieldType.boolean:
return values.every((_) => typeof _ === 'boolean')
? values
: values.map((_) => {
if (_ === null) {
return _;
}
switch (_.toString()) {
case '0':
case 'false':
case 'FALSE':
case 'False':
return false;
case '1':
case 'true':
case 'TRUE':
case 'True':
return true;
default:
throw new Error('Found non-boolean values in a field of type boolean: ' + _.toString());
}
});
default:
throw new Error('Unsupported field type');
}
};