-
Notifications
You must be signed in to change notification settings - Fork 1
/
grafana.js
63 lines (52 loc) · 1.78 KB
/
grafana.js
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
import http from 'k6/http';
import { b64encode } from 'k6/encoding';
export function getUnixTimestamp () {
return new Date().getTime();
}
function calcAuthorizationHeader(username, password) {
const str = b64encode(`${username}:${password}`);
return `Basic ${str}`;
}
function getApiKeyName () {
// Grafana is picky with api key names, generate unique api key name
const apiKeyName = 'pensum-key';
const ts = getUnixTimestamp();
return `${apiKeyName}-${ts}`;
}
function createApiKey (url, apiKeyName, auth) {
const res = http.post(`${url}/api/auth/keys`, JSON.stringify({
'name': apiKeyName,
'role': 'Admin',
'secondsToLive': 120
}), {
headers: {
'Authorization': auth,
'Content-Type': 'application/json',
}
});
const json = JSON.parse(res.body);
return json.key;
}
function deleteApiKey (url, keyId, auth) {
http.del(`${url}/api/auth/keys/${keyId}`, {}, {
headers: { 'Authorization': auth }
});
}
export function getApiKey (url, username, password) {
const auth = calcAuthorizationHeader(username, password);
const res = http.get(`${url}/api/auth/keys`, {
headers: { 'Authorization': auth }
});
const json = JSON.parse(res.body);
const apiKeyName = getApiKeyName();
let apiKey = json.find(({ name }) => name === apiKeyName);
if (apiKey) {
deleteApiKey(url, apiKey.id, auth);
}
apiKey = createApiKey(url, apiKeyName, auth);
return apiKey;
}
export function getReportUrl (grafanaUrl, reportUrl, username, password, runTag, from, to, dashboardUID) {
const apiKey = getApiKey(grafanaUrl, username, password);
return `${reportUrl}/api/v5/report/${dashboardUID}?apitoken=${apiKey}&from=${from}&to=${to}&var-Run=${runTag}`;
}