def CreateBackupAndWaitForLRO(backup_ref,
                              description=None,
                              labels=None,
                              retain_days=None,
                              delete_lock_days=None,
                              client=None):
  """Creates a backup resource and wait for the resulting LRO to complete."""
  if client is None:
    client = GetClientInstance()
  operation = CreateBackup(
      backup_ref,
      description=description,
      labels=labels,
      retain_days=retain_days,
      delete_lock_days=delete_lock_days,
      client=client)
  operation_ref = resources.REGISTRY.ParseRelativeName(
      operation.name, 'gkebackup.projects.locations.operations')

  log.CreatedResource(
      operation_ref.RelativeName(),
      kind='backup {0}'.format(backup_ref.Name()),
      is_async=True)

  poller = waiter.CloudOperationPollerNoResources(
      client.projects_locations_operations)
  return waiter.WaitFor(poller, operation_ref,
                        'Creating backup {0}'.format(backup_ref.Name()))
def CreateRestoreAndWaitForLRO(restore_ref,
                               backup,
                               description=None,
                               labels=None,
                               client=None):
  """Creates a restore resource by calling Backup for GKE service."""
  if client is None:
    client = GetClientInstance()
  operation = CreateRestore(
      restore_ref,
      backup=backup,
      description=description,
      labels=labels,
      client=client)
  operation_ref = resources.REGISTRY.ParseRelativeName(
      operation.name, 'gkebackup.projects.locations.operations')

  log.CreatedResource(
      operation_ref.RelativeName(),
      kind='restore {0}'.format(restore_ref.Name()),
      is_async=True)

  poller = waiter.CloudOperationPollerNoResources(
      client.projects_locations_operations)
  return waiter.WaitFor(poller, operation_ref,
                        'Creating restore {0}'.format(restore_ref.Name()))
  def Run(self, args):
    """Run package import command."""
    client = apis.GetClientInstance('artifactregistry', self.api_version)
    messages = client.MESSAGES_MODULE

    for gcs_source in args.gcs_source:
      if '*' in gcs_source and not gcs_source.endswith('*'):
        raise exceptions.InvalidArgumentException(
            'GCS_SOURCE', 'Wildcards must be at the end of the GCS path.')

    repo_ref = args.CONCEPTS.repository.Parse()
    gcs_source = messages.ImportYumArtifactsGcsSource(
        uris=args.gcs_source,
        useWildcards=True)
    import_request = messages.ImportYumArtifactsRequest(
        gcsSource=gcs_source)

    request = messages.ArtifactregistryProjectsLocationsRepositoriesYumArtifactsImportRequest(
        importYumArtifactsRequest=import_request,
        parent=repo_ref.RelativeName())

    op = client.projects_locations_repositories_yumArtifacts.Import(request)

    op_ref = resources.REGISTRY.ParseRelativeName(
        op.name, collection='artifactregistry.projects.locations.operations')

    if args.async_:
      return op_ref
    else:
      result = waiter.WaitFor(
          waiter.CloudOperationPollerNoResources(
              client.projects_locations_operations),
          op_ref, 'Importing package(s)')

      return result
예제 #4
0
def Await(operation, progress_message):
    """Waits for operation to complete while displaying in-progress indicator.

  Args:
    operation: The Operation resource.
    progress_message: The message to display with the in-progress indicator.

  Returns:
    The resource that is the result of the operation.

  Raises:
    OperationError: if the operation did not complete successfully
  """
    if operation.done:
        if operation.error:
            raise OperationError(operation.error.message)
        return operation.response

    operation_ref = GetOperationRef(operation)
    poller = waiter.CloudOperationPollerNoResources(
        base.GetClientInstance().projects_locations_operations)
    try:
        return waiter.WaitFor(poller, operation_ref, progress_message)
    except waiter.TimeoutError:
        raise OperationTimeoutError(
            'Requested action timed out. Please run the describe command on your resource to see if changes were successful, or try again in a few minutes.'
        )
