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,32 @@
# -*- 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.
"""The main command group for Eventarc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Eventarc(base.Group):
"""Manage Eventarc resources."""
category = base.SERVERLESS_CATEGORY
def Filter(self, context, args):
del context, args

View File

@@ -0,0 +1,29 @@
# -*- 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 audit-logs-provider command group for Eventarc."""
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.DefaultUniverseOnly
class AuditLogsProvider(base.Group):
"""Explore provider serviceNames and methodNames for event type `google.cloud.audit.log.v1.written` in Eventarc."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,26 @@
# -*- 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 method-names command group for Eventarc."""
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 MethodNames(base.Group):
"""Explore values for the methodName attribute for event type `google.cloud.audit.log.v1.written`."""

View File

@@ -0,0 +1,52 @@
# -*- 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 list values for the methodName attribute for event type `google.cloud.audit.log.v1.written`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.eventarc import service_catalog
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To list methodName values for serviceName ``storage.googleapis.com'', run:
$ {command} --service-name=storage.googleapis.com
""",
}
_FORMAT = 'table(method_name)'
@base.ReleaseTracks(base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List values for the methodName attribute for event type `google.cloud.audit.log.v1.written`."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddServiceNameArg(parser, required=True)
parser.display_info.AddFormat(_FORMAT)
def Run(self, args):
"""Run the list command."""
return service_catalog.GetMethods(args.service_name)

View File

@@ -0,0 +1,26 @@
# -*- 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 service-names command group for Eventarc."""
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 ServiceNames(base.Group):
"""Explore values for the serviceName attribute for event type `google.cloud.audit.log.v1.written`."""

View File

@@ -0,0 +1,50 @@
# -*- 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 list values for the serviceName attribute for event type google.cloud.audit.log.v1.written."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import service_catalog
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To list serviceName values for event type `google.cloud.audit.log.v1.written`, run:
$ {command}
""",
}
_FORMAT = 'table(service_name, display_name)'
@base.ReleaseTracks(base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List values for the serviceName attribute for event type `google.cloud.audit.log.v1.written`."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
parser.display_info.AddFormat(_FORMAT)
def Run(self, args):
"""Run the list command."""
return service_catalog.GetServices()

View File

@@ -0,0 +1,29 @@
# -*- 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.
"""The channel connections command group for Eventarc."""
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.DefaultUniverseOnly
class ChannelConnections(base.Group):
"""Manage Eventarc channel connections."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,89 @@
# -*- 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 to create a channel connection."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channel_connections
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To create a new channel connection ``my-channel-connection'' for channel ``my-channel'' with activation token ``channel-activation-token'', run:
$ {command} my-channel-connection --channel=my-channel --activation-token=channel-activation-token
""",
}
ACTIVATION_TOKEN_FLAG = base.Argument(
'--activation-token',
dest='activation_token',
help="""Activation token for the specified channel.""",
required=True)
CHANNEL_FLAG = base.Argument(
'--channel',
dest='channel',
help="""Subscriber channel for which to create the channel connection. This argument should be the full channel name, including project, location and the channel id. """,
required=True)
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create an Eventarc channel connection."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddChannelConnectionResourceArg(parser,
'Channel connection to create.')
CHANNEL_FLAG.AddToParser(parser)
ACTIVATION_TOKEN_FLAG.AddToParser(parser)
flags.AddLabelsArg(
parser, help_text='Labels to apply to the channel connection.'
)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the create command."""
client = channel_connections.ChannelConnectionClientV1()
channel_connection_ref = args.CONCEPTS.channel_connection.Parse()
project_name = channel_connection_ref.Parent().Parent().Name()
location_name = channel_connection_ref.Parent().Name()
log.debug('Creating channel {} for project {} in location {}'.format(
channel_connection_ref.Name(), project_name, location_name))
operation = client.Create(
channel_connection_ref,
client.BuildChannelConnection(
channel_connection_ref,
channel=args.channel,
activation_token=args.activation_token,
labels=args.labels,
),
)
if args.async_:
return operation
return client.WaitFor(operation, 'Creating', channel_connection_ref)

View File

@@ -0,0 +1,66 @@
# -*- 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 to delete the specified channel connection."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channel_connections
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core.console import console_io
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To delete the channel connection ``my-channel-connection'' in location ``us-central1'', run:
$ {command} my-channel-connection --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
"""Delete an Eventarc channel connection."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddChannelConnectionResourceArg(parser,
'Channel connection to delete.')
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
client = channel_connections.ChannelConnectionClientV1()
channel_connection_ref = args.CONCEPTS.channel_connection.Parse()
location_name = channel_connection_ref.Parent().Name()
console_io.PromptContinue(
message=('The following channel connection will be deleted.\n'
'[{name}] in location [{location}]'.format(
name=channel_connection_ref.Name(),
location=location_name)),
throw_if_unattended=True,
cancel_on_no=True)
operation = client.Delete(channel_connection_ref)
if args.async_:
return operation
return client.WaitFor(operation, 'Deleting', channel_connection_ref)

View File

@@ -0,0 +1,52 @@
# -*- 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 to describe the specified channel."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channel_connections
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To describe the channel connection ``my-channel-connection'' in location ``us-central1'', run:
$ {command} my-channel-connection --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describe an Eventarc channel connection."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddChannelConnectionResourceArg(parser,
'Channel connection to describe.')
def Run(self, args):
client = channel_connections.ChannelConnectionClientV1()
channel_ref = args.CONCEPTS.channel_connection.Parse()
return client.Get(channel_ref)

View File

@@ -0,0 +1,76 @@
# -*- 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 to list all channel connections in a project and location."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channel_connections
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
"DESCRIPTION":
"{description}",
"EXAMPLES":
"""\
To list all channel connections in location ``us-central1'', run:
$ {command} --location=us-central1
To list all channel connections in all locations, run:
$ {command} --location=-
or
$ {command}
""",
}
_FORMAT = """\
table(
name.scope("channelConnections"):label=NAME,
channel:label=CHANNEL
)
"""
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List Eventarc channel connections."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddLocationResourceArg(
parser,
"Location for which to list channel connections. This should be one of"
" the supported regions.",
required=False,
allow_aggregation=True,
)
flags.AddProjectResourceArg(parser)
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(channel_connections.GetChannelConnectionsURI)
def Run(self, args):
client = channel_connections.ChannelConnectionClientV1()
args.CONCEPTS.project.Parse()
location_ref = args.CONCEPTS.location.Parse()
return client.List(location_ref, args.limit, args.page_size)

View File

@@ -0,0 +1,72 @@
# -*- 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 publish channels."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channel_connections
from googlecloudsdk.api_lib.eventarc import common_publishing
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To publish an event to your channel connection `my-channel-connection`
with event id `1234`
with event type `event-provider.event.v1.eventType`
with event source `//event-provider/projects/project-id/resource-id`
with event data `{ "key": "value" }`
and event attributes of `attribute1=value`, run:
$ {command} my-channel-connection --event-id=1234 --event-type=event-provider.event.v1.eventType --event-source="//event-provider/event/source" --event-data='{"key": "value"}' --event-attributes=attribute1=value
""",
}
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Publish(base.Command):
"""Publish to an Eventarc channel connection."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddChannelConnectionResourceArg(parser,
'Channel connection to publish to.')
flags.AddEventPublishingArgs(parser)
def Run(self, args):
"""Run the Publish command."""
client = channel_connections.ChannelConnectionClientV1()
channel_connection_ref = args.CONCEPTS.channel_connection.Parse()
name = channel_connection_ref.Name()
log.debug('Publishing event with id: {} to channel connection: {}'.format(
args.event_id, name))
client.Publish(
channel_connection_ref,
common_publishing.CreateCloudEvent(args.event_id, args.event_type,
args.event_source, args.event_data,
args.event_attributes))
return log.out.Print('Event published successfully')

View File

@@ -0,0 +1,29 @@
# -*- 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.
"""The channels command group for Eventarc."""
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.DefaultUniverseOnly
class Channels(base.Group):
"""Manage Eventarc channels."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,80 @@
# -*- 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 to create a channel."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channels
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
# TODO(b/188207212): Update documentation when provider will be a resource
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To create a new channel `my-channel` in location `us-central1`, run:
$ {command} my-channel --location=us-central1
To create a new channel `my-channel` in location `us-central1` with a Cloud KMS CryptoKey, run:
$ {command} my-channel --location=us-central1 --crypto-key=projects/PROJECT_ID/locations/KMS_LOCATION/keyRings/KEYRING/cryptoKeys/KEY
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create an Eventarc channel."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddCreateChannelArg(parser)
flags.AddCryptoKeyArg(parser, with_clear=False, hidden=False)
labels_util.AddCreateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the create command."""
client = channels.ChannelClientV1()
channel_ref = args.CONCEPTS.channel.Parse()
project_name = channel_ref.Parent().Parent().Name()
location_name = channel_ref.Parent().Name()
log.debug('Creating channel {} for project {} in location {}'.format(
channel_ref.Name(), project_name, location_name))
provider_ref = args.CONCEPTS.provider.Parse()
operation = client.Create(
channel_ref,
client.BuildChannel(
channel_ref,
provider_ref,
args.crypto_key,
labels_util.ParseCreateArgs(args, client.LabelsValueCls()),
),
)
if args.async_:
return operation
return client.WaitFor(operation, 'Creating', channel_ref)

View File

@@ -0,0 +1,67 @@
# -*- 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 to delete the specified channel."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channels
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core.console import console_io
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To delete the channel `my-channel` in location `us-central1`, run:
$ {command} my-channel --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
"""Delete an Eventarc channel."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddChannelResourceArg(parser, 'Channel to delete.', required=True)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the delete command."""
client = channels.ChannelClientV1()
channel_ref = args.CONCEPTS.channel.Parse()
location_name = channel_ref.Parent().Name()
console_io.PromptContinue(
message=('The following channel will be deleted.\n'
'[{name}] in location [{location}]'
.format(
name=channel_ref.Name(),
location=location_name)),
throw_if_unattended=True,
cancel_on_no=True)
operation = client.Delete(channel_ref)
if args.async_:
return operation
return client.WaitFor(operation, 'Deleting', channel_ref)

