예제 #1
0
  def Run(self, args):
    """Run 'deployments create'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      If --async=true, returns Operation to poll.
      Else, returns a struct containing the list of resources and list of
        outputs in the deployment.

    Raises:
      HttpException: An http error response was received while executing api
          request.
      ToolException: Config file could not be read or parsed, or the deployment
          creation operation encountered an error.
    """
    client = self.context['deploymentmanager-client']
    messages = self.context['deploymentmanager-messages']
    project = properties.VALUES.core.project.Get(required=True)

    deployment = messages.Deployment(
        name=args.deployment_name,
        target=importer.BuildTargetConfig(
            messages, args.config, args.properties),
    )
    if args.description:
      deployment.description = args.description

    try:
      operation = client.deployments.Insert(
          messages.DeploymentmanagerDeploymentsInsertRequest(
              project=project,
              deployment=deployment,
              preview=args.preview,
          )
      )
    except apitools_exceptions.HttpError as error:
      raise exceptions.HttpException(dm_v2_util.GetError(error))
    if args.async:
      return operation
    else:
      op_name = operation.name
      try:
        dm_v2_util.WaitForOperation(op_name, project, self.context, 'create',
                                    OPERATION_TIMEOUT)
        log.status.Print('Create operation ' + op_name
                         + ' completed successfully.')
      except exceptions.ToolException:
        # Operation timed out or had errors. Print this warning, then still
        # show whatever operation can be gotten.
        log.error('Create operation ' + op_name
                  + ' has errors or failed to complete within '
                  + str(OPERATION_TIMEOUT) + ' seconds.')
      except apitools_exceptions.HttpError as error:
        raise exceptions.HttpException(dm_v2_util.GetError(error))

      return dm_v2_util.FetchResourcesAndOutputs(client, messages, project,
                                                 args.deployment_name)
예제 #2
0
    def Run(self, args):
        """Run 'manifests describe'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      The requested manifest.

    Raises:
      HttpException: An http error response was received while executing api
          request.
    """
        client = self.context['deploymentmanager-client']
        messages = self.context['deploymentmanager-messages']
        project = properties.VALUES.core.project.Get(required=True)

        try:
            return client.manifests.Get(
                messages.DeploymentmanagerManifestsGetRequest(
                    project=project,
                    deployment=args.deployment,
                    manifest=args.manifest,
                ))
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(dm_v2_util.GetError(error))
예제 #3
0
def YieldWithHttpExceptions(generator):
    """Wraps generators to translate HttpErrors into HttpExceptions."""
    try:
        for y in generator:
            yield y
    except apitools_exceptions.HttpError as error:
        raise exceptions.HttpException(dm_v2_util.GetError(error))
예제 #4
0
def BuildTargetConfigFromManifest(client,
                                  messages,
                                  project_id,
                                  deployment_id,
                                  manifest_id,
                                  properties=None):
    """Construct a TargetConfig from a manifest of a previous deployment.

  Args:
    client: Deployment Manager v2 API client.
    messages: Object with v2 API messages.
    project_id: Project for this deployment. This is used when pulling the
        the existing manifest.
    deployment_id: Deployment used to pull retrieve the manifest.
    manifest_id: The manifest to pull down for constructing the target.
    properties: Dictionary of properties, only used if the manifest has a
        single resource. Properties will override only. If the manifest
        has properties which do not exist in the properties hash will remain
        unchanged.

  Returns:
    TargetConfig containing the contents of the config file and the names and
    contents of any imports.

  Raises:
    HttpException: in the event that there is a failure to pull the manifest
        from deployment manager
    DeploymentManagerError: When the manifest being revived has more than one
        resource
  """
    try:
        manifest = client.manifests.Get(
            messages.DeploymentmanagerManifestsGetRequest(
                project=project_id,
                deployment=deployment_id,
                manifest=manifest_id,
            ))
        config_file = manifest.config
        imports = manifest.imports
    except apitools_exceptions.HttpError as error:
        raise exceptions.HttpException(dm_v2_util.GetError(error))

    # If properties were specified, then we need to ensure that the
    # configuration in the manifest retrieved has only a single resource.
    if properties:
        config_yaml = yaml.load(config_file.content)
        if len(config_yaml['resources']) != 1:
            raise DeploymentManagerError(
                'Manifest reuse with properties requires '
                'there only be a single resource.')
        single_resource = config_yaml['resources'][0]
        if not single_resource.has_key('properties'):
            single_resource['properties'] = {}
        existing_properties = single_resource['properties']
        for key, value in properties.iteritems():
            existing_properties[key] = value
        config_file.content = yaml.dump(config_yaml, default_flow_style=False)

    return messages.TargetConfiguration(config=config_file, imports=imports)
