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,21 @@
# -*- 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.
"""A helper library for the Cloud NetApp Files command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,21 @@
# -*- 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.
"""A helper library for the Cloud NetApp Files AD sub-command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,251 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Files Active Directories commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.netapp import util as netapp_util
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
## Helper functions to add args / flags for Active Directory gcloud commands ##
def AddActiveDirectoryDomainArg(parser, required=True):
"""Adds a --domain arg to the given parser."""
parser.add_argument(
'--domain',
type=str,
required=required,
help="""The Active Directory domain."""
)
def AddActiveDirectorySiteArg(parser):
"""Adds a --site arg to the given parser."""
parser.add_argument(
'--site',
type=str,
help="""The Active Directory site the service\
will limit Domain Controller discovery to."""
)
def AddActiveDirectoryDnsArg(parser, required=True):
"""Adds a --dns arg to the given parser."""
parser.add_argument(
'--dns',
type=str,
required=required,
help="""A comma separated list of DNS server IP addresses for the Active Directory domain."""
)
def AddActiveDirectoryNetBiosArg(parser, required=True):
"""Adds a --net-bios-prefix arg to the given parser."""
parser.add_argument(
'--net-bios-prefix',
type=str,
required=required,
help="""NetBIOS prefix name of the server."""
)
def AddActiveDirectoryOrganizationalUnitArg(parser):
"""Adds a --organizational-unit arg to the given parser."""
parser.add_argument(
'--organizational-unit',
type=str,
help="""The Organizational Unit (OU) within the Windows Active Directory the user belongs to."""
)
def AddActiveDirectoryAesEncryptionArg(parser):
"""Adds a --enable-aes arg to the given parser."""
parser.add_argument(
'--enable-aes',
type=arg_parsers.ArgBoolean(truthy_strings=netapp_util.truthy,
falsey_strings=netapp_util.falsey),
help="""The Boolean value indiciating whether AES encryption will be enabled for SMB communication."""
)
def AddActiveDirectoryUsernameArg(parser, required=True):
"""Adds a --username arg to the given parser."""
parser.add_argument(
'--username',
type=str,
required=required,
help="""Username of the Active Directory domain administrator."""
)
def AddActiveDirectoryPasswordArg(parser, required=True):
"""Adds a --password arg to the given parser."""
parser.add_argument(
'--password',
type=str,
required=required,
help="""Password of the Active Directory domain administrator."""
)
def AddActiveDirectoryBackupOperatorsArg(parser):
"""Adds a --backup-operators arg to the given parser."""
parser.add_argument(
'--backup-operators',
type=arg_parsers.ArgList(element_type=str),
metavar='BACKUP_OPERATOR',
help="""Users to be added to the Built-in Backup Operator Active Directory group."""
)
def AddActiveDirectorySecurityOperatorsArg(parser):
"""Adds a --security-operators arg to the given parser."""
parser.add_argument(
'--security-operators',
type=arg_parsers.ArgList(element_type=str),
metavar='SECURITY_OPERATOR',
help="""Domain users to be given the Security privilege."""
)
def AddActiveDirectoryAdministratorsArg(parser):
"""Adds a --administrators arg to the given parser."""
parser.add_argument(
'--administrators',
type=arg_parsers.ArgList(element_type=str),
metavar='ADMINISTRATOR',
help="""Members of the Active Directory built-in Administrators group."""
)
def AddActivevDirectoryKdcHostnameArg(parser):
"""Adds a --kdc-hostname arg to the given parser."""
parser.add_argument(
'--kdc-hostname',
type=str,
help="""Name of the Active Directory machine."""
)
def AddActiveDirectoryKdcIpArg(parser):
"""Adds a --kdc-ip arg to the given parser."""
parser.add_argument(
'--kdc-ip',
type=str,
help="""KDC server IP address for the Active Directory machine."""
)
def AddActiveDirectoryNfsUsersWithLdapArg(parser):
"""Adds a --nfs-users-with-ldap arg to the given parser."""
parser.add_argument(
'--nfs-users-with-ldap',
type=arg_parsers.ArgBoolean(truthy_strings=netapp_util.truthy,
falsey_strings=netapp_util.falsey),
help="""Boolean flag that allows access to local users and LDAP users. If access is needed only for LDAP users, it has to be disabled."""
)
def AddActiveDirectoryLdapSigningArg(parser):
"""Adds a --enable-ldap-signing arg to the given parser."""
parser.add_argument(
'--enable-ldap-signing',
type=arg_parsers.ArgBoolean(truthy_strings=netapp_util.truthy,
falsey_strings=netapp_util.falsey),
help="""Boolean flag that specifies whether or not LDAP traffic needs to be signed."""
)
def AddActiveDirectoryEncryptDcConnectionsArg(parser):
"""Adds a --encrypt-dc-connections arg to the given parser."""
parser.add_argument(
'--encrypt-dc-connections',
type=arg_parsers.ArgBoolean(truthy_strings=netapp_util.truthy,
falsey_strings=netapp_util.falsey),
help="""Boolean flag that specifies whether traffic between SMB server to Domain Controller (DC) will be encrypted."""
)
## Helper functions to combine Active Directory args / flags for ##
## gcloud commands ##
def AddActiveDirectoryCreateArgs(parser):
"""Add args for creating an Active Directory."""
concept_parsers.ConceptParser([
flags.GetActiveDirectoryPresentationSpec(
'The Active Directory to create.')
]).AddToParser(parser)
flags.AddResourceDescriptionArg(parser, 'Active Directory')
flags.AddResourceAsyncFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
AddActiveDirectoryDomainArg(parser)
AddActiveDirectorySiteArg(parser)
AddActiveDirectoryDnsArg(parser)
AddActiveDirectoryNetBiosArg(parser)
AddActiveDirectoryOrganizationalUnitArg(parser)
AddActiveDirectoryAesEncryptionArg(parser)
AddActiveDirectoryUsernameArg(parser)
AddActiveDirectoryPasswordArg(parser)
AddActiveDirectoryBackupOperatorsArg(parser)
AddActiveDirectorySecurityOperatorsArg(parser)
AddActiveDirectoryAdministratorsArg(parser)
AddActivevDirectoryKdcHostnameArg(parser)
AddActiveDirectoryKdcIpArg(parser)
AddActiveDirectoryNfsUsersWithLdapArg(parser)
AddActiveDirectoryLdapSigningArg(parser)
AddActiveDirectoryEncryptDcConnectionsArg(parser)
def AddActiveDirectoryDeleteArgs(parser):
"""Add args for deleting an Active Directory."""
concept_parsers.ConceptParser([
flags.GetActiveDirectoryPresentationSpec(
'The Active Directory to delete.')
]).AddToParser(parser)
flags.AddResourceAsyncFlag(parser)
def AddActiveDirectoryUpdateArgs(parser):
"""Add args for updating an Active Directory."""
concept_parsers.ConceptParser([
flags.GetActiveDirectoryPresentationSpec(
'The Active Directory to update.')
]).AddToParser(parser)
flags.AddResourceDescriptionArg(parser, 'Active Directory')
flags.AddResourceAsyncFlag(parser)
labels_util.AddUpdateLabelsFlags(parser)
AddActiveDirectoryDomainArg(parser)
AddActiveDirectorySiteArg(parser)
AddActiveDirectoryDnsArg(parser)
AddActiveDirectoryNetBiosArg(parser)
AddActiveDirectoryOrganizationalUnitArg(parser)
AddActiveDirectoryAesEncryptionArg(parser)
AddActiveDirectoryUsernameArg(parser)
AddActiveDirectoryPasswordArg(parser)
AddActiveDirectoryBackupOperatorsArg(parser)
AddActiveDirectorySecurityOperatorsArg(parser)
AddActiveDirectoryAdministratorsArg(parser)
AddActivevDirectoryKdcHostnameArg(parser)
AddActiveDirectoryKdcIpArg(parser)
AddActiveDirectoryNfsUsersWithLdapArg(parser)
AddActiveDirectoryLdapSigningArg(parser)
AddActiveDirectoryEncryptDcConnectionsArg(parser)

View File

