feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""Command group for Cloud Monitoring."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA)
class MonitoringGA(base.Group):
# pylint: disable=line-too-long
"""Manage Cloud Monitoring dashboards."""
category = base.MONITORING_CATEGORY
detailed_help = {
'DESCRIPTION':
"""\
Manage Monitoring dashboards.
More information can be found here:
* https://cloud.google.com/monitoring/dashboards/api-dashboard
"""
}
def Filter(self, context, args):
# TODO(b/190537295): Determine if command group works with project number
base.RequireProjectID(args)
del context, args
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class MonitoringBeta(base.Group):
# pylint: disable=line-too-long
"""Manage Cloud Monitoring dashboards and notification channels."""
category = base.MONITORING_CATEGORY
detailed_help = {
'DESCRIPTION':
"""\
Manage Monitoring dashboards and notification
channels.
More information can be found here:
* https://cloud.google.com/monitoring/api/v3/
* https://cloud.google.com/monitoring/alerts/using-channels-api
* https://cloud.google.com/monitoring/dashboards/api-dashboard
"""
}
def Filter(self, context, args):
# TODO(b/190537295): Determine if command group works with project number
base.RequireProjectID(args)
del context, args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class MonitoringAlpha(base.Group):
# pylint: disable=line-too-long
"""Manage Cloud Monitoring alerting policies, dashboards, notification channels, and uptime checks."""
category = base.MONITORING_CATEGORY
detailed_help = {
'DESCRIPTION':
"""\
Manage Monitoring alerting policies, dashboards, and notification
channels.
More information can be found here:
* https://cloud.google.com/monitoring/api/v3/
* https://cloud.google.com/monitoring/alerts/using-alerting-api
* https://cloud.google.com/monitoring/alerts/using-channels-api
* https://cloud.google.com/monitoring/dashboards/api-dashboard
* https://cloud.google.com/monitoring/uptime-checks/manage#api
"""
}
def Filter(self, context, args):
# TODO(b/190537295): Determine if command group works with project number
base.RequireProjectID(args)
del context, args

View File

@@ -0,0 +1,36 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# 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.
"""Command group for Cloud Monitoring alerts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Alerts(base.Group):
"""Manage Cloud Monitoring alerts."""
detailed_help = {
'DESCRIPTION': """\
Manage Monitoring alerts.
More information can be found here:
https://cloud.google.com/monitoring/api/v3/
"""
}

View File

@@ -0,0 +1,13 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: Describe an alert.
description: Describe an alert.
request:
collection: monitoring.projects.alerts
api_version: v3
arguments:
resource:
help_text: The alert to describe.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:alert

View File

@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# 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.
"""Surface for listing alerts."""
from googlecloudsdk.api_lib.monitoring import alerts
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import resource_args
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class List(base.ListCommand):
"""List alerts."""
CLIENT_SIDE_FILTERS = False
detailed_help = {
'API REFERENCE': """\
This command uses the monitoring/v3 API. The full documentation for this
API can be found at: https://cloud.google.com/monitoring/api/""",
'DESCRIPTION': 'List alerts for a project.',
'EXAMPLES': """\
To list all open alerts:
$ {command} --filter="state='OPEN'"
To order alerts by when the alert was opened:
$ {command} --sort-by=openTime
To order alerts by when the alert was opened in reverse order:
$ {command} --sort-by="~openTime"
To list alerts for a specific policy:
$ {command} --filter="policy.displayName='My Policy'"
More information can be found at
https://cloud.google.com/sdk/gcloud/reference/topic/filters""",
}
@staticmethod
def Args(parser):
"""Register flags for this command."""
resource_args.AddProjectResourceArg(parser, 'list alerts from', True)
# Provide the resource spec to the base class to potentially help with
# filter handling.
super(List, List).Args(parser)
base.PAGE_SIZE_FLAG.SetDefault(parser, 1000)
parser.display_info.AddFormat('yaml')
parser.display_info.AddUriFunc(resource_args.GetAlertResourceUriFunc())
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The list of alerts.
"""
project_ref = args.CONCEPTS.project.Parse()
client = alerts.AlertsClient()
order_by_string = ','.join(args.sort_by) if args.sort_by else None
# Pass the filter and order_by to the API client
response = client.List(
project_ref,
a_filter=args.filter,
order_by=order_by_string,
page_size=args.page_size,
)
return response.alerts

View File

@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""Command group for Cloud Monitoring channel descriptors."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class ChannelDescriptors(base.Group):
"""Read Cloud Monitoring notification channel descriptors."""
detailed_help = {
'DESCRIPTION':
"""\
Manage Monitoring notification channel descriptors.
More information can be found here:
https://cloud.google.com/monitoring/api/v3/
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.notificationChannelDescriptors
https://cloud.google.com/monitoring/alerts/using-channels-api
"""
}

View File

@@ -0,0 +1,22 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: Describe a notification channel descriptor.
description: |
Describes a notification channel type by fetching its descriptor.
## EXAMPLES
The following command obtains the descriptor for the `email` channel type:
$ {command} email
The following command obtains the descriptor for the `sms` channel type:
$ {command} sms
request:
collection: monitoring.projects.notificationChannelDescriptors
arguments:
resource:
help_text: The notification channel descriptor to describe.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:notification_channel_descriptor

View File

@@ -0,0 +1,28 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: List notification channel descriptors.
description: |
List notification channel descriptors representing the various NotificationChannel types.
## EXAMPLES
The following command prints all of the `NotificationChannelDescriptor`s:
$ {command}
The following command prints all supported notification channel types:
$ {command} --format="value(type)"
request:
collection: monitoring.projects.notificationChannelDescriptors
response:
id_field: name
arguments:
resource:
help_text: The project to list notification channel descriptors from.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:project
output:
format: yaml

View File

@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""Command group for Cloud Monitoring notification channels."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Channels(base.Group):
"""Manage Cloud Monitoring notification channels."""
detailed_help = {
'DESCRIPTION':
"""\
Manage Monitoring notification channels.
More information can be found here:
https://cloud.google.com/monitoring/api/v3/
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.notificationChannels
https://cloud.google.com/monitoring/alerts/using-channels-api
"""
}

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# 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.
"""Command group for managing Monitoring notification channel configurations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Config(base.Group):
"""Manage Monitoring notification channel configurations."""

View File

@@ -0,0 +1,38 @@
release_tracks: [ALPHA]
command_type: CONFIG_EXPORT
help_text:
brief: Export the configuration for a Monitoring notification channel.
description: |
*{command}* exports the configuration for a Monitoring notification channel.
Notification channel configurations can be exported in
Kubernetes Resource Model (krm) or Terraform HCL formats. The
default format is `krm`.
Specifying `--all` allows you to export the configurations for all
notification channels within the project.
Specifying `--path` allows you to export the configuration(s) to
a local directory.
examples: |
To export the configuration for a notification channel, run:
$ {command} my-notification-channel
To export the configuration for a notification channel to a file, run:
$ {command} my-notification-channel --path=/path/to/dir/
To export the configuration for a notification channel in Terraform
HCL format, run:
$ {command} my-notification-channel --resource-format=terraform
To export the configurations for all notification channels within a
project, run:
$ {command} --all
arguments:
resource:
help_text: Notification channel to export the configuration for.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:notification_channel

View File

