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,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2016 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.

View File

@@ -0,0 +1,86 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CRM API Capability utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.util import apis
API_VERSION = 'v3'
def CapabilitiesClient(api_version: str = API_VERSION):
return apis.GetClientInstance('cloudresourcemanager', api_version)
def CapabilitiesService(api_version: str = API_VERSION):
return CapabilitiesClient(api_version).folders_capabilities
def CapabilitiesMessages(api_version: str = API_VERSION):
return apis.GetMessagesModule('cloudresourcemanager', api_version)
def GetCapability(capability_id: str) -> CapabilitiesMessages().Capability:
"""Get a particular Capability using capability_id.
The method explicitly sets Capability.value to False in case Capability is not
enabled, because the default response does not populate the value field if the
capability is disabled.
Args:
capability_id: The capability_id to get.
Returns:
The response from the Get Request. In case the value is False, it is
explicitly populated with the proper value for clarity.
"""
get_capability_response = CapabilitiesService().Get(
CapabilitiesMessages().CloudresourcemanagerFoldersCapabilitiesGetRequest(
name=capability_id
)
)
if not get_capability_response.value:
get_capability_response.value = False
return get_capability_response
def UpdateCapability(
capability_id: str, value: bool, update_mask: str = ''
) -> CapabilitiesMessages().Operation:
"""Send an Update Request for the capability.
Capability is a singleton resource, and only certain capability_types are
allowed. Currently, "app-management" is the only possible capability_type.
Args:
capability_id: The capability_id to update. Should be in the format:
folders/{folder_id}/capabilities/{capability_type}.
value: The value to set for the capability.
update_mask: The update mask to use for the request.
Returns:
The response from the Update Request.
"""
return CapabilitiesService().Patch(
CapabilitiesMessages().CloudresourcemanagerFoldersCapabilitiesPatchRequest(
name=capability_id,
updateMask=update_mask,
capability=CapabilitiesMessages().Capability(
name=capability_id, value=value
),
)
)

View File

@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 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.
"""CRM API common error handling."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from functools import wraps
from apitools.base.py import exceptions
from googlecloudsdk.api_lib.util import exceptions as api_exceptions
def EmitErrorDetails(func):
"""Decorates a function for better errors."""
@wraps(func)
def Wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exceptions.HttpError as error:
raise api_exceptions.HttpException(error, '{message}{details?\n{?}}')
return Wrapper
def YieldErrorDetails(func):
"""Decorates a function which produces a generator for better errors."""
@wraps(func)
def Wrapper(*args, **kwargs):
try:
for i in func(*args, **kwargs):
yield i
except exceptions.HttpError as error:
raise api_exceptions.HttpException(error, '{message}{details?\n{?}}')
return Wrapper

View File

@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 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.
"""Wrapper for user-visible error exceptions to raise in the CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.core import exceptions
class ResourceManagerError(exceptions.Error):
"""Exceptions for Resource Manager errors."""
class ResourceManagerInputFileError(ResourceManagerError):
"""More specific errors for failure to read input files."""
class ArgumentError(ResourceManagerError):
"""Command argument error."""

View File