View File

@@ -0,0 +1,51 @@
# -*- 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 to describe the specified channel."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channels
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To describe the channel `my-channel` in location `us-central1`, run:
$ {command} my-channel --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describe an Eventarc channel."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddChannelResourceArg(parser, 'Channel to describe.', required=True)
def Run(self, args):
client = channels.ChannelClientV1()
channel_ref = args.CONCEPTS.channel.Parse()
return client.Get(channel_ref)

View File

@@ -0,0 +1,78 @@
# -*- 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 to list all channels in a project and location."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channels
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
"DESCRIPTION":
"{description}",
"EXAMPLES":
""" \
To list all channels in location `us-central1`, run:
$ {command} --location=us-central1
To list all channels in all locations, run:
$ {command} --location=-
or
$ {command}
""",
}
_FORMAT = """ \
table(
name.scope("channels"):label=NAME,
provider:label=PROVIDER,
state:label=STATE,
pubsubTopic.scope("topics"):label=PUBSUB_TOPIC
)
"""
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List Eventarc channels."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddLocationResourceArg(
parser,
"Location for which to list channels. This should be one of the"
" supported regions.",
required=False,
allow_aggregation=True,
)
flags.AddProjectResourceArg(parser)
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(channels.GetChannelURI)
def Run(self, args):
client = channels.ChannelClientV1()
args.CONCEPTS.project.Parse()
location_ref = args.CONCEPTS.location.Parse()
return client.List(location_ref, args.limit, args.page_size)

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 publish channels."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channels
from googlecloudsdk.api_lib.eventarc import common_publishing
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To publish an event to the channel `my-channel`
with event id `1234`
with event type `event-provider.event.v1.eventType`
with event source `//event-provider/event/source`
with event data `{ "key": "value" }`
and event attributes of `attribute1=value`, run:
$ {command} my-channel --event-id=1234 --event-type=event-provider.event.v1.eventType --event-source="//event-provider/event/source" --event-data='{"key": "value"}' --event-attributes=attribute1=value
""",
}
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Publish(base.Command):
"""Publish to an Eventarc channel."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddChannelResourceArg(parser, 'Channel to Publish to.', required=True)
flags.AddEventPublishingArgs(parser)
def Run(self, args):
"""Run the Publish command."""
client = channels.ChannelClientV1()
channel_ref = args.CONCEPTS.channel.Parse()
name = channel_ref.Name()
log.debug('Publishing event with id: {} to channel: {}'.format(
args.event_id, name))
client.Publish(
channel_ref,
common_publishing.CreateCloudEvent(args.event_id, args.event_type,
args.event_source, args.event_data,
args.event_attributes))
return log.out.Print('Event published successfully')

View File

@@ -0,0 +1,93 @@
# -*- 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 update the specified channel."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import channels
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To update the channel `my-channel` in location `us-central1`, run:
$ {command} my-channel --location=us-central1
To configure the channel `my-channel` in location `us-central1` with a Cloud KMS CryptoKey, run:
$ {command} my-channel --location=us-central1 --crypto-key=projects/PROJECT_ID/locations/KMS_LOCATION/keyRings/KEYRING/cryptoKeys/KEY
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an Eventarc channel."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddChannelResourceArg(parser, 'Channel to update.', required=True)
flags.AddCryptoKeyArg(parser, with_clear=True)
labels_util.AddUpdateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the update command."""
client = channels.ChannelClientV1()
channel_ref = args.CONCEPTS.channel.Parse()
project_name = channel_ref.Parent().Parent().Name()
location_name = channel_ref.Parent().Name()
log.debug('Updating channel {} for project {} in location {}'.format(
channel_ref.Name(), project_name, location_name))
original_channel = client.Get(channel_ref)
labels_update_result = labels_util.Diff.FromUpdateArgs(args).Apply(
client.LabelsValueCls(), original_channel.labels
)
update_mask = client.BuildUpdateMask(
crypto_key=args.IsSpecified('crypto_key'),
clear_crypto_key=args.clear_crypto_key,
labels=labels_update_result.needs_update,
)
crypto_key_name = ''
if args.IsSpecified('crypto_key'):
crypto_key_name = args.crypto_key
operation = client.Patch(
channel_ref,
client.BuildChannel(
channel_ref, None, crypto_key_name, labels_update_result.GetOrNone()
),
update_mask,
)
if args.async_:
return operation
return client.WaitFor(operation, 'Updating', channel_ref)

View File

@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 enrollments command group for Eventarc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Enrollments(base.Group):
"""Manage Eventarc enrollments."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 an enrollment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import enrollments
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To create a new enrollment `my-enrollment` in location `us-central1` for message-bus `my-message-bus` with cel matching expression `message.type == "google.cloud.pubsub.topic.v1.messagePublished"` and destination pipeline `my-pipeline`, run:
$ {command} my-enrollment --location=us-central1 --message-bus=my-message-bus --cel-match="message.type == 'google.cloud.pubsub.topic.v1.messagePublished'" --destination-pipeline=my-pipeline
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create an Eventarc enrollment."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddCreateEnrollmentResourceArgs(parser)
flags.AddCelMatchArg(parser, required=True)
labels_util.AddCreateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the create command."""
client = enrollments.EnrollmentClientV1()
enrollment_ref = args.CONCEPTS.enrollment.Parse()
log.debug(
'Creating enrollment {} for project {} in location {}'.format(
enrollment_ref.enrollmentsId,
enrollment_ref.projectsId,
enrollment_ref.locationsId,
)
)
operation = client.Create(
enrollment_ref,
client.BuildEnrollment(
enrollment_ref,
args.cel_match,
args.CONCEPTS.message_bus.Parse(),
args.CONCEPTS.destination_pipeline.Parse(),
labels_util.ParseCreateArgs(args, client.LabelsValueClass()),
),
)
if args.async_:
return operation
return client.WaitFor(operation, 'Creating', enrollment_ref)

View File

@@ -0,0 +1,70 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 delete the specified enrollment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import enrollments
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core.console import console_io
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To delete the enrollment `my-enrollment` in location `us-central1`, run:
$ {command} my-enrollment --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Delete(base.DeleteCommand):
"""Delete an Eventarc enrollment."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddEnrollmentResourceArg(
parser, 'Enrollment to delete.', required=True
)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the delete command."""
client = enrollments.EnrollmentClientV1()
enrollment_ref = args.CONCEPTS.enrollment.Parse()
console_io.PromptContinue(
message=(
'The following enrollment will be deleted.\n'
'[{name}] in location [{location}]'.format(
name=enrollment_ref.enrollmentsId,
location=enrollment_ref.locationsId,
)
),
throw_if_unattended=True,
cancel_on_no=True,
)
operation = client.Delete(enrollment_ref)
if args.async_:
return operation
return client.WaitFor(operation, 'Deleting', enrollment_ref)

View File

@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 describe the specified enrollment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import enrollments
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To describe the enrollment `my-enrollment` in location `us-central1`, run:
$ {command} my-enrollment --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Describe an Eventarc enrollment."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddEnrollmentResourceArg(
parser, 'Enrollment to describe.', required=True
)
def Run(self, args):
client = enrollments.EnrollmentClientV1()
enrollment_ref = args.CONCEPTS.enrollment.Parse()
return client.Get(enrollment_ref)

View File

@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 list all enrollments in a project and location."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import re
from googlecloudsdk.api_lib.eventarc import enrollments
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
"DESCRIPTION": "{description}",
"EXAMPLES": """ \
To list all enrollments in location `us-central1`, run:
$ {command} --location=us-central1
To list all enrollments in all locations, run:
$ {command} --location=-
or
$ {command}
""",
}
_FORMAT = """ \
table(
name.scope("enrollments"):label=NAME,
message_bus.scope("messageBuses"):label=MESSAGE_BUS,
message_bus.scope("projects").segment(1):label=MESSAGE_BUS_PROJECT,
destination():label=DESTINATION,
name.scope("locations").segment(0):label=LOCATION
)
"""
def _Destination(enrollment):
"""Generate a destination string for the enrollment."""
destination = enrollment.get("destination")
if destination is None:
return "Unknown destination"
pipeline_str_pattern = "^projects/.*/locations/.*/pipelines/(.*)$"
match = re.search(pipeline_str_pattern, destination)
if match:
return "Pipeline: {}".format(match.group(1))
# Add other destination match patterns here.
return "Unknown destination"
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List Eventarc enrollments."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddLocationResourceArg(
parser,
"The location for which to list enrollments. This should be one of the"
" supported regions.",
required=False,
allow_aggregation=True,
)
flags.AddProjectResourceArg(parser)
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(enrollments.GetEnrollmentURI)
parser.display_info.AddTransforms({
"destination": _Destination,
})
def Run(self, args):
client = enrollments.EnrollmentClientV1()
location_ref = args.CONCEPTS.location.Parse()
return client.List(location_ref, args.limit, args.page_size)

View File

@@ -0,0 +1,90 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 update the specified enrollment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import enrollments
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To update the enrollment `my-enrollment` with a new CEL expression `message.type == 'google.cloud.pubsub.topic.v1.messagePublished'`, run:
$ {command} my-enrollment --location=us-central1 --cel-match="message.type == 'google.cloud.pubsub.topic.v1.messagePublished'"
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an Eventarc enrollment."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddUpdateEnrollmentResourceArgs(parser)
flags.AddCelMatchArg(parser, required=False)
labels_util.AddUpdateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the update command."""
client = enrollments.EnrollmentClientV1()
enrollment_ref = args.CONCEPTS.enrollment.Parse()
log.debug(
'Updating enrollment {} for project {} in location {}'.format(
enrollment_ref.enrollmentsId,
enrollment_ref.projectsId,
enrollment_ref.locationsId,
)
)
original_enrollment = client.Get(enrollment_ref)
labels_update_result = labels_util.Diff.FromUpdateArgs(args).Apply(
client.LabelsValueClass(), original_enrollment.labels
)
update_mask = client.BuildUpdateMask(
cel_match=args.IsSpecified('cel_match'),
destination=args.IsSpecified('destination_pipeline'),
labels=labels_update_result.needs_update,
)
operation = client.Patch(
enrollment_ref,
client.BuildEnrollment(
enrollment_ref=enrollment_ref,
cel_match=args.cel_match,
message_bus_ref=None,
destination_ref=args.CONCEPTS.destination_pipeline.Parse(),
labels=labels_update_result.GetOrNone(),
),
update_mask,
)
if args.async_:
return operation
return client.WaitFor(operation, 'Updating', enrollment_ref)