@@ -0,0 +1,21 @@
# -*- 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.
"""A helper library for the Cloud NetApp Files Backup Policies sub-command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,148 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Files Backup Policies commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import sys
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.netapp import util as netapp_util
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
BACKUP_POLICIES_LIST_FORMAT = """\
table(
name.basename():label=BACKUP_POLICY_NAME:sort=1,
name.segment(3):label=LOCATION,
enabled,
state
)"""
MIN_DAILY_BACKUP_LIMIT = 2
## Helper functions to add args / flags for Backup Policy gcloud commands ##
def AddBackupPolicyEnabledArg(parser):
"""Adds a --enabled arg to the given parser."""
parser.add_argument(
'--enabled',
type=arg_parsers.ArgBoolean(truthy_strings=netapp_util.truthy,
falsey_strings=netapp_util.falsey),
help="""The Boolean value indiciating whether backups are made automatically according to the schedules.
If enabled, this will be applied to all volumes that have this backup policy attached and enforced on
the volume level. If not specified, the default is true."""
)
def AddBackupPolicyDailyBackupLimitArg(backup_limit_group):
"""Adds a --daily-backup-limit arg to the given parser argument group."""
backup_limit_group.add_argument(
'--daily-backup-limit',
type=arg_parsers.BoundedInt(
lower_bound=MIN_DAILY_BACKUP_LIMIT, upper_bound=sys.maxsize),
help="""
Maximum number of daily backups to keep.
Note that the minimum daily backup limit is 2.
""",
)
def AddBackupPolicyWeeklyBackupLimitArg(backup_limit_group):
"""Adds a --weekly-backup-limit arg to the given parser argument group."""
backup_limit_group.add_argument(
'--weekly-backup-limit',
type=arg_parsers.BoundedInt(lower_bound=0, upper_bound=sys.maxsize),
help="""
Number of weekly backups to keep.
Note that the sum of daily, weekly and monthly backups
should be greater than 1
""",
)
def AddBackupPolicyMonthlyBackupLimitArg(backup_limit_group):
"""Adds a --monthly-backup-limit arg to the given parser argument group."""
backup_limit_group.add_argument(
'--monthly-backup-limit',
type=arg_parsers.BoundedInt(lower_bound=0, upper_bound=sys.maxsize),
help="""
Number of monthly backups to keep.
Note that the sum of daily, weekly and monthly backups
should be greater than 1
""",
)
def AddBackupPolicyBackupLimitGroup(parser):
"""Adds a parser argument group for backup limits.
Flags include:
--daily-backup-limit
--weekly-backup-limit
--monthly-backup-limit
Args:
parser: The argparser.
"""
backup_limit_group = parser.add_group(
help='Add backup limit arguments.'
)
AddBackupPolicyDailyBackupLimitArg(backup_limit_group)
AddBackupPolicyWeeklyBackupLimitArg(backup_limit_group)
AddBackupPolicyMonthlyBackupLimitArg(backup_limit_group)
## Helper functions for Backup Policy surface command
## Helper functions to combine Backup Policy args / flags for gcloud commands ##
def AddBackupPolicyCreateArgs(parser):
"""Add args for creating a Backup Policy."""
concept_parsers.ConceptParser(
[flags.GetBackupPolicyPresentationSpec('The Backup Policy to create')]
).AddToParser(parser)
AddBackupPolicyEnabledArg(parser)
AddBackupPolicyBackupLimitGroup(parser)
flags.AddResourceDescriptionArg(parser, 'Backup Policy')
flags.AddResourceAsyncFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
def AddBackupPolicyDeleteArgs(parser):
"""Add args for deleting a Backup Policy."""
concept_parsers.ConceptParser(
[flags.GetBackupPolicyPresentationSpec('The Backup Policy to delete')]
).AddToParser(parser)
flags.AddResourceAsyncFlag(parser)
def AddBackupPolicyUpdateArgs(parser):
"""Add args for updating a Backup Policy."""
concept_parsers.ConceptParser(
[flags.GetBackupPolicyPresentationSpec('The Backup Policy to update')]
).AddToParser(parser)
AddBackupPolicyEnabledArg(parser)
AddBackupPolicyBackupLimitGroup(parser)
flags.AddResourceDescriptionArg(parser, 'Backup Policy')
flags.AddResourceAsyncFlag(parser)
labels_util.AddUpdateLabelsFlags(parser)

View File

@@ -0,0 +1,21 @@
# -*- 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.
"""A helper library for the Cloud NetApp Files Backup Vaults sub-command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,21 @@
# -*- 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.
"""A helper library for the Cloud NetApp Files Backups sub-command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,116 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Backups commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
BACKUP_VAULTS_LIST_FORMAT = """\
table(
name.basename():label=BACKUP_NAME:sort=1,
name.segment(3):label=LOCATION,
backupVault,
sourceVolume,
sourceSnapshot,
state
)"""
## Helper functions to add backup flags ##
def AddBackupBackupVaultResourceArg(parser, required=True):
group_help = (
'The Backup Vault that the Backup is stored in'
)
concept_parsers.ConceptParser.ForResource(
'--backup-vault',
flags.GetBackupVaultResourceSpec(positional=False),
group_help=group_help,
required=required,
flag_name_overrides={'location': ''},
).AddToParser(parser)
def AddBackupSourceVolumeResourceArg(parser, required=True):
group_help = (
"""The full name of the Source Volume that the Backup is based on',
Format: `projects/{projects_id}/locations/{location}/volumes/{volume_id}`
"""
)
concept_parsers.ConceptParser.ForResource(
'--source-volume',
flags.GetVolumeResourceSpec(positional=False),
group_help=group_help,
required=required,
flag_name_overrides={'location': ''},
).AddToParser(parser)
def AddBackupSourceSnapshotResourceArg(parser):
group_help = (
"""
The full name of the Source Snapshot that the Backup is based on',
Format: `projects/{project_id}/locations/{location}/volumes/{volume_id}/snapshots/{snapshot_id}`
"""
)
concept_parsers.ConceptParser.ForResource(
'--source-snapshot',
flags.GetSnapshotResourceSpec(source_snapshot_op=True, positional=False),
group_help=group_help,
flag_name_overrides={'location': '', 'volume': ''},
).AddToParser(parser)
## Helper functions to combine Backups args / flags for gcloud commands ##
def AddBackupCreateArgs(parser):
"""Add args for creating a Backup."""
concept_parsers.ConceptParser(
[flags.GetBackupPresentationSpec('The Backup to create')]
).AddToParser(parser)
AddBackupBackupVaultResourceArg(parser, required=True)
AddBackupSourceVolumeResourceArg(parser, required=True)
AddBackupSourceSnapshotResourceArg(parser)
flags.AddResourceDescriptionArg(parser, 'Backup Vault')
flags.AddResourceAsyncFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
def AddBackupDeleteArgs(parser):
"""Add args for deleting a Backup Vault."""
concept_parsers.ConceptParser(
[flags.GetBackupPresentationSpec('The Backup to delete')]
).AddToParser(parser)
flags.AddResourceAsyncFlag(parser)
def AddBackupUpdateArgs(parser):
"""Add args for updating a Backup."""
concept_parsers.ConceptParser(
[flags.GetBackupPresentationSpec('The Backup to update')]
).AddToParser(parser)
AddBackupBackupVaultResourceArg(parser, required=True)
flags.AddResourceDescriptionArg(parser, 'Backup')
flags.AddResourceAsyncFlag(parser)
labels_util.AddUpdateLabelsFlags(parser)

View File

@@ -0,0 +1,154 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Backup Vaults commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.util.apis import arg_utils
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.command_lib.util.concepts import presentation_specs
BACKUP_VAULTS_LIST_FORMAT = """\
table(
name.basename():label=BACKUP_VAULT_NAME:sort=1,
name.segment(3):label=LOCATION,
state
)"""
def GetBackupVaultTypeEnumFromArg(choice, messages):
"""Returns the Choice Enum for Backup Vault Type.
Args:
choice: The choice for backup vault type as string
messages: The messages module.
Returns:
the backup vault type enum.
"""
return arg_utils.ChoiceToEnum(
choice=choice,
enum_type=messages.BackupVault.BackupVaultTypeValueValuesEnum,
)
def AddBackupVaultTypeArg(parser):
help_text = """\
String indicating the type of backup vault.
The supported values are: 'IN_REGION','CROSS_REGION'
"""
parser.add_argument(
'--backup-vault-type',
type=str,
help=help_text,
required=False,
)
def AddBackupVaultBackupLocationArg(parser):
"""Adds the Backup Vault Backup Location arg to the arg parser."""
parser.add_argument(
'--backup-region',
type=str,
help="""String indicating backup location for the Backup Vault""",
)
## Helper functions to combine Backup Vaults args / flags for gcloud commands ##
def AddBackupVaultCreateArgs(parser, release_track):
"""Add args for creating a Backup Vault."""
concept_parsers.ConceptParser(
[flags.GetBackupVaultPresentationSpec('The Backup Vault to create')]
).AddToParser(parser)
flags.AddResourceDescriptionArg(parser, 'Backup Vault')
flags.AddResourceAsyncFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
AddBackupRetentionPolicyArg(parser)
AddKmsConfigArg(parser)
if (release_track == base.ReleaseTrack.BETA):
AddBackupVaultTypeArg(parser)
AddBackupVaultBackupLocationArg(parser)
def AddBackupVaultDeleteArgs(parser):
"""Add args for deleting a Backup Vault."""
concept_parsers.ConceptParser(
[flags.GetBackupVaultPresentationSpec('The Backup Vault to delete')]
).AddToParser(parser)
flags.AddResourceAsyncFlag(parser)
def AddBackupVaultUpdateArgs(parser):
"""Add args for updating a Backup Vault."""
concept_parsers.ConceptParser(
[flags.GetBackupVaultPresentationSpec('The Backup Vault to update')]
).AddToParser(parser)
flags.AddResourceDescriptionArg(parser, 'Backup Vault')
flags.AddResourceAsyncFlag(parser)
labels_util.AddUpdateLabelsFlags(parser)
AddBackupRetentionPolicyArg(parser)
def AddBackupRetentionPolicyArg(parser):
"""Adds the Backup Retention Policy arg to the arg parser."""
backup_retention_policy_arg_spec = {
'backup-minimum-enforced-retention-days': int,
'daily-backup-immutable': bool,
'weekly-backup-immutable': bool,
'monthly-backup-immutable': bool,
'manual-backup-immutable': bool
}
backup_retention_policy_help = textwrap.dedent("""\
Backup Retention Policy of the Backup Vault.
Backup Retention Policy allows you to configure the retention policy for
backups created within this vault. It consists of several fields that govern
how long backups are kept and what type of backups are immutable.
""")
parser.add_argument(
'--backup-retention-policy',
type=arg_parsers.ArgDict(spec=backup_retention_policy_arg_spec),
required=False,
help=backup_retention_policy_help,
)
def AddKmsConfigArg(parser, hidden=False):
"""Adds the --kms-config flag to the parser."""
help_text = """\
The resource name of the KMS Config to use for encrypting backups within this backup vault.
Format: projects/{project_id}/locations/{location}/kmsConfigs/{kms_config_id}
"""
kms_config_presentation_spec = presentation_specs.ResourcePresentationSpec(
'--kms-config',
flags.GetKmsConfigResourceSpec(),
help_text,
required=False,
hidden=hidden,
flag_name_overrides={'location': ''},
)
concept_parsers.ConceptParser([kms_config_presentation_spec]).AddToParser(
parser
)

View File

@@ -0,0 +1,547 @@
# -*- 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.
"""Flags and helpers for general Cloud NetApp Files commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.netapp import constants
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope.concepts import concepts
from googlecloudsdk.calliope.concepts import deps
from googlecloudsdk.command_lib.util.concepts import presentation_specs
from googlecloudsdk.core import properties
## Attribute configs ##
def GetLocationAttributeConfig():
"""Return the Location Attribute Config for resources.
Returns:
ResourceParameterAttributeConfig for location.
"""
fallthroughs = [
## if location is not set, use value from
## gcloud config get-value netapp/location or netapp/region
deps.ArgFallthrough('--location'),
deps.PropertyFallthrough(properties.VALUES.netapp.location),
]
return concepts.ResourceParameterAttributeConfig(
name='location',
fallthroughs=fallthroughs,
help_text='The location of the {resource}.')
def GetStoragePoolAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'storage_pool', 'The instance of the {resource}.')
def GetVolumeAttributeConfig(positional=True):
"""Return the Volume Attribute Config for resources.
Args:
positional: boolean value describing whether volume attribute is conditional
Returns:
volume resource parameter attribute config for resource specs
"""
if positional:
fallthroughs = []
else:
## For when we need a volume attribute in Snapshot resource spec, we want
## to assign fallthrough flags
fallthroughs = [deps.ArgFallthrough('--volume')]
help_text = ('The instance of the {resource}' if positional else (
'The volume of the {resource}'))
return concepts.ResourceParameterAttributeConfig(
name='volume', fallthroughs=fallthroughs, help_text=help_text)
def GetSnapshotAttributeConfig(positional=True):
if positional:
help_text = 'The instance of the {resource}'
else:
help_text = 'The snapshot of the {resource}'
return concepts.ResourceParameterAttributeConfig(
'snapshot', help_text=help_text)
def GetReplicationAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'replication', 'The instance of the {resource}')
def GetOperationAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'operation', 'The Cloud NetApp operation.')
def GetActiveDirectoryAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'active_directory', 'The instance of the {resource}.'
)
def GetBackupVaultAttributeConfig(positional=True):
fallthroughs = []
if not positional:
## For when we need a Backup Vault attribute in Backup resource spec
## we want to assign fallthrough flags
fallthroughs = [deps.ArgFallthrough('--backup-vault')]
return concepts.ResourceParameterAttributeConfig(
'backup_vault', 'The Backup Vault of the {resource}.',
fallthroughs=fallthroughs
)
def GetBackupAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'backup', 'The instance of the {resource}.')
def GetBackupPolicyAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'backup_policy', 'The instance of the {resource}.'
)
def GetKmsConfigAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'kms_config', 'The instance of the {resource}')
def GetKeyRingAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'key_ring', 'The instance of the {resource}.'
)
def GetCryptoKeyAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'crypto_key', 'The instance of the {resource}.'
)
def GetQuotaRuleAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'quota_rule', 'The instance of the {resource}.'
)
def GetHostGroupAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
'host_group', 'The instance of the {resource}.'
)
## Resource Specs ##
def GetLocationResourceSpec():
location_attribute_config = GetLocationAttributeConfig()
location_attribute_config.fallthroughs = []
return concepts.ResourceSpec(
constants.LOCATIONS_COLLECTION,
resource_name='location',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=location_attribute_config)
def GetListingLocationResourceSpec():
location_attribute_config = GetLocationAttributeConfig()
location_attribute_config.fallthroughs.insert(
0, deps.Fallthrough(lambda: '-', hint='uses all locations by default.'))
return concepts.ResourceSpec(
constants.LOCATIONS_COLLECTION,
resource_name='location',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=location_attribute_config)
def GetOperationResourceSpec():
return concepts.ResourceSpec(
constants.OPERATIONS_COLLECTION,
resource_name='operation',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=GetLocationAttributeConfig(),
operationsId=GetOperationAttributeConfig())
def GetStoragePoolResourceSpec():
return concepts.ResourceSpec(
constants.STORAGEPOOLS_COLLECTION,
resource_name='storage_pool',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=GetLocationAttributeConfig(),
storagePoolsId=GetStoragePoolAttributeConfig())
def GetVolumeResourceSpec(positional=True):
return concepts.ResourceSpec(
constants.VOLUMES_COLLECTION,
resource_name='volume',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=GetLocationAttributeConfig(),
volumesId=GetVolumeAttributeConfig(positional=positional),
)
def GetSnapshotResourceSpec(source_snapshot_op=False, positional=True):
"""Gets the Resource Spec for Snapshot.
Args:
source_snapshot_op: Boolean on whether operation uses snapshot as source or
not.
positional: Boolean on whether resource is positional arg ornot
Returns:
The Resource Spec for Snapshot
"""
location_attribute_config = GetLocationAttributeConfig()
volume_attribute_config = GetVolumeAttributeConfig(positional=False)
if source_snapshot_op:
# if revert op or backup op (create, update) that is a source snapshot op,
# we don't want volume attribute to have any fallthroughs
# (--volume arg) since volume is positional in revert.
volume_attribute_config.fallthroughs = []
if not positional:
location_attribute_config.fallthroughs = [
deps.PropertyFallthrough(properties.VALUES.netapp.location),
]
return concepts.ResourceSpec(
constants.SNAPSHOTS_COLLECTION,
resource_name='snapshot',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=location_attribute_config,
volumesId=volume_attribute_config,
snapshotsId=GetSnapshotAttributeConfig(positional=positional))
def GetReplicationResourceSpec():
location_attribute_config = GetLocationAttributeConfig()
volume_attribute_config = GetVolumeAttributeConfig(positional=False)
return concepts.ResourceSpec(
constants.REPLICATIONS_COLLECTION,
resource_name='replication',
api_version=constants.BETA_API_VERSION,
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=location_attribute_config,
volumesId=volume_attribute_config,
replicationsId=GetReplicationAttributeConfig())
def GetActiveDirectoryResourceSpec():
return concepts.ResourceSpec(
constants.ACTIVEDIRECTORIES_COLLECTION,
resource_name='active_directory',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=GetLocationAttributeConfig(),
activeDirectoriesId=GetActiveDirectoryAttributeConfig())
def GetKmsConfigResourceSpec():
return concepts.ResourceSpec(
constants.KMSCONFIGS_COLLECTION,
resource_name='kms_config',
api_version=constants.BETA_API_VERSION,
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=GetLocationAttributeConfig(),
kmsConfigsId=GetKmsConfigAttributeConfig())
def GetBackupVaultResourceSpec(positional=True):
return concepts.ResourceSpec(
constants.BACKUPVAULTS_COLLECTION,
resource_name='backup_vault',
api_version=constants.BETA_API_VERSION,
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=GetLocationAttributeConfig(),
backupVaultsId=GetBackupVaultAttributeConfig(positional=positional),
)
def GetBackupResourceSpec(positional=True):
location_attribute_config = GetLocationAttributeConfig()
backup_vault_attribute_config = GetBackupVaultAttributeConfig(
positional=False
)
if not positional:
location_attribute_config.fallthroughs = [
deps.PropertyFallthrough(properties.VALUES.netapp.location),
]
return concepts.ResourceSpec(
constants.BACKUPS_COLLECTION,
resource_name='backup',
api_version=constants.BETA_API_VERSION,
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=location_attribute_config,
backupVaultsId=backup_vault_attribute_config,
backupsId=GetBackupAttributeConfig(),
)
def GetBackupPolicyResourceSpec():
return concepts.ResourceSpec(
constants.BACKUPPOLICIES_COLLECTION,
resource_name='backup_policy',
api_version=constants.BETA_API_VERSION,
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=GetLocationAttributeConfig(),
backupPoliciesId=GetBackupPolicyAttributeConfig())
def GetCryptoKeyResourceSpec():
return concepts.ResourceSpec(
'cloudkms.projects.locations.keyRings.cryptoKeys',
resource_name='crypto_key',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=GetLocationAttributeConfig(),
keyRingsId=GetKeyRingAttributeConfig(),
cryptoKeysId=GetCryptoKeyAttributeConfig()
)
def GetQuotaRuleResourceSpec():
return concepts.ResourceSpec(
constants.QUOTA_RULES_COLLECTION,
resource_name='quota_rule',
api_version=constants.BETA_API_VERSION,
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=GetLocationAttributeConfig(),
volumesId=GetVolumeAttributeConfig(positional=False),
quotaRulesId=GetQuotaRuleAttributeConfig(),
)
def GetHostGroupResourceSpec():
return concepts.ResourceSpec(
constants.HOST_GROUPS_COLLECTION,
resource_name='host_group',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=GetLocationAttributeConfig(),
hostGroupsId=GetHostGroupAttributeConfig(),
)
## Presentation Specs ##
def GetLocationPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'location', GetLocationResourceSpec(), group_help, required=True)
def GetResourceListingLocationPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'--location',
GetListingLocationResourceSpec(),
group_help)
def GetOperationPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'operation', GetOperationResourceSpec(), group_help, required=True)
def GetStoragePoolPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'storage_pool', GetStoragePoolResourceSpec(), group_help, required=True)
def GetVolumePresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'volume', GetVolumeResourceSpec(), group_help, required=True)
def GetSnapshotPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'snapshot',
GetSnapshotResourceSpec(),
group_help,
required=True,
flag_name_overrides={'volume': ''})
def GetReplicationPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'replication',
GetReplicationResourceSpec(),
group_help,
required=True,
flag_name_overrides={'volume': ''})
def GetActiveDirectoryPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'active_directory',
GetActiveDirectoryResourceSpec(),
group_help,
required=True)
def GetKmsConfigPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'kms_config',
GetKmsConfigResourceSpec(),
group_help,
required=True)
def GetBackupVaultPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'backup_vault',
GetBackupVaultResourceSpec(),
group_help,
required=True)
def GetBackupPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'backup',
GetBackupResourceSpec(),
group_help,
required=True,
flag_name_overrides={'backup_vault': ''})
def GetQuotaRulePresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'quota_rule',
GetQuotaRuleResourceSpec(),
group_help,
required=True,
flag_name_overrides={'volume': ''})
def GetHostGroupPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'host_group',
GetHostGroupResourceSpec(),
group_help,
required=True,
)
# TODO(b/290375665): Add more unit tests to test Backup Poicy
# Presentation, resource specs and flags
def GetBackupPolicyPresentationSpec(group_help):
return presentation_specs.ResourcePresentationSpec(
'backup_policy',
GetBackupPolicyResourceSpec(),
group_help,
required=True)
## Add args to arg parser ##
def AddResourceDescriptionArg(parser, resource_name):
"""Add Description arg to arg_parser for a resource called resource_name."""
parser.add_argument(
'--description',
required=False,
help='A description of the Cloud NetApp {}'.format(resource_name))
def AddResourceCapacityArg(parser, resource_name, required=True):
"""Add Capacity arg to arg_parser for a resource called resource_name."""
parser.add_argument(
'--capacity',
type=arg_parsers.BinarySize(
default_unit='GiB', suggested_binary_size_scales=['GiB', 'TiB']),
required=required,
help=('The desired capacity of the {} in GiB or TiB units.'
'If no capacity unit is specified, GiB is assumed.'.format(
resource_name)))
def AddResourceAsyncFlag(parser):
help_text = """Return immediately, without waiting for the operation
in progress to complete."""
concepts.ResourceParameterAttributeConfig(name='async', help_text=help_text)
base.ASYNC_FLAG.AddToParser(parser)
def AddResourcePeerClusterNameArg(parser, required=True):
"""Adds the Peer Cluster Name (--peer-cluster-name) arg to the given parser.
Args:
parser: Argparse parser.
required: Required to establish both cluster and svm peering.
"""
parser.add_argument(
'--peer-cluster-name',
type=str,
required=required,
help="""Name of the destination cluster to be peered
with the source cluster.""",
)
def AddResourcePeerSvmNameArg(parser, required=True):
"""Adds the Peer SVM Name (--peer-svm-name) arg to the given parser.
Args:
parser: Argparse parser.
required: Required to establish both cluster and svm peering.
"""
parser.add_argument(
'--peer-svm-name',
type=str,
required=required,
help="""Name of the local source vserver svm to be peered
with the destination cluster.""",
)
def AddResourcePeerVolumeNameArg(parser, required=True):
"""Adds the Peer Volume Name (--peer-volume-name) arg to the given parser.
Args:
parser: Argparse parser.
required: Required to establish both cluster and svm peering.
"""
parser.add_argument(
'--peer-volume-name',
type=str,
required=required,
help="""Name of the source volume to be peered
with the destination volume.""",
)
def AddResourcePeerIpAddressesArg(parser):
"""Adds the Peer IP Addresses (--peer-ip-addresses) arg to the given parser.
Args:
parser: Argparse parser.
Not required for svm peering.
"""
parser.add_argument(
'--peer-ip-addresses',
type=arg_parsers.ArgList(min_length=1, element_type=str),
metavar='PEER_IP_ADDRESS',
help=(
'List of ip addresses to be used for peering. This is required for'
' cluster peering, not required for svm peering.'
),
)

