Skip to content

Commit f71dc41

Browse files
authored
Cloud Monitoring Alert samples (GoogleCloudPlatform#779)
1 parent 5aadc4d commit f71dc41

14 files changed

+963
-2
lines changed

monitoring/README.md

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ authentication:
5858

5959
1. Set `GOOGLE_APPLICATION_CREDENTIALS` environment variable pointing to that file.
6060

61-
## Samples
61+
## Stackdriver Monitoring Samples
6262

6363
To run the Stackdriver Monitoring Samples:
6464

@@ -80,17 +80,54 @@ To run the Stackdriver Monitoring Samples:
8080

8181
Available commands:
8282
create-metric Creates a logging metric.
83+
create-uptime-check Creates an uptime check.
8384
delete-metric Deletes a logging metric.
85+
delete-uptime-check Deletes an uptime check config.
8486
get-descriptor Gets a logging descriptor.
8587
help Displays help for a command
8688
list Lists commands
8789
list-descriptors Lists logging descriptors.
90+
list-uptime-check-ips Lists Uptime Check IPs.
91+
list-uptime-checks Lists Uptime Check Configs.
8892
read-timeseries-align Aggregates metrics for each timeseries.
8993
read-timeseries-fields Reads Timeseries fields.
9094
read-timeseries-reduce Aggregates metrics across multiple timeseries.
9195
read-timeseries-simple Reads a timeseries.
9296
write-timeseries Writes a timeseries.
9397

98+
## Stackdriver Monitoring Alert Samples
99+
100+
To run the Stackdriver Monitoring Alert Samples:
101+
102+
$ php alerts.php
103+
104+
Stackdriver Monitoring Alerts
105+
106+
Usage:
107+
command [options] [arguments]
108+
109+
Options:
110+
-h, --help Display this help message
111+
-q, --quiet Do not output any message
112+
-V, --version Display this application version
113+
--ansi Force ANSI output
114+
--no-ansi Disable ANSI output
115+
-n, --no-interaction Do not ask any interactive question
116+
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
117+
118+
Available commands:
119+
backup-policies Back up alert policies.
120+
create-channel Create a notification channel.
121+
create-policy Create an alert policy.
122+
delete-channel Delete a notification channel.
123+
enable-policies Enable or disable alert policies in a project.
124+
help Displays help for a command
125+
list Lists commands
126+
list-channels List alert channels.
127+
list-policies List alert policies.
128+
replace-channels Replace alert channels.
129+
restore-policies Restore alert policies from a backup.
130+
94131
## The client library
95132

96133
This sample uses the [Google Cloud Client Library for PHP][google-cloud-php].

monitoring/alerts.php

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
2+
/**
3+
* Copyright 2018 Google Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
namespace Google\Cloud\Samples\Monitoring;
19+
20+
use Symfony\Component\Console\Application;
21+
use Symfony\Component\Console\Command\Command;
22+
use Symfony\Component\Console\Input\InputArgument;
23+
use Symfony\Component\Console\Input\InputDefinition;
24+
25+
# Includes the autoloader for libraries installed with composer
26+
require __DIR__ . '/vendor/autoload.php';
27+
28+
$application = new Application('Stackdriver Monitoring Alerts');
29+
30+
$inputDefinition = new InputDefinition([
31+
new InputArgument('project_id', InputArgument::REQUIRED, 'The project id'),
32+
]);
33+
34+
$application->add(new Command('backup-policies'))
35+
->setDefinition($inputDefinition)
36+
->setDescription('Back up alert policies.')
37+
->setCode(function ($input, $output) {
38+
alert_backup_policies(
39+
$input->getArgument('project_id')
40+
);
41+
});
42+
43+
$application->add(new Command('create-channel'))
44+
->setDefinition($inputDefinition)
45+
->setDescription('Create a notification channel.')
46+
->setCode(function ($input, $output) {
47+
alert_create_channel(
48+
$input->getArgument('project_id')
49+
);
50+
});
51+
52+
$application->add(new Command('create-policy'))
53+
->setDefinition($inputDefinition)
54+
->setDescription('Create an alert policy.')
55+
->setCode(function ($input, $output) {
56+
alert_create_policy(
57+
$input->getArgument('project_id')
58+
);
59+
});
60+
61+
$application->add(new Command('delete-channel'))
62+
->setDefinition(clone $inputDefinition)
63+
->addArgument('channel_id', InputArgument::REQUIRED, 'The notification channel ID to delete')
64+
->setDescription('Delete a notification channel.')
65+
->setCode(function ($input, $output) {
66+
alert_delete_channel(
67+
$input->getArgument('project_id'),
68+
$input->getArgument('channel_id')
69+
);
70+
});
71+
72+
$application->add(new Command('enable-policies'))
73+
->setDefinition(clone $inputDefinition)
74+
->addArgument('enable', InputArgument::OPTIONAL, 'Enable or disable the polcies', true)
75+
->addArgument('filter', InputArgument::OPTIONAL, 'Only enable/disable alert policies that match a filter.')
76+
->setDescription('Enable or disable alert policies in a project.')
77+
->setCode(function ($input, $output) {
78+
alert_enable_policies(
79+
$input->getArgument('project_id'),
80+
$input->getArgument('enable'),
81+
$input->getArgument('filter')
82+
);
83+
});
84+
85+
$application->add(new Command('restore-policies'))
86+
->setDefinition($inputDefinition)
87+
->setDescription('Restore alert policies from a backup.')
88+
->setCode(function ($input, $output) {
89+
alert_restore_policies(
90+
$input->getArgument('project_id')
91+
);
92+
});
93+
94+
$application->add(new Command('list-policies'))
95+
->setDefinition($inputDefinition)
96+
->setDescription('List alert policies.')
97+
->setCode(function ($input, $output) {
98+
alert_list_policies(
99+
$input->getArgument('project_id')
100+
);
101+
});
102+
103+
$application->add(new Command('list-channels'))
104+
->setDefinition($inputDefinition)
105+
->setDescription('List alert channels.')
106+
->setCode(function ($input, $output) {
107+
alert_list_channels(
108+
$input->getArgument('project_id')
109+
);
110+
});
111+
$application->add(new Command('replace-channels'))
112+
->setDefinition(clone $inputDefinition)
113+
->addArgument('policy_id', InputArgument::REQUIRED, 'The policy id')
114+
->addArgument('channel_id', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'list of channel ids')
115+
->setDescription('Replace alert channels.')
116+
->setCode(function ($input, $output) {
117+
alert_replace_channels(
118+
$input->getArgument('project_id'),
119+
$input->getArgument('policy_id'),
120+
(array) $input->getArgument('channel_id')
121+
);
122+
});
123+
124+
// for testing
125+
if (getenv('PHPUNIT_TESTS') === '1') {
126+
return $application;
127+
}
128+
129+
$application->run();

monitoring/composer.json

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,19 @@
11
{
22
"require": {
33
"symfony/console": "^3.3",
4-
"google/cloud-monitoring": "~0.11"
4+
"google/cloud-monitoring": "^0.13.0"
55
},
66
"autoload": {
77
"files": [
8+
"src/alert_backup_policies.php",
9+
"src/alert_create_channel.php",
10+
"src/alert_create_policy.php",
11+
"src/alert_delete_channel.php",
12+
"src/alert_enable_policies.php",
13+
"src/alert_list_channels.php",
14+
"src/alert_list_policies.php",
15+
"src/alert_replace_channels.php",
16+
"src/alert_restore_policies.php",
817
"src/create_metric.php",
918
"src/create_uptime_check.php",
1019
"src/delete_metric.php",

monitoring/phpunit.xml.dist

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@
2222
logging>
2323
<filter>
2424
<whitelist>
25+
<file>alerts.phpfile>
2526
<file>quickstart.phpfile>
27+
<file>monitoring.phpfile>
2628
whitelist>
2729
filter>
2830
<php>
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
2+
/**
3+
* Copyright 2018 Google Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* For instructions on how to run the full sample:
20+
*
21+
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/monitoring/README.md
22+
*/
23+
24+
namespace Google\Cloud\Samples\Monitoring;
25+
26+
// [START monitoring_alert_backup_policies]
27+
use Google\Cloud\Monitoring\V3\AlertPolicyServiceClient;
28+
use Google\Cloud\Monitoring\V3\NotificationChannelServiceClient;
29+
30+
/**
31+
* Back up alert policies.
32+
*
33+
* @param string $projectId Your project ID
34+
*/
35+
function alert_backup_policies($projectId)
36+
{
37+
$alertClient = new AlertPolicyServiceClient([
38+
'projectId' => $projectId,
39+
]);
40+
$channelClient = new NotificationChannelServiceClient([
41+
'projectId' => $projectId,
42+
]);
43+
$projectName = $alertClient->projectName($projectId);
44+
45+
$record = [
46+
'project_name' => $projectName,
47+
'policies' => [],
48+
'channels' => [],
49+
];
50+
$policies = $alertClient->listAlertPolicies($projectName);
51+
foreach ($policies->iterateAllElements() as $policy) {
52+
$record['policies'][] = json_decode($policy->serializeToJsonString());
53+
}
54+
$channels = $channelClient->listNotificationChannels($projectName);
55+
foreach ($channels->iterateAllElements() as $channel) {
56+
$record['channels'][] = json_decode($channel->serializeToJsonString());
57+
}
58+
file_put_contents('backup.json', json_encode($record, JSON_PRETTY_PRINT));
59+
print('Backed up alert policies and notification channels to backup.json.');
60+
}
61+
// [END monitoring_alert_backup_policies]
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
2+
/**
3+
* Copyright 2018 Google Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* For instructions on how to run the full sample:
20+
*
21+
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/monitoring/README.md
22+
*/
23+
24+
namespace Google\Cloud\Samples\Monitoring;
25+
26+
# [START monitoring_alert_create_channel]
27+
use Google\Cloud\Monitoring\V3\NotificationChannelServiceClient;
28+
use Google\Cloud\Monitoring\V3\NotificationChannel;
29+
30+
/**
31+
* @param string $projectId Your project ID
32+
*/
33+
function alert_create_channel($projectId)
34+
{
35+
$channelClient = new NotificationChannelServiceClient([
36+
'projectId' => $projectId,
37+
]);
38+
$projectName = $channelClient->projectName($projectId);
39+
40+
$channel = new NotificationChannel();
41+
$channel->setDisplayName('Test Notification Channel');
42+
$channel->setType('email');
43+
$channel->setLabels(['email_address' => '[email protected]']);
44+
45+
$channel = $channelClient->createNotificationChannel($projectName, $channel);
46+
printf('Created notification channel %s' . PHP_EOL, $channel->getName());
47+
}
48+
# [END monitoring_alert_create_channel]
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
2+
/**
3+
* Copyright 2018 Google Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* For instructions on how to run the full sample:
20+
*
21+
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/monitoring/README.md
22+
*/
23+
24+
namespace Google\Cloud\Samples\Monitoring;
25+
26+
# [START monitoring_alert_create_policy]
27+
use Google\Cloud\Monitoring\V3\AlertPolicyServiceClient;
28+
use Google\Cloud\Monitoring\V3\AlertPolicy;
29+
use Google\Cloud\Monitoring\V3\ComparisonType;
30+
use Google\Cloud\Monitoring\V3\AlertPolicy\Condition;
31+
use Google\Cloud\Monitoring\V3\AlertPolicy\Condition\MetricThreshold;
32+
use Google\Cloud\Monitoring\V3\AlertPolicy\ConditionCombinerType;
33+
use Google\Protobuf\Duration;
34+
35+
/**
36+
* @param string $projectId Your project ID
37+
*/
38+
function alert_create_policy($projectId)
39+
{
40+
$alertClient = new AlertPolicyServiceClient([
41+
'projectId' => $projectId,
42+
]);
43+
$projectName = $alertClient->projectName($projectId);
44+
45+
$policy = new AlertPolicy();
46+
$policy->setDisplayName('Test Alert Policy');
47+
$policy->setCombiner(ConditionCombinerType::PBOR);
48+
/** @see https://cloud.google.com/monitoring/api/resources for a list of resource.type */
49+
/** @see https://cloud.google.com/monitoring/api/metrics_gcp for a list of metric.type */
50+
$policy->setConditions([new Condition([
51+
'display_name' => 'condition-1',
52+
'condition_threshold' => new MetricThreshold([
53+
'filter' => 'resource.type = "gce_instance" AND metric.type = "compute.googleapis.com/instance/cpu/utilization"',
54+
'duration' => new Duration(['seconds' => '60']),
55+
'comparison' => ComparisonType::COMPARISON_LT,
56+
])
57+
])]);
58+
59+
$policy = $alertClient->createAlertPolicy($projectName, $policy);
60+
printf('Created alert policy %s' . PHP_EOL, $policy->getName());
61+
}
62+
# [END monitoring_alert_create_policy]

0 commit comments

Comments
 (0)