View File

@@ -0,0 +1,30 @@
# -*- 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.
"""The gke-destinations command group for Eventarc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class GKEDestinations(base.Group):
"""Manage Eventarc with Cloud Run for Anthos/GKE destinations."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,56 @@
# -*- 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 for initializing a project for Eventarc GKE."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import gke_destinations
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Init(base.Command):
"""Initialize a project for Eventarc with Cloud Run for Anthos/GKE destinations."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""
To initialize a project for Eventarc with Cloud Run for Anthos/GKE destinations:
$ {command}
""",
}
def Run(self, args):
"""Run the gke command."""
client = gke_destinations.GKEDestinationsClient(self.ReleaseTrack())
client.InitServiceAccount()
log.status.Print(_InitializedMessage())
def _InitializedMessage():
project = properties.VALUES.core.project.Get(required=True)
trigger_cmd = 'gcloud eventarc triggers create'
return (
'Initialized project [{}] for Cloud Run for Anthos/GKE destinations in '
'Eventarc. Next, create a trigger via `{}`.').format(
project, trigger_cmd)

View File

@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 Google API sources command group for Eventarc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class GoogleApiSources(base.Group):
"""Manage Eventarc Google API sources."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 Google API source."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import google_api_sources
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To create a new Google API source `my-google-api-source` in location `us-central1` with a destination message bus `my-message-bus`, run:
$ {command} my-google-api-source --location=us-central1 --destination-message-bus=my-message-bus
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create an Eventarc Google API source."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddCreateGoogleApiSourceResourceArgs(parser)
flags.AddLoggingConfigArg(
parser, 'The logging config for the Google API source.'
)
flags.AddWideScopeSubscriptionArg(parser, with_clear=False)
flags.AddCryptoKeyArg(parser, with_clear=False, hidden=False)
labels_util.AddCreateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the create command."""
client = google_api_sources.GoogleApiSourceClientV1()
google_api_source_ref = args.CONCEPTS.google_api_source.Parse()
log.debug(
'Creating Google API source {} for project {} in location {}'.format(
google_api_source_ref.googleApiSourcesId,
google_api_source_ref.projectsId,
google_api_source_ref.locationsId,
)
)
operation = client.Create(
google_api_source_ref,
client.BuildGoogleApiSource(
google_api_source_ref,
args.CONCEPTS.destination_message_bus.Parse(),
args.logging_config,
args.crypto_key,
labels_util.ParseCreateArgs(args, client.LabelsValueClass()),
args.organization_subscription
if args.IsSpecified('organization_subscription')
else None,
args.project_subscriptions,
),
)
if args.async_:
return operation
return client.WaitFor(operation, 'Creating', google_api_source_ref)

View File

@@ -0,0 +1,70 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 delete the specified Google API source."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import google_api_sources
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core.console import console_io
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To delete the Google API source `my-google-api-source` in location `us-central1`, run:
$ {command} my-google-api-source --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Delete(base.DeleteCommand):
"""Delete an Eventarc Google API source."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddGoogleApiSourceResourceArg(
parser, 'Google API source to delete.', required=True
)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the delete command."""
client = google_api_sources.GoogleApiSourceClientV1()
google_api_source_ref = args.CONCEPTS.google_api_source.Parse()
console_io.PromptContinue(
message=(
'The following Google API source will be deleted.\n'
'[{name}] in location [{location}]'.format(
name=google_api_source_ref.googleApiSourcesId,
location=google_api_source_ref.locationsId,
)
),
throw_if_unattended=True,
cancel_on_no=True,
)
operation = client.Delete(google_api_source_ref)
if args.async_:
return operation
return client.WaitFor(operation, 'Deleting', google_api_source_ref)

View File

@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 describe the specified Google API source."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import google_api_sources
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To describe the google API source `my-google-api-source` in location `us-central1`, run:
$ {command} my-google-api-source --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Describe an Eventarc Google API source."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddGoogleApiSourceResourceArg(
parser, 'Google API source to describe.', required=True
)
def Run(self, args):
client = google_api_sources.GoogleApiSourceClientV1()
google_api_source_ref = args.CONCEPTS.google_api_source.Parse()
return client.Get(google_api_source_ref)

View File

@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 list all Google API sources in a project and location."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import google_api_sources
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
"DESCRIPTION": "{description}",
"EXAMPLES": """\
To list all Google API sources in location ``us-central1'', run:
$ {command} --location=us-central1
To list all Google API sources in all locations, run:
$ {command} --location=-
or
$ {command}
""",
}
_FORMAT = """\
table(
name.scope("googleApiSources"):label=NAME,
destination.scope("messageBuses"):label=DESTINATION,
destination.scope("projects").segment(1):label=DESTINATION_PROJECT,
name.scope("locations").segment(0):label=LOCATION,
loggingConfig.logSeverity:label=LOGGING_CONFIG
)
"""
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List Eventarc Google API sources."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddLocationResourceArg(
parser,
"The location for which to list Google API sources. This should be one"
" of the supported regions.",
required=False,
allow_aggregation=True,
)
flags.AddProjectResourceArg(parser)
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(google_api_sources.GetGoogleAPISourceURI)
def Run(self, args):
client = google_api_sources.GoogleApiSourceClientV1()
location_ref = args.CONCEPTS.location.Parse()
return client.List(location_ref, args.limit, args.page_size)

View File

