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,25 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The gcloud firestore databases command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class Databases(base.Group):
"""Manage Creation of Cloud Firestore in Native mode Database."""

View File

@@ -0,0 +1,102 @@
# -*- 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 gcloud Firestore databases clone command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.firestore import databases
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.firestore import flags
from googlecloudsdk.command_lib.firestore import util as utils
from googlecloudsdk.core import properties
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Clone(base.Command):
"""Clone a Google Cloud Firestore database from another.
## EXAMPLES
To clone a database from another:
$ {command}
--source-database=projects/PROJECT_ID/databases/SOURCE_DATABASE
--snapshot-time=2025-05-26T10:20:00.00Z
--destination-database=DATABASE_ID
To clone to a CMEK-enabled database:
$ {command}
--source-database=projects/PROJECT_ID/databases/SOURCE_DATABASE
--snapshot-time=2025-05-26T10:20:00.00Z
--destination-database=DATABASE_ID
--encryption-type=customer-managed-encryption
--kms-key-name=projects/PROJECT_ID/locations/LOCATION_ID/keyRings/KEY_RING_ID/cryptoKeys/CRYPTO_KEY_ID
"""
@classmethod
def Args(cls, parser):
parser.add_argument(
'--source-database',
metavar='SOURCE_DATABASE',
type=str,
required=True,
help=textwrap.dedent("""\
The source database to clone from.
For example, to clone from database
source-db:
$ {command} --source-database=projects/PROJECT_ID/databases/source-db
"""),
)
parser.add_argument(
'--snapshot-time',
metavar='SNAPSHOT_TIME',
type=str,
required=True,
help=textwrap.dedent("""\
Snapshot time at which to clone. This must be a whole minute, in the past, and not earlier than the source database's earliest_version_time.
Additionally, if older than one hour in the past, PITR must be enabled on the source database.
For example, to restore from snapshot `2025-05-26T10:20:00.00Z` of source database `source-db`:
$ {command} --source-database=projects/PROJECT_ID/databases/source-db --snapshot-time=2025-05-26T10:20:00.00Z
"""),
)
flags.AddDestinationDatabase(parser, 'clone', 'database')
flags.AddEncryptionConfigGroup(parser, 'database')
flags.AddTags(parser, 'database')
def Run(self, args):
project = properties.VALUES.core.project.Get(required=True)
return databases.CloneDatabase(
project,
args.source_database,
args.snapshot_time,
args.destination_database,
self.EncryptionConfig(args),
args.tags,
)
def EncryptionConfig(self, args):
return utils.ExtractEncryptionConfig(args)

View File