@@ -0,0 +1,145 @@
# -*- coding: utf-8 -*- #
# Copyright 2016 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.
"""CRM API Folders utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import exceptions as api_exceptions
from googlecloudsdk.api_lib.cloudresourcemanager import organizations
from googlecloudsdk.api_lib.iam import policies as policies_api
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.command_lib.resource_manager import exceptions
from googlecloudsdk.core import resources
FOLDERS_API_VERSION = 'v2'
def FoldersClient(api_version=FOLDERS_API_VERSION):
return apis.GetClientInstance('cloudresourcemanager', api_version)
def FoldersRegistry():
registry = resources.REGISTRY.Clone()
registry.RegisterApiByName('cloudresourcemanager', FOLDERS_API_VERSION)
return registry
def FoldersService(api_version=FOLDERS_API_VERSION):
return FoldersClient(api_version).folders
def FoldersMessages(api_version=FOLDERS_API_VERSION):
return apis.GetMessagesModule('cloudresourcemanager', api_version)
def FolderNameToId(folder_name):
return folder_name[len('folders/'):]
def FolderIdToName(folder_id):
return 'folders/{0}'.format(folder_id)
def GetFolder(folder_id):
return FoldersService().Get(
FoldersMessages().CloudresourcemanagerFoldersGetRequest(
foldersId=folder_id))
def GetIamPolicy(folder_id):
messages = FoldersMessages()
request = messages.CloudresourcemanagerFoldersGetIamPolicyRequest(
foldersId=folder_id,
getIamPolicyRequest=messages.GetIamPolicyRequest(
options=messages.GetPolicyOptions(requestedPolicyVersion=iam_util.
MAX_LIBRARY_IAM_SUPPORTED_VERSION)))
return FoldersService().GetIamPolicy(request)
def SetIamPolicy(folder_id, policy, update_mask=None):
"""Calls /google.cloud.resourcemanager.v2.Folders.SetIamPolicy."""
messages = FoldersMessages()
set_iam_policy_request = messages.SetIamPolicyRequest(
policy=policy, updateMask=update_mask)
request = messages.CloudresourcemanagerFoldersSetIamPolicyRequest(
foldersId=folder_id, setIamPolicyRequest=set_iam_policy_request)
return FoldersService().SetIamPolicy(request)
def GetUri(resource):
"""Returns the uri for resource."""
folder_id = FolderNameToId(resource.name)
folder_ref = FoldersRegistry().Parse(
None,
params={'foldersId': folder_id},
collection='cloudresourcemanager.folders')
return folder_ref.SelfLink()
def GetAncestorsIamPolicy(folder_id, include_deny, release_track):
"""Gets IAM policies for given folder and its ancestors."""
policies = []
resource = GetFolder(folder_id)
try:
while resource is not None:
resource_id = resource.name.split('/')[1]
policies.append({
'type': 'folder',
'id': resource_id,
'policy': GetIamPolicy(resource_id),
})
if include_deny:
deny_policies = policies_api.ListDenyPolicies(resource_id, 'folder',
release_track)
for deny_policy in deny_policies:
policies.append({
'type': 'folder',
'id': resource_id,
'policy': deny_policy
})
parent_id = resource.parent.split('/')[1]
if resource.parent.startswith('folder'):
resource = GetFolder(parent_id)
else:
policies.append({
'type': 'organization',
'id': parent_id,
'policy': organizations.Client().GetIamPolicy(parent_id),
})
if include_deny:
deny_policies = policies_api.ListDenyPolicies(parent_id,
'organization',
release_track)
for deny_policy in deny_policies:
policies.append({
'type': 'organization',
'id': resource_id,
'policy': deny_policy
})
resource = None
except api_exceptions.HttpForbiddenError:
raise exceptions.AncestorsIamPolicyAccessDeniedError(
'User is not permitted to access IAM policy for one or more of the'
' ancestors')
return policies

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*- #
# Copyright 2016 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.
"""CRM API Liens utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.core import resources
LIENS_API_VERSION = 'v1'
def LiensClient():
return apis.GetClientInstance('cloudresourcemanager', LIENS_API_VERSION)
def LiensRegistry():
registry = resources.REGISTRY.Clone()
registry.RegisterApiByName('cloudresourcemanager', LIENS_API_VERSION)
return registry
def LiensService():
return LiensClient().liens
def LiensMessages():
return apis.GetMessagesModule('cloudresourcemanager', LIENS_API_VERSION)
def LienNameToId(lien_name):
return lien_name[len('liens/'):]
def LienIdToName(lien_id):
return 'liens/{0}'.format(lien_id)
def GetLien(lien_id):
return LiensService().Get(
LiensMessages().CloudresourcemanagerLiensGetRequest(LiensId=lien_id))
def GetUri(resource):
"""Returns the uri for resource."""
lien_id = LienNameToId(resource.name)
lien_ref = LiensRegistry().Parse(
None, params={'liensId': lien_id},
collection='cloudresourcemanager.liens')
return lien_ref.SelfLink()

