示例#1
0
def schema_completer(prefix):
    """ For tab-completion via argcomplete, return completion options.

    For the given prefix so far, return the possible options.  Note that
    filtering via startswith happens after this list is returned.
    """
    load_resources()
    components = prefix.split('.')

    # Completions for resource
    if len(components) == 1:
        choices = [r for r in resources.keys() if r.startswith(prefix)]
        if len(choices) == 1:
            choices += ['{}{}'.format(choices[0], '.')]
        return choices

    if components[0] not in resources.keys():
        return []

    # Completions for category
    if len(components) == 2:
        choices = ['{}.{}'.format(components[0], x)
                   for x in ('actions', 'filters') if x.startswith(components[1])]
        if len(choices) == 1:
            choices += ['{}{}'.format(choices[0], '.')]
        return choices

    # Completions for item
    elif len(components) == 3:
        resource_mapping = schema.resource_vocabulary()
        return ['{}.{}.{}'.format(components[0], components[1], x)
                for x in resource_mapping[components[0]][components[1]]]

    return []
示例#2
0
def schema_completer(prefix):
    """ For tab-completion via argcomplete, return completion options.
    
    For the given prefix so far, return the possible options.  Note that
    filtering via startswith happens after this list is returned.
    """
    load_resources()
    components = prefix.split('.')
    
    # Completions for resource
    if len(components) == 1:
        choices = [r for r in resources.keys() if r.startswith(prefix)]
        if len(choices) == 1:
            choices += ['{}{}'.format(choices[0], '.')]
        return choices
    
    if components[0] not in resources.keys():
        return []
    
    # Completions for category
    if len(components) == 2:
        choices = ['{}.{}'.format(components[0], x)
                   for x in ('actions', 'filters') if x.startswith(components[1])]
        if len(choices) == 1:
            choices += ['{}{}'.format(choices[0], '.')]
        return choices
    
    # Completions for item
    elif len(components) == 3:
        resource_mapping = schema.resource_vocabulary()
        return ['{}.{}.{}'.format(components[0], components[1], x) 
                for x in resource_mapping[components[0]][components[1]]]

    return []
示例#3
0
 def get_local_image_mapping(self, image_ids):
     base_image_map = self.get_base_image_mapping()
     resources = {i: base_image_map[i] for i in image_ids if i in base_image_map}
     missing = list(set(image_ids) - set(resources.keys()))
     if missing:
         loaded = self.manager.get_resource_manager('ami').get_resources(missing, False)
         resources.update({image['ImageId']: image for image in loaded})
     return resources
示例#4
0
 def get_local_image_mapping(self, image_ids):
     base_image_map = self.get_base_image_mapping()
     resources = {i: base_image_map[i] for i in image_ids if i in base_image_map}
     missing = list(set(image_ids) - set(resources.keys()))
     if missing:
         loaded = self.manager.get_resource_manager('ami').get_resources(missing, False)
         resources.update({image['ImageId']: image for image in loaded})
     return resources
示例#5
0
 def validate(self):
     related_resource = self.data['resource']
     if related_resource not in aws_resources.keys():
         raise PolicyValidationError(
             "Error: Invalid resource type selected: %s" % related_resource)
     # ideally should never raise here since we shouldn't be applying this
     # action to a resource if it doesn't have a tag action implemented
     if self.manager.action_registry.get('tag') is None:
         raise PolicyValidationError(
             "Error: Tag action missing on resource")
     return self
示例#6
0
 def validate(self):
     related_resource = self.data['resource']
     if related_resource not in aws_resources.keys():
         raise PolicyValidationError(
             "Error: Invalid resource type selected: %s" % related_resource
         )
     # ideally should never raise here since we shouldn't be applying this
     # action to a resource if it doesn't have a tag action implemented
     if self.manager.action_registry.get('tag') is None:
         raise PolicyValidationError(
             "Error: Tag action missing on resource"
         )
     return self
示例#7
0
 def initialize(self, asgs):
     super(ImageFilter, self).initialize(asgs)
     image_ids = set()
     for cfg in self.configs.values():
         image_ids.add(cfg['ImageId'])
     results = self.manager.get_resource_manager('ami').resources()
     base_image_map = {i['ImageId']: i for i in results}
     resources = {i: base_image_map[i] for i in image_ids if i in base_image_map}
     missing = list(set(image_ids) - set(resources.keys()))
     if missing:
         loaded = self.manager.get_resource_manager('ami').get_resources(missing, False)
         resources.update({image['ImageId']: image for image in loaded})
     self.images = resources