@@ -0,0 +1,123 @@
# -*- 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 gcloud Firestore databases connection-string command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.firestore import databases
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.firestore import connection_util
from googlecloudsdk.command_lib.firestore import flags
from googlecloudsdk.core import properties
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class ConnectionString(base.Command):
"""Prints the mongo connection string for the given Firestore database.
## EXAMPLES
To get the connection string for a Firestore database with a databaseId
`testdb` without auth configuration.
$ {command} --database=testdb --auth=none
To get the connection string for a Firestore database with a databaseId
`testdb` with Google Compute Engine VM auth.
$ {command} --database=testdb --auth=gce-vm
"""
_BASE_OUTPUT = 'mongodb://{}{}.{}.firestore.goog:443/{}?loadBalanced=true&tls=true&retryWrites=false'
_GCE_VM_AUTH = '&authMechanism=MONGODB-OIDC&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:FIRESTORE'
@staticmethod
def Args(parser):
flags.AddDatabaseIdFlag(parser, required=True)
group = parser.add_mutually_exclusive_group()
group.add_argument(
'--validate',
metavar='VALIDATE',
required=False,
hidden=False,
type=str,
help="""
Validate the specified connection string for the current database. This
command checks that the connection string is well formed, contains the
required parameters, and specifies correct configuration values for the
current database.
""",
)
group.add_argument(
'--auth',
metavar='AUTH',
required=False,
hidden=False,
type=str,
choices=['none', 'gce-vm', 'access-token', 'scram-sha-256'],
default='none',
help="""
The auth configuration for the connection string.
If connecting from a Google Compute Engine VM, use `gce-vm`. For short
term access using the gcloud CLI's access token, use `access-token`.
For password auth use scram-sha-256. Otherwise, use `none` and configure
auth manually.
""",
)
def Run(self, args):
project = properties.VALUES.core.project.Get(required=True)
db = databases.GetDatabase(project, args.database)
database_id = '_' if args.database == '(default)' else args.database
if args.validate:
connection_util.PrettyPrintValidationResults(
connection_util.ValidateConnectionString(
args.validate, db.uid, db.locationId, args.database
)
)
return None
elif args.auth == 'gce-vm':
return (
self._BASE_OUTPUT.format('', db.uid, db.locationId, database_id)
+ self._GCE_VM_AUTH
)
elif args.auth == 'access-token':
return (
self._BASE_OUTPUT.format(
'access_token:$(gcloud auth print-access-token)@',
db.uid,
db.locationId,
database_id,
)
+ '&authMechanism=PLAIN&authSource=$external'
)
elif args.auth == 'scram-sha-256':
return (
self._BASE_OUTPUT.format(
'username:password@',
db.uid,
db.locationId,
database_id,
)
+ '&authMechanism=SCRAM-SHA-256'
)
return self._BASE_OUTPUT.format('', db.uid, db.locationId, database_id)

View File

