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,55 @@
# -*- 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 super-group for the AlloyDB CLI.
The fact that this is a directory with
an __init__.py in it makes it a command group. The methods written below will
all be called by calliope (though they are all optional).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
DETAILED_HELP = {
'DESCRIPTION': """
The gcloud alloydb command group lets you create and manage Google Cloud AlloyDB
databases.
AlloyDB is a fully-managed database service that makes it easy to set
up, maintain, manage, and administer your Alloydb databases in
the cloud.
More information on AlloyDB can be found at https://cloud.google.com/alloydb
""",
}
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class AlloyDB(base.Group):
"""Create and manage AlloyDB databases."""
category = base.DATABASES_CATEGORY
detailed_help = DETAILED_HELP
def Filter(self, context, args):
# TODO(b/190524014): Determine if command group works with project number
base.RequireProjectID(args)
del context, args
base.DisableUserProjectQuota()

View File

@@ -0,0 +1,32 @@
# -*- 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.
"""Provide commands for managing AlloyDB backups."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Backups(base.Group):
"""Provide commands for managing AlloyDB backups.
Provide commands for managing AlloyDB backups including creating,
deleting, and listing backups.
"""

View File

@@ -0,0 +1,184 @@
# -*- 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.
"""Creates a new AlloyDB backup."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import backup_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.kms import resource_args as kms_resource_args
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
def _ParseBackupType(alloydb_messages, backup_type):
if backup_type:
return alloydb_messages.Backup.TypeValueValuesEnum.lookup_by_name(
backup_type.upper())
return None
# TODO: b/312466999 - Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests.
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Create(base.CreateCommand):
"""Creates a new AlloyDB backup within a given project."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To create a new backup, run:
$ {command} my-backup --cluster=my-cluster --region=us-central1
To create a new cross-region backup, run:
$ {command} projects/my-project/locations/us-west1/backups/my-backup --cluster=my-cluster --region=us-central1
""",
}
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
base.ASYNC_FLAG.AddToParser(parser)
parser.add_argument(
'--region',
required=True,
type=str,
help='The region of the cluster to backup.',
)
parser.add_argument(
'backup',
type=str,
help=(
'The AlloyDB backup to create. This must either be the backup ID'
' (myBackup) or the full backup path'
' (projects/myProject/locations/us-central1/backups/myBackup). In'
' the first case, the project and location are assumed to be the'
' same as the cluster being backed up. The second form can be'
' used to create cross-region and cross-project backups.'
),
)
flags.AddCluster(parser, False)
flags.AddTags(parser)
kms_resource_args.AddKmsKeyResourceArg(
parser,
'backup',
permission_info=(
"The 'AlloyDB Service Agent' service account must hold permission"
" 'Cloud KMS CryptoKey Encrypter/Decrypter'"
),
)
def ConstructResourceFromArgs(
self, alloydb_messages, cluster_ref, backup_ref, args
):
backup_resource = alloydb_messages.Backup()
backup_resource.name = backup_ref.RelativeName()
backup_resource.type = _ParseBackupType(alloydb_messages, 'ON_DEMAND')
backup_resource.clusterName = cluster_ref.RelativeName()
backup_resource.tags = flags.GetTagsFromArgs(
args, alloydb_messages.Backup.TagsValue)
kms_key = flags.GetAndValidateKmsKeyName(args)
if kms_key:
encryption_config = alloydb_messages.EncryptionConfig()
encryption_config.kmsKeyName = kms_key
backup_resource.encryptionConfig = encryption_config
return backup_resource
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster)
backup_ref = client.resource_parser.Parse(
collection='alloydb.projects.locations.backups',
line=args.backup,
params={
'projectsId': properties.VALUES.core.project.GetOrFail,
'locationsId': args.region,
},
)
backup_resource = self.ConstructResourceFromArgs(
alloydb_messages, cluster_ref, backup_ref, args
)
req = alloydb_messages.AlloydbProjectsLocationsBackupsCreateRequest(
backup=backup_resource,
backupId=backup_ref.Name(),
parent=backup_ref.Parent().RelativeName(),
)
op = alloydb_client.projects_locations_backups.Create(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
backup_operations.Await(op_ref, 'Creating backup', self.ReleaseTrack())
return op
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
"""Create a new AlloyDB backup within a given project."""
@classmethod
def Args(cls, parser):
super(CreateBeta, cls).Args(parser)
flags.AddEnforcedRetention(parser)
def ConstructResourceFromArgs(
self, alloydb_messages, cluster_ref, backup_ref, args
):
backup_resource = super(CreateBeta, self).ConstructResourceFromArgs(
alloydb_messages, cluster_ref, backup_ref, args
)
if args.enforced_retention:
backup_resource.enforcedRetention = True
return backup_resource
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(CreateBeta):
"""Create a new AlloyDB backup within a given project."""
@classmethod
def Args(cls, parser):
super(CreateAlpha, cls).Args(parser)

View File

@@ -0,0 +1,92 @@
# -*- 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.
"""Deletes an AlloyDB backup."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import backup_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
"""Deletes an AlloyDB backup within a given project."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To delete a backup, run:
$ {command} my-backup --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser, Parser object for command line inputs
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddBackup(parser)
flags.AddRegion(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
backup_ref = client.resource_parser.Create(
'alloydb.projects.locations.backups',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
backupsId=args.backup)
prompt_message = (
'All of the backup data will be lost upon deletion.')
if not console_io.PromptContinue(message=prompt_message):
return None
req = alloydb_messages.AlloydbProjectsLocationsBackupsDeleteRequest(
name=backup_ref.RelativeName())
op = alloydb_client.projects_locations_backups.Delete(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
backup_operations.Await(op_ref, 'Deleting backup', self.ReleaseTrack(), False)
return op

View File

@@ -0,0 +1,75 @@
# -*- 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.
"""Creates a new AlloyDB backup."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describes an AlloyDB backup in a given project and region."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To describe a backup, run:
$ {command} my-backup --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
flags.AddRegion(parser)
flags.AddBackup(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
backup_ref = client.resource_parser.Create(
'alloydb.projects.locations.backups',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
backupsId=args.backup)
req = alloydb_messages.AlloydbProjectsLocationsBackupsGetRequest(
name=backup_ref.RelativeName())
return alloydb_client.projects_locations_backups.Get(req)

View File

@@ -0,0 +1,105 @@
# -*- 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.
"""Lists AlloyDB backups."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.core import properties
BACKUP_FORMAT = """
table(
name,
state:label=STATUS,
cluster_name,
create_time,
encryptionInfo.encryptionType:label=ENCRYPTION_TYPE
)
"""
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class List(base.ListCommand):
"""Lists AlloyDB backups in a given project.
Lists AlloyDB backups in a given project in the alphabetical order of the
backup name.
"""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To list backups, run:
$ {command} --region=us-central1
Use the --format flag to customize the fields that are outputted. For
example, to list backups with their names and sizes, run:
$ {command} --region=us-central1 --format="table(name, size_bytes)"
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
parser.add_argument(
'--region',
default='-',
help=('Regional location (e.g. asia-east1, us-east1). See the full '
'list of regions at '
'https://cloud.google.com/sql/docs/instance-locations. '
'Default: list clusters in all regions.'))
parser.display_info.AddFormat(BACKUP_FORMAT)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
location_ref = client.resource_parser.Create(
'alloydb.projects.locations',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region)
result = api_util.YieldFromListHandlingUnreachable(
alloydb_client.projects_locations_backups,
alloydb_messages.AlloydbProjectsLocationsBackupsListRequest(
parent=location_ref.RelativeName()),
field='backups',
limit=args.limit,
batch_size=args.page_size,
batch_size_attribute='pageSize'
)
return result

View File

@@ -0,0 +1,32 @@
# -*- 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.
"""Provide commands for managing AlloyDB clusters."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Clusters(base.Group):
"""Provide commands for managing AlloyDB clusters.
Provide commands for managing AlloyDB clusters including creating,
configuring, restarting, and deleting clusters.
"""

View File

@@ -0,0 +1,146 @@
# -*- 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.
"""Creates a new AlloyDB cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import cluster_helper
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.kms import resource_args as kms_resource_args
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
# TODO: b/312466999 - Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests.
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Create(base.CreateCommand):
"""Create a new AlloyDB cluster within a given project."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To create a new cluster, run:
$ {command} my-cluster --region=us-central1 --password=postgres
""",
}
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
alloydb_messages = api_util.GetMessagesModule(cls.ReleaseTrack())
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
flags.AddNetwork(parser)
flags.AddPassword(parser)
flags.AddAllocatedIPRangeName(parser)
kms_resource_args.AddKmsKeyResourceArg(
parser,
'cluster',
permission_info=(
"The 'AlloyDB Service Agent' service account must hold permission"
" 'Cloud KMS CryptoKey Encrypter/Decrypter'"
),
)
flags.AddAutomatedBackupFlags(
parser, alloydb_messages, cls.ReleaseTrack(), update=False
)
flags.AddContinuousBackupConfigFlags(parser, cls.ReleaseTrack())
flags.AddDatabaseVersion(parser, alloydb_messages, cls.ReleaseTrack())
flags.AddEnablePrivateServiceConnect(parser)
flags.AddMaintenanceWindow(parser, alloydb_messages)
flags.AddDenyMaintenancePeriod(parser, alloydb_messages)
flags.AddSubscriptionType(parser, alloydb_messages)
flags.AddTags(parser)
def ConstructCreateRequestFromArgs(self, alloydb_messages, location_ref,
args):
return cluster_helper.ConstructCreateRequestFromArgsGA(
alloydb_messages, location_ref, args)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
location_ref = client.resource_parser.Create(
'alloydb.projects.locations',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region)
req = self.ConstructCreateRequestFromArgs(alloydb_messages, location_ref,
args)
op = alloydb_client.projects_locations_clusters.Create(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
cluster_operations.Await(op_ref, 'Creating cluster', self.ReleaseTrack())
return op
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
"""Create a new AlloyDB cluster within a given project."""
@classmethod
def Args(cls, parser):
super(CreateBeta, cls).Args(parser)
def ConstructCreateRequestFromArgs(
self, alloydb_messages, location_ref, args
):
return cluster_helper.ConstructCreateRequestFromArgsBeta(
alloydb_messages, location_ref, args
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(CreateBeta):
"""Create a new AlloyDB cluster within a given project."""
@classmethod
def Args(cls, parser):
super(CreateAlpha, cls).Args(parser)
def ConstructCreateRequestFromArgs(
self, alloydb_messages, location_ref, args
):
return cluster_helper.ConstructCreateRequestFromArgsAlpha(
alloydb_messages, location_ref, args
)

View File

@@ -0,0 +1,135 @@
# -*- 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.
"""Creates a new AlloyDB secondary cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import cluster_helper
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.kms import resource_args as kms_resource_args
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class CreateSecondary(base.CreateCommand):
"""Create a new AlloyDB SECONDARY cluster within a given project."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To create a new cluster, run:
$ {command} my-cluster --region=us-central1 --primary-cluster=projects/12345/locations/us-central1/clusters/cluster1
""",
}
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
alloydb_messages = api_util.GetMessagesModule(cls.ReleaseTrack())
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
flags.AddPrimaryCluster(parser)
flags.AddAllocatedIPRangeName(parser)
flags.AddContinuousBackupConfigFlagsForCreateSecondary(parser)
flags.AddAutomatedBackupFlagsForCreateSecondary(parser, alloydb_messages)
flags.AddTags(parser)
kms_resource_args.AddKmsKeyResourceArg(
parser,
'cluster',
permission_info=(
"The 'AlloyDB Service Agent' service account must hold permission"
" 'Cloud KMS CryptoKey Encrypter/Decrypter'"
),
)
def ConstructCreateSecondaryRequestFromArgs(
self, alloydb_messages, location_ref, args):
return cluster_helper.ConstructCreatesecondaryRequestFromArgsGA(
alloydb_messages, location_ref, args)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
location_ref = client.resource_parser.Create(
'alloydb.projects.locations',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
)
req = self.ConstructCreateSecondaryRequestFromArgs(
alloydb_messages, location_ref, args
)
op = alloydb_client.projects_locations_clusters.Createsecondary(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations'
)
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
cluster_operations.Await(op_ref, 'Creating cluster', self.ReleaseTrack())
return op
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateSecondaryBeta(CreateSecondary):
"""Create a new AlloyDB SECONDARY cluster within a given project."""
@classmethod
def Args(cls, parser):
super(CreateSecondaryBeta, cls).Args(parser)
def ConstructCreateSecondaryRequestFromArgs(
self, alloydb_messages, location_ref, args):
return cluster_helper.ConstructCreatesecondaryRequestFromArgsBeta(
alloydb_messages, location_ref, args)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateSecondaryAlpha(CreateSecondaryBeta):
"""Create a new AlloyDB SECONDARY cluster within a given project."""
@classmethod
def Args(cls, parser):
super(CreateSecondaryAlpha, cls).Args(parser)
def ConstructCreateSecondaryRequestFromArgs(
self, alloydb_messages, location_ref, args
):
return cluster_helper.ConstructCreatesecondaryRequestFromArgsAlpha(
alloydb_messages, location_ref, args
)

View File

@@ -0,0 +1,92 @@
# -*- 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.
"""Deletes a AlloyDB cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
"""Delete an AlloyDB cluster in a given region."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To delete a cluster, run:
$ {command} my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
flags.AddForce(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region, clustersId=args.cluster)
prompt_message = (
'All of the cluster data will be lost when the cluster is deleted.')
if not console_io.PromptContinue(message=prompt_message):
return None
req = alloydb_messages.AlloydbProjectsLocationsClustersDeleteRequest(
name=cluster_ref.RelativeName(), force=args.force)
op = alloydb_client.projects_locations_clusters.Delete(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
cluster_operations.Await(op_ref, 'Deleting cluster', self.ReleaseTrack(),
False)
return op

View File

@@ -0,0 +1,90 @@
# -*- 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.
"""Describes a AlloyDB cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describe an AlloyDB cluster in a given project and region."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To describe a cluster, run:
$ {command} my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
flags.AddRegion(parser)
flags.AddCluster(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region, clustersId=args.cluster)
req = alloydb_messages.AlloydbProjectsLocationsClustersGetRequest(
name=cluster_ref.RelativeName()
)
cluster = alloydb_client.projects_locations_clusters.Get(req)
normalize_automated_backup_policy(cluster.automatedBackupPolicy)
return cluster
def normalize_automated_backup_policy(policy):
"""Normalizes the policy so that it looks correct when printed."""
if policy is None:
return
if policy.weeklySchedule is None:
return
for start_time in policy.weeklySchedule.startTimes:
# If the customer selects 00:00 as a start time, this ultimately becomes
# a start time with all None fields. In the terminal this is then
# confusingly printed as `{}`. We manually set the hours to be 0 in this
# case so that it appears as `hours: 0`.
if start_time.hours is None:
start_time.hours = 0

View File

@@ -0,0 +1,111 @@
# -*- 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.
"""Exports data from an AlloyDB cluster to Google Cloud Storage."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import cluster_helper
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
# TODO: b/312466999 - Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests.
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Export(base.SilentCommand):
"""Export data from an AlloyDB cluster to Google Cloud Storage."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To export a cluster, run:
$ {command} my-cluster --region=us-central1 --database=my-database --gcs-uri=gs://my-bucket/my-export-file-path --csv --select-query="SELECT * FROM my-table"
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
flags.AddDatabase(parser)
flags.AddDestinationURI(parser)
flags.AddExportOptions(parser)
def ConstructExportRequestFromArgs(
self, alloydb_messages, cluster_ref, args
):
return cluster_helper.ConstructExportRequestFromArgs(
alloydb_messages, cluster_ref, args
)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster)
req = self.ConstructExportRequestFromArgs(
alloydb_messages, cluster_ref, args
)
op = alloydb_client.projects_locations_clusters.Export(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
if not args.async_:
cluster_operations.Await(
op_ref, 'Exporting cluster', self.ReleaseTrack(), False
)
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
return op
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ExportAlpha(Export):
"""Export data from an AlloyDB cluster to Google Cloud Storage."""
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class ExportBeta(Export):
"""Export data from an AlloyDB cluster to Google Cloud Storage."""

View File

@@ -0,0 +1,110 @@
# -*- 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.
"""Imports data into an AlloyDB cluster from Google Cloud Storage."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import cluster_helper
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
# TODO: b/312466999 - Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests.
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Import(base.SilentCommand):
"""Import data into an AlloyDB cluster from Google Cloud Storage."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To import data into a cluster, run:
$ {command} my-cluster --region=us-central1 --database=my-database --gcs-uri=gs://my-bucket/source-file-path --sql --user=my-user"
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
flags.AddDatabase(parser, False)
flags.AddSourceURI(parser)
flags.AddImportUser(parser)
flags.AddImportOptions(parser)
def ConstructImportRequestFromArgs(self, alloydb_messages, cluster_ref, args):
return cluster_helper.ConstructImportRequestFromArgs(
alloydb_messages, cluster_ref, args
)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
)
req = self.ConstructImportRequestFromArgs(
alloydb_messages, cluster_ref, args
)
op = alloydb_client.projects_locations_clusters.Import(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations'
)
if not args.async_:
cluster_operations.Await(
op_ref, 'Importing data from cluster', self.ReleaseTrack(), False
)
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
return op
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ImportAlpha(Import):
"""Import data to an AlloyDB cluster from Google Cloud Storage."""
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class ImportBeta(Import):
"""Import data to an AlloyDB cluster from Google Cloud Storage."""

View File

@@ -0,0 +1,99 @@
# -*- 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.
"""Lists AlloyDB clusters."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.core import properties
CLUSTER_FORMAT = """
table(
name,
network,
state:label=STATUS
)
"""
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List AlloyDB clusters in a given project and region.
List AlloyDB clusters in a given project in alphabetical
order based on the cluster name.
"""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To list clusters, run:
$ {command} --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Constructs and sends request.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
parser.add_argument(
'--region',
default='-',
help=('Regional location (e.g. asia-east1, us-east1). See the full '
'list of regions at '
'https://cloud.google.com/sql/docs/instance-locations. '
'Default: list clusters in all regions.'))
parser.display_info.AddFormat(CLUSTER_FORMAT)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
location_ref = client.resource_parser.Create(
'alloydb.projects.locations',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region)
result = api_util.YieldFromListHandlingUnreachable(
alloydb_client.projects_locations_clusters,
alloydb_messages.AlloydbProjectsLocationsClustersListRequest(
parent=location_ref.RelativeName()
),
field='clusters',
limit=args.limit,
batch_size=args.page_size,
batch_size_attribute='pageSize',
)
return result

View File

@@ -0,0 +1,208 @@
# -*- 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.
"""Migrates a Cloud SQL instance to an AlloyDB cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import argparse
import types
from apitools.base.protorpclite import messages
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import cluster_helper
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.kms import resource_args as kms_resource_args
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
# TODO: b/312466999 - Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests.
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class MigrateCloudSqlGA(base.RestoreCommand):
"""Migrate Cloud SQL instance to an AlloyDB cluster using an existing Cloud SQL backup."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To migrate a Cloud SQL instance to an AlloyDB cluster from a backup, run:
$ {command} my-alloydb-cluster --region=us-central1 --cloud-sql-project-id=my-cloud-sql-project-id --cloud-sql-instance-id=my-cloud-sql-cluster-id --cloud-sql-backup-id=my-cloud-sql-backup-id
""",
}
@classmethod
def Args(cls, parser: argparse.PARSER) -> None:
"""Specifies additional command flags.
Args:
parser: Parser object for command line inputs.
"""
alloydb_messages = api_util.GetMessagesModule(cls.ReleaseTrack())
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
flags.AddNetwork(parser)
flags.AddPassword(parser)
flags.AddAllocatedIPRangeName(parser)
kms_resource_args.AddKmsKeyResourceArg(
parser,
'cluster',
permission_info=(
"The 'AlloyDB Service Agent' service account must hold permission"
" 'Cloud KMS CryptoKey Encrypter/Decrypter'"
),
)
flags.AddAutomatedBackupFlags(
parser, alloydb_messages, cls.ReleaseTrack(), update=False
)
flags.AddContinuousBackupConfigFlags(parser, cls.ReleaseTrack())
flags.AddDatabaseVersion(parser, alloydb_messages, cls.ReleaseTrack())
flags.AddEnablePrivateServiceConnect(parser)
flags.AddMaintenanceWindow(parser, alloydb_messages)
flags.AddSubscriptionType(parser, alloydb_messages)
flags.AddTags(parser)
flags.AddMigrateCloudSqlFlags(parser)
flags.AddDenyMaintenancePeriod(parser, alloydb_messages)
def ConstructMigrateCloudSqlRequestFromArgs(
self,
alloydb_messages: types.ModuleType,
location_ref: resources.Resource,
args: argparse.Namespace,
) -> messages.Message:
"""Constructs the Migrate Cloud Sql request.
Args:
alloydb_messages: The AlloyDB messages module.
location_ref: The location reference for the request.
args: An object that contains the values for the arguments specified in
the .Args() method.
Returns:
The Migrate Cloud Sql request based on args.
"""
return cluster_helper.ConstructMigrateCloudSqlRequestFromArgsGA(
alloydb_messages, location_ref, args
)
def Run(self, args: argparse.Namespace) -> messages.Message:
"""Constructs request from args, and sends it to the server.
Args:
args: An object that contains the values for the arguments specified in
the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
location_ref = client.resource_parser.Create(
'alloydb.projects.locations',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
)
req = self.ConstructMigrateCloudSqlRequestFromArgs(
alloydb_messages, location_ref, args
)
op = alloydb_client.projects_locations_clusters.RestoreFromCloudSQL(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations'
)
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
cluster_operations.Await(
op_ref, 'Migrating Cloud SQL', self.ReleaseTrack()
)
return op
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class MigrateCloudSqlBeta(MigrateCloudSqlGA):
"""Migrate Cloud SQL instance to an AlloyDB cluster.
This command migrates a Cloud SQL instance to an AlloyDB cluster using an
existing Cloud SQL backup.
"""
@classmethod
def Args(cls, parser: argparse.PARSER) -> None:
super(MigrateCloudSqlBeta, cls).Args(parser)
def ConstructMigrateCloudSqlRequestFromArgs(
self,
alloydb_messages: types.ModuleType,
location_ref: resources.Resource,
args: argparse.Namespace,
) -> messages.Message:
"""Constructs the Migrate Cloud Sql request.
Args:
alloydb_messages: The AlloyDB messages module.
location_ref: The location reference for the request.
args: An object that contains the values for the arguments specified in
the .Args() method.
Returns:
The Migrate Cloud Sql request based on args.
"""
return cluster_helper.ConstructMigrateCloudSqlRequestFromArgsBeta(
alloydb_messages, location_ref, args
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class MigrateCloudSqlAlpha(MigrateCloudSqlGA):
"""Migrate Cloud SQL instance to an AlloyDB cluster.
This command migrates a Cloud SQL instance to an AlloyDB cluster using an
existing Cloud SQL backup.
"""
@classmethod
def Args(cls, parser: argparse.PARSER) -> None:
super(MigrateCloudSqlAlpha, cls).Args(parser)
def ConstructMigrateCloudSqlRequestFromArgs(
self,
alloydb_messages: types.ModuleType,
location_ref: resources.Resource,
args: argparse.Namespace,
) -> messages.Message:
"""Constructs the Migrate Cloud Sql request.
Args:
alloydb_messages: The AlloyDB messages module.
location_ref: The location reference for the request.
args: An object that contains the values for the arguments specified in
the .Args() method.
Returns:
The Migrate Cloud Sql request based on args.
"""
return cluster_helper.ConstructMigrateCloudSqlRequestFromArgsAlpha(
alloydb_messages, location_ref, args
)

View File

@@ -0,0 +1,83 @@
# -*- 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.
"""Promote an AlloyDB cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Promote(base.UpdateCommand):
"""Promote an AlloyDB SECONDARY cluster in a given project and region."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To promote a cluster, run:
$ {command} my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster)
req = alloydb_messages.AlloydbProjectsLocationsClustersPromoteRequest(
name=cluster_ref.RelativeName(),
promoteClusterRequest=alloydb_messages.PromoteClusterRequest())
op = alloydb_client.projects_locations_clusters.Promote(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
cluster_operations.Await(op_ref, 'Promoting cluster', self.ReleaseTrack())
return op

View File

@@ -0,0 +1,177 @@
# -*- 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.
"""Restores an AlloyDB cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import cluster_helper
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.kms import resource_args as kms_resource_args
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Restore(base.RestoreCommand):
# TODO(b/407008589): update the description and examples for Backup DR.
"""Restore an AlloyDB cluster from a given backup or a source cluster and a timestamp."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To restore a cluster from a backup, run:
$ {command} my-cluster --region=us-central1 --backup=my-backup
To restore a cluster from a source cluster and a timestamp, run:
$ {command} my-cluster --region=us-central1 \
--source-cluster=old-cluster \
--point-in-time=2012-11-15T16:19:00.094Z
""",
}
@staticmethod
def CommonArgs(parser):
base.ASYNC_FLAG.AddToParser(parser)
flags.AddCluster(parser)
flags.AddRegion(parser)
flags.AddNetwork(parser)
flags.AddAllocatedIPRangeName(parser)
flags.AddEnablePrivateServiceConnect(parser)
flags.AddTags(parser)
kms_resource_args.AddKmsKeyResourceArg(
parser,
'cluster',
permission_info=(
"The 'AlloyDB Service Agent' service account must hold permission"
" 'Cloud KMS CryptoKey Encrypter/Decrypter'"
),
)
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
Restore.CommonArgs(parser)
flags.AddRestoreClusterSourceFlags(parser, cls.ReleaseTrack())
def ConstructRestoreRequestFromArgs(self, alloydb_messages, location_ref,
resource_parser, args):
return cluster_helper.ConstructRestoreRequestFromArgsGA(
alloydb_messages, location_ref, resource_parser, args)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
location_ref = client.resource_parser.Create(
'alloydb.projects.locations',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region)
req = self.ConstructRestoreRequestFromArgs(
alloydb_messages, location_ref, client.resource_parser, args)
op = alloydb_client.projects_locations_clusters.Restore(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
cluster_operations.Await(op_ref, 'Restoring cluster', self.ReleaseTrack())
return op
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class RestoreBeta(Restore):
"""Restore an AlloyDB cluster from a given backup or a source cluster and a timestamp."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To restore a cluster from a backup, run:
$ {command} my-cluster --region=us-central1 --backup=my-backup
To restore a cluster from a source cluster and a timestamp, run:
$ {command} my-cluster --region=us-central1 \
--source-cluster=old-cluster \
--point-in-time=2012-11-15T16:19:00.094Z
""",
}
@classmethod
def Args(cls, parser):
super(RestoreBeta, cls).Args(parser)
def ConstructRestoreRequestFromArgs(
self, alloydb_messages, location_ref, resource_parser, args
):
return cluster_helper.ConstructRestoreRequestFromArgsBeta(
alloydb_messages, location_ref, resource_parser, args
)
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class RestoreAlpha(RestoreBeta):
"""Restore an AlloyDB cluster from a given backup or a source cluster and a timestamp."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To restore a cluster from a backup, run:
$ {command} my-cluster --region=us-central1 --backup=my-backup
To restore a cluster from a source cluster and a timestamp, run:
$ {command} my-cluster --region=us-central1 \
--source-cluster=old-cluster \
--point-in-time=2012-11-15T16:19:00.094Z
""",
}
@classmethod
def Args(cls, parser):
super(RestoreAlpha, cls).Args(parser)
def ConstructRestoreRequestFromArgs(
self, alloydb_messages, location_ref, resource_parser, args
):
return cluster_helper.ConstructRestoreRequestFromArgsAlpha(
alloydb_messages, location_ref, resource_parser, args
)

View File

@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Switchover an AlloyDB cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Switchover(base.UpdateCommand):
"""Switchover an AlloyDB SECONDARY cluster in a given project and region."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To switchover a cluster, run:
$ {command} my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
)
req = alloydb_messages.AlloydbProjectsLocationsClustersSwitchoverRequest(
name=cluster_ref.RelativeName(),
switchoverClusterRequest=alloydb_messages.SwitchoverClusterRequest(),
)
op = alloydb_client.projects_locations_clusters.Switchover(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations'
)
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
cluster_operations.Await(
op_ref, 'Switchover cluster', self.ReleaseTrack()
)
return op

View File

@@ -0,0 +1,134 @@
# -*- 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.
"""Updates a AlloyDB cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.alloydb import cluster_helper
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
# TODO: b/312466999 - Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests.
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Update(base.UpdateCommand):
"""Update an AlloyDB cluster within a given project and region."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To update a cluster, run:
$ {command} my-cluster --region=us-central1 --automated-backup-start-times=12:00 --automated-backup-days-of-week=MONDAY --automated-backup-retention-count=10
""",
}
def __init__(self, *args, **kwargs):
super(Update, self).__init__(*args, **kwargs)
self.parameters = [
(
'--automated-backup-* | --disable-automated-backup | '
'--clear-automated-backup'
),
(
'--enable-continuous-backup | '
'--continuous-backup-* | --clear-continuous-backup-encryption-key'
),
]
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
alloydb_messages = api_util.GetMessagesModule(cls.ReleaseTrack())
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
flags.AddAutomatedBackupFlags(
parser, alloydb_messages, cls.ReleaseTrack(), update=True
)
flags.AddContinuousBackupConfigFlags(
parser, cls.ReleaseTrack(), update=True
)
flags.AddMaintenanceWindow(parser, alloydb_messages, update=True)
flags.AddDenyMaintenancePeriod(parser, alloydb_messages, update=True)
flags.AddMaintenanceVersion(parser)
flags.AddSubscriptionType(parser, alloydb_messages)
def ConstructPatchRequestFromArgs(self, alloydb_messages, cluster_ref, args):
return cluster_helper.ConstructPatchRequestFromArgsGA(
alloydb_messages, cluster_ref, args)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster)
req = self.ConstructPatchRequestFromArgs(alloydb_messages, cluster_ref,
args)
if not req.updateMask:
raise exceptions.MinimumArgumentException(
self.parameters, 'Please specify at least one property to update')
op = alloydb_client.projects_locations_clusters.Patch(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
cluster_operations.Await(op_ref, 'Updating cluster', self.ReleaseTrack(),
False)
return op
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class UpdateBeta(Update):
"""Update an AlloyDB cluster within a given project and region."""
@classmethod
def Args(cls, parser):
super(UpdateBeta, UpdateBeta).Args(parser)
def ConstructPatchRequestFromArgs(self, alloydb_messages, cluster_ref, args):
return cluster_helper.ConstructPatchRequestFromArgsBeta(
alloydb_messages, cluster_ref, args
)

View File

@@ -0,0 +1,109 @@
# -*- 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.
"""Upgrades a AlloyDB cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import cluster_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.alloydb import cluster_helper
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
# TODO: b/312466999 - Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests.
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Upgrade(base.SilentCommand):
"""Upgrade an AlloyDB cluster within a given project and region."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To upgrade a cluster, run:
$ {command} my-cluster --region=us-central1 --version=POSTGRES_15
""",
}
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
alloydb_messages = api_util.GetMessagesModule(cls.ReleaseTrack())
base.ASYNC_FLAG.AddToParser(parser)
flags.AddRegion(parser)
flags.AddCluster(parser)
flags.AddVersion(parser, alloydb_messages)
def ConstructUpgradeRequestFromArgs(
self, alloydb_messages, cluster_ref, args
):
return cluster_helper.ConstructUpgradeRequestFromArgs(
alloydb_messages, cluster_ref, args
)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
)
req = self.ConstructUpgradeRequestFromArgs(
alloydb_messages, cluster_ref, args
)
if not req.upgradeClusterRequest.version:
raise exceptions.MinimumArgumentException(
self.parameters,
'Please specify target version for upgrade in --version flag',
)
op = alloydb_client.projects_locations_clusters.Upgrade(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations'
)
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
cluster_operations.Await(
op_ref, 'Upgrading cluster', self.ReleaseTrack(), False
)
return op

View File

@@ -0,0 +1,32 @@
# -*- 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.
"""Provide commands for managing AlloyDB instances."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Clusters(base.Group):
"""Provide commands for managing AlloyDB instances.
Provide commands for managing AlloyDB clusters including creating,
configuring, restarting, and deleting instances.
"""

View File

@@ -0,0 +1,194 @@
# -*- 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.
"""Creates a new AlloyDB instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import instance_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.alloydb import instance_helper
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
# TODO(b/312466999): Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests.
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Create(base.CreateCommand):
"""Creates a new AlloyDB instance within a given cluster."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To create a new primary instance, run:
$ {command} my-instance --cluster=my-cluster --region=us-central1 --instance-type=PRIMARY --cpu-count=4
To create a new read pool instance, run:
$ {command} my-instance --cluster=my-cluster --region=us-central1 --instance-type=READ_POOL --read-pool-node-count=1 --cpu-count=4
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddAvailabilityType(parser)
flags.AddCluster(parser, False)
flags.AddDatabaseFlags(parser)
flags.AddInstance(parser)
flags.AddInstanceType(parser)
flags.AddCPUCount(parser, required=False)
flags.AddMachineType(parser)
flags.AddReadPoolNodeCount(parser)
flags.AddRegion(parser)
flags.AddInsightsConfigQueryStringLength(parser)
flags.AddInsightsConfigQueryPlansPerMinute(parser)
flags.AddInsightsConfigRecordApplicationTags(
parser, show_negated_in_help=True
)
flags.AddInsightsConfigRecordClientAddress(
parser, show_negated_in_help=True
)
flags.AddSSLMode(parser)
flags.AddRequireConnectors(parser)
flags.AddAssignInboundPublicIp(parser)
flags.AddAuthorizedExternalNetworks(parser)
flags.AddOutboundPublicIp(parser, show_negated_in_help=True)
flags.AddAllowedPSCProjects(parser)
flags.AddPSCNetworkAttachmentUri(parser)
flags.AddPSCAutoConnections(parser)
flags.AddAllocatedIPRangeOverride(parser)
# Connection pooling flags.
flags.AddEnableConnectionPooling(parser)
flags.AddConnectionPoolingPoolMode(parser)
flags.AddConnectionPoolingMinPoolSize(parser)
flags.AddConnectionPoolingMaxPoolSize(parser)
flags.AddConnectionPoolingMaxClientConnections(parser)
flags.AddConnectionPoolingServerIdleTimeout(parser)
flags.AddConnectionPoolingQueryWaitTimeout(parser)
flags.AddConnectionPoolingStatsUsers(parser)
flags.AddConnectionPoolingIgnoreStartupParameters(parser)
flags.AddConnectionPoolingServerLifetime(parser)
flags.AddConnectionPoolingClientConnectionIdleTimeout(parser)
flags.AddConnectionPoolingMaxPreparedStatements(parser)
# TODO(b/185795425): Add --ssl-required and --labels later once we
# understand the use cases
def ConstructCreateRequestFromArgs(
self, client, alloydb_messages, cluster_ref, args
):
return instance_helper.ConstructCreateRequestFromArgsGA(
client, alloydb_messages, cluster_ref, args
)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster)
req = self.ConstructCreateRequestFromArgs(
client, alloydb_messages, cluster_ref, args
)
op = alloydb_client.projects_locations_clusters_instances.Create(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
instance_operations.Await(op_ref, 'Creating instance',
self.ReleaseTrack())
return op
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
"""Creates a new AlloyDB instance within a given cluster."""
@classmethod
def Args(cls, parser):
super(CreateBeta, CreateBeta).Args(parser)
flags.AddObservabilityConfigEnabled(
parser, show_negated_in_help=True
)
flags.AddObservabilityConfigPreserveComments(
parser, show_negated_in_help=True
)
flags.AddObservabilityConfigTrackWaitEvents(
parser, show_negated_in_help=False
)
flags.AddObservabilityConfigMaxQueryStringLength(parser)
flags.AddObservabilityConfigRecordApplicationTags(
parser, show_negated_in_help=True
)
flags.AddObservabilityConfigQueryPlansPerMinute(parser)
flags.AddObservabilityConfigTrackActiveQueries(
parser, show_negated_in_help=True
)
flags.AddAutoscalerCreateFlags(parser)
def ConstructCreateRequestFromArgs(
self, client, alloydb_messages, cluster_ref, args
):
return instance_helper.ConstructCreateRequestFromArgsBeta(
client, alloydb_messages, cluster_ref, args
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(CreateBeta):
"""Creates a new AlloyDB instance within a given cluster."""
@classmethod
def Args(cls, parser):
super(CreateAlpha, CreateAlpha).Args(parser)
def ConstructCreateRequestFromArgs(
self, client, alloydb_messages, cluster_ref, args
):
return instance_helper.ConstructCreateRequestFromArgsAlpha(
client, alloydb_messages, cluster_ref, args
)

View File

@@ -0,0 +1,158 @@
# -*- 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.
"""Creates a new AlloyDB secondary instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import instance_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.alloydb import instance_helper
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
# TODO(b/312466999): Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests.
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class CreateSecondary(base.CreateCommand):
"""Creates a new AlloyDB SECONDARY instance within a given cluster."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To create a new secondary instance, run:
$ {command} my-instance --cluster=my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddCluster(parser, False)
flags.AddAvailabilityType(parser)
flags.AddInstance(parser)
flags.AddRegion(parser)
flags.AddDatabaseFlags(parser)
flags.AddSSLMode(parser, default_from_primary=True)
flags.AddRequireConnectors(parser)
flags.AddAssignInboundPublicIp(parser)
flags.AddAuthorizedExternalNetworks(parser)
flags.AddOutboundPublicIp(parser, show_negated_in_help=True)
flags.AddAllowedPSCProjects(parser)
flags.AddPSCNetworkAttachmentUri(parser)
flags.AddPSCAutoConnections(parser)
flags.AddAllocatedIPRangeOverride(parser)
# Connection pooling flags.
flags.AddEnableConnectionPooling(parser)
flags.AddConnectionPoolingPoolMode(parser)
flags.AddConnectionPoolingMinPoolSize(parser)
flags.AddConnectionPoolingMaxPoolSize(parser)
flags.AddConnectionPoolingMaxClientConnections(parser)
flags.AddConnectionPoolingServerIdleTimeout(parser)
flags.AddConnectionPoolingQueryWaitTimeout(parser)
flags.AddConnectionPoolingStatsUsers(parser)
flags.AddConnectionPoolingIgnoreStartupParameters(parser)
flags.AddConnectionPoolingServerLifetime(parser)
flags.AddConnectionPoolingClientConnectionIdleTimeout(parser)
flags.AddConnectionPoolingMaxPreparedStatements(parser)
def ConstructSecondaryCreateRequestFromArgs(
self, client, alloydb_messages, cluster_ref, args
):
return instance_helper.ConstructSecondaryCreateRequestFromArgsGA(
client, alloydb_messages, cluster_ref, args
)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
)
req = self.ConstructSecondaryCreateRequestFromArgs(
client, alloydb_messages, cluster_ref, args
)
op = alloydb_client.projects_locations_clusters_instances.Createsecondary(
req
)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations'
)
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
instance_operations.Await(
op_ref, 'Creating secondary instance', self.ReleaseTrack()
)
return op
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateSecondaryBeta(CreateSecondary):
"""Creates a new AlloyDB SECONDARY instance within a given cluster."""
@classmethod
def Args(cls, parser):
super(CreateSecondaryBeta, CreateSecondaryBeta).Args(parser)
def ConstructSecondaryCreateRequestFromArgs(
self, client, alloydb_messages, cluster_ref, args
):
return instance_helper.ConstructSecondaryCreateRequestFromArgsBeta(
client, alloydb_messages, cluster_ref, args
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateSecondaryAlpha(CreateSecondaryBeta):
"""Creates a new AlloyDB SECONDARY instance within a given cluster."""
@classmethod
def Args(cls, parser):
super(CreateSecondaryAlpha, CreateSecondaryAlpha).Args(parser)
def ConstructSecondaryCreateRequestFromArgs(
self, client, alloydb_messages, cluster_ref, args
):
return instance_helper.ConstructSecondaryCreateRequestFromArgsAlpha(
client, alloydb_messages, cluster_ref, args
)

View File

@@ -0,0 +1,94 @@
# -*- 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.
"""Deletes an AlloyDB instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import instance_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
"""Deletes an AlloyDB instance within a given cluster."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To delete an instance, run:
$ {command} my-instance --cluster=my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser, Parser object for command line inputs
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddCluster(parser, False)
flags.AddInstance(parser)
flags.AddRegion(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
instance_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters.instances',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
instancesId=args.instance)
prompt_message = (
'Instance settings and IPs will be deleted on upon deletion.')
if not console_io.PromptContinue(message=prompt_message):
return None
req = alloydb_messages.AlloydbProjectsLocationsClustersInstancesDeleteRequest(
name=instance_ref.RelativeName())
op = alloydb_client.projects_locations_clusters_instances.Delete(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
instance_operations.Await(op_ref, 'Deleting instance', self.ReleaseTrack(), False)
return op

View File

@@ -0,0 +1,88 @@
# -*- 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.
"""Describes an AlloyDB instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describes an AlloyDB instance within a given cluster."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To describe an instance, run:
$ {command} my-instance --cluster=my-cluster --region=us-central1
--view=BASIC/FULL
""",
}
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs
"""
alloydb_messages = api_util.GetMessagesModule(cls.ReleaseTrack())
flags.AddCluster(parser, False)
flags.AddInstance(parser)
flags.AddRegion(parser)
flags.AddView(parser, alloydb_messages)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
instance_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters.instances',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
instancesId=args.instance)
if args.view:
req = alloydb_messages.AlloydbProjectsLocationsClustersInstancesGetRequest(
name=instance_ref.RelativeName(),
view=flags.GetInstanceViewFlagMapper(
alloydb_messages).GetEnumForChoice(args.view))
else:
req = alloydb_messages.AlloydbProjectsLocationsClustersInstancesGetRequest(
name=instance_ref.RelativeName())
op = alloydb_client.projects_locations_clusters_instances.Get(req)
return op