@@ -0,0 +1,98 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring channels create` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import channels
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import util
from googlecloudsdk.command_lib.projects import util as projects_util
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Create(base.CreateCommand):
"""Create a new notification channel."""
detailed_help = {
'DESCRIPTION':
"""\
Creates a new notification channel. A channel can be specified as
JSON/YAML passed in as a string through the `--channel-content` flag
or as a file through the `--channel-content-from-file` flag.
A basic channel can also be specified through command line flags. If
a channel is specified through `--channel-content` or
`--channel-content-from-file`, and additional flags are supplied, the
flags will override the given channel's settings.
For information about the JSON/YAML format of a notification channel:
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.notificationChannels
Additional documentation can for this operation can be found at:
https://cloud.google.com/monitoring/alerts/using-channels-api
## EXAMPLES
The following commands setup both email and SMS notification channels for the team lead. Note
that the display name and description focus on the purpose/semantics of the channel rather
than its destination. This is a best-practice that facilitates swapping/updating notification
channels in-place (such as when users change teams, projects, roles, companies, etc.) with
minimal impact to the alerting policies that reference the existing channels. It is also
a best practice to supply at least two channels of different types for a given person.
$ {command} \
--display-name="Foo Team Lead (Primary)" \
--description="Primary contact method for the Foo team lead" \
--type=email \
--user-labels=team=foo,role=lead,ord=1 \
--channel-labels=email_address=user@somedomain.tld
$ {command} \
--display-name="Foo Team Lead (Secondary)" \
--description="Secondary contact method for the Foo team lead" \
--type=sms \
--user-labels=team=foo,role=lead,ord=2 \
--channel-labels=number=123-456-7890
"""
}
@staticmethod
def Args(parser):
flags.AddMessageFlags(parser, 'channel-content')
flags.AddNotificationChannelSettingFlags(parser)
def Run(self, args):
client = channels.NotificationChannelsClient()
messages = client.messages
channel = util.GetNotificationChannelFromArgs(args, messages)
if args.user_labels:
channel.userLabels = util.ParseCreateLabels(
args.user_labels, messages.NotificationChannel.UserLabelsValue)
if args.channel_labels:
channel.labels = util.ParseCreateLabels(
args.channel_labels, messages.NotificationChannel.LabelsValue)
project_ref = (
projects_util.ParseProject(properties.VALUES.core.project.Get()))
result = client.Create(project_ref, channel)
log.CreatedResource(result.name, 'notification channel')
return result

View File

@@ -0,0 +1,31 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: Delete a notification channel.
description: |
Delete a notification channel.
## EXAMPLES
The following command will delete channel `projects/12345/notificationChannels/67890`, but
only if the channel is not actively referenced by existing alerting policies:
$ {command} "projects/12345/notificationChannels/67890"
The following command will delete channel `projects/12345/notificationChannels/67890`, even
if the channel is still actively referenced by alerting policies; if an existing policy
references the channel, it will be modified as a side-effect to remove the channel.
$ {command} "projects/12345/notificationChannels/67890" --force
request:
collection: monitoring.projects.notificationChannels
arguments:
resource:
help_text: The notification channel to delete.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:notification_channel
params:
- arg_name: force
api_field: force
action: store_true
help_text: If true, the notification channel will be deleted regardless of its
use in alerting policies (the policies will be updated to remove the channel).

View File

@@ -0,0 +1,21 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: Describe a notification channel.
description: |
Describe a notification channel.
This retrieves the details about a channel by its programmatic name.
## EXAMPLES
The following command prints out the JSON format of the configuration for the
`NotificationChannel` with the name `projects/12345/notificationChannels/67890`:
$ {command} "projects/12345/notificationChannels/67890" --format=json
request:
collection: monitoring.projects.notificationChannels
arguments:
resource:
help_text: The notification channel to describe.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:notification_channel

View File

@@ -0,0 +1,40 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: List notification channels.
description: |
List notification channels.
This operation supports both --filter and --sort-by arguments.
## EXAMPLES
The following command lists all notification channels where the user label "team" has
value "foo" and where the notification channel is of an "email" type:
$ {command} --filter='type="email" AND userLabels.team="foo"'
The following command lists all of the email addresses alphabetically:
$ {command} \
--filter='type="email"' \
--sort-by=labels.email_address \
--format="value(labels.email_address)"
request:
collection: monitoring.projects.notificationChannels
modify_request_hooks:
- googlecloudsdk.command_lib.monitoring.hooks:ModifyListNotificationChannelsRequest
- googlecloudsdk.command_lib.monitoring.hooks:AddOrderByToListRequest
response:
id_field: name
arguments:
resource:
help_text: The project to list notification channels from.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:project
params:
- arg_name: type
help_text: List only notification channels of this type.
output:
format: yaml

View File

@@ -0,0 +1,134 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring channels update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import channels
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import resource_args
from googlecloudsdk.command_lib.monitoring import util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Create(base.CreateCommand):
"""Update a notification channel."""
detailed_help = {
'DESCRIPTION':
"""\
Updates a notification channel.
If `--channel-content` or `--channel-content-from-file` are specified:
* --fields can be specified; only the specified fields will be
updated.
* Alternatively, the channel will be replaced with the provided
channel. The channel can be modified further using the flags
from the notification channel settings group below.
Otherwise, the channel will be updated with the values specified in
the flags from the notification channel settings group.
For information about the JSON/YAML format of a notification channel:
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.notificationChannels
*Note:* When specifying the Channel as a YAML/JSON, the use of
`channelLabels` as an alternative name for `labels` is supported.
## EXAMPLES
The following command updates an existing email notification channel to point from
its original email address to "newaddress@newdomain.tld":
$ {command} "projects/12345/notificationChannels/67890" \
--update-channel-labels=email_address=newaddress@newdomain.tld
"""
}
@staticmethod
def Args(parser):
channel_arg = resource_args.CreateNotificationChannelResourceArg(
'channel', 'to update')
resource_args.AddResourceArgs(parser, [channel_arg])
flags.AddMessageFlags(parser, 'channel-content')
flags.AddFieldsFlagsWithMutuallyExclusiveSettings(
parser,
fields_help='The list of fields to update. Must specify '
'`--channel-content` or `--channel-content-from-file` '
'if using this flag.',
add_settings_func=flags.AddNotificationChannelSettingFlags,
update=True)
def Run(self, args):
util.ValidateUpdateArgsSpecified(
args,
['channel_content', 'channel_content_from_file', 'display_name',
'enabled', 'type', 'description', 'fields', 'update_user_labels',
'remove_user_labels', 'clear_user_labels', 'update_channel_labels',
'remove_channel_labels', 'clear_channel_labels'],
'channel')
flags.ValidateNotificationChannelUpdateArgs(args)
client = channels.NotificationChannelsClient()
messages = client.messages
channel_ref = args.CONCEPTS.channel.Parse()
passed_yaml_channel = False
channel_str = args.channel_content or args.channel_content_from_file
if channel_str:
passed_yaml_channel = True
channel = util.MessageFromString(
channel_str, messages.NotificationChannel, 'NotificationChannel',
field_remappings=util.CHANNELS_FIELD_REMAPPINGS)
else:
channel = client.Get(channel_ref)
if not args.fields:
enabled = args.enabled if args.IsSpecified('enabled') else None
fields = []
util.ModifyNotificationChannel(channel,
channel_type=args.type,
display_name=args.display_name,
description=args.description,
enabled=enabled,
field_masks=fields)
new_user_labels = util.ProcessUpdateLabels(
args, 'user_labels', messages.NotificationChannel.UserLabelsValue,
channel.userLabels)
new_channel_labels = util.ProcessUpdateLabels(
args, 'channel_labels', messages.NotificationChannel.LabelsValue,
channel.labels)
# TODO(b/73120276): Use field masks per key for label updates.
if new_user_labels:
channel.userLabels = new_user_labels
fields.append('user_labels')
if new_channel_labels:
channel.labels = new_channel_labels
fields.append('labels')
# For more robust concurrent updates, use update masks if we're not
# trying to replace the channel using --channel-content or
# --channel-content-from-file.
fields = None if passed_yaml_channel else ','.join(sorted(fields))
else:
fields = ','.join(args.fields)
return client.Update(channel_ref, channel, fields)

View File

@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# 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.
"""The command group for Cloud Monitoring dashboards."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Web(base.Group):
"""Manage Cloud Monitoring dashboards.
The {command} group lets you manage Monitoring dashboards.
More information on managing dashboards can be found here:
https://cloud.google.com/monitoring/dashboards/api-dashboard
"""

View File

@@ -0,0 +1,115 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Create a new Cloud Monitoring dashboard.
description: |
Create a new Monitoring dashboard. A dashboard can be specified as a
JSON/YAML value passed in as a string through the `--config` flag or
as a file through the `--config-from-file` flag. Validate a dashboard
config without saving by setting the `--validate-only` flag.
For information about the format of a dashboard:
https://cloud.google.com/monitoring/api/ref_v3/rest/v1/projects.dashboards
examples: |
To create a dashboard with a YAML config, run:
$ {command} --config='''
displayName: New Dashboard
gridLayout:
widgets:
- text:
content: Hello World
'''
To validate a dashboard and not save it, run:
$ {command} --validate-only --config='''
displayName: New Dashboard
gridLayout:
widgets:
- text:
content: Hello World
'''
To create a dashboard with a JSON config, run:
$ {command} --config='''
{
"displayName": "New Dashboard",
"gridLayout": {
"widgets": [
{
"text": {
"content": "Hello World",
}
}
]
},
}
'''
To create a dashboard with a specific dashboard ID, run:
$ {command} --config='''
name: projects/MY-PROJECT/dashboards/MY-DASHBOARD
displayName: New Dashboard
gridLayout:
widgets:
- text:
content: Hello World
'''
To create a dashboard within a specific project, run:
$ {command} --project=MY-PROJECT --config='''
displayName: New Dashboard
gridLayout:
widgets:
- text:
content: Hello World
'''
To create a dashboard with a file, run:
$ {command} --config-from-file=MY-FILE
Sample contents of MY-FILE:
displayName: New Dashboard
gridLayout:
widgets:
- text:
content: Hello World
arguments:
resource:
help_text: |
The dashboard to create.
is_parent_resource: true
spec: !REF googlecloudsdk.command_lib.monitoring.resources:project
params:
- group:
mutex: true
required: true
params:
- arg_name: config
processor: googlecloudsdk.core.yaml:load
api_field: dashboard
help_text: |
Dashboard configuration, in either JSON or YAML format, as a string.
- arg_name: config-from-file
type: "googlecloudsdk.calliope.arg_parsers:FileContents:"
processor: googlecloudsdk.core.yaml:load
api_field: dashboard
help_text: |
Path to a JSON or YAML file containing the dashboard configuration.
- arg_name: validate-only
type: bool
default: false
api_field: validateOnly
help_text: |
When set, validate the dashboard but do not save it.
request:
collection: monitoring.projects.dashboards
api_version: v1

View File

@@ -0,0 +1,28 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Delete a Cloud Monitoring dashboard.
description: Delete a Monitoring dashboard.
examples: |
To delete a dashboard, run:
$ {command} MY-DASHBOARD
To delete a dashboard contained within a specific project, run:
$ {command} MY-DASHBOARD --project=MY-PROJECT
To delete a dashboard with a fully qualified dashboard ID, run:
$ {command} projects/MY-PROJECT/dashboards/MY-DASHBOARD
arguments:
resource:
help_text: |
The dashboard to delete.
is_positional: true
spec: !REF googlecloudsdk.command_lib.monitoring.resources:dashboard
request:
collection: monitoring.projects.dashboards
api_version: v1

View File

@@ -0,0 +1,32 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Describe a Cloud Monitoring dashboard.
description: Describe a Monitoring dashboard.
examples: |
To describe a dashboard, run:
$ {command} MY-DASHBOARD
To describe a dashboard in JSON, run:
$ {command} MY-DASHBOARD --format=json
To describe a dashboard contained within a specific project, run:
$ {command} MY-DASHBOARD --project=MY-PROJECT
To describe a dashboard with a fully qualified dashboard ID, run:
$ {command} projects/MY-PROJECT/dashboards/MY-DASHBOARD
arguments:
resource:
help_text: |
The dashboard to describe.
is_positional: true
spec: !REF googlecloudsdk.command_lib.monitoring.resources:dashboard
request:
collection: monitoring.projects.dashboards
api_version: v1

View File

@@ -0,0 +1,25 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: List Cloud Monitoring dashboards.
description: List Monitoring dashboards.
examples: |
To list dashboards, run:
$ {command}
To list dashboards for a specific project, run:
$ {command} --project=MY-PROJECT
arguments:
resource:
help_text: The project to list dashboards from.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:project
request:
collection: monitoring.projects.dashboards
api_version: v1
response:
id_field: name

View File

@@ -0,0 +1,95 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: |
Update a Cloud Monitoring dashboard.
description: |
Update a Monitoring dashboard. The updated dashboard can be specified as a
JSON/YAML value passed in as a string through the `--config` flag or
as a file through the `--config-from-file` flag.
Note: Etags are used to prevent concurrent updates to the same dashboard. The latest etag can
be found in a `describe` or `list` response.
For information about the format of a dashboard:
https://cloud.google.com/monitoring/api/ref_v3/rest/v1/projects.dashboards
examples: |
To update a dashboard with a YAML config, run:
$ {command} MY-DASHBOARD --config='''
displayName: New Dashboard with New Display Name
etag: 40d1040034db4e5a9dee931ec1b12c0d
gridLayout:
widgets:
- text:
content: Hello World
'''
To update a dashboard with a JSON config, run:
$ {command} MY-DASHBOARD --config='''
{
"displayName": "New Dashboard with New Display Name",
"etag": "40d1040034db4e5a9dee931ec1b12c0d",
"gridLayout": {
"widgets": [
{
"text": {
"content": "Hello World",
}
}
]
},
}
'''
To update a dashboard within a specific project, run:
$ {command} MY-DASHBOARD --project=MY-PROJECT --config='''
displayName: New Dashboard with New Display Name
etag: 40d1040034db4e5a9dee931ec1b12c0d
gridLayout:
widgets:
- text:
content: Hello World
'''
To update a dashboard with a file, run:
$ {command} MY-DASHBOARD --config-from-file=MY-FILE
Sample contents of MY-FILE:
displayName: New Dashboard with new Display Name
etag: 40d1040034db4e5a9dee931ec1b12c0d
gridLayout:
widgets:
- text:
content: Hello World
arguments:
resource:
help_text: |
The dashboard to update.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:dashboard
params:
- group:
mutex: true
required: true
params:
- arg_name: config
api_field: dashboard
processor: googlecloudsdk.core.yaml:load
help_text: |
Dashboard configuration, in either JSON or YAML format, as a string.
- arg_name: config-from-file
api_field: dashboard
type: "googlecloudsdk.calliope.arg_parsers:FileContents:"
processor: googlecloudsdk.core.yaml:load
help_text: |
Path to a JSON or YAML file containing the dashboard configuration.
request:
collection: monitoring.projects.dashboards
method: patch
api_version: v1

View File

@@ -0,0 +1,32 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# 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.
"""The command group for Cloud Monitoring Metrics Scopes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Web(base.Group):
"""Manage Cloud Monitoring Metrics Scopes.
The {command} group lets you manage Monitoring metrics scopes.
More information on managing metrics scopes can be found here:
https://cloud.google.com/monitoring/settings/manage-api
"""

View File

@@ -0,0 +1,71 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# 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.
"""Command to create a monitored project in a metrics scope."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import metrics_scopes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import util as monitoring_util
from googlecloudsdk.core import log
class Create(base.CreateCommand):
"""Create a monitored project in a metrics scope.
This command can fail for the following reasons:
* The projects specified do not exist.
* The active account does not have permission to access one of the given
project.
* The monitored project already exists in the metrics scope.
More details can be found at
https://cloud.google.com/monitoring/api/ref_v3/rest/v1/locations.global.metricsScopes.projects/create
## EXAMPLES
The following command adds a monitored project with the ID
`monitored-project-1` to a metrics scope with project id `metrics-scope-1`
assuming the `metrics-scope-1` is the default project:
$ {command} projects/monitored-project-1
The following command adds a monitored project with the ID
`monitored-project-1` to a metrics scope with project id `metrics-scope-1`:
$ {command} projects/monitored-project-1 --project=metrics-scope-1
$ {command}
locations/global/metricsScopes/metrics-scope-1/projects/monitored-project-1
"""
@staticmethod
def Args(parser):
flags.GetMonitoredResourceContainerNameFlag('create').AddToParser(parser)
def Run(self, args):
client = metrics_scopes.MetricsScopeClient()
metrics_scope_def, monitored_project_ref = (
monitoring_util.ParseMonitoredProject(
args.monitored_resource_container_name, True
)
)
result = client.Create(metrics_scope_def, monitored_project_ref)
log.CreatedResource(
client.MonitoredProjectName(metrics_scope_def, monitored_project_ref),
'monitored project')
return result

View File

@@ -0,0 +1,70 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# 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.
"""Command to create a monitored project in a metrics scope."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import metrics_scopes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import util as monitoring_util
from googlecloudsdk.core import log
class Delete(base.DeleteCommand):
"""Delete a monitored project in a metrics scope.
This command can fail for the following reasons:
* The projects specified do not exist.
* The active account does not have permission to access one of the given
project.
More details can be found at
https://cloud.google.com/monitoring/api/ref_v3/rest/v1/locations.global.metricsScopes.projects/delete
## EXAMPLES
The following command adds a monitored project with the ID
`monitored-project-1` to a metrics scope with project id `metrics-scope-1`
assuming the `metrics-scope-1` is the default project:
$ {command} projects/monitored-project-1
The following command adds a monitored project with the ID
`monitored-project-1` to a metrics scope with project id `metrics-scope-1`:
$ {command} projects/monitored-project-1 --project=metrics-scope-1
$ {command}
locations/global/metricsScopes/metrics-scope-1/projects/monitored-project-1
"""
@staticmethod
def Args(parser):
flags.GetMonitoredResourceContainerNameFlag('delete').AddToParser(parser)
def Run(self, args):
client = metrics_scopes.MetricsScopeClient()
metrics_scope_ref, monitored_project_ref = (
monitoring_util.ParseMonitoredProject(
args.monitored_resource_container_name, True
)
)
result = client.Delete(metrics_scope_ref, monitored_project_ref)
log.DeletedResource(
client.MonitoredProjectName(metrics_scope_ref, monitored_project_ref),
'monitored project')
return result

View File

@@ -0,0 +1,28 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: Describe a Cloud Monitoring metrics scope.
description: |
Describe a Cloud Monitoring metrics scope along with the list of projects it is monitoring.
More details can be found at https://cloud.google.com/monitoring/api/ref_v3/rest/v1/locations.global.metricsScopes/get
examples: |
To describe a metrics scope contained within a specific project, run:
$ {command} MY-METRICS-SCOPE-PROJECT-ID
To describe a metrics scope in JSON, run:
$ {command} MY-METRICS-SCOPE-PROJECT-ID --format=json
To describe a metrics scope with a fully qualified metrics scope ID, run:
$ {command} locations/global/metricsScopes/MY-METRICS-SCOPE-PROJECT-ID
arguments:
resource:
help_text: |
The metrics scope to describe.
is_positional: true
spec: !REF googlecloudsdk.command_lib.monitoring.resources:metrics_scope
request:
collection: monitoring.locations.global.metricsScopes
api_version: v1

View File

@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# 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.
"""Command to create a monitored project in a metrics scope."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import metrics_scopes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import util as monitoring_util
from googlecloudsdk.command_lib.projects import util as command_lib_util
class List(base.ListCommand):
"""List the metrics scopes monitoring the specified monitored resource container.
This command can fail for the following reasons:
* The projects specified do not exist.
* The active account does not have permission to access one of the given
project.
More details can be found at
https://cloud.google.com/monitoring/api/ref_v3/rest/v1/locations.global.metricsScopes/listMetricsScopesByMonitoredProject
## EXAMPLES
To list the metrics scopes monitoring MY-PROJECT-ID
$ {command} projects/MY-PROJECT-ID
"""
@staticmethod
def Args(parser):
flags.GetMonitoredResourceContainerNameFlag('list').AddToParser(parser)
def Run(self, args):
client = metrics_scopes.MetricsScopeClient()
_, resource_id = monitoring_util.ParseMonitoredResourceContainer(
args.monitored_resource_container_name, True
)
project_ref = command_lib_util.ParseProject(resource_id)
result = client.List(project_ref)
return result

View File

@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""Command group for Cloud Monitoring policies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(
base.ReleaseTrack.GA, base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA
)
@base.DefaultUniverseOnly
class Policies(base.Group):
"""Manage Cloud Monitoring alerting policies."""
detailed_help = {
'DESCRIPTION': """\
Manage Monitoring alerting policies.
More information can be found here:
https://cloud.google.com/monitoring/api/v3/
"""
}

View File

@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""Command group for Cloud Monitoring Alert Policy conditions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(
base.ReleaseTrack.GA, base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA
)
@base.DefaultUniverseOnly
class Conditions(base.Group):
"""Manage Cloud Monitoring alerting policy conditions."""
detailed_help = {
'DESCRIPTION': """\
Manage Monitoring alerting policies conditions.
More information can be found here:
https://cloud.google.com/monitoring/api/v3/
"""
}

View File

@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring policies conditions create` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import policies
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import resource_args
from googlecloudsdk.command_lib.monitoring import util
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create a condition in an alerting policy."""
@staticmethod
def Args(parser):
condition_arg = resource_args.CreateAlertPolicyResourceArg(
'to add a condition to.')
resource_args.AddResourceArgs(parser, [condition_arg])
flags.AddMessageFlags(parser, 'condition')
flags.AddConditionSettingsFlags(parser)
def Run(self, args):
client = policies.AlertPolicyClient()
messages = client.messages
policy_ref = args.CONCEPTS.alert_policy.Parse()
condition = util.GetConditionFromArgs(args, messages)
policy = client.Get(policy_ref)
policy.conditions.append(condition)
response = client.Update(policy_ref, policy)
return response

View File

@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring policies conditions delete` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import policies
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import resource_args
from googlecloudsdk.command_lib.monitoring import util
from googlecloudsdk.core import log
class Delete(base.CreateCommand):
"""Delete a condition in an alerting policy.
Delete a condition in an alerting policy. If the specified condition does
not exist, this command will fail with an error. This will not delete
the policy if no conditions exist.
"""
@staticmethod
def Args(parser):
condition_arg = resource_args.CreateConditionResourceArg('delete')
resource_args.AddResourceArgs(parser, [condition_arg])
def Run(self, args):
client = policies.AlertPolicyClient()
condition_ref = args.CONCEPTS.condition.Parse()
policy_ref = condition_ref.Parent()
policy = client.Get(policy_ref)
policy = util.RemoveConditionFromPolicy(condition_ref.RelativeName(),
policy)
response = client.Update(policy_ref, policy)
log.DeletedResource(condition_ref.RelativeName(), 'Condition')
return response

View File

@@ -0,0 +1,45 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring policies conditions describe` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import policies
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import resource_args
from googlecloudsdk.command_lib.monitoring import util
class Describe(base.CreateCommand):
"""Describe a condition in a Cloud Monitoring alerting policy."""
@staticmethod
def Args(parser):
condition_arg = resource_args.CreateConditionResourceArg(
'describe')
resource_args.AddResourceArgs(parser, [condition_arg])
def Run(self, args):
client = policies.AlertPolicyClient()
condition_ref = args.CONCEPTS.condition.Parse()
policy_ref = condition_ref.Parent()
policy = client.Get(policy_ref)
condition = util.GetConditionFromPolicy(condition_ref.RelativeName(),
policy)
return condition

View File

@@ -0,0 +1,85 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring policies conditions update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import policies
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import resource_args
from googlecloudsdk.command_lib.monitoring import util
class Update(base.CreateCommand):
"""Update a condition in an alerting policy."""
@staticmethod
def Args(parser):
condition_arg = resource_args.CreateConditionResourceArg('update')
resource_args.AddResourceArgs(parser, [condition_arg])
flags.AddDisplayNameFlag(parser, 'Condition')
flags.AddUpdateableConditionFlags(parser)
def Run(self, args):
util.ValidateUpdateArgsSpecified(
args,
['display_name', 'trigger_count', 'trigger_percent', 'if_value'],
'condition')
client = policies.AlertPolicyClient()
messages = client.messages
condition_ref = args.CONCEPTS.condition.Parse()
policy_ref = condition_ref.Parent()
policy = client.Get(policy_ref)
condition = util.GetConditionFromPolicy(condition_ref.RelativeName(),
policy)
nested_condition = condition.conditionAbsent or condition.conditionThreshold
if args.display_name:
condition.displayName = args.display_name
if args.trigger_count or args.trigger_percent:
nested_condition.trigger = messages.Trigger(
count=args.trigger_count, percent=args.trigger_percent)
if args.if_value is not None:
# Copy existing condition properties into kwargs.
kwargs = {
'trigger_count': nested_condition.trigger.count,
'trigger_percent': nested_condition.trigger.percent,
'aggregations': nested_condition.aggregations,
'duration': nested_condition.duration,
'condition_filter': nested_condition.filter,
'if_value': args.if_value
}
# If any trigger values are specified, overwrite whats in args.
if args.trigger_count or args.trigger_percent:
kwargs['trigger_count'] = args.trigger_count
kwargs['trigger_percent'] = args.trigger_percent
# Clear nested condition messages as this can potentially change.
condition.conditionAbsent = None
condition.conditionThreshold = None
# This will change condition in place.
util.BuildCondition(messages, condition=condition, **kwargs)
return client.Update(policy_ref, policy, fields='conditions')

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# 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.
"""Command group for managing Monitoring alert policy configurations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Config(base.Group):
"""Manage Monitoring alert policy configurations."""

