Skip to content

Commit

Permalink
Fixes #43. (#44)
Browse files Browse the repository at this point in the history
Makes alert tests more stable and adds a list alert sample.
  • Loading branch information
jmdobry authored and Ace Nassri committed Nov 10, 2022
1 parent e32fbb0 commit 9815f9a
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 65 deletions.
1 change: 1 addition & 0 deletions monitoring/snippets/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ Commands:
alerts.js replace <alertPolicyName> <channelNames..> Replace the notification channels of the specified alert policy.
alerts.js disable <projectId> [filter] Disables policies that match the given filter.
alerts.js enable <projectId> [filter] Enables policies that match the given filter.
alerts.js list <projectId> Lists alert policies in the specified project.
Options:
--version Show version number [boolean]
Expand Down
69 changes: 30 additions & 39 deletions monitoring/snippets/alerts.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ 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]
// [START monitoring_alert_create_policy]
const fs = require('fs');

// Imports the Google Cloud client library
Expand Down Expand Up @@ -125,6 +126,7 @@ function restorePolicies(projectId) {
return Promise.reject(err);
});
}
// [END monitoring_alert_create_policy]
// [END monitoring_alert_restore_policies]
}

Expand Down Expand Up @@ -172,8 +174,8 @@ function replaceChannels(projectId, alertPolicyId, channelIds) {
// [END monitoring_alert_replace_channels]
}

function disablePolicies(projectId, filter) {
// [START monitoring_alert_disable_policies]
function enablePolicies(projectId, enabled, filter) {
// [START monitoring_alert_enable_policies]
// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

Expand All @@ -184,7 +186,8 @@ function disablePolicies(projectId, filter) {
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const filter = 'A filter for selecting policies, e.g. user_labels="active"';
// const enabled = true;
// const filter = 'A filter for selecting policies, e.g. description:"cloud"';

const listAlertPoliciesRequest = {
name: client.projectPath(projectId),
Expand All @@ -203,31 +206,31 @@ function disablePolicies(projectId, filter) {
updateMask: {paths: ['disabled']},
alertPolicy: {
name: policy.name,
disabled: true,
disabled: enabled ? false : true,
},
};
})
.map(updateAlertPolicyRequest => {
return client.updateAlertPolicy(updateAlertPolicyRequest);
});
.map(updateAlertPolicyRequest =>
client.updateAlertPolicy(updateAlertPolicyRequest)
);

// Wait for all policies to be disabled
// Wait for all policies to be enabled
return Promise.all(tasks);
})
.then(responses => {
responses.forEach(response => {
const alertPolicy = response[0];
console.log(`Disabled ${alertPolicy.name}.`);
console.log(`${enabled ? 'Enabled' : 'Disabled'} ${alertPolicy.name}.`);
});
})
.catch(err => {
console.error('ERROR:', err);
});
// [END monitoring_alert_disable_policies]
// [END monitoring_alert_enable_policies]
}

function enablePolicies(projectId, filter) {
// [START monitoring_alert_enable_policies]
function listPolicies(projectId) {
// [START monitoring_alert_list_policies]
// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

Expand All @@ -238,46 +241,28 @@ function enablePolicies(projectId, filter) {
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const filter = 'A filter for selecting policies, e.g. description:"cloud"';

const listAlertPoliciesRequest = {
name: client.projectPath(projectId),
// See https://cloud.google.com/monitoring/alerting/docs/sorting-and-filtering
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: false,
},
};
})
.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 ${alertPolicy.name}.`);
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_enable_policies]
// [END monitoring_alert_list_policies]
}

require(`yargs`)
Expand Down Expand Up @@ -308,13 +293,19 @@ require(`yargs`)
`disable <projectId> [filter]`,
`Disables policies that match the given filter.`,
{},
opts => disablePolicies(opts.projectId, opts.filter || ``)
opts => enablePolicies(opts.projectId, false, opts.filter || ``)
)
.command(
`enable <projectId> [filter]`,
`Enables policies that match the given filter.`,
{},
opts => enablePolicies(opts.projectId, opts.filter || ``)
opts => enablePolicies(opts.projectId, true, opts.filter || ``)
)
.command(
`list <projectId>`,
`Lists alert policies in the specified project.`,
{},
opts => listPolicies(opts.projectId)
)
.options({
alertPolicyName: {
Expand Down
68 changes: 42 additions & 26 deletions monitoring/snippets/system-test/alerts.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ test.before(async () => {
alertPolicy: {
displayName: 'first_policy',
combiner: 1,
documentation: {
content: 'Test',
mimeType: 'text/markdown',
},
conditions: [
{
displayName: 'Condition 1',
Expand Down Expand Up @@ -131,32 +135,6 @@ test.after.always(async () => {
await deleteChannels();
});

test.serial(`should backup all policies`, async t => {
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`)));
await client.deleteAlertPolicy({name: policyOneName});
});

test.serial(`should restore policies`, async t => {
const results = await tools.spawnAsyncWithIO(
`node`,
[`alerts.js`, `restore`, projectId],
cwd
);
t.regex(results.output, /Loading policies from .\/policies_backup.json/);
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);
policyOneName = matches[0];
policyTwoName = matches[1];
});

test.serial(`should replace notification channels`, async t => {
const results = await tools.spawnAsyncWithIO(
`node`,
Expand Down Expand Up @@ -188,3 +166,41 @@ test.serial(`should enable policies`, async t => {
t.false(results.output.includes(policyOneName));
t.true(results.output.includes(policyTwoName));
});

test.serial(`should list policies`, async t => {
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'));
});

test.serial(`should backup all policies`, async t => {
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`)));
await client.deleteAlertPolicy({name: policyOneName});
});

test.serial(`should restore policies`, async t => {
const results = await tools.spawnAsyncWithIO(
`node`,
[`alerts.js`, `restore`, projectId],
cwd
);
t.regex(results.output, /Loading policies from .\/policies_backup.json/);
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);
policyOneName = matches[0];
policyTwoName = matches[1];
});

0 comments on commit 9815f9a

Please sign in to comment.