Esempio n. 1
0
    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
Esempio n. 2
0
    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
Esempio n. 3
0
    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 sink with its destination.
    """
        util.CheckLegacySinksCommandArguments(args)

        sink_ref = util.GetSinkReference(args.sink_name, args.log,
                                         args.service)

        try:
            if args.log:
                return util.TypedLogSink(self.GetLogSink(sink_ref),
                                         log_name=args.log)
            elif args.service:
                return util.TypedLogSink(self.GetLogServiceSink(sink_ref),
                                         service_name=args.service)
            else:
                return util.TypedLogSink(
                    self.GetSink(util.GetParentFromArgs(args), sink_ref))
        except apitools_exceptions.HttpError as error:
            v2_sink = not args.log and not args.service
            # Suggest the user to add --log or --log-service flag.
            if v2_sink and exceptions.HttpException(
                    error).payload.status_code == 404:
                log.status.Print(
                    ('Sink was not found. '
                     'Did you forget to add --log or --log-service flag?'))
            raise error
Esempio n. 4
0
    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)
Esempio n. 5
0
    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.")
Esempio n. 6
0
  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)
Esempio n. 7
0
  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 sink with its destination.
    """
    if not args.log_filter:
      # Attempt to create a sink with an empty filter.
      console_io.PromptContinue(
          'Sink with empty filter matches all entries.', cancel_on_no=True)

    if args.include_children and not (args.organization or args.folder):
      log.warn('include-children only has an effect for sinks at the folder '
               'or organization level')

    sink_ref = util.GetSinkReference(args.sink_name, args)

    sink_data = {
        'name': sink_ref.sinksId,
        'destination': args.destination,
        'filter': args.log_filter,
        'includeChildren': args.include_children
    }

    result = self.CreateSink(util.GetParentFromArgs(args), sink_data)

    log.CreatedResource(sink_ref)
    self._epilog_result_destination = result.destination
    self._epilog_writer_identity = result.writerIdentity
    return result
    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)
Esempio n. 9
0
  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 log entries.
    """
    # 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

    return common.FetchLogs(log_filter,
                            order_by=args.order,
                            limit=args.limit,
                            parent=util.GetParentFromArgs(args))
Esempio n. 10
0
    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 sink with its destination.
    """
        if not args.log_filter:
            # Attempt to create a sink with an empty filter.
            console_io.PromptContinue(
                'Sink with empty filter matches all entries.',
                cancel_on_no=True)

        sink_ref = resources.REGISTRY.Parse(
            args.sink_name,
            params={'projectsId': properties.VALUES.core.project.GetOrFail},
            collection='logging.projects.sinks')

        sink_data = {
            'name': sink_ref.sinksId,
            'destination': args.destination,
            'filter': args.log_filter
        }

        result = util.TypedLogSink(
            self.CreateSink(util.GetParentFromArgs(args), sink_data))

        log.CreatedResource(sink_ref)
        self._epilog_result_destination = result.destination
        self._writer_identity = result.writer_identity
        return result
Esempio n. 11
0
  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)))
Esempio n. 12
0
    def _Run(self, args, is_alpha=False):
        if not args.log_filter:
            # Attempt to create a sink with an empty filter.
            console_io.PromptContinue(
                'Sink with empty filter matches all entries.',
                cancel_on_no=True)

        if args.include_children and not (args.organization or args.folder):
            log.warning(
                'include-children only has an effect for sinks at the folder '
                'or organization level')

        sink_ref = util.GetSinkReference(args.sink_name, args)

        sink_data = {
            'name': sink_ref.sinksId,
            'destination': args.destination,
            'filter': args.log_filter,
            'includeChildren': args.include_children
        }

        dlp_options = {}
        if is_alpha:
            if args.IsSpecified('dlp_inspect_template'):
                dlp_options['inspectTemplateName'] = args.dlp_inspect_template
            if args.IsSpecified('dlp_deidentify_template'):
                dlp_options[
                    'deidentifyTemplateName'] = args.dlp_deidentify_template
            if dlp_options:
                sink_data['dlpOptions'] = dlp_options

            if args.IsSpecified('use_partitioned_tables'):
                bigquery_options = {}
                bigquery_options[
                    'usePartitionedTables'] = args.use_partitioned_tables
                sink_data['bigqueryOptions'] = bigquery_options

            if args.IsSpecified('exclusion'):
                sink_data['exclusions'] = args.exclusion

            if args.IsSpecified('description'):
                sink_data['description'] = args.description

            if args.IsSpecified('disabled'):
                sink_data['disabled'] = args.disabled

        result = self.CreateSink(util.GetParentFromArgs(args), sink_data)

        log.CreatedResource(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):
    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)
