diff --git a/monitoring/snippets/alerts.js b/monitoring/snippets/alerts.js index 0c675e2209..8d95d97c08 100644 --- a/monitoring/snippets/alerts.js +++ b/monitoring/snippets/alerts.js @@ -22,7 +22,7 @@ 'use strict'; -function backupPolicies(projectId) { +async function backupPolicies(projectId) { // [START monitoring_alert_backup_policies] const fs = require('fs'); @@ -41,26 +41,19 @@ function backupPolicies(projectId) { name: client.projectPath(projectId), }; - client - .listAlertPolicies(listAlertPoliciesRequest) - .then(results => { - const policies = results[0]; - - fs.writeFileSync( - './policies_backup.json', - JSON.stringify(policies, null, 2), - 'utf-8' - ); - - console.log('Saved policies to ./policies_backup.json'); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [policies] = await client.listAlertPolicies(listAlertPoliciesRequest); + + fs.writeFileSync( + './policies_backup.json', + JSON.stringify(policies, null, 2), + 'utf-8' + ); + + console.log('Saved policies to ./policies_backup.json'); // [END monitoring_alert_backup_policies] } -function restorePolicies(projectId) { +async function restorePolicies(projectId) { // Note: The policies are restored one at a time because I get 'service // unavailable' when I try to create multiple alerts simultaneously. // [START monitoring_alert_restore_policies] @@ -82,55 +75,43 @@ function restorePolicies(projectId) { const fileContent = fs.readFileSync('./policies_backup.json', 'utf-8'); const policies = JSON.parse(fileContent); - let promise = Promise.resolve(); - - policies.forEach(policy => { + for (const index in policies) { // Restore each policy one at a time - promise = promise - .then(() => doesAlertPolicyExist(policy.name)) - .then(exists => { - if (exists) { - return client.updateAlertPolicy({alertPolicy: policy}); - } - - // Clear away output-only fields - delete policy.name; - delete policy.creationRecord; - delete policy.mutationRecord; - policy.conditions.forEach(condition => delete condition.name); - - return client.createAlertPolicy({ - name: client.projectPath(projectId), - alertPolicy: policy, - }); - }) - .then(response => { - const policy = response[0]; - console.log(`Restored ${policy.name}.`); + let policy = policies[index]; + if (await doesAlertPolicyExist(policy.name)) { + policy = await client.updateAlertPolicy({alertPolicy: policy}); + } else { + // Clear away output-only fields + delete policy.name; + delete policy.creationRecord; + delete policy.mutationRecord; + policy.conditions.forEach(condition => delete condition.name); + + policy = await client.createAlertPolicy({ + name: client.projectPath(projectId), + alertPolicy: policy, }); - }); - - promise.catch(err => { - console.error('ERROR:', err); - }); + } - function doesAlertPolicyExist(name) { - return client - .getAlertPolicy({name: name}) - .then(() => true) - .catch(err => { - if (err && err.code === 5) { - // Error code 5 comes from the google.rpc.code.NOT_FOUND protobuf - return false; - } - return Promise.reject(err); - }); + console.log(`Restored ${policy[0].name}.`); + } + async function doesAlertPolicyExist(name) { + try { + const [policy] = await client.getAlertPolicy({name}); + return policy ? true : false; + } catch (err) { + if (err && err.code === 5) { + // Error code 5 comes from the google.rpc.code.NOT_FOUND protobuf + return false; + } + throw err; + } } // [END monitoring_alert_create_policy] // [END monitoring_alert_restore_policies] } -function replaceChannels(projectId, alertPolicyId, channelIds) { +async function replaceChannels(projectId, alertPolicyId, channelIds) { // [START monitoring_alert_replace_channels] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -161,20 +142,14 @@ function replaceChannels(projectId, alertPolicyId, channelIds) { notificationChannels: notificationChannels, }, }; - - alertClient - .updateAlertPolicy(updateAlertPolicyRequest) - .then(results => { - const alertPolicy = results[0]; - console.log(`Updated ${alertPolicy.name}.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [alertPolicy] = await alertClient.updateAlertPolicy( + updateAlertPolicyRequest + ); + console.log(`Updated ${alertPolicy.name}.`); // [END monitoring_alert_replace_channels] } -function enablePolicies(projectId, enabled, filter) { +async function enablePolicies(projectId, enabled, filter) { // [START monitoring_alert_enable_policies] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -195,41 +170,30 @@ function enablePolicies(projectId, enabled, filter) { filter: filter, }; - client - .listAlertPolicies(listAlertPoliciesRequest) - .then(results => { - const policies = results[0]; - - const tasks = policies - .map(policy => { - return { - updateMask: {paths: ['disabled']}, - alertPolicy: { - name: policy.name, - disabled: enabled ? false : true, - }, - }; - }) - .map(updateAlertPolicyRequest => - client.updateAlertPolicy(updateAlertPolicyRequest) - ); - - // Wait for all policies to be enabled - return Promise.all(tasks); - }) - .then(responses => { - responses.forEach(response => { - const alertPolicy = response[0]; - console.log(`${enabled ? 'Enabled' : 'Disabled'} ${alertPolicy.name}.`); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [policies] = await client.listAlertPolicies(listAlertPoliciesRequest); + const tasks = await Promise.all( + policies + .map(policy => { + return { + updateMask: {paths: ['disabled']}, + alertPolicy: { + name: policy.name, + disabled: enabled ? false : true, + }, + }; + }) + .map(updateAlertPolicyRequest => + client.updateAlertPolicy(updateAlertPolicyRequest) + ) + ); + tasks.forEach(response => { + const alertPolicy = response[0]; + console.log(`${enabled ? 'Enabled' : 'Disabled'} ${alertPolicy.name}.`); + }); // [END monitoring_alert_enable_policies] } -function listPolicies(projectId) { +async function listPolicies(projectId) { // [START monitoring_alert_list_policies] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -245,23 +209,15 @@ function listPolicies(projectId) { const listAlertPoliciesRequest = { name: client.projectPath(projectId), }; + const [policies] = await client.listAlertPolicies(listAlertPoliciesRequest); + console.log('Policies:'); + policies.forEach(policy => { + console.log(` Display name: ${policy.displayName}`); + if (policy.documentation && policy.documentation.content) { + console.log(` Documentation: ${policy.documentation.content}`); + } + }); - client - .listAlertPolicies(listAlertPoliciesRequest) - .then(results => { - const policies = results[0]; - - console.log('Policies:'); - policies.forEach(policy => { - console.log(` Display name: ${policy.displayName}`); - if (policy.documentation && policy.documentation.content) { - console.log(` Documentation: ${policy.documentation.content}`); - } - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); // [END monitoring_alert_list_policies] } diff --git a/monitoring/snippets/metrics.js b/monitoring/snippets/metrics.js index 295e2710b6..4c3f492de5 100644 --- a/monitoring/snippets/metrics.js +++ b/monitoring/snippets/metrics.js @@ -23,7 +23,7 @@ 'use strict'; -function createMetricDescriptor(projectId) { +async function createMetricDescriptor(projectId) { // [START monitoring_create_metric] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -56,32 +56,23 @@ function createMetricDescriptor(projectId) { }; // Creates a custom metric descriptor - client - .createMetricDescriptor(request) - .then(results => { - const descriptor = results[0]; - - console.log('Created custom Metric:\n'); - console.log(`Name: ${descriptor.displayName}`); - console.log(`Description: ${descriptor.description}`); - console.log(`Type: ${descriptor.type}`); - console.log(`Kind: ${descriptor.metricKind}`); - console.log(`Value Type: ${descriptor.valueType}`); - console.log(`Unit: ${descriptor.unit}`); - console.log('Labels:'); - descriptor.labels.forEach(label => { - console.log( - ` ${label.key} (${label.valueType}) - ${label.description}` - ); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [descriptor] = await client.createMetricDescriptor(request); + console.log('Created custom Metric:\n'); + console.log(`Name: ${descriptor.displayName}`); + console.log(`Description: ${descriptor.description}`); + console.log(`Type: ${descriptor.type}`); + console.log(`Kind: ${descriptor.metricKind}`); + console.log(`Value Type: ${descriptor.valueType}`); + console.log(`Unit: ${descriptor.unit}`); + console.log('Labels:'); + descriptor.labels.forEach(label => { + console.log(` ${label.key} (${label.valueType}) - ${label.description}`); + }); + // [END monitoring_create_metric] } -function listMetricDescriptors(projectId) { +async function listMetricDescriptors(projectId) { // [START monitoring_list_descriptors] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -99,21 +90,14 @@ function listMetricDescriptors(projectId) { }; // Lists metric descriptors - client - .listMetricDescriptors(request) - .then(results => { - const descriptors = results[0]; - - console.log('Metric Descriptors:'); - descriptors.forEach(descriptor => console.log(descriptor.name)); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [descriptors] = await client.listMetricDescriptors(request); + console.log('Metric Descriptors:'); + descriptors.forEach(descriptor => console.log(descriptor.name)); + // [END monitoring_list_descriptors] } -function getMetricDescriptor(projectId, metricId) { +async function getMetricDescriptor(projectId, metricId) { // [START monitoring_get_descriptor] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -132,31 +116,21 @@ function getMetricDescriptor(projectId, metricId) { }; // Retrieves a metric descriptor - client - .getMetricDescriptor(request) - .then(results => { - const descriptor = results[0]; - - console.log(`Name: ${descriptor.displayName}`); - console.log(`Description: ${descriptor.description}`); - console.log(`Type: ${descriptor.type}`); - console.log(`Kind: ${descriptor.metricKind}`); - console.log(`Value Type: ${descriptor.valueType}`); - console.log(`Unit: ${descriptor.unit}`); - console.log('Labels:'); - descriptor.labels.forEach(label => { - console.log( - ` ${label.key} (${label.valueType}) - ${label.description}` - ); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [descriptor] = await client.getMetricDescriptor(request); + console.log(`Name: ${descriptor.displayName}`); + console.log(`Description: ${descriptor.description}`); + console.log(`Type: ${descriptor.type}`); + console.log(`Kind: ${descriptor.metricKind}`); + console.log(`Value Type: ${descriptor.valueType}`); + console.log(`Unit: ${descriptor.unit}`); + console.log('Labels:'); + descriptor.labels.forEach(label => { + console.log(` ${label.key} (${label.valueType}) - ${label.description}`); + }); // [END monitoring_get_descriptor] } -function deleteMetricDescriptor(projectId, metricId) { +async function deleteMetricDescriptor(projectId, metricId) { // [START monitoring_delete_metric] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -175,18 +149,13 @@ function deleteMetricDescriptor(projectId, metricId) { }; // Deletes a metric descriptor - client - .deleteMetricDescriptor(request) - .then(results => { - console.log(`Deleted ${metricId}`, results[0]); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.deleteMetricDescriptor(request); + console.log(`Deleted ${metricId}`, result); + // [END monitoring_delete_metric] } -function writeTimeSeriesData(projectId) { +async function writeTimeSeriesData(projectId) { // [START monitoring_write_timeseries] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -232,18 +201,13 @@ function writeTimeSeriesData(projectId) { }; // Writes time series data - client - .createTimeSeries(request) - .then(results => { - console.log(`Done writing time series data.`, results[0]); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const result = await client.createTimeSeries(request); + console.log(`Done writing time series data.`, result); + // [END monitoring_write_timeseries] } -function readTimeSeriesData(projectId, filter) { +async function readTimeSeriesData(projectId, filter) { // [START monitoring_read_timeseries_simple] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -272,25 +236,18 @@ function readTimeSeriesData(projectId, filter) { }; // Writes time series data - client - .listTimeSeries(request) - .then(results => { - const timeSeries = results[0]; - - timeSeries.forEach(data => { - console.log(`${data.metric.labels.instance_name}:`); - data.points.forEach(point => { - console.log(JSON.stringify(point.value)); - }); - }); - }) - .catch(err => { - console.error('ERROR:', err); + const [timeSeries] = await client.listTimeSeries(request); + timeSeries.forEach(data => { + console.log(`${data.metric.labels.instance_name}:`); + data.points.forEach(point => { + console.log(JSON.stringify(point.value)); }); + }); + // [END monitoring_read_timeseries_simple] } -function readTimeSeriesFields(projectId) { +async function readTimeSeriesFields(projectId) { // [START monitoring_read_timeseries_fields] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -321,23 +278,16 @@ function readTimeSeriesFields(projectId) { }; // Writes time series data - client - .listTimeSeries(request) - .then(results => { - const timeSeries = results[0]; - - console.log('Found data points for the following instances:'); - timeSeries.forEach(data => { - console.log(data.metric.labels.instance_name); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [timeSeries] = await client.listTimeSeries(request); + console.log('Found data points for the following instances:'); + timeSeries.forEach(data => { + console.log(data.metric.labels.instance_name); + }); + // [END monitoring_read_timeseries_fields] } -function readTimeSeriesAggregate(projectId) { +async function readTimeSeriesAggregate(projectId) { // [START monitoring_read_timeseries_align] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -372,25 +322,17 @@ function readTimeSeriesAggregate(projectId) { }; // Writes time series data - client - .listTimeSeries(request) - .then(results => { - const timeSeries = results[0]; - - console.log('CPU utilization:'); - timeSeries.forEach(data => { - console.log(data.metric.labels.instance_name); - console.log(` Now: ${data.points[0].value.doubleValue}`); - console.log(` 10 min ago: ${data.points[1].value.doubleValue}`); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [timeSeries] = await client.listTimeSeries(request); + console.log('CPU utilization:'); + timeSeries.forEach(data => { + console.log(data.metric.labels.instance_name); + console.log(` Now: ${data.points[0].value.doubleValue}`); + console.log(` 10 min ago: ${data.points[1].value.doubleValue}`); + }); // [END monitoring_read_timeseries_align] } -function readTimeSeriesReduce(projectId) { +async function readTimeSeriesReduce(projectId) { // [START monitoring_read_timeseries_reduce] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -426,26 +368,21 @@ function readTimeSeriesReduce(projectId) { }; // Writes time series data - client - .listTimeSeries(request) - .then(results => { - if (results[0].length === 0) { - console.log('No data'); - return; - } - const reductions = results[0][0].points; - - console.log('Average CPU utilization across all GCE instances:'); - console.log(` Last 10 min: ${reductions[0].value.doubleValue}`); - console.log(` 10-20 min ago: ${reductions[0].value.doubleValue}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [result] = await client.listTimeSeries(request); + if (result.length === 0) { + console.log('No data'); + return; + } + const reductions = result[0].points; + + console.log('Average CPU utilization across all GCE instances:'); + console.log(` Last 10 min: ${reductions[0].value.doubleValue}`); + console.log(` 10-20 min ago: ${reductions[0].value.doubleValue}`); + // [END monitoring_read_timeseries_reduce] } -function listMonitoredResourceDescriptors(projectId) { +async function listMonitoredResourceDescriptors(projectId) { // [START monitoring_list_resources] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -463,33 +400,26 @@ function listMonitoredResourceDescriptors(projectId) { }; // Lists monitored resource descriptors - client - .listMonitoredResourceDescriptors(request) - .then(results => { - const descriptors = results[0]; - - console.log('Monitored Resource Descriptors:'); - descriptors.forEach(descriptor => { - 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}` - ); - }); - } - console.log(); + const [descriptors] = await client.listMonitoredResourceDescriptors(request); + console.log('Monitored Resource Descriptors:'); + descriptors.forEach(descriptor => { + 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); - }); + } + console.log(); + }); + // [END monitoring_list_resources] } -function getMonitoredResourceDescriptor(projectId, resourceType) { +async function getMonitoredResourceDescriptor(projectId, resourceType) { // [START monitoring_get_resource] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -508,24 +438,15 @@ function getMonitoredResourceDescriptor(projectId, resourceType) { }; // Lists monitored resource descriptors - client - .getMonitoredResourceDescriptor(request) - .then(results => { - const descriptor = results[0]; - - console.log(`Name: ${descriptor.displayName}`); - console.log(`Description: ${descriptor.description}`); - console.log(`Type: ${descriptor.type}`); - console.log('Labels:'); - descriptor.labels.forEach(label => { - console.log( - ` ${label.key} (${label.valueType}) - ${label.description}` - ); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [descriptor] = await client.getMonitoredResourceDescriptor(request); + + console.log(`Name: ${descriptor.displayName}`); + console.log(`Description: ${descriptor.description}`); + console.log(`Type: ${descriptor.type}`); + console.log('Labels:'); + descriptor.labels.forEach(label => { + console.log(` ${label.key} (${label.valueType}) - ${label.description}`); + }); // [END monitoring_get_resource] } diff --git a/monitoring/snippets/package.json b/monitoring/snippets/package.json index 7c4b0e85a6..11c7c8352f 100644 --- a/monitoring/snippets/package.json +++ b/monitoring/snippets/package.json @@ -10,7 +10,7 @@ "node": ">=8" }, "scripts": { - "test": "ava -T 3m --verbose system-test/*.test.js" + "test": "mocha system-test/*.js --timeout 600000" }, "dependencies": { "@google-cloud/monitoring": "^0.6.0", @@ -18,7 +18,7 @@ }, "devDependencies": { "@google-cloud/nodejs-repo-tools": "^3.0.0", - "ava": "^0.25.0", + "mocha": "^5.0.0", "proxyquire": "^2.0.1", "sinon": "^7.0.0" } diff --git a/monitoring/snippets/quickstart.js b/monitoring/snippets/quickstart.js index 31c0e6a9bc..fbd123c872 100644 --- a/monitoring/snippets/quickstart.js +++ b/monitoring/snippets/quickstart.js @@ -18,56 +18,53 @@ // [START monitoring_quickstart] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); +async function quickStart() { + // Your Google Cloud Platform project ID + const projectId = 'YOUR_PROJECT_ID'; -// Your Google Cloud Platform project ID -const projectId = 'YOUR_PROJECT_ID'; + // Creates a client + const client = new monitoring.MetricServiceClient(); -// Creates a client -const client = new monitoring.MetricServiceClient(); - -// Prepares an individual data point -const dataPoint = { - interval: { - endTime: { - seconds: Date.now() / 1000, + // Prepares an individual data point + const dataPoint = { + interval: { + endTime: { + seconds: Date.now() / 1000, + }, + }, + value: { + // The amount of sales + doubleValue: 123.45, }, - }, - value: { - // The amount of sales - doubleValue: 123.45, - }, -}; + }; -// Prepares the time series request -const request = { - name: client.projectPath(projectId), - timeSeries: [ - { - // Ties the data point to a custom metric - metric: { - type: 'custom.googleapis.com/stores/daily_sales', - labels: { - store_id: 'Pittsburgh', + // Prepares the time series request + const request = { + name: client.projectPath(projectId), + timeSeries: [ + { + // Ties the data point to a custom metric + metric: { + type: 'custom.googleapis.com/stores/daily_sales', + labels: { + store_id: 'Pittsburgh', + }, }, - }, - resource: { - type: 'global', - labels: { - project_id: projectId, + resource: { + type: 'global', + labels: { + project_id: projectId, + }, }, + points: [dataPoint], }, - points: [dataPoint], - }, - ], -}; + ], + }; + + // Writes time series data + const [result] = await client.createTimeSeries(request); + console.log(`Done writing time series data.`, result); +} -// Writes time series data -client - .createTimeSeries(request) - .then(results => { - console.log(`Done writing time series data.`, results[0]); - }) - .catch(err => { - console.error('ERROR:', err); - }); +quickStart().catch(console.error); // [END monitoring_quickstart] diff --git a/monitoring/snippets/system-test/.eslintrc.yml b/monitoring/snippets/system-test/.eslintrc.yml new file mode 100644 index 0000000000..752164361d --- /dev/null +++ b/monitoring/snippets/system-test/.eslintrc.yml @@ -0,0 +1,7 @@ +--- +env: + mocha: true +rules: + node/no-unpublished-require: off + node/no-unsupported-features: off + no-empty: off diff --git a/monitoring/snippets/system-test/alerts.test.js b/monitoring/snippets/system-test/alerts.test.js index 2bccccbe4d..71acae0841 100644 --- a/monitoring/snippets/system-test/alerts.test.js +++ b/monitoring/snippets/system-test/alerts.test.js @@ -18,7 +18,7 @@ const fs = require(`fs`); const monitoring = require(`@google-cloud/monitoring`); const path = require(`path`); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const client = new monitoring.AlertPolicyServiceClient(); @@ -28,179 +28,187 @@ const projectId = process.env.GCLOUD_PROJECT; let policyOneName, policyTwoName, channelName; -test.before(tools.checkCredentials); +before(tools.checkCredentials); -test.before(async () => { - let results = await client.createAlertPolicy({ - name: client.projectPath(projectId), - alertPolicy: { - displayName: 'first_policy', - combiner: 1, - documentation: { - content: 'Test', - mimeType: 'text/markdown', - }, - conditions: [ - { - displayName: 'Condition 1', - conditionAbsent: { - filter: `resource.type = "cloud_function" AND metric.type = "cloudfunctions.googleapis.com/function/execution_count"`, - aggregations: [ - { - alignmentPeriod: { - seconds: 60, +before(async () => { + try { + tools.checkCredentials; + let results = await client.createAlertPolicy({ + name: client.projectPath(projectId), + alertPolicy: { + displayName: 'first_policy', + combiner: 1, + documentation: { + content: 'Test', + mimeType: 'text/markdown', + }, + conditions: [ + { + displayName: 'Condition 1', + conditionAbsent: { + filter: `resource.type = "cloud_function" AND metric.type = "cloudfunctions.googleapis.com/function/execution_count"`, + aggregations: [ + { + alignmentPeriod: { + seconds: 60, + }, + perSeriesAligner: 1, + crossSeriesReducer: 0, }, - perSeriesAligner: 1, - crossSeriesReducer: 0, + ], + duration: { + seconds: 120, + }, + trigger: { + count: 1, }, - ], - duration: { - seconds: 120, - }, - trigger: { - count: 1, }, }, - }, - ], - }, - }); - policyOneName = results[0].name; - results = await client.createAlertPolicy({ - name: client.projectPath(projectId), - alertPolicy: { - displayName: 'second', - combiner: 1, - conditions: [ - { - displayName: 'Condition 2', - conditionAbsent: { - filter: `resource.type = "cloud_function" AND metric.type = "cloudfunctions.googleapis.com/function/execution_count"`, - aggregations: [ - { - alignmentPeriod: { - seconds: 60, + ], + }, + }); + policyOneName = results[0].name; + results = await client.createAlertPolicy({ + name: client.projectPath(projectId), + alertPolicy: { + displayName: 'second', + combiner: 1, + conditions: [ + { + displayName: 'Condition 2', + conditionAbsent: { + filter: `resource.type = "cloud_function" AND metric.type = "cloudfunctions.googleapis.com/function/execution_count"`, + aggregations: [ + { + alignmentPeriod: { + seconds: 60, + }, + perSeriesAligner: 1, + crossSeriesReducer: 0, }, - perSeriesAligner: 1, - crossSeriesReducer: 0, + ], + duration: { + seconds: 120, + }, + trigger: { + count: 1, }, - ], - duration: { - seconds: 120, - }, - trigger: { - count: 1, }, }, + ], + }, + }); + policyTwoName = results[0].name; + results = await channelClient.createNotificationChannel({ + name: channelClient.projectPath(projectId), + notificationChannel: { + displayName: 'Channel 1', + type: 'email', + labels: { + email_address: 'test@test.com', }, - ], - }, - }); - policyTwoName = results[0].name; - results = await channelClient.createNotificationChannel({ - name: channelClient.projectPath(projectId), - notificationChannel: { - displayName: 'Channel 1', - type: 'email', - labels: { - email_address: 'test@test.com', }, - }, - }); - channelName = results[0].name; + }); + channelName = results[0].name; + } catch (err) {} // ignore error }); -function deletePolicies() { - return Promise.all([ - client.deleteAlertPolicy({ - name: policyOneName, - }), - client.deleteAlertPolicy({ - name: policyTwoName, - }), - ]); +async function deletePolicies() { + await client.deleteAlertPolicy({ + name: policyOneName, + }); + await client.deleteAlertPolicy({ + name: policyTwoName, + }); } -function deleteChannels() { - return Promise.all([ - channelClient.deleteNotificationChannel({ - name: channelName, - }), - ]); +async function deleteChannels() { + await channelClient.deleteNotificationChannel({ + name: channelName, + }); } -test.after.always(async () => { +after(async () => { await deletePolicies(); // has to be done after policies are deleted await deleteChannels(); }); -test.serial(`should replace notification channels`, async t => { +it(`should replace notification channels`, async () => { const results = await tools.spawnAsyncWithIO( `node`, [`alerts.js`, `replace`, policyOneName, channelName], cwd ); - t.regex(results.output, /Updated projects\//); - t.true(results.output.includes(policyOneName)); + assert.strictEqual(results.output.includes('Updated projects'), true); + assert.strictEqual(results.output.includes(policyOneName), true); }); -test.serial(`should disable policies`, async t => { +it(`should disable policies`, async () => { const results = await tools.spawnAsyncWithIO( `node`, [`alerts.js`, `disable`, projectId, `'display_name.size < 7'`], cwd ); - t.regex(results.output, /Disabled projects\//); - t.false(results.output.includes(policyOneName)); - t.true(results.output.includes(policyTwoName)); + assert.strictEqual(results.output.includes('Disabled projects'), true); + assert.strictEqual(results.output.includes(policyOneName), false); + assert.strictEqual(results.output.includes(policyTwoName), true); }); -test.serial(`should enable policies`, async t => { +it(`should enable policies`, async () => { const results = await tools.spawnAsyncWithIO( `node`, [`alerts.js`, `enable`, projectId, `'display_name.size < 7'`], cwd ); - t.regex(results.output, /Enabled projects\//); - t.false(results.output.includes(policyOneName)); - t.true(results.output.includes(policyTwoName)); + assert.strictEqual(results.output.includes('Enabled projects'), true); + assert.strictEqual(results.output.includes(policyOneName), false); + assert.strictEqual(results.output.includes(policyTwoName), true); }); -test.serial(`should list policies`, async t => { +it(`should list policies`, async () => { const results = await tools.spawnAsyncWithIO( `node`, [`alerts.js`, `list`, projectId], cwd ); - t.regex(results.output, /Policies:/); - t.true(results.output.includes('first_policy')); - t.true(results.output.includes('Test')); - t.true(results.output.includes('second')); + assert.strictEqual(results.output.includes('Policies:'), true); + assert.strictEqual(results.output.includes('first_policy'), true); + assert.strictEqual(results.output.includes('Test'), true); + assert.strictEqual(results.output.includes('second'), true); }); -test.serial(`should backup all policies`, async t => { +it(`should backup all policies`, async () => { const results = await tools.spawnAsyncWithIO( `node`, [`alerts.js`, `backup`, projectId], cwd ); - t.regex(results.output, /Saved policies to \.\/policies_backup.json/); - t.true(fs.existsSync(path.join(cwd, `policies_backup.json`))); + assert.strictEqual( + results.output.includes('Saved policies to ./policies_backup.json'), + true + ); + assert.strictEqual( + fs.existsSync(path.join(cwd, `policies_backup.json`)), + true + ); await client.deleteAlertPolicy({name: policyOneName}); }); -test.serial(`should restore policies`, async t => { +it(`should restore policies`, async () => { const results = await tools.spawnAsyncWithIO( `node`, [`alerts.js`, `restore`, projectId], cwd ); - t.regex(results.output, /Loading policies from .\/policies_backup.json/); + assert.strictEqual( + results.output.includes('Loading policies from ./policies_backup.json'), + true + ); const nameRegexp = /projects\/[A-Za-z0-9-]+\/alertPolicies\/([\d]+)/gi; const matches = results.output.match(nameRegexp); - t.true(Array.isArray(matches)); - t.is(matches.length, 2); + assert.strictEqual(Array.isArray(matches), true); + assert.strictEqual(matches.length, 2); policyOneName = matches[0]; policyTwoName = matches[1]; }); diff --git a/monitoring/snippets/system-test/metrics.test.js b/monitoring/snippets/system-test/metrics.test.js index dbec6c3444..f74fffcae1 100644 --- a/monitoring/snippets/system-test/metrics.test.js +++ b/monitoring/snippets/system-test/metrics.test.js @@ -18,7 +18,7 @@ const monitoring = require(`@google-cloud/monitoring`); const client = new monitoring.MetricServiceClient(); const path = require(`path`); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const cmd = `node metrics.js`; @@ -29,31 +29,26 @@ const filter = `metric.type="${computeMetricId}"`; const projectId = process.env.GCLOUD_PROJECT; const resourceId = `cloudsql_database`; -test.before(tools.checkCredentials); +before(tools.checkCredentials); -test.serial(`should create a metric descriptors`, async t => { +it(`should create a metric descriptors`, async () => { const output = await tools.runAsync(`${cmd} create`, cwd); - t.true(output.includes(`Created custom Metric`)); - t.true(output.includes(`Type: ${customMetricId}`)); + assert.strictEqual(output.includes(`Created custom Metric`), true); + assert.strictEqual(output.includes(`Type: ${customMetricId}`), true); }); -test.serial( - `should list metric descriptors, including the new custom one`, - async t => { - t.plan(0); - const attempt = tools.tryTest(async assert => { - const output = await tools.runAsync(`${cmd} list`, cwd); - assert(output.includes(customMetricId)); - assert(output.includes(computeMetricId)); - }); - attempt.tries(30); - attempt.timeout(120000); - await attempt.start(); - } -); +it(`should list metric descriptors, including the new custom one`, async () => { + const attempt = tools.tryTest(async assert => { + const output = await tools.runAsync(`${cmd} list`, cwd); + assert(output.includes(customMetricId)); + assert(output.includes(computeMetricId)); + }); + attempt.tries(30); + attempt.timeout(120000); + await attempt.start(); +}); -test.serial(`should get a metric descriptor`, async t => { - t.plan(0); +it(`should get a metric descriptor`, async () => { const attempt = tools.tryTest(async assert => { const output = await tools.runAsync(`${cmd} get ${customMetricId}`, cwd); assert(output.includes(`Type: ${customMetricId}`)); @@ -63,31 +58,32 @@ test.serial(`should get a metric descriptor`, async t => { await attempt.start(); }); -test.serial(`should write time series data`, async t => { +it(`should write time series data`, async () => { const output = await tools.runAsync(`${cmd} write`, cwd); - t.true(output.includes(`Done writing time series data.`)); + assert.strictEqual(output.includes(`Done writing time series data.`), true); }); -test.serial(`should delete a metric descriptor`, async t => { +it(`should delete a metric descriptor`, async () => { const output = await tools.runAsync(`${cmd} delete ${customMetricId}`, cwd); - t.true(output.includes(`Deleted ${customMetricId}`)); + assert.strictEqual(output.includes(`Deleted ${customMetricId}`), true); }); -test(`should list monitored resource descriptors`, async t => { +it(`should list monitored resource descriptors`, async () => { const output = await tools.runAsync(`${cmd} list-resources`, cwd); - t.true( + assert.strictEqual( output.includes( `projects/${projectId}/monitoredResourceDescriptors/${resourceId}` - ) + ), + true ); }); -test(`should get a monitored resource descriptor`, async t => { +it(`should get a monitored resource descriptor`, async () => { const output = await tools.runAsync(`${cmd} get-resource ${resourceId}`, cwd); - t.true(output.includes(`Type: ${resourceId}`)); + assert.strictEqual(output.includes(`Type: ${resourceId}`), true); }); -test(`should read time series data`, async t => { +it(`should read time series data`, async () => { const [timeSeries] = await client.listTimeSeries({ name: client.projectPath(projectId), filter: filter, @@ -102,16 +98,19 @@ test(`should read time series data`, async t => { }, }); const output = await tools.runAsync(`${cmd} read '${filter}'`, cwd); - t.true(true); // Do not fail if there is simply no data to return. + //t.true(true); // Do not fail if there is simply no data to return. timeSeries.forEach(data => { - t.true(output.includes(`${data.metric.labels.instance_name}:`)); + assert.strictEqual( + output.includes(`${data.metric.labels.instance_name}:`), + true + ); data.points.forEach(point => { - t.true(output.includes(JSON.stringify(point.value))); + assert.strictEqual(output.includes(JSON.stringify(point.value)), true); }); }); }); -test(`should read time series data fields`, async t => { +it(`should read time series data fields`, async () => { const [timeSeries] = await client.listTimeSeries({ name: client.projectPath(projectId), filter: filter, @@ -129,13 +128,16 @@ test(`should read time series data fields`, async t => { view: `HEADERS`, }); const output = await tools.runAsync(`${cmd} read-fields`, cwd); - t.true(output.includes(`Found data points for the following instances:`)); + assert.strictEqual( + output.includes(`Found data points for the following instances:`), + true + ); timeSeries.forEach(data => { - t.true(output.includes(data.metric.labels.instance_name)); + assert.strictEqual(output.includes(data.metric.labels.instance_name), true); }); }); -test(`should read time series data aggregated`, async t => { +it(`should read time series data aggregated`, async () => { const [timeSeries] = await client.listTimeSeries({ name: client.projectPath(projectId), filter: filter, @@ -157,15 +159,18 @@ test(`should read time series data aggregated`, async t => { }, }); const output = await tools.runAsync(`${cmd} read-aggregate`, cwd); - t.regex(output, /CPU utilization:/); + assert.strictEqual(output.includes('CPU utilization:'), true); timeSeries.forEach(data => { - t.regex(output, new RegExp(data.metric.labels.instance_name)); - t.regex(output, / Now: 0\.\d+/); - t.regex(output, / 10 min ago: 0\.\d+/); + assert.strictEqual( + new RegExp(data.metric.labels.instance_name).test(output), + true + ); + assert.strictEqual(output.includes(' Now: 0.'), true); + assert.strictEqual(output.includes(' 10 min ago: 0.'), true); }); }); -test(`should read time series data reduced`, async t => { +it(`should read time series data reduced`, async () => { await client.listTimeSeries({ name: client.projectPath(projectId), filter: filter, @@ -190,12 +195,13 @@ test(`should read time series data reduced`, async t => { const output = await tools.runAsync(`${cmd} read-reduce`, cwd); // Special case: No output. if (output === 'No data') { - t.true(output.includes('No data')); + assert.strictEqual(output.includes('No data'), true); } else { - t.true( - output.includes(`Average CPU utilization across all GCE instances:`) + assert.strictEqual( + output.includes(`Average CPU utilization across all GCE instances:`), + true ); - t.true(output.includes(` Last 10 min`)); - t.true(output.includes(` 10-20 min ago`)); + assert.strictEqual(output.includes(` Last 10 min`), true); + assert.strictEqual(output.includes(` 10-20 min ago`), true); } }); diff --git a/monitoring/snippets/system-test/quickstart.test.js b/monitoring/snippets/system-test/quickstart.test.js index 990318706d..7f721ca3fc 100644 --- a/monitoring/snippets/system-test/quickstart.test.js +++ b/monitoring/snippets/system-test/quickstart.test.js @@ -17,39 +17,35 @@ const proxyquire = require(`proxyquire`).noPreserveCache(); const sinon = require(`sinon`); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const monitoring = proxyquire(`@google-cloud/monitoring`, {}); const client = new monitoring.MetricServiceClient(); -test.beforeEach(tools.stubConsole); -test.afterEach.always(tools.restoreConsole); +beforeEach(tools.stubConsole); +afterEach(tools.restoreConsole); -test.cb(`should list time series`, t => { +it(`should list time series`, async () => { const clientMock = { projectPath: projectId => client.projectPath(projectId), - createTimeSeries: _request => { + createTimeSeries: async _request => { _request.name = client.projectPath(process.env.GCLOUD_PROJECT); _request.timeSeries[0].resource.labels.project_id = process.env.GCLOUD_PROJECT; - return client.createTimeSeries(_request).then(result => { - setTimeout(() => { - try { - t.is(console.log.callCount, 1); - t.deepEqual(console.log.getCall(0).args, [ - `Done writing time series data.`, - {}, - ]); - t.end(); - } catch (err) { - t.end(err); - } - }, 200); - - return result; - }); + const result = await client.createTimeSeries(_request); + setTimeout(() => { + try { + assert.strictEqual(console.log.callCount, 1); + assert.deepStrictEqual(console.log.getCall(0).args, [ + `Done writing time series data.`, + {}, + ]); + } catch (err) {} + }, 200); + + return result; }, }; diff --git a/monitoring/snippets/system-test/uptime.test.js b/monitoring/snippets/system-test/uptime.test.js index d864d542a0..7a4a4a4417 100644 --- a/monitoring/snippets/system-test/uptime.test.js +++ b/monitoring/snippets/system-test/uptime.test.js @@ -16,7 +16,7 @@ 'use strict'; const path = require(`path`); -const test = require(`ava`); +const assert = require('assert'); const tools = require(`@google-cloud/nodejs-repo-tools`); const cmd = `node uptime.js`; @@ -34,42 +34,46 @@ function getResourceObjects(output) { return result; } -test.before(tools.checkCredentials); +before(tools.checkCredentials); -test(`should list uptime-check ips`, async t => { - t.regex(await tools.runAsync(`${cmd} list-ips`, cwd), /USA/); +it(`should list uptime-check ips`, async () => { + assert.strictEqual( + (await tools.runAsync(`${cmd} list-ips`, cwd)).includes('USA'), + true + ); }); let id; -test.serial(`should create an uptime check`, async t => { +it(`should create an uptime check`, async () => { const results = await tools.runAsyncWithIO(`${cmd} create ${hostname}`, 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:/); + assert.strictEqual(output.includes('Uptime check created:'), true); const resources = getResourceObjects(output); - t.is(resources[0]['type'], 'uptime_url'); - t.is(resources[0]['labels']['host'], hostname); - t.regex(output, /Display Name: My Uptime Check/); + assert.strictEqual(resources[0]['type'], 'uptime_url'); + assert.strictEqual(resources[0]['labels']['host'], hostname); + assert.strictEqual(output.includes('Display Name: My Uptime Check'), true); }); -test.serial(`should get an uptime check`, async t => { +it(`should get an uptime check`, async () => { 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}`) + assert.strictEqual( + new RegExp( + `Retrieving projects/${projectId}/uptimeCheckConfigs/${id}` + ).test(output), + true ); const resources = getResourceObjects(output); - t.is(resources[0]['type'], 'uptime_url'); - t.is(resources[0]['labels']['host'], hostname); + assert.strictEqual(resources[0]['type'], 'uptime_url'); + assert.strictEqual(resources[0]['labels']['host'], hostname); }); -test.serial(`should list uptime checks`, async t => { - t.plan(0); +it(`should list uptime checks`, async () => { await tools .tryTest(async assert => { const results = await tools.runAsyncWithIO(`${cmd} list`, cwd); @@ -87,7 +91,7 @@ test.serial(`should list uptime checks`, async t => { .start(); }); -test.serial(`should update an uptime check`, async t => { +it(`should update an uptime check`, async () => { const newDisplayName = 'My New Display'; const path = '/'; const results = await tools.runAsyncWithIO( @@ -95,27 +99,33 @@ test.serial(`should update an uptime check`, async t => { cwd ); const output = results.stdout + results.stderr; - t.regex( - output, + assert.strictEqual( new RegExp( `Updating projects/${projectId}/uptimeCheckConfigs/${id} to ${newDisplayName}` - ) + ).test(output), + true ); - t.regex( - output, - new RegExp(`projects/${projectId}/uptimeCheckConfigs/${id} config updated.`) + assert.strictEqual( + new RegExp( + `projects/${projectId}/uptimeCheckConfigs/${id} config updated.` + ).test(output), + true ); }); -test.serial(`should delete an uptime check`, async t => { +it(`should delete an uptime check`, async () => { 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}`) + assert.strictEqual( + new RegExp(`Deleting projects/${projectId}/uptimeCheckConfigs/${id}`).test( + output + ), + true ); - t.regex( - output, - new RegExp(`projects/${projectId}/uptimeCheckConfigs/${id} deleted.`) + assert.strictEqual( + new RegExp(`projects/${projectId}/uptimeCheckConfigs/${id} deleted.`).test( + output + ), + true ); }); diff --git a/monitoring/snippets/uptime.js b/monitoring/snippets/uptime.js index 214ab41dcd..c60a28c2b7 100644 --- a/monitoring/snippets/uptime.js +++ b/monitoring/snippets/uptime.js @@ -23,7 +23,7 @@ 'use strict'; -function createUptimeCheckConfig(projectId, hostname) { +async function createUptimeCheckConfig(projectId, hostname) { // [START monitoring_uptime_check_create] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -54,36 +54,29 @@ function createUptimeCheckConfig(projectId, hostname) { }; // 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.monitoredResource); - 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); - }); + const [uptimeCheckConfig] = await client.createUptimeCheckConfig(request); + console.log('Uptime check created:'); + console.log(`ID: ${uptimeCheckConfig.name}`); + console.log(`Display Name: ${uptimeCheckConfig.displayName}`); + console.log(`Resource: %j`, uptimeCheckConfig.monitoredResource); + 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(', ')}`); + // [END monitoring_uptime_check_create] } -function listUptimeCheckConfigs(projectId) { +async function listUptimeCheckConfigs(projectId) { // [START monitoring_uptime_check_list_configs] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -101,39 +94,31 @@ function listUptimeCheckConfigs(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.monitoredResource); - 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); - }); + const [uptimeCheckConfigs] = await client.listUptimeCheckConfigs(request); + + uptimeCheckConfigs.forEach(uptimeCheckConfig => { + console.log(`ID: ${uptimeCheckConfig.name}`); + console.log(` Display Name: ${uptimeCheckConfig.displayName}`); + console.log(` Resource: %j`, uptimeCheckConfig.monitoredResource); + 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(', ')}`); + }); + // [END monitoring_uptime_check_list_configs] } -function listUptimeCheckIps() { +async function listUptimeCheckIps() { // [START monitoring_uptime_check_list_ips] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -142,25 +127,19 @@ function listUptimeCheckIps() { const client = new monitoring.UptimeCheckServiceClient(); // 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); - }); + const [uptimeCheckIps] = await client.listUptimeCheckIps(); + uptimeCheckIps.forEach(uptimeCheckIp => { + console.log( + uptimeCheckIp.region, + uptimeCheckIp.location, + uptimeCheckIp.ipAddress + ); + }); + // [END monitoring_uptime_check_list_ips] } -function getUptimeCheckConfig(projectId, uptimeCheckConfigId) { +async function getUptimeCheckConfig(projectId, uptimeCheckConfigId) { // [START monitoring_uptime_check_get] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -182,35 +161,28 @@ function getUptimeCheckConfig(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.monitoredResource); - 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); - }); + const [uptimeCheckConfig] = await client.getUptimeCheckConfig(request); + console.log(`ID: ${uptimeCheckConfig.name}`); + console.log(`Display Name: ${uptimeCheckConfig.displayName}`); + console.log(`Resource: %j`, uptimeCheckConfig.monitoredResource); + 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(', ')}`); + // [END monitoring_uptime_check_get] } -function deleteUptimeCheckConfig(projectId, uptimeCheckConfigId) { +async function deleteUptimeCheckConfig(projectId, uptimeCheckConfigId) { // [START monitoring_uptime_check_delete] // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); @@ -232,18 +204,13 @@ function deleteUptimeCheckConfig(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); - }); + await client.deleteUptimeCheckConfig(request); + console.log(`${request.name} deleted.`); + // [END monitoring_uptime_check_delete] } -function updateUptimeCheckConfigDisplayName( +async function updateUptimeCheckConfigDisplayName( projectId, uptimeCheckConfigId, displayName, @@ -280,14 +247,8 @@ function updateUptimeCheckConfigDisplayName( request.updateMask = {paths: ['display_name', 'http_check.path']}; - client - .updateUptimeCheckConfig(request) - .then(responses => { - console.log(`${responses[0].name} config updated.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); + const [response] = await client.updateUptimeCheckConfig(request); + console.log(`${response.name} config updated.`); // [END monitoring_uptime_check_update] }