def Filter(self, context, args):
    """Modify the context that will be given to this group's commands when run.

    Args:
      context: The current context.
      args: The argparse namespace given to the corresponding .Run() invocation.

    Returns:
      The updated context.
    """
    # All logging collections use projectId, so we can set a default value.
    resources.SetParamDefault(
        api='logging', collection=None, param='projectsId',
        resolver=resolvers.FromProperty(properties.VALUES.core.project))

    context['logging_client_v1beta3'] = apis.GetClientInstance(
        'logging', 'v1beta3')
    context['logging_messages_v1beta3'] = apis.GetMessagesModule(
        'logging', 'v1beta3')

    context['logging_client_v2beta1'] = apis.GetClientInstance(
        'logging', 'v2beta1')
    context['logging_messages_v2beta1'] = apis.GetMessagesModule(
        'logging', 'v2beta1')

    context['logging_resources'] = resources
    return context
Exemple #2
0
def NewAPIAdapter():
  """Initialize an api adapter for the given api_version.

  Returns:
    APIAdapter object.
  """
  api_client = core_apis.GetClientInstance('container', 'v1')
  api_client.check_response_func = CheckResponse
  messages = core_apis.GetMessagesModule('container', 'v1')

  api_compute_client = core_apis.GetClientInstance('compute', 'v1')
  api_compute_client.check_response_func = CheckResponse
  compute_messages = core_apis.GetMessagesModule('compute', 'v1')

  registry = cloud_resources.REGISTRY.CloneAndSwitchAPIs(
      api_client, api_compute_client)

  adapter = V1Adapter

  registry.SetParamDefault(
      api='compute', collection=None, param='project',
      resolver=resolvers.FromProperty(properties.VALUES.core.project))
  registry.SetParamDefault(
      api='container', collection=None, param='projectId',
      resolver=resolvers.FromProperty(properties.VALUES.core.project))
  registry.SetParamDefault(
      api='container', collection=None, param='zone',
      resolver=resolvers.FromProperty(properties.VALUES.compute.zone))

  return adapter(registry, api_client, messages, api_compute_client,
                 compute_messages)
Exemple #3
0
 def InitializeApiClients(cls):
   cls._debug_client = apis.GetClientInstance('debug', 'v2')
   cls._debug_messages = apis.GetMessagesModule('debug', 'v2')
   cls._resource_client = apis.GetClientInstance('projects', 'v1beta1')
   cls._resource_messages = apis.GetMessagesModule('projects', 'v1beta1')
   cls.SNAPSHOT_TYPE = (
       cls._debug_messages.Breakpoint.ActionValueValuesEnum.CAPTURE)
   cls.LOGPOINT_TYPE = cls._debug_messages.Breakpoint.ActionValueValuesEnum.LOG
Exemple #4
0
 def InitializeApiClients(cls):
     """Sets up class with instantiated api client."""
     cls._debug_client = apis.GetClientInstance('clouddebugger', 'v2')
     cls._debug_messages = apis.GetMessagesModule('clouddebugger', 'v2')
     cls._resource_client = apis.GetClientInstance('cloudresourcemanager',
                                                   'v1beta1')
     cls._resource_messages = apis.GetMessagesModule(
         'cloudresourcemanager', 'v1beta1')
     cls.SNAPSHOT_TYPE = (
         cls._debug_messages.Breakpoint.ActionValueValuesEnum.CAPTURE)
     cls.LOGPOINT_TYPE = cls._debug_messages.Breakpoint.ActionValueValuesEnum.LOG
     cls._resource_parser = resources.REGISTRY.Clone()
     cls._resource_parser.RegisterApiByName('clouddebugger', 'v2')