View File

@@ -0,0 +1,38 @@
release_tracks: [ALPHA]
command_type: CONFIG_EXPORT
help_text:
brief: Export the configuration for a Monitoring alert policy.
description: |
*{command}* exports the configuration for a Monitoring alert policy.
Alert policy configurations can be exported in
Kubernetes Resource Model (krm) or Terraform HCL formats. The
default format is `krm`.
Specifying `--all` allows you to export the configurations for all
alert policies within the project.
Specifying `--path` allows you to export the configuration(s) to
a local directory.
examples: |
To export the configuration for an alert policy, run:
$ {command} my-alert-policy
To export the configuration for an alert policy to a file, run:
$ {command} my-alert-policy --path=/path/to/dir/
To export the configuration for an alert policy in Terraform
HCL format, run:
$ {command} my-alert-policy --resource-format=terraform
To export the configurations for all alert policies within a
project, run:
$ {command} --all
arguments:
resource:
help_text: Alert policy to export the configuration for.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:policy

View File

@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring policies create` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import policies
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import resource_args
from googlecloudsdk.command_lib.monitoring import util
from googlecloudsdk.command_lib.projects import util as projects_util
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create a new alerting policy."""
detailed_help = {
'DESCRIPTION': """\
Creates a new alerting policy. An alert policy can be specified as a
JSON/YAML value passed in as a string through the `--policy` flag or
as a file through the `--policy-from-file` flag. A basic policy can
also be specified through command line flags. If a policy is specified
through `--policy` or `--policy-from-file`, and additional flags are
supplied, the flags will override the policy's settings and a
specified condition will be appended to the list of conditions.
For information about the JSON/YAML format of an alerting policy:
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.alertPolicies
"""
}
@staticmethod
def Args(parser):
flags.AddMessageFlags(parser, 'policy')
flags.AddPolicySettingsFlags(parser)
flags.AddConditionSettingsFlags(parser)
channels_resource_arg = resource_args.CreateNotificationChannelResourceArg(
arg_name='--notification-channels',
extra_help="""\
to be added to the policy. These should be the resource names (not
the display name) of the channels. Acceptable formats are:
* Channel Name: `my-channel`
* The project specified through `--project` or the default
project defined by the `core/project` property will be used,
in that order.
* Channel Relative Name:
`projects/my-project/notificationChannels/channel-id0`
* Channel URI:
https://monitoring.{universe_domain}/v3/projects/my-project/notificationChannels/channel-id0
""".format(
universe_domain=properties.VALUES.core.universe_domain.Get()
),
required=False,
plural=True,
)
resource_args.AddResourceArgs(parser, [channels_resource_arg])
def Run(self, args):
client = policies.AlertPolicyClient()
messages = client.messages
policy = util.CreateAlertPolicyFromArgs(args, client.messages)
if args.user_labels:
policy.userLabels = util.ParseCreateLabels(
args.user_labels, messages.AlertPolicy.UserLabelsValue)
project_ref = (
projects_util.ParseProject(properties.VALUES.core.project.Get()))
result = client.Create(project_ref, policy)
log.CreatedResource(result.name, 'alert policy')
return result

View File

@@ -0,0 +1,11 @@
- help_text:
brief: Delete a Cloud Monitoring alerting policy.
description: Delete a Monitoring alerting policy.
request:
collection: monitoring.projects.alertPolicies
arguments:
resource:
help_text: The alerting policy to delete.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:policy

View File

@@ -0,0 +1,11 @@
- help_text:
brief: Describe an alerting policy.
description: Describe an alerting policy.
request:
collection: monitoring.projects.alertPolicies
arguments:
resource:
help_text: The alerting policy to describe.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:policy

View File

@@ -0,0 +1,40 @@
- help_text:
brief: List alerting policies.
description: List alerting policies.
examples: |
To order your results first by the team key in user_labels and
then the policy's display name:
$ {command} --sort-by user_label.team,display_name
To order your results in reverse order, you can add either '~' or '-'
in front of the field name:
$ {command} --sort-by "-display_name"
To return results with non-empty display names or descriptions:
$ {command} --filter "(NOT display_name.empty OR NOT description.empty)"
To return results whose descriptions contain the word 'cloud':
$ {command} --filter "description:(cloud)"
Please find all supported fields at
https://cloud.google.com/monitoring/api/v3/sorting-and-filtering#alertpolicy.
request:
collection: monitoring.projects.alertPolicies
modify_request_hooks:
- googlecloudsdk.command_lib.monitoring.hooks:AddOrderByToListRequest
response:
id_field: name
arguments:
resource:
help_text: The Cloud Monitoring Workspace from which to list policies from.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:project
output:
format: yaml

View File

@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring policies migrate` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import channels
from googlecloudsdk.api_lib.monitoring import policies
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import util
from googlecloudsdk.command_lib.projects import util as projects_util
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_io
class Migrate(base.CreateCommand):
"""Migrate a Prometheus configuration file to Cloud Monitoring."""
detailed_help = {'DESCRIPTION': """\
Creates new alerting policies and/or notification channels based on
provided Prometheus files. The rules YAML file, which holds the alert
rules, must be specified as a file through the
`--policies-from-prometheus-alert-rules-yaml` flag.
"""}
@staticmethod
def Args(parser):
flags.AddMigrateFlags(parser)
def Run(self, args):
notification_channel_client = channels.NotificationChannelsClient()
alert_policy_client = policies.AlertPolicyClient()
promql_flags = [
'--policies-from-prometheus-alert-rules-yaml',
'--channels-from-prometheus-alertmanager-yaml',
]
util.ValidateAtleastOneSpecified(args, promql_flags)
project_ref = projects_util.ParseProject(
properties.VALUES.core.project.Get()
)
if not console_io.PromptContinue(
message=(
'Each call of the migration tool will create a new set of alert'
' policies and/or notification channels. Thus, the migration tool'
' should not be used to update existing alert policies and/or'
' notification channels.'
),
default=False,
):
return
notification_channels = util.CreateNotificationChannelsFromArgs(
args, alert_policy_client.messages
)
created_channel_names = []
for channel in notification_channels:
result = notification_channel_client.Create(project_ref, channel)
log.CreatedResource(result.name, 'notification channel')
created_channel_names.append(result.name)
promql_policies = util.CreatePromQLPoliciesFromArgs(
args, alert_policy_client.messages, created_channel_names
)
policies_results = []
# might be good to have a rollback mechanism for when a subset of the
# creations fails. In this case, should we delete the already
# created policies?
for policy in promql_policies:
result = alert_policy_client.Create(project_ref, policy)
log.CreatedResource(result.name, 'alert policy')
policies_results.append(result)
return policies_results