예제 #5
0
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)
예제 #6
0
def WaitForDeletePreviewOperation(operation):
    """Waits for the given "preview delete" LRO to complete.

  Args:
    operation: the operation to poll.

  Raises:
    apitools.base.py.HttpError: if the request returns an HTTP error

  Returns:
    A messages.Preview resource.
  """
    client = GetClientInstance()
    operation_ref = resources.REGISTRY.ParseRelativeName(
        operation.name, collection='config.projects.locations.operations')
    poller = waiter.CloudOperationPollerNoResources(
        client.projects_locations_operations)
    progress_message = 'Previewing the deployment deletion'
    result = waiter.WaitFor(poller,
                            operation_ref,
                            progress_message,
                            max_wait_ms=_MAX_WAIT_TIME_MS,
                            wait_ceiling_ms=_WAIT_CEILING_MS)
    json = encoding.MessageToJson(result)
    messages = GetMessagesModule()
    return encoding.JsonToMessage(messages.Preview, json)
예제 #7
0
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)
예제 #8
0
    def Run(self, args):
        volume = args.CONCEPTS.volume.Parse()
        client = BmsClient()
        op_ref = client.RestoreVolumeSnapshot(volume, args.snapshot)

        if op_ref.done:
            log.RestoredResource(volume.Name(), kind='volume')
            return op_ref

        if args.async_:
            log.status.Print(
                'Restore request issued for [{}]\nCheck operation '
                '[{}] for status.'.format(volume.Name(), op_ref.name))
            return op_ref

        op_resource = resources.REGISTRY.ParseRelativeName(
            op_ref.name,
            collection='baremetalsolution.operations',
            api_version='v1')
        poller = waiter.CloudOperationPollerNoResources(
            client.operation_service)
        res = waiter.WaitFor(
            poller, op_resource,
            'Waiting for operation [{}] to complete'.format(op_ref.name))
        log.RestoredResource(volume.Name(), kind='volume')
        return res
예제 #9
0
    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)
예제 #10
0
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(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 WaitForCreateKrmApiHostOperation(
        operation,
        progress_message='Waiting for cluster to create',
        max_wait_ms=_MAX_WAIT_TIME_MS):
    """Waits for the given "create" LRO to complete.

  Args:
    operation: the operation to poll.
    progress_message: the message to display while waiting for the operation.
    max_wait_ms: number of ms to wait before raising TimeoutError.

  Raises:
    apitools.base.py.HttpError: if the request returns an HTTP error.

  Returns:
    A messages.KrmApiHost resource.
  """
    client = GetClientInstance()
    operation_ref = resources.REGISTRY.ParseRelativeName(
        operation.name,
        collection='krmapihosting.projects.locations.operations')
    poller = waiter.CloudOperationPollerNoResources(
        client.projects_locations_operations)
    result = waiter.WaitFor(poller,
                            operation_ref,
                            progress_message,
                            max_wait_ms=max_wait_ms,
                            wait_ceiling_ms=_WAIT_CEILING_MS)
    json = encoding.MessageToJson(result)
    messages = GetMessagesModule()
    return encoding.JsonToMessage(messages.KrmApiHost, json)
예제 #13
0
def WaitForOperation(response, api_version):
  operation_ref = resources.REGISTRY.ParseRelativeName(
      response.name, collection=OPERATIONS_COLLECTION)
  return waiter.WaitFor(
      waiter.CloudOperationPollerNoResources(
          GetClient(api_version).projects_locations_operations), operation_ref,
      'Waiting for [{0}] to finish'.format(operation_ref.Name()))
예제 #14
0
  def WaitOperation(self, operation_ref):
    """Waits for a long-running operation.

    Args:
      operation_ref: the operation reference.

    Raises:
      waiter.OperationError: if the operation contains an error.

    Returns:
      messages.AnnotateVideoResponse, the final result of the operation.
    """
    message = 'Waiting for operation [{}] to complete'.format(
        operation_ref.RelativeName())
    return waiter.WaitFor(
        waiter.CloudOperationPollerNoResources(
            self.search_client.operations,
            # TODO(b/62478975): remove this workaround when operation resources
            # are compatible with gcloud parsing.
            get_name_func=lambda x: x.RelativeName()),
        operation_ref,
        message,
        exponential_sleep_multiplier=2.0,
        sleep_ms=500,
        wait_ceiling_ms=20000)
예제 #15
0
  def WaitForOperation(self, operation):
    """Wait until the operation is complete or times out.

    Args:
      operation: The operation resource to wait on.

    Returns:
      The operation resource when it has completed.

    Raises:
      OperationTimeoutError: When the operation polling times out.
      OperationError: When the operation completed with an error.
    """
    poller = waiter.CloudOperationPollerNoResources(self._service)
    operation_ref = resources.REGISTRY.Parse(
        operation.name, collection='edgeml.operations')
    operation_type = operation_ref.Name().split('/')[0]
    message = _WAITING_MESSAGE.get(operation_type, 'Waiting for operation [{}]')
    return waiter.WaitFor(
        poller,
        operation_ref,
        message,
        pre_start_sleep_ms=1000,
        max_wait_ms=_MAX_WAIT_TIME_MS,
        exponential_sleep_multiplier=None,
        jitter_ms=None,
        wait_ceiling_ms=None,
        sleep_ms=5000)
예제 #16
0
def WaitForOperation(operation):
    """Waits for the given google.longrunning.Operation to complete."""
    operation_ref = resources.REGISTRY.Parse(
        operation.name, collection='datastore.projects.operations')
    poller = waiter.CloudOperationPollerNoResources(GetService())
    return waiter.WaitFor(
        poller, operation_ref,
        'Waiting for [{0}] to finish'.format(operation_ref.RelativeName()))
 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)
