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 metric. """ # Calling the API's Update method on a non-existing metric creates it. # Make sure the metric exists so we don't accidentally create it. metric = util.GetClient().projects_metrics.Get(util.GetMessages( ).LoggingProjectsMetricsGetRequest(metricName=util.CreateResourceName( util.GetCurrentProjectParent(), 'metrics', args.metric_name))) updated_metric = util.UpdateLogMetric(metric, description=args.description, log_filter=args.log_filter) result = util.GetClient().projects_metrics.Update( util.GetMessages().LoggingProjectsMetricsUpdateRequest( metricName=util.CreateResourceName( util.GetCurrentProjectParent(), 'metrics', args.metric_name), logMetric=updated_metric)) log.UpdatedResource(args.metric_name) 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 created view. """ view_data = {} if args.IsSpecified('description'): view_data['description'] = args.description if args.IsSpecified('log_filter'): view_data['filter'] = args.log_filter return util.GetClient().projects_locations_buckets_views.Create( util.GetMessages( ).LoggingProjectsLocationsBucketsViewsCreateRequest( viewId=args.VIEW_ID, parent=util.CreateResourceName( util.CreateResourceName( util.GetProjectResource(args.project).RelativeName(), 'locations', args.location), 'buckets', args.bucket), logView=util.GetMessages().LogView(**view_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 created bucket. """ bucket_data = {} if args.IsSpecified('retention_days'): bucket_data['retentionDays'] = args.retention_days if args.IsSpecified('description'): bucket_data['description'] = args.description if args.IsSpecified('enable_analytics'): bucket_data['analyticsEnabled'] = args.enable_analytics return util.GetClient().projects_locations_buckets.Create( util.GetMessages().LoggingProjectsLocationsBucketsCreateRequest( bucketId=args.BUCKET_ID, parent=util.CreateResourceName( util.GetProjectResource(args.project).RelativeName(), 'locations', args.location), logBucket=util.GetMessages().LogBucket(**bucket_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 updated CMEK settings. """ cmek_settings = {} update_mask = [] if hasattr(args.CONCEPTS, 'kms_key_name'): if args.kms_key_name is '': cmek_settings['kmsKeyName'] = '' else: cmek_settings['kmsKeyName'] = ( args.CONCEPTS.kms_key_name.Parse().RelativeName()) update_mask.append('kms_key_name') parent_name = util.GetParentFromArgs(args) return util.GetClient().organizations.UpdateCmekSettings( util.GetMessages().LoggingOrganizationsUpdateCmekSettingsRequest( name=parent_name, cmekSettings=util.GetMessages().CmekSettings(**cmek_settings), updateMask=','.join(update_mask)))
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(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 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 _Run(self, args, is_alpha=False): bucket_data = {} if args.IsSpecified('retention_days'): bucket_data['retentionDays'] = args.retention_days if args.IsSpecified('description'): bucket_data['description'] = args.description if args.IsSpecified('restricted_fields'): bucket_data['restrictedFields'] = args.restricted_fields if is_alpha and args.IsSpecified('enable_analytics'): bucket_data['analyticsEnabled'] = args.enable_analytics if is_alpha and args.IsSpecified('index'): bucket_data['indexConfigs'] = args.index if is_alpha and args.IsSpecified('cmek_kms_key_name'): console_io.PromptContinue( 'CMEK cannot be disabled on a bucket once enabled.', cancel_on_no=True) cmek_settings = util.GetMessages().CmekSettings( kmsKeyName=args.cmek_kms_key_name) bucket_data['cmekSettings'] = cmek_settings return util.GetClient().projects_locations_buckets.Create( util.GetMessages().LoggingProjectsLocationsBucketsCreateRequest( bucketId=args.BUCKET_ID, parent=util.CreateResourceName( util.GetProjectResource(args.project).RelativeName(), 'locations', args.location), logBucket=util.GetMessages().LogBucket(**bucket_data)))
def testDeletePromptYes(self): self.WriteInput('Y') self.mock_client_v2.projects_metrics.Delete.Expect( util.GetMessages().LoggingProjectsMetricsDeleteRequest( metricName='projects/my-project/metrics/my-metric'), util.GetMessages().Empty()) self.RunLogging('metrics delete my-metric') self.AssertErrContains('Deleted [my-metric]')
def SetUp(self): self._metrics = [ util.GetMessages().LogMetric( name='my-metric', description='my-metric description', filter='my-metric filter'), util.GetMessages().LogMetric( name='my-metric2', description='my-metric2 description', filter='my-metric2 filter')]
def testCreateNoPerms(self): new_metric = util.GetMessages().LogMetric(name='my-metric', description='my-desc', filter='my-filter') self.mock_client_v2.projects_metrics.Create.Expect( util.GetMessages().LoggingProjectsMetricsCreateRequest( parent='projects/my-project', logMetric=new_metric), exception=http_error.MakeHttpError(403)) self.RunWithoutPerms('metrics create my-metric --description=my-desc ' '--log-filter=my-filter')
def testCreateWithFlags(self): new_metric = util.GetMessages().LogMetric(name='my-metric', description='my-desc', filter='my-filter') self.mock_client_v2.projects_metrics.Create.Expect( util.GetMessages().LoggingProjectsMetricsCreateRequest( parent='projects/my-project', logMetric=new_metric), new_metric) self.RunLogging('metrics create my-metric --description=my-desc ' '--log-filter=my-filter') self.AssertOutputContains('') self.AssertErrContains('Created [my-metric]')
def testGet(self): test_metric = util.GetMessages().LogMetric( name='my-metric', description='my-metric description', filter='my-metric filter') self.mock_client_v2.projects_metrics.Get.Expect( util.GetMessages().LoggingProjectsMetricsGetRequest( metricName='projects/my-project/metrics/my-metric'), test_metric) self.RunLogging('metrics describe my-metric') self.AssertOutputContains(test_metric.name) self.AssertOutputContains(test_metric.description) self.AssertOutputContains(test_metric.filter)
def testUpdateMetricBadFile(self): test_metric = util.GetMessages().LogMetric( name='my-metric', description='my-metric description', filter='my-metric filter') self.mock_client_v2.projects_metrics.Get.Expect( util.GetMessages().LoggingProjectsMetricsGetRequest( metricName='projects/my-project/metrics/my-metric'), test_metric) self.Touch(self.cwd_path, 'bad.yaml', contents='[') with self.assertRaises(yaml.Error): self.RunLogging( 'metrics update my-metric --config-from-file {}'.format( os.path.join(self.cwd_path, 'bad.yaml')))
def CreateSink(self, parent, sink_data): """Creates a v2 sink specified by the arguments.""" messages = util.GetMessages() return util.GetClient().projects_sinks.Create( messages.LoggingProjectsSinksCreateRequest( parent=parent, logSink=messages.LogSink(**sink_data), uniqueWriterIdentity=True))
def GetSink(self, parent, sink_ref): """Returns a sink specified by the arguments.""" # Use V2 logging API. return util.GetClient().projects_sinks.Get( util.GetMessages().LoggingProjectsSinksGetRequest( sinkName=util.CreateResourceName(parent, 'sinks', sink_ref.sinksId)))
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: A long running operation. """ operation_name = util.CreateResourceName( util.CreateResourceName(util.GetParentFromArgs(args), 'locations', args.location), 'operations', args.operation_id) operation_reference = util.GetOperationReference( args.operation_id, args) console_io.PromptContinue('Really cancel operation [%s]?' % operation_name, cancel_on_no=True) request = util.GetMessages( ).LoggingProjectsLocationsOperationsCancelRequest(name=operation_name) util.GetClient().projects_locations_operations.Cancel(request) print('Cancelled [%s]' % operation_reference) print('Note:it may take up to 10 minutes for the ' "operation's status to be updated.")
def ListSinks(self, parent): """List sinks.""" # Use V2 logging API. result = util.GetClient().projects_sinks.List( util.GetMessages().LoggingProjectsSinksListRequest(parent=parent)) for sink in result.sinks: yield util.TypedLogSink(sink)
def testUpdateMetricFromFileSomeData(self): msgs = util.GetMessages() self.Touch(self.cwd_path, 'update.yaml', contents=('description: My fun filter.\n' 'filter: severity>=ERROR')) test_metric = msgs.LogMetric( name='my-metric', description='my-metric description', filter='my-metric filter', labelExtractors=msgs.LogMetric.LabelExtractorsValue( additionalProperties=[ msgs.LogMetric.LabelExtractorsValue.AdditionalProperty( key='label1', value='extractor1') ])) self.mock_client_v2.projects_metrics.Get.Expect( msgs.LoggingProjectsMetricsGetRequest( metricName='projects/my-project/metrics/my-metric'), test_metric) updated_metric = msgs.LogMetric( name='my-metric', description='My fun filter.', filter='severity>=ERROR', labelExtractors=msgs.LogMetric.LabelExtractorsValue( additionalProperties=[ msgs.LogMetric.LabelExtractorsValue.AdditionalProperty( key='label1', value='extractor1') ])) self.mock_client_v2.projects_metrics.Update.Expect( msgs.LoggingProjectsMetricsUpdateRequest( metricName='projects/my-project/metrics/my-metric', logMetric=updated_metric), updated_metric) self.RunLogging( 'metrics update my-metric --config-from-file {}'.format( os.path.join(self.cwd_path, 'update.yaml')))
def DeleteSink(self, parent, sink_ref): """Deletes a sink specified by the arguments.""" # Use V2 logging API. messages = util.GetMessages() return util.GetClient().projects_sinks.Delete( messages.LoggingProjectsSinksDeleteRequest( sinkName=util.CreateResourceName(parent, 'sinks', sink_ref.sinksId)))
def ListProjectSinks(self, project): """List project sinks from the specified project.""" # Use V2 logging API for project sinks. result = util.GetClient().projects_sinks.List( util.GetMessages().LoggingProjectsSinksListRequest( parent='projects/{0}'.format(project))) for sink in result.sinks: yield util.TypedLogSink(sink)
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)))
def UpdateSink(self, parent, sink_data): """Updates a sink specified by the arguments.""" messages = util.GetMessages() return util.GetClient().projects_sinks.Update( messages.LoggingProjectsSinksUpdateRequest( sinkName=util.CreateResourceName(parent, 'sinks', sink_data['name']), logSink=messages.LogSink(**sink_data), uniqueWriterIdentity=True))
def GetProjectSink(self): """Returns a project sink specified by the arguments.""" # Use V2 logging API for project sinks. sink_ref = self.context['sink_reference'] return util.GetClient().projects_sinks.Get( util.GetMessages().LoggingProjectsSinksGetRequest( sinkName=util.CreateResourceName( 'projects/{0}'.format(sink_ref.projectsId), 'sinks', sink_ref.sinksId)))
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 metric. """ # One of the flags is required to update the metric. if not (args.description or args.log_filter): raise exceptions.MinimumArgumentException( ['--description', '--log-filter']) # Calling the API's Update method on a non-existing metric creates it. # Make sure the metric exists so we don't accidentally create it. metric = util.GetClient().projects_metrics.Get(util.GetMessages( ).LoggingProjectsMetricsGetRequest(metricName=util.CreateResourceName( util.GetCurrentProjectParent(), 'metrics', args.metric_name))) if args.description: metric_description = args.description else: metric_description = metric.description if args.log_filter: metric_filter = args.log_filter else: metric_filter = metric.filter updated_metric = util.GetMessages().LogMetric( name=args.metric_name, description=metric_description, filter=metric_filter) result = util.GetClient().projects_metrics.Update( util.GetMessages().LoggingProjectsMetricsUpdateRequest( metricName=util.CreateResourceName( util.GetCurrentProjectParent(), 'metrics', args.metric_name), logMetric=updated_metric)) log.UpdatedResource(args.metric_name) return result
def PatchSink(self, parent, sink_data, update_mask): """Patches a sink specified by the arguments.""" messages = util.GetMessages() return util.GetClient().projects_sinks.Patch( messages.LoggingProjectsSinksPatchRequest( sinkName=util.CreateResourceName(parent, 'sinks', sink_data['name']), logSink=messages.LogSink(**sink_data), uniqueWriterIdentity=True, updateMask=','.join(update_mask)))
def CreateSink(self, parent, sink_data, unique_writer_identity): """Creates a v2 sink specified by the arguments.""" messages = util.GetMessages() # Change string value to enum. sink_data['outputVersionFormat'] = getattr( messages.LogSink.OutputVersionFormatValueValuesEnum, sink_data['outputVersionFormat']) return util.GetClient().projects_sinks.Create( messages.LoggingProjectsSinksCreateRequest( parent=parent, logSink=messages.LogSink(**sink_data), uniqueWriterIdentity=unique_writer_identity))
def _Run(self, args, is_alpha=False): bucket_data = {} if args.IsSpecified('retention_days'): bucket_data['retentionDays'] = args.retention_days if args.IsSpecified('description'): bucket_data['description'] = args.description if is_alpha and args.IsSpecified('enable_analytics'): bucket_data['analyticsEnabled'] = args.enable_analytics if is_alpha and args.IsSpecified('restricted_fields'): bucket_data['restrictedFields'] = args.restricted_fields return util.GetClient().projects_locations_buckets.Create( util.GetMessages().LoggingProjectsLocationsBucketsCreateRequest( bucketId=args.BUCKET_ID, parent=util.CreateResourceName( util.GetProjectResource(args.project).RelativeName(), 'locations', args.location), logBucket=util.GetMessages().LogBucket(**bucket_data)))
def DeleteProjectSink(self): """Deletes a project sink specified by the arguments.""" # Use V2 logging API for project sinks. messages = util.GetMessages() sink_ref = self.context['sink_reference'] # TODO(b/32504514): Use resource parser return util.GetClient().projects_sinks.Delete( messages.LoggingProjectsSinksDeleteRequest( sinkName=util.CreateResourceName( 'projects/{0}'.format(sink_ref.projectsId), 'sinks', sink_ref.sinksId)))
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. """ util.GetClient().projects_locations_buckets.Undelete( util.GetMessages().LoggingProjectsLocationsBucketsUndeleteRequest( name=util.CreateResourceName( util.CreateResourceName( util.GetParentFromArgs(args), 'locations', args.location), 'buckets', args.BUCKET_ID)))