Exemplo n.º 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.
      ConfigError: Config file could not be read or parsed, or the
          deployment creation operation encountered an error.
    """
        deployment = dm_base.GetMessages().Deployment(
            name=args.deployment_name,
            target=importer.BuildTargetConfig(dm_base.GetMessages(),
                                              args.config, args.properties),
        )
        if self.ReleaseTrack() in [base.ReleaseTrack.ALPHA]:
            label_dict = labels_util.GetUpdateLabelsDictFromArgs(args)
            label_entry = []
            if label_dict:
                label_entry = [
                    dm_base.GetMessages().DeploymentLabelEntry(key=k, value=v)
                    for k, v in sorted(label_dict.iteritems())
                ]
                deployment.labels = label_entry

        if args.description:
            deployment.description = args.description

        try:
            operation = dm_base.GetClient().deployments.Insert(
                dm_base.GetMessages(
                ).DeploymentmanagerDeploymentsInsertRequest(
                    project=dm_base.GetProject(),
                    deployment=deployment,
                    preview=args.preview,
                ))
            # Fetch and print the latest fingerprint of the deployment.
            fingerprint = dm_v2_util.FetchDeploymentFingerprint(
                dm_base.GetClient(), dm_base.GetMessages(),
                dm_base.GetProject(), args.deployment_name)
            dm_util.PrintFingerprint(fingerprint)

        except apitools_exceptions.HttpError as error:
            raise exceptions.HttpException(error, dm_v2_util.HTTP_ERROR_FORMAT)
        if args. async:
            return operation
        else:
            op_name = operation.name
            try:
                dm_write.WaitForOperation(op_name,
                                          operation_description='create',
                                          project=dm_base.GetProject(),
                                          timeout=OPERATION_TIMEOUT)
                log.status.Print('Create operation ' + op_name +
                                 ' completed successfully.')
            except apitools_exceptions.HttpError as error:
                raise exceptions.HttpException(error,
                                               dm_v2_util.HTTP_ERROR_FORMAT)

            return dm_v2_util.FetchResourcesAndOutputs(dm_base.GetClient(),
                                                       dm_base.GetMessages(),
                                                       dm_base.GetProject(),
                                                       args.deployment_name)
Exemplo n.º 2
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.
    """
    deployment = dm_base.GetMessages().Deployment(
        name=args.deployment_name,
    )

    if args.config:
      deployment.target = importer.BuildTargetConfig(
          dm_base.GetMessages(), args.config, args.properties)
    elif (self.ReleaseTrack() in [base.ReleaseTrack.ALPHA,
                                  base.ReleaseTrack.BETA]
          and args.manifest_id):
      deployment.target = importer.BuildTargetConfigFromManifest(
          dm_base.GetClient(), dm_base.GetMessages(), dm_base.GetProject(),
          args.deployment_name, args.manifest_id, args.properties)
    # Get the fingerprint from the deployment to update.
    try:
      current_deployment = dm_base.GetClient().deployments.Get(
          dm_base.GetMessages().DeploymentmanagerDeploymentsGetRequest(
              project=dm_base.GetProject(),
              deployment=args.deployment_name
          )
      )

      if args.fingerprint:
        deployment.fingerprint = dm_util.DecodeFingerprint(args.fingerprint)
      else:
        # If no fingerprint is present, default to an empty fingerprint.
        # TODO(b/34966984): Remove the empty default after cleaning up all
        # deployments that has no fingerprint
        deployment.fingerprint = current_deployment.fingerprint or ''

      # Update the labels of the deployment
      if self.ReleaseTrack() in [base.ReleaseTrack.ALPHA]:
        update_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
        remove_labels = labels_util.GetRemoveLabelsListFromArgs(args)
        current_labels = current_deployment.labels

        deployment.labels = dm_labels.UpdateLabels(
            current_labels, dm_base.GetMessages().DeploymentLabelEntry,
            update_labels, remove_labels)

        # If no config or manifest_id are specified, but try to update labels,
        # only get current manifest when it is not a preveiw request
        if not args.config and not args.manifest_id:
          if args.update_labels or args.remove_labels:
            if not args.preview:
              current_manifest = dm_v2_util.ExtractManifestName(
                  current_deployment)
              deployment.target = importer.BuildTargetConfigFromManifest(
                  dm_base.GetClient(), dm_base.GetMessages(),
                  dm_base.GetProject(), args.deployment_name, current_manifest)

      if args.description is None:
        deployment.description = current_deployment.description
      elif not args.description or args.description.isspace():
        deployment.description = None
      else:
        deployment.description = args.description
    except apitools_exceptions.HttpError as error:
      raise exceptions.HttpException(error, dm_v2_util.HTTP_ERROR_FORMAT)

    try:
      operation = dm_base.GetClient().deployments.Update(
          dm_base.GetMessages().DeploymentmanagerDeploymentsUpdateRequest(
              deploymentResource=deployment,
              project=dm_base.GetProject(),
              deployment=args.deployment_name,
              preview=args.preview,
              createPolicy=(dm_base.GetMessages()
                            .DeploymentmanagerDeploymentsUpdateRequest
                            .CreatePolicyValueValuesEnum(args.create_policy)),
              deletePolicy=(dm_base.GetMessages()
                            .DeploymentmanagerDeploymentsUpdateRequest
                            .DeletePolicyValueValuesEnum(args.delete_policy)),
          )
      )
      # Fetch and print the latest fingerprint of the deployment.
      new_fingerprint = dm_v2_util.FetchDeploymentFingerprint(
          dm_base.GetClient(),
          dm_base.GetMessages(),
          dm_base.GetProject(),
          args.deployment_name)
      dm_util.PrintFingerprint(new_fingerprint)
    except apitools_exceptions.HttpError as error:
      raise exceptions.HttpException(error, dm_v2_util.HTTP_ERROR_FORMAT)
    if args.async:
      return operation
    else:
      op_name = operation.name
      try:
        dm_write.WaitForOperation(op_name,
                                  'update',
                                  dm_base.GetProject(),
                                  timeout=OPERATION_TIMEOUT)
        log.status.Print('Update operation ' + op_name
                         + ' completed successfully.')
      except apitools_exceptions.HttpError as error:
        raise exceptions.HttpException(error, dm_v2_util.HTTP_ERROR_FORMAT)

      return dm_v2_util.FetchResourcesAndOutputs(dm_base.GetClient(),
                                                 dm_base.GetMessages(),
                                                 dm_base.GetProject(),
                                                 args.deployment_name)