View File

@@ -0,0 +1,207 @@
# -*- coding: utf-8 -*- #
# Copyright 2016 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.
"""CRM API Operations utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import time
from apitools.base.py import encoding
from apitools.base.py import exceptions
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core import resources
from googlecloudsdk.core import yaml
from googlecloudsdk.core.console import progress_tracker as tracker
from googlecloudsdk.core.util import retry
import ruamel.yaml
OPERATIONS_API_V1 = 'v1'
OPERATIONS_API_V3 = 'v3'
class OperationError(exceptions.Error):
pass
def OperationsClient(version=OPERATIONS_API_V1):
return apis.GetClientInstance('cloudresourcemanager', version)
def OperationsRegistry(version=OPERATIONS_API_V1):
registry = resources.REGISTRY.Clone()
registry.RegisterApiByName('cloudresourcemanager', version)
return registry
def OperationsService(version=OPERATIONS_API_V1):
return OperationsClient(version).operations
def OperationsMessages(version=OPERATIONS_API_V1):
return apis.GetMessagesModule('cloudresourcemanager', version)
def OperationNameToId(operation_name):
return operation_name[len('operations/'):]
def OperationIdToName(operation_id):
return 'operations/{0}'.format(operation_id)
def GetOperation(operation_id):
return OperationsService().Get(
OperationsMessages().CloudresourcemanagerOperationsGetRequest(
operationsId=operation_id))
def GetOperationV3(operation_id):
return OperationsService(OPERATIONS_API_V3).Get(
OperationsMessages(
OPERATIONS_API_V3).CloudresourcemanagerOperationsGetRequest(
name=OperationIdToName(operation_id)))
def WaitForOperation(operation):
wait_message = 'Waiting for [{0}] to finish'.format(operation.name)
with tracker.ProgressTracker(wait_message, autotick=False) as pt:
retryer = OperationRetryer()
poller = OperationPoller(pt)
return retryer.RetryPollOperation(poller, operation)
def ExtractOperationResponse(operation, response_message_type):
raw_dict = encoding.MessageToDict(operation.response)
return encoding.DictToMessage(raw_dict, response_message_type)
def ToOperationResponse(message):
raw_dict = encoding.MessageToDict(message)
return encoding.DictToMessage(raw_dict,
OperationsMessages().Operation.ResponseValue)
class OperationRetryer(object):
"""A wrapper around a Retryer that works with CRM operations.
Uses predefined constants for retry timing, so all CRM operation commands can
share their retry timing settings.
"""
def __init__(self,
pre_start_sleep=lambda: time.sleep(1),
max_retry_ms=2000,
max_wait_ms=300000,
wait_ceiling_ms=20000,
first_retry_sleep_ms=2000):
self._pre_start_sleep = pre_start_sleep
self._max_retry_ms = max_retry_ms
self._max_wait_ms = max_wait_ms
self._wait_ceiling_ms = wait_ceiling_ms
self._first_retry_sleep_ms = first_retry_sleep_ms
def RetryPollOperation(self, operation_poller, operation):
self._pre_start_sleep()
return self._Retryer().RetryOnResult(
lambda: operation_poller.Poll(operation),
should_retry_if=self._ShouldRetry,
sleep_ms=self._first_retry_sleep_ms)
def _Retryer(self):
return retry.Retryer(
exponential_sleep_multiplier=2,
max_wait_ms=self._max_wait_ms,
wait_ceiling_ms=self._wait_ceiling_ms)
def _ShouldRetry(self, result, state):
if isinstance(result, exceptions.HttpError):
return self._CheckTimePassedBelowMax(result, state)
return self._CheckResultNotException(result)
def _CheckTimePassedBelowMax(self, result, state):
if state.time_passed_ms > self._max_retry_ms:
raise result
return True
def _CheckResultNotException(self, result):
if isinstance(result, Exception):
raise result
return not result.done
class OperationPoller(object):
def __init__(self, progress_tracker=None):
self._progress_tracker = progress_tracker
def Poll(self, operation):
if self._progress_tracker:
self._progress_tracker.Tick()
latest = GetOperation(OperationNameToId(operation.name))
if latest.done and latest.error:
raise OperationFailedException(latest)
return latest
class OperationFailedException(core_exceptions.Error):
"""Exception for failed operations."""
def __init__(self, operation_with_error):
op_id = OperationNameToId(operation_with_error.name)
error_code = operation_with_error.error.code
error_message = operation_with_error.error.message
message = 'Operation [{0}] failed: {1}: {2}'.format(op_id, error_code,
error_message)
try:
# Convert the proto message to a Python dict to safely access details
error_py_value = encoding.MessageToPyValue(operation_with_error.error)
details = error_py_value.get('details', [])
if details:
message += '\n' + yaml.dump(details)
except (TypeError, AttributeError, ruamel.yaml.YAMLError) as e:
# If formatting fails for any reason, fall back to the base message.
message += f'\n(Failed to parse or format error details: {e})'
super(OperationFailedException, self).__init__(message)
def GetUri(resource):
"""Returns the uri for resource."""
operation_id = OperationNameToId(resource.name)
operation_ref = OperationsRegistry().Parse(
None,
params={'operationsId': operation_id},
collection='cloudresourcemanager.operations')
return operation_ref.SelfLink()
def GetFailedOperation(operation_name, messages, error_details, error_code,
error_message):
"""Returns a failed operation with error details."""
details_messages = []
for item in error_details:
# Each item in the details list is an 'Any' proto,
# represented by DetailsValueListEntry
details_messages.append(
encoding.DictToMessage(item, messages.Status.DetailsValueListEntry))
return messages.Operation(
name='operations/' + operation_name,
done=True,
error=messages.Status(
code=error_code, message=error_message, details=details_messages))

View File

@@ -0,0 +1,79 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 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.
"""Org Policies utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.protorpclite.messages import DecodeError
from apitools.base.py import encoding
from googlecloudsdk.api_lib.resource_manager import exceptions
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.core import yaml
from googlecloudsdk.core.util import files
import six
CONSTRAINTS_PREFIX = 'constraints/'
ORG_POLICIES_API_VERSION = 'v1'
def OrgPoliciesClient():
return apis.GetClientInstance('cloudresourcemanager',
ORG_POLICIES_API_VERSION)
def OrgPoliciesMessages():
return apis.GetMessagesModule('cloudresourcemanager',
ORG_POLICIES_API_VERSION)
def GetFileAsMessage(path, message):
"""Reads a YAML or JSON object of type message from local path.
Args:
path: A local path to an object specification in YAML or JSON format.
message: The message type to be parsed from the file.
Returns:
Object of type message, if successful.
Raises:
files.Error, exceptions.ResourceManagerInputFileError
"""
in_text = files.ReadFileContents(path)
if not in_text:
raise exceptions.ResourceManagerInputFileError(
'Empty policy file [{0}]'.format(path))
# Parse it, first trying YAML then JSON.
try:
result = encoding.PyValueToMessage(message, yaml.load(in_text))
except (ValueError, AttributeError, yaml.YAMLParseError):
try:
result = encoding.JsonToMessage(message, in_text)
except (ValueError, DecodeError) as e:
# ValueError is raised when JSON is badly formatted
# DecodeError is raised when a tag is badly formatted (not Base64)
raise exceptions.ResourceManagerInputFileError(
'Policy file [{0}] is not properly formatted YAML or JSON '
'due to [{1}]'.format(path, six.text_type(e)))
return result
def FormatConstraint(constraint_id):
if constraint_id.startswith(CONSTRAINTS_PREFIX):
return constraint_id
else:
return CONSTRAINTS_PREFIX + constraint_id