View File

@@ -0,0 +1,86 @@
# -*- 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.
"""Failover an AlloyDB instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import instance_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Failover(base.SilentCommand):
"""Failover an AlloyDB instance within a given cluster."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To failover an instance, run:
$ {command} my-instance --cluster=my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser, Parser object for command line inputs
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddCluster(parser, False)
flags.AddInstance(parser)
flags.AddRegion(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
project_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters.instances',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
instancesId=args.instance)
req = alloydb_messages.AlloydbProjectsLocationsClustersInstancesFailoverRequest(
name=project_ref.RelativeName())
op = alloydb_client.projects_locations_clusters_instances.Failover(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations')
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
instance_operations.Await(op_ref, 'Failing over instance',
self.ReleaseTrack(), False)
return op

View File

@@ -0,0 +1,96 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Inject fault on an AlloyDB instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import instance_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class InjectFault(base.SilentCommand):
"""Inject fault on an AlloyDB instance within a given cluster."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To Inject fault on an instance, run:
$ {command} my-instance --cluster=my-cluster --region=us-central1 --fault-type=stop-vm
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser, Parser object for command line inputs
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddCluster(parser, False)
flags.AddInstance(parser)
flags.AddRegion(parser)
flags.AddFaultType(parser, True)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
fault_type = flags.GetInjectFaultTypeFlagMapper(
alloydb_messages
).GetEnumForChoice(args.fault_type)
project_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters.instances',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
instancesId=args.instance,
)
req = alloydb_messages.AlloydbProjectsLocationsClustersInstancesInjectFaultRequest(
name=project_ref.RelativeName(),
injectFaultRequest=alloydb_messages.InjectFaultRequest(
faultType=fault_type
),
)
op = alloydb_client.projects_locations_clusters_instances.InjectFault(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations'
)
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
instance_operations.Await(
op_ref, 'Injecting fault over instance', self.ReleaseTrack(), False
)
return op

View File

@@ -0,0 +1,103 @@
# -*- 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.
"""Lists AlloyDB instances in a given cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.core import properties
_INSTANCE_FORMAT = """
table(
name,
instanceType:label="INSTANCE_TYPE",
state:label=STATUS
)
"""
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class List(base.ListCommand):
"""Lists AlloyDB instances in a given cluster."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To list instances, run:
$ {command} --cluster=my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs
"""
cluster_args = parser.add_argument_group(help='Cluster')
cluster_args.add_argument(
'--region',
required=True,
default='-',
help=('Regional location (e.g. asia-east1, us-east1) of CLUSTER. '
'See the full list of regions at '
'https://cloud.google.com/sql/docs/instance-locations. '
'Default: list clusters in all regions.'))
cluster_args.add_argument(
'--cluster',
required=True,
default='-',
help=('AlloyDB cluster ID'))
parser.display_info.AddFormat(_INSTANCE_FORMAT)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster)
result = api_util.YieldFromListHandlingUnreachable(
alloydb_client.projects_locations_clusters_instances,
alloydb_messages
.AlloydbProjectsLocationsClustersInstancesListRequest(
parent=cluster_ref.RelativeName()),
field='instances',
limit=args.limit,
batch_size=args.page_size,
batch_size_attribute='pageSize')
return result