View File

@@ -0,0 +1,125 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring policies update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import policies
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import resource_args
from googlecloudsdk.command_lib.monitoring import util
from googlecloudsdk.command_lib.util.args import repeated
class Update(base.CreateCommand):
"""Updates an alerting policy."""
detailed_help = {
'DESCRIPTION': """\
Updates an alerting policy.
If `--policy` or `--policy-from-file` are specified:
* If `--fields` is specified, the only the specified fields will be
updated.
* Else, the policy will be replaced with the provided policy. The
policy can be modified further using the flags from the Policy
Settings group below.
Otherwise, the policy will be updated with the values specified in
the flags from the Policy Settings group.
For information about the JSON/YAML format of an alerting policy:
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.alertPolicies
"""
}
@staticmethod
def Args(parser):
resources = [
resource_args.CreateAlertPolicyResourceArg('to be updated.')]
resource_args.AddResourceArgs(parser, resources)
flags.AddMessageFlags(parser, 'policy')
flags.AddFieldsFlagsWithMutuallyExclusiveSettings(
parser,
fields_help=('The list of fields to update. Must specify `--policy` or '
'`--policy-from-file` if using this flag.'),
add_settings_func=flags.AddPolicySettingsFlags,
fields_choices=['disabled', 'notificationChannels'],
update=True)
def Run(self, args):
util.ValidateUpdateArgsSpecified(
args,
['policy', 'policy_from_file', 'display_name', 'enabled',
'add_notification_channels', 'remove_notification_channels',
'set_notification_channels',
'clear_notification_channels', 'documentation', 'documentation_format',
'documentation_from_file', 'fields', 'update_user_labels',
'remove_user_labels', 'clear_user_labels'],
'policy')
flags.ValidateAlertPolicyUpdateArgs(args)
client = policies.AlertPolicyClient()
messages = client.messages
passed_yaml_policy = False
policy_ref = args.CONCEPTS.alert_policy.Parse()
if args.policy or args.policy_from_file:
passed_yaml_policy = True
policy = util.GetBasePolicyMessageFromArgs(args, messages.AlertPolicy)
else:
# If a full policy isn't given, we want to do Read-Modify-Write.
policy = client.Get(policy_ref)
if not args.fields:
channels = policy.notificationChannels
new_channels = repeated.ParseResourceNameArgs(
args, 'notification_channels', lambda: channels,
util.ParseNotificationChannel)
enabled = args.enabled if args.IsSpecified('enabled') else None
fields = []
util.ModifyAlertPolicy(
policy,
messages,
display_name=args.display_name,
documentation_content=
args.documentation or args.documentation_from_file,
documentation_format=args.documentation_format,
enabled=enabled,
channels=new_channels,
field_masks=fields)
new_labels = util.ProcessUpdateLabels(
args,
'user_labels',
messages.AlertPolicy.UserLabelsValue,
policy.userLabels)
if new_labels:
policy.userLabels = new_labels
# TODO(b/73120276): Use field masks per key for label updates.
fields.append('user_labels')
# For more robust concurrent updates, use update masks if we're not
# trying to replace the policy using --policy or --policy-from-file.
fields = None if passed_yaml_policy else ','.join(sorted(fields))
else:
fields = ','.join(args.fields)
return client.Update(policy_ref, policy, fields)