@@ -0,0 +1,112 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 update the specified Google API source."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import google_api_sources
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To update the Google API source `my-google-api-source` in location `us-central1` with destination message bus `my-message-bus`, run:
$ {command} my-google-api-source --location=us-central1 --destination-message-bus=my-message-bus
To update the Google API source `my-google-api-source` in location `us-central1` with `INFO` level logging, run:
$ {command} my-google-api-source --location=us-central1 --logging-config=INFO
To update the Google API source `my-google-api-source` in location `us-central1` with a Cloud KMS CryptoKey, run:
$ {command} my-google-api-source --location=us-central1 --crypto-key=projects/PROJECT_ID/locations/KMS_LOCATION/keyRings/KEYRING/cryptoKeys/KEY
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an Eventarc Google API source."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddUpdateGoogleApiSourceResourceArgs(parser)
flags.AddLoggingConfigArg(
parser, 'The logging config of the Google API source.'
)
flags.AddWideScopeSubscriptionArg(parser, with_clear=True)
flags.AddCryptoKeyArg(parser, with_clear=True)
labels_util.AddUpdateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the update command."""
client = google_api_sources.GoogleApiSourceClientV1()
google_api_source_ref = args.CONCEPTS.google_api_source.Parse()
log.debug(
'Updating Google API source {} for project {} in location {}'
.format(
google_api_source_ref.googleApiSourcesId,
google_api_source_ref.projectsId,
google_api_source_ref.locationsId,
)
)
original_google_api_source = client.Get(google_api_source_ref)
labels_update_result = labels_util.Diff.FromUpdateArgs(args).Apply(
client.LabelsValueClass(), original_google_api_source.labels
)
update_mask = client.BuildUpdateMask(
destination=args.IsSpecified('destination_message_bus'),
logging_config=args.IsSpecified('logging_config'),
crypto_key=args.IsSpecified('crypto_key'),
clear_crypto_key=args.clear_crypto_key,
labels=labels_update_result.needs_update,
organization_subscription=args.IsSpecified('organization_subscription'),
project_subscriptions=args.IsSpecified('project_subscriptions'),
clear_project_subscriptions=args.clear_project_subscriptions,
)
operation = client.Patch(
google_api_source_ref,
client.BuildGoogleApiSource(
google_api_source_ref=google_api_source_ref,
destination_ref=args.CONCEPTS.destination_message_bus.Parse(),
logging_config=args.logging_config,
crypto_key_name=args.crypto_key,
labels=labels_update_result.GetOrNone(),
organization_subscription=args.organization_subscription
if args.IsSpecified('organization_subscription')
else None,
project_subscriptions=args.project_subscriptions,
),
update_mask,
)
if args.async_:
return operation
return client.WaitFor(operation, 'Updating', google_api_source_ref)

View File

@@ -0,0 +1,29 @@
# -*- 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 google channels command group for Eventarc."""
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.DefaultUniverseOnly
class GoogleChannels(base.Group):
"""Manage Eventarc Google channels."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,55 @@
# -*- 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 describe the specified google channel."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import google_channels
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To describe the Google channel in location `us-central1`, run:
$ {command} --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describe an Eventarc Google channel."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddLocationResourceArg(
parser, 'The location of the Google Channel.', required=True)
def Run(self, args):
client = google_channels.GoogleChannelConfigClientV1()
config_name = '%s/googleChannelConfig' % (
args.CONCEPTS.location.Parse().RelativeName())
response = client.Get(config_name)
return response

View File

@@ -0,0 +1,87 @@
# -*- 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 update the specified google channel."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import google_channels
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To update the Google channel in location `us-central1`, run:
$ {command} --location=us-central1
To configure the Google channel in location `us-central1` with a Cloud KMS CryptoKey, run:
$ {command} --location=us-central1 --crypto-key=projects/PROJECT_ID/locations/KMS_LOCATION/keyRings/KEYRING/cryptoKeys/KEY
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an Eventarc Google channel."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddLocationResourceArg(
parser, 'The location of the Google Channel.', required=True)
flags.AddCryptoKeyArg(parser, with_clear=True)
labels_util.AddUpdateLabelsFlags(parser)
def Run(self, args):
"""Run the update command."""
client = google_channels.GoogleChannelConfigClientV1()
location_name = args.CONCEPTS.location.Parse().RelativeName()
config_name = f'{location_name}/googleChannelConfig'
original_google_channel = client.Get(config_name)
labels_update_result = labels_util.Diff.FromUpdateArgs(args).Apply(
client.LabelsValueClass(), original_google_channel.labels
)
update_mask = client.BuildUpdateMask(
crypto_key=args.IsSpecified('crypto_key'),
clear_crypto_key=args.clear_crypto_key,
labels=labels_update_result.needs_update,
)
crypto_key_name = ''
if args.IsSpecified('crypto_key'):
crypto_key_name = args.crypto_key
response = client.Update(
config_name,
client.BuildGoogleChannelConfig(
config_name,
crypto_key_name,
labels=labels_update_result.GetOrNone(),
),
update_mask,
)
return response

View File

@@ -0,0 +1,30 @@
# -*- 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.
"""The kafka sources command group for Eventarc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
@base.Hidden
class KafkaSources(base.Group):
"""Manage Eventarc kafka sources."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,119 @@
# -*- 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 to create a Kafka source."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import kafka_sources
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To create a new Kafka source `my-kafka-source` in location `us-central1` with the required fields: bootstrap server URI 'https://example-cluster.com:9092', Kafka topics `topic1` and `topic2`, network attachment 'my-network-attachment', and message bus `my-message-bus`, run:
$ {command} my-kafka-source --location=us-central1 --bootstrap-servers='https://example-cluster.com:9092' --topics='topic1,topic2' --network_attachment=my-network-attachment --message-bus=my-message-bus
To create a new Kafka source `my-kafka-source` in location `us-central1` with an initial offset of `newest`, run:
$ {command} my-kafka-source --location=us-central1 --bootstrap-servers='https://example-cluster.com:9092' --topics='topic1,topic2' --network_attachment=my-network-attachment --message-bus=my-message-bus --initial-offset=newest
To create a new Kafka source `my-kafka-source` in location `us-central1` with consumer group ID `my-kafka-source-group`, run:
$ {command} my-kafka-source --location=us-central1 --bootstrap-servers='https://example-cluster.com:9092' --topics='topic1,topic2' --network_attachment=my-network-attachment --message-bus=my-message-bus --consumer-group-id=my-kafka-source-group
To create a new Kafka source `my-kafka-source` in location `us-central1` SASL/Plain authentication with the Kafka broker, run:
$ {command} my-kafka-source --location=us-central1 --bootstrap-servers='https://example-cluster.com:9092' --topics='topic1,topic2' --network_attachment=my-network-attachment --message-bus=my-message-bus --sasl-mechanism=PLAIN --sasl-username=kafka-username --sasl-password=projects/12345/secrets/my-sasl-secret/versions/1
To create a new Kafka source `my-kafka-source` in location `us-central1` SASL/SCRAM-SHA-256 authentication with the Kafka broker, run:
$ {command} my-kafka-source --location=us-central1 --bootstrap-servers='https://example-cluster.com:9092' --topics='topic1,topic2' --network_attachment=my-network-attachment --message-bus=my-message-bus --sasl-mechanism=SCRAM-SHA-256 --sasl-username=kafka-username --sasl-password=projects/12345/secrets/my-sasl-secret/versions/1
To create a new Kafka source `my-kafka-source` in location `us-central1` SASL/SCRAM-SHA-512 authentication with the Kafka broker, run:
$ {command} my-kafka-source --location=us-central1 --bootstrap-servers='https://example-cluster.com:9092' --topics='topic1,topic2' --network_attachment=my-network-attachment --message-bus=my-message-bus --sasl-mechanism=SCRAM-SHA-512 --sasl-username=kafka-username --sasl-password=projects/12345/secrets/my-sasl-secret/versions/1
To create a new Kafka source `my-kafka-source` in location `us-central1` Mutual TLS (mTLS) authentication with the Kafka broker, run:
$ {command} my-kafka-source --location=us-central1 --bootstrap-servers='https://example-cluster.com:9092' --topics='topic1,topic2' --network_attachment=my-network-attachment --message-bus=my-message-bus --tls-client-certificate=projects/12345/secrets/my-tls-cert/versions/1 --tls-client-key=projects/12345/secrets/my-tls-key/versions/1
To create a new Kafka source `my-kafka-source` in location `us-central1` with an INFO level logging configuration, run:
$ {command} my-kafka-source --location=us-central1 --bootstrap-servers='https://example-cluster.com:9092' --topics='topic1,topic2' --network_attachment=my-network-attachment --message-bus=my-message-bus --logging_config=INFO
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create an Eventarc Kafka source."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddCreateKafkaSourceResourceArgs(parser)
flags.AddKafkaSourceBootstrapServersArg(parser, required=True)
flags.AddKafkaSourceTopicArg(parser, required=True)
flags.AddKafkaSourceConsumerGroupIDArg(parser, required=False)
flags.AddKafkaSourceInitialOffsetArg(parser, required=False)
flags.AddKafkaSourceNetworkAttachmentArg(parser, required=True)
flags.AddKafkaSourceAuthGroup(parser, required=True)
flags.AddLoggingConfigArg(parser, 'The logging config of the kafka source.')
labels_util.AddCreateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the create command."""
client = kafka_sources.KafkaSourceClientV1()
kafka_source_ref = args.CONCEPTS.kafka_source.Parse()
log.debug(
'Creating kafka source {} for project {} in location {}'.format(
kafka_source_ref.kafkaSourcesId,
kafka_source_ref.projectsId,
kafka_source_ref.locationsId,
)
)
operation = client.Create(
kafka_source_ref,
client.BuildKafkaSource(
kafka_source_ref=kafka_source_ref,
bootstrap_servers=args.bootstrap_servers,
consumer_group_id=args.consumer_group_id,
topics=args.topics,
sasl_mechanism=args.sasl_mechanism,
sasl_username=args.sasl_username,
sasl_password=args.sasl_password,
tls_client_certificate=args.tls_client_certificate,
tls_client_key=args.tls_client_key,
network_attachment=args.network_attachment,
message_bus=args.message_bus,
initial_offset=args.initial_offset,
logging_config=args.logging_config,
labels=labels_util.ParseCreateArgs(args, client.LabelsValueClass()),
),
)
if args.async_:
return operation
return client.WaitFor(operation, 'Creating', kafka_source_ref)

View File

@@ -0,0 +1,70 @@
# -*- 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 to delete the specified Kafka source."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import kafka_sources
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core.console import console_io
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To delete the Kafka source `my-kafka-source` in location `us-central1`, run:
$ {command} my-kafka-source --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class Delete(base.DeleteCommand):
"""Delete an Eventarc Kafka source."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddKafkaSourceResourceArg(
parser, 'Kafka source to delete.', required=True
)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the delete command."""
client = kafka_sources.KafkaSourceClientV1()
kafka_source_ref = args.CONCEPTS.kafka_source.Parse()
console_io.PromptContinue(
message=(
'The following Kafka source will be deleted.\n'
'[{name}] in location [{location}]'.format(
name=kafka_source_ref.kafkaSourcesId,
location=kafka_source_ref.locationsId,
)
),
throw_if_unattended=True,
cancel_on_no=True,
)
operation = client.Delete(kafka_source_ref)
if args.async_:
return operation
return client.WaitFor(operation, 'Deleting', kafka_source_ref)

View File

@@ -0,0 +1,52 @@
# -*- 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 to describe the specified Kafka source."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import kafka_sources
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To describe the Kafka source `my-kafka-source` in location `us-central1`, run:
$ {command} my-kafka-source --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Describe an Eventarc Kafka source."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddKafkaSourceResourceArg(
parser, 'Kafka source to describe.', required=True
)
def Run(self, args):
client = kafka_sources.KafkaSourceClientV1()
kafka_source_ref = args.CONCEPTS.kafka_source.Parse()
return client.Get(kafka_source_ref)

View File

@@ -0,0 +1,74 @@
# -*- 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 to list all Kafka sources in a project and location."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import kafka_sources
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
"DESCRIPTION": "{description}",
"EXAMPLES": """\
To list all Kafka sources in location ``us-central1'', run:
$ {command} --location=us-central1
To list all Kafka sources in all locations, run:
$ {command} --location=-
or
$ {command}
""",
}
_FORMAT = """\
table(
name.scope("kafkaSources"):label=NAME,
name.scope("locations").segment(0):label=LOCATION,
loggingConfig.logSeverity:label=LOGGING_CONFIG
)
"""
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List Eventarc Kafka sources."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddLocationResourceArg(
parser,
"Location for which to list Kafka sources. This should be one of the"
" supported regions.",
required=False,
allow_aggregation=True,
)
flags.AddProjectResourceArg(parser)
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(kafka_sources.GetKafkaSourceURI)
def Run(self, args):
client = kafka_sources.KafkaSourceClientV1()
location_ref = args.CONCEPTS.location.Parse()
return client.List(location_ref, args.limit, args.page_size)

View File

