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 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) """ client = util.GetApiClientInstance() function_ref = resources.REGISTRY.Parse( args.name, params={ 'projectsId': properties.VALUES.core.project.GetOrFail, 'locationsId': properties.VALUES.functions.region.GetOrFail, }, collection='cloudfunctions.projects.locations.functions') # 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: None Raises: FunctionsError: If the user doesn't confirm on prompt. """ client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE function_ref = resources.REGISTRY.Parse( args.name, params={ 'projectsId': properties.VALUES.core.project.GetOrFail, 'locationsId': properties.VALUES.functions.region.GetOrFail }, collection='cloudfunctions.projects.locations.functions') 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(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. Yields: Objects representing user functions. """ client = util.GetApiClientInstance() list_generator = list_pager.YieldFromList( service=client.projects_locations_functions, request=self.BuildRequest(args), limit=args.limit, field='functions', batch_size_attribute='pageSize') # Decorators (e.g. util.CatchHTTPErrorRaiseHTTPException) don't work # for generators. We have to catch the exception above the iteration loop, # but inside the function. try: for item in list_generator: yield item except exceptions.HttpError as error: msg = util.GetHttpErrorMessage(error) unused_type, unused_value, traceback = sys.exc_info() raise base_exceptions.HttpException, msg, traceback
def SetFunctionSourceProps(function, function_ref, source_arg, stage_bucket, ignore_file=None, update_date=False): """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. update_date: update file date in archive if it is older than 1980. Returns: A list of fields on the function that have been changed. """ 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, update_date=update_date) service = api_util.GetApiClientInstance().projects_locations_functions upload_url = UploadFile(zip_file, stage_bucket, messages, service, function_ref) if upload_url.startswith('gs://'): function.sourceArchiveUrl = upload_url return ['sourceArchiveUrl'] else: function.sourceUploadUrl = upload_url return ['sourceUploadUrl']
def _UpdateFunction(self, unused_location, function): client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE op = client.projects_locations_functions.Update(function) with progress_tracker.ProgressTracker( 'Deploying function (may take a while - up to 2 minutes)'): operations.Wait(op, messages, client) return self._GetExistingFunction(function.name)
def Run(self, args): client = util.GetApiClientInstance() messages = util.GetApiMessagesModule() locations = args.regions or [properties.VALUES.functions.region.GetOrFail()] project = properties.VALUES.core.project.GetOrFail() limit = args.limit return self._YieldFromLocations(locations, project, limit, messages, client)
def _CreateFunction(self, location, function): client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE op = client.projects_locations_functions.Create( messages.CloudfunctionsProjectsLocationsFunctionsCreateRequest( location=location, cloudFunction=function)) operations.Wait(op, messages, client, _DEPLOY_WAIT_NOTICE) return self._GetExistingFunction(function.name)
def _CreateFunction(self, location, function): client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE op = client.projects_locations_functions.Create( messages.CloudfunctionsProjectsLocationsFunctionsCreateRequest( location=location, cloudFunction=function)) with progress_tracker.ProgressTracker( 'Deploying function (may take a while - up to 2 minutes)'): operations.Wait(op, messages, client) return self._GetExistingFunction(function.name)
def _UpdateFunction(self, unused_location, function): client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE op = client.projects_locations_functions.Patch( messages.CloudfunctionsProjectsLocationsFunctionsPatchRequest( cloudFunction=function, name=function.name, updateMask=None, )) operations.Wait(op, messages, client, _DEPLOY_WAIT_NOTICE) return self._GetExistingFunction(function.name)
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 _GetExistingFunction(self, name): client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE try: # We got response for a get request so a function exists. return client.projects_locations_functions.Get( messages.CloudfunctionsProjectsLocationsFunctionsGetRequest( name=name)) except apitools_exceptions.HttpError as error: if error.status_code == httplib.NOT_FOUND: # The function has not been found. return None raise
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 exceptions.HttpError as error: msg = util.GetHttpErrorMessage(error) unused_type, unused_value, traceback = sys.exc_info() raise base_exceptions.HttpException, msg, traceback
def Run(self, args): client = util.GetApiClientInstance() messages = util.GetApiMessagesModule() locations = [] if args.regions: locations = args.regions if args.region: locations += [args.region] if not locations: locations = ['-'] project = properties.VALUES.core.project.GetOrFail() limit = args.limit return self._YieldFromLocations(locations, project, limit, messages, client)
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() return client.projects_locations_functions.Get( messages.CloudfunctionsProjectsLocationsFunctionsGetRequest( name=function_ref.RelativeName()))
def _ApplyArgsToFunction(self, function, is_new_function, trigger_params, function_ref, args, project): """Apply values from args to base_function. Args: function: function message to modify is_new_function: bool, indicates if this is a new function (and source code for it must be deployed) or an existing function (so it may keep its old source code). trigger_params: parameters for creating functions trigger. function_ref: reference to function. args: commandline args specyfying how to modify the function. project: project of the function. Returns: Pair of function and update mask. """ update_mask = [] messages = util.GetApiMessagesModule() client = util.GetApiClientInstance() self._ApplyNonSourceArgsToFunction(function, function_ref, update_mask, messages, args, trigger_params) # Only Add source to function if its explicitly provided, a new function, # using a stage budget or deploy of an existing function that previously # used local source if (args.source or args.stage_bucket or is_new_function or function.sourceUploadUrl): # deploy_util.AddSourceToFunction( function, function_ref, update_mask, args.source, args.stage_bucket, messages, client.projects_locations_functions) # Set information about deployment tool. labels_to_update = args.update_labels or {} labels_to_update['deployment-tool'] = 'cli-gcloud' labels_diff = labels_util.Diff(additions=labels_to_update, subtractions=args.remove_labels, clear=args.clear_labels) labels_update = labels_diff.Apply(messages.CloudFunction.LabelsValue, function.labels) if labels_update.needs_update: function.labels = labels_update.labels update_mask.append('labels') return function, ','.join(sorted(update_mask))
def SetFunctionSourceProps(function, function_ref, source_arg, stage_bucket): """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. Returns: A list of fields on the function that have been changed. """ 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://'): 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) service = api_util.GetApiClientInstance().projects_locations_functions upload_url = UploadFile(zip_file, stage_bucket, messages, service, function_ref) if upload_url.startswith('gs://'): function.sourceArchiveUrl = upload_url return ['sourceArchiveUrl'] else: function.sourceUploadUrl = upload_url return ['sourceUploadUrl']
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.AddBindingToIamPolicy(messages.Binding, 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): """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): """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 = resources.REGISTRY.Parse( args.name, params={ 'projectsId': properties.VALUES.core.project.GetOrFail, 'locationsId': properties.VALUES.functions.region.GetOrFail }, collection='cloudfunctions.projects.locations.functions') return client.projects_locations_functions.Get( messages.CloudfunctionsProjectsLocationsFunctionsGetRequest( name=function_ref.RelativeName()))
def _UpdateFunction(self, unused_location, function): client = util.GetApiClientInstance() messages = client.MESSAGES_MODULE op = client.projects_locations_functions.Update(function) operations.Wait(op, messages, client, _DEPLOY_WAIT_NOTICE) return self._GetExistingFunction(function.name)