コード例 #1
0
    def Run(self, args):
        projects = self.context['projects_client']
        messages = self.context['projects_messages']

        project_ref = self.GetProject(args.id)

        # Create project.
        project_creation_result = projects.projects.Create(
            messages.Project(
                projectId=project_ref.Name(),
                name=args.name if args.name else project_ref.Name()))

        if args.enable_cloud_apis:
            # Enable cloudapis.googleapis.com
            services_client = apis.GetClientInstance('servicemanagement', 'v1')
            services_messages = apis.GetMessagesModule('servicemanagement',
                                                       'v1')
            enable_operation = enable_api.EnableServiceApiCall(
                services_client, services_messages, project_ref.Name(),
                'cloudapis.googleapis.com')
            services_util.WaitForOperation(enable_operation.name,
                                           services_client)
            # TODO(user): Retry in case it failed?

        log.CreatedResource(project_ref)
        return project_creation_result
コード例 #2
0
def Create(project_ref,
           project_name,
           enable_cloud_apis=True,
           update_labels=None):
    """Create a new project."""
    client = projects_util.GetClient()
    messages = projects_util.GetMessages()

    # Create project.
    project_creation_result = client.projects.Create(
        messages.CloudresourcemanagerProjectsCreateRequest(
            project=messages.Project(
                projectId=project_ref.Name(),
                name=project_name if project_name else project_ref.Name(),
                labels=labels_util.UpdateLabels(None,
                                                messages.Project.LabelsValue,
                                                update_labels=update_labels))))

    if enable_cloud_apis:
        # Enable cloudapis.googleapis.com
        services_client = apis.GetClientInstance('servicemanagement', 'v1')
        enable_operation = services_enable_api.EnableServiceApiCall(
            project_ref.Name(), 'cloudapis.googleapis.com')
        services_util.WaitForOperation(enable_operation.name, services_client)
        # TODO(user): Retry in case it failed?

    return project_creation_result
コード例 #3
0
  def Run(self, args):
    project_ref = command_lib_util.ParseProject(args.id)
    try:
      create_op = projects_api.Create(
          project_ref,
          display_name=args.name,
          update_labels=labels_util.GetUpdateLabelsDictFromArgs(args))
    except apitools_exceptions.HttpError as error:
      if error.status_code == httplib.CONFLICT:
        msg = ('Project creation failed. The project ID you specified is '
               'already in use by another project. Please try an alternative '
               'ID.')
        unused_type, unused_value, traceback = sys.exc_info()
        raise exceptions.HttpException, msg, traceback
      raise
    log.CreatedResource(project_ref, async=True)
    create_op = operations.WaitForOperation(create_op)

    # Enable cloudapis.googleapis.com
    if args.enable_cloud_apis:
      log.debug('Enabling cloudapis.googleapis.com')
      services_client = apis.GetClientInstance('servicemanagement', 'v1')
      enable_operation = services_enable_api.EnableServiceApiCall(
          project_ref.Name(), 'cloudapis.googleapis.com')
      services_util.WaitForOperation(enable_operation.name, services_client)
      # TODO(user): Retry in case it failed?

    return operations.ExtractOperationResponse(
        create_op, apis.GetMessagesModule('cloudresourcemanager', 'v1').Project)
コード例 #4
0
    def Run(self, args):
        """Default Run method implementation."""

        flags.CheckParentFlags(args, parent_required=False)
        project_id = args.id
        if not project_id and args.name:
            candidate = command_lib_util.IdFromName(args.name)
            if candidate and console_io.PromptContinue(
                    'No project id provided.',
                    'Use [{}] as project id'.format(candidate),
                    throw_if_unattended=True):
                project_id = candidate
        if not project_id:
            raise exceptions.RequiredArgumentException(
                'PROJECT_ID', 'an id must be provided for the new project')
        project_ref = command_lib_util.ParseProject(project_id)
        labels = labels_util.Diff.FromCreateArgs(args).Apply(
            projects_util.GetMessages().Project.LabelsValue)
        try:
            create_op = projects_api.Create(
                project_ref,
                display_name=args.name,
                parent=projects_api.ParentNameToResourceId(
                    flags.GetParentFromFlags(args)),
                labels=labels)
        except apitools_exceptions.HttpConflictError:
            msg = (
                'Project creation failed. The project ID you specified is '
                'already in use by another project. Please try an alternative '
                'ID.')
            unused_type, unused_value, traceback = sys.exc_info()
            raise exceptions.HttpException, msg, traceback
        log.CreatedResource(project_ref, async=True)
        create_op = operations.WaitForOperation(create_op)

        # Enable cloudapis.googleapis.com
        if args.enable_cloud_apis:
            log.debug('Enabling cloudapis.googleapis.com')
            services_client = apis.GetClientInstance('servicemanagement', 'v1')
            enable_operation = services_enable_api.EnableServiceApiCall(
                project_ref.Name(), 'cloudapis.googleapis.com')
            enable_operation_ref = resources.REGISTRY.Parse(
                enable_operation.name,
                collection='servicemanagement.operations')
            services_util.WaitForOperation(enable_operation_ref,
                                           services_client)

        if args.set_as_default:
            project_property = properties.FromString('core/project')
            properties.PersistProperty(project_property, args.id)
            log.status.Print(
                'Updated property [core/project] to [{0}].'.format(args.id))

        return operations.ExtractOperationResponse(
            create_op,
            apis.GetMessagesModule('cloudresourcemanager', 'v1').Project)