@@ -0,0 +1,29 @@
# -*- 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.
"""The locations command group for Eventarc."""
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.DefaultUniverseOnly
class Locations(base.Group):
"""Explore locations available for Eventarc."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,53 @@
# -*- 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.
"""Command to list all locations available in Eventarc API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import locations
from googlecloudsdk.calliope import base
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To list all locations, run:
$ {command}
""",
}
_FORMAT = 'table(locationId:label=NAME)'
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List locations available for Eventarc."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(locations.GetLocationsURI)
def Run(self, args):
"""Run the list command."""
client = locations.LocationsClient(self.ReleaseTrack())
return client.List(limit=args.limit, page_size=args.page_size)

View File

@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 message buses command group for Eventarc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class MessageBuses(base.Group):
"""Manage Eventarc message buses."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,78 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 message bus."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import message_buses
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To create a new message bus `my-message-bus` in location `us-central1`, run:
$ {command} my-message-bus --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create an Eventarc message bus."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddMessageBusResourceArg(
parser, 'The message bus to create.', required=True
)
flags.AddLoggingConfigArg(parser, 'The logging config of the message bus.')
flags.AddCryptoKeyArg(parser, with_clear=False, hidden=False)
labels_util.AddCreateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the create command."""
client = message_buses.MessageBusClientV1()
message_bus_ref = args.CONCEPTS.message_bus.Parse()
log.debug(
'Creating message bus {} for project {} in location {}'.format(
message_bus_ref.messageBusesId,
message_bus_ref.projectsId,
message_bus_ref.locationsId,
)
)
operation = client.Create(
message_bus_ref,
client.BuildMessageBus(
message_bus_ref,
args.logging_config,
args.crypto_key,
labels_util.ParseCreateArgs(args, client.LabelsValueClass()),
),
)
if args.async_:
return operation
return client.WaitFor(operation, 'Creating', message_bus_ref)

View File

@@ -0,0 +1,70 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 delete the specified message bus."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import message_buses
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core.console import console_io
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To delete the message bus `my-message-bus` in location `us-central1`, run:
$ {command} my-message-bus --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Delete(base.DeleteCommand):
"""Delete an Eventarc message bus."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddMessageBusResourceArg(
parser, 'Message bus to delete.', required=True
)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the delete command."""
client = message_buses.MessageBusClientV1()
message_bus_ref = args.CONCEPTS.message_bus.Parse()
console_io.PromptContinue(
message=(
'The following message bus will be deleted.\n'
'[{name}] in location [{location}]'.format(
name=message_bus_ref.messageBusesId,
location=message_bus_ref.locationsId,
)
),
throw_if_unattended=True,
cancel_on_no=True,
)
operation = client.Delete(message_bus_ref)
if args.async_:
return operation
return client.WaitFor(operation, 'Deleting', message_bus_ref)

View File

@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 describe the specified message bus."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import message_buses
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To describe the message bus `my-message-bus` in location `us-central1`, run:
$ {command} my-message-bus --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Describe an Eventarc message bus."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddMessageBusResourceArg(
parser, 'Message bus to describe.', required=True
)
def Run(self, args):
client = message_buses.MessageBusClientV1()
message_bus_ref = args.CONCEPTS.message_bus.Parse()
return client.Get(message_bus_ref)

View File

@@ -0,0 +1,74 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 list all message buses in a project and location."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import message_buses
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
"DESCRIPTION": "{description}",
"EXAMPLES": """\
To list all message buses in location ``us-central1'', run:
$ {command} --location=us-central1
To list all message buses in all locations, run:
$ {command} --location=-
or
$ {command}
""",
}
_FORMAT = """\
table(
name.scope("messageBuses"):label=NAME,
name.scope("locations").segment(0):label=LOCATION,
loggingConfig.logSeverity:label=LOGGING_CONFIG
)
"""
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List Eventarc message buses."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddLocationResourceArg(
parser,
"The location for which to list message buses. This should be one of"
" the supported regions.",
required=False,
allow_aggregation=True,
)
flags.AddProjectResourceArg(parser)
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(message_buses.GetMessageBusURI)
def Run(self, args):
client = message_buses.MessageBusClientV1()
location_ref = args.CONCEPTS.location.Parse()
return client.List(location_ref, args.limit, args.page_size)

View File

@@ -0,0 +1,61 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 list all message buses in a project and location."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import enrollments
from googlecloudsdk.api_lib.eventarc import message_buses
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
"DESCRIPTION": "{description}",
"EXAMPLES": """\
To list all enrollments in message-bus `my-message-bus` in `us-central1`, run:
$ {command} my-message-bus --location=us-central1
""",
}
_FORMAT = """ \
table(
list().scope("projects").segment(1):label=ENROLLMENT_PROJECT,
list().scope("enrollments"):label=NAME
)
"""
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class ListEnrollments(base.ListCommand):
"""List Eventarc enrollments attached to an Eventarc message bus."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddMessageBusResourceArg(
parser, "The message bus on which to list enrollments.", required=True
)
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(enrollments.GetEnrollmentURI)
def Run(self, args):
client = message_buses.MessageBusClientV1()
message_bus_ref = args.CONCEPTS.message_bus.Parse()
return client.ListEnrollments(message_bus_ref, args.limit, args.page_size)

View File

@@ -0,0 +1,86 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 publish on message buses."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import message_buses
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as calliope_exceptions
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To publish an event to the message bus `my-message-bus` with event id `1234`, event type `event-provider.event.v1.eventType`, event source `//event-provider/event/source`, event data `{ "key": "value" }` and event attributes of `attribute1=value`, run:
$ {command} my-message-bus --location=us-central1 --event-id=1234 --event-type=event-provider.event.v1.eventType --event-source="//event-provider/event/source" --event-data='{"key": "value"}' --event-attributes=attribute1=value
To publish an event to the message bus `my-message-bus` with a json message, run:
$ {command} my-message-bus --location=us-central1 --json-message='{"id": 1234, "type": "event-provider.event.v1.eventType", "source": "//event-provider/event/source", "specversion": "1.0", "data": {"key": "value"}}'
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Publish(base.Command):
"""Publish to an Eventarc message bus."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddMessageBusPublishingArgs(parser)
def Run(self, args):
"""Run the Publish command."""
client = message_buses.MessageBusClientV1()
message_bus_ref = args.CONCEPTS.message_bus.Parse()
log.debug(
'Publishing to message bus: {}'.format(message_bus_ref.messageBusesId)
)
destination_enrollment_ref = args.CONCEPTS.destination_enrollment.Parse()
if (
destination_enrollment_ref
and destination_enrollment_ref.locationsId
!= message_bus_ref.locationsId
):
raise calliope_exceptions.InvalidArgumentException(
'--destination-enrollment',
'Destination Enrollment and Message Bus must be in the same'
' location.',
)
client.Publish(
message_bus_ref,
args.json_message,
args.avro_message,
args.event_id,
args.event_type,
args.event_source,
args.event_data,
args.event_attributes,
destination_enrollment_ref,
)
return log.out.Print('Event published successfully')

View File

@@ -0,0 +1,97 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 update the specified message bus."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import message_buses
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To update the message bus `my-message-bus` in location `us-central1`, run:
$ {command} my-message-bus --location=us-central1
To configure the message bus `my-message-bus` in location `us-central1` with a Cloud KMS CryptoKey, run:
$ {command} my-message-bus --location=us-central1 --crypto-key=projects/PROJECT_ID/locations/KMS_LOCATION/keyRings/KEYRING/cryptoKeys/KEY
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an Eventarc message bus."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddMessageBusResourceArg(
parser, 'Message bus to update.', required=True
)
flags.AddLoggingConfigArg(parser, 'The logging config of the message bus.')
flags.AddCryptoKeyArg(parser, with_clear=True)
labels_util.AddUpdateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the update command."""
client = message_buses.MessageBusClientV1()
message_bus_ref = args.CONCEPTS.message_bus.Parse()
log.debug(
'Updating message bus {} for project {} in location {}'.format(
message_bus_ref.messageBusesId,
message_bus_ref.projectsId,
message_bus_ref.locationsId,
)
)
original_message_bus = client.Get(message_bus_ref)
labels_update_result = labels_util.Diff.FromUpdateArgs(args).Apply(
client.LabelsValueClass(), original_message_bus.labels
)
update_mask = client.BuildUpdateMask(
logging_config=args.IsSpecified('logging_config'),
crypto_key=args.IsSpecified('crypto_key'),
clear_crypto_key=args.clear_crypto_key,
labels=labels_update_result.needs_update,
)
operation = client.Patch(
message_bus_ref,
client.BuildMessageBus(
message_bus_ref=message_bus_ref,
logging_config=args.logging_config,
crypto_key_name=args.crypto_key,
labels=labels_update_result.GetOrNone(),
),
update_mask,
)
if args.async_:
return operation
return client.WaitFor(operation, 'Updating', message_bus_ref)

View File

