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,38 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for the Database Migration Service CLI."""
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.GA)
class DatabaseMigration(base.Group):
"""Manage Database Migration Service resources.
Commands for managing Database Migration Service resources.
"""
category = base.DATABASES_CATEGORY
def Filter(self, context, args):
# TODO(b/190529791): Determine if command group works with project number
base.RequireProjectID(args)
del context, args

View File

@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Connection profiles command group for Database Migration Service."""
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.GA)
class ConnectionProfiles(base.Group):
"""Manage Database Migration Service connection profiles.
Commands for managing Database Migration Service connection profiles.
"""

View File

@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Connection profiles create command group for Database Migration Service."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class ConnectionProfilesCreate(base.Group):
"""Create Database Migration Service connection profiles.
Commands for creating Database Migration Service connection profiles.
- Create a source connection profile with the `mysql` or `postgresql`
commands.
- Create a destination connection profile for a Cloud SQL instance with the
`cloudsql` command. For Cloud SQL instance as a source, use the `create`
command for the relevant engine type (e.g. `mysql`).
"""

View File

@@ -0,0 +1,93 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create connection profiles for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration import flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import alloydb_flags as ad_flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import create_helper
from googlecloudsdk.command_lib.database_migration.connection_profiles import flags as cp_flags
DETAILED_HELP = {
'DESCRIPTION':
'Create a Database Migration Service destination connection profile '
'for AlloyDB. This will create an AlloyDB cluster and primary instance.',
'EXAMPLES':
"""\
To create a connection profile for AlloyDB:
$ {command} my-profile --region=us-central1 \\
--password=my_password \\
--primary-id=my-primary \\
--cpu-count=2
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class AlloyDB(base.Command):
"""Create a Database Migration Service connection profile for AlloyDB."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddAlloyDBConnectionProfileResourceArgs(parser, 'to create')
cp_flags.AddNoAsyncFlag(parser)
cp_flags.AddDisplayNameFlag(parser)
cp_flags.AddRoleFlag(parser)
ad_flags.AddPasswordFlag(parser)
ad_flags.AddNetworkFlag(parser)
ad_flags.AddClusterLabelsFlag(parser)
ad_flags.AddPrimaryIdFlag(parser)
ad_flags.AddCpuCountFlag(parser)
ad_flags.AddDatabaseFlagsFlag(parser)
ad_flags.AddPrimaryLabelsFlag(parser)
ad_flags.AddDatabaseVersionFlag(parser)
ad_flags.AddEnablePublicIpFlag(parser)
ad_flags.AddEnableOutboundPublicIpFlag(parser)
ad_flags.AddAuthorizedNetworkCidrRangesFlag(parser)
flags.AddLabelsCreateFlags(parser)
def Run(self, args):
"""Create a Database Migration Service connection profile for AlloyDB.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the create
operation if the create was successful.
"""
connection_profile_ref = args.CONCEPTS.connection_profile.Parse()
parent_ref = connection_profile_ref.Parent().RelativeName()
helper = create_helper.CreateHelper()
return helper.create(self.ReleaseTrack(), parent_ref,
connection_profile_ref, args, 'ALLOYDB')

View File

@@ -0,0 +1,134 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create connection profiles for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration import flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import cloudsql_flags as cs_flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import create_helper
from googlecloudsdk.command_lib.database_migration.connection_profiles import flags as cp_flags
DETAILED_HELP = {
'DESCRIPTION':
'Create a Database Migration Service destination connection profile '
'for Cloud SQL. This will create a Cloud SQL replica. '
'Used for PostgreSQL and MySQL migrations.',
'EXAMPLES':
"""\
To create a connection profile for Cloud SQL with database version
MySQL 5.6:
$ {command} my-profile --region=us-central1
--database-version=MYSQL_5_6 --source-id=cp1 --tier=db-n1-standard-1
To create a connection profile for Cloud SQL and a Cloud SQL replica
with database version PostgreSQL 10:
$ {command} my-profile --region=us-central1
--database-version=POSTGRES_10 --source-id=cp1
--tier=db-custom-1-3840 --zone=us-central1-a
""",
}
class _CloudSQL(object):
"""Create a Database Migration Service connection profile for Cloud SQL."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddCloudSqlConnectionProfileResourceArgs(parser, 'to create')
cp_flags.AddNoAsyncFlag(parser)
cp_flags.AddDisplayNameFlag(parser)
cp_flags.AddProviderFlag(parser)
cs_flags.AddActivationPolicylag(parser)
cs_flags.AddAuthorizedNetworksFlag(parser)
cs_flags.AddAutoStorageIncreaseFlag(parser)
cs_flags.AddDatabaseFlagsFlag(parser)
cs_flags.AddDataDiskSizeFlag(parser)
cs_flags.AddDataDiskTypeFlag(parser)
cs_flags.AddAvailabilityTypeFlag(parser)
cs_flags.AddEnableIpv4Flag(parser)
cs_flags.AddPrivateNetworkFlag(parser)
cs_flags.AddRequireSslFlag(parser)
cs_flags.AddUserLabelsFlag(parser)
cs_flags.AddStorageAutoResizeLimitFlag(parser)
cs_flags.AddTierFlag(parser)
cs_flags.AddZoneFlag(parser)
cs_flags.AddSecondaryZoneFlag(parser)
cs_flags.AddRootPassword(parser)
flags.AddLabelsCreateFlags(parser)
def Run(self, args):
"""Create a Database Migration Service connection profile for Cloud SQL.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the create
operation if the create was successful.
"""
connection_profile_ref = args.CONCEPTS.connection_profile.Parse()
parent_ref = connection_profile_ref.Parent().RelativeName()
helper = create_helper.CreateHelper()
return helper.create(self.ReleaseTrack(), parent_ref,
connection_profile_ref, args, 'CLOUDSQL')
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CloudSQLAlpha(_CloudSQL, base.Command):
"""Create a Database Migration Service connection profile for Cloud SQL."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
_CloudSQL.Args(parser)
cs_flags.AddDatabaseVersionGroup(
parser, support_new_versions=False, support_version_name=False
)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class CloudSQLGA(_CloudSQL, base.Command):
"""Create a Database Migration Service connection profile for Cloud SQL."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
_CloudSQL.Args(parser)
cs_flags.AddDatabaseVersionGroup(
parser, support_new_versions=True, support_version_name=True
)
resource_args.AddCmekResourceArgs(parser)
cp_flags.AddRoleFlag(parser)
cs_flags.AddAllocatedIpRangeFlag(parser)
cs_flags.AddEditionFlag(parser)
cs_flags.AddEnableDataCacheFlag(parser)

View File

@@ -0,0 +1,115 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create connection profiles for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration import flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import create_helper
from googlecloudsdk.command_lib.database_migration.connection_profiles import flags as cp_flags
from googlecloudsdk.core.console import console_io
DESCRIPTION = ('Create a Database Migration Service connection profile for '
'MySQL.')
EXAMPLES = """\
To create a connection profile for MySQL:
$ {{command}} my-profile --region=us-central1 --password=123456
--username=my-user --host=1.2.3.4 --port=3306
If the source is a Cloud SQL database, run:
$ {{command}} my-profile --region=us-central1 --password=123456
--username=my-user --host=1.2.3.4 --port=3306
--{instance}=my-instance --provider=CLOUDSQL
"""
class _MySQL(object):
"""Create a Database Migration Service connection profile for MySQL."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConnectionProfileResourceArg(parser, 'to create')
cp_flags.AddNoAsyncFlag(parser)
cp_flags.AddDisplayNameFlag(parser)
cp_flags.AddDatabaseParamsFlags(parser, require_password=False)
cp_flags.AddProviderFlag(parser)
flags.AddLabelsCreateFlags(parser)
def Run(self, args):
"""Create a Database Migration Service connection profile.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the create
operation if the create was successful.
"""
connection_profile_ref = args.CONCEPTS.connection_profile.Parse()
parent_ref = connection_profile_ref.Parent().RelativeName()
if args.prompt_for_password:
args.password = console_io.PromptPassword('Please Enter Password: ')
helper = create_helper.CreateHelper()
return helper.create(self.ReleaseTrack(), parent_ref,
connection_profile_ref, args, 'MYSQL')
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class MySQLAlpha(_MySQL, base.Command):
"""Create a Database Migration Service connection profile for MySQL."""
detailed_help = {
'DESCRIPTION': DESCRIPTION,
'EXAMPLES': EXAMPLES.format(instance='instance')
}
@staticmethod
def Args(parser):
_MySQL.Args(parser)
cp_flags.AddSslConfigGroup(parser, base.ReleaseTrack.ALPHA)
cp_flags.AddInstanceFlag(parser)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class MySQLGA(_MySQL, base.Command):
"""Create a Database Migration Service connection profile for MySQL."""
detailed_help = {
'DESCRIPTION': DESCRIPTION,
'EXAMPLES': EXAMPLES.format(instance='cloudsql-instance')
}
@staticmethod
def Args(parser):
_MySQL.Args(parser)
cp_flags.AddSslConfigGroup(parser, base.ReleaseTrack.GA)
cp_flags.AddCloudSQLInstanceFlag(parser)
cp_flags.AddRoleFlag(parser)

View File

@@ -0,0 +1,94 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create connection profiles for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration import flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import create_helper
from googlecloudsdk.command_lib.database_migration.connection_profiles import flags as cp_flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import oracle_flags
from googlecloudsdk.core.console import console_io
DETAILED_HELP = {
'DESCRIPTION': (
'Create a Database Migration Service connection profile for Oracle.'
),
'EXAMPLES': """\
To create a connection profile my-profile for Oracle:
$ {command} my-profile --region=us-central1
--password=123456 --username=my-user
--host=1.2.3.4 --port=5432
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Oracle(base.Command):
"""Create a Database Migration Service connection profile for Oracle."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddOracleConnectionProfileResourceArg(parser, 'to create')
cp_flags.AddNoAsyncFlag(parser)
cp_flags.AddDisplayNameFlag(parser)
cp_flags.AddUsernameFlag(parser, required=True)
cp_flags.AddPasswordFlagGroup(parser, required=True)
cp_flags.AddHostFlag(parser, required=True)
cp_flags.AddPortFlag(parser, required=True)
cp_flags.AddSslServerOnlyConfigGroup(parser)
cp_flags.AddRoleFlag(parser)
oracle_flags.AddDatabaseServiceFlag(parser)
flags.AddLabelsCreateFlags(parser)
def Run(self, args):
"""Create a Database Migration Service connection profile.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the create
operation if the create was successful.
"""
connection_profile_ref = args.CONCEPTS.connection_profile.Parse()
parent_ref = connection_profile_ref.Parent().RelativeName()
if args.prompt_for_password:
args.password = console_io.PromptPassword(
'Please Enter Password for the database user {user}: '.format(
user=args.username
)
)
helper = create_helper.CreateHelper()
return helper.create(self.ReleaseTrack(), parent_ref,
connection_profile_ref, args, 'ORACLE')

View File

@@ -0,0 +1,94 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create connection profiles for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration import flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import create_helper
from googlecloudsdk.command_lib.database_migration.connection_profiles import flags as cp_flags
from googlecloudsdk.core.console import console_io
DETAILED_HELP = {
'DESCRIPTION': (
'Create a Database Migration Service connection profile for PostgreSQL.'
),
'EXAMPLES': """\
To create a connection profile my-profile for PostgreSQL:
$ {command} my-profile --region=us-central1
--password=123456 --username=my-user
--host=1.2.3.4 --port=5432
If the source is a Cloud SQL database, run:
$ {command} my-profile --region=us-central1
--password=123456 --username=my-user
--host=1.2.3.4 --port=5432 --cloudsql-instance=my-instance
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class PostgreSQL(base.Command):
"""Create a Database Migration Service connection profile for PostgreSQL."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddPostgresqlConnectionProfileResourceArg(parser, 'to create')
cp_flags.AddNoAsyncFlag(parser)
cp_flags.AddDisplayNameFlag(parser)
cp_flags.AddDatabaseParamsFlags(
parser, with_database_name=True, supports_iam_auth=True)
cp_flags.AddSslConfigGroup(parser, base.ReleaseTrack.GA)
cp_flags.AddCloudSQLInstanceFlag(parser)
cp_flags.AddAlloydbClusterFlag(parser)
cp_flags.AddRoleFlag(parser)
flags.AddLabelsCreateFlags(parser)
def Run(self, args):
"""Create a Database Migration Service connection profile.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the create
operation if the create was successful.
"""
connection_profile_ref = args.CONCEPTS.connection_profile.Parse()
parent_ref = connection_profile_ref.Parent().RelativeName()
if args.prompt_for_password:
args.password = console_io.PromptPassword('Please Enter Password: ')
helper = create_helper.CreateHelper()
return helper.create(self.ReleaseTrack(), parent_ref,
connection_profile_ref, args, 'POSTGRESQL')

View File

@@ -0,0 +1,192 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create connection profiles for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.database_migration import flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import create_helper
from googlecloudsdk.command_lib.database_migration.connection_profiles import flags as cp_flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import sqlserver_flags
from googlecloudsdk.core.console import console_io
DETAILED_HELP = {
'DESCRIPTION': (
'Create a Database Migration Service connection profile for SQL Server.'
),
'EXAMPLES': """\
To create a source connection profile my-source-profile for SQL Server:
$ {command} my-source-profile --region=us-central1
--gcs-bucket=bucket-name --gcs-prefix=prefix/path
To create a destination connection profile my-dest-profile for SQL
Server:
$ {command} my-dest-profile --region=us-central1
--cloudsql-instance=cloudsql-id
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class _SQLServer(base.Command):
"""Create a Database Migration Service connection profile for SQL Server."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddSqlServerConnectionProfileResourceArg(parser, 'to create')
cp_flags.AddNoAsyncFlag(parser)
cp_flags.AddDisplayNameFlag(parser)
cp_flags.AddRoleFlag(parser)
cp_flags.AddSslServerOnlyOrRequiredConfigGroup(parser)
cp_flags.AddSslFlags(parser)
sqlserver_flags.AddCloudSqlInstanceFlags(parser)
sqlserver_flags.AddCpDetailsFlag(parser)
cp_flags.AddDatabaseFlag(parser)
flags.AddLabelsCreateFlags(parser)
def Run(self, args):
"""Create a Database Migration Service connection profile.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the create
operation if the create was successful.
"""
self._ValidateArgs(args)
connection_profile_ref = args.CONCEPTS.connection_profile.Parse()
parent_ref = connection_profile_ref.Parent().RelativeName()
if args.prompt_for_password:
args.password = console_io.PromptPassword('Please Enter Password: ')
helper = create_helper.CreateHelper()
return helper.create(
self.ReleaseTrack(),
parent_ref,
connection_profile_ref,
args,
'SQLSERVER',
)
def _ValidateArgs(self, args):
"""Validates the arguments for the command."""
self._ValidateHeterogeneousOrDagArgs(args)
self._ValidateHomeogeneousDestinationArgs(args)
def _ValidateHeterogeneousOrDagArgs(self, args):
if args.IsKnownAndSpecified('dbm_port'):
self._ValidateDagArgs(args)
else:
self._ValidateHeterogeneousArgs(args)
def _ValidateHeterogeneousArgs(self, args):
"""Validates the arguments for heterogeneous source connection profiles."""
if args.IsKnownAndSpecified('host'):
if args.username is None:
raise exceptions.BadArgumentException(
'--username',
'Username must be specified with --host.',
)
if args.password is None:
raise exceptions.BadArgumentException(
'--password',
'Password must be specified with --host.',
)
if not self._IsDestinationRole(args) and args.IsKnownAndSpecified(
'cloudsql_instance'
):
raise exceptions.BadArgumentException(
'--cloudsql-instance',
'Cloud SQL instance can not be used with --host.',
)
if args.IsKnownAndSpecified('cloudsql_project_id'):
raise exceptions.BadArgumentException(
'--cloudsql-project-id',
'Cloud SQL project ID can not be used with --host.',
)
def _IsDestinationRole(self, args):
return args.IsKnownAndSpecified('role') and args.role == 'DESTINATION'
def _ValidateDagArgs(self, args):
"""Validates the arguments for DAG HMM source/destination connection profiles."""
if not args.IsKnownAndSpecified('role'):
raise exceptions.BadArgumentException(
'--role',
'Role must be specified with --dbm-port.',
)
if args.username is None:
raise exceptions.BadArgumentException(
'--username',
'Username must be specified with --dbm-port.',
)
if (
not args.IsKnownAndSpecified('cloudsql_instance')
and args.IsKnownAndSpecified('role')
and args.role == 'DESTINATION'
):
raise exceptions.BadArgumentException(
'--cloudsql-instance',
'Cloud SQL instance must be specified with --dbm-port and'
' --role=DESTINATION.',
)
if args.IsKnownAndSpecified('cloudsql_project_id'):
raise exceptions.BadArgumentException(
'--cloudsql-project-id',
'Cloud SQL project ID can not be used with --dbm-port.',
)
if args.IsKnownAndSpecified('database'):
raise exceptions.BadArgumentException(
'--database',
'Database can not be used with --dbm-port.',
)
def _ValidateHomeogeneousDestinationArgs(self, args):
"""Validates the arguments for homeogeneous destination connection profiles."""
if (
not args.IsKnownAndSpecified('host')
and args.IsKnownAndSpecified('role')
and args.role == 'DESTINATION'
):
if args.cloudsql_instance is None:
raise exceptions.BadArgumentException(
'--cloudsql-instance',
'Cloud SQL instance must be specified with --role=DESTINATION.',
)
if args.IsKnownAndSpecified('gcs_bucket'):
raise exceptions.BadArgumentException(
'--gcs-bucket',
'GCS bucket can not be used with --role=DESTINATION.',
)

View File

@@ -0,0 +1,31 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: |
Delete a Database Migration Service connection profile.
description: |
Deletes a connection profile. A connection profile can only be deleted if it is not in use by
any active migration jobs.
examples: |
To delete a connection profile:
$ {command} CONNECTION_PROFILE --region=us-central1
request:
collection: datamigration.projects.locations.connectionProfiles
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
arguments:
resource:
help_text: |
Connection profile resource - Connection profile to delete.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:connection_profile
params:
- api_field: force
arg_name: force
required: false
help_text: |
Cloud SQL replica database is also deleted (only for Cloud SQL connection profiles).

View File

@@ -0,0 +1,20 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: Show details about a Database Migration Service connection profile.
description: Show details about a connection profile.
examples: |
To show details about a connection profile, run:
$ {command} my-connection-profile --region=us-central1
request:
collection: datamigration.projects.locations.connectionProfiles
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
arguments:
resource:
help_text: The connection profile you want to get the details of.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:connection_profile

View File

@@ -0,0 +1,172 @@
# -*- 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.
"""Implementation of connection profile list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import connection_profiles
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import properties
def _GetUri(release_track, connection_profile_info):
"""Gets the resource URI for a connection profile."""
return connection_profiles.ConnectionProfilesClient(release_track).GetUri(
connection_profile_info.name)
class _ConnectionProfileInfo(object):
"""Container for connection profile data using in list display."""
def __init__(self, message, host, engine):
self.display_name = message.displayName
self.name = message.name
self.state = message.state
self.provider_display = message.provider
self.host = host
self.create_time = message.createTime
self.engine = engine
if message.cloudsql:
# In old connection profiles the "provider" field isn't populated
if not message.provider:
self.provider_display = 'CLOUDSQL'
# If the connection profile's "oneof" = cloudsql --> read only replica
self.provider_display = '{}_{}'.format(self.provider_display, 'REPLICA')
class _List(object):
"""Base class for listing Database Migration Service connection profiles."""
@classmethod
def Args(cls, parser):
"""Register flags for this command."""
concept_parsers.ConceptParser.ForResource(
'--region',
resource_args.GetRegionResourceSpec(),
group_help='The location you want to list the connection profiles for.'
).AddToParser(parser)
parser.display_info.AddFormat("""
table(
name.basename():label=CONNECTION_PROFILE_ID,
display_name,
name.scope('locations').segment(0):label=REGION,
state,
provider_display:label=PROVIDER,
engine,
host:label=HOSTNAME/IP,
create_time.date():label=CREATED
)
""")
parser.display_info.AddUriFunc(lambda p: _GetUri(cls.ReleaseTrack(), p))
def Run(self, args):
"""Runs the command.
Args:
args: All the arguments that were provided to this command invocation.
Returns:
An iterator over objects containing connection profile data.
"""
cp_client = connection_profiles.ConnectionProfilesClient(
self.ReleaseTrack())
project_id = properties.VALUES.core.project.Get(required=True)
profiles = cp_client.List(project_id, args)
if args.format is None or args.format.startswith('"table'):
return [
_ConnectionProfileInfo(profile, self._GetHost(profile),
cp_client.GetEngineName(profile))
for profile in profiles
]
return profiles
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ListAlpha(_List, base.ListCommand):
"""List Database Migration Service connection profiles.
List connection profiles.
## API REFERENCE
This command uses the datamigration/v1alpha2 API. The full documentation
for this API can be found at: https://cloud.google.com/database-migration/
## EXAMPLES
To list all connection profiles in a project and region ``us-central1'',
run:
$ {command} --region=us-central1
To filter connection profiles with the given state:
$ {command} --filter="state=READY"
"""
def _GetHost(self, profile):
if profile.mysql:
return profile.mysql.host
elif profile.cloudsql:
return (profile.cloudsql.publicIp
if profile.cloudsql.publicIp
else profile.cloudsql.privateIp)
else:
return None
@base.ReleaseTracks(base.ReleaseTrack.GA)
class ListGA(_List, base.ListCommand):
"""List Database Migration Service connection profiles.
List connection profiles.
## API REFERENCE
This command uses the datamigration/v1 API. The full documentation
for this API can be found at: https://cloud.google.com/database-migration/
## EXAMPLES
To list all connection profiles in a project and region 'us-central1', run:
$ {command} --region=us-central1
To filter connection profiles with the given state:
$ {command} --filter="state=READY"
"""
def _GetHost(self, profile):
# TODO(b/178304949): Add SQL SERVER case once supported.
if profile.mysql:
return profile.mysql.host
elif profile.postgresql:
return profile.postgresql.host
elif profile.cloudsql:
return (profile.cloudsql.publicIp
if profile.cloudsql.publicIp
else profile.cloudsql.privateIp)
elif profile.alloydb:
return profile.alloydb.settings.primaryInstanceSettings.privateIp
elif profile.oracle:
return profile.oracle.host
else:
return None

View File

@@ -0,0 +1,112 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to test connection profiles for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from typing import Any
from googlecloudsdk.api_lib.database_migration import api_util
from googlecloudsdk.api_lib.database_migration import connection_profiles
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.connection_profiles import flags as cp_flags
from googlecloudsdk.core import log
DETAILED_HELP = {
'DESCRIPTION': """
Validates a Database Migration Service connection profile.
""",
'EXAMPLES': """\
To test a connection profile:
$ {command} my-profile --region=us-central1
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Test(base.Command):
"""Test a Database Migration Service connection profile."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConnectionProfileResourceArg(parser, 'to test')
cp_flags.AddNoAsyncFlag(parser)
def Run(self, args: Any) -> Any:
"""Test a Database Migration Service connection profile.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the test
operation.
"""
connection_profile_ref = args.CONCEPTS.connection_profile.Parse()
cp_client = connection_profiles.ConnectionProfilesClient(
self.ReleaseTrack()
)
result_operation = cp_client.Test(connection_profile_ref.RelativeName())
client = api_util.GetClientInstance(self.ReleaseTrack())
messages = api_util.GetMessagesModule(self.ReleaseTrack())
resource_parser = api_util.GetResourceParser(self.ReleaseTrack())
if args.IsKnownAndSpecified('no_async'):
log.status.Print(
'Waiting for connection profile [{}] to be test with [{}]'.format(
connection_profile_ref.connectionProfilesId, result_operation.name
)
)
api_util.HandleLRO(
client, result_operation, client.projects_locations_connectionProfiles
)
log.status.Print(
'Tested connection profile {} [{}]'.format(
connection_profile_ref.connectionProfilesId, result_operation.name
)
)
return
operation_ref = resource_parser.Create(
'datamigration.projects.locations.operations',
operationsId=result_operation.name,
projectsId=connection_profile_ref.projectsId,
locationsId=connection_profile_ref.locationsId,
)
return client.projects_locations_operations.Get(
messages.DatamigrationProjectsLocationsOperationsGetRequest(
name=operation_ref.operationsId
)
)

View File

@@ -0,0 +1,142 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to update connection profiles for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import api_util
from googlecloudsdk.api_lib.database_migration import connection_profiles
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration import flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import flags as cp_flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import oracle_flags
from googlecloudsdk.command_lib.database_migration.connection_profiles import sqlserver_flags
from googlecloudsdk.core.console import console_io
DETAILED_HELP = {
'DESCRIPTION':
"""
Update a Database Migration Service connection profile.
- Draft connection profile: the user can update all flags available in
`connection-profiles create` command.
- Existing connection profile: the user can update a limited list of
flags, see `connection-profiles update` Synopsis.
- If a migration job is using the connection profile, then updates to
fields `host`, `port`, `username`, and `password` will propagate to the
destination instance.
""",
'EXAMPLES':
"""\
To update the username of a connection profile:
$ {command} my-profile --region=us-central1
--username=new-user
""",
}
class _Update(object):
"""Update a Database Migration Service connection profile."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConnectionProfileResourceArg(parser, 'to update')
cp_flags.AddDisplayNameFlag(parser)
cp_flags.AddUsernameFlag(parser)
cp_flags.AddPasswordFlagGroup(parser)
cp_flags.AddHostFlag(parser)
cp_flags.AddPortFlag(parser)
cp_flags.AddDbmPortFlag(parser)
cp_flags.AddCaCertificateFlag(parser)
cp_flags.AddPrivateKeyFlag(parser)
flags.AddLabelsUpdateFlags(parser)
def Run(self, args):
"""Update a Database Migration Service connection profiles.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the create
operation if the create was successful.
"""
connection_profile_ref = args.CONCEPTS.connection_profile.Parse()
if args.prompt_for_password:
args.password = console_io.PromptPassword('Please Enter Password: ')
cp_client = connection_profiles.ConnectionProfilesClient(
self.ReleaseTrack())
result_operation = cp_client.Update(connection_profile_ref.RelativeName(),
args)
client = api_util.GetClientInstance(self.ReleaseTrack())
messages = api_util.GetMessagesModule(self.ReleaseTrack())
resource_parser = api_util.GetResourceParser(self.ReleaseTrack())
operation_ref = resource_parser.Create(
'datamigration.projects.locations.operations',
operationsId=result_operation.name,
projectsId=connection_profile_ref.projectsId,
locationsId=connection_profile_ref.locationsId)
return client.projects_locations_operations.Get(
messages.DatamigrationProjectsLocationsOperationsGetRequest(
name=operation_ref.operationsId))
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(_Update, base.Command):
"""Update a Database Migration Service connection profile."""
@staticmethod
def Args(parser):
_Update.Args(parser)
cp_flags.AddCertificateFlag(parser)
cp_flags.AddInstanceFlag(parser)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class UpdateGA(_Update, base.Command):
"""Update a Database Migration Service connection profile."""
@staticmethod
def Args(parser):
_Update.Args(parser)
cp_flags.AddClientCertificateFlag(parser)
cp_flags.AddCloudSQLInstanceFlag(parser)
cp_flags.AddAlloydbClusterFlag(parser)
cp_flags.AddSslTypeFlag(
parser, hidden=False, choices=None
) # Add all choices in update command
sqlserver_flags.AddSourceUpdateFlag(parser)
sqlserver_flags.AddCloudSqlProjectIdFlag(parser)
cp_flags.AddDatabaseFlag(parser)
oracle_flags.AddDatabaseServiceFlag(parser, required=False)
cp_flags.AddEnableIamAuthenticationFlag(parser)

View File

@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The conversion workspaces command group for Database Migration Service."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA)
class ConversionWorkspaces(base.Group):
"""Manage Database Migration Service conversion workspaces.
Commands for managing Database Migration Service conversion workspaces.
"""

View File

@@ -0,0 +1,79 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to apply conversion workspaces for a database migration."""
import argparse
from typing import Optional
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
from googlecloudsdk.generated_clients.apis.datamigration.v1 import datamigration_v1_messages as messages
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Apply(command_mixin.ConversionWorkspacesCommandMixin, base.Command):
"""Apply a Database Migration Service conversion workspace."""
detailed_help = {
'DESCRIPTION': (
'Apply Database Migration Service conversion workspace onto the'
' destination database.'
),
'EXAMPLES': """\
To apply a conversion workspace:
$ {command} my-conversion-workspace --region=us-central1
--destination-connection-profile=projects/1234/locations/us-central1/connectionProfiles/destination-connection-profile-name
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceApplyResourceArg(parser, 'to apply')
cw_flags.AddNoAsyncFlag(parser)
cw_flags.AddFilterFlag(parser)
def Run(self, args: argparse.Namespace) -> Optional[messages.Operation]:
"""Apply a Database Migration Service conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the apply
operation if the apply was successful.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
result_operation = self.client.operations.Apply(
name=conversion_workspace_ref.RelativeName(),
destination_connection_profile_ref=args.CONCEPTS.destination_connection_profile.Parse(),
filter_expr=self.ExtractBackendFilter(args),
)
return self.HandleOperationResult(
conversion_workspace_ref=conversion_workspace_ref,
result_operation=result_operation,
operation_name='Applied',
sync=args.IsKnownAndSpecified('no_async'),
)

View File

@@ -0,0 +1,79 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to commit conversion workspaces for a database migration."""
import argparse
from typing import Optional
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
from googlecloudsdk.generated_clients.apis.datamigration.v1 import datamigration_v1_messages as messages
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Commit(command_mixin.ConversionWorkspacesCommandMixin, base.Command):
"""Commit a Database Migration Service conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Commit a Database Migration Service conversion workspace.
""",
'EXAMPLES': """\
To commit a version of conversion workspace called
my-conversion-workspace:
$ {command} my-conversion-workspace --region=us-central1
--commit-name=my-commit
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceResourceArg(parser, 'to commit')
cw_flags.AddNoAsyncFlag(parser)
cw_flags.AddCommitNameFlag(parser)
def Run(self, args: argparse.Namespace) -> Optional[messages.Operation]:
"""Commit a Database Migration Service conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the commit
operation if the commit was successful.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
result_operation = self.client.operations.Commit(
name=conversion_workspace_ref.RelativeName(),
commit_name=args.commit_name,
)
return self.HandleOperationResult(
conversion_workspace_ref=conversion_workspace_ref,
result_operation=result_operation,
operation_name='Committed',
sync=args.IsKnownAndSpecified('no_async'),
)

View File

@@ -0,0 +1,79 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to convert conversion workspaces for a database migration."""
import argparse
from typing import Optional
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
from googlecloudsdk.generated_clients.apis.datamigration.v1 import datamigration_v1_messages as messages
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Convert(command_mixin.ConversionWorkspacesCommandMixin, base.Command):
"""Convert a Database Migration Service conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Convert a Database Migration Service conversion workspace.
""",
'EXAMPLES': """\
To convert a conversion workspace:
$ {command} my-conversion-workspace --region=us-central1
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceResourceArg(parser, 'to convert')
cw_flags.AddNoAsyncFlag(parser)
cw_flags.AddAutoCommitFlag(parser)
cw_flags.AddFilterFlag(parser)
def Run(self, args: argparse.Namespace) -> Optional[messages.Operation]:
"""Convert a Database Migration Service conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the convert
operation if the convert was successful.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
result_operation = self.client.operations.Convert(
name=conversion_workspace_ref.RelativeName(),
filter_expr=self.ExtractBackendFilter(args),
auto_commit=args.auto_commit,
)
return self.HandleOperationResult(
conversion_workspace_ref=conversion_workspace_ref,
result_operation=result_operation,
operation_name='Converted',
sync=args.IsKnownAndSpecified('no_async'),
)

View File

@@ -0,0 +1,87 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to convert conversion workspaces for a database migration."""
import argparse
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.api_lib.database_migration.conversion_workspaces.app_code_conversion import application_code_converter
from googlecloudsdk.api_lib.database_migration.conversion_workspaces.app_code_conversion import conversion_params
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
from googlecloudsdk.command_lib.util.concepts import concept_parsers
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class ConvertApplicationCode(
command_mixin.ConversionWorkspacesCommandMixin,
base.Command,
):
"""Convert the application code."""
detailed_help = {
'DESCRIPTION': """
Convert the provided source code from accessing the source database to
accessing the destination database.
""",
'EXAMPLES': """\
To convert the application code:
$ {command} --source-file=Path/to/source --region=us-central1
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
concept_parsers.ConceptParser.ForResource(
'--region',
resource_args.GetRegionResourceSpec(),
group_help='The location of the resource.',
required=True,
).AddToParser(parser)
cw_flags.AddSourceDialectFlag(parser)
cw_flags.AddTargetDialectFlag(parser)
cw_flags.AddSourceDetailsFlag(parser)
cw_flags.AddTargetPathFlag(parser)
def Run(self, args: argparse.Namespace):
"""Convert the application code.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
"""
params = conversion_params.ApplicationCodeConversionParams(
name=args.CONCEPTS.region.Parse().RelativeName(),
source_dialect=args.source_dialect,
target_dialect=args.target_dialect,
source_folder=args.source_folder,
target_path=args.target_path,
source_file=args.source_file,
)
converter = application_code_converter.ApplicationCodeConverter(
params=params,
ai_client=self.client.ai,
)
converter.Convert()

View File

@@ -0,0 +1,154 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create conversion workspaces for a database migration."""
import argparse
from typing import Optional, Type, TypeVar
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.generated_clients.apis.datamigration.v1 import datamigration_v1_messages as messages
GlobalSettingsValue = TypeVar('GlobalSettingsValue')
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(command_mixin.ConversionWorkspacesCommandMixin, base.Command):
"""Create a Database Migration Service conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Create a Database Migration Service conversion workspace.
""",
'EXAMPLES': """\
To create a conversion workspace:
$ {command} my-conversion-workspace --region=us-central1
--display-name=cw1
--source-database-engine=ORACLE
--source-database-version=11
--destination-database-engine=POSTGRESQL
--destination-database-version=15
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceResourceArg(parser, 'to create')
cw_flags.AddNoAsyncFlag(parser)
cw_flags.AddDisplayNameFlag(parser)
cw_flags.AddDatabaseEngineFlags(parser)
cw_flags.AddDatabaseProviderFlags(parser)
cw_flags.AddDatabaseVersionFlag(parser)
cw_flags.AddGlobalSettingsFlag(parser)
def Run(self, args: argparse.Namespace) -> Optional[messages.Operation]:
"""Create a Database Migration Service conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the create
operation if the create was successful.
"""
self._ValidateEngineProviderFlags(args)
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
result_operation = self.client.crud.Create(
parent_ref=conversion_workspace_ref.Parent().RelativeName(),
conversion_workspace_id=conversion_workspace_ref.conversionWorkspacesId,
display_name=args.display_name,
source_database_provider=args.source_database_provider,
source_database_engine=args.source_database_engine,
source_database_version=args.source_database_version,
destination_database_provider=args.destination_database_provider,
destination_database_engine=args.destination_database_engine,
destination_database_version=args.destination_database_version,
global_settings=self._BuildGlobalSettings(
args=args,
global_settings_value_cls=self.client.crud.messages.ConversionWorkspace.GlobalSettingsValue,
),
)
return self.HandleOperationResult(
conversion_workspace_ref=conversion_workspace_ref,
result_operation=result_operation,
operation_name='Created',
sync=args.IsKnownAndSpecified('no_async'),
)
def _ValidateEngineProviderFlags(self, args: argparse.Namespace) -> None:
"""Validates the engine and provider flags."""
if (
args.source_database_provider
not in args.source_database_engine.supported_providers
):
raise exceptions.InvalidArgumentException(
'--source_database_engine, --source_database_provider',
f'Source database engine {args.source_database_engine} is not'
' supported by the source database provider'
f' {args.source_database_provider}.\nSupported providers are:'
f' {", ".join(map(str, args.source_database_engine.supported_providers))}.',
)
if (
args.destination_database_provider
not in args.destination_database_engine.supported_providers
):
raise exceptions.InvalidArgumentException(
'--destination_database_engine, --destination_database_provider',
f'Destination database engine {args.destination_database_engine} is'
' not supported by the destination database provider'
f' {args.destination_database_provider}.\nSupported providers are:'
f' {", ".join(map(str, args.destination_database_engine.supported_providers))}.',
)
def _BuildGlobalSettings(
self,
args: argparse.Namespace,
global_settings_value_cls: Type[GlobalSettingsValue],
) -> GlobalSettingsValue:
"""Builds the global settings for the conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
global_settings_value_cls: The class to use for the global settings value.
Returns:
A global settings value object.
"""
if args.global_settings is None:
args.global_settings = {}
args.global_settings.update(filter='*', v2='true')
return labels_util.ParseCreateArgs(
args=args,
labels_cls=global_settings_value_cls,
labels_dest='global_settings',
)

View File

@@ -0,0 +1,93 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to delete a database migration conversion workspace."""
import argparse
from typing import Optional
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as pc_flags
from googlecloudsdk.core.console import console_io
from googlecloudsdk.generated_clients.apis.datamigration.v1 import datamigration_v1_messages as messages
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Delete(command_mixin.ConversionWorkspacesCommandMixin, base.Command):
"""Delete a Database Migration conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Delete a Database Migration conversion workspace.
""",
'EXAMPLES': """\
To delete a conversion workspace called 'my-conversion-workspace', run:
$ {command} my-conversion-workspace --region=us-central1
""",
}
@staticmethod
def CommonArgs(parser):
"""Common arguments for all release tracks.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceResourceArg(parser, 'to delete')
pc_flags.AddNoAsyncFlag(parser)
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command."""
Delete.CommonArgs(parser)
def Run(self, args: argparse.Namespace) -> Optional[messages.Operation]:
"""Delete a Database Migration conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
An Optional[dict] object representing the operations resource describing
the delete
operation if the delete was successful.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
if not console_io.PromptContinue(
message=(
'You are about to delete conversion workspace'
f' {conversion_workspace_ref.RelativeName()}.\n'
'Are you sure?'
)
):
return
result_operation = self.client.crud.Delete(
name=conversion_workspace_ref.RelativeName(),
)
return self.HandleOperationResult(
conversion_workspace_ref=conversion_workspace_ref,
result_operation=result_operation,
operation_name='Deleted',
sync=args.IsKnownAndSpecified('no_async'),
has_resource=False,
)

View File

@@ -0,0 +1,17 @@
- release_tracks: [GA]
help_text:
brief: Show details about a database migration conversion workspace.
description: Show details about a conversion workspace.
examples: |
To show details about a conversion workspace, run:
$ {command} my-conversion-workspace --region=us-central1
request:
collection: datamigration.projects.locations.conversionWorkspaces
api_version: v1
arguments:
resource:
help_text: The conversion workspace you want to get the details of.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:conversion_workspace

View File

@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to commit conversion workspaces for a database migration."""
import argparse
from typing import Generator
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
from googlecloudsdk.generated_clients.apis.datamigration.v1 import datamigration_v1_messages as messages
_DEFAULT_PAGE_SIZE = 100
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class DescribeDDLs(
command_mixin.ConversionWorkspacesCommandMixin,
base.ListCommand,
):
"""Describe DDLs in a Database Migration Service conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Describe DDLs in a Database Migration Service conversion workspace.
""",
'EXAMPLES': """\
To describe the DDLs of the draft tree in my-conversion-workspace in a
project and location `us-central1`, run:
$ {command} my-conversion-workspace --region=us-central1
To describe the DDLs of the source tree in a conversion workspace in a
project and location `us-central1`, run:
$ {command} my-conversion-workspace --region=us-central1 --tree-type=SOURCE
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceResourceArg(parser, 'to describe DDLs')
cw_flags.AddTreeTypeFlag(parser, required=False)
cw_flags.AddCommitIdFlag(parser)
cw_flags.AddUncommittedFlag(parser)
base.PAGE_SIZE_FLAG.SetDefault(parser, _DEFAULT_PAGE_SIZE)
parser.display_info.AddFormat("""table(ddl:label=DDLs)""")
def Run(
self,
args: argparse.Namespace,
) -> Generator[messages.EntityDdl, None, None]:
"""Describe the DDLs for a Database Migration Service conversion workspace.
Args:
args: argparse.Namespace, the arguments that this command was invoked
with.
Returns:
A list of DDLs for the specified conversion workspace and arguments.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
return self.client.entities.DescribeDDLs(
name=conversion_workspace_ref.RelativeName(),
commit_id=args.commit_id,
uncommitted=args.uncommitted,
tree_type=args.tree_type,
filter_expr=self.ExtractBackendFilter(args),
page_size=args.GetValue('page_size'),
)

View File

@@ -0,0 +1,87 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to commit conversion workspaces for a database migration."""
import argparse
from typing import Any, Dict, Generator
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
_DEFAULT_PAGE_SIZE = 100
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class DescribeEntities(
command_mixin.ConversionWorkspacesCommandMixin,
base.ListCommand,
):
"""Describe database entities in a Database Migration conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Describe database entities in a Database Migration conversion workspace.
""",
'EXAMPLES': """\
To describe the database entities of the source tree in a conversion
workspace in a project and location `us-central1`, run:
$ {command} my-conversion-workspace --region=us-central1 --tree-type=SOURCE
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
resource_args.AddConversionWorkspaceResourceArg(parser, 'describe entities')
cw_flags.AddTreeTypeFlag(parser, required=True)
cw_flags.AddCommitIdFlag(parser)
cw_flags.AddUncommittedFlag(parser)
base.PAGE_SIZE_FLAG.SetDefault(parser, _DEFAULT_PAGE_SIZE)
parser.display_info.AddFormat("""
table(
tree:label=TREE_TYPE,
entityType:label=ENTITY_TYPE,
parentEntity:label=PARENT,
shortName:label=NAME,
status:label=STATUS
)
""")
def Run(
self,
args: argparse.Namespace,
) -> Generator[Dict[str, Any], None, None]:
"""Describe database entities for a DMS conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A list of entities for the specified conversion workspace and arguments.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
return self.client.entities.DescribeEntities(
name=conversion_workspace_ref.RelativeName(),
commit_id=args.commit_id,
uncommitted=args.uncommitted,
tree_type=args.tree_type,
filter_expr=self.ExtractBackendFilter(args),
page_size=args.GetValue('page_size'),
)

View File

@@ -0,0 +1,96 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to commit conversion workspaces for a database migration."""
import argparse
from typing import Any, Dict, Generator
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
_DEFAULT_PAGE_SIZE = 100
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class DescribeIssues(
command_mixin.ConversionWorkspacesCommandMixin,
base.ListCommand,
):
"""Describe issues in a Database Migration Service conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Describe database entity issues in a Database Migration Services conversion workspace.
""",
'EXAMPLES': """\
To describe the database entity issues in a conversion workspace
in a project and location `us-central1`, run:
$ {command} my-conversion-workspace --region=us-central1
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceResourceArg(
parser, 'to describe issues'
)
cw_flags.AddCommitIdFlag(parser)
cw_flags.AddUncommittedFlag(parser)
base.PAGE_SIZE_FLAG.SetDefault(parser, _DEFAULT_PAGE_SIZE)
parser.display_info.AddFormat("""
table(
parentEntity:label=PARENT,
shortName:label=NAME,
entityType:label=ENTITY_TYPE,
issueType:label=ISSUE_TYPE,
issueSeverity:label=ISSUE_SEVERITY,
issueCode:label=ISSUE_CODE,
issueMessage:label=ISSUE_MESSAGE
)
""")
def Run(
self,
args: argparse.Namespace,
) -> Generator[Dict[str, Any], None, None]:
"""Describe the database entity issues for a DMS conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A list of database entity issues for the specified conversion workspace
and arguments.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
return self.client.entities.DescribeIssues(
name=conversion_workspace_ref.RelativeName(),
commit_id=args.commit_id,
uncommitted=args.uncommitted,
filter_expr=self.ExtractBackendFilter(args),
page_size=args.GetValue('page_size'),
)

View File

@@ -0,0 +1,86 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to import rules in a conversion workspaces for a database migration from config files."""
import argparse
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class ImportRules(command_mixin.ConversionWorkspacesCommandMixin, base.Command):
"""Import mapping rules in a Database Migration Service conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Import mapping rules in a Database Migration Service conversion
workspace from a configuration file. For example, for Oracle to
PostgreSQL migrations that could be an Ora2Pg config file.
""",
'EXAMPLES': """\
To import rules in a conversion workspace:
$ {command} my-conversion-workspace --region=us-central1
--file-format=ORA2PG --config-files=PATH1/config1.conf,PATH2/config2.conf
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceResourceArg(parser, 'to import rules')
cw_flags.AddImportFileFormatFlag(parser)
cw_flags.AddConfigFilesFlag(parser)
cw_flags.AddAutoCommitFlag(parser)
def Run(self, args: argparse.Namespace) -> None:
"""Import rules in a Database Migration Service conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
# Import mapping rules is a passthrough method and returns only done: true
# along with the error (if any)
result_operation = self.client.operations.ImportRules(
name=conversion_workspace_ref.RelativeName(),
config_files=args.config_files,
file_format=args.file_format,
auto_commit=args.auto_commit,
)
if result_operation.error is not None:
log.status.Print(
'Imported mapping rules for conversion workspace'
f' {conversion_workspace_ref.conversionWorkspacesId} failed with'
f' error [{result_operation.error.message}]',
)
else:
log.status.Print(
'Imported mapping rules for conversion workspace'
f' {conversion_workspace_ref.conversionWorkspacesId}',
)

View File

@@ -0,0 +1,31 @@
- release_tracks: [GA]
help_text:
brief: List conversion workspaces.
description: List conversion workspaces.
examples: |
To list all conversion workspaces in a project and location `us-central1`, run:
$ {command} --region=us-central1
request:
collection: datamigration.projects.locations.conversionWorkspaces
api_version: v1
response:
id_field: name
arguments:
resource:
help_text: The region you want to list the conversion workspaces for.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:region
output:
format: |
table(
name.basename():label=CONVERSION_WORKSPACE_ID,
displayName,
name.scope('locations').segment(0):label=REGION,
source.engine:label=SOURCE,
destination.engine:label=DESTINATION,
createTime.date():label=CREATED
)

View File

@@ -0,0 +1,45 @@
- release_tracks: [GA]
help_text:
brief: List background jobs in the conversion workspaces.
description: List background jobs in the conversion workspaces.
examples: |
To list the background jobs in a conversion workspaces in a project and location `us-central1`, run:
$ {command} my-conversion-workspace --region=us-central1
request:
collection: datamigration.projects.locations.conversionWorkspaces
api_version: v1
method: searchBackgroundJobs
response:
id_field: id
result_attribute: jobs
arguments:
resource:
help_text: The conversion workspace you want to get the details of.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:conversion_workspace
params:
- api_field: maxSize
arg_name: max-size
help_text: |
The maximum number of jobs to return. The service may return fewer than this value. If
unspecified, at most 100 jobs will be returned. The maximum value is 100; values above 100
will be coerced to 100.
- api_field: returnMostRecentPerJobType
arg_name: most-recent-per-job-type
help_text: |
Returns only the most recent job per job type.
output:
format: |
table(
id:label=JOB_ID,
jobType:label=JOB_TYPE,
startTime:label=START_TIME,
finishTime:label=FINISH_TIME,
completionState:label=STATE,
completionComment:label=COMMENT
)

View File

@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The conversion workspace mapping rules command group for Database Migration Service."""
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class MappingRules(base.Group):
"""Manage Database Migration Service Conversion Workspace mapping rules.
Commands for managing Database Migration Service Conversion Workspace mapping
rules.
"""

View File

@@ -0,0 +1,32 @@
- release_tracks: [GA]
help_text:
brief: List Mapping Rules.
description: List mapping rules.
examples: |
To list all mapping rules in a project and location `us-central1`, run:
$ {command} --conversion-workspace=my-conversion-workspace --region=us-central1
request:
collection: datamigration.projects.locations.conversionWorkspaces.mappingRules
api_version: v1
response:
id_field: name
modify_response_hooks:
- googlecloudsdk.command_lib.database_migration.conversion_workspaces.hooks:ModifyMappingRuleResponse
arguments:
resource:
arg_name: conversion-workspace
help_text: The conversion workspace you want to list mapping rules for.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:conversion_workspace
output:
format: |
table(
name.basename():label=MAPPING_RULE_ID,
displayName,
ruleScope:label=scope,
filter
)

View File

@@ -0,0 +1,75 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to rollback conversion workspaces for a database migration."""
import argparse
from typing import Optional
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
from googlecloudsdk.generated_clients.apis.datamigration.v1 import datamigration_v1_messages as messages
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Rollback(command_mixin.ConversionWorkspacesCommandMixin, base.Command):
"""Rollback a Database Migration Service conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Rollback a Database Migration Service conversion workspace to the last
committed snapshot.
""",
'EXAMPLES': """\
To rollback a conversion workspace to the last committed snapshot:
$ {command} my-conversion-workspace --region=us-central1
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceResourceArg(parser, 'to rollback')
cw_flags.AddNoAsyncFlag(parser)
def Run(self, args: argparse.Namespace) -> Optional[messages.Operation]:
"""Rollback a Database Migration Service conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the rollback
operation if the rollback was successful.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
result_operation = self.client.operations.Rollback(
name=conversion_workspace_ref.RelativeName(),
)
return self.HandleOperationResult(
conversion_workspace_ref=conversion_workspace_ref,
result_operation=result_operation,
operation_name='Rolled back',
sync=args.IsKnownAndSpecified('no_async'),
)

View File

@@ -0,0 +1,80 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to seed conversion workspaces for a database migration."""
import argparse
from typing import Optional
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
from googlecloudsdk.generated_clients.apis.datamigration.v1 import datamigration_v1_messages as messages
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Seed(command_mixin.ConversionWorkspacesCommandMixin, base.Command):
"""Seed a Database Migration Service conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Seed a Database Migration Service conversion workspace.
""",
'EXAMPLES': """\
To seed a conversion workspace:
$ {command} my-conversion-workspace --region=us-central1
--source-connection-profile=cp1
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceSeedResourceArg(parser, 'to seed')
cw_flags.AddNoAsyncFlag(parser)
cw_flags.AddAutoCommitFlag(parser)
def Run(self, args: argparse.Namespace) -> Optional[messages.Operation]:
"""Seed a Database Migration Service conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the seed
operation if the seed was successful.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
result_operation = self.client.operations.Seed(
name=conversion_workspace_ref.RelativeName(),
src_connection_profile_ref=args.CONCEPTS.source_connection_profile.Parse(),
dest_connection_profile_ref=args.CONCEPTS.destination_connection_profile.Parse(),
auto_commit=args.auto_commit,
)
return self.HandleOperationResult(
conversion_workspace_ref=conversion_workspace_ref,
result_operation=result_operation,
operation_name='Seeded',
sync=args.IsKnownAndSpecified('no_async'),
)

View File

@@ -0,0 +1,79 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to update conversion workspaces for a database migration."""
import argparse
from typing import Optional
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import command_mixin
from googlecloudsdk.command_lib.database_migration.conversion_workspaces import flags as cw_flags
from googlecloudsdk.generated_clients.apis.datamigration.v1 import datamigration_v1_messages as messages
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Update(command_mixin.ConversionWorkspacesCommandMixin, base.Command):
"""Update a Database Migration Service conversion workspace."""
detailed_help = {
'DESCRIPTION': """
Update a Database Migration Service conversion workspace.
""",
'EXAMPLES': """\
To update a conversion workspace:
$ {command} my-conversion-workspace --region=us-central1
--display-name=new-display-name
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser) -> None:
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddConversionWorkspaceResourceArg(parser, 'to update')
cw_flags.AddNoAsyncFlag(parser)
cw_flags.AddDisplayNameFlag(parser)
cw_flags.AddGlobalFilterFlag(parser)
def Run(self, args: argparse.Namespace) -> Optional[messages.Operation]:
"""Update a Database Migration Service conversion workspace.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the update
operation if the update was successful.
"""
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
result_operation = self.client.crud.Update(
name=conversion_workspace_ref.RelativeName(),
display_name=args.display_name,
global_filter=args.global_filter,
)
return self.HandleOperationResult(
conversion_workspace_ref=conversion_workspace_ref,
result_operation=result_operation,
operation_name='Updated',
sync=args.IsKnownAndSpecified('no_async'),
)

View File

@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The migration jobs command group for Database Migration Service."""
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.GA)
class MigrationJobs(base.Group):
"""Manage Database Migration Service migration jobs.
Commands for managing Database Migration Service migration jobs.
"""

View File

@@ -0,0 +1,238 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create migration jobs for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import api_util
from googlecloudsdk.api_lib.database_migration import migration_jobs
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration import flags
from googlecloudsdk.command_lib.database_migration.migration_jobs import flags as mj_flags
from googlecloudsdk.core import log
MYSQL_CONNECTIVITY_DOC = 'https://cloud.google.com/database-migration/docs/mysql/configure-connectivity'
DETAILED_HELP_ALPHA = {
'DESCRIPTION': """
Create a Database Migration Service migration job.
Recommended steps before creating the migration job:
- Create a source connection profile. See prerequisites [here](https://cloud.google.com/database-migration/docs/mysql/configure-source-database).
- Create a destination connection profile. For migrating to Cloud SQL for MySQL or Cloud SQL for PostgreSQL, use the cloudsql connection profile for DMS to create the CloudSQL replica for you.
- Configure the connectivity method. See prerequisites [here]({MYSQL_CONNECTIVITY_DOC}).
""".format(MYSQL_CONNECTIVITY_DOC=MYSQL_CONNECTIVITY_DOC),
'EXAMPLES': """\
To create a continuous migration job with IP allowlist connectivity:
$ {command} my-migration-job --region=us-central1 --type=CONTINUOUS
--source=cp1 --destination=cp2
To create a continuous migration job with VPC peering connectivity:
$ {command} my-migration-job --region=us-central1 --type=CONTINUOUS
--source=cp1 --destination=cp2
--peer-vpc=projects/my-project/global/networks/my-network
To create a one-time migration job with reverse-SSH tunnel connectivity:
$ {command} my-migration-job --region=us-central1 --type=ONE_TIME
--source=cp1 --destination=cp2 --vm=vm1 --vm-ip=1.1.1.1
--vm-port=1111 --vpc=projects/my-project/global/networks/my-network
""",
}
DETAILED_HELP_GA = {
'DESCRIPTION': """
Create a Database Migration Service migration job.
Recommended steps before creating the migration job:
- Create a source connection profile. See prerequisites [here](https://cloud.google.com/database-migration/docs/mysql/configure-source-database).
- Create a destination connection profile. For migrating to Cloud SQL for MySQL or Cloud SQL for PostgreSQL, use the cloudsql connection profile for DMS to create the CloudSQL replica for you.
- Configure the connectivity method. See prerequisites [here]({MYSQL_CONNECTIVITY_DOC}).
- [Heterogeneous migrations only] Create a conversion workspace.
""".format(MYSQL_CONNECTIVITY_DOC=MYSQL_CONNECTIVITY_DOC),
'EXAMPLES': """\
To create a continuous migration job with IP allowlist connectivity:
$ {command} my-migration-job --region=us-central1 --type=CONTINUOUS
--source=cp1 --destination=cp2
To create a continuous migration job with VPC peering connectivity:
$ {command} my-migration-job --region=us-central1 --type=CONTINUOUS
--source=cp1 --destination=cp2
--peer-vpc=projects/my-project/global/networks/my-network
To create a one-time migration job with reverse-SSH tunnel connectivity:
$ {command} my-migration-job --region=us-central1 --type=ONE_TIME
--source=cp1 --destination=cp2 --vm=vm1 --vm-ip=1.1.1.1
--vm-port=1111 --vpc=projects/my-project/global/networks/my-network
To create a heterogeneous continuous migration job:
$ {command} my-migration-job --region=us-central1 --type=CONTINUOUS
--source=cp1 --destination=cp2 --conversion-workspace=cw
To create a continuous SQL Server to SQL Server homogeneous migration
job with differential backup enabled:
$ {command} my-migration-job --region=us-central1 --type=CONTINUOUS
--source=cp1 --destination=cp2
--sqlserver-diff-backup
--sqlserver-databases=db1,db2,db3
To create a continuous SQL Server to SQL Server homogeneous migration
job with encrypted databases:
$ {command} my-migration-job --region=us-central1 --type=CONTINUOUS
--source=cp1 --destination=cp2
--sqlserver-databases=db1,db2,db3
--sqlserver-encrypted-databases=PATH/TO/ENCRYPTION/SETTINGS
""",
}
class _Create(object):
"""Create a Database Migration Service migration job."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
mj_flags.AddNoAsyncFlag(parser)
mj_flags.AddDisplayNameFlag(parser)
mj_flags.AddTypeFlag(parser, required=True)
mj_flags.AddDumpGroupFlag(parser)
mj_flags.AddConnectivityGroupFlag(
parser, mj_flags.ApiType.CREATE, required=True
)
flags.AddLabelsCreateFlags(parser)
def Run(self, args):
"""Create a Database Migration Service migration job.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the create
operation if the create was successful.
"""
migration_job_ref = args.CONCEPTS.migration_job.Parse()
parent_ref = migration_job_ref.Parent().RelativeName()
source_ref = args.CONCEPTS.source.Parse()
destination_ref = args.CONCEPTS.destination.Parse()
if self.ReleaseTrack() == base.ReleaseTrack.GA:
conversion_workspace_ref = args.CONCEPTS.conversion_workspace.Parse()
original_migration_name_ref = (
args.CONCEPTS.original_migration_name.Parse()
)
cmek_key_ref = args.CONCEPTS.cmek_key.Parse()
else:
conversion_workspace_ref = None
original_migration_name_ref = None
cmek_key_ref = None
mj_client = migration_jobs.MigrationJobsClient(self.ReleaseTrack())
result_operation = mj_client.Create(
parent_ref,
migration_job_ref.migrationJobsId,
source_ref,
destination_ref,
conversion_workspace_ref,
original_migration_name_ref,
cmek_key_ref,
args,
)
client = api_util.GetClientInstance(self.ReleaseTrack())
messages = api_util.GetMessagesModule(self.ReleaseTrack())
resource_parser = api_util.GetResourceParser(self.ReleaseTrack())
if args.IsKnownAndSpecified('no_async'):
log.status.Print(
'Waiting for migration job [{}] to be created with [{}]'.format(
migration_job_ref.migrationJobsId, result_operation.name))
api_util.HandleLRO(client, result_operation,
client.projects_locations_migrationJobs)
log.status.Print('Created migration job {} [{}]'.format(
migration_job_ref.migrationJobsId, result_operation.name))
return
operation_ref = resource_parser.Create(
'datamigration.projects.locations.operations',
operationsId=result_operation.name,
projectsId=migration_job_ref.projectsId,
locationsId=migration_job_ref.locationsId)
return client.projects_locations_operations.Get(
messages.DatamigrationProjectsLocationsOperationsGetRequest(
name=operation_ref.operationsId))
@base.ReleaseTracks(base.ReleaseTrack.GA)
class CreateGA(_Create, base.Command):
"""Create a Database Migration Service migration job."""
detailed_help = DETAILED_HELP_GA
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddHeterogeneousMigrationJobResourceArgs(
parser, 'to create', required=True
)
_Create.Args(parser)
mj_flags.AddFilterFlag(parser)
mj_flags.AddCommitIdFlag(parser)
mj_flags.AddDumpParallelLevelFlag(parser)
mj_flags.AddSqlServerHomogeneousMigrationConfigFlag(parser, is_update=False)
mj_flags.AddDumpTypeFlag(parser)
mj_flags.AddMigrationJobObjectsConfigFlagForCreateAndUpdate(parser)
mj_flags.AddHeterogeneousMigrationConfigFlag(parser)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(_Create, base.Command):
"""Create a Database Migration Service migration job."""
detailed_help = DETAILED_HELP_ALPHA
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddMigrationJobResourceArgs(
parser, 'to create', required=True
)
_Create.Args(parser)

View File

@@ -0,0 +1,32 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: |
Delete a Database Migration Service migration job.
description: |
Delete a Database Migration Service migration job.
examples: |
To delete a migration job:
$ {command} MIGRATION_JOB --region=us-central1
request:
collection: datamigration.projects.locations.migrationJobs
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
arguments:
resource:
help_text: |
Migration job resource - Database Migration Service migration job to delete.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:migration_job
params:
- api_field: force
arg_name: force
required: false
help_text: |
The destination Cloud SQL connection profile is always deleted with the
migration job. In case of force delete, the destination Cloud SQL replica
database is also deleted.

View File

@@ -0,0 +1,22 @@
- release_tracks: [GA]
help_text:
brief: |
Demote a destination of a Database Migration Service migration job.
description: |
Demote a destination of a Database Migration Service migration job.
examples: |
To Demote a migration job destination:
$ {command} MIGRATION_JOB --region=us-central1
request:
collection: datamigration.projects.locations.migrationJobs
GA:
api_version: v1
method: demoteDestination
arguments:
resource:
help_text: |
Migration job resource - Cloud Database Migration Service migration job to demote its destination.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:migration_job

View File

@@ -0,0 +1,20 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: Show details about a Database Migration Service migration job.
description: Show details about a Database Migration Service migration job.
examples: |
To show details about a migration job, run:
$ {command} my-migration-job --region=us-central1
request:
collection: datamigration.projects.locations.migrationJobs
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
arguments:
resource:
help_text: The migration job you want to get the details of.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:migration_job

View File

@@ -0,0 +1,115 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to restart migration jobs for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import api_util
from googlecloudsdk.api_lib.database_migration import migration_jobs
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
DETAILED_HELP = {
'DESCRIPTION': """
Fetch objects for a Database Migration Service migration job by connection to the source.
""",
'EXAMPLES': """\
To fetch source objects for a migration job:
$ {command} MIGRATION_JOB --region=us-central1
""",
}
class _MigrationJobObjectInfo:
"""Container for migration job object data using in list display."""
def __init__(self, message):
self.name = message.name
self.source_object = message.sourceObject
self.error = message.error if message.error is not None else None
self.state = message.state
self.phase = message.phase
self.create_time = message.createTime
self.update_time = message.updateTime
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class FetchSourceObjects(base.Command):
"""Fetch objects for a Database Migration Service migration job by connection to the source."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddOnlyMigrationJobResourceArgs(parser, 'to restart')
parser.display_info.AddFormat("""
table(
source_object,
state:label=STATE,
phase:label=PHASE,
error:label=ERROR
)
""")
def Run(self, args):
"""Fetch source objects for a Database Migration Service migration job.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the restart
operation if the restart was successful.
"""
migration_job_ref = args.CONCEPTS.migration_job.Parse()
mj_client = migration_jobs.MigrationJobsClient(self.ReleaseTrack())
result_operation = mj_client.FetchSourceObjects(
migration_job_ref.RelativeName(),
)
client = api_util.GetClientInstance(self.ReleaseTrack())
log.status.Print(
'Waiting for migration job [{}] to fetch source objects with [{}]'
.format(migration_job_ref.migrationJobsId, result_operation.name)
)
api_util.HandleLRO(
client,
result_operation,
client.projects_locations_migrationJobs,
no_resource=True,
)
log.status.Print(
'Fetched source objects for migration job {} [{}]'.format(
migration_job_ref.migrationJobsId, result_operation.name
)
)
obj = mj_client.ListObjects(migration_job_ref)
return [_MigrationJobObjectInfo(o) for o in obj]

View File

@@ -0,0 +1,93 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: Generate a SSH script for a Database Migration Service migration job.
description: |
Generate a script for a Database Migration Service migration job, to configure Reverse SSH
tunnel connectivity with a bastion host on a Compute Engine VM instance.
You can use an existing VM instance or create a new VM for this purpose.
Copy the generated script and run it in bash from a machine that has:
- The gcloud command-line tool installed.
- Access to your source database.
- Access to the existing bastion VM, or permissions and access to the Cloud Compute API if creating a new bastion VM.
Make sure this machine is available during the entire migration.
Running the script will set up the SSH tunnel on the VM you selected and will establish
connectivity between the source database and the Cloud SQL instance.
Find additional information [here](https://cloud.google.com/database-migration/docs/mysql/configure-connectivity-reverse-ssh-tunnel).
ALPHA:
examples: |
To generate an SSH script with bastion VM instance creation:
$ {command} my-migration-job --vm=vm1 --vm-port=1111 --vm-machine-type=n1-standard-1
--vm-zone-create=us-central1-a --vpc=projects/my-project/global/networks/my-network
--region=us-central1
To generate an SSH script with an existing bastion VM instance:
$ {command} my-migration-job --vm=vm1 --vm-port=1111 --vm-zone=us-central1-a --region=us-central1
GA:
examples: |
To generate an SSH script with bastion VM instance creation:
$ {command} my-migration-job --vm=vm1 --vm-port=1111 --vm-machine-type=n1-standard-1
--vm-zone-create=us-central1-a --subnet=sample-subnet --region=us-central1
To generate an SSH script with an existing bastion VM instance:
$ {command} my-migration-job --vm=vm1 --vm-port=1111 --vm-zone=us-central1-a
--region=us-central1
request:
collection: datamigration.projects.locations.migrationJobs
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
method: generateSshScript
arguments:
resource:
help_text: The migration job to generate the SSH script for.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:migration_job
params:
- api_field: generateSshScriptRequest.vm
arg_name: vm
required: true
help_text: |
Bastion Compute Engine VM instance name to use or to create.
- api_field: generateSshScriptRequest.vmPort
arg_name: vm-port
help_text: |
Port that will be open on the bastion host.
- group:
required: true
mutex: true
params:
- group:
params:
- api_field: generateSshScriptRequest.vmCreationConfig.vmMachineType
arg_name: vm-machine-type
required: true
help_text: |
Machine type for a new VM instance.
To get a list of available machine types, run 'gcloud compute machine-types list'.
- api_field: generateSshScriptRequest.vmCreationConfig.vmZone
arg_name: vm-zone-create
help_text: |
Zone to create the VM instance in.
- api_field: generateSshScriptRequest.vmCreationConfig.subnet
required: true
ALPHA:
arg_name: vpc
help_text: |
VPC to create the VM instance in.
GA:
arg_name: subnet
help_text: |
Subnet to create the VM instance in.
- api_field: generateSshScriptRequest.vmSelectionConfig.vmZone
arg_name: vm-zone
help_text: |
Zone the existing bastion VM instance is located in.

View File

@@ -0,0 +1,34 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: List Database Migration Service migration jobs.
description: List Database Migration Service migration jobs.
examples: |
To list all migration jobs in a project and region 'us-central1', run:
$ {command} --region=us-central1
request:
collection: datamigration.projects.locations.migrationJobs
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
response:
id_field: name
arguments:
resource:
help_text: The location you want to list the migration jobs for.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:region
output:
format: |
table(
name.basename():label=MIGRATION_JOB_ID,
displayName,
name.scope('locations').segment(0):label=REGION,
state:label=STATUS,
source.scope("connectionProfiles"),
destination.scope("connectionProfiles")
)

View File

@@ -0,0 +1,114 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to promote migration jobs for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import migration_jobs
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.migration_jobs import flags as mj_flags
DETAILED_HELP_ALPHA = {
'DESCRIPTION': """
Promote a Database Migration Service migration job.
""",
'EXAMPLES': """\
To promote a migration job:
$ {command} MIGRATION_JOB --region=us-central1
""",
}
DETAILED_HELP_GA = {
'DESCRIPTION': """
Promote a Database Migration Service migration job.
""",
'EXAMPLES': """\
To promote a migration job:
$ {command} MIGRATION_JOB --region=us-central1
""",
}
class _Promote(object):
"""Promote a Database Migration Service migration job."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddOnlyMigrationJobResourceArgs(parser, 'to promote')
def Run(self, args):
"""Promote a Database Migration Service migration job.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the promote
operation if the promote was successful.
"""
migration_job_ref = args.CONCEPTS.migration_job.Parse()
mj_client = migration_jobs.MigrationJobsClient(self.ReleaseTrack())
return mj_client.Promote(
migration_job_ref.RelativeName(),
args,
)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class PromoteGA(_Promote, base.Command):
"""Promote a Database Migration Service migration job."""
detailed_help = DETAILED_HELP_GA
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
_Promote.Args(parser)
mj_flags.AddMigrationJobObjectsConfigFlagForPromote(parser)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class PromoteAlpha(_Promote, base.Command):
"""Promote a Database Migration Service migration job."""
detailed_help = DETAILED_HELP_ALPHA
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
_Promote.Args(parser)

View File

@@ -0,0 +1,121 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to restart migration jobs for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import migration_jobs
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.migration_jobs import flags as mj_flags
DETAILED_HELP_ALPHA = {
'DESCRIPTION': """
Restart a Database Migration Service migration job.
""",
'EXAMPLES': """\
To restart a migration job:
$ {command} MIGRATION_JOB --region=us-central1
""",
}
DETAILED_HELP_GA = {
'DESCRIPTION': """
Restart a Database Migration Service migration job.
""",
'EXAMPLES': """\
To restart a migration job:
$ {command} MIGRATION_JOB --region=us-central1
To restart a migration job without running prior configuration verification:
$ {command} MIGRATION_JOB --region=us-central1 --skip-validation
""",
}
class _Restart(object):
"""Restart a Database Migration Service migration job."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddOnlyMigrationJobResourceArgs(parser, 'to restart')
def Run(self, args):
"""Restart a Database Migration Service migration job.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the restart
operation if the restart was successful.
"""
migration_job_ref = args.CONCEPTS.migration_job.Parse()
mj_client = migration_jobs.MigrationJobsClient(self.ReleaseTrack())
return mj_client.Restart(
migration_job_ref.RelativeName(),
args,
)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class RestartGA(_Restart, base.Command):
"""Restart a Database Migration Service migration job."""
detailed_help = DETAILED_HELP_GA
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
_Restart.Args(parser)
mj_flags.AddSkipValidationFlag(parser)
mj_flags.AddMigrationJobObjectsConfigFlagForRestart(parser)
mj_flags.AddRestartFailedObjectsFlag(parser)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class RestartAlpha(_Restart, base.Command):
"""Restart a Database Migration Service migration job."""
detailed_help = DETAILED_HELP_ALPHA
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
_Restart.Args(parser)

View File

@@ -0,0 +1,33 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: |
Resume a Database Migration Service migration job.
description: |
Resume a Database Migration Service migration job.
examples: |
To resume a migration job:
$ {command} MIGRATION_JOB --region=us-central1
request:
collection: datamigration.projects.locations.migrationJobs
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
method: resume
arguments:
resource:
help_text: |
Migration job resource - Cloud Database Migration Service migration job to resume.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:migration_job
params:
- arg_name: skip-validation
release_tracks: [GA]
GA:
api_field: resumeMigrationJobRequest.skipValidation
required: false
help_text: |
Resume the migration job without running prior configuration verification.

View File

@@ -0,0 +1,33 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: |
Start a Database Migration Service migration job.
description: |
Start a Database Migration Service migration job.
examples: |
To start a migration job:
$ {command} MIGRATION_JOB --region=us-central1
request:
collection: datamigration.projects.locations.migrationJobs
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
method: start
arguments:
resource:
help_text: |
Migration job resource - Cloud Database Migration Service migration job to start.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:migration_job
params:
- arg_name: skip-validation
release_tracks: [GA]
GA:
api_field: startMigrationJobRequest.skipValidation
required: false
help_text: |
Start the migration job without running prior configuration verification.

View File

@@ -0,0 +1,24 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: |
Stop a Database Migration Service migration job.
description: |
Stop a Database Migration Service migration job.
examples: |
To stop a migration job:
$ {command} MIGRATION_JOB --region=us-central1
request:
collection: datamigration.projects.locations.migrationJobs
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
method: stop
arguments:
resource:
help_text: |
Migration job resource - Cloud Database Migration Service migration job to stop.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:migration_job

View File

@@ -0,0 +1,147 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to update migration jobs for a database migration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import api_util
from googlecloudsdk.api_lib.database_migration import migration_jobs
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration import flags
from googlecloudsdk.command_lib.database_migration.migration_jobs import flags as mj_flags
from googlecloudsdk.core import log
DETAILED_HELP = {
'DESCRIPTION':
"""
Update a Database Migration Service migration job.
- Draft migration job: user can update all available flags.
- Any other state can only update flags: `--display-name`,
`--dump-path`, and connectivity method flags.
""",
'EXAMPLES':
"""\
To update the source and destination connection profiles of a draft
migration job:
$ {command} my-migration-job --region=us-central1 --source=new-src
--destination=new-dest
To update the display name of a running migration job:
$ {command} my-migration-job --region=us-central1
--display-name=new-name
""",
}
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.GA)
class _Update(object):
"""Update a Database Migration Service migration job."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddMigrationJobResourceArgs(parser, 'to update')
mj_flags.AddNoAsyncFlag(parser)
mj_flags.AddDisplayNameFlag(parser)
mj_flags.AddTypeFlag(parser)
mj_flags.AddDumpGroupFlag(parser)
mj_flags.AddConnectivityGroupFlag(parser, mj_flags.ApiType.UPDATE)
flags.AddLabelsUpdateFlags(parser)
def Run(self, args):
"""Update a Database Migration Service migration job.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the update
operation if the update was successful.
"""
migration_job_ref = args.CONCEPTS.migration_job.Parse()
source_ref = args.CONCEPTS.source.Parse()
destination_ref = args.CONCEPTS.destination.Parse()
mj_client = migration_jobs.MigrationJobsClient(self.ReleaseTrack())
result_operation = mj_client.Update(migration_job_ref.RelativeName(),
source_ref, destination_ref, args)
client = api_util.GetClientInstance(self.ReleaseTrack())
messages = api_util.GetMessagesModule(self.ReleaseTrack())
resource_parser = api_util.GetResourceParser(self.ReleaseTrack())
if args.IsKnownAndSpecified('no_async'):
log.status.Print(
'Waiting for migration job [{}] to be updated with [{}]'.format(
migration_job_ref.migrationJobsId, result_operation.name))
api_util.HandleLRO(client, result_operation,
client.projects_locations_migrationJobs)
log.status.Print('Updated migration job {} [{}]'.format(
migration_job_ref.migrationJobsId, result_operation.name))
return
operation_ref = resource_parser.Create(
'datamigration.projects.locations.operations',
operationsId=result_operation.name,
projectsId=migration_job_ref.projectsId,
locationsId=migration_job_ref.locationsId)
return client.projects_locations_operations.Get(
messages.DatamigrationProjectsLocationsOperationsGetRequest(
name=operation_ref.operationsId))
@base.ReleaseTracks(base.ReleaseTrack.GA)
class UpdateGA(_Update, base.Command):
"""Update a Database Migration Service migration job."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
_Update.Args(parser)
mj_flags.AddDumpParallelLevelFlag(parser)
mj_flags.AddDumpTypeFlag(parser)
mj_flags.AddFilterFlag(parser)
mj_flags.AddCommitIdFlag(parser)
mj_flags.AddSqlServerHomogeneousMigrationConfigFlag(parser, is_update=True)
mj_flags.AddMigrationJobObjectsConfigFlagForCreateAndUpdate(parser)
mj_flags.AddHeterogeneousMigrationConfigFlag(parser, is_update=True)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(_Update, base.Command):
"""Update a Database Migration Service migration job."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
_Update.Args(parser)

View File

@@ -0,0 +1,24 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: |
Verify a Database Migration Service migration job.
description: |
Verify a Database Migration Service migration job.
examples: |
To verify a migration job:
$ {command} MIGRATION_JOB --region=us-central1
request:
collection: datamigration.projects.locations.migrationJobs
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
method: verify
arguments:
resource:
help_text: |
Migration job resource - Cloud Database Migration Service migration job to verify.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:migration_job

View File

@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The migration job objects command group for Database Migration Service."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Objects(base.Group):
"""Manage Database Migration Service migration job objects.
Commands for managing Database Migration Service migration job objects.
"""

View File

@@ -0,0 +1,85 @@
# -*- 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.
"""Implementation of migration job objects list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import objects
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
class _MigrationJobObjectInfo:
"""Container for migration job object data using in list display."""
def __init__(self, message):
self.name = message.name
self.source_object = message.sourceObject
self.error = message.error if message.error is not None else None
self.state = message.state
self.phase = message.phase
self.create_time = message.createTime
self.update_time = message.updateTime
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List a DMS migration job objects.
List migration job objects.
## API REFERENCE
This command uses the database-migration/v1 API. The full documentation
for this API can be found at: https://cloud.google.com/database-migration/
## EXAMPLES
To list all objects in a migration job and location 'us-central1',
run:
$ {command} --migration-job=mj --region=us-central1
"""
@classmethod
def Args(cls, parser):
"""Register flags for this command."""
resource_args.AddOnlyMigrationJobResourceArgs(
parser, 'to list migration job objects', positional=False
)
parser.display_info.AddFormat("""
table(
source_object,
state:label=STATE,
phase:label=PHASE,
error:label=ERROR
)
""")
def Run(self, args):
"""Runs the command.
Args:
args: All the arguments that were provided to this command invocation.
Returns:
An iterator over objects containing migration job objects data.
"""
objects_client = objects.ObjectsClient(self.ReleaseTrack())
migration_job_ref = args.CONCEPTS.migration_job.Parse()
obj = objects_client.List(migration_job_ref, args)
return [_MigrationJobObjectInfo(o) for o in obj]

View File

@@ -0,0 +1,71 @@
# -*- 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.
"""Implementation of migration job object lookup command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import objects
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.objects import flags as objects_flags
DESCRIPTION = (
'Lookup a migration job object by its source object identifier (e.g.'
' database)'
)
EXAMPLES = """\
To lookup an existing migration job object:
$ {command} --migration-job=my-job --location=us-central1 --database=my-database
"""
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Lookup(base.Command):
"""Lookup a DMS migration job object."""
detailed_help = {'DESCRIPTION': DESCRIPTION, 'EXAMPLES': EXAMPLES}
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddOnlyMigrationJobResourceArgs(
parser, 'to list migration job objects', positional=False
)
objects_flags.AddSourceObjectIdentifierFlag(parser)
def Run(self, args):
"""Lookup a DMS migration job object.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the looked up migration job object if the
lookup was successful.
"""
objects_client = objects.ObjectsClient(self.ReleaseTrack())
migration_job_ref = args.CONCEPTS.migration_job.Parse()
return objects_client.Lookup(migration_job_ref, args)

View File

@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The operations command group for Database Migration Service."""
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.GA)
class Operations(base.Group):
"""Manage Database Migration Service operations.
Commands for managing Database Migration Service operations.
"""

View File

@@ -0,0 +1,22 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: Delete a Database Migration Service operation.
description: Delete a Database Migration Service operation.
examples: |
To delete an operation.
$ {command} OPERATION --region=us-central1
request:
collection: datamigration.projects.locations.operations
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
method: delete
arguments:
resource:
help_text: |
Operation resource - Database Migration Service operation to delete.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:operation

View File

@@ -0,0 +1,20 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: Show details about a operation.
description: Show details about a operation.
examples: |
To show details about a operation, run:
$ {command} my-operation --region=us-central1
request:
collection: datamigration.projects.locations.operations
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
arguments:
resource:
help_text: The operation you want to get the details of.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:operation

View File

@@ -0,0 +1,33 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: List operations.
description: List operations.
examples: |
To list all operations in a project and region 'us-central1', run:
$ {command} --region=us-central1
request:
collection: datamigration.projects.locations.operations
GA:
api_version: v1
ALPHA:
api_version: v1alpha2
response:
id_field: name
arguments:
resource:
help_text: The location you want to list the operations for.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:region
output:
format: |
table(
name.scope("operations"):label=ID,
metadata.target.scope("locations"):label=TARGET,
metadata.verb:label=ACTION,
done:label=DONE,
error.code:label=ERROR_CODE
)

View File

@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The private connections command group for Database Migration Service."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA)
class PrivateConnections(base.Group):
"""Manage Database Migration Service private connections.
Commands for managing Database Migration Service private connections.
"""

View File

@@ -0,0 +1,147 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create a database migration private connection."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import api_util
from googlecloudsdk.api_lib.database_migration import private_connections
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration import flags
from googlecloudsdk.command_lib.database_migration.private_connections import flags as pc_flags
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.command_lib.util.concepts import presentation_specs
from googlecloudsdk.core import log
DESCRIPTION = 'Create a Database Migration private connection'
EXAMPLES = """\
To create a private connection with VPC Peering called 'my-private-connection', run:
$ {command} my-private-connection --region=us-central1 --display-name=my-private-connection --vpc=vpc-example --subnet=10.0.0.0/29
To create a private connection with PSC Interface called 'my-privateConnection', run:
$ {command} my-private-connection --location=us-central1 --display-name=my-private-connection --network-attachment=network-attachment-example
To use a private connection, all migrations and connection profiles that use this configuration must be in the same region.
"""
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class Create(base.Command):
"""Create a Database Migration private connection."""
detailed_help = {'DESCRIPTION': DESCRIPTION, 'EXAMPLES': EXAMPLES}
@staticmethod
def CommonArgs(parser, release_track):
"""Common arguments for all release tracks.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
release_track: Some arguments are added based on the command release
track.
"""
resource_args.AddPrivateConnectionResourceArg(parser, 'to create')
pc_flags.AddDisplayNameFlag(parser)
pc_flags.AddNoAsyncFlag(parser)
pc_flags.AddSkipValidationFlag(parser)
pc_flags.AddValidateOnlyFlag(parser)
flags.AddLabelsCreateFlags(parser)
config_group = parser.add_group(mutex=True, required=True)
vpc_peering_group = config_group.add_group(
help='Arguments for VPC Peering configuration.'
)
vpc_peering_group.add_argument(
'--subnet',
help="""A free subnet for peering. (CIDR of /29).""",
required=True,
)
# Add VPC resource arg inside the VPC Peering group
vpc_spec = presentation_specs.ResourcePresentationSpec(
'--vpc',
resource_args.GetVpcResourceSpec(),
'Resource ID of the VPC network to peer with.',
group=vpc_peering_group,
required=True,
) # Ensure VPC is required within this group
concept_parsers.ConceptParser([vpc_spec]).AddToParser(vpc_peering_group)
# --- PSC Interface Group ---
psc_group = config_group.add_group(
help='Arguments for Private Service Connect Interface configuration.'
)
pc_flags.AddNetworkAttachmentFlag(psc_group)
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command."""
Create.CommonArgs(parser, base.ReleaseTrack.GA)
def Run(self, args):
"""Create a Database Migration private connection.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the create
operation if the create was successful.
"""
private_connection_ref = args.CONCEPTS.private_connection.Parse()
parent_ref = private_connection_ref.Parent().RelativeName()
pc_client = private_connections.PrivateConnectionsClient(
release_track=self.ReleaseTrack())
result_operation = pc_client.Create(
parent_ref, private_connection_ref.privateConnectionsId, args)
client = api_util.GetClientInstance(self.ReleaseTrack())
messages = api_util.GetMessagesModule(self.ReleaseTrack())
resource_parser = api_util.GetResourceParser(self.ReleaseTrack())
if args.IsKnownAndSpecified('no_async'):
log.status.Print(
'Waiting for private connection [{}] to be created with [{}]'.format(
private_connection_ref.privateConnectionsId,
result_operation.name))
api_util.HandleLRO(client, result_operation,
client.projects_locations_privateConnections)
log.status.Print('Created private connection {} [{}]'.format(
private_connection_ref.privateConnectionsId, result_operation.name))
return
operation_ref = resource_parser.Create(
'datamigration.projects.locations.operations',
operationsId=result_operation.name,
projectsId=private_connection_ref.projectsId,
locationsId=private_connection_ref.locationsId)
return client.projects_locations_operations.Get(
messages.DatamigrationProjectsLocationsOperationsGetRequest(
name=operation_ref.operationsId))

View File

@@ -0,0 +1,111 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to delete a database migration private connection."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.database_migration import api_util
from googlecloudsdk.api_lib.database_migration import private_connections
from googlecloudsdk.api_lib.database_migration import resource_args
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.database_migration.private_connections import flags as pc_flags
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
DESCRIPTION = 'Delete a Database Migration private connection'
EXAMPLES = """\
To delete a private connection called 'my-private-connection', run:
$ {command} my-private-connection --region=us-central1
"""
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Delete(base.Command):
"""Delete a Database Migration private connection."""
detailed_help = {'DESCRIPTION': DESCRIPTION, 'EXAMPLES': EXAMPLES}
@staticmethod
def CommonArgs(parser):
"""Common arguments for all release tracks.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
resource_args.AddPrivateConnectionDeleteResourceArg(parser, 'to delete')
pc_flags.AddNoAsyncFlag(parser)
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command."""
Delete.CommonArgs(parser)
def Run(self, args):
"""Delete a Database Migration private connection.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the delete
operation if the delete was successful.
"""
private_connection_ref = args.CONCEPTS.private_connection.Parse()
delete_warning = ('You are about to delete private_connection {}.\n'
'Are you sure?'.format(
private_connection_ref.RelativeName()))
if not console_io.PromptContinue(message=delete_warning):
return None
pc_client = private_connections.PrivateConnectionsClient(
release_track=self.ReleaseTrack())
result_operation = pc_client.Delete(private_connection_ref.RelativeName())
client = api_util.GetClientInstance(self.ReleaseTrack())
messages = api_util.GetMessagesModule(self.ReleaseTrack())
resource_parser = api_util.GetResourceParser(self.ReleaseTrack())
if args.IsKnownAndSpecified('no_async'):
log.status.Print(
'Waiting for private connection [{}] to be deleted with [{}]'.format(
private_connection_ref.privateConnectionsId,
result_operation.name))
api_util.HandleLRO(
client,
result_operation,
client.projects_locations_privateConnections,
no_resource=True)
log.status.Print('Deleted private connection {} [{}]'.format(
private_connection_ref.privateConnectionsId, result_operation.name))
return
operation_ref = resource_parser.Create(
'datamigration.projects.locations.operations',
operationsId=result_operation.name,
projectsId=private_connection_ref.projectsId,
locationsId=private_connection_ref.locationsId)
return client.projects_locations_operations.Get(
messages.DatamigrationProjectsLocationsOperationsGetRequest(
name=operation_ref.operationsId))

View File

@@ -0,0 +1,17 @@
- release_tracks: [GA]
help_text:
brief: Show details about a database migration private connection.
description: Show details about a private connection.
examples: |
To show details about a private connection called 'my-private-connection', run:
$ {command} my-private-connection --region=us-central1
request:
collection: datamigration.projects.locations.privateConnections
api_version: v1
arguments:
resource:
help_text: The private connection you want to get the details of.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:private_connection

View File

@@ -0,0 +1,30 @@
- release_tracks: [GA]
help_text:
brief: List private connections.
description: List private connections.
examples: |
To list all private connections in the current project and location 'us-central1', run:
$ {command} --region=us-central1
request:
collection: datamigration.projects.locations.privateConnections
api_version: v1
response:
id_field: name
arguments:
resource:
help_text: The region you want to list the private connections for.
spec: !REF googlecloudsdk.command_lib.database_migration.resources:region
output:
format: |
table(
name.basename():label=PRIVATE_CONNECTION_ID,
displayName,
name.scope('locations').segment(0):label=REGION,
state:label=STATUS,
createTime.date():label=CREATED
)