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: 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 _Run(self, args): try: # pylint: disable=g-import-not-at-top from googlecloudsdk.api_lib.logging import tailing from googlecloudsdk.third_party.logging_v2.gapic.transports.logging_service_v2_grpc_transport import LoggingServiceV2GrpcTransport # pylint: enable=g-import-not-at-top except ImportError: raise NoGRPCInstalledError() log.err.Print('Initializing tail session.') parent = util.GetParentFromArgs(args) if args.IsSpecified('location'): parent = util.CreateResourceName( util.CreateResourceName( util.CreateResourceName(parent, 'locations', args.location), 'buckets', args.bucket), 'views', args.view) buffer_window_seconds = None if args.buffer_window: if args.buffer_window < 0 or args.buffer_window > 60: log.error('The buffer window must be set between 0s and 1m.') buffer_window_seconds = args.buffer_window transport = LoggingServiceV2GrpcTransport( credentials=StoredCredentials(), address='logging.googleapis.com:443') # By default and up to the INFO verbosity, all console output is included in # the log file. When tailing logs, coarse filters could cause very large # files. So, we limit the log file to WARNING logs and above. log.SetLogFileVerbosity(logging.WARNING) return tailing.TailLogs( bidi.BidiRpc(transport.tail_log_entries), [parent], args.log_filter or '', buffer_window_seconds=buffer_window_seconds)
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, 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 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): # Take into account freshness only if all requirements are met. if (args.freshness and args.order == 'desc' and (not args.log_filter or 'timestamp' not in args.log_filter)): # Argparser returns freshness in seconds. freshness = datetime.timedelta(seconds=args.freshness) # Cloud Logging uses timestamps in UTC timezone. last_timestamp = datetime.datetime.utcnow() - freshness # Construct timestamp filter. log_filter = ('timestamp>="%s"' % util.FormatTimestamp(last_timestamp)) # Append any user supplied filters. if args.log_filter: log_filter += ' AND %s' % args.log_filter else: log_filter = args.log_filter parent = util.GetParentFromArgs(args) if is_alpha and args.IsSpecified('location'): parent = util.CreateResourceName( util.CreateResourceName( util.CreateResourceName(parent, 'locations', args.location), 'buckets', args.bucket), 'views', args.view) return common.FetchLogs(log_filter, order_by=args.order, limit=args.limit, parent=parent)
def _Run(self, args): try: # pylint: disable=g-import-not-at-top from googlecloudsdk.api_lib.logging import tailing # pylint: enable=g-import-not-at-top except ImportError: raise NoGRPCInstalledError() log.err.Print('Initializing tail session.') parent = util.GetParentFromArgs(args) if args.IsSpecified('location'): parent = util.CreateResourceName( util.CreateResourceName( util.CreateResourceName(parent, 'locations', args.location), 'buckets', args.bucket), 'views', args.view) buffer_window_seconds = None if args.buffer_window: if args.buffer_window < 0 or args.buffer_window > 60: log.error('The buffer window must be set between 0s and 1m.') buffer_window_seconds = args.buffer_window tailer = tailing.LogTailer() # By default and up to the INFO verbosity, all console output is included in # the log file. When tailing logs, coarse filters could cause very large # files. So, we limit the log file to WARNING logs and above. log.SetLogFileVerbosity(logging.WARNING) return tailer.TailLogs([parent], args.log_filter or '', buffer_window_seconds=buffer_window_seconds)
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. """ util.GetClient().projects_locations_buckets.Undelete( util.GetMessages().LoggingProjectsLocationsBucketsUndeleteRequest( name=util.CreateResourceName( util.CreateResourceName( util.GetParentFromArgs(args), 'locations', args.location), 'buckets', args.BUCKET_ID)))
def _Run(self, args): if not args.log_filter: console_io.PromptContinue( 'An empty filter matches all log entries.', cancel_on_no=True) parent_name = util.CreateResourceName( util.CreateResourceName( util.GetParentFromArgs(args), 'locations', args.location), 'buckets', args.bucket_id) request = util.GetMessages().CopyLogEntriesRequest( destination=args.destination, filter=args.log_filter, name=parent_name) return util.GetClient().entries.Copy(request)
def _Run(self, args): filter_clauses = read_logs_lib.MakeTimestampFilters(args) filter_clauses += [args.log_filter] if args.log_filter else [] parent = util.GetParentFromArgs(args) if args.IsSpecified('location'): parent = util.CreateResourceName( util.CreateResourceName( util.CreateResourceName(parent, 'locations', args.location), 'buckets', args.bucket), 'views', args.view) return common.FetchLogs( read_logs_lib.JoinFilters(filter_clauses, operator='AND') or None, order_by=args.order, limit=args.limit, parent=parent)
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_views.Delete( util.GetMessages( ).LoggingProjectsLocationsBucketsViewsDeleteRequest( name=util.CreateResourceName( util.CreateResourceName( util.GetBucketLocationFromArgs(args), 'buckets', args.bucket), 'views', args.VIEW_ID))) log.DeletedResource(args.VIEW_ID)
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, 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 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 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 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 GetCurrentBucket(self, args): """Returns a bucket specified by the arguments. Loads the current bucket at most once. If called multiple times, the previously-loaded bucket will be returned. Args: args: The argument set. This is not checked across GetCurrentBucket calls, and must be consistent. """ if not self._current_bucket: return util.GetClient().projects_locations_buckets.Get( util.GetMessages().LoggingProjectsLocationsBucketsGetRequest( name=util.CreateResourceName( util.CreateResourceName( util.GetProjectResource( args.project).RelativeName(), 'locations', args.location), 'buckets', args.BUCKET_ID))) return self._current_bucket
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. """ console_io.PromptContinue( 'Really delete bucket [%s]? (You can undelete it within 7 days if you ' 'change your mind later)' % args.BUCKET_ID, cancel_on_no=True) util.GetClient().projects_locations_buckets.Delete( util.GetMessages().LoggingProjectsLocationsBucketsDeleteRequest( name=util.CreateResourceName( util.CreateResourceName(util.GetParentFromArgs( args), 'locations', args.location), 'buckets', args.BUCKET_ID))) log.DeletedResource(args.BUCKET_ID)
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 GetProjectSink(self): """Returns a project sink specified by the arguments.""" # Use V2 logging API for project sinks. client = self.context['logging_client_v2'] messages = self.context['logging_messages_v2'] sink_ref = self.context['sink_reference'] return client.projects_sinks.Get( messages.LoggingProjectsSinksGetRequest( sinkName=util.CreateResourceName( 'projects/{0}'.format(sink_ref.projectsId), 'sinks', sink_ref.sinksId)))
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 UpdateSink(self, parent, sink_data): """Updates a 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.Update( messages.LoggingProjectsSinksUpdateRequest( sinkName=util.CreateResourceName(parent, 'sinks', sink_data['name']), logSink=messages.LogSink(**sink_data), uniqueWriterIdentity=True))
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 metric with its description and configured filter. """ return util.GetClient().projects_metrics.Get(util.GetMessages( ).LoggingProjectsMetricsGetRequest(metricName=util.CreateResourceName( util.GetCurrentProjectParent(), 'metrics', args.metric_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 specified location """ return util.GetClient().projects_locations.Get( util.GetMessages().LoggingProjectsLocationsGetRequest( name=util.CreateResourceName(util.GetParentFromArgs(args), 'locations', args.LOCATION_ID)))
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 list of logs. """ project = properties.VALUES.core.project.Get(required=True) project_ref = resources.REGISTRY.Parse( project, collection='cloudresourcemanager.projects') parent = project_ref.RelativeName() if args.IsSpecified('view'): # We are replacing the parent with the resourceName path for a view # instead of populating the resourceNames field. # This is due to the parent being a legacy required field. parent = util.CreateResourceName( util.CreateResourceName( util.CreateResourceName(parent, 'locations', args.location), 'buckets', args.bucket), 'views', args.view) request = util.GetMessages().LoggingProjectsLogsListRequest( parent=parent) result = list_pager.YieldFromList(util.GetClient().projects_logs, request, field='logNames', limit=args.limit, batch_size=None, batch_size_attribute='pageSize') 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: A long running operation. """ parent_name = util.CreateResourceName( util.CreateResourceName(util.GetParentFromArgs(args), 'locations', args.location), 'operations', args.operation_id) request = util.GetMessages( ).LoggingProjectsLocationsOperationsGetRequest(name=parent_name) result = util.GetClient().projects_locations_operations.Get(request) serialize_op = resource_projector.MakeSerializable(result) self._cancellation_requested = serialize_op.get('metadata', {}).get( 'cancellationRequested', '') return result