View File

@@ -0,0 +1,105 @@
# -*- 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.
"""Restarts an AlloyDB instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import instance_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.alloydb import instance_helper
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
# TODO(b/312466999): Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.GA, base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA
)
class Restart(base.SilentCommand):
"""Restarts an AlloyDB instance within a given cluster."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To restart an instance, run:
$ {command} my-instance --cluster=my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser, Parser object for command line inputs
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddCluster(parser, False)
flags.AddInstance(parser)
flags.AddRegion(parser)
flags.AddNodeIds(parser)
def ConstructRestartRequest(self, **kwargs):
return instance_helper.ConstructRestartRequestFromArgs(
kwargs.get('alloydb_messages'),
kwargs.get('project_ref'),
kwargs.get('args'),
)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
project_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters.instances',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
instancesId=args.instance,
)
req = self.ConstructRestartRequest(
alloydb_messages=alloydb_messages,
project_ref=project_ref,
args=args
)
op = alloydb_client.projects_locations_clusters_instances.Restart(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations'
)
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
instance_operations.Await(
op_ref, 'Restarting instance', self.ReleaseTrack(), False
)
return op

View File

@@ -0,0 +1,192 @@
# -*- 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.
"""Updates an AlloyDB instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.api_lib.alloydb import instance_operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.alloydb import instance_helper
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
# TODO(b/312466999): Change @base.DefaultUniverseOnly to
# @base.UniverseCompatible once b/312466999 is fixed.
# See go/gcloud-cli-running-tpc-tests.
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Update(base.UpdateCommand):
"""Updates an AlloyDB instance within a given cluster."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To update the number of nodes in the read pool, run:
$ {command} my-read-instance --cluster=my-cluster --region=us-central1 --read-pool-node-count=3
""",
}
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser, Parser object for command line inputs
"""
base.ASYNC_FLAG.AddToParser(parser)
alloydb_messages = api_util.GetMessagesModule(cls.ReleaseTrack())
# Update runs for a long time, it is better to default to async mode so that
# users can query the operation status and find the status.
base.ASYNC_FLAG.SetDefault(parser, True)
flags.AddAvailabilityType(parser)
flags.AddCluster(parser, False)
flags.AddDatabaseFlags(parser)
flags.AddInstance(parser)
flags.AddCPUCount(parser, required=False)
flags.AddMachineType(parser, required=False)
flags.AddReadPoolNodeCount(parser)
flags.AddRegion(parser)
flags.AddInsightsConfigQueryStringLength(parser)
flags.AddInsightsConfigQueryPlansPerMinute(parser)
flags.AddInsightsConfigRecordApplicationTags(
parser, show_negated_in_help=True
)
flags.AddInsightsConfigRecordClientAddress(
parser, show_negated_in_help=True
)
flags.AddSSLMode(parser, update=True)
flags.AddRequireConnectors(parser)
flags.AddAssignInboundPublicIp(parser)
flags.AddAuthorizedExternalNetworks(parser)
flags.AddOutboundPublicIp(parser, show_negated_in_help=True)
flags.AddAllowedPSCProjects(parser)
flags.AddPSCNetworkAttachmentUri(parser)
flags.ClearPSCNetworkAttachmentUri(parser)
flags.AddPSCAutoConnectionGroup(parser)
flags.AddActivationPolicy(parser, alloydb_messages)
# Connection pooling flags.
flags.AddEnableConnectionPooling(parser)
flags.AddConnectionPoolingPoolMode(parser)
flags.AddConnectionPoolingMinPoolSize(parser)
flags.AddConnectionPoolingMaxPoolSize(parser)
flags.AddConnectionPoolingMaxClientConnections(parser)
flags.AddConnectionPoolingServerIdleTimeout(parser)
flags.AddConnectionPoolingQueryWaitTimeout(parser)
flags.AddConnectionPoolingStatsUsers(parser)
flags.AddConnectionPoolingIgnoreStartupParameters(parser)
flags.AddConnectionPoolingServerLifetime(parser)
flags.AddConnectionPoolingClientConnectionIdleTimeout(parser)
flags.AddConnectionPoolingMaxPreparedStatements(parser)
# TODO(b/185795425): Add --ssl-required and --labels later once we
# understand the use cases
def ConstructPatchRequestFromArgs(self, alloydb_messages, instance_ref, args):
return instance_helper.ConstructPatchRequestFromArgs(
alloydb_messages, instance_ref, args)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
instance_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters.instances',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
instancesId=args.instance,
)
req = self.ConstructPatchRequestFromArgs(
alloydb_messages, instance_ref, args
)
op = alloydb_client.projects_locations_clusters_instances.Patch(req)
op_ref = resources.REGISTRY.ParseRelativeName(
op.name, collection='alloydb.projects.locations.operations'
)
log.status.Print('Operation ID: {}'.format(op_ref.Name()))
if not args.async_:
instance_operations.Await(
op_ref, 'Updating instance', self.ReleaseTrack(), False
)
return op
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(Update):
"""Updates an AlloyDB instance within a given cluster."""
@classmethod
def Args(cls, parser):
super(UpdateBeta, cls).Args(parser)
flags.AddUpdateMode(parser)
flags.AddObservabilityConfigEnabled(
parser, show_negated_in_help=True
)
flags.AddObservabilityConfigPreserveComments(
parser, show_negated_in_help=True
)
flags.AddObservabilityConfigTrackWaitEvents(
parser, show_negated_in_help=False
)
flags.AddObservabilityConfigMaxQueryStringLength(parser)
flags.AddObservabilityConfigRecordApplicationTags(
parser, show_negated_in_help=True
)
flags.AddObservabilityConfigQueryPlansPerMinute(parser)
flags.AddObservabilityConfigTrackActiveQueries(
parser, show_negated_in_help=True
)
flags.AddAutoscalerUpdateFlags(parser)
def ConstructPatchRequestFromArgs(self, alloydb_messages, instance_ref, args):
return instance_helper.ConstructPatchRequestFromArgsBeta(
alloydb_messages, instance_ref, args
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(UpdateBeta):
"""Updates an AlloyDB instance within a given cluster."""
@classmethod
def Args(cls, parser):
super(UpdateAlpha, cls).Args(parser)
def ConstructPatchRequestFromArgs(self, alloydb_messages, instance_ref, args):
return instance_helper.ConstructPatchRequestFromArgsAlpha(
alloydb_messages, instance_ref, args
)

View File

@@ -0,0 +1,32 @@
# -*- 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.
"""Provide commands for managing AlloyDB operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Operations(base.Group):
"""Provide commands for managing AlloyDB operations.
Provide commands for managing AlloyDB operations including cancelling,
deleting, describing, and listing.
"""

View File

@@ -0,0 +1,75 @@
# -*- 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.
"""Cancels an AlloyDB operation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Cancel(base.Command):
"""Cancels an AlloyDB operation."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To cancel an operation, run:
$ {command} operation-123456789 --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
flags.AddRegion(parser)
flags.AddOperation(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
args.format = 'default'
client = api_util.AlloyDBClient(self.ReleaseTrack())
operation_ref = client.resource_parser.Create(
'alloydb.projects.locations.operations',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
operationsId=args.operation)
req = client.alloydb_messages.AlloydbProjectsLocationsOperationsCancelRequest(
name=operation_ref.RelativeName())
client.alloydb_client.projects_locations_operations.Cancel(req)
log.status.write('Operation cancelled.\n')

View File

@@ -0,0 +1,75 @@
# -*- 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.
"""Deletes an AlloyDB operation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Cancel(base.DeleteCommand):
"""Deletes an AlloyDB operation."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To delete an operation, run:
$ {command} operation-123456789 --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
flags.AddRegion(parser)
flags.AddOperation(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
A resource object dispatched by display.Displayer().
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
operation_ref = client.resource_parser.Create(
'alloydb.projects.locations.operations',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
operationsId=args.operation)
req = client.alloydb_messages.AlloydbProjectsLocationsOperationsDeleteRequest(
name=operation_ref.RelativeName())
return client.alloydb_client.projects_locations_operations.Delete(req)

View File

@@ -0,0 +1,72 @@
# -*- 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.
"""Describes an AlloyDB operation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describes an AlloyDB operation."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To describe an operation, run:
$ {command} operation-123456789 --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
flags.AddRegion(parser)
flags.AddOperation(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
operation_ref = client.resource_parser.Create(
'alloydb.projects.locations.operations',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
operationsId=args.operation)
req = client.alloydb_messages.AlloydbProjectsLocationsOperationsGetRequest(
name=operation_ref.RelativeName())
return client.alloydb_client.projects_locations_operations.Get(req)

View File

@@ -0,0 +1,106 @@
# -*- 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.
"""Lists AlloyDB operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import re
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class List(base.ListCommand):
"""Lists AlloyDB operations."""
detailed_help = {
'DESCRIPTION':
'{description}',
'EXAMPLES':
"""\
To list operations, run:
$ {command} --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
parser.add_argument(
'--region',
default='-',
help=('Regional location (e.g. asia-east1, us-east1). See the full '
'list of regions at '
'https://cloud.google.com/sql/docs/instance-locations. '
'Default: list operations in all regions.'))
flags.AddCluster(parser, False, False)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
location_ref = client.resource_parser.Create(
'alloydb.projects.locations',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region)
def _FilterOperation(operation_item):
if args.cluster is None:
return True
for additional_property in operation_item.metadata.additionalProperties:
if additional_property.key == 'target':
target = additional_property.value.string_value
return self._matchesTarget(target, args.cluster)
return False
result = list_pager.YieldFromList(
client.alloydb_client.projects_locations_operations,
client.alloydb_messages.AlloydbProjectsLocationsOperationsListRequest(
name=location_ref.RelativeName()),
field='operations',
predicate=_FilterOperation,
limit=args.limit,
batch_size=args.page_size,
batch_size_attribute='pageSize')
return result
def _matchesTarget(self, target, cluster_id):
# Pattern matches all operations for which the target is either the cluster
# or a resource for which the cluster is an ancestor like instance.
# The intention is that the user would be able to list all operations
# pertaining to a particular cluster using the --cluster flag.
pattern = r'projects/[^/]*/locations/[^/]*/clusters/' + cluster_id + r'($|/.*$)'
return re.match(pattern, target) is not None

View File

@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provide commands for managing AlloyDB users."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Users(base.Group):
"""Provide commands for managing AlloyDB users.
Provide commands for managing AlloyDB users including creating,
configuring, getting, listing, and deleting users.
"""

View File

@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Creates a user in a given cluster.
Creates a user in a given cluster with specified username, type, and password.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.alloydb import user_helper
from googlecloudsdk.core import properties
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Creates a user in a given cluster.
Creates a user in a given cluster with specified username, cluster, region,
type, and password.
"""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To create a new user, run:
$ {command} my-username --cluster=my-cluster --region=us-central1 --password=postgres
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs
"""
flags.AddUsername(parser)
flags.AddCluster(parser, False)
flags.AddRegion(parser)
flags.AddUserPassword(parser)
flags.AddUserType(parser)
flags.AddCreateSuperuser(parser)
flags.AddDBRoles(parser)
flags.AddKeepExtraRoles(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
)
req = user_helper.ConstructCreateRequestFromArgs(
client, alloydb_messages, cluster_ref, args
)
return alloydb_client.projects_locations_clusters_users.Create(req)

View File

@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Deletes an AlloyDB user."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Delete(base.DeleteCommand):
"""Deletes an AlloyDB user in a given cluster."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To delete an user, run:
$ {command} my-username --cluster=my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser, Parser object for command line inputs
"""
flags.AddUsername(parser)
flags.AddCluster(parser, False)
flags.AddRegion(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
user_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters.users',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
usersId=args.username,
)
prompt_message = 'User will be deleted from cluster upon completion.'
if not console_io.PromptContinue(message=prompt_message):
return None
req = alloydb_messages.AlloydbProjectsLocationsClustersUsersDeleteRequest(
name=user_ref.RelativeName()
)
return alloydb_client.projects_locations_clusters_users.Delete(req)

View File

@@ -0,0 +1,93 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Lists AlloyDB users in a given cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.core import properties
_USER_FORMAT = """
table(
name,
userType:label="USER_TYPE",
databaseRoles:label="DATABASE_ROLES"
)
"""
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class List(base.ListCommand):
"""Lists AlloyDB users in a given cluster."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To list users, run:
$ {command} --cluster=my-cluster --region=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser, Parser object for command line inputs
"""
flags.AddRegion(parser)
flags.AddCluster(parser, False)
parser.display_info.AddFormat(_USER_FORMAT)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
cluster_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
)
result = api_util.YieldFromListHandlingUnreachable(
alloydb_client.projects_locations_clusters_users,
alloydb_messages.AlloydbProjectsLocationsClustersUsersListRequest(
parent=cluster_ref.RelativeName()
),
field='users',
limit=args.limit,
batch_size=args.page_size,
batch_size_attribute='pageSize',
)
return result

View File

@@ -0,0 +1,78 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Updates a AlloyDB user's password."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.alloydb import user_helper
from googlecloudsdk.core import properties
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Update(base.UpdateCommand):
"""Update an AlloyDB user's password within a given cluster and region."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To update a user's password, run:
$ {command} my-username --cluster=my-cluster --region=us-central1 --password=postgres
""",
}
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
flags.AddUsername(parser)
flags.AddRegion(parser)
flags.AddCluster(parser, False)
flags.AddUserPassword(parser, True)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
user_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters.users',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
usersId=args.username,
)
req = user_helper.ConstructPatchRequestFromArgs(
alloydb_messages, user_ref, args
)
return alloydb_client.projects_locations_clusters_users.Patch(req)