View File

@@ -0,0 +1,78 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for the Resource Settings service."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.util import apis
RESOURCE_SETTINGS_API_NAME = 'cloudresourcemanager'
RESOURCE_SETTINGS_API_VERSION = 'v3'
def ResourceSettingsClient():
"""Returns a client instance of the Resource Settings service."""
return apis.GetClientInstance(RESOURCE_SETTINGS_API_NAME,
RESOURCE_SETTINGS_API_VERSION)
def ResourceSettingsMessages():
"""Returns the messages module for the Resource Settings service."""
return apis.GetMessagesModule(RESOURCE_SETTINGS_API_NAME,
RESOURCE_SETTINGS_API_VERSION)
# Folders Settings
def FoldersSettingsService():
"""Returns the service class for the Folders Settings resource."""
client = ResourceSettingsClient()
return client.folders_settings
# Folders Effective Settings
def FoldersEffectiveSettingsService():
"""Returns the service class for the Folders Effective Settings resource."""
client = ResourceSettingsClient()
return client.folders_effectiveSettings
# Organization Settings
def OrganizationsSettingsService():
"""Returns the service class for the Organization Settings resource."""
client = ResourceSettingsClient()
return client.organizations_settings
# Organization Effective Settings
def OrganizationsEffectiveSettingsService():
"""Returns the service class for the Organization Effective Settings resource."""
client = ResourceSettingsClient()
return client.organizations_effectiveSettings
# Project Settings
def ProjectsSettingsService():
"""Returns the service class for the Project Settings resource."""
client = ResourceSettingsClient()
return client.projects_settings
# Project Effective Settings
def ProjectsEffectiveSettingsService():
"""Returns the service class for the Project Effective Settings resource."""
client = ResourceSettingsClient()
return client.projects_effectiveSettings

