コード例 #1
0
def Run(args, release_track):
    """Add an invoker binding to the IAM policy of a Google Cloud Function."""
    client = api_util.GetClientInstance(release_track=release_track)
    messages = api_util.GetMessagesModule(release_track=release_track)

    function_ref = args.CONCEPTS.name.Parse()
    function = client.projects_locations_functions.Get(
        messages.CloudfunctionsProjectsLocationsFunctionsGetRequest(
            name=function_ref.RelativeName()))

    service_ref_one_platform = resources.REGISTRY.ParseRelativeName(
        function.serviceConfig.service,
        CLOUD_RUN_SERVICE_COLLECTION_ONE_PLATFORM)

    run_connection_context = connection_context.RegionalConnectionContext(
        service_ref_one_platform.locationsId,
        global_methods.SERVERLESS_API_NAME,
        global_methods.SERVERLESS_API_VERSION)

    with serverless_operations.Connect(run_connection_context) as operations:
        service_ref_k8s = resources.REGISTRY.ParseRelativeName(
            'namespaces/{}/services/{}'.format(
                properties.VALUES.core.project.GetOrFail(),
                service_ref_one_platform.Name()),
            CLOUD_RUN_SERVICE_COLLECTION_K8S)

        return operations.AddOrRemoveIamPolicyBinding(
            service_ref_k8s,
            True,  # Add the binding
            member=args.member,
            role=serverless_operations.ALLOW_UNAUTH_POLICY_BINDING_ROLE)
コード例 #2
0
def Run(args, release_track):
    """Adds a binding to the IAM policy for a Google Cloud Function.

  Args:
    args: an argparse namespace. All the arguments that were provided to this
      command invocation.
    release_track: The relevant value from the
      googlecloudsdk.calliope.base.ReleaseTrack enum.

  Returns:
    The updated IAM policy.
  """
    client = api_util.GetClientInstance(release_track=release_track)
    messages = api_util.GetMessagesModule(release_track=release_track)

    function_ref = args.CONCEPTS.name.Parse()
    function_relative_name = function_ref.RelativeName()

    policy = client.projects_locations_functions.GetIamPolicy(
        messages.CloudfunctionsProjectsLocationsFunctionsGetIamPolicyRequest(
            resource=function_relative_name))

    iam_util.AddBindingToIamPolicy(messages.Binding, policy, args.member,
                                   args.role)

    return client.projects_locations_functions.SetIamPolicy(
        messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest(
            resource=function_relative_name,
            setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)))
コード例 #3
0
def Run(args, release_track):
  """Display details of a Google Cloud Function."""
  client = api_util.GetClientInstance(release_track=release_track)
  messages = api_util.GetMessagesModule(release_track=release_track)

  function_ref = args.CONCEPTS.name.Parse()

  return client.projects_locations_functions.Get(
      messages.CloudfunctionsProjectsLocationsFunctionsGetRequest(
          name=function_ref.RelativeName()))
コード例 #4
0
def Run(args, release_track):
    """Get the IAM policy for a Google Cloud Function."""
    client = api_util.GetClientInstance(release_track=release_track)
    messages = api_util.GetMessagesModule(release_track=release_track)

    function_ref = args.CONCEPTS.name.Parse()
    function_relative_name = function_ref.RelativeName()

    return client.projects_locations_functions.GetIamPolicy(
        messages.CloudfunctionsProjectsLocationsFunctionsGetIamPolicyRequest(
            resource=function_relative_name))
コード例 #5
0
def Run(args, release_track):
  """Set the IAM policy for a Google Cloud Function."""
  client = api_util.GetClientInstance(release_track=release_track)
  messages = api_util.GetMessagesModule(release_track=release_track)

  function_ref = args.CONCEPTS.name.Parse()
  function_relative_name = function_ref.RelativeName()

  policy, update_mask = iam_util.ParseYamlOrJsonPolicyFile(
      args.policy_file, messages.Policy)

  return client.projects_locations_functions.SetIamPolicy(
      messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest(
          resource=function_relative_name,
          setIamPolicyRequest=messages.SetIamPolicyRequest(
              policy=policy, updateMask=update_mask)))
コード例 #6
0
def Run(args, release_track):
    """Removes a binding from the IAM policy for a Google Cloud Function."""
    client = api_util.GetClientInstance(release_track=release_track)
    messages = api_util.GetMessagesModule(release_track=release_track)

    function_ref = args.CONCEPTS.name.Parse()
    function_relative_name = function_ref.RelativeName()

    policy = client.projects_locations_functions.GetIamPolicy(
        messages.CloudfunctionsProjectsLocationsFunctionsGetIamPolicyRequest(
            resource=function_relative_name))

    iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)

    return client.projects_locations_functions.SetIamPolicy(
        messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest(
            resource=function_relative_name,
            setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)))