View File

@@ -0,0 +1,16 @@
# -*- 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.
"""A helper library for the Cloud NetApp Host Groups sub-command group."""

View File

@@ -0,0 +1,126 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Files Host Groups commands."""
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.util.apis import arg_utils
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
## Helper functions to add args / flags for HostGroups gcloud commands ##
def GetHostGroupTypeEnumFromArg(choice, messages):
"""Returns the Choice Enum for Host Group Type.
Args:
choice: The choice for host group type as string
messages: The messages module.
Returns:
the host group type enum.
"""
return arg_utils.ChoiceToEnum(
choice=choice,
enum_type=messages.HostGroup.TypeValueValuesEnum,
)
def GetHostGroupOsTypeEnumFromArg(choice, messages):
"""Returns the Choice Enum for Host Group OS Type.
Args:
choice: The choice for host group os type as string
messages: The messages module.
Returns:
the host group os type enum.
"""
return arg_utils.ChoiceToEnum(
choice=choice,
enum_type=messages.HostGroup.OsTypeValueValuesEnum,
)
def AddHostGroupTypeArg(parser):
help_text = """\
String indicating the type of host group.
The supported values are: 'ISCSI_INITIATOR'
"""
parser.add_argument(
'--type',
type=str,
help=help_text,
required=True,
choices=['ISCSI_INITIATOR'],
)
def AddHostGroupHostsArg(parser, required=False):
help_text = """\
List of hosts in the host group.
"""
parser.add_argument(
'--hosts',
type=arg_parsers.ArgList(min_length=1, element_type=str),
help=help_text,
required=required,
metavar='HOST',
)
def AddHostGroupOsTypeArg(parser):
help_text = """\
String indicating the OS type of the hosts in the host group.
The supported values are: 'LINUX', 'WINDOWS', 'ESXI'
"""
parser.add_argument(
'--os-type',
type=str,
help=help_text,
required=True,
choices=['LINUX', 'WINDOWS', 'ESXI'],
)
## Helper function to combine HostGroups args / flags for gcloud commands ##
def AddHostGroupCreateArgs(parser):
"""Add args for creating a Host Group."""
concept_parsers.ConceptParser([
flags.GetHostGroupPresentationSpec('The Host Group to create.')
]).AddToParser(parser)
AddHostGroupTypeArg(parser)
AddHostGroupHostsArg(parser, required=True)
AddHostGroupOsTypeArg(parser)
flags.AddResourceDescriptionArg(parser, 'Host Group')
flags.AddResourceAsyncFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
def AddHostGroupUpdateArgs(parser):
"""Add args for updating a Host Group."""
concept_parsers.ConceptParser([
flags.GetHostGroupPresentationSpec('The Host Group to update.')
]).AddToParser(parser)
AddHostGroupHostsArg(parser, required=False)
flags.AddResourceDescriptionArg(parser, 'Host Group')
flags.AddResourceAsyncFlag(parser)
labels_util.AddUpdateLabelsFlags(parser)

View File

@@ -0,0 +1,21 @@
# -*- 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.
"""A helper library for the Cloud NetApp Files KMS Configs sub-command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,170 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Files KMS Configs commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope.concepts import concepts
from googlecloudsdk.calliope.concepts import deps
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import properties
KMS_CONFIGS_LIST_FORMAT = """\
table(
name.basename():label=KMS_CONFIG_NAME:sort=1,
name.segment(3):label=LOCATION,
cryptoKeyName,
state
)"""
## Resource Attribute Config for KMS Key ##
def GetKmsKeyAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
name='kms-key', help_text='The KMS key of the {resource}'
)
def GetKmsKeyRingAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
name='kms-keyring', help_text='The KMS keyring of the {resource}'
)
def GetKmsProjectAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
name='kms-project',
help_text='The Cloud project for the {resource}.',
fallthroughs=[deps.PropertyFallthrough(properties.VALUES.core.project)],
)
def GetKmsLocationAttributeConfig():
fallthroughs = [
## if --kms-location is not set, use value from --location or
## gcloud config get-value netapp/location or netapp/region
deps.ArgFallthrough('--location'),
deps.PropertyFallthrough(properties.VALUES.netapp.location),
]
return concepts.ResourceParameterAttributeConfig(
name='kms-location',
help_text='The Cloud location for the {resource}.',
fallthroughs=fallthroughs,
)
def GetKmsKeyResourceSpec():
return concepts.ResourceSpec(
'cloudkms.projects.locations.keyRings.cryptoKeys',
resource_name='kms_key',
projectsId=GetKmsProjectAttributeConfig(),
locationsId=GetKmsLocationAttributeConfig(),
keyRingsId=GetKmsKeyRingAttributeConfig(),
cryptoKeysId=GetKmsKeyAttributeConfig(),
)
## Helper functions to add args / flags for KMS Config gcloud commands ##
def AddKmsKeyResourceArg(parser, required=True):
concept_parsers.ConceptParser.ForResource(
name='--kms-key',
resource_spec=GetKmsKeyResourceSpec(),
group_help=(
'The Cloud KMS (Key Management Service) Crypto Key that will be used'
),
required=required,
).AddToParser(parser)
## Helper functions for KMS Configs surface command
def ConstructCryptoKeyName(kms_project, kms_location, kms_keyring, kms_key):
return 'projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s' % (
kms_project,
kms_location,
kms_keyring,
kms_key,
)
def ExtractKmsProjectFromCryptoKeyName(name):
name_split = name.split('/')
return name_split[1]
def ExtractKmsLocationFromCryptoKeyName(name):
name_split = name.split('/')
return name_split[3]
def ExtractKmsKeyRingFromCryptoKeyName(name):
name_split = name.split('/')
return name_split[5]
def ExtractKmsCryptoKeyFromCryptoKeyName(name):
name_split = name.split('/')
return name_split[7]
## Helper functions to combine KMS Configs args / flags for gcloud commands ##
def AddKMSConfigCreateArgs(parser):
"""Add args for creating a KMS Config."""
concept_parsers.ConceptParser(
[flags.GetKmsConfigPresentationSpec('The KMS Config to create')]
).AddToParser(parser)
AddKmsKeyResourceArg(parser, required=True)
flags.AddResourceDescriptionArg(parser, 'KMS Config')
flags.AddResourceAsyncFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
def AddKMSConfigDeleteArgs(parser):
"""Add args for deleting a KMS Config."""
concept_parsers.ConceptParser(
[flags.GetKmsConfigPresentationSpec('The KMS Config to delete')]
).AddToParser(parser)
flags.AddResourceAsyncFlag(parser)
def AddKMSConfigUpdateArgs(parser):
"""Add args for updating a KMS Config."""
concept_parsers.ConceptParser(
[flags.GetKmsConfigPresentationSpec('The KMS Config to update')]
).AddToParser(parser)
AddKmsKeyResourceArg(parser, required=False)
flags.AddResourceDescriptionArg(parser, 'KMS Config')
flags.AddResourceAsyncFlag(parser)
labels_util.AddUpdateLabelsFlags(parser)
def AddKMSConfigEncryptArgs(parser):
"""Add args for encrypting volumes under a KMS Config."""
concept_parsers.ConceptParser(
[flags.GetKmsConfigPresentationSpec('The KMS Config used to encrypt')]
).AddToParser(parser)
flags.AddResourceAsyncFlag(parser)

