Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion monitoring/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ authentication:

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

## Samples
## Stackdriver Monitoring Samples

To run the Stackdriver Monitoring Samples:

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

Available commands:
create-metric Creates a logging metric.
create-uptime-check Creates an uptime check.
delete-metric Deletes a logging metric.
delete-uptime-check Deletes an uptime check config.
get-descriptor Gets a logging descriptor.
help Displays help for a command
list Lists commands
list-descriptors Lists logging descriptors.
list-uptime-check-ips Lists Uptime Check IPs.
list-uptime-checks Lists Uptime Check Configs.
read-timeseries-align Aggregates metrics for each timeseries.
read-timeseries-fields Reads Timeseries fields.
read-timeseries-reduce Aggregates metrics across multiple timeseries.
read-timeseries-simple Reads a timeseries.
write-timeseries Writes a timeseries.

## Stackdriver Monitoring Alert Samples

To run the Stackdriver Monitoring Alert Samples:

$ php alerts.php

Stackdriver Monitoring Alerts

Usage:
command [options] [arguments]

Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
backup-policies Back up alert policies.
create-channel Create a notification channel.
create-policy Create an alert policy.
delete-channel Delete a notification channel.
enable-policies Enable or disable alert policies in a project.
help Displays help for a command
list Lists commands
list-channels List alert channels.
list-policies List alert policies.
replace-channels Replace alert channels.
restore-policies Restore alert policies from a backup.

## The client library

This sample uses the [Google Cloud Client Library for PHP][google-cloud-php].
Expand Down
129 changes: 129 additions & 0 deletions monitoring/alerts.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?php
/**
* Copyright 2018 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.
*/

namespace Google\Cloud\Samples\Monitoring;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

$application = new Application('Stackdriver Monitoring Alerts');

$inputDefinition = new InputDefinition([
new InputArgument('project_id', InputArgument::REQUIRED, 'The project id'),
]);

$application->add(new Command('backup-policies'))
->setDefinition($inputDefinition)
->setDescription('Back up alert policies.')
->setCode(function ($input, $output) {
alert_backup_policies(
$input->getArgument('project_id')
);
});

$application->add(new Command('create-channel'))
->setDefinition($inputDefinition)
->setDescription('Create a notification channel.')
->setCode(function ($input, $output) {
alert_create_channel(
$input->getArgument('project_id')
);
});

$application->add(new Command('create-policy'))
->setDefinition($inputDefinition)
->setDescription('Create an alert policy.')
->setCode(function ($input, $output) {
alert_create_policy(
$input->getArgument('project_id')
);
});

$application->add(new Command('delete-channel'))
->setDefinition(clone $inputDefinition)
->addArgument('channel_id', InputArgument::REQUIRED, 'The notification channel ID to delete')
->setDescription('Delete a notification channel.')
->setCode(function ($input, $output) {
alert_delete_channel(
$input->getArgument('project_id'),
$input->getArgument('channel_id')
);
});

$application->add(new Command('enable-policies'))
->setDefinition(clone $inputDefinition)
->addArgument('enable', InputArgument::OPTIONAL, 'Enable or disable the polcies', true)
->addArgument('filter', InputArgument::OPTIONAL, 'Only enable/disable alert policies that match a filter.')
->setDescription('Enable or disable alert policies in a project.')
->setCode(function ($input, $output) {
alert_enable_policies(
$input->getArgument('project_id'),
$input->getArgument('enable'),
$input->getArgument('filter')
);
});

$application->add(new Command('restore-policies'))
->setDefinition($inputDefinition)
->setDescription('Restore alert policies from a backup.')
->setCode(function ($input, $output) {
alert_restore_policies(
$input->getArgument('project_id')
);
});

$application->add(new Command('list-policies'))
->setDefinition($inputDefinition)
->setDescription('List alert policies.')
->setCode(function ($input, $output) {
alert_list_policies(
$input->getArgument('project_id')
);
});

$application->add(new Command('list-channels'))
->setDefinition($inputDefinition)
->setDescription('List alert channels.')
->setCode(function ($input, $output) {
alert_list_channels(
$input->getArgument('project_id')
);
});
$application->add(new Command('replace-channels'))
->setDefinition(clone $inputDefinition)
->addArgument('policy_id', InputArgument::REQUIRED, 'The policy id')
->addArgument('channel_id', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'list of channel ids')
->setDescription('Replace alert channels.')
->setCode(function ($input, $output) {
alert_replace_channels(
$input->getArgument('project_id'),
$input->getArgument('policy_id'),
(array) $input->getArgument('channel_id')
);
});

// for testing
if (getenv('PHPUNIT_TESTS') === '1') {
return $application;
}

