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,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.
"""The gcloud run revisions group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.run import flags
@base.UniverseCompatible
class Revisions(base.Group):
"""View and manage your Cloud Run revisions.
This set of commands can be used to view and manage your existing Cloud Run
revisions.
"""
detailed_help = {
'EXAMPLES': """
To list your existing revisions, run:
$ {command} list
""",
}
@staticmethod
def Args(parser):
"""Adds --platform and the various related args."""
flags.AddPlatformAndLocationFlags(parser)
def Filter(self, context, args):
"""Runs before command.Run and validates platform with passed args."""
# Ensures a platform is set on the run/platform property and
# all other passed args are valid for this platform and release track.
flags.GetAndValidatePlatform(args, self.ReleaseTrack(), flags.Product.RUN)
return context

View File

@@ -0,0 +1,101 @@
# -*- 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.
"""Command for deleting revisions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.run import connection_context
from googlecloudsdk.command_lib.run import deletion
from googlecloudsdk.command_lib.run import flags
from googlecloudsdk.command_lib.run import pretty_print
from googlecloudsdk.command_lib.run import resource_args
from googlecloudsdk.command_lib.run import serverless_operations
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.command_lib.util.concepts import presentation_specs
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class Delete(base.Command):
"""Delete a revision."""
detailed_help = {
'DESCRIPTION':
"""\
{description}
""",
'EXAMPLES':
"""\
To delete a revision:
$ {command} <revision-name>
""",
}
@staticmethod
def CommonArgs(parser):
revision_presentation = presentation_specs.ResourcePresentationSpec(
'REVISION',
resource_args.GetRevisionResourceSpec(),
'Revision to delete.',
required=True,
prefixes=False)
concept_parsers.ConceptParser([revision_presentation]).AddToParser(parser)
flags.AddAsyncFlag(parser, default_async_for_cluster=True)
@staticmethod
def Args(parser):
Delete.CommonArgs(parser)
def Run(self, args):
"""Delete a revision."""
conn_context = connection_context.GetConnectionContext(
args, flags.Product.RUN, self.ReleaseTrack())
revision_ref = args.CONCEPTS.revision.Parse()
console_io.PromptContinue(
message='Revision [{}] will be deleted.'.format(
revision_ref.revisionsId),
throw_if_unattended=True,
cancel_on_no=True)
async_ = deletion.AsyncOrDefault(args.async_)
with serverless_operations.Connect(conn_context) as client:
deletion.Delete(
revision_ref, client.GetRevision, client.DeleteRevision, async_
)
if async_:
pretty_print.Success(
'Revision [{}] is being deleted.'.format(revision_ref.revisionsId)
)
else:
log.DeletedResource(revision_ref.revisionsId, 'revision')
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class AlphaDelete(Delete):
"""Delete a revision."""
@staticmethod
def Args(parser):
Delete.CommonArgs(parser)
AlphaDelete.__doc__ = Delete.__doc__

View File