View File

@@ -0,0 +1,20 @@
# -*- 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.
"""A helper library for the Cloud NetApp Files locations sub-command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,24 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Files locations commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
LOCATIONS_LIST_FORMAT = """\
table(
name.basename():label=NAME:sort=1
)"""

View File

@@ -0,0 +1,20 @@
# -*- 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.
"""A helper library for the Cloud NetApp Files Operations sub-command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

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.
"""Flags and helpers for the Cloud NetApp Files Operations commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
OPERATIONS_LIST_FORMAT = """\
table(
name.basename():label=OPERATION_NAME,
name.segment(3):label=LOCATION,
metadata.verb:label=TYPE,
metadata.target.basename(),
done.yesno(yes='DONE', no='RUNNING'):label=STATUS,
metadata.createTime.date():sort=1,
duration(start=metadata.createTime,end=metadata.endTime,precision=0,calendar=false).slice(2:).join("").yesno(no="<1S"):label=DURATION
)"""

View File

@@ -0,0 +1,21 @@
# -*- 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.
"""A helper library for the Cloud NetApp Files Storage Pools sub-command group.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,418 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Files Storage Pools commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.netapp import util as netapp_api_util
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope.concepts import concepts
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.netapp import util as netapp_util
from googlecloudsdk.command_lib.util.apis import arg_utils
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
STORAGE_POOLS_LIST_FORMAT = """\
table(
name.basename():label=STORAGE_POOL_NAME:sort=1,
name.segment(3):label=LOCATION,
serviceLevel,
capacityGib,
network,
state,
volumeCapacityGib,
type
)"""
## Helper functions to add args / flags for Storage Pools gcloud commands ##
def GetStoragePoolServiceLevelArg(messages, required=True):
"""Adds a --service-level arg to the given parser.
Args:
messages: The messages module.
required: bool, whether choice arg is required or not
Returns:
the choice arg.
"""
custom_mappings = {
'PREMIUM': (
'premium',
"""
Premium Service Level for Cloud NetApp Storage Pool.
The Premium Service Level has a throughput per GiB of
allocated volume size of 64 KiB/s.""",
),
'EXTREME': (
'extreme',
"""
Extreme Service Level for Cloud NetApp Storage Pool.
The Extreme Service Level has a throughput per GiB of
allocated volume size of 128 KiB/s.""",
),
'STANDARD': (
'standard',
"""
Standard Service Level for Cloud NetApp Storage Pool.
The Standard Service Level has a throughput per GiB of
allocated volume size of 16 KiB/s.""",
),
'FLEX': (
'flex',
"""
Flex Service Level for Cloud NetApp Storage Pool.
The Flex Service Level has a throughput per GiB of
allocated volume size of 16 KiB/s.""",
),
}
service_level_arg = arg_utils.ChoiceEnumMapper(
'--service-level',
messages.StoragePool.ServiceLevelValueValuesEnum,
help_str="""The service level for the Cloud NetApp Storage Pool.
For more details, see:
https://cloud.google.com/netapp/volumes/docs/configure-and-use/storage-pools/overview#service_levels
""",
custom_mappings=custom_mappings,
required=required,
)
return service_level_arg
def GetDirectoryServiceTypeEnumFromArg(choice, messages):
"""Returns the Choice Enum for Directory Service Type.
Args:
choice: The choice for directory service type as string
messages: The messages module.
Returns:
the directory service type enum.
"""
return arg_utils.ChoiceToEnum(
choice=choice,
enum_type=messages.ValidateDirectoryServiceRequest.DirectoryServiceTypeValueValuesEnum,
)
def GetStoragePoolQosTypeArg(messages):
"""Adds the Qos Type arg to the arg parser."""
qos_type_arg = arg_utils.ChoiceEnumMapper(
'--qos-type',
messages.StoragePool.QosTypeValueValuesEnum,
help_str="""Quality of service (QoS) type for the Storage Pool.""",
)
return qos_type_arg
def GetStoragePoolTypeEnumFromArg(choice, messages):
"""Returns the Choice Enum for StoragePoolType."""
return arg_utils.ChoiceToEnum(
choice=choice,
enum_type=messages.StoragePool.TypeValueValuesEnum
)
def AddStoragePoolTypeArg(parser, messages):
"""Adds the --type arg to the arg parser for Storage Pools."""
type_arg = arg_utils.ChoiceEnumMapper(
'--type',
messages.StoragePool.TypeValueValuesEnum,
help_str='The type of the Storage Pool. `FILE` pools support file-based '
'volumes only. `UNIFIED` pools support both file and block '
'volumes.',
custom_mappings={
'FILE': ('file', 'File-based volumes only (default).'),
'UNIFIED': ('unified', 'Both file and block volumes.'),
})
type_arg.choice_arg.AddToParser(parser)
def AddStoragePoolServiceLevelArg(
parser, messages, required=False
):
GetStoragePoolServiceLevelArg(
messages, required=required
).choice_arg.AddToParser(parser)
def AddStoragePoolAsyncFlag(parser):
help_text = """Return immediately, without waiting for the operation
in progress to complete."""
concepts.ResourceParameterAttributeConfig(name='async', help_text=help_text)
base.ASYNC_FLAG.AddToParser(parser)
def AddStoragePoolNetworkArg(parser, required=True):
"""Adds a --network arg to the given parser.
Args:
parser: argparse parser.
required: bool whether arg is required or not
"""
network_arg_spec = {
'name': str,
'psa-range': str,
}
network_help = """\
Network configuration for a Cloud NetApp Files Storage Pool. Specifying
`psa-range` is optional.
*name*::: The name of the Google Compute Engine
[VPC network](/compute/docs/networks-and-firewalls#networks) to which
the volume is connected. Short-form (VPC network ID) or long-form
(full VPC network name: projects/PROJECT/locations/LOCATION/networks/NETWORK) are both
accepted, but please use the long-form when attempting to create a Storage Pool using a shared VPC.
*psa-range*::: This field is not implemented. The values provided in
this field are ignored.
"""
parser.add_argument(
'--network',
type=arg_parsers.ArgDict(spec=network_arg_spec, required_keys=['name']),
required=required,
help=network_help)
def AddStoragePoolActiveDirectoryArg(parser):
"""Adds a --active-directory arg to the given parser."""
concept_parsers.ConceptParser.ForResource(
'--active-directory',
flags.GetActiveDirectoryResourceSpec(),
'The Active Directory to attach to the Storage Pool.',
flag_name_overrides={'location': ''}).AddToParser(parser)
def AddStoragePoolKmsConfigArg(parser):
"""Adds a --kms-config arg to the given parser."""
concept_parsers.ConceptParser.ForResource(
'--kms-config',
flags.GetKmsConfigResourceSpec(),
'The KMS config to attach to the Storage Pool.',
flag_name_overrides={'location': ''}).AddToParser(parser)
def AddStoragePoolEnableLdapArg(parser):
"""Adds the --enable-ladp arg to the given parser."""
parser.add_argument(
'--enable-ldap',
type=arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey),
help="""Boolean flag indicating whether Storage Pool is a NFS LDAP Storage Pool or not"""
)
def AddStoragePoolAllowAutoTieringArg(parser):
"""Adds the --allow-auto-tiering arg to the given parser."""
parser.add_argument(
'--allow-auto-tiering',
type=arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey),
help="""Boolean flag indicating whether Storage Pool is allowed to use auto-tiering""",
)
def AddStoragePoolZoneArg(parser):
"""Adds the Zone arg to the arg parser."""
parser.add_argument(
'--zone',
type=str,
help="""String indicating active zone of the Storage Pool""",
)
def AddStoragePoolReplicaZoneArg(parser):
"""Adds the Replica Zone arg to the arg parser."""
parser.add_argument(
'--replica-zone',
type=str,
help="""String indicating replica zone for the Storage Pool""",
)
def AddStoragePoolDirectoryServiceTypeArg(parser):
"""Adds the Directory Service Type arg to the arg parser."""
parser.add_argument(
'--directory-service-type',
type=str,
help="""String indicating directory service type for the Storage Pool""",
)
def AddStoragePoolCustomPerformanceEnabledArg(parser):
"""Adds the Custom Performance Enabled arg to the arg parser."""
parser.add_argument(
'--custom-performance-enabled',
type=arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
help="""Boolean flag indicating whether Storage Pool is a custom performance Storage Pool or not""",
)
def AddStoragePoolTotalThroughputArg(parser):
"""Adds the Total Throughput arg to the arg parser."""
parser.add_argument(
'--total-throughput',
type=arg_parsers.BinarySize(
default_unit='MiB/s',
suggested_binary_size_scales=['MiB/s', 'GiB/s'],
type_abbr='B/s',
),
help="""The total throughput of the Storage Pool in MiB/s or GiB/s units.
If no throughput unit is specified, MiB/s is assumed.""",
)
def AddStoragePoolTotalIopsArg(parser):
"""Adds the Total IOPS arg to the arg parser."""
parser.add_argument(
'--total-iops',
type=int,
help="""Integer indicating total IOPS of the Storage Pool""",
)
def AddStoragePoolHotTierSizeArg(parser):
"""Adds the Hot Tier Size arg to the arg parser."""
parser.add_argument(
'--hot-tier-size',
type=arg_parsers.BinarySize(
default_unit='GiB',
suggested_binary_size_scales=['GiB'],
type_abbr='B',
),
help="""The hot tier size of the Storage Pool in GiB units.
This is a required field when --allow-auto-tiering is set for flex service level.""",
)
def AddStoragePoolEnableHotTierAutoResizeArg(parser):
"""Adds the Enable Hot Tier Auto Resize arg to the arg parser."""
parser.add_argument(
'--enable-hot-tier-auto-resize',
type=arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
help="""Boolean flag indicating whether Storage Pool is allowed to use hot tier auto resize""",
)
def AddStoragePoolUnifiedPoolArg(parser):
"""Adds the Unified Pool arg to the parser."""
parser.add_argument(
'--unified-pool',
type=arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
help="""Boolean flag indicating whether Storage Pool is a unified pool that supports BLOCK storage. Defaults to False if not specified.""",
hidden=True,
)
def AddStoragePoolQosTypeArg(parser, messages):
GetStoragePoolQosTypeArg(
messages
).choice_arg.AddToParser(parser)
## Helper functions to combine Storage Pools args / flags for gcloud commands ##
def AddStoragePoolCreateArgs(parser, release_track):
"""Add args for creating a Storage Pool."""
concept_parsers.ConceptParser([
flags.GetStoragePoolPresentationSpec('The Storage Pool to create.')
]).AddToParser(parser)
flags.AddResourceDescriptionArg(parser, 'Storage Pool')
flags.AddResourceCapacityArg(parser, 'Storage Pool')
flags.AddResourceAsyncFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
messages = netapp_api_util.GetMessagesModule(release_track=release_track)
AddStoragePoolServiceLevelArg(
parser, messages=messages, required=True
)
AddStoragePoolNetworkArg(parser)
AddStoragePoolActiveDirectoryArg(parser)
AddStoragePoolKmsConfigArg(parser)
AddStoragePoolEnableLdapArg(parser)
AddStoragePoolZoneArg(parser)
AddStoragePoolReplicaZoneArg(parser)
AddStoragePoolAllowAutoTieringArg(parser)
AddStoragePoolCustomPerformanceEnabledArg(parser)
AddStoragePoolTotalThroughputArg(parser)
AddStoragePoolTotalIopsArg(parser)
AddStoragePoolTypeArg(parser, messages)
AddStoragePoolQosTypeArg(parser, messages)
if (release_track == base.ReleaseTrack.ALPHA or
release_track == base.ReleaseTrack.BETA):
AddStoragePoolHotTierSizeArg(parser)
AddStoragePoolEnableHotTierAutoResizeArg(parser)
AddStoragePoolUnifiedPoolArg(parser)
def AddStoragePoolDeleteArgs(parser):
"""Add args for deleting a Storage Pool."""
concept_parsers.ConceptParser([
flags.GetStoragePoolPresentationSpec('The Storage Pool to delete.')
]).AddToParser(parser)
flags.AddResourceAsyncFlag(parser)
def AddStoragePoolUpdateArgs(parser, release_track):
"""Add args for updating a Storage Pool."""
messages = netapp_api_util.GetMessagesModule(release_track=release_track)
concept_parsers.ConceptParser([
flags.GetStoragePoolPresentationSpec('The Storage Pool to update.')
]).AddToParser(parser)
flags.AddResourceDescriptionArg(parser, 'Storage Pool')
flags.AddResourceAsyncFlag(parser)
flags.AddResourceCapacityArg(parser, 'Storage Pool', required=False)
labels_util.AddUpdateLabelsFlags(parser)
AddStoragePoolActiveDirectoryArg(parser)
AddStoragePoolZoneArg(parser)
AddStoragePoolReplicaZoneArg(parser)
AddStoragePoolAllowAutoTieringArg(parser)
AddStoragePoolTotalThroughputArg(parser)
AddStoragePoolQosTypeArg(parser, messages)
AddStoragePoolTotalIopsArg(parser)
if (release_track == base.ReleaseTrack.ALPHA or
release_track == base.ReleaseTrack.BETA):
AddStoragePoolHotTierSizeArg(parser)
AddStoragePoolEnableHotTierAutoResizeArg(parser)
def AddStoragePoolSwitchArg(parser):
"""Add args for switching zones of a Storage Pool."""
concept_parsers.ConceptParser([
flags.GetStoragePoolPresentationSpec('The Storage Pool to switch.')
]).AddToParser(parser)
flags.AddResourceAsyncFlag(parser)
def AddStoragePoolValidateDirectoryServiceArg(parser):
"""Add args for validating directory service of a Storage Pool."""
concept_parsers.ConceptParser([
flags.GetStoragePoolPresentationSpec('The Storage Pool to validate.')
]).AddToParser(parser)
flags.AddResourceAsyncFlag(parser)
AddStoragePoolDirectoryServiceTypeArg(parser)