Esempio n. 14
0
  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)))
Esempio n. 15
0
    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 CMEK settings for the specified project, folder, organizations
      or billing-account.
    """
        parent_name = util.GetParentFromArgs(args)
        return util.GetClient().v2.GetCmekSettings(
            util.GetMessages().LoggingGetCmekSettingsRequest(name=parent_name))
Esempio n. 17
0
 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)
Esempio n. 18
0
    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 sink with its destination.
    """
        sink_ref = util.GetSinkReference(args.sink_name, args)
        sink_resource = util.CreateResourceName(util.GetParentFromArgs(args),
                                                'sinks', sink_ref.sinksId)
        return util.GetClient().projects_sinks.Get(
            util.GetMessages().LoggingProjectsSinksGetRequest(
                sinkName=sink_resource))
Esempio n. 19
0
    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:
      The list of locations.
    """
        result = util.GetClient().projects_locations.List(
            util.GetMessages().LoggingProjectsLocationsListRequest(
                name=util.GetParentFromArgs(args)))

        for location in result.locations:
            yield location
Esempio n. 20
0
    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:
      The list of sinks.
    """
        result = util.GetClient().projects_sinks.List(
            util.GetMessages().LoggingProjectsSinksListRequest(
                parent=util.GetParentFromArgs(args)))
        for sink in result.sinks:
            if not sink.filter:
                sink.filter = '(empty filter)'
            yield 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)))
Esempio n. 22
0
  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.
    """
    sink_ref = util.GetSinkReference(args.sink_name, args)
    sink_resource = util.CreateResourceName(util.GetParentFromArgs(args),
                                            'sinks', sink_ref.sinksId)

    console_io.PromptContinue('Really delete sink [%s]?' % sink_ref.sinksId,
                              cancel_on_no=True)

    util.GetClient().projects_sinks.Delete(
        util.GetMessages().LoggingProjectsSinksDeleteRequest(
            sinkName=sink_resource))
    log.DeletedResource(sink_ref)
Esempio n. 23
0
    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)
Esempio n. 24
0
    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.CheckLegacySinksCommandArguments(args)

        sink_ref = util.GetSinkReference(args.sink_name, args.log,
                                         args.service)

        if args.log:
            sink_description = 'log sink [%s] from [%s]' % (sink_ref.sinksId,
                                                            sink_ref.logsId)
        elif args.service:
            sink_description = 'log-service sink [%s] from [%s]' % (
                sink_ref.sinksId, sink_ref.logServicesId)
        else:
            sink_description = 'sink [%s]' % sink_ref.sinksId

        if not console_io.PromptContinue(
                'Really delete %s?' % sink_description):
            raise calliope_exceptions.ToolException('action canceled by user')

        try:
            if args.log:
                self.DeleteLogSink(sink_ref)
            elif args.service:
                self.DeleteLogServiceSink(sink_ref)
            else:
                self.DeleteSink(util.GetParentFromArgs(args), sink_ref)
            log.DeletedResource(sink_ref)
        except apitools_exceptions.HttpError as error:
            v2_sink = not args.log and not args.service
            # Suggest the user to add --log or --log-service flag.
            if v2_sink and exceptions.HttpException(
                    error).payload.status_code == 404:
                log.status.Print(
                    ('Sink was not found. '
                     'Did you forget to add --log or --log-service flag?'))
            raise error
Esempio n. 25
0
  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 sink with its destination.
    """
    util.CheckSinksCommandArguments(args)

    if not args.unique_writer_identity:
      log.warn(
          '--unique-writer-identity is deprecated and will soon be removed.')

    if not (args.log or args.service or args.log_filter):
      # Attempt to create a sink with an empty filter.
      console_io.PromptContinue(
          'Sink with empty filter matches all entries.', cancel_on_no=True)

    sink_ref = self.context['sink_reference']
    sink_data = {'name': sink_ref.sinksId, 'destination': args.destination,
                 'filter': args.log_filter}

    if args.log:
      result = util.TypedLogSink(self.CreateLogSink(sink_data),
                                 log_name=args.log)
    elif args.service:
      result = util.TypedLogSink(self.CreateLogServiceSink(sink_data),
                                 service_name=args.service)
    else:
      sink_data['outputVersionFormat'] = args.output_version_format
      result = util.TypedLogSink(
          self.CreateSink(util.GetParentFromArgs(args), sink_data,
                          args.unique_writer_identity))
    log.CreatedResource(sink_ref)
    self._epilog_result_destination = result.destination
    self._writer_identity = result.writer_identity
    return result