Exemple #5
0
  def __call__(self, arg_value):
    """Parses arg_value into an EndpointAddress.

    Args:
      arg_value: A simple or "full" address. Simple addresses are just the
        address (IPv6/v4 or domain) optionally followed by a :PORT. Full
        addresses are of the form
          address=ADRESS[;port_number=NUM[,protocol=PROTOCOL][,port_name=NAME]]+
        port_name must be specified if more than one port specification is
        supplied for the address.
    Returns:
      An EndpointAddress represented by arg_value
    """
    self.arg_value = arg_value

    if not arg_value:
      self.raiseValidationError('Address arguments can not be empty')

    if arg_value.startswith('address='):
      # It's a keyed address
      arg_parts = arg_value.split(';')
      address_parts = arg_parts[0].split('=')

      if len(address_parts) < 2:
        self.raiseValidationError('The address can not be empty.')

      address = address_parts[1]
      ports = self.parse_port_specs(address_parts[1], arg_parts[1:])
      return apis.GetMessagesModule('serviceregistry').EndpointAddress(
          address=address, ports=ports)
    elif ';' in arg_value or ',' in arg_value:
      # Don't let users accidentally mix the simple and keyed schemes
      self.raiseValidationError(
          'The target specification contains a comma or semi-colon and looks '
          'like a fully keyed target specification. This format must begin '
          'with address=')
    else:
      # It's just an ADDRESS:PORT
      host_port = arg_parsers.HostPort.Parse(arg_value, ipv6_enabled=True)

      endpoint_address = (apis.GetMessagesModule('serviceregistry')
                          .EndpointAddress(address=host_port.host))

      if host_port.port:
        endpoint_address.ports = [
            apis.GetMessagesModule('serviceregistry').EndpointPort(
                portNumber=int(host_port.port))
        ]

      return endpoint_address
Exemple #6
0
def _Args(parser, include_alpha_targets, include_beta_targets):
  """Argument parsing."""
  flags.AddCommonFlags(parser)
  flags.AddUpdateArgs(parser, include_alpha_targets, include_beta_targets)

  address = parser.add_argument(
      '--address',
      help='The external IP address that the forwarding rule will serve.')
  address.detailed_help = """\
      The external IP address that the forwarding rule will
      serve. All traffic sent to this IP address is directed to the
      target pointed to by the forwarding rule. If the address is
      reserved, it must either (1) reside in the global scope if the
      forwarding rule is being configured to point to a target HTTP
      proxy or (2) reside in the same region as the forwarding rule
      if the forwarding rule is being configured to point to a
      target pool or target instance. If this flag is omitted, an
      ephemeral IP address is assigned.
      """
  v1_messages = core_apis.GetMessagesModule('compute', 'v1')
  ip_protocol = parser.add_argument(
      '--ip-protocol',
      choices=_SupportedProtocols(v1_messages),
      type=lambda x: x.upper(),
      help='The IP protocol that the rule will serve.')
  ip_protocol.detailed_help = """\
      The IP protocol that the rule will serve. If left empty, TCP
      is used. Supported protocols are: {0}.
      """.format(', '.join(_SupportedProtocols(v1_messages)))

  parser.add_argument(
      '--description',
      help='An optional textual description for the forwarding rule.')

  ports_scope = parser.add_mutually_exclusive_group()
  ports = ports_scope.add_argument(
      '--ports',
      metavar='[PORT | PORT-PORT]',
      help=('If specified, only packets addressed to the ports or '
            'port ranges will be forwarded.'),
      type=arg_parsers.ArgList(
          min_length=1, element_type=arg_parsers.Range.Parse),
      default=[])

  ports.detailed_help = """\
          If specified, only packets addressed to ports in the specified
          list will be forwarded. If not specified for regional forwarding
          rules, all ports are matched. This flag is required for global
          forwarding rules and accepts a single continuous set of ports.

          Individual ports and ranges can be specified,
          for example (`--ports 8000-8004` or `--ports 80`).
          """
  port_range = ports_scope.add_argument(
      '--port-range',
      type=arg_parsers.Range.Parse,
      help='DEPRECATED, use --ports. If specified, only packets addressed to '
           'the port or ports in the specified range will be forwarded.',
      metavar='[PORT | PORT-PORT]')
  port_range.detailed_help = """\
Exemple #7
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.
    """
        # TODO(b/31062835): remove CloneAndSwitchAPI and extract API code to api_lib
        client = apis.GetClientInstance('ml', 'v1beta1')
        msgs = apis.GetMessagesModule('ml', 'v1beta1')
        res = resources.REGISTRY.CloneAndSwitchAPIs(client).Parse(
            args.version,
            params={'modelsId': args.model},
            collection='ml.projects.models.versions')
        req = msgs.MlProjectsModelsVersionsSetDefaultRequest(
            projectsId=res.projectsId,
            modelsId=res.modelsId,
            versionsId=res.Name(),
            googleCloudMlV1beta1SetDefaultVersionRequest=(
                msgs.GoogleCloudMlV1beta1SetDefaultVersionRequest()))
        resp = client.projects_models_versions.SetDefault(req)
        return resp