예제 #5
0
    def Run(self, args):
        """Run 'deployments describe'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      The requested Deployment.

    Raises:
      HttpException: An http error response was received while executing api
          request.
    """
        client = self.context['deploymentmanager-client']
        messages = self.context['deploymentmanager-messages']
        project = properties.VALUES.core.project.Get(required=True)

        try:
            deployment = client.deployments.Get(
                messages.DeploymentmanagerDeploymentsGetRequest(
                    project=project, deployment=args.deployment_name))
        except apitools_exceptions.HttpError as error:
            raise exceptions.HttpException(dm_v2_util.GetError(error))

        # Get resources belonging to the deployment to display
        project = properties.VALUES.core.project.Get(required=True)
        try:
            response = client.resources.List(
                messages.DeploymentmanagerResourcesListRequest(
                    project=project, deployment=deployment.name))
            resources = response.resources
        except apitools_exceptions.HttpError:
            # Couldn't get resources, skip adding them to the table.
            # TODO(user): Why not raise HTTP exception here?
            resources = None

        outputs = []

        manifest = dm_v2_util.ExtractManifestName(deployment)

        if manifest:
            manifest_response = client.manifests.Get(
                messages.DeploymentmanagerManifestsGetRequest(
                    project=project,
                    deployment=args.deployment_name,
                    manifest=manifest,
                ))
            outputs = dm_v2_util.FlattenLayoutOutputs(manifest_response.layout)

        return _Results(deployment, resources, outputs)
예제 #6
0
파일: delete.py 프로젝트: TobiahRex/Wingman
    def Run(self, args):
        """Run 'deployments delete'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      If --async=true, returns Operation to poll.
      Else, returns boolean indicating whether insert operation succeeded.

    Raises:
      HttpException: An http error response was received while executing api
          request.
      ToolException: The deployment deletion operation encountered an error.
    """
        client = self.context['deploymentmanager-client']
        messages = self.context['deploymentmanager-messages']
        project = properties.VALUES.core.project.Get(required=True)

        prompt_message = ('The following deployments will be deleted:\n- ' +
                          '\n- '.join(args.deployment_name))
        if not args.quiet:
            if not console_io.PromptContinue(message=prompt_message,
                                             default=False):
                raise exceptions.ToolException('Deletion aborted by user.')

        operations = []
        for deployment_name in args.deployment_name:
            try:
                operation = client.deployments.Delete(
                    messages.DeploymentmanagerDeploymentsDeleteRequest(
                        project=project,
                        deployment=deployment_name,
                    ))
            except apitools_exceptions.HttpError as error:
                raise exceptions.HttpException(dm_v2_util.GetError(error))
            if args. async:
                operations.append(operation)
            else:
                op_name = operation.name
                try:
                    dm_v2_util.WaitForOperation(client, messages, op_name,
                                                project, 'delete',
                                                OPERATION_TIMEOUT)
                    log.status.Print('Delete operation ' + op_name +
                                     ' completed successfully.')
                except (exceptions.ToolException, DeploymentManagerError):
                    log.error('Delete operation ' + op_name +
                              ' has errors or failed to complete within in ' +
                              str(OPERATION_TIMEOUT) + ' seconds.')
                except apitools_exceptions.HttpError as error:
                    raise exceptions.HttpException(dm_v2_util.GetError(error))
                try:
                    completed_operation = client.operations.Get(
                        messages.DeploymentmanagerOperationsGetRequest(
                            project=project,
                            operation=op_name,
                        ))
                except apitools_exceptions.HttpError as error:
                    raise exceptions.HttpException(dm_v2_util.GetError(error))
                operations.append(completed_operation)

        return operations