View File

@@ -0,0 +1,36 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# 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.
"""Command group for Cloud Monitoring snoozes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Snoozes(base.Group):
"""Manage Cloud Monitoring snoozes."""
detailed_help = {
'DESCRIPTION': """\
Manage Monitoring snoozes.
More information can be found here:
https://cloud.google.com/monitoring/api/v3/
"""
}

View File

@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring snoozes cancel` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import snoozes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import resource_args
from googlecloudsdk.command_lib.monitoring import util
from googlecloudsdk.core import log
from googlecloudsdk.core.util import times
class Cancel(base.UpdateCommand):
"""Cancels a snooze."""
detailed_help = {
'DESCRIPTION': """\
Cancel a snooze.
If the start time is in the future, then
this command is equivalent to:
* update --start-time="+PT1S" --end-time="+PT1S
Otherwise, if the start time is past and the ending time is in the
future, then this command is equivalent to:
* update --end-time="+PT1S
For information about the JSON/YAML format of a snooze:
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.snoozes
""",
'EXAMPLES': """\
To cancel a snooze, run:
$ {command} MY-SNOOZE
To cancel a snooze contained within a specific project, run:
$ {command} MY-SNOOZE --project=MY-PROJECT
To cancel a snooze with a fully qualified snooze ID, run:
$ {command} projects/MY-PROJECT/snoozes/MY-SNOOZE
"""
}
@staticmethod
def Args(parser):
resources = [
resource_args.CreateSnoozeResourceArg('to be canceled.')]
resource_args.AddResourceArgs(parser, resources)
def Run(self, args):
client = snoozes.SnoozeClient()
messages = client.messages
snooze_ref = args.CONCEPTS.snooze.Parse()
# TODO(b/271427290): Replace 500 with 404 in api
snooze = client.Get(snooze_ref)
start_time = times.ParseDateTime(snooze.interval.startTime)
end_time = times.ParseDateTime('+PT1S')
if start_time > times.Now():
start_time = end_time
util.ModifySnooze(
snooze,
messages,
start_time=start_time,
end_time=end_time)
result = client.Update(snooze_ref, snooze, None)
log.UpdatedResource(result.name, 'snooze')
return result

View File

@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring snoozes create` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import snoozes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import util
from googlecloudsdk.command_lib.projects import util as projects_util
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create a new snooze."""
detailed_help = {
'DESCRIPTION': """\
Creates a new snooze. A snooze can be specified as a JSON/YAML value
passed in as a file through the `--snooze-from-file` flag. A snooze
can also be specified through command line flags. If a snooze is
specified through `--snooze-from-file`, and additional flags are
supplied, the flags will override the snooze's settings.
For information about the JSON/YAML format of a snooze:
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.snoozes
""",
'EXAMPLES': """\
To create a snooze with command-line options, run:
$ {command} --criteria-policies=LIST_OF_POLICIES
--criteria-filter=FILTER
--display-name=DISPLAY_NAME --start-time=START_TIME
--end-time=END_TIME
To create a snooze with a file, run:
$ {command} --snooze-from-file=MY-FILE
Sample contents of MY-FILE:
criteria:
policies:
- projects/MY-PROJECT/alertPolicies/MY-POLICY
filter: 'resource.labels.zone="us-central1-a" AND resource.labels.instance_id="1234567890"'
interval:
startTime: '2024-03-01T08:00:00Z'
endTime: '2024-03-08T04:59:59.500Z'
displayName: New Snooze
""",
}
@staticmethod
def Args(parser):
flags.AddFileMessageFlag(parser, 'snooze')
flags.AddSnoozeSettingsFlags(parser)
def Run(self, args):
client = snoozes.SnoozeClient()
snooze = util.CreateSnoozeFromArgs(args, client.messages)
project_ref = (
projects_util.ParseProject(properties.VALUES.core.project.Get()))
result = client.Create(project_ref, snooze)
log.CreatedResource(result.name, 'snooze')
return result