Exemple #8
0
  def Filter(self, context, args):
    """Context() is a filter function that can update the context.

    Args:
      context: The current context.
      args: The argparse namespace that was specified on the CLI or API.

    Returns:
      The updated context.
    """
    properties.VALUES.compute.zone.Get(required=True)
    context['updater_api'] = core_apis.GetClientInstance(
        'replicapoolupdater', 'v1beta1')
    context['updater_messages'] = core_apis.GetMessagesModule(
        'replicapoolupdater', 'v1beta1')
    resources.SetParamDefault(
        api='compute', collection=None, param='project',
        resolver=resolvers.FromProperty(properties.VALUES.core.project))
    resources.SetParamDefault(
        api='compute', collection=None, param='zone',
        resolver=resolvers.FromProperty(properties.VALUES.compute.zone))
    resources.SetParamDefault(
        api='replicapoolupdater', collection=None, param='project',
        resolver=resolvers.FromProperty(properties.VALUES.core.project))
    resources.SetParamDefault(
        api='replicapoolupdater', collection=None, param='zone',
        resolver=resolvers.FromProperty(properties.VALUES.compute.zone))
    context['updater_resources'] = resources
    return context
Exemple #9
0
def TransformBuildSource(r, undefined=''):
  """Returns the formatted build source.

  Args:
    r: JSON-serializable object.
    undefined: Returns this value if the resource cannot be formatted.
  Returns:
    The formatted build source.
  """
  messages = core_apis.GetMessagesModule('cloudbuild', 'v1')
  b = apitools_encoding.DictToMessage(r, messages.Build)
  if b.source is None:
    return undefined
  storage_source = b.source.storageSource
  repo_source = b.source.repoSource
  if storage_source is not None:
    bucket = storage_source.bucket
    obj = storage_source.object
    if bucket is None or obj is None:
      return undefined
    return 'gs://{0}/{1}'.format(bucket, obj)
  if repo_source is not None:
    repo_name = repo_source.repoName or 'default'
    branch_name = repo_source.branchName
    if branch_name is not None:
      return '{0}@{1}'.format(repo_name, branch_name)
    tag_name = repo_source.tagName
    if tag_name is not None:
      return '{0}@{1}'.format(repo_name, tag_name)
    commit_sha = repo_source.commitSha
    if commit_sha is not None:
      return '{0}@{1}'.format(repo_name, commit_sha)
  return undefined