@@ -0,0 +1,356 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create a Cloud Firestore Database."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.firestore import api_utils
from googlecloudsdk.api_lib.firestore import databases
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.firestore import flags
from googlecloudsdk.core import properties
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class CreateFirestoreAPI(base.Command):
"""Create a Google Cloud Firestore database via Firestore API.
## EXAMPLES
To create a Firestore Enterprise database named `foo` in `nam5` for use with
MongoDB Compatibility.
$ {command} --database=foo --edition=enterprise --location=nam5
To create a Firestore Native database in `nam5`.
$ {command} --location=nam5
To create a Firestore Native database in `us-central1` with tags.
$ {command} --location=us-central1 --tags=key1=value1,key2=value2
To create a Datastore Mode database in `us-east1`.
$ {command} --location=us-east1 --type=datastore-mode
To create a Datastore Mode database in `us-east1` with a databaseId `foo`.
$ {command} --database=foo --location=us-east1 --type=datastore-mode
To create a Firestore Native database in `nam5` with delete protection
enabled.
$ {command} --location=nam5 --delete-protection
To create a Firestore Native database in `nam5` with Point In Time Recovery
(PITR) enabled.
$ {command} --location=nam5 --enable-pitr
To create a Firestore Native database in `nam5` encrypted by a
Customer-managed encryption key (CMEK).
$ {command}
--location=nam5
--kms-key-name=projects/PROJECT_ID/locations/us/keyRings/KEY_RING_ID/cryptoKeys/CRYPTO_KEY_ID
"""
def DatabaseType(self, database_type):
if database_type == 'firestore-native':
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.TypeValueValuesEnum.FIRESTORE_NATIVE
)
elif database_type == 'datastore-mode':
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.TypeValueValuesEnum.DATASTORE_MODE
)
else:
raise ValueError('invalid database type: {}'.format(database_type))
def DatabaseEdition(self, database_edition):
if database_edition == 'standard':
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.DatabaseEditionValueValuesEnum.STANDARD
)
elif database_edition == 'enterprise':
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.DatabaseEditionValueValuesEnum.ENTERPRISE
)
else:
raise ValueError('invalid database edition: {}'.format(database_edition))
def DatabaseDeleteProtectionState(self, enable_delete_protection):
if enable_delete_protection:
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.DeleteProtectionStateValueValuesEnum.DELETE_PROTECTION_ENABLED
)
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.DeleteProtectionStateValueValuesEnum.DELETE_PROTECTION_DISABLED
)
def DatabasePitrState(self, enable_pitr):
if enable_pitr is None:
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.PointInTimeRecoveryEnablementValueValuesEnum.POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED
)
if enable_pitr:
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.PointInTimeRecoveryEnablementValueValuesEnum.POINT_IN_TIME_RECOVERY_ENABLED
)
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.PointInTimeRecoveryEnablementValueValuesEnum.POINT_IN_TIME_RECOVERY_DISABLED
)
def DatabaseCmekConfig(self, args):
if args.kms_key_name is not None:
return api_utils.GetMessages().GoogleFirestoreAdminV1CmekConfig(
kmsKeyName=args.kms_key_name
)
return api_utils.GetMessages().GoogleFirestoreAdminV1CmekConfig()
def Run(self, args):
project = properties.VALUES.core.project.Get(required=True)
return databases.CreateDatabase(
project,
args.location,
args.database,
self.DatabaseType(args.type),
self.DatabaseEdition(args.edition),
self.DatabaseDeleteProtectionState(args.delete_protection),
self.DatabasePitrState(args.enable_pitr),
self.DatabaseCmekConfig(args),
mongodb_compatible_data_access_mode=None,
firestore_data_access_mode=None,
realtime_updates_mode=None,
tags=args.tags,
)
@classmethod
def Args(cls, parser):
flags.AddLocationFlag(
parser, required=True, suggestion_aliases=['--region']
)
parser.add_argument(
'--edition',
help='The edition of the database.',
default='standard',
choices=['standard', 'enterprise'],
)
parser.add_argument(
'--type',
help='The type of the database.',
default='firestore-native',
choices=['firestore-native', 'datastore-mode'],
)
parser.add_argument(
'--database',
help=textwrap.dedent("""\
The ID to use for the database, which will become the final
component of the database's resource name. If database ID is not
provided, (default) will be used as database ID.
This value should be 4-63 characters. Valid characters are /[a-z][0-9]-/
with first character a letter and the last a letter or a number. Must
not be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/.
Using "(default)" database ID is also allowed.
"""),
type=str,
default='(default)',
)
parser.add_argument(
'--delete-protection',
help=textwrap.dedent("""\
Whether to enable delete protection on the created database.
If set to true, delete protection of the new database will be enabled
and delete operations will fail unless delete protection is disabled.
Default to false.
"""),
action='store_true',
default=False,
)
parser.add_argument(
'--enable-pitr',
help=textwrap.dedent("""\
Whether to enable Point In Time Recovery (PITR) on the created database.
If set to true, PITR on the new database will be enabled. By default, this feature is not enabled.
"""),
action='store_true',
default=None,
)
flags.AddKmsKeyNameFlag(parser)
flags.AddTags(parser, 'database')
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateFirestoreAPIAlpha(CreateFirestoreAPI):
"""Create a Google Cloud Firestore database via Firestore API.
## EXAMPLES
To create a Firestore Enterprise database named `foo` in `nam5` for use with
MongoDB Compatibility.
$ {command} --database=foo --edition=enterprise --location=nam5
To create a Firestore Native database in `nam5`.
$ {command} --location=nam5
To create a Firestore Native database in `us-central1` with tags.
$ {command} --location=us-central1 --tags=key1=value1,key2=value2
To create a Datastore Mode database in `us-east1`.
$ {command} --location=us-east1 --type=datastore-mode
To create a Datastore Mode database in `us-east1` with a databaseId `foo`.
$ {command} --database=foo --location=us-east1 --type=datastore-mode
To create a Firestore Native database in `nam5` with delete protection
enabled.
$ {command} --location=nam5 --delete-protection
To create a Firestore Native database in `nam5` with Point In Time Recovery
(PITR) enabled.
$ {command} --location=nam5 --enable-pitr
To create a Firestore Native database in `nam5` encrypted by a
Customer-managed encryption key (CMEK).
$ {command}
--location=nam5
--kms-key-name=projects/PROJECT_ID/locations/us/keyRings/KEY_RING_ID/cryptoKeys/CRYPTO_KEY_ID
"""
def MongodbCompatibleDataAccessMode(self, enable):
if enable is None:
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.MongodbCompatibleDataAccessModeValueValuesEnum.DATA_ACCESS_MODE_UNSPECIFIED
)
if enable:
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.MongodbCompatibleDataAccessModeValueValuesEnum.DATA_ACCESS_MODE_ENABLED
)
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.MongodbCompatibleDataAccessModeValueValuesEnum.DATA_ACCESS_MODE_DISABLED
)
def FirestoreDataAccessMode(self, enable):
if enable is None:
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.FirestoreDataAccessModeValueValuesEnum.DATA_ACCESS_MODE_UNSPECIFIED
)
if enable:
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.FirestoreDataAccessModeValueValuesEnum.DATA_ACCESS_MODE_ENABLED
)
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.FirestoreDataAccessModeValueValuesEnum.DATA_ACCESS_MODE_DISABLED
)
def RealtimeUpdatesMode(self, enable):
if enable is None:
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.RealtimeUpdatesModeValueValuesEnum.REALTIME_UPDATES_MODE_UNSPECIFIED
)
if enable:
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.RealtimeUpdatesModeValueValuesEnum.REALTIME_UPDATES_MODE_ENABLED
)
return (
api_utils.GetMessages().GoogleFirestoreAdminV1Database.RealtimeUpdatesModeValueValuesEnum.REALTIME_UPDATES_MODE_DISABLED
)
def Run(self, args):
project = properties.VALUES.core.project.Get(required=True)
return databases.CreateDatabase(
project,
args.location,
args.database,
self.DatabaseType(args.type),
self.DatabaseEdition(args.edition),
self.DatabaseDeleteProtectionState(args.delete_protection),
self.DatabasePitrState(args.enable_pitr),
self.DatabaseCmekConfig(args),
self.MongodbCompatibleDataAccessMode(
args.enable_mongodb_compatible_data_access
),
self.FirestoreDataAccessMode(args.enable_firestore_data_access),
self.RealtimeUpdatesMode(args.enable_realtime_updates),
args.tags,
)
@classmethod
def Args(cls, parser):
CreateFirestoreAPI.Args(parser)
parser.add_argument(
'--enable-mongodb-compatible-data-access',
help=textwrap.dedent("""\
Whether to enable MongoDB Compatible API Data Access on the
created database.
If set to true, MongoDB Compatible API Data Access on the new
database will be enabled. By default, this feature is enabled for
Enterprise edition databases.
To disable, use --no-enable-mongodb-compatible-data-access.
"""),
action='store_true',
default=None,
hidden=True,
)
parser.add_argument(
'--enable-firestore-data-access',
help=textwrap.dedent("""\
Whether to enable Firestore API Data Access on the created
database.
If set to true, Firestore API Data Access on the new database will
be enabled. By default, this feature is disabled for Enterprise
edition databases. To explicitly disable,
use --no-enable-firestore-data-access.
"""),
action='store_true',
default=None,
hidden=True,
)
parser.add_argument(
'--enable-realtime-updates',
help=textwrap.dedent("""\
Whether to enable Realtime Updates feature on the created database.
If set to true, Realtime Updates feature on the new database will
be enabled. By default, this feature is disabled for Enterprise
edition databases. To explicitly disable,
use --no-enable-realtime-updates.
"""),
action='store_true',
default=None,
hidden=True,
)