View File

@@ -0,0 +1,61 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring snoozes describe` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import snoozes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import resource_args
class Describe(base.DescribeCommand):
"""Describe a snooze."""
detailed_help = {
'EXAMPLES': """\
To describe a snooze, run:
$ {command} MY-SNOOZE
To describe a snooze in JSON, run:
$ {command} MY-SNOOZE --format=json
To describe a snooze contained within a specific project, run:
$ {command} MY-SNOOZE --project=MY-PROJECT
To describe a snooze with a fully qualified snooze ID, run:
$ {command} projects/MY-PROJECT/snoozes/MY-SNOOZE
"""
}
@staticmethod
def Args(parser):
resources = [
resource_args.CreateSnoozeResourceArg('to be described.')]
resource_args.AddResourceArgs(parser, resources)
def Run(self, args):
client = snoozes.SnoozeClient()
snooze_ref = args.CONCEPTS.snooze.Parse()
# TODO(b/271427290): Replace 500 with 404 in api
result = client.Get(snooze_ref)
return result

View File

@@ -0,0 +1,36 @@
- help_text:
brief: List snoozes.
description: List snoozes.
examples: |
To order your results first by the snooze's display name and then the end time:
$ {command} --sort-by=display_name,interval.end_time
To order your results in reverse order, you can add '~' in front of the field name:
$ {command} --sort-by="~display_name"
To return results with expired snoozes only:
$ {command} --filter="interval.end_time<+PT1S"
To return results whose display name contain the word 'cloud':
$ {command} --filter="display_name:(cloud)"
More information can be found at
https://cloud.google.com/sdk/gcloud/reference/topic/filters
request:
collection: monitoring.projects.snoozes
response:
id_field: name
arguments:
resource:
help_text: The Cloud Monitoring Workspace from which to list snoozes from.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:project
output:
format: yaml

View File

@@ -0,0 +1,133 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring snoozes update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import snoozes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import resource_args
from googlecloudsdk.command_lib.monitoring import util
from googlecloudsdk.core import log
class Update(base.UpdateCommand):
"""Updates a snooze."""
detailed_help = {
'DESCRIPTION': """\
Update a snooze.
If `--snooze-from-file` is specified, then the update rules depend on
the value of the (optional) `--fields` flag:
* If `--fields` is specified, then only the specified fields of the
snooze are updated.
* Else, all fields of the snooze are replaced. The updated snooze
can be modified further using the flags from the Snooze
Settings group below.
Otherwise, the snooze will be updated with the values specified in
the flags from the Snooze Settings group.
For information about the JSON/YAML format of a snooze:
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.snoozes
""",
'EXAMPLES': """\
To update a snooze time interval with command-line options, run:
$ {command} MY-SNOOZE --start-time=START_TIME --end-time=END_TIME
To update a snooze display name with a file, run:
$ {command} --snooze-from-file=MY-FILE --fields=display_name
Sample contents of MY-FILE:
criteria:
policies:
- projects/MY-PROJECT/alertPolicies/MY-POLICY
interval:
startTime: '2024-03-01T08:00:00Z'
endTime: '2024-03-08T04:59:59.500Z'
displayName: New Snooze with New Display Name
"""
}
@staticmethod
def Args(parser):
resources = [
resource_args.CreateSnoozeResourceArg('to be updated.')]
resource_args.AddResourceArgs(parser, resources)
flags.AddFileMessageFlag(parser, 'snooze')
flags.AddFieldsFlagsWithMutuallyExclusiveSettings(
parser,
fields_help=('The list of fields to update. Must specify '
'`--snooze-from-file` if using this flag.'),
add_settings_func=flags.AddSnoozeSettingsFlags,
update=True)
def Run(self, args):
util.ValidateUpdateArgsSpecified(
args,
['snooze_from_file', 'display_name',
'start_time', 'end_time', 'fields'],
'snooze')
flags.ValidateSnoozeUpdateArgs(args)
client = snoozes.SnoozeClient()
messages = client.messages
passed_yaml_snooze = False
snooze_ref = args.CONCEPTS.snooze.Parse()
if args.snooze_from_file:
passed_yaml_snooze = True
snooze = util.GetBaseSnoozeMessageFromArgs(
args, messages.Snooze, update=True
)
else:
# If a full snooze isn't given, we want to do Read-Modify-Write.
# TODO(b/271427290): Replace 500 with 404 in api
snooze = client.Get(snooze_ref)
# And validate that the snooze reference is not Past/Canceled.
flags.ValidateSnoozeInterval(
snooze,
display_name=args.display_name,
start_time=args.start_time,
end_time=args.end_time,
)
if not args.fields:
fields = []
util.ModifySnooze(
snooze,
messages,
display_name=args.display_name,
start_time=args.start_time,
end_time=args.end_time,
field_masks=fields)
# For more robust concurrent updates, use update masks if we're not
# trying to replace the snooze using --snooze-from-file.
fields = None if passed_yaml_snooze else ','.join(sorted(fields))
else:
fields = ','.join(args.fields)
result = client.Update(snooze_ref, snooze, fields)
log.UpdatedResource(result.name, 'snooze')
return result

View File

@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# 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.
"""Command group for Cloud Monitoring uptime."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
@base.DefaultUniverseOnly
class Uptime(base.Group):
"""Manage Cloud Monitoring uptime checks and synthetic monitors."""
detailed_help = {
'DESCRIPTION': """\
Manage Monitoring uptime checks and synthetic monitors.
More information can be found here:
https://cloud.google.com/monitoring/api/v3/
"""}

View File

@@ -0,0 +1,71 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring uptime create` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import uptime
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import util
from googlecloudsdk.command_lib.projects import util as projects_util
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
class Create(base.CreateCommand):
"""Create a new uptime check or synthetic monitor."""
detailed_help = {
"DESCRIPTION": """\
Create a new uptime check or synthetic monitor.
Flags only apply to uptime checks unless noted that they apply to
synthetic monitors.
For information about the JSON/YAML format of an uptime check:
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.uptimeCheckConfigs
""",
"EXAMPLES": """\
To create an uptime check against a URL, run:
$ {command} DISPLAY_NAME --resource-type=uptime-url
--resource-labels=host=google.com,project_id=PROJECT_ID
To create a synthetic monitor, run:
$ {command} SYNTHETIC_MONITOR_NAME
--synthetic-target=projects/PROJECT_ID/locations/REGION/functions/FUNCTION_NAME
""",
}
@staticmethod
def Args(parser):
flags.AddDisplayNameFlag(
parser, "uptime check or synthetic monitor", positional=True
)
flags.AddUptimeSettingsFlags(parser)
def Run(self, args):
client = uptime.UptimeClient()
uptime_check = util.CreateUptimeFromArgs(args, client.messages)
project_ref = projects_util.ParseProject(
properties.VALUES.core.project.Get()
)
result = client.Create(project_ref, uptime_check)
log.CreatedResource(result.name, "uptime")
return result

