diff --git a/monitoring/README.md b/monitoring/README.md index 520c781ead..47cacb7688 100644 --- a/monitoring/README.md +++ b/monitoring/README.md @@ -1,8 +1,8 @@ Google Cloud Platform logo -# Stackdriver Monitoring Node.js Samples +# Stackdriver Monitoring: Node.js Samples -[![Build](https://storage.googleapis.com/cloud-docs-samples-badges/GoogleCloudPlatform/nodejs-docs-samples/nodejs-docs-samples-monitoring.svg)]() +[![Build](https://storage.googleapis.com/.svg)]() [Stackdriver Monitoring](https://cloud.google.com/monitoring/docs) collects metrics, events, and metadata from Google Cloud Platform, Amazon Web Services (AWS), hosted uptime probes, application instrumentation, and a variety of common application components including Cassandra, Nginx, Apache Web Server, Elasticsearch and many others. @@ -11,8 +11,7 @@ * [Setup](#setup) * [Samples](#samples) * [Metrics](#metrics) - * [Listing resources](#listing-resources) - * [Custom metrics](#custom-metrics) + * [Uptime Config](#uptime-config) * [Running the tests](#running-the-tests) ## Setup @@ -59,6 +58,7 @@ Commands: get-resource [projectId] Get a monitored resource descriptor. Options: + --version Show version number [boolean] --help Show help [boolean] --projectId, -p [string] @@ -81,37 +81,38 @@ For more information, see https://cloud.google.com/monitoring/docs [metrics_0_docs]: https://cloud.google.com/monitoring/docs [metrics_0_code]: metrics.js -### Listing resources +### Uptime Config -View the [documentation][list_1_docs] or the [source code][list_1_code]. +View the [documentation][uptime_1_docs] or the [source code][uptime_1_code]. -`list_resources.js` is a command-line program to demonstrate connecting to the -Google Monitoring API to retrieve API data. +__Usage:__ `node uptime.js --help` -__Usage:__ `node list_resources ` - -``` -node list_resources my-cool-project ``` +Commands: + create [projectId] Creates an uptime check config. + list [projectId] Lists uptime check configs. + list-ips Lists uptime check config IPs. + get [projectId] Gets an uptime check config. + delete [projectId] Deletes an uptime check config. -[list_1_docs]: https://cloud.google.com/monitoring/demos/#hello-world -[list_1_code]: list_resources.js - -### Custom metrics - -View the [documentation][metrics_2_docs] or the [source code][metrics_2_code]. - -`create_custom_metric.js` demonstrates how to create a custom metric, write a -timeseries value to it, and read it back. +Options: + --version Show version number [boolean] + --help Show help [boolean] + --projectId, -p [string] -__Usage:__ `node create_custom_metric ` +Examples: + node uptime.js create my-instance Create an uptime check for a "my-instance" GCE instance. + node uptime.js list List all uptime check configs. + node uptime.js list-ips + node uptime.js get My-Uptime-Check + node uptime.js delete My-Uptime-Check +For more information, see https://cloud.google.com/monitoring/uptime-checks/ ``` -node create_custom_metric my-cool-project -``` -[metrics_2_docs]: https://cloud.google.com/monitoring/demos/#custom_metrics -[metrics_2_code]: create_custom_metric.js +[uptime_1_docs]: https://cloud.google.com/monitoring/docs +[uptime_1_code]: uptime.js + ## Running the tests diff --git a/monitoring/metrics.js b/monitoring/metrics.js index ee3a5c0c25..52d899d973 100644 --- a/monitoring/metrics.js +++ b/monitoring/metrics.js @@ -29,9 +29,11 @@ function createMetricDescriptor (projectId) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; const request = { @@ -82,9 +84,11 @@ function listMetricDescriptors (projectId) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; const request = { @@ -111,13 +115,13 @@ function getMetricDescriptor (projectId, metricId) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; - - // An example of "metricId" is "logging.googleapis.com/log_entry_count" - // const metricId = 'some/metric/id'; + // const metricId = 'custom.googleapis.com/your/id'; const request = { name: client.metricDescriptorPath(projectId, metricId) @@ -151,12 +155,12 @@ function deleteMetricDescriptor (projectId, metricId) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; - - // The ID of the Metric Descriptor to delete, e.g. // const metricId = 'custom.googleapis.com/stores/daily_sales'; const request = { @@ -180,9 +184,11 @@ function writeTimeSeriesData (projectId, metricId) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; const dataPoint = { @@ -238,12 +244,12 @@ function readTimeSeriesData (projectId, filter) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; - - // An example "filter" is 'metric.type="compute.googleapis.com/instance/cpu/utilization"' // const filter = 'metric.type="compute.googleapis.com/instance/cpu/utilization"'; const request = { @@ -284,9 +290,11 @@ function readTimeSeriesFields (projectId) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; const request = { @@ -328,9 +336,11 @@ function readTimeSeriesAggregate (projectId) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; const request = { @@ -378,9 +388,11 @@ function readTimeSeriesReduce (projectId) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; const request = { @@ -426,9 +438,11 @@ function listMonitoredResourceDescriptors (projectId) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; const request = { @@ -441,7 +455,21 @@ function listMonitoredResourceDescriptors (projectId) { const descriptors = results[0]; console.log('Monitored Resource Descriptors:'); - descriptors.forEach((descriptor) => console.log(descriptor.name)); + descriptors.forEach((descriptor) => { + if (descriptor.type === 'uptime_url') { + console.log(JSON.stringify(descriptor, null, 2)); + } else { + return; + } + console.log(descriptor.name); + console.log(` Type: ${descriptor.type}`); + if (descriptor.labels) { + console.log(` Labels:`); + descriptor.labels.forEach((label) => { + console.log(` ${label.key} (${label.valueType}): ${label.description}`); + }); + } + }); }) .catch((err) => { console.error('ERROR:', err); @@ -455,13 +483,13 @@ function getMonitoredResourceDescriptor (projectId, resourceType) { const Monitoring = require('@google-cloud/monitoring'); // Creates a client - const client = Monitoring.v3.metric(); + const client = Monitoring.metric(); - // The Google Cloud Platform project on which to execute the request + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ // const projectId = 'YOUR_PROJECT_ID'; - - // "resourceType" should be a predefined type, such as "cloudsql_database" - // const resourceType = 'some_resource_type'; + // const resourceType = 'some_resource_type, e.g. cloudsql_database'; const request = { name: client.monitoredResourceDescriptorPath(projectId, resourceType) diff --git a/monitoring/package.json b/monitoring/package.json index a69f0dd5b6..f1278f12b5 100644 --- a/monitoring/package.json +++ b/monitoring/package.json @@ -21,10 +21,10 @@ "yargs": "9.0.1" }, "devDependencies": { - "@google-cloud/nodejs-repo-tools": "2.0.4", + "@google-cloud/nodejs-repo-tools": "2.0.9", "ava": "0.22.0", "proxyquire": "1.8.0", - "sinon": "4.0.0" + "sinon": "4.0.1" }, "cloud-repo-tools": { "requiresKeyFile": true, @@ -37,6 +37,13 @@ "file": "metrics.js", "docs_link": "https://cloud.google.com/monitoring/docs", "usage": "node metrics.js --help" + }, + { + "id": "uptime", + "name": "Uptime Config", + "file": "uptime.js", + "docs_link": "https://cloud.google.com/monitoring/docs", + "usage": "node uptime.js --help" } ] } diff --git a/monitoring/system-test/metrics.test.js b/monitoring/system-test/metrics.test.js index 5b534209a9..614f1bcef6 100644 --- a/monitoring/system-test/metrics.test.js +++ b/monitoring/system-test/metrics.test.js @@ -15,7 +15,7 @@ 'use strict'; -const client = require(`@google-cloud/monitoring`).v3.metric(); +const client = require(`@google-cloud/monitoring`).metric(); const path = require(`path`); const test = require(`ava`); const tools = require(`@google-cloud/nodejs-repo-tools`); diff --git a/monitoring/system-test/quickstart.test.js b/monitoring/system-test/quickstart.test.js index 4386d412e7..47502637d1 100644 --- a/monitoring/system-test/quickstart.test.js +++ b/monitoring/system-test/quickstart.test.js @@ -20,7 +20,7 @@ const sinon = require(`sinon`); const test = require(`ava`); const tools = require(`@google-cloud/nodejs-repo-tools`); -const client = proxyquire(`@google-cloud/monitoring`, {}).v3.metric(); +const client = proxyquire(`@google-cloud/monitoring`, {}).metric(); test.beforeEach(tools.stubConsole); test.afterEach.always(tools.restoreConsole); diff --git a/monitoring/system-test/uptime.test.js b/monitoring/system-test/uptime.test.js new file mode 100644 index 0000000000..35f7f8001a --- /dev/null +++ b/monitoring/system-test/uptime.test.js @@ -0,0 +1,69 @@ +/** + * Copyright 2017, 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. + */ + +'use strict'; + +const client = require(`@google-cloud/monitoring`).uptimeCheck(); +const path = require(`path`); +const test = require(`ava`); +const tools = require(`@google-cloud/nodejs-repo-tools`); + +const cmd = `node uptime.js`; +const cwd = path.join(__dirname, `..`); +const projectId = process.env.GCLOUD_PROJECT; +const instanceId = 'uptime-test-' + Date.now(); + +test.before(tools.checkCredentials); + +test(`should get an uptime check`, async (t) => { + t.regex(await tools.runAsync(`${cmd} list-ips`, cwd), /USA/); +}); + +let id; + +test.serial(`should create an uptime check`, async (t) => { + const results = await tools.runAsyncWithIO(`${cmd} create ${instanceId}`, cwd); + const output = results.stdout + results.stderr; + const matches = output.match(new RegExp(`ID: projects/${projectId}/uptimeCheckConfigs/(.+)`)); + id = matches[1]; + t.regex(output, /Uptime check created:/); + t.regex(output, new RegExp(`Resource: {"type":"gce_instance","labels":{"instance_id":"${instanceId}"}}`)); + t.regex(output, /Display Name: My GCE Instance Uptime Check/); +}); + +test.serial(`should get an uptime check`, async (t) => { + const results = await tools.runAsyncWithIO(`${cmd} get ${id}`, cwd); + const output = results.stdout + results.stderr; + t.regex(output, new RegExp(`Retrieving projects/${projectId}/uptimeCheckConfigs/${id}`)); + t.regex(output, new RegExp(`Resource: {"type":"gce_instance","labels":{"instance_id":"${instanceId}"}}`)); +}); + +test.serial(`should list uptime checks`, async (t) => { + t.plan(0); + await tools.tryTest(async (assert) => { + const results = await tools.runAsyncWithIO(`${cmd} list`, cwd); + const output = results.stdout + results.stderr; + assert((new RegExp(`Resource: {"type":"gce_instance","labels":{"instance_id":"${instanceId}"}}`)).test(output)); + assert(/Display Name: My GCE Instance Uptime Check/.test(output)); + }).start(); +}); + +test.serial(`should delete an uptime check`, async (t) => { + const results = await tools.runAsyncWithIO(`${cmd} delete ${id}`, cwd); + const output = results.stdout + results.stderr; + t.regex(output, new RegExp(`Deleting projects/${projectId}/uptimeCheckConfigs/${id}`)); + t.regex(output, new RegExp(`projects/${projectId}/uptimeCheckConfigs/${id} deleted.`)); +}); + diff --git a/monitoring/uptime.js b/monitoring/uptime.js new file mode 100644 index 0000000000..e8a687e2c8 --- /dev/null +++ b/monitoring/uptime.js @@ -0,0 +1,266 @@ +/** + * Copyright 2017, 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. + */ + +/** + * This application demonstrates how to perform basic operations on uptime check + * configs with the Google Stackdriver Monitoring API. + * + * For more information, see the README.md under /monitoring and the + * documentation at https://cloud.google.com/monitoring/uptime-checks/. + */ + +'use strict'; + +function createUptimeCheckConfig (projectId, gceInstanceId) { + // [START monitoring_uptime_check_create] + // Imports the Google Cloud client library + const Monitoring = require('@google-cloud/monitoring'); + + // Creates a client + const client = Monitoring.uptimeCheck(); + + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ + // const projectId = 'YOUR_PROJECT_ID'; + // const gceInstanceId = 'my-instance'; + + const request = { + // i.e. parent: 'projects/my-project-id' + parent: client.projectPath(projectId), + uptimeCheckConfig: { + displayName: 'My GCE Instance Uptime Check', + resource: { + // See the Uptime Check docs for supported MonitoredResource types + type: 'gce_instance', + labels: { instance_id: gceInstanceId } + }, + httpCheck: { path: '/', port: 80 }, + timeout: { seconds: 10 }, + period: { seconds: 300 } + } + }; + + // Creates an uptime check config for a GCE instance + client.createUptimeCheckConfig(request) + .then((results) => { + const uptimeCheckConfig = results[0]; + + console.log('Uptime check created:'); + console.log(`ID: ${uptimeCheckConfig.name}`); + console.log(`Display Name: ${uptimeCheckConfig.displayName}`); + console.log(`Resource: %j`, uptimeCheckConfig.resource); + console.log(`Period: %j`, uptimeCheckConfig.period); + console.log(`Timeout: %j`, uptimeCheckConfig.timeout); + console.log(`Check type: ${uptimeCheckConfig.check_request_type}`); + console.log(`Check: %j`, uptimeCheckConfig.httpCheck || uptimeCheckConfig.tcpCheck); + console.log(`Content matchers: ${uptimeCheckConfig.contentMatchers.map((matcher) => matcher.content).join(', ')}`); + console.log(`Regions: ${uptimeCheckConfig.selectedRegions.join(', ')}`); + }) + .catch((err) => { + console.error('ERROR:', err); + }); + // [END monitoring_uptime_check_create] +} + +function listUptimeCheckConfigs (projectId) { + // [START monitoring_uptime_check_list_configs] + // Imports the Google Cloud client library + const Monitoring = require('@google-cloud/monitoring'); + + // Creates a client + const client = Monitoring.uptimeCheck(); + + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ + // const projectId = 'YOUR_PROJECT_ID'; + + const request = { + parent: client.projectPath(projectId) + }; + + // Retrieves an uptime check config + client.listUptimeCheckConfigs(request) + .then((results) => { + const uptimeCheckConfigs = results[0]; + + uptimeCheckConfigs.forEach((uptimeCheckConfig) => { + console.log(`ID: ${uptimeCheckConfig.name}`); + console.log(` Display Name: ${uptimeCheckConfig.displayName}`); + console.log(` Resource: %j`, uptimeCheckConfig.resource); + console.log(` Period: %j`, uptimeCheckConfig.period); + console.log(` Timeout: %j`, uptimeCheckConfig.timeout); + console.log(` Check type: ${uptimeCheckConfig.check_request_type}`); + console.log(` Check: %j`, uptimeCheckConfig.httpCheck || uptimeCheckConfig.tcpCheck); + console.log(` Content matchers: ${uptimeCheckConfig.contentMatchers.map((matcher) => matcher.content).join(', ')}`); + console.log(` Regions: ${uptimeCheckConfig.selectedRegions.join(', ')}`); + }); + }) + .catch((err) => { + console.error('ERROR:', err); + }); + // [END monitoring_uptime_check_list_configs] +} + +function listUptimeCheckIps () { + // [START monitoring_uptime_check_list_ips] + // Imports the Google Cloud client library + const Monitoring = require('@google-cloud/monitoring'); + + // Creates a client + const client = Monitoring.uptimeCheck(); + + // List uptime check IPs + client.listUptimeCheckIps() + .then((results) => { + const uptimeCheckIps = results[0]; + uptimeCheckIps.forEach((uptimeCheckIp) => { + console.log(uptimeCheckIp.region, uptimeCheckIp.location, uptimeCheckIp.ipAddress); + }); + }) + .catch((err) => { + console.error('ERROR:', err); + }); + // [END monitoring_uptime_check_list_ips] +} + +function getUptimeCheckConfig (projectId, uptimeCheckConfigId) { + // [START monitoring_uptime_check_get] + // Imports the Google Cloud client library + const Monitoring = require('@google-cloud/monitoring'); + + // Creates a client + const client = Monitoring.uptimeCheck(); + + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ + // const projectId = 'YOUR_PROJECT_ID'; + // const uptimeCheckConfigId = 'YOUR_UPTIME_CHECK_CONFIG_ID'; + + const request = { + // i.e. name: 'projects/my-project-id/uptimeCheckConfigs/My-Uptime-Check + name: client.uptimeCheckConfigPath(projectId, uptimeCheckConfigId) + }; + + console.log(`Retrieving ${request.name}`); + + // Retrieves an uptime check config + client.getUptimeCheckConfig(request) + .then((results) => { + const uptimeCheckConfig = results[0]; + + console.log(`ID: ${uptimeCheckConfig.name}`); + console.log(`Display Name: ${uptimeCheckConfig.displayName}`); + console.log(`Resource: %j`, uptimeCheckConfig.resource); + console.log(`Period: %j`, uptimeCheckConfig.period); + console.log(`Timeout: %j`, uptimeCheckConfig.timeout); + console.log(`Check type: ${uptimeCheckConfig.check_request_type}`); + console.log(`Check: %j`, uptimeCheckConfig.httpCheck || uptimeCheckConfig.tcpCheck); + console.log(`Content matchers: ${uptimeCheckConfig.contentMatchers.map((matcher) => matcher.content).join(', ')}`); + console.log(`Regions: ${uptimeCheckConfig.selectedRegions.join(', ')}`); + }) + .catch((err) => { + console.error('ERROR:', err); + }); + // [END monitoring_uptime_check_get] +} + +function deleteUptimeCheckConfig (projectId, uptimeCheckConfigId) { + // [START monitoring_uptime_check_delete] + // Imports the Google Cloud client library + const Monitoring = require('@google-cloud/monitoring'); + + // Creates a client + const client = Monitoring.uptimeCheck(); + + /** + * TODO(developer): Uncomment and edit the following lines of code. + */ + // const projectId = 'YOUR_PROJECT_ID'; + // const uptimeCheckConfigId = 'YOUR_UPTIME_CHECK_CONFIG_ID'; + + const request = { + // i.e. name: 'projects/my-project-id/uptimeCheckConfigs/My-Uptime-Check + name: client.uptimeCheckConfigPath(projectId, uptimeCheckConfigId) + }; + + console.log(`Deleting ${request.name}`); + + // Delete an uptime check config + client.deleteUptimeCheckConfig(request) + .then(() => { + console.log(`${request.name} deleted.`); + }) + .catch((err) => { + console.error('ERROR:', err); + }); + // [END monitoring_uptime_check_delete] +} + +require(`yargs`) + .demand(1) + .command( + `create [projectId]`, + `Creates an uptime check config.`, + {}, + (opts) => createUptimeCheckConfig(opts.projectId, '' + opts.gceInstanceId) + ) + .command( + `list [projectId]`, + `Lists uptime check configs.`, + {}, + (opts) => listUptimeCheckConfigs(opts.projectId) + ) + .command( + `list-ips`, + `Lists uptime check config IPs.`, + {}, + (opts) => listUptimeCheckIps() + ) + .command( + `get [projectId]`, + `Gets an uptime check config.`, + {}, + (opts) => getUptimeCheckConfig(opts.projectId, opts.uptimeCheckConfigId) + ) + .command( + `delete [projectId]`, + `Deletes an uptime check config.`, + {}, + (opts) => deleteUptimeCheckConfig(opts.projectId, opts.uptimeCheckConfigId) + ) + .options({ + projectId: { + alias: 'p', + default: process.env.GCLOUD_PROJECT, + global: true, + requiresArg: true, + type: 'string' + } + }) + .example(`node $0 create my-instance`, 'Create an uptime check for a "my-instance" GCE instance.') + .example(`node $0 list`, 'List all uptime check configs.') + .example(`node $0 list "resource.type = gce_instance AND resource.label.instance_id = mongodb"`, 'List all uptime check configs for a specific GCE instance.') + .example(`node $0 list-ips`) + .example(`node $0 get My-Uptime-Check`) + .example(`node $0 delete My-Uptime-Check`) + .wrap(120) + .recommendCommands() + .epilogue(`For more information, see https://cloud.google.com/monitoring/uptime-checks/`) + .help() + .strict() + .argv;