예제 #7
0
    def Run(self, args):
        """Run 'deployments update'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      If --async=true, returns Operation to poll.
      Else, returns a struct containing the list of resources and list of
        outputs in the deployment.

    Raises:
      HttpException: An http error response was received while executing api
          request.
      ToolException: Config file could not be read or parsed, or the deployment
          creation operation encountered an error.
    """
        client = self.context['deploymentmanager-client']
        messages = self.context['deploymentmanager-messages']
        project = properties.VALUES.core.project.Get(required=True)

        deployment = messages.Deployment(name=args.deployment_name, )
        if args.config:
            deployment.target = importer.BuildTargetConfig(
                messages, args.config, args.properties)
        # Get the fingerprint from the deployment to update.
        try:
            current_deployment = client.deployments.Get(
                messages.DeploymentmanagerDeploymentsGetRequest(
                    project=project, deployment=args.deployment_name))
            # If no fingerprint is present, default to an empty fingerprint.
            # This empty default can be removed once the fingerprint change is
            # fully implemented and all deployments have fingerprints.
            deployment.fingerprint = current_deployment.fingerprint or ''
        except apitools_exceptions.HttpError as error:
            raise exceptions.HttpException(dm_v2_util.GetError(error))

        try:
            operation = client.deployments.Update(
                messages.DeploymentmanagerDeploymentsUpdateRequest(
                    deploymentResource=deployment,
                    project=project,
                    deployment=args.deployment_name,
                    preview=args.preview,
                    createPolicy=(
                        messages.DeploymentmanagerDeploymentsUpdateRequest.
                        CreatePolicyValueValuesEnum(args.create_policy)),
                    deletePolicy=(
                        messages.DeploymentmanagerDeploymentsUpdateRequest.
                        DeletePolicyValueValuesEnum(args.delete_policy)),
                ))
        except apitools_exceptions.HttpError as error:
            raise exceptions.HttpException(dm_v2_util.GetError(error))
        if args. async:
            return operation
        else:
            op_name = operation.name
            try:
                dm_v2_util.WaitForOperation(op_name, project, self.context,
                                            'update', OPERATION_TIMEOUT)
                log.status.Print('Update operation ' + op_name +
                                 ' completed successfully.')
            except exceptions.ToolException:
                # Operation timed out or had errors. Print this warning, then still
                # show whatever operation can be gotten.
                log.error('Update operation ' + op_name +
                          ' has errors or failed to complete within ' +
                          str(OPERATION_TIMEOUT) + ' seconds.')
            except apitools_exceptions.HttpError as error:
                raise exceptions.HttpException(dm_v2_util.GetError(error))

            return dm_v2_util.FetchResourcesAndOutputs(client, messages,
                                                       project,
                                                       args.deployment_name)
예제 #8
0
  def Run(self, args):
    """Run 'deployments stop'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      If --async=true, returns Operation to poll.
      Else, returns boolean indicating whether stop operation succeeded.

    Raises:
      HttpException: An http error response was received while executing api
          request.
      ToolException: The stop operation encountered an error.
    """
    client = self.context['deploymentmanager-client']
    messages = self.context['deploymentmanager-messages']
    project = properties.VALUES.core.project.Get(required=True)

    # Get the fingerprint from the deployment to stop.
    try:
      current_deployment = client.deployments.Get(
          messages.DeploymentmanagerDeploymentsGetRequest(
              project=project,
              deployment=args.deployment_name
          )
      )
      # If no fingerprint is present, default to an empty fingerprint.
      # This empty default can be removed once the fingerprint change is
      # fully implemented and all deployments have fingerprints.
      fingerprint = current_deployment.fingerprint or ''
    except apitools_base.HttpError as error:
      raise exceptions.HttpException(dm_v2_util.GetError(error))

    try:
      operation = client.deployments.Stop(
          messages.DeploymentmanagerDeploymentsStopRequest(
              project=project,
              deployment=args.deployment_name,
              deploymentsStopRequest=messages.DeploymentsStopRequest(
                  fingerprint=fingerprint,
              ),
          )
      )
    except apitools_base.HttpError as error:
      raise exceptions.HttpException(dm_v2_util.GetError(error))
    if args.async:
      return operation
    else:
      op_name = operation.name
      try:
        dm_v2_util.WaitForOperation(op_name, project, self.context, 'stop',
                                    OPERATION_TIMEOUT)
        log.status.Print('Stop operation ' + op_name
                         + ' completed successfully.')
      except exceptions.ToolException:
        # Operation timed out or had errors. Print this warning, then still
        # show whatever operation can be gotten.
        log.error('Stop operation ' + op_name
                  + ' has errors or failed to complete within '
                  + str(OPERATION_TIMEOUT) + ' seconds.')
      except apitools_base.HttpError as error:
        raise exceptions.HttpException(dm_v2_util.GetError(error))
      try:
        # Fetch a list of the stopped resources.
        response = client.resources.List(
            messages.DeploymentmanagerResourcesListRequest(
                project=project,
                deployment=args.deployment_name,
            )
        )
        # TODO(munutzer): Pagination
        return response.resources if response.resources else []
      except apitools_base.HttpError as error:
        raise exceptions.HttpException(dm_v2_util.GetError(error))