@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 pipelines command group for Eventarc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Pipelines(base.Group):
"""Manage Eventarc pipelines."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,154 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 pipeline."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import pipelines
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To create a new pipeline `my-pipeline` in location `us-central1` with its destination targeting HTTP endpoint URI 'https://example-endpoint.com', run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com'
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination and a message binding template, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com',http_endpoint_message_binding_template='{"headers": {"new-header-key": "new-header-value"}}'
To create a new pipeline `my-pipeline` in location `us-central1` with a Cloud Workflow destination `my-workflow`, run:
$ {command} my-pipeline --location=us-central1 --destinations=workflow=my-workflow
To create a new pipeline `my-pipeline` in location `us-central1` with a message bus destination `my-message-bus`, run:
$ {command} my-pipeline --location=us-central1 --destinations=message_bus=my-message-bus
To create a new pipeline `my-pipeline` in location `us-central1` with a Cloud Pub/Sub Topic destination `my-topic`, run:
$ {command} my-pipeline --location=us-central1 --destinations=pubsub_topic=my-topic
To create a new pipeline `my-pipeline` in location `us-central1` with a Cloud Workflow in project `example-project` and location `us-east1`, run:
$ {command} my-pipeline --location=us-central1 --destinations=workflow=my-workflow,project=example-project,location=us-east1
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and a service account `example-service-account@example-project.gserviceaccount.iam.com` for OIDC authentication, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com',google_oidc_authentication_service_account=example-service-account@example-project.gserviceaccount.iam.com
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and a service account `example-service-account@example-project.gserviceaccount.iam.com` for OIDC authentication with audience `https://example.com`, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com',google_oidc_authentication_service_account=example-service-account@example-project.gserviceaccount.iam.com,google_oidc_authentication_audience='https://example.com'
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and a service account `example-service-account@example-project.gserviceaccount.iam.com` for OAuth token authentication, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com',oauth_token_authentication_service_account=example-service-account@example-project.gserviceaccount.iam.com
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and a service account `example-service-account@example-project.gserviceaccount.iam.com` for OAuth token authentication with scope `https://www.googleapis.com/auth/cloud-platform`, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com',oauth_token_authentication_service_account=example-service-account@example-project.gserviceaccount.iam.com,oauth_token_authentication_scope='https://www.googleapis.com/auth/cloud-platform'
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and the JSON input and output payload formats, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com',output_payload_format_json= --input-payload-format-json=
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and the Avro input and output payload formats, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com',output_payload_format_avro_schema_definition='{"type": "record", "name": "my_record", "fields": [{"name": "my_field", "type": "string"}]}' --input-payload-format-avro-schema-definition='{"type": "record", "name": "my_record", "fields": [{"name": "my_field", "type": "string"}]}'
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and the Protobuf input and output payload formats, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com',output_payload_format_protobuf_schema_definition='syntax = "proto3"; message Location { string home_address = 1; }' --input-payload-format-protobuf-schema-definition='syntax = "proto3"; message Location { string home_address = 1; }'
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and a transformation mediation, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com'--mediations=transformation_template='message.removeFields(["data.credit_card_number","data.ssn"])'
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and a INFO level logging configuration, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com'--logging_config=INFO
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and a custom retry policy, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com' --max-retry-attempts=10 --min-retry-delay=2s --max-retry-delay=64s
To create a new pipeline `my-pipeline` in location `us-central1` with an HTTP endpoint URI destination `https://example-endpoint.com` and a Cloud KMS CryptoKey, run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com' --crypto-key=projects/PROJECT_ID/locations/KMS_LOCATION/keyRings/KEYRING/cryptoKeys/KEY
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create an Eventarc pipeline."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddPipelineResourceArg(
parser, 'The pipeline to create.', required=True
)
flags.AddPipelineDestinationsArg(parser, required=True)
flags.AddInputPayloadFormatArgs(parser)
flags.AddMediationsArg(parser)
flags.AddLoggingConfigArg(parser, 'The logging config of the pipeline.')
flags.AddPipelineRetryPolicyArgs(parser)
flags.AddCryptoKeyArg(parser, with_clear=False, hidden=False)
labels_util.AddCreateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the create command."""
client = pipelines.PipelineClientV1()
pipelines_ref = args.CONCEPTS.pipeline.Parse()
log.debug(
'Creating pipeline {} for project {} in location {}'.format(
pipelines_ref.pipelinesId,
pipelines_ref.projectsId,
pipelines_ref.locationsId,
)
)
operation = client.Create(
pipelines_ref,
client.BuildPipeline(
pipeline_ref=pipelines_ref,
destinations=args.destinations,
input_payload_format_json=args.input_payload_format_json,
input_payload_format_avro_schema_definition=args.input_payload_format_avro_schema_definition,
input_payload_format_protobuf_schema_definition=args.input_payload_format_protobuf_schema_definition,
mediations=args.mediations,
logging_config=args.logging_config,
max_retry_attempts=args.max_retry_attempts,
min_retry_delay=args.min_retry_delay,
max_retry_delay=args.max_retry_delay,
crypto_key_name=args.crypto_key,
labels=labels_util.ParseCreateArgs(args, client.LabelsValueClass()),
),
)
if args.async_:
return operation
return client.WaitFor(operation, 'Creating', pipelines_ref)

View File

@@ -0,0 +1,68 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 delete the specified pipeline."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import pipelines
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core.console import console_io
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To delete the pipeline `my-pipeline` in location `us-central1`, run:
$ {command} my-pipeline --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Delete(base.DeleteCommand):
"""Delete an Eventarc pipeline."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddPipelineResourceArg(parser, 'Pipeline to delete.', required=True)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the delete command."""
client = pipelines.PipelineClientV1()
pipeline_ref = args.CONCEPTS.pipeline.Parse()
console_io.PromptContinue(
message=(
'The following pipeline will be deleted.\n'
'[{name}] in location [{location}]'.format(
name=pipeline_ref.pipelinesId,
location=pipeline_ref.locationsId,
)
),
throw_if_unattended=True,
cancel_on_no=True,
)
operation = client.Delete(pipeline_ref)
if args.async_:
return operation
return client.WaitFor(operation, 'Deleting', pipeline_ref)

View File

@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 describe the specified pipeline."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import pipelines
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To describe the pipeline `my-pipeline` in location `us-central1`, run:
$ {command} my-pipeline --location=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Describe an Eventarc pipeline."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddPipelineResourceArg(parser, 'Pipeline to describe.', required=True)
def Run(self, args):
client = pipelines.PipelineClientV1()
pipeline_ref = args.CONCEPTS.pipeline.Parse()
return client.Get(pipeline_ref)

View File

@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 list all pipelines in a project and location."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import pipelines
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
"DESCRIPTION": "{description}",
"EXAMPLES": """\
To list all pipelines in location ``us-central1'', run:
$ {command} --location=us-central1
To list all pipelines in all locations, run:
$ {command} --location=-
or
$ {command}
""",
}
_FORMAT = """\
table(
name.scope("pipelines"):label=NAME,
name.scope("locations").segment(0):label=LOCATION,
loggingConfig.logSeverity:label=LOGGING_CONFIG,
inputPayloadFormat():label=INPUT_PAYLOAD_FORMAT,
retryPolicy.maxAttempts:label=MAX_RETRY_ATTEMPTS,
retryPolicy.minRetryDelay:label=MIN_RETRY_DELAY,
retryPolicy.maxRetryDelay:label=MAX_RETRY_DELAY
)
"""
def _InputPayloadFormat(pipeline):
"""Generate an input payload format string for the pipeline."""
input_payload_format = pipeline.get("inputPayloadFormat")
if input_payload_format is None:
return "None"
if input_payload_format.get("json") is not None:
return "Json"
if input_payload_format.get("avro") is not None:
return "Avro"
if input_payload_format.get("protobuf") is not None:
return "Protobuf"
return "Unknown Format"
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List Eventarc pipelines."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddLocationResourceArg(
parser,
"Location for which to list pipelines. This should be one of the"
" supported regions.",
required=False,
allow_aggregation=True,
)
flags.AddProjectResourceArg(parser)
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(pipelines.GetPipelineURI)
parser.display_info.AddTransforms({
"inputPayloadFormat": _InputPayloadFormat,
})
def Run(self, args):
client = pipelines.PipelineClientV1()
location_ref = args.CONCEPTS.location.Parse()
return client.List(location_ref, args.limit, args.page_size)

View File

@@ -0,0 +1,117 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 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 update the specified pipeline."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import pipelines
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To update the pipeline `my-pipeline` with its destination targeting HTTP endpoint URI 'https://example-endpoint.com' and network attachment 'my-network-attachment', run:
$ {command} my-pipeline --location=us-central1 --destinations=http_endpoint_uri='https://example-endpoint.com',network_attachment=my-network-attachment
""",
}
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an Eventarc pipeline."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddPipelineResourceArg(
parser, group_help_text='The pipeline to update.', required=True
)
flags.AddPipelineDestinationsArg(parser, required=False)
flags.AddInputPayloadFormatArgs(parser)
flags.AddMediationsArg(parser)
flags.AddLoggingConfigArg(parser, 'The logging config of the pipeline.')
flags.AddPipelineRetryPolicyArgs(parser)
flags.AddCryptoKeyArg(parser, with_clear=True, hidden=False)
labels_util.AddUpdateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the update command."""
client = pipelines.PipelineClientV1()
pipeline_ref = args.CONCEPTS.pipeline.Parse()
log.debug(
'Updating pipeline {} for project {} in location {}'.format(
pipeline_ref.pipelinesId,
pipeline_ref.projectsId,
pipeline_ref.locationsId,
)
)
original_pipeline = client.Get(pipeline_ref)
labels_update_result = labels_util.Diff.FromUpdateArgs(args).Apply(
client.LabelsValueClass(), original_pipeline.labels
)
update_mask = client.BuildUpdateMask(
destinations=args.IsSpecified('destinations'),
input_payload_format_json=args.IsSpecified('input_payload_format_json'),
input_payload_format_avro_schema_definition=args.IsSpecified(
'input_payload_format_avro_schema_definition'
),
input_payload_format_protobuf_schema_definition=args.IsSpecified(
'input_payload_format_protobuf_schema_definition'
),
mediations=args.IsSpecified('mediations'),
logging_config=args.IsSpecified('logging_config'),
max_retry_attempts=args.IsSpecified('max_retry_attempts'),
min_retry_delay=args.IsSpecified('min_retry_delay'),
max_retry_delay=args.IsSpecified('max_retry_delay'),
crypto_key=args.IsSpecified('crypto_key'),
clear_crypto_key=args.clear_crypto_key,
labels=labels_update_result.needs_update,
)
operation = client.Patch(
pipeline_ref,
client.BuildPipeline(
pipeline_ref=pipeline_ref,
destinations=args.destinations,
input_payload_format_json=args.input_payload_format_json,
input_payload_format_avro_schema_definition=args.input_payload_format_avro_schema_definition,
input_payload_format_protobuf_schema_definition=args.input_payload_format_protobuf_schema_definition,
mediations=args.mediations,
logging_config=args.logging_config,
max_retry_attempts=args.max_retry_attempts,
min_retry_delay=args.min_retry_delay,
max_retry_delay=args.max_retry_delay,
crypto_key_name=args.crypto_key,
labels=labels_update_result.GetOrNone(),
),
update_mask,
)
if args.async_:
return operation
return client.WaitFor(operation, 'Updating', pipeline_ref)

View File