Exemplo n.º 3
0
    def Run(self, args):
        """Run 'deployments cancel-preview'.

    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 cancel preview operation
      succeeded.

    Raises:
      HttpException: An http error response was received while executing api
          request.
    """

        if args.fingerprint:
            fingerprint = dm_util.DecodeFingerprint(args.fingerprint)
        else:
            # If no fingerprint is present, default to an empty fingerprint.
            # TODO(b/34966984): Remove the empty default after cleaning up all
            # deployments that has no fingerprint
            fingerprint = dm_v2_util.FetchDeploymentFingerprint(
                dm_base.GetClient(),
                dm_base.GetMessages(),
                dm_base.GetProject(),
                args.deployment_name,
            ) or ''

        try:
            operation = dm_base.GetClient().deployments.CancelPreview(
                dm_base.GetMessages(
                ).DeploymentmanagerDeploymentsCancelPreviewRequest(
                    project=dm_base.GetProject(),
                    deployment=args.deployment_name,
                    deploymentsCancelPreviewRequest=dm_base.GetMessages().
                    DeploymentsCancelPreviewRequest(fingerprint=fingerprint, ),
                ))
            # Fetch and print the latest fingerprint of the deployment.
            new_fingerprint = dm_v2_util.FetchDeploymentFingerprint(
                dm_base.GetClient(), dm_base.GetMessages(),
                dm_base.GetProject(), args.deployment_name)
            dm_util.PrintFingerprint(new_fingerprint)
        except apitools_exceptions.HttpError as error:
            raise exceptions.HttpException(error, dm_v2_util.HTTP_ERROR_FORMAT)
        if args. async:
            return operation
        else:
            op_name = operation.name
            try:
                dm_write.WaitForOperation(op_name,
                                          'cancel-preview',
                                          dm_base.GetProject(),
                                          timeout=OPERATION_TIMEOUT)
                log.status.Print('Cancel preview operation ' + op_name +
                                 ' completed successfully.')
            except apitools_exceptions.HttpError as error:
                raise exceptions.HttpException(error,
                                               dm_v2_util.HTTP_ERROR_FORMAT)
            try:
                # Fetch a list of the canceled resources.
                response = dm_base.GetClient().resources.List(
                    dm_base.GetMessages(
                    ).DeploymentmanagerResourcesListRequest(
                        project=dm_base.GetProject(),
                        deployment=args.deployment_name,
                    ))
                # TODO(user): Pagination
                return response.resources if response.resources else []
            except apitools_exceptions.HttpError as error:
                raise exceptions.HttpException(error,
                                               dm_v2_util.HTTP_ERROR_FORMAT)
Exemplo n.º 4
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.
      ConfigError: Config file could not be read or parsed, or the
          deployment creation operation encountered an error.
    """
        if ((not args.IsSpecified('format')) and
            (args. async or getattr(args, 'automatic_rollback', False))):
            args.format = flags.OPERATION_FORMAT

        deployment = dm_base.GetMessages().Deployment(
            name=args.
            deployment_name,  # TODO(b/37913150): Use resource parser.
            target=importer.BuildTargetConfig(dm_base.GetMessages(),
                                              args.config, args.properties),
        )

        self._SetMetadata(args, deployment)

        try:
            operation = dm_base.GetClient().deployments.Insert(
                dm_base.GetMessages(
                ).DeploymentmanagerDeploymentsInsertRequest(
                    project=dm_base.GetProject(),
                    deployment=deployment,
                    preview=args.preview,
                ))

            # Fetch and print the latest fingerprint of the deployment.
            fingerprint = dm_v2_util.FetchDeploymentFingerprint(
                dm_base.GetClient(), dm_base.GetMessages(),
                dm_base.GetProject(), args.deployment_name)
            dm_util.PrintFingerprint(fingerprint)

        except apitools_exceptions.HttpError as error:
            raise exceptions.HttpException(error, dm_v2_util.HTTP_ERROR_FORMAT)
        if args. async:
            return operation
        else:
            op_name = operation.name
            try:
                dm_write.WaitForOperation(op_name,
                                          operation_description='create',
                                          project=dm_base.GetProject(),
                                          timeout=OPERATION_TIMEOUT)
                log.status.Print('Create operation ' + op_name +
                                 ' completed successfully.')
            except apitools_exceptions.HttpError as error:
                # TODO(b/37911296): Use gcloud default error handling.
                raise exceptions.HttpException(error,
                                               dm_v2_util.HTTP_ERROR_FORMAT)
            except dm_exceptions.OperationError as error:
                response = self._HandleOperationError(error, args, operation,
                                                      dm_base.GetProject())
                return response

            return dm_v2_util.FetchResourcesAndOutputs(dm_base.GetClient(),
                                                       dm_base.GetMessages(),
                                                       dm_base.GetProject(),
                                                       args.deployment_name)