View File

@@ -0,0 +1,80 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Updates a AlloyDB user's password."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.alloydb import user_helper
from googlecloudsdk.core import properties
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
@base.DefaultUniverseOnly
class Update(base.UpdateCommand):
"""Update an AlloyDB user's database roles within a given cluster and region."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To update a user's database roles, run:
$ {command} my-username --cluster=my-cluster --region=us-central1 --db-roles=role1,role2
""",
}
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
flags.AddUsername(parser)
flags.AddRegion(parser)
flags.AddCluster(parser, False)
flags.AddDBRoles(parser, True)
flags.AddKeepExtraRoles(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
user_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters.users',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
usersId=args.username,
)
req = user_helper.ConstructPatchRequestFromArgs(
alloydb_messages, user_ref, args
)
return alloydb_client.projects_locations_clusters_users.Patch(req)

View File

@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Updates a AlloyDB user's superuser role."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.alloydb import api_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.alloydb import flags
from googlecloudsdk.command_lib.alloydb import user_helper
from googlecloudsdk.core import properties
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Update(base.UpdateCommand):
"""Update an AlloyDB user's superuser role within a given cluster and region."""
detailed_help = {
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To update a user's superuser role, run:
$ {command} my-username --cluster=my-cluster --region=us-central1 --superuser=true/false
""",
}
@classmethod
def Args(cls, parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
flags.AddUsername(parser)
flags.AddRegion(parser)
flags.AddCluster(parser, False)
flags.AddSetSuperuser(parser)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
alloydb_messages = client.alloydb_messages
user_ref = client.resource_parser.Create(
'alloydb.projects.locations.clusters.users',
projectsId=properties.VALUES.core.project.GetOrFail,
locationsId=args.region,
clustersId=args.cluster,
usersId=args.username,
)
req = alloydb_messages.AlloydbProjectsLocationsClustersUsersGetRequest(
name=user_ref.RelativeName(),
)
user = alloydb_client.projects_locations_clusters_users.Get(req)
is_superuser = 'alloydbsuperuser' in user.databaseRoles
if is_superuser == args.superuser:
return user
else:
# Pass user database roles in args for Patch request
args.db_roles = user.databaseRoles
user_req = user_helper.ConstructPatchRequestFromArgs(
alloydb_messages, user_ref, args
)
return alloydb_client.projects_locations_clusters_users.Patch(user_req)