forked from GoogleCloudPlatform/nodejs-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_custom_metric.js
274 lines (248 loc) · 7.96 KB
/
create_custom_metric.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
// Copyright 2015, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Simple command-line program to demonstrate creating a custom
* metric with the Google Cloud Monitoring API, writing a random value to it,
* and reading it back.
*/
'use strict';
/* jshint camelcase: false */
var google = require('googleapis');
var async = require('async');
var monitoringScopes = [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/monitoring',
'https://www.googleapis.com/auth/monitoring.read',
'https://www.googleapis.com/auth/monitoring.write'
];
/**
* Returns the current timestamp in RFC33339 with milliseconds format.
*/
function getNow () {
var d = new Date();
return JSON.parse(JSON.stringify(d).replace('Z', '000Z'));
}
/**
* Returns an hour ago in RFC33339 with milliseconds format. This is used
* to start the window to view the metric written in.
*/
function getStartTime () {
var d = new Date();
d.setHours(d.getHours() - 1);
return JSON.parse(JSON.stringify(d).replace('Z', '000Z'));
}
var CUSTOM_METRIC_DOMAIN = 'custom.googleapis.com';
/**
* Constructor function. The CustomMetrics class stores the type of metric
* in its instance class allowing unique ones to be used in tests.
*/
function CustomMetrics (projectName, metricType) {
this.projectResource = 'projects/' + projectName;
this.metricType = CUSTOM_METRIC_DOMAIN + '/' + metricType;
this.metricName = this.projectResource +
'/metricDescriptors/' + this.metricType;
this.valueOverride = false;
}
/**
* Creates a custom metric. For demonstration purposes, this is a hypothetical
* measurement (measured in the 'items' unit, with random values written to
* it.
* @param {Object} authClient The authorized Monitoring client.
* @param {Function} callback Callback function.
*/
CustomMetrics.prototype.createCustomMetric = function (client, callback) {
var monitoring = google.monitoring('v3');
monitoring.projects.metricDescriptors.create({
auth: client,
name: this.projectResource,
resource: {
name: this.metricName,
type: this.metricType,
labels: [
{
key: 'environment',
valueType: 'STRING',
description: 'An abritrary measurement'
}
],
metricKind: 'GAUGE',
valueType: 'INT64',
unit: 'items',
description: 'An arbitrary measurement.',
displayName: 'Custom Metric'
}
}, function (err, customMetric) {
if (err) {
return callback(err);
}
console.log('Created custom metric', customMetric);
callback(null, customMetric);
});
};
/**
* Writes a time series value for the custom metric just created. It uses a
* GAUGE measurement which indicates the value at this point in time. For
* demonstration purposes, this is a random value. For GAUGE measurements,
* the start time and end time of the value must be the same. The
* resource for this value is a hypothetical GCE instance.
* @param {Object} authClient The authorized Google Cloud Monitoring API client
* @param {Function} callback Callback Function.
*/
CustomMetrics.prototype.writeTimeSeriesForCustomMetric =
function (client, callback) {
var monitoring = google.monitoring('v3');
var now = getNow();
monitoring.projects.timeSeries.create({
auth: client,
name: this.projectResource,
resource: {
timeSeries: [{
metric: {
type: this.metricType,
labels: {
environment: 'production'
}
},
resource: {
type: 'gce_instance',
labels: {
instance_id: 'test_instance',
zone: 'us-central1-f'
}
},
metricKind: 'GAUGE',
valueType: 'INT64',
points: {
interval: {
startTime: now,
endTime: now
},
value: {
int64Value: this.getRandomInt(1, 20)
}
}
}]
}
}, function (err, timeSeries) {
if (err) {
return callback(err);
}
console.log('Wrote time series', timeSeries);
callback(null, timeSeries);
});
};
/**
* Lists the time series written for the custom metric. The window
* to read the timeseries starts an hour ago and extends unti the current
* time, so should include the metric value written by
* the earlier calls.
* @param {Object} authClient The authorized Google Cloud Monitoring API client
* @param {Function} callback Callback function.
*/
CustomMetrics.prototype.listTimeSeries = function (client, callback) {
var monitoring = google.monitoring('v3');
var startTime = getStartTime();
var endTime = getNow();
console.log('Reading metric type', this.metricType);
monitoring.projects.timeSeries.list({
auth: client,
name: this.projectResource,
filter: 'metric.type="' + this.metricType + '"',
pageSize: 3,
'interval.startTime': startTime,
'interval.endTime': endTime
}, function (err, timeSeries) {
if (err) {
return callback(err);
}
console.log('Time series', timeSeries);
callback(null, timeSeries);
});
};
/**
* @param {Object} authClient The authorized Google Cloud Monitoring API client
* @param {Function} callback Callback function.
*/
CustomMetrics.prototype.deleteMetric = function (client, callback) {
var monitoring = google.monitoring('v3');
console.log(this.metricName);
monitoring.projects.metricDescriptors.delete({
auth: client,
name: this.metricName
}, function (err, result) {
if (err) {
return callback(err);
}
console.log('Deleted metric', result);
callback(null, result);
});
};
/**
* Gets random integer between low and high (exclusive). Used to fill in
* a random value for the measurement.
*/
CustomMetrics.prototype.getRandomInt = function (low, high) {
return Math.floor(Math.random() * (high - low) + low);
};
CustomMetrics.prototype.getMonitoringClient = function (callback) {
google.auth.getApplicationDefault(function (err, authClient) {
if (err) {
return callback(err);
}
// Depending on the environment that provides the default credentials
// (e.g. Compute Engine, App Engine), the credentials retrieved may
// require you to specify the scopes you need explicitly.
// Check for this case, and inject the Cloud Storage scope if required.
if (authClient.createScopedRequired &&
authClient.createScopedRequired()) {
authClient = authClient.createScoped(monitoringScopes);
}
callback(null, authClient);
});
};
// Run the examples
exports.main = function (projectId, name, cb) {
var customMetrics = new CustomMetrics(projectId, name);
customMetrics.getMonitoringClient(function (err, authClient) {
if (err) {
return cb(err);
}
// Create the service object.
async.series([
function (cb) {
customMetrics.createCustomMetric(authClient, cb);
},
function (cb) {
setTimeout(function () {
customMetrics.writeTimeSeriesForCustomMetric(authClient, cb);
}, 5000);
},
function (cb) {
setTimeout(function () {
customMetrics.listTimeSeries(authClient, cb);
}, 5000);
},
function (cb) {
customMetrics.deleteMetric(authClient, cb);
}
], cb);
});
};
if (require.main === module) {
var args = process.argv.slice(2);
exports.main(
args[0] || process.env.GCLOUD_PROJECT,
args[1] || 'custom_measurement',
console.log
);
}