@@ -0,0 +1,85 @@
# -*- 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.
"""Command for obtaining details about revisions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.run import connection_context
from googlecloudsdk.command_lib.run import exceptions
from googlecloudsdk.command_lib.run import flags
from googlecloudsdk.command_lib.run import resource_args
from googlecloudsdk.command_lib.run import serverless_operations
from googlecloudsdk.command_lib.run.printers import export_printer
from googlecloudsdk.command_lib.run.printers import revision_printer
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.command_lib.util.concepts import presentation_specs
from googlecloudsdk.core.resource import resource_printer
@base.UniverseCompatible
class Describe(base.DescribeCommand):
"""Obtain details about revisions."""
detailed_help = {
'DESCRIPTION': """\
{description}
""",
'EXAMPLES': """\
To describe a revision `my-service-00001-abc`in us-central1:
$ {command} --region=us-central1 my-service-00001-abc
""",
}
@staticmethod
def CommonArgs(parser):
revision_presentation = presentation_specs.ResourcePresentationSpec(
'REVISION',
resource_args.GetRevisionResourceSpec(),
'Revision to describe.',
required=True,
prefixes=False)
concept_parsers.ConceptParser([
revision_presentation]).AddToParser(parser)
resource_printer.RegisterFormatter(
revision_printer.REVISION_PRINTER_FORMAT,
revision_printer.RevisionPrinter)
parser.display_info.AddFormat(revision_printer.REVISION_PRINTER_FORMAT)
resource_printer.RegisterFormatter(
export_printer.EXPORT_PRINTER_FORMAT,
export_printer.ExportPrinter)
@staticmethod
def Args(parser):
Describe.CommonArgs(parser)
def Run(self, args):
"""Show details about a revision."""
conn_context = connection_context.GetConnectionContext(
args, flags.Product.RUN, self.ReleaseTrack())
revision_ref = args.CONCEPTS.revision.Parse()
with serverless_operations.Connect(conn_context) as client:
wrapped_revision = client.GetRevision(revision_ref)
# If the revision is a worker pool revision, we should not show it.
if not wrapped_revision or wrapped_revision.worker_pool_name is not None:
raise exceptions.ArgumentError('Cannot find revision [{}]'.format(
revision_ref.revisionsId))
return wrapped_revision

View File

@@ -0,0 +1,137 @@
# -*- 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 for listing available reivions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.run import commands
from googlecloudsdk.command_lib.run import connection_context
from googlecloudsdk.command_lib.run import flags
from googlecloudsdk.command_lib.run import platforms
from googlecloudsdk.command_lib.run import pretty_print
from googlecloudsdk.command_lib.run import resource_args
from googlecloudsdk.command_lib.run import serverless_operations
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.command_lib.util.concepts import presentation_specs
from googlecloudsdk.core import log
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class List(commands.List):
"""List available revisions."""
detailed_help = {
'DESCRIPTION': """\
{description}
""",
'EXAMPLES': """\
To list all revisions for the provided service:
$ {command} --service=foo
""",
}
@classmethod
def CommonArgs(cls, parser):
# Flags specific to connecting to a cluster
namespace_presentation = presentation_specs.ResourcePresentationSpec(
'--namespace',
resource_args.GetNamespaceResourceSpec(),
'Namespace to list revisions in.',
required=True,
prefixes=False,
hidden=True,
)
concept_parsers.ConceptParser([namespace_presentation]).AddToParser(parser)
# Flags not specific to any platform
flags.AddServiceFlag(parser)
parser.display_info.AddFormat(
'table('
'{ready_column},'
'name:label=REVISION,'
'active.yesno(yes="yes", no=""),'
'service_name:label=SERVICE:sort=1,'
'creation_timestamp.date("%Y-%m-%d %H:%M:%S %Z"):'
'label=DEPLOYED:sort=2:reverse,'
'author:label="DEPLOYED BY"):({alias})'.format(
ready_column=pretty_print.READY_COLUMN,
alias=commands.SATISFIES_PZS_ALIAS,
)
)
parser.display_info.AddUriFunc(cls._GetResourceUri)
@classmethod
def Args(cls, parser):
cls.CommonArgs(parser)
def _FilterWorkerPoolRevisions(self, revisions):
"""Filters out revisions that are worker pool revisions.
Per discussion with jmahood@, we want to make sure that all resources are
self-contained, so none of the describe/list commands should mix the
resource type.
Args:
revisions: List of revisions to filter.
Returns:
List of revisions that are service revisions.
"""
return list(filter(lambda rev: rev.worker_pool_name is None, revisions))
def Run(self, args):
"""List available revisions."""
label_selector = None
service_name = args.service
conn_context = connection_context.GetConnectionContext(
args, flags.Product.RUN, self.ReleaseTrack()
)
namespace_ref = args.CONCEPTS.namespace.Parse()
with serverless_operations.Connect(conn_context) as client:
self.SetCompleteApiEndpoint(conn_context.endpoint)
if platforms.GetPlatform() != platforms.PLATFORM_MANAGED:
location_msg = ' in [{}]'.format(conn_context.cluster_location)
log.status.Print(
'For cluster [{cluster}]{zone}:'.format(
cluster=conn_context.cluster_name,
zone=location_msg if conn_context.cluster_location else '',
)
)
if service_name is not None:
label_selector = 'serving.knative.dev/service = {}'.format(service_name)
for rev in self._FilterWorkerPoolRevisions(
client.ListRevisions(
namespace_ref, label_selector, args.limit, args.page_size
)
):
yield rev
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class AlphaList(List):
"""List available revisions."""
@classmethod
def Args(cls, parser):
cls.CommonArgs(parser)
AlphaList.__doc__ = List.__doc__

View File

@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 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.
"""Group definition for logs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.run import exceptions
from googlecloudsdk.command_lib.run import platforms
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Logs(base.Group):
"""Read logs for Cloud Run revisions."""
def _CheckPlatform(self):
if platforms.GetPlatform() != platforms.PLATFORM_MANAGED:
raise exceptions.PlatformError(
'This command group only supports listing regions for '
'Cloud Run (fully managed).')
def Filter(self, context, args):
self._CheckPlatform()
return context