$application->run();
11 changes: 10 additions & 1 deletion monitoring/composer.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
{
"require": {
"symfony/console": "^3.3",
"google/cloud-monitoring": "~0.11"
"google/cloud-monitoring": "^0.13.0"
},
"autoload": {
"files": [
"src/alert_backup_policies.php",
"src/alert_create_channel.php",
"src/alert_create_policy.php",
"src/alert_delete_channel.php",
"src/alert_enable_policies.php",
"src/alert_list_channels.php",
"src/alert_list_policies.php",
"src/alert_replace_channels.php",
"src/alert_restore_policies.php",
"src/create_metric.php",
"src/create_uptime_check.php",
"src/delete_metric.php",
Expand Down
2 changes: 2 additions & 0 deletions monitoring/phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
</logging>
<filter>
<whitelist>
<file>alerts.php</file>
<file>quickstart.php</file>
<file>monitoring.php</file>
</whitelist>
</filter>
<php>
Expand Down
61 changes: 61 additions & 0 deletions monitoring/src/alert_backup_policies.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php
/**
* Copyright 2018 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.
*/

/**
* For instructions on how to run the full sample:
*
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/monitoring/README.md
*/

namespace Google\Cloud\Samples\Monitoring;

// [START monitoring_alert_backup_policies]
use Google\Cloud\Monitoring\V3\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\NotificationChannelServiceClient;

/**
* Back up alert policies.
*
* @param string $projectId Your project ID
*/
function alert_backup_policies($projectId)
{
$alertClient = new AlertPolicyServiceClient([
'projectId' => $projectId,
]);
$channelClient = new NotificationChannelServiceClient([
'projectId' => $projectId,
]);
$projectName = $alertClient->projectName($projectId);

$record = [
'project_name' => $projectName,
'policies' => [],
'channels' => [],
];
$policies = $alertClient->listAlertPolicies($projectName);
foreach ($policies->iterateAllElements() as $policy) {
$record['policies'][] = json_decode($policy->serializeToJsonString());
}
$channels = $channelClient->listNotificationChannels($projectName);
foreach ($channels->iterateAllElements() as $channel) {
$record['channels'][] = json_decode($channel->serializeToJsonString());
}
file_put_contents('backup.json', json_encode($record, JSON_PRETTY_PRINT));
print('Backed up alert policies and notification channels to backup.json.');
}
// [END monitoring_alert_backup_policies]
48 changes: 48 additions & 0 deletions monitoring/src/alert_create_channel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
/**
* Copyright 2018 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.
*/

/**
* For instructions on how to run the full sample:
*
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/monitoring/README.md
*/

namespace Google\Cloud\Samples\Monitoring;

# [START monitoring_alert_create_channel]
use Google\Cloud\Monitoring\V3\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\NotificationChannel;

/**
* @param string $projectId Your project ID
*/
function alert_create_channel($projectId)
{
$channelClient = new NotificationChannelServiceClient([
'projectId' => $projectId,
]);
$projectName = $channelClient->projectName($projectId);

$channel = new NotificationChannel();
$channel->setDisplayName('Test Notification Channel');
$channel->setType('email');
$channel->setLabels(['email_address' => '[email protected]']);

$channel = $channelClient->createNotificationChannel($projectName, $channel);
printf('Created notification channel %s' . PHP_EOL, $channel->getName());
}
# [END monitoring_alert_create_channel]
62 changes: 62 additions & 0 deletions monitoring/src/alert_create_policy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php
/**
* Copyright 2018 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.
*/

/**
* For instructions on how to run the full sample:
*
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/monitoring/README.md
*/

namespace Google\Cloud\Samples\Monitoring;

# [START monitoring_alert_create_policy]
use Google\Cloud\Monitoring\V3\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\AlertPolicy;
use Google\Cloud\Monitoring\V3\ComparisonType;
use Google\Cloud\Monitoring\V3\AlertPolicy\Condition;
use Google\Cloud\Monitoring\V3\AlertPolicy\Condition\MetricThreshold;
use Google\Cloud\Monitoring\V3\AlertPolicy\ConditionCombinerType;
use Google\Protobuf\Duration;

/**
* @param string $projectId Your project ID
*/
function alert_create_policy($projectId)
{
$alertClient = new AlertPolicyServiceClient([
'projectId' => $projectId,
]);
$projectName = $alertClient->projectName($projectId);

$policy = new AlertPolicy();
$policy->setDisplayName('Test Alert Policy');
$policy->setCombiner(ConditionCombinerType::PBOR);
/** @see https://cloud.google.com/monitoring/api/resources for a list of resource.type */
/** @see https://cloud.google.com/monitoring/api/metrics_gcp for a list of metric.type */
$policy->setConditions([new Condition([
'display_name' => 'condition-1',
'condition_threshold' => new MetricThreshold([
'filter' => 'resource.type = "gce_instance" AND metric.type = "compute.googleapis.com/instance/cpu/utilization"',
'duration' => new Duration(['seconds' => '60']),
'comparison' => ComparisonType::COMPARISON_LT,
])
])]);

$policy = $alertClient->createAlertPolicy($projectName, $policy);
printf('Created alert policy %s' . PHP_EOL, $policy->getName());
}
# [END monitoring_alert_create_policy]
Loading