예제 #18
0
 def WaitForOperation(self, operation, message):
     registry = resources.REGISTRY.Clone()
     registry.RegisterApiByName('iamassist', 'v1alpha3')
     operation_ref = registry.Parse(operation.name,
                                    collection='iamassist.operations')
     poller = waiter.CloudOperationPollerNoResources(self._service)
     return waiter.WaitFor(poller,
                           operation_ref,
                           message,
                           wait_ceiling_ms=_MAX_WAIT_TIME_MS)
예제 #19
0
 def WaitForOperation(self, operation, message):
     registry = resources.REGISTRY.Clone()
     registry.RegisterApiByName('policysimulator', self._api_version)
     operation_ref = registry.Parse(operation.name,
                                    collection='policysimulator.operations')
     poller = waiter.CloudOperationPollerNoResources(self._service)
     return waiter.WaitFor(poller,
                           operation_ref,
                           message,
                           wait_ceiling_ms=_MAX_WAIT_TIME_MS)
예제 #20
0
 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)
예제 #21
0
def WaitForOperation(operation):
    """Waits for the given Operation to complete."""
    operation_ref = resources.REGISTRY.Parse(
        operation.name,
        collection='firestore.projects.databases.operations',
        api_version=OPERATIONS_API_VERSION)
    poller = waiter.CloudOperationPollerNoResources(GetService(),
                                                    lambda x: x.RelativeName())
    return waiter.WaitFor(
        poller, operation_ref,
        'Waiting for [{0}] to finish'.format(operation_ref.RelativeName()))
예제 #22
0
 def Commit(self, policy_ref, etag):
   commit_req = self.messages.CommitServicePerimetersRequest(etag=etag)
   req = self.messages.AccesscontextmanagerAccessPoliciesServicePerimetersCommitRequest(
       parent=policy_ref.RelativeName(),
       commitServicePerimetersRequest=commit_req)
   operation = self.client.accessPolicies_servicePerimeters.Commit(req)
   poller = waiter.CloudOperationPollerNoResources(self.client.operations)
   operation_ref = core_resources.REGISTRY.Parse(
       operation.name, collection='accesscontextmanager.operations')
   return waiter.WaitFor(
       poller, operation_ref,
       'Waiting for COMMIT operation [{}]'.format(operation_ref.Name()))
예제 #23
0
  def WaitFor(self, operation):
    """Waits until the given long-running operation is complete.

    Args:
      operation: the long-running operation to wait for.

    Returns:
      The long-running operation's response.
    """
    poller = waiter.CloudOperationPollerNoResources(self._operation_service)
    operation_ref = resources.REGISTRY.Parse(
        operation.name, collection='eventarc.projects.locations.operations')
    message = 'Waiting for operation [{}] to complete'.format(
        operation_ref.Name())
    return waiter.WaitFor(poller, operation_ref, message)