@@ -0,0 +1,29 @@
# -*- 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.
"""The providers command group for Eventarc."""
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.DefaultUniverseOnly
class Providers(base.Group):
"""Explore event providers available in Eventarc."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,54 @@
# -*- 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 to describe an event provider."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import providers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To describe the provider ``my-provider'', run:
$ {command} my-provider
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describe an Eventarc event provider."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddProviderResourceArg(
parser, 'The event provider to describe.', True)
def Run(self, args):
"""Run the describe command."""
client = providers.ProvidersClient(self.ReleaseTrack())
provider_ref = args.CONCEPTS.provider.Parse()
provider = client.Get(provider_ref)
return provider

View File

@@ -0,0 +1,82 @@
# -*- 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 to list all event providers available in Eventarc API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import providers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To list all providers in location `us-central1`, run:
$ {command} --location=us-central1
To list all providers in all locations, run:
$ {command} --location=-
or
$ {command}
""",
}
_FORMAT = """ \
table(
name.scope("providers"):label=NAME,
name.scope("locations").segment(0):label=LOCATION
)
"""
_FILTER = 'name:/providers/'
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List event providers available in Eventarc."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddLocationResourceArg(
parser,
'The location in which to list event providers.',
required=False,
allow_aggregation=True,
)
flags.AddProjectResourceArg(parser)
flags.AddProviderNameArg(parser)
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(providers.GetProvidersURI)
def Run(self, args):
"""Run the list command."""
client = providers.ProvidersClient(self.ReleaseTrack())
args.CONCEPTS.project.Parse()
location_ref = args.CONCEPTS.location.Parse()
if args.name:
args.GetDisplayInfo().AddFilter(_FILTER + args.name)
return client.List(
location_ref.RelativeName(), limit=args.limit, page_size=args.page_size)

View File

@@ -0,0 +1,29 @@
# -*- 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.
"""The triggers command group for Eventarc."""
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.DefaultUniverseOnly
class Triggers(base.Group):
"""Manage Eventarc triggers."""
category = base.SERVERLESS_CATEGORY

View File

@@ -0,0 +1,223 @@
# -*- 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.
"""Command to create a trigger."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import encoding
from googlecloudsdk.api_lib.eventarc import triggers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.eventarc import types
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import exceptions
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION': '{description}',
'EXAMPLES': """ \
To create a new trigger ``my-trigger'' for events of type ``google.cloud.pubsub.topic.v1.messagePublished'' with destination Cloud Run service ``my-service'', run:
$ {command} my-trigger --event-filters="type=google.cloud.pubsub.topic.v1.messagePublished" --destination-run-service=my-service
""",
}
class NoDestinationLocationSpecifiedError(exceptions.Error):
"""Error when no destination location was specified for a global trigger."""
class UnsupportedDestinationError(exceptions.Error):
"""Error when none of the supported destination args is specified."""
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create an Eventarc trigger."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddCreateTrigerResourceArgs(parser, cls.ReleaseTrack())
flags.AddEventFiltersArg(parser, cls.ReleaseTrack(), required=True)
flags.AddEventFiltersPathPatternArg(parser, cls.ReleaseTrack())
flags.AddEventDataContentTypeArg(parser, cls.ReleaseTrack())
flags.AddServiceAccountArg(parser)
flags.AddCreateDestinationArgs(parser, cls.ReleaseTrack(), required=True)
flags.AddTransportTopicResourceArg(parser)
flags.AddTriggerRetryPolicyArgs(parser)
labels_util.AddCreateLabelsFlags(parser)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the create command."""
client = triggers.TriggersClientV1()
trigger_ref = args.CONCEPTS.trigger.Parse()
channel_ref = flags.GetChannelArg(args, self.ReleaseTrack())
transport_topic_ref = args.CONCEPTS.transport_topic.Parse()
event_filters = flags.GetEventFiltersArg(args, self.ReleaseTrack())
event_filters_path_pattern = flags.GetEventFiltersPathPatternArg(
args, self.ReleaseTrack()
)
event_data_content_type = flags.GetEventDataContentTypeArg(
args, self.ReleaseTrack()
)
# destination Cloud Run
if args.IsSpecified('destination_run_service') or args.IsKnownAndSpecified(
'destination_run_job'
):
resource_type = (
'service' if args.IsSpecified('destination_run_service') else 'job'
)
destination_run_region = self.GetDestinationLocation(
args,
trigger_ref,
'destination_run_region',
'Cloud Run {}'.format(resource_type),
)
# Jobs only exist in the v1 API and thus only in the GA track.
# This extra check is needed so we don't throw trying to access a flag
# which doesn't exist.
run_job = (
args.destination_run_job if 'destination_run_job' in args else None
)
destination_message = client.BuildCloudRunDestinationMessage(
args.destination_run_service,
run_job,
args.destination_run_path,
destination_run_region,
)
dest_str = 'Cloud Run {} [{}]'.format(
resource_type, args.destination_run_service or run_job
)
loading_msg = ''
# destination GKE service
elif args.IsSpecified('destination_gke_service'):
destination_gke_location = self.GetDestinationLocation(
args, trigger_ref, 'destination_gke_location', 'GKE service'
)
destination_gke_namespace = args.destination_gke_namespace or 'default'
destination_message = client.BuildGKEDestinationMessage(
args.destination_gke_cluster,
destination_gke_location,
destination_gke_namespace,
args.destination_gke_service,
args.destination_gke_path,
)
dest_str = 'GKE service [{}] in cluster [{}]'.format(
args.destination_gke_service, args.destination_gke_cluster
)
loading_msg = 'this operation may take several minutes'
# destination Http Endpoint
elif args.IsSpecified('destination_http_endpoint_uri'):
destination_message = client.BuildHTTPEndpointDestinationMessage(
args.destination_http_endpoint_uri,
args.network_attachment,
)
dest_str = 'HTTP endpoint [{}]'.format(args.destination_http_endpoint_uri)
loading_msg = 'this operation may take several minutes'
# destination Workflow
elif args.IsSpecified('destination_workflow'):
destination_workflow_location = self.GetDestinationLocation(
args, trigger_ref, 'destination_workflow_location', 'Workflow'
)
destination_message = client.BuildWorkflowDestinationMessage(
trigger_ref.Parent().Parent().Name(),
args.destination_workflow,
destination_workflow_location,
)
dest_str = 'Workflow [{}]'.format(args.destination_workflow)
loading_msg = ''
# Destination Cloud Function
elif args.IsSpecified('destination_function'):
destination_function_location = self.GetDestinationLocation(
args, trigger_ref, 'destination_function_location', 'Function'
)
destination_message = client.BuildFunctionDestinationMessage(
trigger_ref.Parent().Parent().Name(),
args.destination_function,
destination_function_location,
)
dest_str = 'Cloud Function [{}]'.format(args.destination_function)
loading_msg = ''
else:
raise UnsupportedDestinationError('Must specify a valid destination.')
trigger_message = client.BuildTriggerMessage(
trigger_ref,
event_filters,
event_filters_path_pattern,
event_data_content_type,
args.service_account,
destination_message,
transport_topic_ref,
channel_ref,
args.max_retry_attempts,
labels_util.ParseCreateArgs(args, client.LabelsValueClass()),
)
operation = client.Create(trigger_ref, trigger_message)
self._event_type = event_filters['type']
if args.async_:
return operation
response = client.WaitFor(operation, 'Creating', trigger_ref, loading_msg)
trigger_dict = encoding.MessageToPyValue(response)
if types.IsPubsubType(self._event_type):
topic = trigger_dict['transport']['pubsub']['topic']
if args.IsSpecified('transport_topic'):
log.status.Print(
'Publish to Pub/Sub topic [{}] to receive events in {}.'.format(
topic, dest_str
)
)
else:
log.status.Print('Created Pub/Sub topic [{}].'.format(topic))
log.status.Print(
'Publish to this topic to receive events in {}.'.format(dest_str)
)
return response
def Epilog(self, resources_were_displayed):
if resources_were_displayed:
log.warning(
'It may take up to {} minutes for the new trigger to become active.'
.format(triggers.MAX_ACTIVE_DELAY_MINUTES)
)
def GetDestinationLocation(
self, args, trigger_ref, location_arg_name, destination_type
):
# If no Destination region was provided, use the trigger's location instead.
if not args.IsSpecified(location_arg_name):
destination_location = trigger_ref.Parent().Name()
if destination_location == 'global':
raise NoDestinationLocationSpecifiedError(
'The `{}` flag is required when creating a global trigger with a '
'destination {}.'.format(
args.GetFlag(location_arg_name), destination_type
)
)
else:
destination_location = args.GetValue(location_arg_name)
return destination_location

View File

@@ -0,0 +1,56 @@
# -*- 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.
"""Command to delete a trigger."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import triggers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To delete the trigger ``my-trigger'', run:
$ {command} my-trigger
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Delete(base.DeleteCommand):
"""Delete an Eventarc trigger."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddTriggerResourceArg(parser, 'The trigger to delete.', required=True)
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
"""Run the delete command."""
client = triggers.TriggersClientV1()
trigger_ref = args.CONCEPTS.trigger.Parse()
operation = client.Delete(trigger_ref)
if args.async_:
return operation
return client.WaitFor(operation, 'Deleting', trigger_ref)

View File

