def Run(self, args): """Constructs and sends request. Args: args: argparse.Namespace, An object that contains the values for the arguments specified in the .Args() method. Returns: ProcessHttpResponse of the request made. """ client = api_util.AlloyDBClient(self.ReleaseTrack()) alloydb_client = client.alloydb_client alloydb_messages = client.alloydb_messages cluster_ref = client.resource_parser.Create( 'alloydb.projects.locations.clusters', projectsId=properties.VALUES.core.project.GetOrFail, locationsId=args.region, clustersId=args.cluster) req = cluster_helper.ConstructPatchRequestFromArgs( alloydb_messages, cluster_ref, args) if not req.updateMask: parameters = [ ('--automated-backup-* | --disable-automated-backup | ' '--clear-automated-backup') ] raise exceptions.MinimumArgumentException( parameters, 'Please specify at least one property to update') op = alloydb_client.projects_locations_clusters.Patch(req) op_ref = resources.REGISTRY.ParseRelativeName( op.name, collection='alloydb.projects.locations.operations') log.status.Print('Operation ID: {}'.format(op_ref.Name())) if not args.async_: cluster_operations.Await(op_ref, 'Updating cluster', self.ReleaseTrack(), False) return op
def Run(cls, release_track, args, support_redirect): """Validates arguments and patches a security policy rule.""" if not any([ args.description, args.src_ip_ranges, args.expression, args.action, args.preview is not None ]): raise exceptions.MinimumArgumentException([ '--description', '--src-ip-ranges', '--expression', '--action', '--preview' ], 'At least one property must be modified.') holder = base_classes.ComputeApiHolder(release_track) ref = holder.resources.Parse( args.name, collection='compute.securityPolicyRules', params={ 'project': properties.VALUES.core.project.GetOrFail, 'securityPolicy': args.security_policy }) security_policy_rule = client.SecurityPolicyRule( ref, compute_client=holder.client) redirect_target = None if support_redirect: redirect_target = args.redirect_target return security_policy_rule.Patch(src_ip_ranges=args.src_ip_ranges, expression=args.expression, action=args.action, description=args.description, preview=args.preview, redirect_target=redirect_target)
def GetZone(args, ignore_property=False, required=True): """Get a zone from argument or property. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. ignore_property: bool, if true, will get location only from argument. required: bool, if true, lack of zone will cause raise an exception. Raises: MinimumArgumentException: if location if required and not provided. Returns: str, a zone selected by user. """ zone = getattr(args, 'zone', None) if ignore_property: zone_property = None else: zone_property = properties.VALUES.compute.zone.Get() if required and not zone and not zone_property: raise calliope_exceptions.MinimumArgumentException( ['--zone'], 'Please specify zone') return zone or zone_property
def _GetNamesAndAddresses(self, args): """Returns names and addresses provided in args.""" if not args.addresses and not args.name: raise exceptions.MinimumArgumentException( ['NAME', '--address'], 'At least one name or address must be provided.') if args.name: names = args.name else: # If we dont have any names then we must some addresses. names = [name_generator.GenerateRandomName() for _ in args.addresses] if args.addresses: addresses = args.addresses else: # If we dont have any addresses then we must some names. addresses = [None] * len(args.name) if len(addresses) != len(names): raise exceptions.BadArgumentException( '--addresses', 'If providing both, you must specify the same number of names as ' 'addresses.') return names, addresses
def UpdateDomainMapping(self, domain, certificate_id, no_certificate_id): """Updates a domain mapping for the given application. Args: domain: str, the custom domain string. certificate_id: str, a certificate id for the domain. no_certificate_id: boolean, remove the certificate id from the domain. Returns: The updated DomainMapping object. """ mask_fields = [] if certificate_id or no_certificate_id: mask_fields.append('sslSettings.certificateId') ssl = self.messages.SslSettings(certificateId=certificate_id) domain_mapping = self.messages.DomainMapping(id=domain, sslSettings=ssl) if not mask_fields: raise exceptions.MinimumArgumentException( 'Please specify at least one attribute to the domain-mapping update.') request = self.messages.AppengineAppsDomainMappingsPatchRequest( name=self._FormatDomainMapping(domain), domainMapping=domain_mapping, updateMask=','.join(mask_fields)) operation = requests.MakeRequest(self.client.apps_domainMappings.Patch, request) return operations_util.WaitForOperation(self.client.apps_operations, operation).response
def _GetKubeconfigAndContext(self, kubeconfig_file, context): """Gets the kubeconfig and cluster context from arguments and defaults. Args: kubeconfig_file: The kubecontext file to use context: The value of the context flag Returns: the kubeconfig filepath and context name Raises: calliope_exceptions.MinimumArgumentException: if a kubeconfig file cannot be deduced from the command line flags or environment exceptions.Error: if the context does not exist in the deduced kubeconfig file """ kubeconfig_file = ( kubeconfig_file or os.getenv('KUBECONFIG') or '~/.kube/config') kubeconfig = files.ExpandHomeDir(kubeconfig_file) if not kubeconfig: raise calliope_exceptions.MinimumArgumentException( ['--kubeconfig-file'], 'Please specify --kubeconfig, set the $KUBECONFIG environment ' 'variable, or ensure that $HOME/.kube/config exists') kc = kconfig.Kubeconfig.LoadFromFile(kubeconfig) context_name = context if context_name not in kc.contexts: raise exceptions.Error( 'context [{}] does not exist in kubeconfig [{}]'.format( context_name, kubeconfig)) return kubeconfig, context_name
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 updated sink with its new destination. """ sink_ref = util.GetTraceSinkResource(args.sink_name, args.project) sink_resource_name = sink_ref.RelativeName() sink_data = {'name': sink_resource_name} update_mask = [] if args.IsSpecified('destination'): sink_data['outputConfig'] = {'destination': args.destination} update_mask.append('output_config.destination') if not update_mask: raise calliope_exceptions.MinimumArgumentException( 'Please specify the destination to update') result = self.PatchSink(sink_resource_name, sink_data, update_mask) log.UpdatedResource(sink_ref) return util.FormatTraceSink(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 updated view. """ view_data = {} update_mask = [] parameter_names = ['--log-filter', '--description'] if args.IsSpecified('log_filter'): view_data['filter'] = args.log_filter update_mask.append('filter') if args.IsSpecified('description'): view_data['description'] = args.description update_mask.append('description') if not update_mask: raise calliope_exceptions.MinimumArgumentException( parameter_names, 'Please specify at least one property to update') return util.GetClient().projects_locations_buckets_views.Patch( util.GetMessages().LoggingProjectsLocationsBucketsViewsPatchRequest( name=util.CreateResourceName(util.CreateResourceName( util.CreateResourceName( util.GetProjectResource(args.project).RelativeName(), 'locations', args.location), 'buckets', args.bucket), 'views', args.VIEW_ID), logView=util.GetMessages().LogView(**view_data), updateMask=','.join(update_mask)))
def GetZoneOrRegion(args, ignore_property=False, required=True): """Get a location (zone or region) from argument or property. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. ignore_property: bool, if true, will get location only from argument. required: bool, if true, lack of zone will cause raise an exception. Raises: MinimumArgumentException: if location if required and not provided. ConflictingArgumentsException: if both --zone and --region arguments provided. Returns: str, a location selected by user. """ zone = getattr(args, 'zone', None) region = getattr(args, 'region', None) if ignore_property: zone_property = None else: zone_property = properties.VALUES.compute.zone.Get() if zone and region: raise calliope_exceptions.ConflictingArgumentsException( '--zone', '--region') location = region or zone or zone_property if required and not location: raise calliope_exceptions.MinimumArgumentException( ['--zone', '--region'], 'Please specify location.') return location
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 updated sink with its new destination. """ # One of the flags is required to update the sink. # log_filter can be an empty string, so check explicitly for None. if not args.destination and args.log_filter is None: raise calliope_exceptions.MinimumArgumentException( ['[destination]', '--log-filter'], 'Please specify at least one property to update') sink_ref = util.GetSinkReference(args.sink_name, args) # Calling Update on a non-existing sink creates it. # We need to make sure it exists, otherwise we would create it. sink = self.GetSink(util.GetParentFromArgs(args), sink_ref) # Only update fields that were passed to the command. if args.destination: destination = args.destination else: destination = sink.destination if args.log_filter is not None: log_filter = args.log_filter else: log_filter = sink.filter sink_data = { 'name': sink_ref.sinksId, 'destination': destination, 'filter': log_filter, 'includeChildren': sink.includeChildren, 'startTime': sink.startTime, 'endTime': sink.endTime } # Check for legacy configuration, and let users decide if they still want # to update the sink with new settings. if 'cloud-logs@' in sink.writerIdentity: console_io.PromptContinue( 'This update will create a new writerIdentity (service account) for ' 'the sink. In order for the sink to continue working, grant that ' 'service account correct permission on the destination. The service ' 'account will be displayed after a successful update operation.', cancel_on_no=True, default=False) result = self.UpdateSink(util.GetParentFromArgs(args), sink_data) log.UpdatedResource(sink_ref) self._epilog_result_destination = result.destination self._epilog_writer_identity = result.writerIdentity return result
def ParseAckIdsArgs(args): """Gets the list of ack_ids from args. This is only necessary because we are deprecating the positional `ack_id`. Putting the positional and a flag in an argument group, will group flag under positional args. This would be confusing. DeprecationAction can't be used here because in order to make the positional argument optional, we have to use `nargs='*'`. Since this means zero or more, the DeprecationAction warn message is always triggered. This function does not exist in util.py in order to group the explanation for why this exists with the deprecated flags. Once the positional is removed, this function can be removed. Args: args (argparse.Namespace): Parsed arguments Returns: list[str]: List of ack ids. """ if args.ack_id and args.ack_ids: raise exceptions.ConflictingArgumentsException('ACK_ID', '--ack-ids') elif not (args.ack_id or args.ack_ids): raise exceptions.MinimumArgumentException(['ACK_ID', '--ack-ids']) else: if args.ack_id: log.warning(DEPRECATION_FORMAT_STR.format('ACK_ID', '--ack-ids')) ack_ids = args.ack_id or args.ack_ids if not isinstance(ack_ids, list): ack_ids = [ack_ids] return ack_ids
def Run(self, args): secret_ref = args.CONCEPTS.secret.Parse() if not args.remove_cmek and not args.set_kms_key: raise calliope_exceptions.MinimumArgumentException( ['--remove-cmek', '--set-kms-key']) if args.remove_cmek and args.set_kms_key: raise calliope_exceptions.ConflictingArgumentsException( self.REMOVE_AND_SET_CMEK_MESSAGE) if args.remove_cmek and args.location: raise calliope_exceptions.ConflictingArgumentsException( self.REMOVE_CMEK_AND_LOCATION_MESSAGE) # args.set_kms_key without args.location is allowed only if the secret has # a single replica. # Attempt to get the secret secret = secrets_api.Secrets().GetOrNone(secret_ref) # Secret does not exist if secret is None: raise calliope_exceptions.InvalidArgumentException( 'secret', self.SECRET_MISSING_MESSAGE.format(secret=secret_ref.Name())) if args.remove_cmek: return self._RemoveCmek(secret_ref, secret) return self._SetKmsKey(secret_ref, secret, args.set_kms_key, args.location)
def Run(self, args): if not any([ args.description, args.src_ip_ranges, args.expression, args.action, args.preview is not None ]): raise exceptions.MinimumArgumentException([ '--description', '--src-ip-ranges', '--expression', '--action', '--preview' ], 'At least one property must be modified.') holder = base_classes.ComputeApiHolder(self.ReleaseTrack()) ref = holder.resources.Parse( args.name, collection='compute.securityPolicyRules', params={ 'project': properties.VALUES.core.project.GetOrFail, 'securityPolicy': args.security_policy }) security_policy_rule = client.SecurityPolicyRule( ref, compute_client=holder.client) return security_policy_rule.Patch(src_ip_ranges=args.src_ip_ranges, expression=args.expression, action=args.action, description=args.description, preview=args.preview)
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 updated bucket. """ bucket_data = {} update_mask = [] if args.IsSpecified('retention_days'): bucket_data['retentionDays'] = args.retention_days update_mask.append('retention_days') if args.IsSpecified('description'): bucket_data['description'] = args.description update_mask.append('description') if not update_mask: raise calliope_exceptions.MinimumArgumentException( ['--retention-days', '--description'], 'Please specify at least one property to update') return util.GetClient().projects_locations_buckets.Patch( util.GetMessages().LoggingProjectsLocationsBucketsPatchRequest( name=util.CreateResourceName( util.CreateResourceName( util.GetProjectResource(args.project).RelativeName(), 'locations', args.location), 'buckets', args.BUCKET_ID), logBucket=util.GetMessages().LogBucket(**bucket_data), updateMask=','.join(update_mask)))
def GetKubeconfigAndContext(args): """Get kubeconfig and context of the cluster from arguments. Args: args: command line arguments Returns: the kubeconfig and context name Raises: calliope_exceptions.MinimumArgumentException: if $KUBECONFIG is not set and --kubeconfig is not provided. c_util.Error: if the context provided in args (or the current context in the kubeconfig file if a context is not provided) does not exist. """ kubeconfig = args.kubeconfig_file or os.environ.get('KUBECONFIG') if not kubeconfig: raise calliope_exceptions.MinimumArgumentException([ '--from-kubeconfig' ], 'Please specify kubeconfig or set $KUBECONFIG environment variable') kc = kconfig.Kubeconfig.LoadFromFile(kubeconfig) context_name = args.context if not context_name: context_name = kc.current_context if not kc.contexts[context_name]: raise c_util.Error( 'context {0} does not exist in kubeconfig {1}'.format( context_name, kubeconfig)) return kubeconfig, context_name
def _Run(self, args, is_alpha=False): bucket_data = {} update_mask = [] parameter_names = ['--retention-days', '--description'] if args.IsSpecified('retention_days'): bucket_data['retentionDays'] = args.retention_days update_mask.append('retention_days') if args.IsSpecified('description'): bucket_data['description'] = args.description update_mask.append('description') if is_alpha: parameter_names.extend(['--locked']) if args.IsSpecified('locked'): bucket_data['locked'] = args.locked update_mask.append('locked') if args.locked: console_io.PromptContinue( 'WARNING: Locking a bucket cannot be undone.', default=False, cancel_on_no=True) if not update_mask: raise calliope_exceptions.MinimumArgumentException( parameter_names, 'Please specify at least one property to update') return util.GetClient().projects_locations_buckets.Patch( util.GetMessages().LoggingProjectsLocationsBucketsPatchRequest( name=util.CreateResourceName( util.CreateResourceName( util.GetProjectResource(args.project).RelativeName(), 'locations', args.location), 'buckets', args.BUCKET_ID), logBucket=util.GetMessages().LogBucket(**bucket_data), updateMask=','.join(update_mask)))
def Run(cls, release_track, args, support_redirect, support_rate_limit): """Validates arguments and patches a security policy rule.""" modified_fields = [ args.description, args.src_ip_ranges, args.expression, args.action, args.preview is not None ] min_args = [ '--description', '--src-ip-ranges', '--expression', '--action', '--preview' ] if support_redirect: modified_fields.append(args.redirect_target) min_args.append('--redirect_target') if support_rate_limit: modified_fields.extend([ args.rate_limit_threshold_count, args.rate_limit_threshold_interval_sec, args.conform_action, args.exceed_action, args.enforce_on_key, args.ban_threshold_count, args.ban_threshold_interval_sec, args.ban_duration_sec ]) min_args.extend([ '--rate-limit-threshold-count', '--rate-limit-threshold-interval-sec', '--conform-action', '--exceed-action', '--enforce-on-key', '--ban-threshold-count', '--ban-threshold-interval-sec', '--ban-duration-sec' ]) if not any(modified_fields): raise exceptions.MinimumArgumentException( min_args, 'At least one property must be modified.') holder = base_classes.ComputeApiHolder(release_track) ref = holder.resources.Parse( args.name, collection='compute.securityPolicyRules', params={ 'project': properties.VALUES.core.project.GetOrFail, 'securityPolicy': args.security_policy }) security_policy_rule = client.SecurityPolicyRule( ref, compute_client=holder.client) redirect_target = None rate_limit_options = None if support_redirect: redirect_target = args.redirect_target if support_rate_limit: rate_limit_options = ( security_policies_utils.CreateRateLimitOptions( holder.client, args)) return security_policy_rule.Patch( src_ip_ranges=args.src_ip_ranges, expression=args.expression, action=args.action, description=args.description, preview=args.preview, redirect_target=redirect_target, rate_limit_options=rate_limit_options)
def FallBackFlags(args): if (not args.organization and not args.folder and not args.project): args.organization = properties.VALUES.scc.organization.Get() if not args.organization: args.project = properties.VALUES.core.project.Get() if (not args.organization and not args.folder and not args.project): raise calliope_exceptions.MinimumArgumentException( ['--organization', '--folder', '--project'])
def CreateRequests(self, args): """Returns a list of requests necessary for adding images.""" image = self.messages.Image( name=args.name, description=args.description, sourceType=self.messages.Image.SourceTypeValueValuesEnum.RAW, family=args.family) csek_keys = csek_utils.CsekKeyStore.FromArgs( args, self._ALLOW_RSA_ENCRYPTED_CSEK_KEYS) if csek_keys: image_ref = self.resources.Parse(args.name, collection='compute.images') image.imageEncryptionKey = csek_utils.MaybeToMessage( csek_keys.LookupKey( image_ref, raise_if_missing=args.require_csek_key_create), self.compute_client.apitools_client) # Validate parameters. if args.source_disk_zone and not args.source_disk: raise exceptions.ToolException( 'You cannot specify [--source-disk-zone] unless you are specifying ' '[--source-disk].') if args.source_disk and args.source_uri: raise exceptions.ConflictingArgumentsException( '--source-uri', '--source-disk') if not (args.source_disk or args.source_uri): raise exceptions.MinimumArgumentException([ '--source-uri', '--source-disk' ], 'Please specify either the source disk or the Google Cloud Storage ' 'URI of the disk image.') # TODO(user): use resources.REGISTRY.Parse() for GCS URIs (b/30086260). if args.source_uri: source_uri = utils.NormalizeGoogleStorageUri(args.source_uri) image.rawDisk = self.messages.Image.RawDiskValue(source=source_uri) else: source_disk_ref = flags.SOURCE_DISK_ARG.ResolveAsResource( args, self.resources, scope_lister=compute_flags.GetDefaultScopeLister( self.compute_client, self.project)) image.sourceDisk = source_disk_ref.SelfLink() image.sourceDiskEncryptionKey = csek_utils.MaybeLookupKeyMessage( csek_keys, source_disk_ref, self.compute_client.apitools_client) if args.licenses: image.licenses = args.licenses request = self.messages.ComputeImagesInsertRequest( image=image, project=self.project) return [request]
def UpdateSslCertificate(self, cert_id, display_name=None, cert_path=None, private_key_path=None): """Updates a certificate for the given application. One of display_name, cert_path, or private_key_path should be set. Omitted fields will not be updated from their current value. Any invalid arguments will fail the entire command. Args: cert_id: str, the id of the certificate to update. display_name: str, the display name for a new certificate. cert_path: str, location on disk to a certificate file. private_key_path: str, location on disk to a private key file. Returns: The created AuthorizedCertificate object. Raises: InvalidInputError if the user does not specify both cert and key. """ if bool(cert_path) ^ bool(private_key_path): missing_arg = '--certificate' if not cert_path else '--private-key' raise exceptions.RequiredArgumentException( missing_arg, 'The certificate and the private key must both be updated together.' ) mask_fields = [] if display_name: mask_fields.append('displayName') cert_data = None if cert_path and private_key_path: certificate = files.ReadFileContents(cert_path) private_key = files.ReadFileContents(private_key_path) cert_data = self.messages.CertificateRawData( privateKey=private_key, publicCertificate=certificate) mask_fields.append('certificateRawData') auth_cert = self.messages.AuthorizedCertificate( displayName=display_name, certificateRawData=cert_data) if not mask_fields: raise exceptions.MinimumArgumentException([ '--certificate', '--private-key', '--display-name' ], 'Please specify at least one attribute to the certificate update.' ) request = self.messages.AppengineAppsAuthorizedCertificatesPatchRequest( name=self._FormatSslCert(cert_id), authorizedCertificate=auth_cert, updateMask=','.join(mask_fields)) return self.client.apps_authorizedCertificates.Patch(request)
def GetKubeconfigAndContext(self, flags, temp_kubeconfig_dir): """Gets the kubeconfig and cluster context from arguments and defaults. Args: flags: the flags passed to the enclosing command. It must include kubeconfig and context. temp_kubeconfig_dir: a TemporaryDirectoryObject. Returns: the kubeconfig filepath and context name Raises: calliope_exceptions.MinimumArgumentException: if a kubeconfig file cannot be deduced from the command line flags or environment exceptions.Error: if the context does not exist in the deduced kubeconfig file """ # Parsing flags to get the name and location of the GKE cluster to register if flags.gke_uri or flags.gke_cluster: location, name = _ParseGKEURI( flags.gke_uri) if flags.gke_uri else _ParseGKECluster( flags.gke_cluster) return _GetGKEKubeconfig(location, name, temp_kubeconfig_dir), None # We need to support in-cluster configuration so that gcloud can run from # a container on the Cluster we are registering. KUBERNETES_SERICE_PORT # and KUBERNETES_SERVICE_HOST environment variables are set in a kubernetes # cluster automatically, which can be used by kubectl to talk to # the API server. if not flags.kubeconfig and encoding.GetEncodedValue( os.environ, 'KUBERNETES_SERVICE_PORT') and encoding.GetEncodedValue( os.environ, 'KUBERNETES_SERVICE_HOST'): return None, None kubeconfig_file = (flags.kubeconfig or encoding.GetEncodedValue( os.environ, 'KUBECONFIG') or '~/.kube/config') kubeconfig = files.ExpandHomeDir(kubeconfig_file) if not kubeconfig: raise calliope_exceptions.MinimumArgumentException( ['--kubeconfig'], 'Please specify --kubeconfig, set the $KUBECONFIG environment ' 'variable, or ensure that $HOME/.kube/config exists') kc = kconfig.Kubeconfig.LoadFromFile(kubeconfig) context_name = flags.context if context_name not in kc.contexts: raise exceptions.Error( 'context [{}] does not exist in kubeconfig [{}]'.format( context_name, kubeconfig)) return kubeconfig, context_name
def _ValidateArgs(self, args): """Validates that at least one field to update is specified. Args: args: The arguments given to the update command. """ if not (args.IsSpecified('description') or args.IsSpecified('security_policy')): parameter_names = ['--description', '--security_policy'] raise exceptions.MinimumArgumentException( parameter_names, 'Please specify at least one property to update')
def _Run(self, args, support_dlp=False): sink_ref = util.GetSinkReference(args.sink_name, args) sink_data = {'name': sink_ref.sinksId} update_mask = [] if args.IsSpecified('destination'): sink_data['destination'] = args.destination update_mask.append('destination') if args.IsSpecified('log_filter'): sink_data['filter'] = args.log_filter update_mask.append('filter') parameter_names = ['[destination]', '--log-filter'] dlp_options = {} if support_dlp: parameter_names.extend( ['--dlp-inspect-template', '--dlp-deidentify-template']) if args.IsSpecified('dlp_inspect_template'): dlp_options['inspectTemplateName'] = args.dlp_inspect_template update_mask.append('dlp_options.inspect_template_name') if args.IsSpecified('dlp_deidentify_template'): dlp_options[ 'deidentifyTemplateName'] = args.dlp_deidentify_template update_mask.append('dlp_options.deidentify_template_name') if dlp_options: sink_data['dlpOptions'] = dlp_options if not update_mask: raise calliope_exceptions.MinimumArgumentException( parameter_names, 'Please specify at least one property to update') # Check for legacy configuration, and let users decide if they still want # to update the sink with new settings. sink = self.GetSink(util.GetParentFromArgs(args), sink_ref) if 'cloud-logs@' in sink.writerIdentity: console_io.PromptContinue( 'This update will create a new writerIdentity (service account) for ' 'the sink. In order for the sink to continue working, grant that ' 'service account correct permission on the destination. The service ' 'account will be displayed after a successful update operation.', cancel_on_no=True, default=False) result = self.PatchSink(util.GetParentFromArgs(args), sink_data, update_mask) log.UpdatedResource(sink_ref) self._epilog_result_destination = result.destination self._epilog_writer_identity = result.writerIdentity self._epilog_is_dlp_sink = bool(dlp_options) return result
def Run(self, args): """Runs the update command.""" contact_name = util.GetContactName(args) categories = util.GetNotificationCategories( args, contacts.GetContactNotificationCategoryEnum()) language = args.language if not language and not categories: raise exceptions.MinimumArgumentException( ['notification-categories', 'language']) client = contacts.ContactsClient() return client.Update(contact_name, categories, language)
def _ValidateArgs(self, args): """Validates that at least one field to update is specified. Args: args: The arguments given to the update command. """ if not (args.IsSpecified('total_count') or args.IsSpecified('start_time') or args.IsSpecified('end_time') or args.IsSpecified('duration')): parameter_names = [ '--total-count', '--start-time', '--end-time', '--duration' ] raise exceptions.MinimumArgumentException( parameter_names, 'Please specify at least one property to update')
def _ValidateArgs(self, args): """Validates that at least one field to update is specified. Args: args: The arguments given to the update-backend command. """ if not (args.IsSpecified('description') or args.IsSpecified('enable_layer7_ddos_defense') or args.IsSpecified('layer7_ddos_defense_rule_visibility')): parameter_names = [ '--description', '--enable-layer7-ddos-defense', '--layer7-ddos-defense-rule-visibility' ] raise exceptions.MinimumArgumentException( parameter_names, 'Please specify at least one property to update')
def ValidateSourceArgs(args, sources): """Validate that there is one, and only one, source for creating an image.""" sources_error_message = 'Please specify a source for image creation.' # Get the list of source arguments source_arg_list = [getattr(args, s.replace('-', '_')) for s in sources] # Count the number of source arguments that are specified. source_arg_count = sum(bool(a) for a in source_arg_list) source_arg_names = ['--' + s for s in sources] if source_arg_count > 1: raise exceptions.ConflictingArgumentsException(*source_arg_names) if source_arg_count < 1: raise exceptions.MinimumArgumentException(source_arg_names, sources_error_message)
def GetKubeconfigAndContext(self, flags): """Gets the kubeconfig and cluster context from arguments and defaults. Args: flags: the flags passed to the enclosing command. It must include kubeconfig and context. Returns: the kubeconfig filepath and context name Raises: calliope_exceptions.MinimumArgumentException: if a kubeconfig file cannot be deduced from the command line flags or environment exceptions.Error: if the context does not exist in the deduced kubeconfig file """ # We need to support in-cluster configuration so that gcloud can run from # a container on the Cluster we are registering. if not flags.kubeconfig and encoding.GetEncodedValue( os.environ, 'KUBERNETES_SERVICE_PORT') and encoding.GetEncodedValue( os.environ, 'KUBERNETES_SERVICE_HOST'): return None, None kubeconfig_file = (flags.kubeconfig or encoding.GetEncodedValue( os.environ, 'KUBECONFIG') or '~/.kube/config') kubeconfig = files.ExpandHomeDir(kubeconfig_file) if not kubeconfig: raise calliope_exceptions.MinimumArgumentException( ['--kubeconfig'], 'Please specify --kubeconfig, set the $KUBECONFIG environment ' 'variable, or ensure that $HOME/.kube/config exists') kc = kconfig.Kubeconfig.LoadFromFile(kubeconfig) context_name = flags.context if not context_name: raise exceptions.Error('argument --context: Must be specified.') if context_name not in kc.contexts: raise exceptions.Error( 'context [{}] does not exist in kubeconfig [{}]'.format( context_name, kubeconfig)) return kubeconfig, context_name
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: Cluster message for the successfully updated node pool. Raises: util.Error, if creation failed. """ adapter = self.context['api_adapter'] location_get = self.context['location_get'] location = location_get(args) pool_ref = adapter.ParseNodePool(args.name, location) options = self.ParseUpdateNodePoolOptions(args) if options.enable_autorepair is None and options.enable_autoupgrade is None: raise exceptions.MinimumArgumentException( ['--[no-]enable-autoupgrade', '--[no-]enable-autorepair'], 'Please reformat your request.') if options.enable_autorepair is not None: log.status.Print( messages.AutoUpdateUpgradeRepairMessage( options.enable_autorepair, 'autorepair')) if options.enable_autoupgrade is not None: log.status.Print( messages.AutoUpdateUpgradeRepairMessage( options.enable_autoupgrade, 'autoupgrade')) try: operation_ref = adapter.UpdateNodePool(pool_ref, options) adapter.WaitForOperation(operation_ref, 'Updating node pool {0}'.format( pool_ref.nodePoolId), timeout_s=args.timeout) pool = adapter.GetNodePool(pool_ref) except apitools_exceptions.HttpError as error: raise exceptions.HttpException(error, util.HTTP_ERROR_FORMAT) log.UpdatedResource(pool_ref) return pool
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 updated settings. """ settings = {} update_mask = [] parameter_names = [ '--kms-key-name | --clear-kms-key', '--storage-location', '--disable-default-sink' ] if args.IsSpecified('kms_key_name'): settings['kmsKeyName'] = ( args.CONCEPTS.kms_key_name.Parse().RelativeName()) update_mask.append('kms_key_name') if args.IsSpecified('clear_kms_key'): settings['kmsKeyName'] = '' update_mask.append('kms_key_name') if args.IsSpecified('storage_location'): settings['storageLocation'] = args.storage_location update_mask.append('storage_location') if args.IsSpecified('disable_default_sink'): settings['disableDefaultSink'] = args.disable_default_sink update_mask.append('disable_default_sink') if not update_mask: raise calliope_exceptions.MinimumArgumentException( parameter_names, 'Please specify at least one property to update.') parent_name = util.GetParentFromArgs(args) return util.GetClient().v2.UpdateSettings( util.GetMessages().LoggingUpdateSettingsRequest( name=parent_name, settings=util.GetMessages().Settings(**settings), updateMask=','.join(update_mask)))