def WaitForOperation(client, messages, operation_name, project, operation_description, timeout=None): """Wait for an operation to complete. Polls the operation requested approximately every second, showing a progress indicator. Returns when the operation has completed. Args: client: Object to make requests with messages: Object to build requests with operation_name: The name of the operation to wait on, as returned by operations.list. project: The name of the project that this operation belongs to. operation_description: A short description of the operation to wait on, such as 'create' or 'delete'. Will be displayed to the user. timeout: Optional (approximate) timeout in seconds, after which wait will return failure. Raises: HttpException: A http error response was received while executing api request. Will be raised if the operation cannot be found. OperationError: The operation finished with error(s). OperationTimeOutError: The operation exceeded the timeout without completing. """ ticks = 0 message = ('Waiting for ' + ('{0} '.format(operation_description) if operation_description else '') + operation_name) with progress_tracker.ProgressTracker(message, autotick=False) as ticker: while timeout is None or ticks < timeout: ticks += 1 try: operation = client.operations.Get( messages.DeploymentmanagerOperationsGetRequest( project=project, operation=operation_name, ) ) except apitools_exceptions.HttpError as error: raise api_exceptions.HttpException(error, HTTP_ERROR_FORMAT) ticker.Tick() # Operation status will be one of PENDING, RUNNING, DONE if operation.status == 'DONE': if operation.error: raise exceptions.OperationError( 'Error in Operation ' + operation_name + ':\n' + GetOperationError(operation.error)) else: # Operation succeeded return time.sleep(1) # wait one second and try again # Timeout exceeded raise exceptions.OperationTimeoutError( 'Wait for Operation {0} exceeded {1} second timeout.'.format( operation_name, timeout))
def _RaiseTimeout(): raise exceptions.OperationTimeoutError( 'Variable did not change prior to timeout.', exit_code=2)