예제 #24
0
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
  """
    op_service = ar_requests.GetClient().projects_locations_operations
    op_resource = resources.REGISTRY.ParseRelativeName(
        operation.name,
        collection="artifactregistry.projects.locations.operations")
    poller = waiter.CloudOperationPollerNoResources(op_service)
    waiter.WaitFor(poller, op_resource, message)
예제 #25
0
  def WaitForOperation(self, operation_ref, message):
    """Waits until operation is complete.

    Args:
      operation_ref: a Resource reference to a
        certificatemanager.projects.locations.operations resource to wait for.
      message: str, message to be displayed while waiting.

    Returns:
      Operation result.
    """
    return waiter.WaitFor(
        waiter.CloudOperationPollerNoResources(self._service),
        operation_ref,
        message,
        wait_ceiling_ms=15 * 1000)
예제 #26
0
    def WaitForOperation(self, operation_ref):
        """Waits on the long-running operation until the done field is True.

    Args:
      operation_ref: the operation reference.

    Raises:
      waiter.OperationError: if the operation contains an error.

    Returns:
      the 'response' field of the Operation.
    """
        return waiter.WaitFor(
            waiter.CloudOperationPollerNoResources(
                self.client.projects_locations_operations), operation_ref,
            'Waiting for [{0}] to finish'.format(operation_ref.Name()))
예제 #27
0
def Await(operation, progress_message):
    """Waits for operation to complete while displaying in-progress indicator.

  Args:
    operation: The Operation resource.
    progress_message: The message to display with the in-progress indicator.

  Returns:
    The resource that is the result of the operation.
  """
    if operation.done:
        return operation.response

    operation_ref = GetOperationRef(operation)
    poller = waiter.CloudOperationPollerNoResources(
        base.GetClientInstance().projects_locations_operations)
    return waiter.WaitFor(poller, operation_ref, progress_message)
예제 #28
0
  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.
    """

    wp_region = args.region

    release_track = self.ReleaseTrack()
    client = cloudbuild_util.GetClientInstance(release_track)
    messages = cloudbuild_util.GetMessagesModule(release_track)

    parent = properties.VALUES.core.project.Get(required=True)

    wp_name = args.WORKER_POOL

    # Get the workerpool ref
    wp_resource = resources.REGISTRY.Parse(
        None,
        collection='cloudbuild.projects.locations.workerPools',
        api_version=cloudbuild_util.RELEASE_TRACK_TO_API_VERSION[release_track],
        params={
            'projectsId': parent,
            'locationsId': wp_region,
            'workerPoolsId': wp_name,
        })

    # Send the Delete request
    deleted_op = client.projects_locations_workerPools.Delete(
        messages.CloudbuildProjectsLocationsWorkerPoolsDeleteRequest(
            name=wp_resource.RelativeName()))

    op_resource = resources.REGISTRY.ParseRelativeName(
        deleted_op.name, collection='cloudbuild.projects.locations.operations')
    waiter.WaitFor(
        waiter.CloudOperationPollerNoResources(
            client.projects_locations_operations), op_resource,
        'Deleting worker pool')

    log.DeletedResource(wp_resource)
예제 #29
0
def WaitForOperation(operation):
  """Silently waits for the given google.longrunning.Operation to complete.

  Args:
    operation: The operation to poll.

  Raises:
    apitools.base.py.HttpError: if the request returns an HTTP error

  Returns:
    The response field of the completed operation.
  """
  op_service = ods_util.GetClient().projects_locations_operations
  op_resource = resources.REGISTRY.ParseRelativeName(
      operation.name,
      collection='ondemandscanning.projects.locations.operations')
  poller = waiter.CloudOperationPollerNoResources(op_service)
  return waiter.PollUntilDone(poller, op_resource)
    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:
      Nothing on success.
    """

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        parent = properties.VALUES.core.project.Get(required=True)

        config_id = args.CONFIG

        # 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,
            })

        # Send the Delete request
        deleted_op = client.projects_locations_bitbucketServerConfigs.Delete(
            messages.
            CloudbuildProjectsLocationsBitbucketServerConfigsDeleteRequest(
                name=bbs_resource.RelativeName()))
        op_resource = resources.REGISTRY.ParseRelativeName(
            deleted_op.name,
            collection='cloudbuild.projects.locations.operations')
        waiter.WaitFor(
            waiter.CloudOperationPollerNoResources(
                client.projects_locations_operations), op_resource,
            'Deleting Bitbucket Server config')
        log.DeletedResource(bbs_resource)