Exemple #10
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.
    """
        # TODO(b/31062835): remove CloneAndSwitchAPI and extract API code to api_lib
        client = apis.GetClientInstance('ml', 'v1beta1')
        msgs = apis.GetMessagesModule('ml', 'v1beta1')
        reg = resources.REGISTRY.CloneAndSwitchAPIs(client)
        res = reg.Parse(args.version,
                        params={'modelsId': args.model},
                        collection='ml.projects.models.versions')
        req = msgs.MlProjectsModelsVersionsCreateRequest(
            projectsId=res.projectsId,
            modelsId=res.modelsId,
            googleCloudMlV1beta1Version=msgs.GoogleCloudMlV1beta1Version(
                name=res.Name(), deploymentUri=args.origin))
        op = client.projects_models_versions.Create(req)
        if args. async:
            return op
        with console_io.ProgressTracker('Creating version...'):
            operations.WaitForOperation(client.projects_operations,
                                        op,
                                        registry=reg)
        return op.response
Exemple #11
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.
    """
        client = apis.GetClientInstance('ml', 'v1alpha3')
        msgs = apis.GetMessagesModule('ml', 'v1alpha3')
        res = resources.REGISTRY.Parse(
            args.version,
            params={'modelsId': args.model},
            collection='ml.projects.models.versions')
        req = msgs.MlProjectsModelsCreateVersionRequest(
            projectsId=res.projectsId,
            modelsId=res.modelsId,
            googleCloudMlV1alpha3Version=msgs.GoogleCloudMlV1alpha3Version(
                name=res.Name(), originUri=args.origin))
        op = client.projects_models.CreateVersion(req)
        if args. async:
            return op
        with console_io.ProgressTracker('Creating version...'):
            operations.WaitForOperation(client.projects_operations, op)
        return op.response
  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)
Exemple #13
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.
    """

    client = core_apis.GetClientInstance('cloudbuild', 'v1')
    messages = core_apis.GetMessagesModule('cloudbuild', 'v1')

    ongoing_filter = None
    if args.ongoing:
      ongoing_filter = 'status="WORKING" OR status="QUEUED"'

    return list_pager.YieldFromList(
        client.projects_builds,
        messages.CloudbuildProjectsBuildsListRequest(
            pageSize=args.page_size,
            projectId=properties.VALUES.core.project.Get(),
            filter=ongoing_filter),
        field='builds',
        batch_size_attribute='pageSize')
Exemple #14
0
    def Filter(self, context, args):
        """Context() is a filter function that can update the context.

    Args:
      context: The current context.
      args: The argparse namespace that was specified on the CLI or API.

    Returns:
      The updated context.
    Raises:
      ToolException: When no project is specified.
    """

        api_name = 'serviceregistry'
        api_version = 'v1alpha'
        context[constants.CLIENT] = apis.GetClientInstance(
            api_name, api_version)
        context[constants.MESSAGES] = apis.GetMessagesModule(
            api_name, api_version)

        project = properties.VALUES.core.project
        resolver = resolvers.FromProperty(project)

        registry = resources.REGISTRY.Clone()
        registry.SetParamDefault('serviceregistry', None, 'project', resolver)
        registry.RegisterApiByName(api_name, api_version)

        context[constants.RESOURCES] = registry

        return context
Exemple #15
0
    def Filter(self, context, args):
        context['dataproc_messages'] = apis.GetMessagesModule('dataproc', 'v1')
        context['resources'] = resources.REGISTRY

        # TODO(user): Move outside of context in a place that will be easier to
        # convert into a property when there are multiple regions.
        context['dataproc_region'] = self.REGION
        context['dataproc_client'] = apis.GetClientInstance('dataproc', 'v1')

        resources.REGISTRY.SetParamDefault(api='dataproc',
                                           collection=None,
                                           param='projectId',
                                           resolver=resolvers.FromProperty(
                                               properties.VALUES.core.project))
        resources.REGISTRY.SetParamDefault(
            api='dataproc',
            collection=None,
            param='region',
            resolver=lambda: context['dataproc_region'])

        # These two properties are artifacts of how our Operations API get
        # converted into generated libraries.
        resources.REGISTRY.SetParamDefault(api='dataproc',
                                           collection=None,
                                           param='projectsId',
                                           resolver=resolvers.FromProperty(
                                               properties.VALUES.core.project))
        resources.REGISTRY.SetParamDefault(
            api='dataproc',
            collection=None,
            param='regionsId',
            resolver=lambda: context['dataproc_region'])

        return context
Exemple #16
0
def TransformBuildImages(r, undefined=''):
  """Returns the formatted build results images.

  Args:
    r: JSON-serializable object.
    undefined: Returns this value if the resource cannot be formatted.
  Returns:
    The formatted build results images.
  """
  messages = core_apis.GetMessagesModule('cloudbuild', 'v1')
  b = apitools_encoding.DictToMessage(r, messages.Build)
  if b.results is None:
    return undefined
  images = b.results.images
  if not images:
    return undefined
  names = []
  for i in images:
    if i.name is None:
      names.append(undefined)
    else:
      names.append(i.name)
  if len(names) > 1:
    return names[0] + ' (+{0} more)'.format(len(names)-1)
  return names[0]
Exemple #17
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.
    """

        client = core_apis.GetClientInstance('cloudbuild', 'v1')
        messages = core_apis.GetMessagesModule('cloudbuild', 'v1')
        registry = self.context['registry']

        build_ref = registry.Parse(args.build,
                                   collection='cloudbuild.projects.builds')

        logger = cb_logs.CloudBuildClient(client, messages)
        if args.stream:
            logger.Stream(build_ref)
            return

        # Just print out what's available now.
        logger.PrintLog(build_ref)
