Exemple #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.

    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
Exemple #2
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.
    """
        if not console_io.PromptContinue(
                'Really delete metric [%s]?' % args.metric_name):
            raise exceptions.ToolException('action canceled by user')

        util.GetClient().projects_metrics.Delete(
            util.GetMessages().LoggingProjectsMetricsDeleteRequest(
                metricName=util.CreateResourceName(
                    util.GetCurrentProjectParent(), 'metrics',
                    args.metric_name)))
        log.DeletedResource(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 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)))
Exemple #4
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)
Exemple #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:
      The list of log entries.
    """
        return list_pager.YieldFromList(
            util.GetClient().monitoredResourceDescriptors,
            util.GetMessages().LoggingMonitoredResourceDescriptorsListRequest(
            ),
            field='resourceDescriptors',
            limit=args.limit,
            batch_size=args.limit,
            batch_size_attribute='pageSize')
Exemple #6
0
    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
Exemple #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.
    """
        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)
Exemple #8
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 metrics.
    """
        request = util.GetMessages().LoggingProjectsMetricsListRequest(
            parent=util.GetCurrentProjectParent())

        return list_pager.YieldFromList(util.GetClient().projects_metrics,
                                        request,
                                        field='metrics',
                                        limit=args.limit,
                                        batch_size=None,
                                        batch_size_attribute='pageSize')
Exemple #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.
    """
        project = properties.VALUES.core.project.Get(required=True)

        if not console_io.PromptContinue(
                'Really delete all log entries from [%s]?' % args.log_name):
            raise exceptions.ToolException('action canceled by user')

        # TODO(b/32504514): Use resource parser
        util.GetClient().projects_logs.Delete(
            util.GetMessages().LoggingProjectsLogsDeleteRequest(
                logName=util.CreateLogResourceName(
                    'projects/{0}'.format(project), args.log_name)))
        log.DeletedResource(args.log_name)
Exemple #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 metric.
    """
        messages = util.GetMessages()
        new_metric = messages.LogMetric(name=args.metric_name,
                                        description=args.description,
                                        filter=args.log_filter)

        result = util.GetClient().projects_metrics.Create(
            messages.LoggingProjectsMetricsCreateRequest(
                parent=util.GetCurrentProjectParent(), logMetric=new_metric))
        log.CreatedResource(args.metric_name)
        return result
Exemple #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 list of logs.
    """
    project = properties.VALUES.core.project.Get(required=True)

    project_ref = resources.REGISTRY.Parse(
        project, collection='cloudresourcemanager.projects')
    request = util.GetMessages().LoggingProjectsLogsListRequest(
        parent=project_ref.RelativeName())

    return list_pager.YieldFromList(
        util.GetClient().projects_logs, request, field='logNames',
        limit=args.limit, batch_size=None, batch_size_attribute='pageSize')
Exemple #12
0
    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)))
Exemple #13
0
  def _Run(self, args, is_alpha=False):
    bucket_data = {}
    update_mask = []
    parameter_names = ['--retention-days', '--description', '--locked']
    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 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 is_alpha and args.enable_loglink is not None:
      bucket_data['logLink'] = {'enabled': args.enable_loglink}
      update_mask.append('log_link.enabled')

    if is_alpha and args.IsSpecified('restricted_fields'):
      bucket_data['restrictedFields'] = args.restricted_fields
      update_mask.append('restricted_fields')

    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 created bucket.
    """
        bucket_data = {}
        if args.IsSpecified('retention_days'):
            bucket_data['retentionDays'] = args.retention_days
        if args.IsSpecified('description'):
            bucket_data['description'] = args.description

        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)))