コード例 #7
0
def Run(args, release_track):
    """Delete a Google Cloud Function."""
    client = api_util.GetClientInstance(release_track=release_track)
    messages = api_util.GetMessagesModule(release_track=release_track)

    function_ref = args.CONCEPTS.name.Parse()
    function_relative_name = function_ref.RelativeName()

    prompt_message = 'Function [{0}] will be deleted.'.format(
        function_relative_name)
    if not console_io.PromptContinue(message=prompt_message):
        raise exceptions.FunctionsError('Deletion aborted by user.')

    operation = client.projects_locations_functions.Delete(
        messages.CloudfunctionsProjectsLocationsFunctionsDeleteRequest(
            name=function_relative_name))
    api_util.WaitForOperation(client, messages, operation, 'Deleting function')

    log.DeletedResource(function_relative_name)
コード例 #8
0
def Run(args, release_track):
  """List Google Cloud Functions."""
  client = api_util.GetClientInstance(release_track=release_track)
  messages = api_util.GetMessagesModule(release_track=release_track)
  project = properties.VALUES.core.project.GetOrFail()
  limit = args.limit

  list_v2_generator = _YieldFromLocations(args.regions, project, limit,
                                          messages, client)

  # Currently GCF v2 exists in staging so users of GCF v2 have in their config
  # the api_endpoint_overrides of cloudfunctions.
  # To list GCF v1 resources use _OverrideEndpointOverrides to forcibly
  # overwrites's the user config's override with the original v1 endpoint.
  with _OverrideEndpointOverrides('cloudfunctions',
                                  'https://cloudfunctions.googleapis.com/'):
    client = api_v1_util.GetApiClientInstance()
    messages = api_v1_util.GetApiMessagesModule()
    list_v1_generator = command.YieldFromLocations(args.regions, project, limit,
                                                   messages, client)

  combined_generator = itertools.chain(list_v2_generator, list_v1_generator)
  return combined_generator
コード例 #9
0
ファイル: command.py プロジェクト: PrateekKhatri/gcloud_cli
def Run(args, release_track):
    """Run a function deployment with the given args."""
    client = api_util.GetClientInstance(release_track=release_track)
    messages = api_util.GetMessagesModule(release_track=release_track)

    function_ref = args.CONCEPTS.name.Parse()

    _ValidateLegacyV1Flags(args)

    function = messages.Function(name=function_ref.RelativeName(),
                                 buildConfig=_GetBuildConfig(args, messages),
                                 eventTrigger=_GetEventTrigger(args, messages),
                                 serviceConfig=_GetServiceConfig(
                                     args, messages))

    create_request = messages.CloudfunctionsProjectsLocationsFunctionsCreateRequest(
        parent='projects/%s/locations/%s' % (_GetProject(), args.region),
        functionId=function_ref.Name(),
        function=function)

    operation = client.projects_locations_functions.Create(create_request)

    api_util.WaitForOperation(client, messages, operation,
                              'Deploying function (may take a while)')