Exemple #18
0
def List():
  client = apis.GetClientInstance('ml', 'v1beta1')
  msgs = apis.GetMessagesModule('ml', 'v1beta1')
  req = msgs.MlProjectsJobsListRequest(
      projectsId=properties.VALUES.core.project.Get())
  return list_pager.YieldFromList(
      client.projects_jobs, req, field='jobs', batch_size_attribute='pageSize')
Exemple #19
0
    def Filter(self, context, args):
        """Initialize context for bigquery commands.

    Args:
      context: The current context.
      args: The argparse namespace that was specified on the CLI or API.

    Returns:
      The updated context.
    """
        resources.REGISTRY.SetParamDefault(api='bigquery',
                                           collection=None,
                                           param='projectId',
                                           resolver=resolvers.FromProperty(
                                               properties.VALUES.core.project))

        # TODO(user): remove command dependence on these.
        context[BIGQUERY_MESSAGES_MODULE_KEY] = apis.GetMessagesModule(
            'bigquery', 'v2')
        context[APITOOLS_CLIENT_KEY] = apis.GetClientInstance('bigquery', 'v2')
        context[BIGQUERY_REGISTRY_KEY] = resources.REGISTRY

        # Inject bigquery backend params.
        bigquery.Bigquery.SetResourceParser(resources.REGISTRY)
        bigquery.Bigquery.SetApiEndpoint()
Exemple #20
0
    def Filter(self, context, args):
        """Context() is a filter function that can update the context.

    Args:
      context: The current context.
      args: The argparse namespace that was specified on the CLI or API.

    Returns:
      The updated context.
    Raises:
      ToolException: When no project is specified.
    """

        client = apis.GetClientInstance('serviceregistry', 'v1alpha')
        context[constants.CLIENT] = client
        context[constants.MESSAGES] = apis.GetMessagesModule(
            'serviceregistry', 'v1alpha')

        project = properties.VALUES.core.project
        resolver = resolvers.FromProperty(project)
        resources.REGISTRY.SetParamDefault('serviceregistry', None, 'project',
                                           resolver)
        # guarantee we use the same API as our client
        context[constants.RESOURCES] = resources.REGISTRY.CloneAndSwitchAPIs(
            client)

        return context
    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