コード例 #5
0
ファイル: create.py プロジェクト: eduardofacanha/Robin
  def Run(self, args):
    """Create a GCP repository to the current directory.

    Args:
      args: argparse.Namespace, the arguments this command is run with.

    Returns:
      (sourcerepo_v1_messages.Repo) The created respository.

    Raises:
      ToolException: on project initialization errors, on missing billing
        account, and when the repo name is already in use.
    """
    project_id = resolvers.FromProperty(properties.VALUES.core.project)
    res = resources.REGISTRY.Parse(
        args.name,
        params={'projectsId': project_id},
        collection='sourcerepo.projects.repos')
    # check that the name does not have forbidden characters.
    # we'd like to do this by putting the validator in the flag type, but
    # we cannot for now because it needs to work on the parsed name.
    flags.REPO_NAME_VALIDATOR(res.Name())
    source_handler = sourcerepo.Source()

    # This service enabled check can be removed when cl/148491846 is ready
    if not enable_api.IsServiceEnabled(res.projectsId,
                                       _SOURCEREPO_SERVICE_NAME):
      message = ('{api} is required for repository creation and is not '
                 'enabled.'.format(api=_SOURCEREPO_SERVICE_NAME))
      if console_io.PromptContinue(
          message=message,
          prompt_string='Would you like to enable it?',
          default=True):
        operation = enable_api.EnableServiceApiCall(res.projectsId,
                                                    _SOURCEREPO_SERVICE_NAME)
        # wait for the operation to complete, will raise an exception if the
        # operation fails.
        services_util.ProcessOperationResult(operation, async=False)
      else:
        error_message = ('Cannot create a repository without enabling '
                         '{api}'.format(api=_SOURCEREPO_SERVICE_NAME))
        raise exceptions.Error(error_message)
    try:
      repo = source_handler.CreateRepo(res)
      if repo:
        log.CreatedResource(res.Name())
        log.Print('You may be billed for this repository. '
                  'See {url} for details.'.format(url=_BILLING_URL))
        return repo
    except exceptions.HttpError as error:
      exc = c_exc.HttpException(error)
      exc.error_format = _ERROR_FORMAT
      raise exc
コード例 #6
0
    def Run(self, args):
        """Run 'service-management enable'.

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

    Returns:
      The response from the consumer settings API call.
    """
        operation = enable_api.EnableServiceApiCall(self.project, args.service)
        services_util.ProcessOperationResult(operation, args. async)
コード例 #7
0
ファイル: enable.py プロジェクト: eduardofacanha/Robin
    def Run(self, args):
        """Run 'service-management enable'.

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

    Returns:
      The response from the consumer settings API call.
    """
        project = properties.VALUES.core.project.Get(required=True)
        service = arg_parsers.GetServiceNameFromArg(args.service)
        operation = enable_api.EnableServiceApiCall(project, service)
        return services_util.ProcessOperationResult(operation, args. async)
コード例 #8
0
    def Run(self, args):
        """Run 'service-management enable'.

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

    Returns:
      The response from the consumer settings API call.

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

        # TODO(b/25392897): Add support for Operation completion, and --async flag
        result = enable_api.EnableServiceApiCall(self.services_client,
                                                 self.services_messages,
                                                 args.consumer_project,
                                                 args.service)

        return services_util.ProcessOperationResult(result, args. async)