View File

@@ -0,0 +1,34 @@
# -*- 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.
"""Flags and helpers for general Cloud NetApp Files commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.core import exceptions
truthy = ['true', 'True', 'TRUE', 'on', 'ON', 'yes', 'YES']
falsey = ['false', 'False', 'FALSE', 'off', 'OFF', 'no', 'NO']
class Error(exceptions.Error):
"""Base class for exceptions in this module."""
class InvalidArgumentError(Error):
"""Raised when command line argument constraints are violated."""

View File

@@ -0,0 +1,21 @@
# -*- 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.
"""A helper library for the Cloud NetApp Files Volumes sub-command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,854 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Files Volumes commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import argparse
import textwrap
from typing import Any
from googlecloudsdk.api_lib.netapp import util as netapp_api_util
from googlecloudsdk.calliope import actions
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base as calliope_base
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.netapp import util as netapp_util
from googlecloudsdk.command_lib.util.apis import arg_utils
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
VOLUMES_LIST_FORMAT = """\
table(
name.basename():label=VOLUME_NAME:sort=1,
name.segment(3):label=LOCATION,
storagePool,
capacityGib:label=CAPACITY_GB,
serviceLevel,
shareName,
state
)"""
## Helper functions to add args / flags for Volumes gcloud commands ##
def AddVolumeAssociatedStoragePoolArg(parser, required=True):
concept_parsers.ConceptParser.ForResource(
'--storage-pool',
flags.GetStoragePoolResourceSpec(),
'The Storage Pool to associate with Volume.',
required=required,
flag_name_overrides={'location': ''},
).AddToParser(parser)
def AddVolumeNetworkArg(parser, required=True):
"""Adds a --network arg to the given parser.
Args:
parser: argparse parser.
required: bool whether arg is required or not
"""
network_arg_spec = {
'name': str,
'psa-range': str,
}
network_help = textwrap.dedent("""\
Network configuration for a Cloud NetApp Files Volume. Specifying
`psa-range` is optional.
*name*::: The name of the Google Compute Engine
[VPC network](/compute/docs/networks-and-firewalls#networks) to which
the volume is connected.
*psa-range*::: This field is not implemented. The values provided in
this field are ignored.
""")
parser.add_argument(
'--network',
type=arg_parsers.ArgDict(spec=network_arg_spec, required_keys=['name']),
required=required,
help=network_help,
)
def GetVolumeProtocolEnumFromArg(choice, messages):
"""Returns the Choice Enum for Protocols.
Args:
choice: The choice for protocol input as string
messages: The messages module.
Returns:
the protocol enum
"""
return arg_utils.ChoiceToEnum(
choice=choice, enum_type=messages.Volume.ProtocolsValueListEntryValuesEnum
)
def AddVolumeProtocolsArg(parser, required=True):
"""Adds the Protocols arg to the arg parser."""
parser.add_argument(
'--protocols',
type=arg_parsers.ArgList(min_length=1, element_type=str),
required=required,
metavar='PROTOCOL',
help="""Type of File System protocols for the Cloud NetApp Files Volume. \
Valid component values are:
`NFSV3`, `NFSV4`, `SMB`.""",
)
def AddVolumeShareNameArg(parser, required=False):
"""Adds the Share name arg to the arg parser."""
parser.add_argument(
'--share-name',
type=str,
required=required,
help="""Share name of the Mount path clients will use.""",
)
def AddVolumeExportPolicyArg(parser: argparse.ArgumentParser, messages: Any):
"""Adds the Export Policy (--export-policy) arg to the given parser.
Args:
parser: argparse parser.
messages: The messages module.
"""
export_policy_arg_spec = {
'allowed-clients': str,
'has-root-access': str,
'access-type': str,
'kerberos-5-read-only': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
'kerberos-5-read-write': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
'kerberos-5i-read-only': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
'kerberos-5i-read-write': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
'kerberos-5p-read-write': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
'kerberos-5p-read-only': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
'nfsv3': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
'nfsv4': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
'squash-mode': messages.SimpleExportPolicyRule.SquashModeValueValuesEnum,
'anon-uid': int,
}
export_policy_help = textwrap.dedent("""\
Export Policy of a Cloud NetApp Files Volume.
This will be a field similar to network
in which export policy fields can be specified as such:
`--export-policy=allowed-clients=ALLOWED_CLIENTS_IP_ADDRESSES,
has-root-access=HAS_ROOT_ACCESS_BOOL,access=ACCESS_TYPE,nfsv3=NFSV3,
nfsv4=NFSV4,kerberos-5-read-only=KERBEROS_5_READ_ONLY,
kerberos-5-read-write=KERBEROS_5_READ_WRITE,
kerberos-5i-read-only=KERBEROS_5I_READ_ONLY,
kerberos-5i-read-write=KERBEROS_5I_READ_WRITE,
kerberos-5p-read-only=KERBEROS_5P_READ_ONLY,
kerberos-5p-read-write=KERBEROS_5P_READ_WRITE,
squash-mode=SQUASH_MODE,anon-uid=ANON_UID`
""")
parser.add_argument(
'--export-policy',
type=arg_parsers.ArgDict(spec=export_policy_arg_spec),
action='append',
help=export_policy_help,
)
def AddVolumeUnixPermissionsArg(parser):
"""Adds the Unix Permissions arg to the arg parser."""
parser.add_argument(
'--unix-permissions',
type=str,
help="""Unix permissions the mount point will be created with. \
Unix permissions are only applicable with NFS protocol only""",
)
def GetVolumeSmbSettingsEnumFromArg(choice, messages):
"""Returns the Choice Enum for SMB Setting.
Args:
choice: The choice for SMB setting input as string
messages: The messages module.
Returns:
The choice arg.
"""
return arg_utils.ChoiceToEnum(
choice=choice,
enum_type=messages.Volume.SmbSettingsValueListEntryValuesEnum,
)
def AddVolumeSmbSettingsArg(parser):
"""Adds the --smb-settings arg to the arg parser."""
parser.add_argument(
'--smb-settings',
type=arg_parsers.ArgList(min_length=1, element_type=str),
metavar='SMB_SETTING',
help="""List of settings specific to SMB protocol \
for a Cloud NetApp Files Volume. \
Valid component values are:
`ENCRYPT_DATA`, `BROWSABLE`, `CHANGE_NOTIFY`, `NON_BROWSABLE`,
`OPLOCKS`, `SHOW_SNAPSHOT`, `SHOW_PREVIOUS_VERSIONS`,
`ACCESS_BASED_ENUMERATION`, `CONTINUOUSLY_AVAILABLE`.""",
)
def AddVolumeHourlySnapshotArg(parser):
"""Adds the --snapshot-hourly arg to the arg parser."""
hourly_snapshot_arg_spec = {
'snapshots-to-keep': float,
'minute': float,
}
hourly_snapshot_help = """
Make a snapshot every hour e.g. at 04:00, 05:20, 06:00
"""
parser.add_argument(
'--snapshot-hourly',
type=arg_parsers.ArgDict(spec=hourly_snapshot_arg_spec),
help=hourly_snapshot_help,
)
def AddVolumeDailySnapshotArg(parser):
"""Adds the --snapshot-daily arg to the arg parser."""
daily_snapshot_arg_spec = {
'snapshots-to-keep': float,
'minute': float,
'hour': float,
}
daily_snapshot_help = """
Make a snapshot every day e.g. at 06:00, 05:20, 23:50
"""
parser.add_argument(
'--snapshot-daily',
type=arg_parsers.ArgDict(spec=daily_snapshot_arg_spec),
help=daily_snapshot_help,
)
def AddVolumeWeeklySnapshotArg(parser):
"""Adds the --snapshot-weekly arg to the arg parser."""
weekly_snapshot_arg_spec = {
'snapshots-to-keep': float,
'minute': float,
'hour': float,
'day': str,
}
weekly_snapshot_help = """
Make a snapshot every week e.g. at Monday 04:00, Wednesday 05:20,
Sunday 23:50
"""
parser.add_argument(
'--snapshot-weekly',
type=arg_parsers.ArgDict(spec=weekly_snapshot_arg_spec),
help=weekly_snapshot_help,
)
def AddVolumeMonthlySnapshotArg(parser):
"""Addss the --snapshot-monthly arg to the arg parser."""
monthly_snapshot_arg_spec = {
'snapshots-to-keep': float,
'minute': float,
'hour': float,
'day': str,
}
monthly_snapshot_help = """
Make a snapshot once a month e.g. at 2nd 04:00, 7th 05:20, 24th 23:50
"""
parser.add_argument(
'--snapshot-monthly',
type=arg_parsers.ArgDict(spec=monthly_snapshot_arg_spec),
help=monthly_snapshot_help,
)
def AddVolumeSnapReserveArg(parser):
"""Adds the --snap-reserve arg to the arg parser."""
action = actions.DeprecationAction(
'snap-reserve', warn='The {flag_name} option is deprecated', removed=False
)
parser.add_argument(
'--snap-reserve',
type=float,
help="""The percentage of volume storage reserved for snapshot storage.
The default value for this is 0 percent""",
action=action,
)
def AddVolumeSnapshotDirectoryArg(parser):
"""Adds the --snapshot-directory arg to the arg parser."""
parser.add_argument(
'--snapshot-directory',
type=arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
default='true',
help="""Snapshot Directory if enabled (true) makes the Volume
contain a read-only .snapshot directory which provides access
to each of the volume's snapshots
""",
)
def GetVolumeSecurityStyleEnumFromArg(choice, messages):
"""Returns the Choice Enum for Security style.
Args:
choice: The choice for Security style input as string
messages: The messages module.
Returns:
The choice arg.
"""
return arg_utils.ChoiceToEnum(
choice=choice, enum_type=messages.Volume.SecurityStyleValueValuesEnum
)
def AddVolumeSecurityStyleArg(parser, messages):
"""Adds the --security-style arg to the arg parser."""
security_style_arg = arg_utils.ChoiceEnumMapper(
'--security-style',
messages.Volume.SecurityStyleValueValuesEnum,
help_str="""The security style of the Volume. This can either be
UNIX or NTFS.
""",
custom_mappings={
'UNIX': ('unix', """UNIX security style for Volume"""),
'NTFS': ('ntfs', """NTFS security style for Volume."""),
},
default='SECURITY_STYLE_UNSPECIFIED',
)
security_style_arg.choice_arg.AddToParser(parser)
def AddVolumeEnableKerberosArg(parser):
"""Adds the --enable-kerberos arg to the arg parser."""
parser.add_argument(
'--enable-kerberos',
type=arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
help="""Boolean flag indicating whether Volume is a kerberos Volume or not""",
)
def AddVolumeEnableLdapArg(parser):
"""Adds the --enable-ladp arg to the arg parser."""
parser.add_argument(
'--enable-ldap',
type=arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
help="""Boolean flag indicating whether Volume is a NFS LDAP Volume or not""",
)
def AddVolumeForceArg(parser):
"""Adds the --force arg to the arg parser."""
parser.add_argument(
'--force',
action='store_true',
help="""Forces the deletion of a volume and its child resources, such as snapshots.""",
)
def AddVolumeRevertSnapshotArg(parser, required=True):
"""Adds the --snapshot arg to the arg parser."""
concept_parsers.ConceptParser.ForResource(
'--snapshot',
flags.GetSnapshotResourceSpec(source_snapshot_op=True, positional=False),
required=required,
flag_name_overrides={'location': '', 'volume': ''},
group_help='The Snapshot to revert the Volume back to.',
).AddToParser(parser)
def AddVolumeSourceSnapshotArg(parser):
"""Adds the --source-snapshot arg to the arg parser."""
concept_parsers.ConceptParser.ForResource(
'--source-snapshot',
flags.GetSnapshotResourceSpec(source_snapshot_op=True, positional=False),
flag_name_overrides={'location': '', 'volume': ''},
group_help='The source Snapshot to create the Volume from.',
).AddToParser(parser)
def AddVolumeSourceBackupArg(parser):
"""Adds the --source-backup arg to the arg parser."""
concept_parsers.ConceptParser.ForResource(
'--source-backup',
flags.GetBackupResourceSpec(positional=False),
flag_name_overrides={'location': ''},
group_help='The source Backup to create the Volume from.',
).AddToParser(parser)
def GetVolumeRestrictedActionsEnumFromArg(choice, messages):
"""Returns the Choice Enum for Restricted Actions.
Args:
choice: The choice for restricted actions input as string.
messages: The messages module.
Returns:
the Restricted Actions enum.
"""
return arg_utils.ChoiceToEnum(
choice=choice,
enum_type=messages.Volume.RestrictedActionsValueListEntryValuesEnum,
)
def AddVolumeRestrictedActionsArg(parser):
"""Adds the --restricted-actions arg to the arg parser."""
parser.add_argument(
'--restricted-actions',
type=arg_parsers.ArgList(min_length=1, element_type=str),
metavar='RESTRICTED_ACTION',
help="""Actions to be restricted for a volume. \
Valid restricted action options are:
'DELETE'.""",
)
def GetOsTypeEnumFromArg(choice, messages):
"""Returns the Choice Enum for OS Type.
Args:
choice: The choice for OS Type input as string.
messages: The messages module.
Returns:
the OS Type enum.
"""
return arg_utils.ChoiceToEnum(
choice=choice,
enum_type=messages.BlockDevice.OsTypeValueValuesEnum
)
def AddVolumeBackupConfigArg(parser):
"""Adds the --backup-config arg to the arg parser."""
backup_config_arg_spec = {
'backup-policies': arg_parsers.ArgList(
min_length=1, element_type=str, custom_delim_char='#'
),
'backup-vault': str,
'enable-scheduled-backups': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
}
backup_config_help = textwrap.dedent("""\
Backup Config contains backup related config on a volume.
Backup Config will have the following format
`--backup-config=backup-policies=BACKUP_POLICIES,
backup-vault=BACKUP_VAULT_NAME,
enable-scheduled-backups=ENABLE_SCHEDULED_BACKUPS
backup-policies is a pound-separated (#) list of backup policy names, backup-vault can include
a single backup-vault resource name, and enable-scheduled-backups is a Boolean value indicating
whether or not scheduled backups are enabled on the volume.
""")
parser.add_argument(
'--backup-config',
type=arg_parsers.ArgDict(spec=backup_config_arg_spec),
help=backup_config_help,
)
def AddVolumeLargeCapacityArg(parser):
"""Adds the --large-capacity arg to the arg parser."""
parser.add_argument(
'--large-capacity',
type=arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
help="""Boolean flag indicating whether Volume is a large capacity Volume or not""",
)
def AddVolumeMultipleEndpointsArg(parser):
"""Adds the --multiple-endpoints arg to the arg parser."""
parser.add_argument(
'--multiple-endpoints',
type=arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
help="""Boolean flag indicating whether Volume is a multiple endpoints Volume or not""",
)
def AddVolumeBlockDevicesArg(parser, messages):
"""Adds the --block-devices arg to the arg parser."""
block_device_arg_spec = {
'name': str,
'host-groups': arg_parsers.ArgList(
min_length=1, element_type=str, custom_delim_char='#'),
'os-type': messages.BlockDevice.OsTypeValueValuesEnum,
'size-gib': int,
}
block_devices_help = textwrap.dedent("""\
A block device to be created with the volume.
This flag can be repeated to specify multiple block devices.
The following keys are available:
*name*::: A user-defined name for the block device.
*host-groups*::: A comma-separated list of host groups that can mount the block volume.
*os-type*::: The OS type of the volume. Allowed values are `OS_TYPE_UNSPECIFIED`, `LINUX`, `WINDOWS`.
*size-gib*::: The size of the block device in GiB. Note that this value is ignored during volume creation and is system-managed.
""")
parser.add_argument(
'--block-devices',
type=arg_parsers.ArgDict(
spec=block_device_arg_spec),
action='append',
help=block_devices_help,
)
def AddVolumeTieringPolicyArg(parser, messages, release_track):
"""Adds the --tiering-policy arg to the arg parser."""
if (release_track == calliope_base.ReleaseTrack.BETA or
release_track == calliope_base.ReleaseTrack.ALPHA):
tiering_policy_arg_spec = {
'tier-action': messages.TieringPolicy.TierActionValueValuesEnum,
'cooling-threshold-days': int,
'enable-hot-tier-bypass-mode': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy,
falsey_strings=netapp_util.falsey,
),
}
else:
tiering_policy_arg_spec = {
'tier-action': messages.TieringPolicy.TierActionValueValuesEnum,
'cooling-threshold-days': int,
}
tiering_policy_help = textwrap.dedent("""\
Tiering Policy contains auto tiering policy on a volume.
Tiering Policy will have the following format
--tiering-policy=tier-action=TIER_ACTION,
cooling-threshold-days=COOLING_THRESHOLD_DAYS
tier-action is an enum, supported values are ENABLED or PAUSED,
cooling-threshold-days is an integer represents time in days to mark the
volume's data block as cold and make it eligible for tiering,
can be range from 7-183. Default is 31.
""")
parser.add_argument(
'--tiering-policy',
type=arg_parsers.ArgDict(spec=tiering_policy_arg_spec),
metavar='tier-action=ENABLED|PAUSED',
help=tiering_policy_help,
)
def AddVolumeHybridReplicationParametersArg(
parser, messages, release_track=calliope_base.ReleaseTrack.GA, hidden=False
):
"""Adds the --hybrid-replication-parameters arg to the arg parser."""
del release_track
hybrid_replication_parameters_arg_spec = {
'replication': str,
'peer-volume-name': str,
'peer-cluster-name': str,
'peer-svm-name': str,
'peer-ip-addresses': arg_parsers.ArgList(
min_length=1, element_type=str, custom_delim_char='#'
),
'cluster-location': str,
'description': str,
'replication-schedule': (
messages.HybridReplicationParameters.ReplicationScheduleValueValuesEnum
),
'hybrid-replication-type': (
messages.HybridReplicationParameters.HybridReplicationTypeValueValuesEnum
),
'large-volume-constituent-count': int,
'labels': arg_parsers.ArgList(
min_length=1, element_type=str, custom_delim_char='#'
),
}
hybrid_replication_parameters_help = textwrap.dedent("""\
Hybrid Replication Parameters contains hybrid replication parameters on a volume.
Hybrid Replication Parameters will have the following format
--hybrid-replication-parameters=replication=REPLICATION,
peer-volume-name=PEER_VOLUME_NAME,
peer-cluster-name=PEER_CLUSTER_NAME,
peer-svm-name=PEER_SVM_NAME,
peer-ip-addresses=[PEER-IP-ADDRESS1#PEER-IP-ADDRESS2#...],
cluster-location=CLUSTER_LOCATION,
description=DESCRIPTION,
replication-schedule=REPLICATION_SCHEDULE,
hybrid-replication-type=HYBRID_REPLICATION_TYPE,
large-volume-constituent-count=LARGE_VOLUME_CONSTITUENT_COUNT,
labels=[KEY1:VALUE1#KEY2:VALUE2#...],
replication is the desired name for the replication of the volume,
peer-volume-name is the name of the user's local source volume,
peer-cluster-name is the name of the user's local source cluster,
peer-svm-name is the name of the user's local source vserver svm,
peer-ip-addresses is a ampersand-separated(#) list of ip addresses,
cluster-location is the name of the source cluster location,
description is the description of the replication,
replication-schedule is the schedule of corresponding hybrid replication
created, hybrid-replication-type is the hybrid replication type of the
corresponding hybrid replication created, large-volume-constituent-count
is the number of constituent volumes in the large volume, and labels is an
hashtag-separated(#) key value pair of labels with key and value separated
by colon(:) for the replication.
""")
parser.add_argument(
'--hybrid-replication-parameters',
type=arg_parsers.ArgDict(spec=hybrid_replication_parameters_arg_spec),
help=hybrid_replication_parameters_help,
hidden=hidden,
)
def AddVolumeThroughputMibpsArg(parser):
"""Adds the --throughput-mibps arg to the arg parser."""
parser.add_argument(
'--throughput-mibps',
type=float,
help='The desired throughput of the volume in MiB/s.',
)
def AddVolumeCacheParametersArg(parser, hidden=False):
"""Adds the --cache-parameters arg to the arg parser."""
cache_parameters_arg_spec = {
'peer-volume-name': str,
'peer-cluster-name': str,
'peer-svm-name': str,
'peer-ip-addresses': arg_parsers.ArgList(
min_length=1, element_type=str, custom_delim_char='#'
),
'enable-global-file-lock': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
'cache-config': arg_parsers.ArgList(
element_type=arg_parsers.ArgDict(), custom_delim_char='#'
),
}
cache_parameters_help = textwrap.dedent("""\
Cache Parameters contains cache parameters of a volume.
Cache Parameters will have the following format
`--cache-parameters=peer-volume-name=PEER_VOLUME_NAME,
peer-cluster-name=PEER_CLUSTER_NAME,
peer-svm-name=PEER_SVM_NAME,
peer-ip-addresses=[PEER-IP-ADDRESS1#PEER-IP-ADDRESS2#...],
enable-global-file-lock=ENABLE_GLOBAL_FILE_LOCK,
cache-config=CACHE_CONFIG`
*peer-volume-name*::: Name of the user's local source volume
*peer-cluster-name*::: Name of the user's local source cluster
*peer-svm-name*::: Name of the user's local source vserver svm
*peer-ip-addresses*::: Hashtag-separated(#) list of IP addresses
*enable-global-file-lock*::: If true, enable global file lock
*cache-config*::: Cache-config as a hashtag-separated(#) list of key-value pairs
""")
parser.add_argument(
'--cache-parameters',
type=arg_parsers.ArgDict(spec=cache_parameters_arg_spec),
help=cache_parameters_help,
hidden=hidden,
)
def AddVolumeCachePrePopulateArg(parser, hidden=False):
"""Adds the --cache-pre-populate arg to the arg parser."""
cache_pre_populate_arg_spec = {
'path-list': arg_parsers.ArgList(
min_length=1, element_type=str, custom_delim_char='#'
),
'exclude-path-list': arg_parsers.ArgList(
min_length=1, element_type=str, custom_delim_char='#'
),
'recursion': arg_parsers.ArgBoolean(
truthy_strings=netapp_util.truthy, falsey_strings=netapp_util.falsey
),
}
cache_pre_populate_help = textwrap.dedent("""\
Cache Pre-populate contains cache pre-populate parameters of a volume.
Cache Pre-populate will have the following format
`--cache-pre-populate=path-list=PATH_LIST1#PATH_LIST2,
exclude-path-list=EXCLUDE_PATH_LIST1#EXCLUDE_PATH_LIST2,
recursion=RECURSION`
*path-list*::: Hashtag-separated(#) list of paths to be pre-populated
*exclude-path-list*::: Hashtag-separated(#) list of paths to be excluded from pre-population
*recursion*::: Boolean value indicating pre-populate recursion.
""")
parser.add_argument(
'--cache-pre-populate',
type=arg_parsers.ArgDict(spec=cache_pre_populate_arg_spec),
help=cache_pre_populate_help,
hidden=hidden,
)
def AddVolumeRestoreFileListArg(parser, required=True):
"""Adds the --file-list arg to the arg parser."""
parser.add_argument(
'--file-list',
type=arg_parsers.ArgList(min_length=1, element_type=str),
metavar='FILE_LIST',
required=required,
help="""List of files to be restored in the form of their absolute path as in source volume.""",
)
def AddVolumeRestoreDestinationPathArg(parser, required=False):
"""Adds the --restore-destination-path arg to the arg parser."""
parser.add_argument(
'--restore-destination-path',
type=str,
required=required,
help="""Name of the absolute directory path in the destination volume..""",
)
## Helper functions to combine Volumes args / flags for gcloud commands #
def AddVolumeCreateArgs(parser, release_track):
"""Add args for creating a Volume."""
concept_parsers.ConceptParser(
[flags.GetVolumePresentationSpec('The Volume to create.')]
).AddToParser(parser)
messages = netapp_api_util.GetMessagesModule(release_track=release_track)
flags.AddResourceDescriptionArg(parser, 'Volume')
flags.AddResourceCapacityArg(parser, 'Volume')
AddVolumeAssociatedStoragePoolArg(parser)
flags.AddResourceAsyncFlag(parser)
AddVolumeProtocolsArg(parser)
AddVolumeShareNameArg(parser)
AddVolumeExportPolicyArg(parser, messages)
AddVolumeUnixPermissionsArg(parser)
AddVolumeSmbSettingsArg(parser)
AddVolumeSourceSnapshotArg(parser)
AddVolumeHourlySnapshotArg(parser)
AddVolumeDailySnapshotArg(parser)
AddVolumeWeeklySnapshotArg(parser)
AddVolumeMonthlySnapshotArg(parser)
AddVolumeSnapReserveArg(parser)
AddVolumeSnapshotDirectoryArg(parser)
AddVolumeSecurityStyleArg(parser, messages)
AddVolumeEnableKerberosArg(parser)
AddVolumeRestrictedActionsArg(parser)
AddVolumeLargeCapacityArg(parser)
AddVolumeMultipleEndpointsArg(parser)
if release_track in [
calliope_base.ReleaseTrack.BETA, calliope_base.ReleaseTrack.GA,
]:
AddVolumeBackupConfigArg(parser)
AddVolumeSourceBackupArg(parser)
AddVolumeThroughputMibpsArg(parser)
AddVolumeTieringPolicyArg(parser, messages, release_track)
AddVolumeHybridReplicationParametersArg(parser, messages, release_track)
AddVolumeCacheParametersArg(parser)
AddVolumeCachePrePopulateArg(parser)
AddVolumeBlockDevicesArg(parser, messages)
labels_util.AddCreateLabelsFlags(parser)
def AddVolumeDeleteArgs(parser):
"""Add args for deleting a Volume."""
concept_parsers.ConceptParser(
[flags.GetVolumePresentationSpec('The Volume to delete.')]
).AddToParser(parser)
flags.AddResourceAsyncFlag(parser)
AddVolumeForceArg(parser)
def AddVolumeUpdateArgs(parser, release_track):
"""Add args for updating a Volume."""
concept_parsers.ConceptParser(
[flags.GetVolumePresentationSpec('The Volume to update.')]
).AddToParser(parser)
messages = netapp_api_util.GetMessagesModule(release_track=release_track)
flags.AddResourceDescriptionArg(parser, 'Volume')
flags.AddResourceCapacityArg(parser, 'Volume', required=False)
AddVolumeAssociatedStoragePoolArg(parser, required=False)
flags.AddResourceAsyncFlag(parser)
AddVolumeProtocolsArg(parser, required=False)
AddVolumeShareNameArg(parser, required=False)
AddVolumeExportPolicyArg(parser, messages)
AddVolumeUnixPermissionsArg(parser)
AddVolumeSmbSettingsArg(parser)
AddVolumeSourceSnapshotArg(parser)
AddVolumeHourlySnapshotArg(parser)
AddVolumeDailySnapshotArg(parser)
AddVolumeWeeklySnapshotArg(parser)
AddVolumeMonthlySnapshotArg(parser)
AddVolumeSnapReserveArg(parser)
AddVolumeSnapshotDirectoryArg(parser)
AddVolumeSecurityStyleArg(parser, messages)
AddVolumeEnableKerberosArg(parser)
AddVolumeRestrictedActionsArg(parser)
if release_track in [
calliope_base.ReleaseTrack.BETA, calliope_base.ReleaseTrack.GA,
]:
AddVolumeBackupConfigArg(parser)
AddVolumeSourceBackupArg(parser)
AddVolumeThroughputMibpsArg(parser)
AddVolumeTieringPolicyArg(parser, messages, release_track)
AddVolumeCacheParametersArg(parser)
AddVolumeCachePrePopulateArg(parser)
AddVolumeBlockDevicesArg(parser, messages)
labels_util.AddUpdateLabelsFlags(parser)
def AddVolumeRestoreFromBackupArg(parser, required=True):
"""Adds the --backup arg to the arg parser."""
concept_parsers.ConceptParser.ForResource(
'--backup',
flags.GetBackupResourceSpec(positional=False),
required=required,
flag_name_overrides={'location': ''},
group_help='The Backup from which files are restored back to the Volume.',
).AddToParser(parser)