Exemple #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 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('display_name'):
      bucket_data['displayName'] = args.display_name
      update_mask.append('display_name')
    if args.IsSpecified('description'):
      bucket_data['description'] = args.description
      update_mask.append('description')

    if not update_mask:
      raise calliope_exceptions.MinimumArgumentException(
          ['--retention-days', '--display-name', '--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)))
Exemple #16
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 view.
    """
        view_data = {}
        update_mask = []
        parameter_names = ['--filter', '--description']
        if args.IsSpecified('filter'):
            view_data['filter'] = args.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.
    """
        messages = util.GetMessages()
        project = properties.VALUES.core.project.Get(required=True)

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

        entry = messages.LogEntry(
            logName=util.CreateLogResourceName('projects/{0}'.format(project),
                                               args.log_name),
            resource=messages.MonitoredResource(type='global'),
            severity=severity_value)

        if args.payload_type == 'json' or args.payload_type == 'struct':
            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')
Exemple #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 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
Exemple #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.

    Returns:
      The updated CMEK settings.
    """
    cmek_settings = {}
    if args.IsSpecified('kms_key_name'):
      cmek_settings['kmsKeyName'] = (
          args.CONCEPTS.kms_key_name.Parse().RelativeName())

    if args.IsSpecified('clear_kms_key'):
      cmek_settings['kmsKeyName'] = ''

    parent_name = util.GetParentFromArgs(args)
    return util.GetClient().organizations.UpdateCmekSettings(
        util.GetMessages().LoggingOrganizationsUpdateCmekSettingsRequest(
            name=parent_name,
            cmekSettings=util.GetMessages().CmekSettings(**cmek_settings),
            updateMask='kms_key_name'))
Exemple #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.

    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
Exemple #21
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 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)))
Exemple #22
0
 def GetSink(self, parent, sink_ref):
     """Returns a sink specified by the arguments."""
     return util.GetClient().projects_sinks.Get(
         util.GetMessages().LoggingProjectsSinksGetRequest(
             sinkName=util.CreateResourceName(parent, 'sinks',
                                              sink_ref.sinksId)))
Exemple #23
0
    def _Run(self, args, is_alpha=False):
        bucket_data = {}
        update_mask = []
        parameter_names = ['--retention-days', '--description', '--locked']
        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 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 args.IsSpecified('restricted_fields'):
            bucket_data['restrictedFields'] = args.restricted_fields
            update_mask.append('restricted_fields')

        if is_alpha and args.enable_loglink is not None:
            bucket_data['logLink'] = {'enabled': args.enable_loglink}
            update_mask.append('log_link.enabled')

        if is_alpha and (args.IsSpecified('clear_indexes')
                         or args.IsSpecified('remove_indexes')
                         or args.IsSpecified('add_index')
                         or args.IsSpecified('update_index')):
            bucket = self.GetCurrentBucket(args)
            bucket_data['indexConfigs'] = []
            update_mask.append('index_configs')
            indexes_to_remove = (args.remove_indexes
                                 if args.IsSpecified('remove_indexes') else [])
            indexes_to_update = (args.update_index
                                 if args.IsSpecified('update_index') else [])
            for index in bucket.indexConfigs:
                if index.fieldPath in indexes_to_remove:
                    indexes_to_remove.remove(index.fieldPath)
                else:
                    for i in range(len(indexes_to_update)):
                        if index.fieldPath == indexes_to_update[i][
                                'fieldPath']:
                            for key, value in indexes_to_update[i].items():
                                if key == 'type':
                                    index.type = value
                            indexes_to_update.pop(i)
                            break
                    bucket_data['indexConfigs'].append(index)

            if indexes_to_remove:
                raise calliope_exceptions.InvalidArgumentException(
                    '--remove-indexes', 'Indexes {0} do not exist'.format(
                        ','.join(indexes_to_remove)))

            if indexes_to_update:
                raise calliope_exceptions.InvalidArgumentException(
                    '--update-index',
                    'Indexes {0} do not exist'.format(','.join(
                        [index['fieldPath'] for index in indexes_to_update])))

            if args.IsSpecified('clear_indexes'):
                bucket_data['indexConfigs'] = []

            if args.IsSpecified('add_index'):
                bucket_data['indexConfigs'] += args.add_index

        if is_alpha and args.IsSpecified('cmek_kms_key_name'):
            bucket = self.GetCurrentBucket(args)
            if not bucket.cmekSettings:
                # This is the first time CMEK settings are being applied. Warn the user
                # that this is irreversible.
                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
            update_mask.append('cmek_settings')

        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)))