View File

@@ -0,0 +1,95 @@
# -*- 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 read logs for a revision."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from googlecloudsdk.api_lib.logging import common
from googlecloudsdk.api_lib.logging.formatter import FormatLog
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.logs import read as read_logs_lib
from googlecloudsdk.command_lib.run import flags
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Read(base.Command):
"""Read logs for a Cloud Run revision."""
detailed_help = {
'DESCRIPTION':
"""\
{command} reads log entries. Log entries matching *--log-filter* are
returned in order of decreasing timestamps, most-recent entries first.
If the log entries come from multiple logs, then entries from
different logs might be intermingled in the results.
""",
'EXAMPLES':
"""\
To read log entries from for a Cloud Run revision, run:
$ {command} my-revision
To read log entries with severity ERROR or higher, run:
$ {command} my-revision --log-filter="severity>=ERROR"
To read log entries written in a specific time window, run:
$ {command} my-revision --log-filter='timestamp<="2015-05-31T23:59:59Z" AND timestamp>="2015-05-31T00:00:00Z"'
To read up to 10 log entries in your revision payloads that include
the word `SearchText` and format the output in `JSON` format, run:
$ {command} my-revision --log-filter="textPayload:SearchText" --limit=10 --format=json
Detailed information about filters can be found at:
[](https://cloud.google.com/logging/docs/view/advanced_filters)
""",
}
@staticmethod
def Args(parser):
read_logs_lib.LogFilterArgs(parser)
read_logs_lib.LoggingReadArgs(parser)
parser.add_argument('revision', help='Name for a Cloud Run revision.')
def Run(self, args):
filters = [args.log_filter] if args.IsSpecified('log_filter') else []
filters.append('resource.labels.revision_name = %s' % args.revision)
filters.append('resource.type = %s \n' % 'cloud_run_revision')
filters.append('resource.labels.location = %s \n' %
flags.GetRegion(args, prompt=True))
filters.append('severity >= DEFAULT \n')
filters += read_logs_lib.MakeTimestampFilters(args)
lines = []
logs = common.FetchLogs(
read_logs_lib.JoinFilters(filters),
order_by=args.order,
limit=args.limit)
for log_line in logs:
output_log = FormatLog(log_line)
if output_log:
lines.append(output_log)
for line in reversed(lines):
log.out.Print(line)

View File

@@ -0,0 +1,79 @@
# -*- 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 tail logs for a service."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.logs import read as read_logs_lib
from googlecloudsdk.command_lib.run import flags
from googlecloudsdk.command_lib.run import streaming
from googlecloudsdk.core import properties
from googlecloudsdk.core.credentials import store
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Tail(base.BinaryBackedCommand):
"""Tail logs for a Cloud Run revision."""
detailed_help = {
'DESCRIPTION':
"""\
{command} tails log-entries for a particular
Cloud Run revision in real time. The log entries are formatted for
consumption in a terminal.
""",
'EXAMPLES':
"""\
To tail log entries for a Cloud Run revision, run:
$ {command} my-revision
To tail log entries with severity ERROR or higher, run:
$ {command} my-revision --log-filter="severity>=ERROR"
Detailed information about filters can be found at:
[](https://cloud.google.com/logging/docs/view/advanced_filters)
""",
}
@staticmethod
def Args(parser):
parser.add_argument('revision', help='Name for a Cloud Run revision.')
read_logs_lib.LogFilterArgs(parser)
def Run(self, args):
filters = []
if args.IsSpecified('log_filter'):
filters.append(args.log_filter)
filters.append('resource.type=%s' % 'cloud_run_revision')
filters.append('resource.labels.revision_name=%s' % args.revision)
filters.append('resource.labels.location=%s' %
flags.GetRegion(args, prompt=True))
filters.append('severity>=DEFAULT')
project_id = properties.VALUES.core.project.Get(required=True)
filter_str = ' '.join(filters)
command_executor = streaming.LogStreamingWrapper()
response = command_executor(
project_id=project_id,
log_format='run',
log_filter=filter_str,
token=store.GetFreshAccessTokenIfEnabled(),
)
return self._DefaultOperationResponseHandler(response)