Exemple #22
0
def ProcessEndpointsServices(app_config_services, project):
  """Pushes service configs to the Endpoints handler.

  First, this method checks each service in the list of services to see
  whether it's to be handled by Cloud Endpoints. If so, it pushes the config.

  Args:
    app_config_services: The list of services from an app config.
    project: The name of the GCP project.
  """
  for _, service in app_config_services:
    if service and service.parsed and service.parsed.beta_settings:
      bs = service.parsed.beta_settings
      use_endpoints = bs.get('use_endpoints_api_management', '').lower()
      swagger_file = bs.get('endpoints_swagger_spec_file')
      if use_endpoints in ('true', '1', 'yes') and swagger_file:
        if os.path.isabs(swagger_file):
          swagger_abs_path = swagger_file
        else:
          swagger_abs_path = os.path.normpath(os.path.join(
              os.path.dirname(service.file), swagger_file))
        cloud_endpoints.PushServiceConfig(
            swagger_abs_path,
            project,
            apis.GetClientInstance('servicemanagement', 'v1'),
            apis.GetMessagesModule('servicemanagement', 'v1'))
Exemple #23
0
 def __init__(self,
              debug_client=None,
              debug_messages=None,
              resource_client=None,
              resource_messages=None):
     """Sets up class with instantiated api client."""
     self._debug_client = (debug_client
                           or apis.GetClientInstance('clouddebugger', 'v2'))
     self._debug_messages = (debug_messages or apis.GetMessagesModule(
         'clouddebugger', 'v2'))
     self._resource_client = (resource_client or apis.GetClientInstance(
         'cloudresourcemanager', 'v1beta1'))
     self._resource_messages = (resource_messages or apis.GetMessagesModule(
         'cloudresourcemanager', 'v1beta1'))
     self._resource_parser = resources.REGISTRY.Clone()
     self._resource_parser.RegisterApiByName('clouddebugger', 'v2')
Exemple #24
0
def ProcessOperationResult(result):
  """Validate and process Operation result message for user display.

  This method checks to make sure the result is of type Operation and
  converts the StartTime field from a UTC timestamp to a local datetime
  string.

  Args:
    result: The message to process (expected to be of type Operation)

  Returns:
    The processed message in Python dict form
  """
  if not result:
    return

  messages = apis.GetMessagesModule('servicemanagement', 'v1')

  RaiseIfResultNotTypeOf(result, messages.Operation)

  result_dict = encoding.MessageToDict(result)

  # Convert metadata startTime to local time
  if 'metadata' in result_dict and 'startTime' in result_dict['metadata']:
    result_dict['metadata']['startTime'] = (
        ConvertUTCDateTimeStringToLocalTimeString(
            result_dict['metadata']['startTime']))

  return result_dict
    def Filter(self, context, args):
        client = core_apis.GetClientInstance('autoscaler', 'v1beta2')
        context['autoscaler-client'] = client

        messages_v2 = core_apis.GetMessagesModule('autoscaler', 'v1beta2')
        context['autoscaler_messages_module'] = messages_v2

        resources.SetParamDefault(api='compute',
                                  collection=None,
                                  param='project',
                                  resolver=resolvers.FromProperty(
                                      properties.VALUES.core.project))
        resources.SetParamDefault(api='autoscaler',
                                  collection=None,
                                  param='project',
                                  resolver=resolvers.FromProperty(
                                      properties.VALUES.core.project))
        resources.SetParamDefault(api='autoscaler',
                                  collection=None,
                                  param='zone',
                                  resolver=resolvers.FromProperty(
                                      properties.VALUES.compute.zone))
        resources.SetParamDefault(api='replicapool',
                                  collection=None,
                                  param='project',
                                  resolver=resolvers.FromProperty(
                                      properties.VALUES.core.project))
        resources.SetParamDefault(api='replicapool',
                                  collection=None,
                                  param='zone',
                                  resolver=resolvers.FromProperty(
                                      properties.VALUES.compute.zone))

        context['autoscaler_resources'] = resources
        return context