@@ -0,0 +1,64 @@
# -*- 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.
"""Command to describe a trigger."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import triggers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To describe the trigger ``my-trigger'', run:
$ {command} my-trigger
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Describe an Eventarc trigger."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddTriggerResourceArg(
parser, 'The trigger to describe.', required=True)
def Run(self, args):
"""Run the describe command."""
client = triggers.TriggersClientV1()
trigger_ref = args.CONCEPTS.trigger.Parse()
trigger = client.Get(trigger_ref)
event_type = client.GetEventType(trigger)
self._active_time = triggers.TriggerActiveTime(event_type,
trigger.updateTime)
return trigger
def Epilog(self, resources_were_displayed):
if resources_were_displayed and self._active_time:
log.warning(
'The trigger was recently modified and will become active by {}.'
.format(self._active_time))

View File

@@ -0,0 +1,158 @@
# -*- 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.
"""Command to list all triggers in a project and location."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import re
from googlecloudsdk.api_lib.eventarc import triggers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.eventarc import types
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To list all triggers in location ``us-central1'', run:
$ {command} --location=us-central1
To list all triggers in all locations, run:
$ {command} --location=-
or
$ {command}
""",
}
_FORMAT = """ \
table(
name.scope("triggers"):label=NAME,
eventFilters.type():label=TYPE,
destination():label=DESTINATION,
active_status():label=ACTIVE,
name.scope("locations").segment(0):label=LOCATION
)
"""
_FORMAT_BETA = """ \
table(
name.scope("triggers"):label=NAME,
matchingCriteria.type():label=TYPE,
destination.cloudRunService.service:label=DESTINATION_RUN_SERVICE,
destination.cloudRunService.path:label=DESTINATION_RUN_PATH,
active_status():label=ACTIVE
)
"""
def _ActiveStatus(trigger):
event_filters = trigger.get('eventFilters', trigger.get('matchingCriteria'))
event_type = types.EventFiltersDictToType(event_filters)
active_time = triggers.TriggerActiveTime(event_type, trigger['updateTime'])
return 'By {}'.format(active_time) if active_time else 'Yes'
def _Destination(trigger):
"""Generate a destination string for the trigger.
Based on different destination types, this function returns a destination
string accordingly:
* Cloud Run trigger: "Cloud Run: {cloud run service or job}"
* GKE trigger: "GKE: {gke service}"
* Workflows trigger: "Workflows: {workflow name}"
* Cloud Functions trigger: "Cloud Functions: {cloud function name}"
For unknown destination (e.g. new types of destination and corrupted
destination), this function returns an empty string.
Args:
trigger: eventarc trigger proto in python map format.
Returns:
A string representing the destination for the trigger.
"""
destination = trigger.get('destination')
if destination is None:
return ''
if 'cloudRun' in destination:
dest = destination.get('cloudRun')
# While not explicit in the API, these are effectively oneof.
job = dest.get('job')
if job:
return 'Cloud Run job: {}'.format(job)
service = dest.get('service')
return 'Cloud Run service: {}'.format(service)
elif 'gke' in destination:
dest = destination.get('gke')
return 'GKE: {}'.format(dest.get('service'))
elif 'cloudFunction' in destination:
cloud_function_str_pattern = '^projects/.*/locations/.*/functions/(.*)$'
dest = destination.get('cloudFunction')
match = re.search(cloud_function_str_pattern, dest)
return 'Cloud Functions: {}'.format(match.group(1)) if match else ''
elif 'workflow' in destination:
workflows_str_pattern = '^projects/.*/locations/.*/workflows/(.*)$'
dest = destination.get('workflow')
match = re.search(workflows_str_pattern, dest)
return 'Workflows: {}'.format(match.group(1)) if match else ''
elif 'httpEndpoint' in destination:
dest = destination.get('httpEndpoint')
return 'HTTP endpoint: {}'.format(dest.get('uri'))
else:
# For new types of triggers, return empty string for now.
return ''
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class List(base.ListCommand):
"""List Eventarc triggers."""
detailed_help = _DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddLocationResourceArg(
parser,
'The location for which to list triggers. This should be either '
"``global'' or one of the supported regions.",
required=False,
allow_aggregation=True,
)
flags.AddProjectResourceArg(parser)
parser.display_info.AddFormat(_FORMAT)
parser.display_info.AddUriFunc(triggers.GetTriggerURI)
parser.display_info.AddTransforms({
'active_status': _ActiveStatus,
'destination': _Destination,
'type': types.EventFiltersDictToType,
})
def Run(self, args):
"""Run the list command."""
client = triggers.TriggersClientV1()
args.CONCEPTS.project.Parse()
location_ref = args.CONCEPTS.location.Parse()
return client.List(location_ref, args.limit, args.page_size)

View File

@@ -0,0 +1,196 @@
# -*- 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.
"""Command to update a trigger."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.eventarc import triggers
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.eventarc import flags
from googlecloudsdk.command_lib.eventarc import types
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
_DETAILED_HELP = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
""" \
To update the trigger ``my-trigger'' by setting its destination Cloud Run service to ``my-service'', run:
$ {command} my-trigger --destination-run-service=my-service
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an Eventarc trigger."""
detailed_help = _DETAILED_HELP
@classmethod
def Args(cls, parser):
flags.AddTriggerResourceArg(parser, 'The trigger to update.', required=True)
flags.AddEventFiltersArg(parser, cls.ReleaseTrack())
flags.AddEventFiltersPathPatternArg(parser, cls.ReleaseTrack())
flags.AddEventDataContentTypeArg(parser, cls.ReleaseTrack())
flags.AddUpdateDestinationArgs(parser, cls.ReleaseTrack())
base.ASYNC_FLAG.AddToParser(parser)
service_account_group = parser.add_mutually_exclusive_group()
flags.AddServiceAccountArg(service_account_group)
flags.AddClearServiceAccountArg(service_account_group)
flags.AddTriggerRetryPolicyArgs(parser)
labels_util.AddUpdateLabelsFlags(parser)
def Run(self, args):
"""Run the update command."""
client = triggers.TriggersClientV1()
trigger_ref = args.CONCEPTS.trigger.Parse()
event_filters = flags.GetEventFiltersArg(args, self.ReleaseTrack())
event_filters_path_pattern = flags.GetEventFiltersPathPatternArg(
args, self.ReleaseTrack())
event_data_content_type = flags.GetEventDataContentTypeArg(
args, self.ReleaseTrack()
)
original_trigger = client.Get(trigger_ref)
labels_update_result = labels_util.Diff.FromUpdateArgs(args).Apply(
client.LabelsValueClass(), original_trigger.labels
)
update_mask = client.BuildUpdateMask(
event_filters=event_filters is not None,
event_filters_path_pattern=event_filters_path_pattern is not None,
event_data_content_type=event_data_content_type is not None,
service_account=args.IsSpecified('service_account')
or args.clear_service_account,
destination_run_service=args.IsSpecified('destination_run_service'),
destination_run_job=args.IsSpecified('destination_run_job'),
destination_run_path=args.IsSpecified('destination_run_path')
or args.clear_destination_run_path,
destination_run_region=args.IsSpecified('destination_run_region'),
destination_gke_namespace=args.IsSpecified('destination_gke_namespace'),
destination_gke_service=args.IsSpecified('destination_gke_service'),
destination_gke_path=args.IsSpecified('destination_gke_path')
or args.clear_destination_gke_path,
destination_workflow=args.IsSpecified('destination_workflow'),
destination_workflow_location=args.IsSpecified(
'destination_workflow_location'
),
destination_function=args.IsSpecified('destination_function'),
destination_function_location=args.IsSpecified(
'destination_function_location'
),
max_retry_attempts=args.IsSpecified('max_retry_attempts'),
labels=labels_update_result.needs_update,
)
# The type can't be updated, so it's safe to use the original trigger's
# type.
# In the async case, this is the only way to get the type.
self._event_type = client.GetEventType(original_trigger)
destination_message = None
if (args.IsSpecified('destination_run_service') or
args.IsSpecified('destination_run_job') or
args.IsSpecified('destination_run_region') or
args.IsSpecified('destination_run_path') or
args.clear_destination_run_path):
destination_message = client.BuildCloudRunDestinationMessage(
args.destination_run_service, args.destination_run_job,
args.destination_run_path, args.destination_run_region)
elif (args.IsSpecified('destination_gke_namespace') or
args.IsSpecified('destination_gke_service') or
args.IsSpecified('destination_gke_path') or
args.clear_destination_gke_path):
destination_message = client.BuildGKEDestinationMessage(
None, None, args.destination_gke_namespace,
args.destination_gke_service, args.destination_gke_path)
elif (args.IsSpecified('destination_workflow') or
args.IsSpecified('destination_workflow_location')):
location = self.GetWorkflowDestinationLocation(args, original_trigger)
workflow = self.GetWorkflowDestination(args, original_trigger)
destination_message = client.BuildWorkflowDestinationMessage(
trigger_ref.Parent().Parent().Name(), workflow, location)
elif (args.IsSpecified('destination_function') or
args.IsSpecified('destination_function_location')):
location = self.GetFunctionDestinationLocation(args, original_trigger)
function = self.GetFunctionDestination(args, original_trigger)
destination_message = client.BuildFunctionDestinationMessage(
trigger_ref.Parent().Parent().Name(), function, location)
trigger_message = client.BuildTriggerMessage(
trigger_ref,
event_filters,
event_filters_path_pattern,
event_data_content_type,
args.service_account,
destination_message,
None,
None,
args.max_retry_attempts,
labels_update_result.GetOrNone(),
)
operation = client.Patch(trigger_ref, trigger_message, update_mask)
if args.async_:
return operation
return client.WaitFor(operation, 'Updating', trigger_ref)
def Epilog(self, resources_were_displayed):
if resources_were_displayed and types.IsAuditLogType(self._event_type):
log.warning(
'It may take up to {} minutes for the update to take full effect.'
.format(triggers.MAX_ACTIVE_DELAY_MINUTES))
def GetWorkflowDestinationLocation(self, args, old_trigger):
if args.IsSpecified('destination_workflow_location'):
return args.destination_workflow_location
if old_trigger.destination.workflow:
return old_trigger.destination.workflow.split('/')[3]
raise exceptions.InvalidArgumentException(
'--destination-workflow',
'The specified trigger is not for a workflow destination.')
def GetWorkflowDestination(self, args, old_trigger):
if args.IsSpecified('destination_workflow'):
return args.destination_workflow
if old_trigger.destination.workflow:
return old_trigger.destination.workflow.split('/')[5]
raise exceptions.InvalidArgumentException(
'--destination-workflow-location',
'The specified trigger is not for a workflow destination.')
def GetFunctionDestinationLocation(self, args, old_trigger):
if args.IsSpecified('destination_function_location'):
return args.destination_function_location
if old_trigger.destination.cloudFunction:
return old_trigger.destination.cloudFunction.split('/')[3]
raise exceptions.InvalidArgumentException(
'--destination-function',
'The specified trigger is not for a function destination.')
def GetFunctionDestination(self, args, old_trigger):
if args.IsSpecified('destination_function'):
return args.destination_function
if old_trigger.destination.cloudFunction:
return old_trigger.destination.cloudFunction.split('/')[5]
raise exceptions.InvalidArgumentException(
'--destination-function-location',
'The specified trigger is not for a function destination.')