View File

@@ -0,0 +1,238 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for manipulating organization policies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.resource_manager.settings import service as settings_service
ORGANIZATION = 'organization'
FOLDER = 'folder'
PROJECT = 'project'
def ComputeResourceType(args):
"""Returns the resource type from the user-specified arguments.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the Args method.
"""
if args.organization:
resource_type = ORGANIZATION
elif args.folder:
resource_type = FOLDER
else:
resource_type = PROJECT
return resource_type
def GetPatchRequestFromResourceType(resource_type, name, local_value, etag):
"""Returns the Setting from the user-specified arguments.
Args:
resource_type: A String object that contains the resource type
name: The resource name of the setting and has the following syntax:
[organizations|folders|projects]/{resource_id}/settings/{setting_name}.
local_value: The configured value of the setting at the given parent
resource
etag: A fingerprint used for optimistic concurrency.
"""
setting = settings_service.ResourceSettingsMessages(
).Setting(
name=name, value=local_value, etag=etag)
if resource_type == ORGANIZATION:
request = settings_service.ResourceSettingsMessages(
).CloudresourcemanagerOrganizationsSettingsPatchRequest(
name=name, setting=setting)
elif resource_type == FOLDER:
request = settings_service.ResourceSettingsMessages(
).CloudresourcemanagerFoldersSettingsPatchRequest(
name=name, setting=setting)
else:
request = settings_service.ResourceSettingsMessages(
).CloudresourcemanagerProjectsSettingsPatchRequest(
name=name, setting=setting)
return request
def GetDescribeRequestFromArgs(args, setting_name, is_effective):
"""Returns the get_request from the user-specified arguments.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the Args method.
setting_name: setting name such as `settings/iam-projectCreatorRoles`
is_effective: indicate if it is requesting for an effective setting
"""
messages = settings_service.ResourceSettingsMessages()
if args.organization:
if is_effective:
get_request = (
messages.CloudresourcemanagerOrganizationsEffectiveSettingsGetRequest(
name=setting_name
)
)
else:
get_request = (
messages.CloudresourcemanagerOrganizationsSettingsGetRequest(
name=setting_name
)
)
elif args.folder:
if is_effective:
get_request = (
messages.CloudresourcemanagerFoldersEffectiveSettingsGetRequest(
name=setting_name
)
)
else:
get_request = messages.CloudresourcemanagerFoldersSettingsGetRequest(
name=setting_name
)
else:
if is_effective:
get_request = (
messages.CloudresourcemanagerProjectsEffectiveSettingsGetRequest(
name=setting_name
)
)
else:
get_request = messages.CloudresourcemanagerProjectsSettingsGetRequest(
name=setting_name
)
return get_request
def GetListRequestFromArgs(args, parent_resource):
"""Returns the get_request from the user-specified arguments.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the Args method.
parent_resource: resource location such as `organizations/123`
"""
messages = settings_service.ResourceSettingsMessages()
if args.organization:
get_request = messages.CloudresourcemanagerOrganizationsSettingsListRequest(
parent=parent_resource)
elif args.folder:
get_request = messages.CloudresourcemanagerFoldersSettingsListRequest(
parent=parent_resource)
else:
get_request = messages.CloudresourcemanagerProjectsSettingsListRequest(
parent=parent_resource)
return get_request
def GetDeleteValueRequestFromArgs(args, setting_name):
"""Returns the get_request from the user-specified arguments.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the Args method.
setting_name: setting name such as `settings/iam-projectCreatorRoles`
"""
messages = settings_service.ResourceSettingsMessages()
if args.organization:
get_request = (
messages.CloudresourcemanagerOrganizationsSettingsClearRequest(
name=setting_name
)
)
elif args.folder:
get_request = messages.CloudresourcemanagerFoldersSettingsClearRequest(
name=setting_name
)
else:
get_request = messages.CloudresourcemanagerProjectsSettingsClearRequest(
name=setting_name
)
return get_request
def GetServiceFromArgs(args):
"""Returns the service from the user-specified arguments.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the Args method.
"""
resource_type = ComputeResourceType(args)
return GetServiceFromResourceType(resource_type)
def GetServiceFromResourceType(resource_type):
"""Returns the service from the resource type input.
Args:
resource_type: A String object that contains the resource type
"""
if resource_type == ORGANIZATION:
service = settings_service.OrganizationsSettingsService()
elif resource_type == FOLDER:
service = settings_service.FoldersSettingsService()
else:
service = settings_service.ProjectsSettingsService()
return service
def GetEffectiveServiceFromArgs(args):
"""Returns the service from the user-specified arguments.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the Args method.
"""
resource_type = ComputeResourceType(args)
return GetEffectiveServiceFromResourceType(resource_type)
def GetEffectiveServiceFromResourceType(resource_type):
"""Returns the service from the resource type input.
Args:
resource_type: A String object that contains the resource type
"""
if resource_type == ORGANIZATION:
service = settings_service.OrganizationsEffectiveSettingsService()
elif resource_type == FOLDER:
service = settings_service.FoldersEffectiveSettingsService()
else:
service = settings_service.ProjectsEffectiveSettingsService()
return service