Esempio n. 26
0
    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 sink with its destination.
    """
        if not args.unique_writer_identity:
            log.warn(
                '--unique-writer-identity is deprecated and will soon be removed.'
            )

        if not args.log_filter:
            # Attempt to create a sink with an empty filter.
            console_io.PromptContinue(
                'Sink with empty filter matches all entries.',
                cancel_on_no=True)

        sink_ref = resources.REGISTRY.Parse(
            args.sink_name, collection='logging.projects.sinks')

        sink_data = {
            'name': sink_ref.sinksId,
            'destination': args.destination,
            'filter': args.log_filter,
            'outputVersionFormat': args.output_version_format
        }

        result = util.TypedLogSink(
            self.CreateSink(util.GetParentFromArgs(args), sink_data,
                            args.unique_writer_identity))

        log.CreatedResource(sink_ref)
        self._epilog_result_destination = result.destination
        self._writer_identity = result.writer_identity
        return result
Esempio n. 27
0
    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 sinks.
    """

        util.CheckLegacySinksCommandArguments(args)
        project = properties.VALUES.core.project.Get(required=True)

        if args.log:
            return self.ListLogSinks(project, args.log)
        elif args.service:
            return self.ListLogServiceSinks(project, args.service)
        elif (args.organization or args.folder or args.billing_account
              or args.only_v2_sinks):
            return self.ListSinks(util.GetParentFromArgs(args))
        else:
            return self.YieldAllSinks(project)
Esempio n. 28
0
    def _Run(self, args, support_dlp=False):
        if not args.log_filter:
            # Attempt to create a sink with an empty filter.
            console_io.PromptContinue(
                'Sink with empty filter matches all entries.',
                cancel_on_no=True)

        if args.include_children and not (args.organization or args.folder):
            log.warning(
                'include-children only has an effect for sinks at the folder '
                'or organization level')

        sink_ref = util.GetSinkReference(args.sink_name, args)

        sink_data = {
            'name': sink_ref.sinksId,
            'destination': args.destination,
            'filter': args.log_filter,
            'includeChildren': args.include_children
        }

        if support_dlp:
            dlp_options = {}
            if args.IsSpecified('dlp_inspect_template'):
                dlp_options['inspectTemplateName'] = args.dlp_inspect_template
            if args.IsSpecified('dlp_deidentify_template'):
                dlp_options[
                    'deidentifyTemplateName'] = args.dlp_deidentify_template
            if dlp_options:
                sink_data['dlpOptions'] = dlp_options

        result = self.CreateSink(util.GetParentFromArgs(args), sink_data)

        log.CreatedResource(sink_ref)
        self._epilog_result_destination = result.destination
        self._epilog_writer_identity = result.writerIdentity
        return result
Esempio n. 29
0
  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.
    """
    messages = util.GetMessages()

    severity_value = getattr(messages.LogEntry.SeverityValueValuesEnum,
                             args.severity.upper())

    entry = messages.LogEntry(
        logName=util.CreateLogResourceName(
            util.GetParentFromArgs(args), args.log_name),
        resource=messages.MonitoredResource(type='global'),
        severity=severity_value)

    if args.payload_type == 'json':
      json_object = util.ConvertToJsonObject(args.message)
      struct = messages.LogEntry.JsonPayloadValue()
      # Protobufs in Python do strict type-checking. We have to change the
      # type from JsonObject.Property to JsonPayloadValue.AdditionalProperty
      # even though both types have the same fields (key, value).
      struct.additionalProperties = [
          messages.LogEntry.JsonPayloadValue.AdditionalProperty(
              key=json_property.key,
              value=json_property.value)
          for json_property in json_object.properties
      ]
      entry.jsonPayload = struct
    else:
      entry.textPayload = args.message

    util.GetClient().entries.Write(
        messages.WriteLogEntriesRequest(entries=[entry]))
    log.status.write('Created log entry.\n')
Esempio n. 30
0
    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