View File

@@ -0,0 +1,16 @@
# -*- 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.
"""A helper library for the Cloud NetApp Volume QuotaRules sub-command group."""

View File

@@ -0,0 +1,115 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Files Volume QuotaRules commands."""
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.util.apis import arg_utils
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
## Helper functions to add args / flags for QuotaRules gcloud commands ##
def GetQuotaRuleTypeEnumFromArg(choice, messages):
"""Returns the Choice Enum for Quota Rule Type.
Args:
choice: The choice for quota rule type as string
messages: The messages module.
Returns:
the quota rule type enum.
"""
return arg_utils.ChoiceToEnum(
choice=choice,
enum_type=messages.QuotaRule.TypeValueValuesEnum,
)
def AddQuotaRuleVolumeArg(parser, required=False):
concept_parsers.ConceptParser.ForResource(
'--volume',
flags.GetVolumeResourceSpec(positional=False),
'The volume for which quota rule applies.',
flag_name_overrides={'location': ''},
required=required,
).AddToParser(parser)
def AddQuotaRuleTypeArg(parser):
help_text = """\
String indicating the type of quota rule.
The supported values are: 'DEFAULT_USER_QUOTA','DEFAULT_GROUP_QUOTA','INDIVIDUAL_USER_QUOTA','INDIVIDUAL_GROUP_QUOTA'
"""
parser.add_argument(
'--type',
type=str,
help=help_text,
required=True,
)
def AddQuotaRuleTargetArg(parser):
help_text = """\
The target of the quota rule.
Identified by a Unix UID/GID, Windows SID, or null for default.
"""
parser.add_argument(
'--target',
type=str,
help=help_text,
)
def AddQuotaRuleDiskLimitMib(parser, required=False):
help_text = 'The disk limit in MiB for the quota rule.'
parser.add_argument(
'--disk-limit-mib',
type=int,
help=help_text,
required=required,
)
## Helper function to combine QuotaRules args / flags for gcloud commands ##
def AddQuotaRuleCreateArgs(parser):
"""Add args for creating a Quota rule."""
concept_parsers.ConceptParser([
flags.GetQuotaRulePresentationSpec('The Quota rule to create.')
]).AddToParser(parser)
AddQuotaRuleVolumeArg(parser, required=True)
AddQuotaRuleTypeArg(parser)
AddQuotaRuleTargetArg(parser)
AddQuotaRuleDiskLimitMib(parser, required=True)
flags.AddResourceDescriptionArg(parser, 'Quota rule')
flags.AddResourceAsyncFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
def AddQuotaRuleUpdateArgs(parser):
"""Add args for updating a Quota rule."""
concept_parsers.ConceptParser([
flags.GetQuotaRulePresentationSpec('The Quota rule to update.')
]).AddToParser(parser)
AddQuotaRuleVolumeArg(parser, required=True)
AddQuotaRuleDiskLimitMib(parser, required=False)
flags.AddResourceDescriptionArg(parser, 'Quota rule')
flags.AddResourceAsyncFlag(parser)
labels_util.AddUpdateLabelsFlags(parser)

View File

@@ -0,0 +1,20 @@
# -*- 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.
"""A helper library for the Cloud NetApp Volume Replications sub-command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,136 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Files Volume Replications commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.util.apis import arg_utils
from googlecloudsdk.command_lib.util.concepts import concept_parsers
## Helper functions to add args / flags for Replications gcloud commands ##
def AddReplicationVolumeArg(parser, reverse_op=False):
group_help = (
'The Volume that the Replication is based on'
if not reverse_op
else 'The source Volume to reverse the Replication direction of'
)
concept_parsers.ConceptParser.ForResource(
'--volume',
flags.GetVolumeResourceSpec(positional=False),
group_help=group_help,
flag_name_overrides={'location': ''},
).AddToParser(parser)
def AddReplicationForceArg(parser):
"""Adds the --force arg to the arg parser."""
parser.add_argument(
'--force',
action='store_true',
help="""Indicates whether to stop replication forcefully while data transfer is in progress.
Warning! if force is true, this will abort any current transfers and can lead to data loss due to partial transfer.
If force is false, stop replication will fail while data transfer is in progress and you will need to retry later.
""",
)
def GetReplicationReplicationScheduleEnumFromArg(choice, messages):
"""Returns the Choice Enum for Replication Schedule.
Args:
choice: The choice for replication schedule input as string.
messages: The messages module.
Returns:
The replication schedule enum.
"""
return arg_utils.ChoiceToEnum(
choice=choice,
enum_type=messages.Replication.ReplicationScheduleValueValuesEnum,
)
def AddReplicationReplicationScheduleArg(parser, required=True):
"""Adds the Replication Schedule (--replication-schedule) arg to the given parser.
Args:
parser: Argparse parser.
required: If the Replication Schedule is required. E.g. it is required by
Create, but not required by Update.
"""
parser.add_argument(
'--replication-schedule',
type=str,
required=required,
help='The schedule for the Replication.',
)
def AddReplicationDestinationVolumeParametersArg(parser, messages):
"""Adds the Destination Volume Parameters (--destination-volume-parameters) arg to the given parser.
Args:
parser: Argparse parser.
messages: The messages module.
"""
destination_volume_parameters_spec = {
'storage_pool': str,
'volume_id': str,
'share_name': str,
'description': str,
'tiering_policy': arg_parsers.ArgObject(
spec={
'tier-action': messages.TieringPolicy.TierActionValueValuesEnum,
'cooling-threshold-days': int,
},
enable_shorthand=False,
),
}
destination_volume_parameters_help = """\
"""
parser.add_argument(
'--destination-volume-parameters',
type=arg_parsers.ArgObject(
spec=destination_volume_parameters_spec,
required_keys=['storage_pool'],
),
required=True,
help=destination_volume_parameters_help,
)
def AddReplicationClusterLocationArg(parser, hidden=False):
"""Adds the Cluster Location (--cluster-location) arg to the given parser.
Args:
parser: Argparse parser.
hidden: If the Cluster Location is hidden.
"""
parser.add_argument(
'--cluster-location',
type=str,
required=False,
help='Location of the user cluster.',
hidden=hidden,
)