View File

@@ -0,0 +1,18 @@
- help_text:
brief: Delete an uptime check or synthetic monitor.
description: Delete an uptime check or synthetic monitor
examples: |
To delete an uptime check or synthetic monitor:
$ {command} CHECK_ID
More information can be found at
https://cloud.google.com/monitoring/uptime-checks/manage#delete.
request:
collection: monitoring.projects.uptimeCheckConfigs
arguments:
resource:
help_text: The uptime check or synthetic monitor to delete.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:uptime_check

View File

@@ -0,0 +1,18 @@
- help_text:
brief: Describe an uptime check or synthetic monitor.
description: Describe an uptime check or synthetic monitor
examples: |
To describe an uptime check or synthetic monitor:
$ {command} CHECK_ID
More information can be found at
https://cloud.google.com/monitoring/uptime-checks/manage#get.
request:
collection: monitoring.projects.uptimeCheckConfigs
arguments:
resource:
help_text: The uptime check or synthetic monitor to describe.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:uptime_check

View File

@@ -0,0 +1,22 @@
- help_text:
brief: List uptime checks and synthetic monitors.
description: List uptime checks and synthetic monitors.
examples: |
To see all uptime checks and synthetic monitors:
$ {command}
More information can be found at
https://cloud.google.com/monitoring/uptime-checks/using-uptime-checks
command_type: LIST
request:
collection: monitoring.projects.uptimeCheckConfigs
response:
id_field: name
arguments:
resource:
help_text: |
The Cloud Monitoring Workspace from which to list uptime checks and synthetic monitors.
spec: !REF googlecloudsdk.command_lib.monitoring.resources:project