Exemple #26
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.
    """
        client = apis.GetClientInstance('ml', 'v1beta1')
        msgs = apis.GetMessagesModule('ml', 'v1beta1')

        project = properties.VALUES.core.project.Get(required=True)
        project_ref = resources.REGISTRY.Parse(
            project, collection='cloudresourcemanager.projects')
        console_io.PromptContinue(
            message=
            '\nCloud ML needs to add its service accounts to your project '
            '({0}) as Editors. This will enable Cloud Machine Learning to access '
            'resources in your project when running your training and '
            'prediction jobs.'.format(project),
            cancel_on_no=True)

        # Get service account information from cloud ml service.
        req = msgs.MlProjectsGetConfigRequest(projectsId=project)
        resp = client.projects.GetConfig(req)

        # Add cloud ml service account.
        cloud_ml_service_account = 'serviceAccount:' + resp.serviceAccount
        projects_api.AddIamPolicyBinding(project_ref, cloud_ml_service_account,
                                         EDITOR_ROLE)
        log.status.Print('Added {0} as an Editor to project \'{1}\'.'.format(
            cloud_ml_service_account, project))
Exemple #27
0
    def Args(parser):
        """Args is called by calliope to gather arguments for this command.

    Args:
      parser: An argparse parser that you can use to add arguments that go
          on the command line after this command. Positional arguments are
          allowed.
    """
        parser.add_argument(
            '--async',
            help=
            'Return immediately and print information about the Operation in '
            'progress rather than waiting for the Operation to complete. '
            '(default=False)',
            dest='async',
            default=False,
            action='store_true')

        parser.add_argument('deployment_name', help='Deployment name.')

        parser.add_argument(
            '--config',
            help='Filename of config which specifies resources to deploy. '
            'Required unless launching an already-previewed update to this '
            'deployment.',
            dest='config')

        parser.add_argument(
            '--properties',
            type=arg_parsers.ArgDict(),
            help='A comma seperated, key=value, map '
            'to be used when deploying a template file directly.',
            dest='properties')

        parser.add_argument(
            '--preview',
            help='Preview the requested update without making any changes to the'
            'underlying resources. (default=False)',
            dest='preview',
            default=False,
            action='store_true')

        v2_messages = core_apis.GetMessagesModule('deploymentmanager', 'v2')
        parser.add_argument(
            '--create-policy',
            help='Create policy for resources that have changed in the update. '
            'Can be CREATE_OR_ACQUIRE (default) or ACQUIRE.',
            dest='create_policy',
            default='CREATE_OR_ACQUIRE',
            choices=(v2_messages.DeploymentmanagerDeploymentsUpdateRequest.
                     CreatePolicyValueValuesEnum.to_dict().keys()))

        parser.add_argument(
            '--delete-policy',
            help='Delete policy for resources that have changed in the update. '
            'Can be DELETE (default) or ABANDON.',
            dest='delete_policy',
            default='DELETE',
            choices=(v2_messages.DeploymentmanagerDeploymentsUpdateRequest.
                     DeletePolicyValueValuesEnum.to_dict().keys()))
Exemple #28
0
def GetCallerViews():
  messages = apis.GetMessagesModule('servicemanagement', 'v1')
  get_request = messages.ServicemanagementServicesProjectSettingsGetRequest
  return {
      'CONSUMER': get_request.ViewValueValuesEnum.CONSUMER_VIEW,
      'PRODUCER': get_request.ViewValueValuesEnum.PRODUCER_VIEW,
      'ALL': get_request.ViewValueValuesEnum.ALL,
  }
Exemple #29
0
def Get(instance):
    """Get an instance by name."""
    client = apis.GetClientInstance('spanner', 'v1')
    msgs = apis.GetMessagesModule('spanner', 'v1')
    ref = resources.REGISTRY.Parse(instance,
                                   collection='spanner.projects.instances')
    req = msgs.SpannerProjectsInstancesGetRequest(name=ref.RelativeName())
    return client.projects_instances.Get(req)
Exemple #30
0
def Create(job):
    client = apis.GetClientInstance('ml', 'v1beta1')
    msgs = apis.GetMessagesModule('ml', 'v1beta1')
    req = msgs.MlProjectsJobsCreateRequest(
        projectsId=properties.VALUES.core.project.Get(),
        googleCloudMlV1beta1Job=job)
    resp = client.projects_jobs.Create(req)
    return resp