示例#8
0
def schema_cmd(options):
    """ Print info about the resources, actions and filters available. """
    if options.json:
        schema.json_dump(options.resource)
        return

    load_resources()
    resource_mapping = schema.resource_vocabulary()

    if options.summary:
        schema.summary(resource_mapping)
        return

    # Here are the formats for what we accept:
    # - No argument
    #   - List all available RESOURCES
    # - RESOURCE
    #   - List all available actions and filters for supplied RESOURCE
    # - RESOURCE.actions
    #   - List all available actions for supplied RESOURCE
    # - RESOURCE.actions.ACTION
    #   - Show class doc string and schema for supplied action
    # - RESOURCE.filters
    #   - List all available filters for supplied RESOURCE
    # - RESOURCE.filters.FILTER
    #   - Show class doc string and schema for supplied filter

    if not options.resource:
        resource_list = {'resources': sorted(resources.keys())}
        print(yaml.safe_dump(resource_list, default_flow_style=False))
        return

    # Format is RESOURCE.CATEGORY.ITEM
    components = options.resource.split('.')

    #
    # Handle resource
    #
    resource = components[0].lower()
    if resource not in resource_mapping:
        log.error('{} is not a valid resource'.format(resource))
        sys.exit(1)

    if len(components) == 1:
        del (resource_mapping[resource]['classes'])
        output = {resource: resource_mapping[resource]}
        print(yaml.safe_dump(output))
        return

    #
    # Handle category
    #
    category = components[1].lower()
    if category not in ('actions', 'filters'):
        log.error(
            "Valid choices are 'actions' and 'filters'. You supplied '{}'".
            format(category))
        sys.exit(1)

    if len(components) == 2:
        output = "No {} available for resource {}.".format(category, resource)
        if category in resource_mapping[resource]:
            output = {
                resource: {
                    category: resource_mapping[resource][category]
                }
            }
        print(yaml.safe_dump(output))
        return

    #
    # Handle item
    #
    item = components[2].lower()
    if item not in resource_mapping[resource][category]:
        log.error('{} is not in the {} list for resource {}'.format(
            item, category, resource))
        sys.exit(1)

    if len(components) == 3:
        cls = resource_mapping[resource]['classes'][category][item]

        # Print docstring
        docstring = _schema_get_docstring(cls)
        print("\nHelp\n----\n")
        if docstring:
            print(docstring)
        else:
            # Shouldn't ever hit this, so exclude from cover
            print("No help is available for this item.")  # pragma: no cover

        # Print schema
        print("\nSchema\n------\n")
        if hasattr(cls, 'schema'):
            print(json.dumps(cls.schema, indent=4))
        else:
            # Shouldn't ever hit this, so exclude from cover
            print("No schema is available for this item.",
                  file=sys.sterr)  # pragma: no cover
        print('')
        return

    # We received too much (e.g. s3.actions.foo.bar)
    log.error("Invalid selector '{}'.  Max of 3 components in the "
              "format RESOURCE.CATEGORY.ITEM".format(options.resource))
    sys.exit(1)
示例#9
0
def schema_cmd(options):
    """ Print info about the resources, actions and filters available. """
    if options.json:
        schema.json_dump(options.resource)
        return

    load_resources()
    resource_mapping = schema.resource_vocabulary()

    if options.summary:
        schema.summary(resource_mapping)
        return

    # Here are the formats for what we accept:
    # - No argument
    #   - List all available RESOURCES
    # - RESOURCE
    #   - List all available actions and filters for supplied RESOURCE
    # - RESOURCE.actions
    #   - List all available actions for supplied RESOURCE
    # - RESOURCE.actions.ACTION
    #   - Show class doc string and schema for supplied action
    # - RESOURCE.filters
    #   - List all available filters for supplied RESOURCE
    # - RESOURCE.filters.FILTER
    #   - Show class doc string and schema for supplied filter

    if not options.resource:
        resource_list = {'resources': sorted(resources.keys())}
        print(yaml.safe_dump(resource_list, default_flow_style=False))
        return

    # Format is RESOURCE.CATEGORY.ITEM
    components = options.resource.split('.')

    #
    # Handle resource
    #
    resource = components[0].lower()
    if resource not in resource_mapping:
        eprint('Error: {} is not a valid resource'.format(resource))
        sys.exit(1)

    if len(components) == 1:
        del(resource_mapping[resource]['classes'])
        output = {resource: resource_mapping[resource]}
        print(yaml.safe_dump(output))
        return

    #
    # Handle category
    #
    category = components[1].lower()
    if category not in ('actions', 'filters'):
        eprint(("Error: Valid choices are 'actions' and 'filters'."
                " You supplied '{}'").format(category))
        sys.exit(1)

    if len(components) == 2:
        output = "No {} available for resource {}.".format(category, resource)
        if category in resource_mapping[resource]:
            output = {resource: {
                category: resource_mapping[resource][category]}}
        print(yaml.safe_dump(output))
        return

    #
    # Handle item
    #
    item = components[2].lower()
    if item not in resource_mapping[resource][category]:
        eprint('Error: {} is not in the {} list for resource {}'.format(
            item, category, resource))
        sys.exit(1)

    if len(components) == 3:
        cls = resource_mapping[resource]['classes'][category][item]

        # Print docstring
        docstring = _schema_get_docstring(cls)
        print("\nHelp\n----\n")
        if docstring:
            print(docstring)
        else:
            # Shouldn't ever hit this, so exclude from cover
            print("No help is available for this item.")  # pragma: no cover

        # Print schema
        print("\nSchema\n------\n")
        pp = pprint.PrettyPrinter(indent=4)
        if hasattr(cls, 'schema'):
            pp.pprint(cls.schema)
        else:
            # Shouldn't ever hit this, so exclude from cover
            print("No schema is available for this item.", file=sys.sterr)  # pragma: no cover
        print('')
        return

    # We received too much (e.g. s3.actions.foo.bar)
    eprint("Invalid selector '{}'.  Max of 3 components in the "
           "format RESOURCE.CATEGORY.ITEM".format(options.resource))
    sys.exit(1)