def CreateMembership(project, membership_id, description, gke_cluster_self_link=None, external_id=None, release_track=None, issuer_url=None, oidc_jwks=None): """Creates a Membership resource in the GKE Hub API. Args: project: the project in which to create the membership membership_id: the value to use for the membership_id description: the value to put in the description field gke_cluster_self_link: the selfLink for the cluster if it is a GKE cluster, or None if it is not external_id: the unique id associated with the cluster, or None if it is not available. release_track: the release_track used in the gcloud command, or None if it is not available. issuer_url: the discovery URL for the cluster's service account token issuer. Set to None to skip enabling Workload Identity. oidc_jwks: the JSON Web Key Set containing public keys for validating service account tokens. Set to None if the issuer_url is publicly-routable. Still requires issuer_url to be set. Returns: the created Membership resource. Raises: - apitools.base.py.HttpError: if the request returns an HTTP error - exceptions raised by waiter.WaitFor() """ client = gkehub_api_util.GetApiClientForTrack(release_track) messages = client.MESSAGES_MODULE parent_ref = ParentRef(project, 'global') request = messages.GkehubProjectsLocationsMembershipsCreateRequest( membership=messages.Membership(description=description), parent=parent_ref, membershipId=membership_id, ) if gke_cluster_self_link: endpoint = messages.MembershipEndpoint(gkeCluster=messages.GkeCluster( resourceLink=gke_cluster_self_link)) request.membership.endpoint = endpoint if external_id: request.membership.externalId = external_id if issuer_url: request.membership.authority = messages.Authority(issuer=issuer_url) if release_track is not base.ReleaseTrack.GA: if oidc_jwks: request.membership.authority.oidcJwks = oidc_jwks.encode( 'utf-8') op = client.projects_locations_memberships.Create(request) op_resource = resources.REGISTRY.ParseRelativeName( op.name, collection='gkehub.projects.locations.operations') return waiter.WaitFor( waiter.CloudOperationPoller(client.projects_locations_memberships, client.projects_locations_operations), op_resource, 'Waiting for membership to be created')
def Patch(self, policy_ref, title=None): """Patch an access policy. Args: policy_ref: resources.Resource, reference to the policy to patch title: str, title of the policy or None if not updating Returns: AccessPolicy, the updated access policy """ policy = self.messages.AccessPolicy() update_mask = [] if title is not None: update_mask.append('title') policy.title = title update_mask.sort() # For ease-of-testing m = self.messages request_type = m.AccesscontextmanagerAccessPoliciesPatchRequest request = request_type( accessPolicy=policy, name=policy_ref.RelativeName(), updateMask=','.join(update_mask), ) operation = self.client.accessPolicies.Patch(request) poller = waiter.CloudOperationPoller(self.client.accessPolicies, self.client.operations) poller = util.OperationPoller(self.client.accessPolicies, self.client.operations, policy_ref) operation_ref = resources.REGISTRY.Parse( operation.name, collection='accesscontextmanager.operations') return waiter.WaitFor( poller, operation_ref, 'Waiting for PATCH operation [{}]'.format(operation_ref.Name()))
def CreateMembership(project, membership_id, description): """Creates a Membership resource in the GKE Hub API. Args: project: the project in which to create the membership membership_id: the value to use for the membership_id description: the value to put in the description field Returns: the created Membership resource. Raises: - apitools.base.py.HttpError: if the request returns an HTTP error - exceptions raised by waiter.WaitFor() """ client = _MembershipClient() request = client.MESSAGES_MODULE.GkehubProjectsLocationsGlobalMembershipsCreateRequest( membership=client.MESSAGES_MODULE.Membership(description=description), parent='projects/{}/locations/global'.format(project), membershipId=membership_id, ) op = client.projects_locations_global_memberships.Create(request) op_resource = resources.REGISTRY.ParseRelativeName( op.name, collection='gkehub.projects.locations.operations') return waiter.WaitFor( waiter.CloudOperationPoller(client.projects_locations_global_memberships, client.projects_locations_operations), op_resource, 'Waiting for membership to be created')
def Await(op_ref, message, release_track, creates_resource=True): """Waits for the given google.longrunning.Operation to complete. Args: op_ref: The operation to poll. message: String to display for default progress_tracker. release_track: The API release track (e.g. ALPHA, BETA, etc.) creates_resource: Whether or not the operation creates a resource Raises: apitools.base.py.HttpError: if the request returns an HTTP error Returns: The Operation or the Resource the Operation is associated with. """ client = api_util.AlloyDBClient(release_track) alloydb_client = client.alloydb_client if creates_resource: poller = waiter.CloudOperationPoller( alloydb_client.projects_locations_clusters_instances, alloydb_client.projects_locations_operations) else: poller = waiter.CloudOperationPollerNoResources( alloydb_client.projects_locations_operations) return waiter.WaitFor( poller, op_ref, message, exponential_sleep_multiplier=1.0, sleep_ms=10000)
def Await(operation, message, creates_resource=True): """Waits for the given google.longrunning.Operation to complete. Args: operation: The operation to poll. message: String to display for default progress_tracker. creates_resource: Whether or not the operation creates a resource. Raises: apitools.base.py.HttpError: If the request returns an HTTP error. Returns: The Operation or the Resource the Operation is associated with. """ client = api_util.AlloyDBClient(api_util.API_VERSION_DEFAULT) alloydb_client = client.alloydb_client if creates_resource: poller = waiter.CloudOperationPoller( alloydb_client.projects_locations_clusters, alloydb_client.projects_locations_operations) else: poller = waiter.CloudOperationPollerNoResources( alloydb_client.projects_locations_operations) ref = resources.REGISTRY.ParseRelativeName( operation.name, collection='alloydbadmin.projects.locations.operations') return waiter.WaitFor(poller, ref, message)
def WaitForOperation(operation, message, service): """Waits for the given google.longrunning.Operation to complete. Args: operation: The operation to poll. message: String to display for default progress_tracker. service: The service to get the resource after the long running operation completes. Raises: apitools.base.py.HttpError: if the request returns an HTTP error Returns: The TagKey or TagValue resource. """ poller = waiter.CloudOperationPoller(service, tags.OperationsService()) if poller.IsDone(operation): # Use the poller to get the result so it prints the same regardless if the # Operation is immediately done or not. Currently the poller will raise a # KeyError because it assumes a 'name' field which is not present when # the Operation response is of type Empty. try: return poller.GetResult(operation) except KeyError: return operation operation_ref = resources.REGISTRY.Parse( operation.name, collection='cloudresourcemanager.operations') return waiter.WaitFor(poller, operation_ref, message)
def WaitForOperation(self, operation_ref, message, has_result=True, max_wait=datetime.timedelta(seconds=3600)): """Waits for an operation to complete. Polls the IDS Operation service until the operation completes, fails, or max_wait_seconds elapses. Args: operation_ref: a Resource created by GetOperationRef describing the operation. message: the message to display to the user while they wait. has_result: if True, the function will return the target of the operation when it completes. If False, nothing will be returned (useful for Delete operations) max_wait: The time to wait for the operation to succeed before returning. Returns: if has_result = True, an Endpoint entity. Otherwise, None. """ if has_result: poller = waiter.CloudOperationPoller(self.service, self.operations_service) else: poller = waiter.CloudOperationPollerNoResources( self.operations_service) return waiter.WaitFor(poller, operation_ref, message, max_wait_ms=max_wait.seconds * 1000)
def WaitForOperation(self, operation_ref, message=None, service=None): """Waits for the given google.longrunning.Operation to complete. Args: operation_ref: The operation to poll. message: String to display for default progress_tracker. service: The service to get the resource after the long running operation completes. Raises: apitools.base.py.HttpError: if the request returns an HTTP error Returns: The Operation or the Resource the Operation is associated with. """ # Consumers of OperationsClient can be resource-aware and if so, they can # provide the service used for interacting with the Resource the Operation # is associated with. In this case, OperationsClient#WaitForOperation will # return the Resource the polled Operation is associated with. Otherwise, # no service is provided and the Operation object itself is returned. # # Example: `gateways create` is resource-aware and returns an # ApigatewayGateway while `operations wait` is not resource-aware and will # return the Operation itself. if service is None: poller = waiter.CloudOperationPollerNoResources(self.service) else: poller = waiter.CloudOperationPoller(service, self.service) if message is None: message = 'Waiting for Operation [{}] to complete'.format( operation_ref.RelativeName()) return waiter.WaitFor(poller, operation_ref, message)
def UpdateMembership(name, membership, update_mask, release_track, external_id=None, issuer_url=None, oidc_jwks=None): """UpdateMembership updates membership resource in the GKE Hub API. Args: name: The full resource name of the membership to update, e.g. projects/foo/locations/global/memberships/name. membership: Membership resource that needs to be updated. update_mask: Field names of membership resource to be updated. release_track: The release_track used in the gcloud command. external_id: the unique id associated with the cluster, or None if it is not available. issuer_url: The discovery URL for the cluster's service account token issuer. oidc_jwks: The JSON Web Key Set string containing public keys for validating service account tokens. Set to None if the issuer_url is publicly-reachable. Still requires issuer_url to be set. Returns: The updated Membership resource. Raises: - apitools.base.py.HttpError: if the request returns an HTTP error - exceptions raised by waiter.WaitFor() """ client = gkehub_api_util.GetApiClientForTrack(release_track) messages = client.MESSAGES_MODULE request = messages.GkehubProjectsLocationsMembershipsPatchRequest( membership=membership, name=name, updateMask=update_mask) if release_track is not base.ReleaseTrack.GA: if issuer_url: request.membership.authority = messages.Authority( issuer=issuer_url) if release_track is base.ReleaseTrack.ALPHA: if oidc_jwks: request.membership.authority.oidcJwks = oidc_jwks.encode( 'utf-8') else: # If oidc_jwks is None, unset membership.oidc_jwks, and let the API # determine when that's an error, not the client, to avoid problems # like cl/339713504 fixed (see unsetting membership.authority, below). request.membership.authority.oidcJwks = None else: # if issuer_url is None, unset membership.authority to disable WI. request.membership.authority = None if external_id: request.membership.externalId = external_id op = client.projects_locations_memberships.Patch(request) op_resource = resources.REGISTRY.ParseRelativeName( op.name, collection='gkehub.projects.locations.operations') return waiter.WaitFor( waiter.CloudOperationPoller(client.projects_locations_memberships, client.projects_locations_operations), op_resource, 'Waiting for membership to be updated')
def WaitForOperation(operation, message, service, release_track, is_delete=False): """Waits for the given google.longrunning.Operation to complete. Args: operation: The operation to poll. message: String to display for default progress_tracker. service: The service to get the resource after the long running operation completes. release_track: base.ReleaseTrack object. is_delete: Bool indicating is Poller should fetch resource post operation. Raises: apitools.base.py.HttpError: if the request returns an HTTP error Returns: The created Environment resource. """ operation_ref = GetOperationResource(operation.name, release_track) client = GetClient(release_track) if is_delete: poller = waiter.CloudOperationPollerNoResources( client.projects_locations_operations) else: poller = waiter.CloudOperationPoller( service, client.projects_locations_operations) return waiter.WaitFor(poller, operation_ref, message)
def _WaitForOperation(client, operation, resource_type): """Waits for an operation to complete. Args: client: GAPIC API client, client used to make requests. operation: run_apps.v1alpha1.operation, object to wait for. resource_type: type, the expected type of resource response Returns: The resulting resource of input paramater resource_type. """ poller = waiter.CloudOperationPoller(resource_type, client.projects_locations_operations) operation_ref = resources.REGISTRY.ParseRelativeName( operation.name, collection='{}.projects.locations.operations'.format(API_NAME)) try: return poller.GetResult(waiter.PollUntilDone( poller, operation_ref, max_wait_ms=_POLLING_TIMEOUT_MS, wait_ceiling_ms=_RETRY_TIMEOUT_MS)) except waiter.OperationError: operation = poller.Poll(operation_ref) raise exceptions.IntegrationsOperationError( 'OperationError: code={0}, message={1}'.format( operation.error.code, encoding.Decode(operation.error.message)))
def CreateFeature(project, feature_id, **kwargs): """Creates a Feature resource in Hub. Args: project: the project in which to create the Feature feature_id: the value to use for the feature_id **kwargs: arguments for Feature object. For eg, multiclusterFeatureSpec Returns: the created Feature resource. Raises: - apitools.base.py.HttpError: if the request returns an HTTP error - exceptions raised by waiter.WaitFor() """ client = core_apis.GetClientInstance('gkehub', 'v1alpha1') messages = client.MESSAGES_MODULE request = messages.GkehubProjectsLocationsGlobalFeaturesCreateRequest( feature=messages.Feature(**kwargs), parent='projects/{}/locations/global'.format(project), featureId=feature_id, ) op = client.projects_locations_global_features.Create(request) op_resource = resources.REGISTRY.ParseRelativeName( op.name, collection='gkehub.projects.locations.operations') return waiter.WaitFor( waiter.CloudOperationPoller(client.projects_locations_global_features, client.projects_locations_operations), op_resource, 'Waiting for Feature to be created')
def Await(operation, message): """Wait for the specified operation.""" client = apis.GetClientInstance('spanner', 'v1') poller = waiter.CloudOperationPoller(client.projects_instances, client.projects_instances_operations) ref = resources.REGISTRY.ParseRelativeName( operation.name, collection='spanner.projects.instances.operations') return waiter.WaitFor(poller, ref, message)
def __init__(self, release_track=base.ReleaseTrack.GA): self.client = util.GetClientInstance(release_track) self.messages = util.GetMessagesModule(release_track) self.resourceless_waiter = waiter.CloudOperationPollerNoResources( operation_service=self.client.projects_locations_operations) self.feature_waiter = waiter.CloudOperationPoller( result_service=self.client.projects_locations_features, operation_service=self.client.projects_locations_operations)
def Run(self, args): """This is what gets called when the user runs this command.""" client = client_util.GetClientInstance() messages = client_util.GetMessagesModule() project = properties.VALUES.core.project.Get(required=True) parent = 'projects/%s/locations/%s' % (project, args.region) workflow_name = '%s/workflows/%s' % (parent, args.WORKFLOW_ID) run_workflow_req = messages.RunWorkflowRequest() # Add params ('key1=val1,key2=val2') to RunWorkflow request. if args.params: params = [] for key, value in args.params.items(): param = messages.Param( name=key, value=messages.ParamValue( type=messages.ParamValue.TypeValueValuesEnum('STRING'), stringVal=value, )) params.append(param) run_workflow_req.params = params # Call RunWorkflow. Initial not-Done LRO immediately returned. run_workflow_operation = client.projects_locations_workflows.Run( messages.CloudbuildProjectsLocationsWorkflowsRunRequest( name=workflow_name, runWorkflowRequest=run_workflow_req, )) run_workflow_operation_name = run_workflow_operation.name run_workflow_operation_ref = resources.REGISTRY.ParseRelativeName( run_workflow_operation_name, collection='cloudbuild.projects.locations.operations') # Wait for RunWorkflow LRO to be marked as Done. # Underlying, this also waits for the CreatePipelineRun LRO to be Done. waiter.WaitFor( waiter.CloudOperationPoller(client.projects_locations_workflows, client.projects_locations_operations), run_workflow_operation_ref, 'Running Workflow and Creating PipelineRun') # Re-fetch the RunWorkflow LRO now that it is done. run_workflow_operation_done = client.projects_locations_operations.Get( messages.CloudbuildProjectsLocationsOperationsGetRequest( name=run_workflow_operation_name)) # Extract the PipelineRunId from the RunWorkflowCustomOperationMetadata. pipeline_run_id = '' for additional_property in run_workflow_operation_done.metadata.additionalProperties: if additional_property.key == 'pipelineRunId': pipeline_run_id = additional_property.value.string_value pipeline_run_name = parent + '/pipelineRuns/' + pipeline_run_id # Log ran/created resources and return Done RunWorkflow LRO. log.status.Print('Ran workflow: {}'.format(workflow_name)) log.status.Print('Created pipeline run: {}'.format(pipeline_run_name)) return run_workflow_operation_done
def WaitForOperation(operation, resource): """Waits for the given google.longrunning.Operation to complete.""" operation_ref = resources.REGISTRY.Parse( operation.name, collection='dataplex.projects.locations.operations') poller = waiter.CloudOperationPoller( resource, GetClientInstance().projects_locations_operations) return waiter.WaitFor( poller, operation_ref, 'Waiting for [{0}] to finish'.format(operation_ref.RelativeName()))
def WaitForOperation(self, operation, message, is_delete=False): operation_ref = resources.REGISTRY.Parse( operation.name, collection='sddc.projects.locations.operations') if is_delete: poller = waiter.CloudOperationPollerNoResources( self.operations_service) else: poller = waiter.CloudOperationPoller(self.service, self.operations_service) return waiter.WaitFor(poller, operation_ref, message)
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Some value that we want to have printed later. """ client = cloudbuild_util.GetClientInstance() messages = cloudbuild_util.GetMessagesModule() config_id = args.CONFIG bbs = cloudbuild_util.BitbucketServerConfigFromArgs(args, True) parent = properties.VALUES.core.project.Get(required=True) # Get the bitbucket server config ref bbs_resource = resources.REGISTRY.Parse( None, collection='cloudbuild.projects.locations.bitbucketServerConfigs', api_version='v1', params={ 'projectsId': parent, # Use default region global until Proctor is fully regionalized. 'locationsId': cloudbuild_util.DEFAULT_REGION, 'bitbucketServerConfigsId': config_id, }) update_mask = cloudbuild_util.MessageToFieldPaths(bbs) req = messages.CloudbuildProjectsLocationsBitbucketServerConfigsPatchRequest( name=bbs_resource.RelativeName(), bitbucketServerConfig=bbs, updateMask=','.join(update_mask)) # Send the Update request updated_op = client.projects_locations_bitbucketServerConfigs.Patch( req) op_resource = resources.REGISTRY.ParseRelativeName( updated_op.name, collection='cloudbuild.projects.locations.operations') updated_bbs = waiter.WaitFor( waiter.CloudOperationPoller( client.projects_locations_bitbucketServerConfigs, client.projects_locations_operations), op_resource, 'Updating Bitbucket Server config') log.UpdatedResource(bbs_resource) return updated_bbs
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: The updated github enterprise resource. """ client = cloudbuild_util.GetClientInstance() messages = cloudbuild_util.GetMessagesModule() config_id = args.CONFIG ghe = cloudbuild_util.GitHubEnterpriseConfigFromArgs(args, True) parent = properties.VALUES.core.project.Get(required=True) # Get the github enterprise config ref ghe_resource = resources.REGISTRY.Parse( None, collection='cloudbuild.projects.githubEnterpriseConfigs', api_version='v1', params={ 'projectsId': parent, 'githubEnterpriseConfigsId': config_id, }) ghe.name = ghe_resource.RelativeName() update_mask = cloudbuild_util.MessageToFieldPaths(ghe) req = messages.CloudbuildProjectsGithubEnterpriseConfigsPatchRequest( name=ghe.name, gitHubEnterpriseConfig=ghe, updateMask=','.join(update_mask)) # Send the Update request updated_op = client.projects_githubEnterpriseConfigs.Patch(req) op_resource = resources.REGISTRY.ParseRelativeName( updated_op.name, collection='cloudbuild.projects.locations.operations') updated_ghe = waiter.WaitFor( waiter.CloudOperationPoller( client.projects_githubEnterpriseConfigs, client.projects_locations_operations), op_resource, 'Updating GitHub Enterprise Config') log.UpdatedResource(ghe_resource) return updated_ghe
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Some value that we want to have printed later. """ client = cloudbuild_util.GetClientInstance() messages = cloudbuild_util.GetMessagesModule() bbs = cloudbuild_util.BitbucketServerConfigFromArgs(args, False) parent = properties.VALUES.core.project.Get(required=True) # Use default region global until Proctor is fully regionalized. bbs_region = cloudbuild_util.DEFAULT_REGION # Get the parent project ref parent_resource = resources.REGISTRY.Create( collection='cloudbuild.projects.locations', projectsId=parent, locationsId=bbs_region) # Send the Create request created_op = client.projects_locations_bitbucketServerConfigs.Create( messages. CloudbuildProjectsLocationsBitbucketServerConfigsCreateRequest( parent=parent_resource.RelativeName(), bitbucketServerConfig=bbs, bitbucketServerConfigId=args.name)) op_resource = resources.REGISTRY.ParseRelativeName( created_op.name, collection='cloudbuild.projects.locations.operations') created_config = waiter.WaitFor( waiter.CloudOperationPoller( client.projects_locations_bitbucketServerConfigs, client.projects_locations_operations), op_resource, 'Creating Bitbucket Server config') bbs_resource = resources.REGISTRY.Parse( None, collection='cloudbuild.projects.locations.bitbucketServerConfigs', api_version='v1', params={ 'projectsId': parent, 'locationsId': bbs_region, 'bitbucketServerConfigsId': created_config.name, }) log.CreatedResource(bbs_resource) return created_config
def Patch(self, level_ref, description=None, title=None, combine_function=None, basic_level_conditions=None): """Patch an access level. Args: level_ref: resources.Resource, reference to the level to patch description: str, description of the level or None if not updating title: str, title of the level or None if not updating combine_function: ZoneTypeValueValuesEnum, combine function enum value of the level or None if not updating basic_level_conditions: list of Condition, the conditions for a basic level or None if not updating Returns: AccessLevel, the updated access level """ level = self.messages.AccessLevel() update_mask = [] if description is not None: update_mask.append('description') level.description = description if title is not None: update_mask.append('title') level.title = title if combine_function is not None: update_mask.append('basic.combiningFunction') level.basic = level.basic or self.messages.BasicLevel() level.basic.combiningFunction = combine_function if basic_level_conditions is not None: update_mask.append('basic.conditions') level.basic = level.basic or self.messages.BasicLevel() level.basic.conditions = basic_level_conditions update_mask.sort() # For ease-of-testing m = self.messages request_type = m.AccesscontextmanagerAccessPoliciesAccessLevelsPatchRequest request = request_type( accessLevel=level, name=level_ref.RelativeName(), updateMask=','.join(update_mask), ) operation = self.client.accessPolicies_accessLevels.Patch(request) poller = waiter.CloudOperationPoller( self.client.accessPolicies_accessLevels, self.client.operations) operation_ref = resources.REGISTRY.Parse( operation.name, collection='accesscontextmanager.operations') return waiter.WaitFor( poller, operation_ref, 'Waiting for PATCH operation [{}]'.format(operation_ref.Name()))
def CreateMembership(project, membership_id, description, gke_cluster_self_link=None, external_id=None, release_track=None): """Creates a Membership resource in the GKE Hub API. Args: project: the project in which to create the membership membership_id: the value to use for the membership_id description: the value to put in the description field gke_cluster_self_link: the selfLink for the cluster if it is a GKE cluster, or None if it is not external_id: the unique id associated with the cluster, or None if it is not available. release_track: the release_track used in the gcloud command, or None if it is not available. Returns: the created Membership resource. Raises: - apitools.base.py.HttpError: if the request returns an HTTP error - exceptions raised by waiter.WaitFor() """ client = gkehub_api_util.GetApiClientForTrack(release_track) messages = client.MESSAGES_MODULE parent_ref = ParentRef(project, 'global') request = messages.GkehubProjectsLocationsMembershipsCreateRequest( membership=messages.Membership(description=description), parent=parent_ref, membershipId=membership_id, ) if gke_cluster_self_link: endpoint = messages.MembershipEndpoint(gkeCluster=messages.GkeCluster( resourceLink=gke_cluster_self_link)) request.membership.endpoint = endpoint if external_id: request.membership.externalId = external_id op = client.projects_locations_memberships.Create(request) op_resource = resources.REGISTRY.ParseRelativeName( op.name, collection='gkehub.projects.locations.operations') return waiter.WaitFor( waiter.CloudOperationPoller(client.projects_locations_memberships, client.projects_locations_operations), op_resource, 'Waiting for membership to be created')
def WaitForOperation(operation, message, service): """Waits for the given google.longrunning.Operation to complete. Args: operation: The operation to poll. message: String to display for default progress_tracker. service: The service to get the resource after the long running operation completes. Raises: apitools.base.py.HttpError: if the request returns an HTTP error Returns: The TagKey or TagValue resource. """ poller = waiter.CloudOperationPoller(service, tags.OperationsService()) return _WaitForOperation(operation, message, poller)
def UpdateFeature(project, feature_id, feature_display_name, mask, **kwargs): """Updates a Feature resource in Hub. Args: project: the project in which to update the Feature feature_id: the value to use for the feature_id feature_display_name: the FEATURE_DISPLAY_NAME of this Feature mask: resource fields to be updated. For eg. multiclusterFeatureSpec **kwargs: arguments for Feature object. For eg, multiclusterFeatureSpec Returns: the updated Feature resource. Raises: - apitools.base.py.HttpError: if the request returns an HTTP error - exceptions raised by waiter.WaitFor() """ client = core_apis.GetClientInstance('gkehub', 'v1alpha1') messages = client.MESSAGES_MODULE request = messages.GkehubProjectsLocationsGlobalFeaturesPatchRequest( name='projects/{0}/locations/global/features/{1}'.format( project, feature_id), updateMask=mask, feature=messages.Feature(**kwargs), ) try: op = client.projects_locations_global_features.Patch(request) except apitools_exceptions.HttpUnauthorizedError as e: raise exceptions.Error( 'You are not authorized to see the status of {} ' 'feature from project [{}]. Underlying error: {}'.format( feature_display_name, project, e)) except apitools_exceptions.HttpNotFoundError as e: raise exceptions.Error( '{} Feature for project [{}] is not enabled'.format( feature_display_name, project)) op_resource = resources.REGISTRY.ParseRelativeName( op.name, collection='gkehub.projects.locations.operations') result = waiter.WaitFor( waiter.CloudOperationPoller(client.projects_locations_global_features, client.projects_locations_operations), op_resource, 'Waiting for Feature {} to be updated'.format(feature_display_name)) return result
def WaitForOperation(operation, message): """Waits for the given google.longrunning.Operation to complete. Args: operation: The operation to poll. message: String to display for default progress_tracker. Raises: apitools.base.py.HttpError: if the request returns an HTTP error Returns: The created Label Keyresource. """ operation_ref = resources.REGISTRY.Parse( operation.name, collection='labelmanager.operations') poller = waiter.CloudOperationPoller(labelmanager.LabelKeysService(), labelmanager.OperationsService()) return waiter.WaitFor(poller, operation_ref, message)
def WaitForOperation(self, operation, progress_message): """Waits for the given google.longrunning.Operation to complete. Args: operation: The operation to poll. progress_message: String to display for default progress_tracker. Raises: apitools.base.py.HttpError: if the request returns an HTTP error Returns: The created Environment resource. """ operation_ref = self.GetOperationResource(operation.name) poller = waiter.CloudOperationPoller( self.client.organizations_locations_workloads, self.client.organizations_locations_operations) return waiter.WaitFor(poller, operation_ref, progress_message)
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Some value that we want to have printed later. """ client = cloudbuild_util.GetClientInstance() messages = cloudbuild_util.GetMessagesModule() ghe = cloudbuild_util.GitHubEnterpriseConfigFromArgs(args, False) parent = properties.VALUES.core.project.Get(required=True) # Get the parent project ref parent_resource = resources.REGISTRY.Create( collection='cloudbuild.projects', projectId=parent) # Send the Create request created_op = client.projects_githubEnterpriseConfigs.Create( messages.CloudbuildProjectsGithubEnterpriseConfigsCreateRequest( parent=parent_resource.RelativeName(), gitHubEnterpriseConfig=ghe)) op_resource = resources.REGISTRY.ParseRelativeName( created_op.name, collection='cloudbuild.projects.locations.operations') created_config = waiter.WaitFor( waiter.CloudOperationPoller( client.projects_githubEnterpriseConfigs, client.projects_locations_operations), op_resource, 'Creating github enterprise config') ghe_resource = resources.REGISTRY.Parse( None, collection='cloudbuild.projects.githubEnterpriseConfigs', api_version='v1', params={ 'projectsId': parent, 'githubEnterpriseConfigsId': created_config.name, }) log.CreatedResource(ghe_resource) return created_config
def Run(self, args): realm_configs = args.add_realm content_ref = args.CONCEPTS.content.Parse() content_name = content_ref.RelativeName() location = content_ref.locationsId instance_name = args.instance version = args.version client = api_util.GetClient() result_operation = instances.Create(instance_name, content_name, location, version, realm_configs) log.status.Print( 'Create request issued for: [{}]'.format(instance_name)) if args.async_: log.status.Print('Check operation [{}] for status.\n'.format( result_operation.name)) return result_operation operation_resource = resources.REGISTRY.Parse( result_operation.name, collection='stream.projects.locations.operations', api_version='v1alpha1') created_instance = waiter.WaitFor( waiter.CloudOperationPoller( client.projects_locations_streamInstances, client.projects_locations_operations), operation_resource, 'Waiting for operation [{}] to complete'.format( result_operation.name)) instance_resource = resources.REGISTRY.Parse( None, collection='stream.projects.locations.streamInstances', api_version='v1alpha1', params={ 'projectsId': properties.VALUES.core.project.Get(required=True), 'locationsId': 'global', 'streamInstancesId': instance_name }) log.CreatedResource(instance_resource) return created_instance
def WaitForDeploymentOperation(operation, progress_message): """Waits for the given google.longrunning.Operation to complete. Args: operation: The operation to poll. progress_message: String to display for default progress_tracker. Raises: apitools.base.py.HttpError: if the request returns an HTTP error Returns: The created Deployment resource. """ client = GetClientInstance() operation_ref = resources.REGISTRY.ParseRelativeName( operation.name, collection='config.projects.locations.operations') poller = waiter.CloudOperationPoller(client.projects_locations_deployments, client.projects_locations_operations) return waiter.WaitFor(poller, operation_ref, progress_message)
def testOperationError(self): with api_mock.Client(self.client_class) as client: result_service = getattr(client, self.RESULT_SERVICE) operation_service = client.operations operation_ref = resources.REGISTRY.Create( self.OPERATIONS_COLLECTION, operationsId='operationX') self.ExpectOperation(operation_service, 'operations/operationX', result_service=None, result_name='theinstance', error_msg='Something happened') poller = waiter.CloudOperationPoller(result_service, operation_service) with self.assertRaisesRegex(waiter.OperationError, r'Something happened'): waiter.WaitFor(poller=poller, operation_ref=operation_ref, message='Making it')