View File

@@ -0,0 +1,26 @@
- help_text:
brief: List uptime check server ips.
description: List uptime check egress ips.
examples: |
To see all uptime check servers ips:
$ {command}
More information can be found at
https://cloud.google.com/monitoring/uptime-checks/using-uptime-checks
command_type: LIST
request:
method: list
collection: monitoring.uptimeCheckIps
response:
id_field: ipAddress
arguments:
params:
[]
output:
format: yaml

View File

@@ -0,0 +1,162 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# 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.
"""`gcloud monitoring uptime create` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import uptime
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import flags
from googlecloudsdk.command_lib.monitoring import resource_args
from googlecloudsdk.command_lib.monitoring import util
from googlecloudsdk.command_lib.util.args import repeated
from googlecloudsdk.core import log
class Update(base.UpdateCommand):
"""Update an existing uptime check or synthetic monitor."""
detailed_help = {
'DESCRIPTION': """\
Updates an existing uptime check or synthetic monitor.
Flags only apply to uptime checks unless noted that they apply to
synthetic monitors.
For information about the JSON/YAML format of an uptime check:
https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.uptimeCheckConfigs
""",
'EXAMPLES': """\
To update an uptime check or synthetic monitor, run:
$ {command} CHECK_ID --period=5 --timeout=30
""",}
@staticmethod
def Args(parser):
resources = [resource_args.CreateUptimeResourceArg('to be updated.')]
resource_args.AddResourceArgs(parser, resources)
flags.AddUptimeSettingsFlags(parser, update=True)
def Run(self, args):
client = uptime.UptimeClient()
uptime_check_ref = args.CONCEPTS.check_id.Parse()
uptime_check = client.Get(uptime_check_ref)
new_user_labels = util.ProcessUpdateLabels(
args,
'user_labels',
client.messages.UptimeCheckConfig.UserLabelsValue,
uptime_check.userLabels,
)
new_headers = None
regions = ParseSelectedRegions(uptime_check.selectedRegions)
new_regions = repeated.ParsePrimitiveArgs(args, 'regions', lambda: regions)
status_codes = []
new_status_codes = []
status_classes = []
new_status_classes = []
if uptime_check.httpCheck is not None:
new_headers = util.ProcessUpdateLabels(
args,
'headers',
client.messages.HttpCheck.HeadersValue,
uptime_check.httpCheck.headers,
)
for status in uptime_check.httpCheck.acceptedResponseStatusCodes:
if status.statusClass is not None:
status_classes.append(status.statusClass)
else:
status_codes.append(status.statusValue)
new_status_codes = repeated.ParsePrimitiveArgs(
args, 'status_codes', lambda: status_codes
)
status_classes = ParseStatusClasses(status_classes)
new_status_classes = repeated.ParsePrimitiveArgs(
args, 'status_classes', lambda: status_classes
)
util.ModifyUptimeCheck(
uptime_check,
client.messages,
args,
regions=new_regions,
user_labels=new_user_labels,
headers=new_headers,
status_classes=new_status_classes,
status_codes=new_status_codes,
update=True
)
# Full replace, no fields_mask
result = client.Update(uptime_check_ref, uptime_check, fields=None)
log.UpdatedResource(result.name, 'uptime')
return result
def ParseSelectedRegions(selected_regions):
"""Convert previously selected regions from enum to flag for update logic."""
client = uptime.UptimeClient()
messages = client.messages
region_mapping = {
messages.UptimeCheckConfig.SelectedRegionsValueListEntryValuesEnum.USA_OREGON: (
'usa-oregon'
),
messages.UptimeCheckConfig.SelectedRegionsValueListEntryValuesEnum.USA_IOWA: (
'usa-iowa'
),
messages.UptimeCheckConfig.SelectedRegionsValueListEntryValuesEnum.USA_VIRGINIA: (
'usa-virginia'
),
messages.UptimeCheckConfig.SelectedRegionsValueListEntryValuesEnum.EUROPE: (
'europe'
),
messages.UptimeCheckConfig.SelectedRegionsValueListEntryValuesEnum.SOUTH_AMERICA: (
'south-america'
),
messages.UptimeCheckConfig.SelectedRegionsValueListEntryValuesEnum.ASIA_PACIFIC: (
'asia-pacific'
),
}
return [region_mapping.get(region) for region in selected_regions]
def ParseStatusClasses(status_classes):
"""Convert previously status classes from enum to flag for update logic."""
client = uptime.UptimeClient()
messages = client.messages
status_mapping = {
messages.ResponseStatusCode.StatusClassValueValuesEnum.STATUS_CLASS_1XX: (
'1xx'
),
messages.ResponseStatusCode.StatusClassValueValuesEnum.STATUS_CLASS_2XX: (
'2xx'
),
messages.ResponseStatusCode.StatusClassValueValuesEnum.STATUS_CLASS_3XX: (
'3xx'
),
messages.ResponseStatusCode.StatusClassValueValuesEnum.STATUS_CLASS_4XX: (
'4xx'
),
messages.ResponseStatusCode.StatusClassValueValuesEnum.STATUS_CLASS_5XX: (
'5xx'
),
messages.ResponseStatusCode.StatusClassValueValuesEnum.STATUS_CLASS_ANY: (
'any'
),
}
return [status_mapping.get(status_class) for status_class in status_classes]