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: Function call results (error or result with execution id) """ if args.data: try: json.loads(args.data) except ValueError as e: raise exceptions.InvalidArgumentException( '--data', 'Is not a valid JSON: ' + six.text_type(e)) client = util.GetApiClientInstance() function_ref = args.CONCEPTS.name.Parse() # Do not retry calling function - most likely user want to know that the # call failed and debug. client.projects_locations_functions.client.num_retries = 0 messages = client.MESSAGES_MODULE return client.projects_locations_functions.Call( messages.CloudfunctionsProjectsLocationsFunctionsCallRequest( name=function_ref.RelativeName(), callFunctionRequest=messages.CallFunctionRequest( data=args.data)))
def SetFunctionSourceProps(function, function_ref, source_arg, stage_bucket, ignore_file=None, kms_key=None): """Add sources to function. Args: function: The function to add a source to. function_ref: The reference to the function. source_arg: Location of source code to deploy. stage_bucket: The name of the Google Cloud Storage bucket where source code will be stored. ignore_file: custom ignore_file name. Override .gcloudignore file to customize files to be skipped. kms_key: KMS key configured for the function. Returns: A list of fields on the function that have been changed. Raises: FunctionsError: If the kms_key doesn't exist or GCF P4SA lacks permissions. """ function.sourceArchiveUrl = None function.sourceRepository = None function.sourceUploadUrl = None messages = api_util.GetApiMessagesModule() if source_arg is None: source_arg = '.' source_arg = source_arg or '.' if source_arg.startswith('gs://'): if not source_arg.endswith('.zip'): # Users may have .zip archives with unusual names, and we don't want to # prevent those from being deployed; the deployment should go through so # just warn here. log.warning( '[{}] does not end with extension `.zip`. ' 'The `--source` argument must designate the zipped source archive ' 'when providing a Google Cloud Storage URI.'.format( source_arg)) function.sourceArchiveUrl = source_arg return ['sourceArchiveUrl'] elif source_arg.startswith('https://'): function.sourceRepository = messages.SourceRepository( url=_AddDefaultBranch(source_arg)) return ['sourceRepository'] with file_utils.TemporaryDirectory() as tmp_dir: zip_file = _CreateSourcesZipFile(tmp_dir, source_arg, ignore_file) service = api_util.GetApiClientInstance().projects_locations_functions upload_url = UploadFile(zip_file, stage_bucket, messages, service, function_ref, kms_key) if upload_url.startswith('gs://'): function.sourceArchiveUrl = upload_url return ['sourceArchiveUrl'] else: function.sourceUploadUrl = upload_url return ['sourceUploadUrl']
def Run(args): """Display details of a Google Cloud Function.""" client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE function_ref = args.CONCEPTS.name.Parse() return client.projects_locations_functions.Get( messages.CloudfunctionsProjectsLocationsFunctionsGetRequest( name=function_ref.RelativeName()))
def Run(args): """List Google Cloud Functions.""" client = util.GetApiClientInstance() messages = util.GetApiMessagesModule() project = properties.VALUES.core.project.GetOrFail() limit = args.limit return YieldFromLocations(args.regions, project, limit, messages, client)
def Run(self, args): client = util.GetApiClientInstance() messages = util.GetApiMessagesModule() if args.regions: locations = args.regions else: locations = ['-'] project = properties.VALUES.core.project.GetOrFail() limit = args.limit return self._YieldFromLocations(locations, project, limit, messages, client)
def Run(args): """Remove a binding from the IAM policy for a Google Cloud Function.""" client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE function_ref = args.CONCEPTS.name.Parse() policy = client.projects_locations_functions.GetIamPolicy( messages.CloudfunctionsProjectsLocationsFunctionsGetIamPolicyRequest( resource=function_ref.RelativeName())) iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role) return client.projects_locations_functions.SetIamPolicy( messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest( resource=function_ref.RelativeName(), setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)))
def Run(self, args): client = util.GetApiClientInstance() list_generator = list_pager.YieldFromList( service=client.projects_locations, request=self._BuildRequest(), field='locations', batch_size_attribute='pageSize') try: for item in list_generator: yield item except api_exceptions.HttpError as error: msg = util.GetHttpErrorMessage(error) exceptions.reraise(base_exceptions.HttpException(msg))
def Run(args): """Set the IAM policy for a Google Cloud Function.""" client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE function_ref = args.CONCEPTS.name.Parse() policy, update_mask = iam_util.ParseYamlOrJsonPolicyFile( args.policy_file, messages.Policy) result = client.projects_locations_functions.SetIamPolicy( messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest( resource=function_ref.RelativeName(), setIamPolicyRequest=messages.SetIamPolicyRequest( policy=policy, updateMask=update_mask))) iam_util.LogSetIamPolicy(function_ref.Name(), 'function') return result
def Run(args): """Delete a Google Cloud Function.""" client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE function_ref = args.CONCEPTS.name.Parse() function__url = function_ref.RelativeName() prompt_message = 'Resource [{0}] will be deleted.'.format(function__url) if not console_io.PromptContinue(message=prompt_message): raise exceptions.FunctionsError('Deletion aborted by user.') op = client.projects_locations_functions.Delete( messages.CloudfunctionsProjectsLocationsFunctionsDeleteRequest( name=function__url)) operations.Wait(op, messages, client) log.DeletedResource(function__url)
def Run(args): """Lists regions available with the given args.""" del args # unused by list command client = util.GetApiClientInstance() list_generator = list_pager.YieldFromList( service=client.projects_locations, request=_BuildRequest(), field='locations', batch_size_attribute='pageSize') try: for item in list_generator: yield item except api_exceptions.HttpError as error: msg = util.GetHttpErrorMessage(error) exceptions.reraise(base_exceptions.HttpException(msg))
def Run(args): """Call a v1 Google Cloud Function.""" if args.data: try: json.loads(args.data) except ValueError as e: raise exceptions.InvalidArgumentException( '--data', 'Is not a valid JSON: ' + six.text_type(e)) client = util.GetApiClientInstance() function_ref = args.CONCEPTS.name.Parse() # Do not retry calling function - most likely user want to know that the # call failed and debug. client.projects_locations_functions.client.num_retries = 0 messages = client.MESSAGES_MODULE return client.projects_locations_functions.Call( messages.CloudfunctionsProjectsLocationsFunctionsCallRequest( name=function_ref.RelativeName(), callFunctionRequest=messages.CallFunctionRequest(data=args.data)))
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: The specified function with its description and configured filter. """ client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE function_ref = args.CONCEPTS.name.Parse() policy = client.projects_locations_functions.GetIamPolicy( messages.CloudfunctionsProjectsLocationsFunctionsGetIamPolicyRequest( resource=function_ref.RelativeName())) iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role) return client.projects_locations_functions.SetIamPolicy( messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest( resource=function_ref.RelativeName(), setIamPolicyRequest=messages.SetIamPolicyRequest( policy=policy)))
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
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: The specified function with its description and configured filter. """ client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE function_ref = args.CONCEPTS.name.Parse() policy, update_mask = iam_util.ParseYamlOrJsonPolicyFile( args.policy_file, messages.Policy) result = client.projects_locations_functions.SetIamPolicy( messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest( resource=function_ref.RelativeName(), setIamPolicyRequest=messages.SetIamPolicyRequest( policy=policy, updateMask=update_mask))) iam_util.LogSetIamPolicy(function_ref.Name(), 'function') return result
def _Run(self, args): region = properties.VALUES.functions.region.Get() log_filter = [ 'resource.type="cloud_function"', 'resource.labels.region="%s"' % region, 'logName:"cloud-functions"' ] if args.name: log_filter.append('resource.labels.function_name="%s"' % args.name) if args.execution_id: log_filter.append('labels.execution_id="%s"' % args.execution_id) 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='ASC', limit=args.limit)) if args.name and not entries: # Check if the function even exists in the given region. try: client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE client.projects_locations_functions.Get( messages.CloudfunctionsProjectsLocationsFunctionsGetRequest( name='projects/%s/locations/%s/functions/%s' % (properties.VALUES.core.project.Get(required=True), 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 == 'function_name': row['name'] = label.value if entry.labels: for label in entry.labels.additionalProperties: if label.key == 'execution_id': row['execution_id'] = label.value if entry.timestamp: row['time_utc'] = util.FormatTimestamp(entry.timestamp) yield row