View File

@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to delete a Cloud Firestore Database."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.firestore import databases
from googlecloudsdk.calliope import base
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(
base.ReleaseTrack.GA, base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA
)
class DeleteDatabase(base.Command):
"""Delete a Google Cloud Firestore database.
## EXAMPLES
To delete a Firestore database test.
$ {command} --database=test
To delete the Firestore (default) database.
$ {command} --database=(default)
To delete a Firestore database test providing etag.
$ {command} --database=test --etag=etag
"""
def Run(self, args):
project = properties.VALUES.core.project.Get(required=True)
console_io.PromptContinue(
message=(
"The database 'projects/{}/databases/{}' will be deleted.".format(
project, args.database
)
),
cancel_on_no=True,
)
return databases.DeleteDatabase(project, args.database, args.etag)
@staticmethod
def Args(parser):
parser.add_argument(
'--database',
help='The database to operate on.',
type=str,
required=True,
)
parser.add_argument(
'--etag',
help=(
'The current etag of the Database. If an etag is provided and does'
' not match the current etag of the database, deletion will be'
' blocked and a FAILED_PRECONDITION error will be returned.'
),
type=str,
)

View File

@@ -0,0 +1,54 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The gcloud Firestore databases describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.firestore import databases
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.firestore import flags
from googlecloudsdk.core import properties
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Describe(base.DescribeCommand):
"""Describes information about a Cloud Firestore database.
The following command describes a Google Cloud Firestore database.
## EXAMPLES
To describe a Firestore database with a databaseId `testdb`.
$ {command} --database=testdb
If databaseId is not specified, the command will describe information about
the `(default)` database.
$ {command}
"""
@staticmethod
def Args(parser):
flags.AddDatabaseIdFlag(parser, required=False)
def Run(self, args):
project = properties.VALUES.core.project.Get(required=True)
return databases.GetDatabase(project, args.database)