View File

@@ -0,0 +1,20 @@
# -*- 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.
"""A helper library for the Cloud NetApp Volume Snapshots sub-command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

View File

@@ -0,0 +1,70 @@
# -*- 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.
"""Flags and helpers for the Cloud NetApp Files Volume Snapshots commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.command_lib.netapp import flags
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
## Helper functions to add args / flags for Snapshots gcloud commands ##
def AddSnapshotVolumeArg(parser):
concept_parsers.ConceptParser.ForResource(
'--volume',
flags.GetVolumeResourceSpec(positional=False),
'The Volume to take a Snapshot of.',
flag_name_overrides={'location': ''},
).AddToParser(parser)
## Helper functions to combine Snapshots args / flags for gcloud commands #
def AddSnapshotCreateArgs(parser):
"""Add args for creating a Snapshot."""
concept_parsers.ConceptParser([
flags.GetSnapshotPresentationSpec('The Snapshot to create.')
]).AddToParser(parser)
AddSnapshotVolumeArg(parser)
flags.AddResourceAsyncFlag(parser)
flags.AddResourceDescriptionArg(parser, 'Snapshot')
labels_util.AddCreateLabelsFlags(parser)
def AddSnapshotDeleteArgs(parser):
"""Add args for deleting a Snapshot."""
concept_parsers.ConceptParser([
flags.GetSnapshotPresentationSpec('The Snapshot to delete.')
]).AddToParser(parser)
AddSnapshotVolumeArg(parser)
flags.AddResourceAsyncFlag(parser)
def AddSnapshotUpdateArgs(parser):
"""Add args for updating a Snapshot."""
concept_parsers.ConceptParser([
flags.GetSnapshotPresentationSpec('The Snapshot to update.')
]).AddToParser(parser)
AddSnapshotVolumeArg(parser)
flags.AddResourceAsyncFlag(parser)
flags.AddResourceDescriptionArg(parser, 'Snapshot')
labels_util.AddUpdateLabelsFlags(parser)