View File

@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for the Tag Manager server."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.util import apis
TAGS_API_VERSION = 'v3'
def TagClient():
"""Returns a client instance of the CRM Tags service."""
return apis.GetClientInstance('cloudresourcemanager', TAGS_API_VERSION)
def TagMessages():
"""Returns the messages module for the Tags service."""
return apis.GetMessagesModule('cloudresourcemanager', TAGS_API_VERSION)
def TagKeysService():
"""Returns the tag keys service class."""
client = TagClient()
return client.tagKeys
def TagValuesService():
"""Returns the tag values service class."""
client = TagClient()
return client.tagValues
def TagBindingsService():
"""Returns the tag bindings service class."""
client = TagClient()
return client.tagBindings
def EffectiveTagsService():
"""Returns the effective tags service class."""
client = TagClient()
return client.effectiveTags
# TODO(b/404505614): Refactor the code following abstraction to avoid
# duplication.
def TagBindingsCollectionService():
"""Returns the tag bindings collection class."""
client = TagClient()
return client.locations_tagBindingCollections
def EffectiveTagsCollectionService():
"""Returns the effective tags collection class."""
client = TagClient()
return client.locations_effectiveTagBindingCollections
def TagHoldsService():
"""Returns the tag holds service class."""
client = TagClient()
return client.tagValues_tagHolds
def OperationsService():
"""Returns the operations service class."""
client = TagClient()
return client.operations