View File

@@ -0,0 +1,58 @@
# -*- 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.
"""List all Firestore databases under the project."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.firestore import databases
from googlecloudsdk.calliope import base
from googlecloudsdk.core import properties
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class ListAlpha(base.ListCommand):
"""Lists all Firestore databases under the project.
## EXAMPLES
To list all active Firestore databases.
$ {command}
To list all Firestore databases including deleted databases.
$ {command} --show-deleted
"""
@staticmethod
def Args(parser):
parser.add_argument(
'--show-deleted',
help='Show the deleted databases.',
action='store_true',
default=False,
)
def ListDatabases(self, show_deleted):
project = properties.VALUES.core.project.Get(required=True)
return databases.ListDatabases(project, show_deleted)
def Run(self, args):
return self.ListDatabases(args.show_deleted)

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.
"""The gcloud Firestore databases ping command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import itertools
import statistics
import textwrap
import time
from googlecloudsdk.api_lib.firestore import databases
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.firestore import connection_util
from googlecloudsdk.command_lib.firestore import flags
from googlecloudsdk.core import properties
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class Ping(base.Command):
"""Times the connection and ping time for a Firestore with MongoDB compatibility database.
## EXAMPLES
To time the connection and ping times for a Firestore with MongoDB
compatibility database `testdb`:
$ {command} --database=testdb
"""
_NUM_CONNECTS = 5
_NUM_PINGS = 10
@staticmethod
def Args(parser):
flags.AddDatabaseIdFlag(parser, required=True)
def Run(self, args):
project = properties.VALUES.core.project.Get(required=True)
db = databases.GetDatabase(project, args.database)
hostname = f'{db.uid}.{db.locationId}.firestore.goog'
timing_results = []
print(f'Testing connectivity latency to {hostname}.')
for _ in range(self._NUM_CONNECTS):
try:
timing_results.append(
connection_util.ConnectAndPing(hostname, self._NUM_PINGS)
)
except IOError as e:
print(f'Failed to establish connection to {hostname}: {e}')
time.sleep(1)
# Compute the timing statistics and build the output summary.
connect_times = list(
filter(None, [result[0] for result in timing_results if result])
)
connection_time_avg = (
f'{sum(connect_times) / len(connect_times):.3f}'
if connect_times
else 'N/A'
)
ping_time_lists = [result[1] for result in timing_results if result]
ping_times = list(
filter(None, itertools.chain.from_iterable(ping_time_lists))
)
ping_time_avg = (
f'{sum(ping_times) / len(ping_times):.3f}' if ping_times else 'N/A'
)
ping_time_stddev = (
f'{statistics.stdev(ping_times):.3f}' if len(ping_times) > 1 else 'N/A'
)
summary = f"""
Successful connections: {len(connect_times)} / {self._NUM_CONNECTS}
Average connection setup latency (s): {connection_time_avg}
Successful pings: {len(ping_times)} / {self._NUM_PINGS * self._NUM_CONNECTS}
Ping time average (s): {ping_time_avg}
Ping time standard deviation (s): {ping_time_stddev}
"""
print(textwrap.dedent(summary))