コード例 #10
0
def Run(args, release_track):
    """Runs a function deployment with the given args."""
    client = api_util.GetClientInstance(release_track=release_track)
    messages = api_util.GetMessagesModule(release_track=release_track)

    function_ref = args.CONCEPTS.name.Parse()

    _ValidateLegacyV1Flags(args)
    _ValidateUnsupportedV2Flags(args)

    existing_function = _GetFunction(client, messages, function_ref)

    is_new_function = existing_function is None
    if is_new_function and not args.runtime:
        if not console_io.CanPrompt():
            raise calliope_exceptions.RequiredArgumentException(
                'runtime', 'Flag `--runtime` is required for new functions.')
        gcf_client = api_client_v2.FunctionsClient(release_track=release_track)
        runtimes = [
            r.name
            for r in gcf_client.ListRuntimes(function_ref.locationsId).runtimes
        ]
        idx = console_io.PromptChoice(runtimes,
                                      message='Please select a runtime:\n')
        args.runtime = runtimes[idx]
        log.status.Print(
            'To skip this prompt, add `--runtime={}` to your command next time.\n'
            .format(args.runtime))

    if existing_function and existing_function.serviceConfig:
        has_all_traffic_on_latest_revision = existing_function.serviceConfig.allTrafficOnLatestRevision
        if (has_all_traffic_on_latest_revision is not None
                and not has_all_traffic_on_latest_revision):
            log.warning(_LATEST_REVISION_TRAFFIC_WARNING_MESSAGE)

    event_trigger, trigger_updated_fields = _GetEventTrigger(
        args, messages, existing_function)

    build_config, build_updated_fields = _GetBuildConfig(
        args, client, messages, function_ref.locationsId, function_ref.Name(),
        existing_function)

    service_config, service_updated_fields = _GetServiceConfig(
        args, messages, existing_function)

    labels_value, labels_updated_fields = _GetLabels(args, messages,
                                                     existing_function)

    # cs/symbol:google.cloud.functions.v2main.Function$
    function = messages.Function(name=function_ref.RelativeName(),
                                 buildConfig=build_config,
                                 eventTrigger=event_trigger,
                                 serviceConfig=service_config,
                                 labels=labels_value)

    if is_new_function:
        _CreateAndWait(client, messages, function_ref, function)
    else:
        _UpdateAndWait(
            client, messages, function_ref, function,
            frozenset.union(trigger_updated_fields, build_updated_fields,
                            service_updated_fields, labels_updated_fields))

    function = client.projects_locations_functions.Get(
        messages.CloudfunctionsProjectsLocationsFunctionsGetRequest(
            name=function_ref.RelativeName()))

    if event_trigger is None:
        _SetInvokerPermissions(args, function, is_new_function)

    log.status.Print(
        'You can view your function in the Cloud Console here: ' +
        'https://console.cloud.google.com/functions/details/{}/{}?project={}\n'
        .format(function_ref.locationsId, function_ref.Name(),
                properties.VALUES.core.project.GetOrFail()))

    return function
コード例 #11
0
def _Run(args, release_track):
    """Display log entries produced by Google Cloud Functions."""
    if args.execution_id:
        raise exceptions.FunctionsError(EXECUTION_ID_NOT_SUPPORTED)

    region = properties.VALUES.functions.region.GetOrFail()
    log_filter = [
        'resource.type="cloud_run_revision"',
        'resource.labels.location="%s"' % region,
        'logName:"run.googleapis.com"'
    ]

    if args.name:
        log_filter.append('resource.labels.service_name="%s"' % args.name)
    if args.min_log_level:
        log_filter.append('severity>=%s' % args.min_log_level.upper())

    log_filter.append('timestamp>="%s"' % logging_util.FormatTimestamp(
        args.start_time
        or datetime.datetime.utcnow() - datetime.timedelta(days=7)))

    if args.end_time:
        log_filter.append('timestamp<="%s"' %
                          logging_util.FormatTimestamp(args.end_time))

    log_filter = ' '.join(log_filter)

    entries = list(
        logging_common.FetchLogs(log_filter, order_by='DESC',
                                 limit=args.limit))

    if args.name and not entries:
        # Check if the function even exists in the given region.
        try:
            client = api_util.GetClientInstance(release_track=release_track)
            messages = api_util.GetMessagesModule(release_track=release_track)
            client.projects_locations_functions.Get(
                messages.CloudfunctionsProjectsLocationsFunctionsGetRequest(
                    name='projects/%s/locations/%s/functions/%s' %
                    (properties.VALUES.core.project.GetOrFail(), region,
                     args.name)))
        except (HttpForbiddenError, HttpNotFoundError):
            # The function doesn't exist in the given region.
            log.warning(
                'There is no function named `%s` in region `%s`. Perhaps you '
                'meant to specify `--region` or update the `functions/region` '
                'configuration property?' % (args.name, region))

    for entry in entries:
        message = entry.textPayload
        if entry.jsonPayload:
            props = [
                prop.value for prop in entry.jsonPayload.additionalProperties
                if prop.key == 'message'
            ]
            if len(props) == 1 and hasattr(props[0], 'string_value'):
                message = props[0].string_value
        row = {'log': message}
        if entry.severity:
            severity = six.text_type(entry.severity)
            if severity in flags.SEVERITIES:
                # Use short form (first letter) for expected severities.
                row['level'] = severity[0]
            else:
                # Print full form of unexpected severities.
                row['level'] = severity
        if entry.resource and entry.resource.labels:
            for label in entry.resource.labels.additionalProperties:
                if label.key == 'service_name':
                    row['name'] = label.value
        if entry.timestamp:
            row['time_utc'] = api_util.FormatTimestamp(entry.timestamp)
        yield row
コード例 #12
0
 def __init__(self, release_track):
     self.client = util.GetClientInstance(release_track)
     self.messages = util.GetMessagesModule(release_track)