/
aws_ebs.js
287 lines (276 loc) · 9.88 KB
/
aws_ebs.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
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
/**
* The driver gets AWS EBS and uses the script item to make HTTP requests to the CloudWatch API.
*
* Computes hash-based message authentication codes (HMAC) using a specified algorithm and creates a CloudWatch metric to be monitored for an AWS EBS.
* Then it authorizes an HTTP POST request to an Amazon Web Services (AWS) endpoint.
*
* Communication protocol is https
*/
//These functions are used to compute hash-based message authentication codes (HMAC) using a specified algorithm.
function sha256(message) {
return D.crypto.hash(message, "sha256", null, "hex");
}
function hmac(algo, key, message) {
key = D._unsafe.buffer.from(key);
return D.crypto.hmac(message, key, algo, "hex");
}
var region = "ADD_REGION";
var volumeId = "ADD_VOLUME_ID";
var accessKey = D.device.username(); //accessKey == username
var secretKey = D.device.password(); //secretKey == password
var requestPeriod = 600;
var volumes;
var vars = [];
function sign(key, message) {
var hex = hmac("sha256", key, message);
if ((hex.length % 2) === 1) {
throw "Invalid length of a hex string!";
}
var result = new Int8Array(hex.length / 2);
for (var i = 0, b = 0; i < hex.length; i += 2, b++) {
result[b] = parseInt(hex.substring(i, i + 2), 16);
}
return result;
}
/**
* @returns CloudWatch metrics to be monitored for an AWS EBS.
*/
function createMetricsPayload(period, volumeId) {
var metricsList = [
"BurstBalance:Percent",
"VolumeReadOps:Count",
"VolumeWriteOps:Count",
"VolumeTotalReadTime:Seconds",
"VolumeQueueLength:Count",
"VolumeWriteBytes:Bytes",
"VolumeTotalWriteTime:Seconds",
"VolumeReadBytes:Bytes",
"VolumeIdleTime:Seconds"
];
return metricsList.map(function (metric) {
var parts = metric.split(":", 2);
var name = parts[0].replace(/[^a-zA-Z0-9]/g, "");
return {
"Id": name.charAt(0).toLowerCase() + name.slice(1),
"MetricStat": {
"Metric": {
"MetricName": parts[0],
"Namespace": "AWS/EBS",
"Dimensions": [
{
"Name": "VolumeId",
"Value": volumeId
}
]
},
"Period": period,
"Stat": "Average",
"Unit": parts[1]
}
};
});
}
/**
* Authorization based on: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
* @returns an HTTP POST request to an Amazon Web Services (AWS) endpoint.
*/
function httpPost(data) {
var d = D.q.defer();
var service = "monitoring";
var body = JSON.stringify(data);
var method = "POST";
var amzdate = (new Date()).toISOString().replace(/\.\d+Z/, "Z").replace(/[-:]/g, ""),
date = amzdate.replace(/T\d+Z/, ""),
host = service + "." + region + ".amazonaws.com:443",
device = D.createExternalDevice(service + "." + region + ".amazonaws.com"),
canonicalUri = "/",
canonicalHeaders = "content-encoding:amz-1.0\n" + "host:" + host + "\n" + "x-amz-date:" + amzdate + "\n",
signedHeaders = "content-encoding;host;x-amz-date",
canonicalRequest = method + "\n" + canonicalUri + "\n" + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + sha256(body),
credentialScope = date + "/" + region + "/" + service + "/" + "aws4_request",
requestString = "AWS4-HMAC-SHA256" + "\n" + amzdate + "\n" + credentialScope + "\n" + sha256(canonicalRequest),
key = sign("AWS4" + secretKey, date);
key = sign(key, region);
key = sign(key, service);
key = sign(key, "aws4_request");
var auth = "AWS4-HMAC-SHA256 Credential=" + accessKey + "/" + credentialScope + ", " + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + hmac("sha256", key, requestString);
device.http.post({
url: canonicalUri,
protocol: "https",
headers: {
"x-amz-date": amzdate,
"X-Amz-Target": "GraniteServiceVersion20100801.GetMetricData",
"Accept": "application/json",
"Content-Type": "application/json",
"Content-Encoding": "amz-1.0",
"Authorization": auth
},
body: body
},
function (err, response, body) {
if (err) {
D.failure(D.errorType.GENERIC_ERROR);
}
if (response.statusCode == 404) {
D.failure(D.errorType.RESOURCE_UNAVAILABLE);
}
if (response.statusCode === 401 || response.statusCode === 403) {
D.failure(D.errorType.AUTHENTICATION_ERROR);
}
if (response.statusCode != 200) {
D.failure(D.errorType.GENERIC_ERROR);
}
d.resolve(JSON.parse(body));
});
return d.promise;
}
/**
* @returns promise for http response containing EBS metrics
*/
function getMetricsData() {
var payload = {},
endTime = Math.floor((new Date().getTime()) / 1000),
startTime = endTime - requestPeriod;
payload["Action"] = "GetMetricStatistics";
payload["Version"] = "2010-08-01";
payload["StartTime"] = startTime;
payload["EndTime"] = endTime;
payload["MetricDataQueries"] = createMetricsPayload(requestPeriod, volumeId);
return httpPost(payload)
.then(function (data) {
volumes = data.MetricDataResults;
});
}
/**
* @param {string} label The label to search for in the metric array.
* @returns A function that takes no arguments and returns the first value associated with the given label, or null if no such label exists.
*/
function extractValue(label) {
return function () {
var filteredData = volumes.filter(function (item) { return item.Label === label; });
if (filteredData.length === 0 || filteredData[0].Values.length === 0) {
return null;
}
var value = filteredData[0].Values[0];
if (typeof value !== "number") {
return null;
}
return value.toFixed(3);
};
}
// The list of custom driver variables to monitor
function fillConfig() {
monitoringList = [
{
//Provides information about the percentage of I/O credits (for gp2) or throughput credits (for st1 and sc1) remaining in the burst bucket.
uid: "burst_balance",
label: "Burst balance",
execute: extractValue("BurstBalance"),
unit: "%"
},
{
//The total number of read operations in a specified period of time. Note: read operations are counted on completion.
uid: "read_ops",
label: "Read, ops",
execute: extractValue("VolumeReadOps"),
unit: "Ops"
},
{
//The total number of write operations in a specified period of time.
uid: "write_ops",
label: "Write, ops",
execute: extractValue("VolumeWriteOps"),
unit: "Ops"
},
{
//The total number of seconds spent by all read operations that completed in a specified period of time.uid: "total_read_time",
uid: "total_read_time",
label: "Read time, total",
execute: extractValue("VolumeTotalReadTime"),
unit: "s"
},
{
//The number of read and write operation requests waiting to be completed in a specified period of time.
uid: "queue_length",
label: "Queue length",
execute: extractValue("VolumeQueueLength")
},
{
//Provides information on the write operations in a specified period of time.
uid: "write_bytes",
label: "Write, bytes",
execute: extractValue("VolumeWriteBytes"),
unit: "Bps"
},
{
//The total number of seconds spent by all write operations that completed in a specified period of time.
uid: "total_write_time",
label: "Write time, total",
execute: extractValue("VolumeTotalWriteTime"),
unit: "s"
},
{
//Provides information on the read operations in a specified period of time.
uid: "read_bytes",
label: "Read, bytes",
execute: extractValue("VolumeReadBytes"),
unit: "Bps"
},
{
//The total number of seconds in a specified period of time when no read or write operations were submitted.
uid: "idle_time",
label: "Idle time",
execute: extractValue("VolumeIdleTime"),
unit: "s"
},
];
}
/**
* @param {[object]} data array of objects
* @returns list of domotz variables
*/
function extract(data) {
vars = monitoringList.map(function (c) {
var result;
if (Array.isArray(c.execute)) {
result = c.execute.reduce(function (a, b) { return b(a); }, data);
} else if (typeof (c.execute) == "function") {
result = c.execute(data);
}
if (result != null) {
return D.device.createVariable(c.uid, c.label, result, c.unit, c.type);
} else {
return null;
}
}).filter(function (v) {
return v != null;
});
}
function failure(err) {
console.error(err);
D.failure(D.errorType.GENERIC_ERROR);
}
/**
* @remote_procedure
* @label Validate Association
* @documentation This procedure is used to validate if the driver AWS EBS is accessible.
*/
function validate() {
getMetricsData()
.then(function () {
D.success();
}).catch(failure);
}
/**
* @remote_procedure
* @label Get Device Variables
* @documentation This procedure is used to extract monitoring parameters from AWS EBS.
*/
function get_status() {
getMetricsData()
.then(fillConfig)
.then(extract)
.then(function () {
D.success(vars);
}).catch(failure);
}