View File

@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The gcloud Firestore databases restore command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.firestore import databases
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.firestore import flags
from googlecloudsdk.command_lib.firestore import util as utils
from googlecloudsdk.core import properties
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class RestoreFirestoreAPI(base.Command):
"""Restores a Cloud Firestore database from a backup.
## EXAMPLES
To restore a database from a backup.
$ {command}
--source-backup=projects/PROJECT_ID/locations/LOCATION_ID/backups/BACKUP_ID
--destination-database=DATABASE_ID
To restore a database from a backup with tags.
$ {command}
--source-backup=projects/PROJECT_ID/locations/LOCATION_ID/backups/BACKUP_ID
--destination-database=DATABASE_ID
--tags=key1=value1,key2=value2
To restore to a CMEK-enabled database.
$ {command}
--source-backup=projects/PROJECT_ID/locations/LOCATION_ID/backups/BACKUP_ID
--destination-database=DATABASE_ID
--encryption-type=customer-managed-encryption
--kms-key-name=projects/PROJECT_ID/locations/LOCATION_ID/keyRings/KEY_RING_ID/cryptoKeys/CRYPTO_KEY_ID
"""
@classmethod
def Args(cls, parser):
parser.add_argument(
'--source-backup',
metavar='SOURCE_BACKUP',
type=str,
required=True,
help=textwrap.dedent("""\
The source backup to restore from.
For example, to restore from backup `cf9f748a-7980-4703-b1a1-d1ffff591db0` in us-east1:
$ {command} --source-backup=projects/PROJECT_ID/locations/us-east1/backups/cf9f748a-7980-4703-b1a1-d1ffff591db0
"""),
)
flags.AddDestinationDatabase(parser, 'restore', 'backup')
flags.AddEncryptionConfigGroup(parser, 'backup')
flags.AddTags(parser, 'database')
def Run(self, args):
project = properties.VALUES.core.project.Get(required=True)
return databases.RestoreDatabase(
project,
args.source_backup,
args.destination_database,
self.EncryptionConfig(args),
args.tags,
)
def EncryptionConfig(self, args):
return utils.ExtractEncryptionConfig(args)

View File

@@ -0,0 +1,30 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Update the database configuration of a Cloud Firestore database.
description: |
Update the database configuration of a Cloud Firestore database.
examples: |
The following command updates the database type of a Cloud Firestore database.
$ {command} --type=firestore-native
async:
collection: firestore.projects.databases.operations
api_version: v1
extract_resource_result: false
request:
collection: firestore.projects.databases
resource_method_params:
googleFirestoreAdminV1Database.name: '{__relative_name__}'
arguments:
resource:
help_text: Cloud Firestore database to update.
is_positional: false
# The resource arg specification itself. Imported from firestore/resources.yaml
spec: !REF googlecloudsdk.command_lib.firestore.resources:database
params:
- _REF_: googlecloudsdk.command_lib.firestore.flags:type
- _REF_: googlecloudsdk.command_lib.firestore.flags:enable_delete_protection
- _REF_: googlecloudsdk.command_lib.firestore.flags:enable_pitr