Skip to content

Commit ba4914c

Browse files
author
Jon Wayne Parrott
committed
Merge pull request #82 from GoogleCloudPlatform/monitoringv3
Add Monitoring v3 Samples
2 parents 3807926 + 2f88e01 commit ba4914c

File tree

4 files changed

+442
-0
lines changed

4 files changed

+442
-0
lines changed

monitoring/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Cloud Monitoring Sample
2+
3+
`list_resources.js` is a command-line program to demonstrate connecting to the Google
4+
Monitoring API to retrieve API data.
5+
6+
`create_custom_metric.js` demonstrates how to create a custom metric, write a timeseries value to it,
7+
and read it back.
8+
9+
## Prerequisites to run locally:
10+
11+
Go to the [Google Developers Console](https://console.developer.google.com).
12+
13+
* Go to API Manager -> Credentials and click New Credential in the Google Developers Console.
14+
[or click here ]{https://console.developers.google.com/project/_/apiui/credential/serviceaccount)
15+
Select a JSON-format key, which will be downloaded to your computer. The key file must be located on the computer(s) from which you will access the Monitoring API. Access to the file should be restricted so that only trusted people can read the key.
16+
17+
```
18+
export GOOGLE_APPLICATION_CREDENTIALS=~/Downloads/<project-id>-0123456789abcdef.json
19+
```
20+
21+
# Run locally
22+
23+
npm install
24+
node list_resources.js <YOUR-PROJECT-ID>
25+
node create_custom_metric.js <YOUR-PROJECT-ID>
26+
27+

monitoring/create_custom_metric.js

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
// Copyright 2015, Google, Inc.
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
/**
15+
* @fileoverview Simple command-line program to demonstrate creating a custom
16+
* metric with the Google Cloud Monitoring API, writing a random value to it,
17+
* and reading it back.
18+
*/
19+
'use strict';
20+
21+
/* jshint camelcase: false */
22+
23+
var google = require('googleapis');
24+
var async = require('async');
25+
26+
var args = process.argv.slice(2);
27+
if (args.length !== 1) {
28+
console.log('Usage: node auth_and_list_env.js <project_id>');
29+
process.exit();
30+
}
31+
32+
var monitoringScopes = [
33+
'https://www.googleapis.com/auth/cloud-platform',
34+
'https://www.googleapis.com/auth/monitoring',
35+
'https://www.googleapis.com/auth/monitoring.read',
36+
'https://www.googleapis.com/auth/monitoring.write'
37+
];
38+
39+
40+
/** The project resource created from the project ID */
41+
var PROJECT_RESOURCE = 'projects/' + args[0];
42+
43+
/** This domain should be used for all custom metrics. */
44+
var CUSTOM_METRIC_DOMAIN = 'custom.googleapis.com';
45+
46+
/** This is the type of the custom metric */
47+
var CUSTOM_METRIC_TYPE = CUSTOM_METRIC_DOMAIN + '/custom_measurement';
48+
49+
/** This is the name of the custom metric */
50+
var CUSTOM_METRIC_NAME = PROJECT_RESOURCE + '/metricDescriptors/' +
51+
CUSTOM_METRIC_TYPE;
52+
53+
/**
54+
* Returns the current timestamp in RFC33339 with milliseconds format.
55+
*/
56+
function getNow() {
57+
var d = new Date();
58+
return JSON.parse(JSON.stringify(d).replace('Z', '000Z'));
59+
}
60+
61+
/**
62+
* Returns an hour ago in RFC33339 with milliseconds format. This is used
63+
* to start the window to view the metric written in.
64+
*/
65+
function getStartTime() {
66+
var d = new Date();
67+
d.setHours(d.getHours() - 1);
68+
return JSON.parse(JSON.stringify(d).replace('Z', '000Z'));
69+
}
70+
71+
/**
72+
* Gets random integer between low and high (exclusive). Used to fill in
73+
* a random value for the measurement.
74+
*/
75+
function getRandomInt(low, high) {
76+
return Math.floor(Math.random() * (high - low) + low);
77+
}
78+
79+
80+
/**
81+
* Creates a custo metric. For demonstration purposes, this is a hypothetical
82+
* measurement (measured in the 'items' unit, with random values written to
83+
* it.
84+
* @param authClient The authorized Monitoring client.
85+
* @param projectId
86+
* @param callback
87+
*/
88+
function createCustomMetric(authClient, projectResource, callback) {
89+
var monitoring = google.monitoring('v3');
90+
91+
monitoring.projects.metricDescriptors.create({
92+
auth: authClient,
93+
name: projectResource,
94+
resource: {
95+
name: CUSTOM_METRIC_NAME,
96+
type: CUSTOM_METRIC_TYPE,
97+
labels: [
98+
{
99+
key: 'environment',
100+
valueType: 'STRING',
101+
description: 'An abritrary measurement'
102+
}
103+
],
104+
metricKind: 'GAUGE',
105+
valueType: 'INT64',
106+
unit: 'items',
107+
description: 'An arbitrary measurement.',
108+
displayName: 'Custom Metric'
109+
}
110+
}, function (error, customMetric) {
111+
if (error) {
112+
console.error('Error Creating Custom Metric', error);
113+
return;
114+
}
115+
console.log('createCustomMetric: ');
116+
console.log(customMetric);
117+
callback();
118+
});
119+
}
120+
121+
/**
122+
* Writes a time series value for the custom metric just created. It uses a
123+
* GAUGE measurement which indicates the value at this point in time. For
124+
* demonstration purposes, this is a random value. For GAUGE measurements,
125+
* the start time and end time of the value must be the same. The
126+
* resource for this value is a hypothetical GCE instance.
127+
* @param authClient The authorized Google Cloud Monitoring API client
128+
* @param projectResource The project resource created from the project ID
129+
* @param callback
130+
*/
131+
function writeTimeSeriesForCustomMetric(client, projectResource, callback) {
132+
var monitoring = google.monitoring('v3');
133+
var now = getNow();
134+
monitoring.projects.timeSeries.create({
135+
auth: client,
136+
name: projectResource,
137+
resource: {
138+
timeSeries: [{
139+
metric: {
140+
type: CUSTOM_METRIC_TYPE,
141+
labels: {
142+
environment: 'STAGING'
143+
}
144+
},
145+
resource: {
146+
type: 'gce_instance',
147+
labels: {
148+
instance_id: 'test_instance',
149+
zone: 'us-central1-f'
150+
}
151+
},
152+
metricKind: 'GAUGE',
153+
valueType: 'INT64',
154+
points: {
155+
interval: {
156+
startTime: now,
157+
endTime: now
158+
},
159+
value: {
160+
int64Value: getRandomInt(1, 20)
161+
}
162+
}
163+
}]
164+
}
165+
}, function (error, timeSeries) {
166+
if (error) {
167+
console.error('Error writing time series', error);
168+
return;
169+
}
170+
console.log('timeSeries: ');
171+
console.log(timeSeries);
172+
callback();
173+
});
174+
}
175+
176+
/**
177+
* Lists the time series written for the custom metric. The window
178+
* to read the timeseries starts an hour ago and extends unti the current
179+
* time, so should include the metric value written by
180+
* the earlier calls.
181+
* @param authClient The authorized Google Cloud Monitoring API client
182+
* @param projectResource The project resource created from the project ID
183+
* @param callback
184+
*/
185+
function listTimeSeries(client, projectResource, callback) {
186+
var monitoring = google.monitoring('v3');
187+
var startTime = getStartTime();
188+
var endTime = getNow();
189+
monitoring.projects.timeSeries.list({
190+
auth: client,
191+
name: projectResource,
192+
filter: 'metric.type="' + CUSTOM_METRIC_TYPE + '"',
193+
pageSize: 3,
194+
'interval.startTime': startTime,
195+
'interval.endTime': endTime
196+
}, function (error, timeSeries) {
197+
if (error) {
198+
console.error('Error readTimeseries', error);
199+
return;
200+
}
201+
console.log('readTimeseries ');
202+
console.log(JSON.stringify(timeSeries));
203+
callback();
204+
});
205+
}
206+
207+
google.auth.getApplicationDefault(function (error, authClient) {
208+
if (error) {
209+
console.error(error);
210+
process.exit(1);
211+
}
212+
213+
// Depending on the environment that provides the default credentials
214+
// (e.g. Compute Engine, App Engine), the credentials retrieved may
215+
// require you to specify the scopes you need explicitly.
216+
// Check for this case, and inject the Cloud Storage scope if required.
217+
if (authClient.createScopedRequired &&
218+
authClient.createScopedRequired()) {
219+
authClient = authClient.createScoped(monitoringScopes);
220+
}
221+
222+
// Create the service object.
223+
async.series([
224+
function (callback) {
225+
createCustomMetric(authClient, PROJECT_RESOURCE, callback);
226+
}, function (callback) {
227+
writeTimeSeriesForCustomMetric(authClient,
228+
PROJECT_RESOURCE, callback);
229+
}, function (callback) {
230+
// wait 2 seconds for the write to be received
231+
setTimeout(function () {
232+
listTimeSeries(authClient, PROJECT_RESOURCE, callback);
233+
}, 2000);
234+
}]);
235+
});

0 commit comments

Comments
 (0)