text
stringlengths
81
112k
Return a mapping of launch configs for the given set of asgs def get_launch_configs(self, asgs): """Return a mapping of launch configs for the given set of asgs""" config_names = set() for a in asgs: if 'LaunchConfigurationName' not in a: continue config_...
Support server side filtering on arns or names def get_resources(self, ids, cache=True): """Support server side filtering on arns or names """ if ids[0].startswith('arn:'): params = {'LoadBalancerArns': ids} else: params = {'Names': ids} return self.query...
Validate a configuration file. def validate(config): """Validate a configuration file.""" with open(config) as fh: data = utils.yaml_load(fh.read()) jsonschema.validate(data, CONFIG_SCHEMA)
Run across a set of accounts and buckets. def run(config, tag, bucket, account, not_bucket, not_account, debug, region): """Run across a set of accounts and buckets.""" logging.basicConfig( level=logging.INFO, format="%(asctime)s: %(name)s:%(levelname)s %(message)s") logging.getLogger('boto...
Delete all persistent cluster state. def reset(c7n_async=None): """Delete all persistent cluster state. """ click.echo('Delete db? Are you Sure? [yn] ', nl=False) c = click.getchar() click.echo() if c == 'y': click.echo('Wiping database') worker.connection.flushdb() elif c =...
Show information on salactus workers. (slow) def workers(): """Show information on salactus workers. (slow)""" counter = Counter() for w in Worker.all(connection=worker.connection): for q in w.queues: counter[q.name] += 1 import pprint pprint.pprint(dict(counter))
Report on stats by account def accounts(dbpath, output, format, account, config=None, tag=None, tagprefix=None, region=(), not_region=(), not_bucket=None): """Report on stats by account""" d = db.db(dbpath) accounts = d.accounts() formatter = ( format == 'csv' and form...
Report on stats by bucket def buckets(bucket=None, account=None, matched=False, kdenied=False, errors=False, dbpath=None, size=None, denied=False, format=None, incomplete=False, oversize=False, region=(), not_region=(), inventory=None, output=None, config=None, sort=None, ...
watch scan rates across the cluster def watch(limit): """watch scan rates across the cluster""" period = 5.0 prev = db.db() prev_totals = None while True: click.clear() time.sleep(period) cur = db.db() cur.data['gkrate'] = {} progress = [] prev_bucke...
Discover the partitions on a bucket via introspection. For large buckets which lack s3 inventories, salactus will attempt to process objects in parallel on the bucket by breaking the bucket into a separate keyspace partitions. It does this with a heurestic that attempts to sample the keyspace and deter...
Show all information known on a bucket. def inspect_bucket(bucket): """Show all information known on a bucket.""" state = db.db() found = None for b in state.buckets(): if b.name == bucket: found = b if not found: click.echo("no bucket named: %s" % bucket) return...
Show contents of a queue. def inspect_queue(queue, state, limit, bucket): """Show contents of a queue.""" if not HAVE_BIN_LIBS: click.echo("missing required binary libs (lz4, msgpack)") return conn = worker.connection def job_row(j): if isinstance(j.args[0], basestring): ...
Report on progress by queues. def queues(): """Report on progress by queues.""" conn = worker.connection failure_q = None def _repr(q): return "running:%d pending:%d finished:%d" % ( StartedJobRegistry(q.name, conn).count, q.count, FinishedJobRegistry(q.name...
Show any unexpected failures def failures(): """Show any unexpected failures""" if not HAVE_BIN_LIBS: click.echo("missing required binary libs (lz4, msgpack)") return q = Queue('failed', connection=worker.connection) for i in q.get_job_ids(): j = q.job_class.fetch(i, connection...
Generate a c7n-org subscriptions config file def main(output): """ Generate a c7n-org subscriptions config file """ client = SubscriptionClient(Session().get_credentials()) subs = [sub.serialize(True) for sub in client.subscriptions.list()] results = [] for sub in subs: sub_info = ...
Overrides ServiceClient.send() function to implement retries & log headers def custodian_azure_send_override(self, request, headers=None, content=None, **kwargs): """ Overrides ServiceClient.send() function to implement retries & log headers """ retries = 0 max_retries = 3 while retries < max_retri...
Retrieves Azure AD Objects for corresponding object ids passed. :param graph_client: A client for Microsoft Graph. :param object_ids: The object ids to retrieve Azure AD objects for. :param raise_on_graph_call_error: A boolean indicate whether an error should be raised if the underlying ...
Attempts to resolve a principal name. :param graph_object: the Azure AD Graph Object :return: The resolved value or an empty string if unsuccessful. def get_principal_name(graph_object): """Attempts to resolve a principal name. :param graph_object: the Azure AD Graph Object :ret...
Given a string with a port or port range: '80', '80-120' Returns tuple with range start and end ports: (80, 80), (80, 120) def _get_port_range(range_str): """ Given a string with a port or port range: '80', '80-120' Returns tuple with range start and end ports: (80, 80), (80, 120) ...
Extracts ports ranges from the NSG rule object Returns an array of PortsRange tuples def _get_rule_port_ranges(rule): """ Extracts ports ranges from the NSG rule object Returns an array of PortsRange tuples """ properties = rule['properties'] if 'destinationPortR...
Converts array of port ranges to the set of integers Example: [(10-12), (20,20)] -> {10, 11, 12, 20} def _port_ranges_to_set(ranges): """ Converts array of port ranges to the set of integers Example: [(10-12), (20,20)] -> {10, 11, 12, 20} """ return set([i for r in range...
Validate that provided string has proper port numbers: 1. port number < 65535 2. range start < range end def validate_ports_string(ports): """ Validate that provided string has proper port numbers: 1. port number < 65535 2. range start < range end """ ...
Transform a list of port numbers to the list of strings with port ranges Example: [10, 12, 13, 14, 15] -> ['10', '12-15'] def get_ports_strings_from_list(data): """ Transform a list of port numbers to the list of strings with port ranges Example: [10, 12, 13, 14, 15] -> ['10', '12-15'] ...
Build entire ports array filled with True (Allow), False (Deny) and None(default - Deny) based on the provided Network Security Group object, direction and protocol. def build_ports_dict(nsg, direction_key, ip_protocol): """ Build entire ports array filled with True (Allow), False (Deny) and None(d...
Given an arbitrary resource attempt to resolve back to a qualified name. def get_name(self, r): """Given an arbitrary resource attempt to resolve back to a qualified name.""" namer = ResourceNameAdapters[self.manager.resource_type.service] return namer(r)
Main. def update_headers(src_tree): """Main.""" print("src tree", src_tree) for root, dirs, files in os.walk(src_tree): py_files = fnmatch.filter(files, "*.py") for f in py_files: print("checking", f) p = os.path.join(root, f) with open(p) as fh: ...
Show extant locks and unlocks. def list_locks(account_id, resource_type=None, resource_id=None): """Show extant locks and unlocks. """ locks = Client(BASE_URL, account_id).list_locks().json() for r in locks: if 'LockDate' in r: r['LockDate'] = datetime.fromtimestamp(r['LockDate']) ...
Show extant locks' status def lock_status(account_id, resource_id, parent_id): """Show extant locks' status """ return output( Client(BASE_URL, account_id).lock_status(resource_id, parent_id))
Lock a resource def lock(account_id, resource_id, region): """Lock a resource """ return output( Client(BASE_URL, account_id).lock(resource_id, region))
Get extant locks for the given account. def list_locks(self, account_id=None): """Get extant locks for the given account. """ account_id = self.get_account_id(account_id) return self.http.get( "%s/%s/locks" % (self.endpoint, account_id), auth=self.get_api_auth())
Get the lock status for a given resource. for security groups, parent id is their vpc. def lock_status(self, resource_id, parent_id=None, account_id=None): """Get the lock status for a given resource. for security groups, parent id is their vpc. """ account_id = self.get_accou...
Lock a given resource def lock(self, resource_id, region, account_id=None): """Lock a given resource """ account_id = self.get_account_id(account_id) return self.http.post( "%s/%s/locks/%s/lock" % (self.endpoint, account_id, resource_id), json={'region': region},...
report on a cross account policy execution. def report(config, output, use, output_dir, accounts, field, no_default_fields, tags, region, debug, verbose, policy, policy_tags, format, resource, cache_path): """report on a cross account policy execution.""" accounts_config, custodian_config...
run an aws script across accounts def run_script(config, output_dir, accounts, tags, region, echo, serial, script_args): """run an aws script across accounts""" # TODO count up on success / error / error list by account accounts_config, custodian_config, executor = init( config, None, serial, True,...
Execute a set of policies on an account. def run_account(account, region, policies_config, output_path, cache_period, cache_path, metrics, dryrun, debug): """Execute a set of policies on an account. """ logging.getLogger('custodian.output').setLevel(logging.ERROR + 1) CONN_CACHE.session...
run a custodian policy across accounts def run(config, use, output_dir, accounts, tags, region, policy, policy_tags, cache_period, cache_path, metrics, dryrun, debug, verbose, metrics_uri): """run a custodian policy across accounts""" accounts_config, custodian_config, executor = init( ...
Send logs def emit(self, message): """Send logs""" # We're sending messages asynchronously, bubble to caller when # we've detected an error on the message. This isn't great, # but options once we've gone async without a deferred/promise # aren't great. if self.transport ...
Ensure all logging output has been flushed. def flush(self): """Ensure all logging output has been flushed.""" if self.shutdown: return self.flush_buffers(force=True) self.queue.put(FLUSH_MARKER) self.queue.join()
format message. def format_message(self, msg): """format message.""" return {'timestamp': int(msg.created * 1000), 'message': self.format(msg), 'stream': self.log_stream or msg.name, 'group': self.log_group}
start thread transports. def start_transports(self): """start thread transports.""" self.transport = Transport( self.queue, self.batch_size, self.batch_interval, self.session_factory) thread = threading.Thread(target=self.transport.loop) self.threads.append(threa...
Handle various client side errors when describing images def extract_bad_ami(e): """Handle various client side errors when describing images""" msg = e.response['Error']['Message'] error = e.response['Error']['Code'] e_ami_ids = None if error == 'InvalidAMIID.NotFound': ...
format config for lambda exec def format_json(config): """format config for lambda exec """ with open(config) as fh: print(json.dumps(yaml.safe_load(fh.read()), indent=2))
Sanity check api deployment def check(): """Sanity check api deployment """ t = time.time() results = Client(BASE_URL).version() print("Endpoint", BASE_URL) print("Response Time %0.2f" % (time.time() - t)) print("Headers") for k, v in results.headers.items(): print(" %s: %s" % (...
lambda/api/db metrics def metrics(function, api, start, period): """lambda/api/db metrics""" from c7n.mu import LambdaManager manager = LambdaManager(boto3.Session) start = parse_date(start) period = int(abs(parse_timedelta(period).total_seconds())) print("Lambda Metrics") metrics = manage...
Fetch locks data def records(account_id): """Fetch locks data """ s = boto3.Session() table = s.resource('dynamodb').Table('Sphere11.Dev.ResourceLocks') results = table.scan() for r in results['Items']: if 'LockDate' in r: r['LockDate'] = datetime.fromtimestamp(r['LockDate'...
Attempt to acquire any pending locks. def flush_pending(function): """Attempt to acquire any pending locks. """ s = boto3.Session() client = s.client('lambda') results = client.invoke( FunctionName=function, Payload=json.dumps({'detail-type': 'Scheduled Event'}) ) content = ...
Check config status in an account. def config_status(): """ Check config status in an account. """ s = boto3.Session() client = s.client('config') channels = client.describe_delivery_channel_status()[ 'DeliveryChannelsStatus'] for c in channels: print(yaml.safe_dump({ ...
run local app server, assumes into the account def local(reload, port): """run local app server, assumes into the account """ import logging from bottle import run from app import controller, app from c7n.resources import load_resources load_resources() print("Loaded resources definitio...
Given a class, return its docstring. If no docstring is present for the class, search base classes in MRO for a docstring. def _schema_get_docstring(starting_class): """ Given a class, return its docstring. If no docstring is present for the class, search base classes in MRO for a docstring. ...
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. def schema_completer(prefix): """ For tab-completion via argcomplete, return completion options. For the gi...
Print info about the resources, actions and filters available. def schema_cmd(options): """ Print info about the resources, actions and filters available. """ from c7n import schema if options.json: schema.json_dump(options.resource) return load_resources() resource_mapping = sche...
Determine the start and end dates based on user-supplied options. def _metrics_get_endpoints(options): """ Determine the start and end dates based on user-supplied options. """ if bool(options.start) ^ bool(options.end): log.error('--start and --end must be specified together') sys.exit(1) ...
Extract an instance id from an error def extract_instance_id(state_error): "Extract an instance id from an error" instance_id = None match = RE_ERROR_INSTANCE_ID.search(str(state_error)) if match: instance_id = match.groupdict().get('instance_id') if match is None or instance_id is None: ...
EC2 API and AWOL Tags While ec2 api generally returns tags when doing describe_x on for various resources, it may also silently fail to do so unless a tag is used as a filter. See footnote on for official documentation. https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_...
meta model subscriber on resource registration. SecurityHub Findings Filter def register_resources(klass, registry, resource_class): """ meta model subscriber on resource registration. SecurityHub Findings Filter """ for rtype, resource_manager in registry.items(): ...
Publish message to a GCP pub/sub topic def publish_message(self, message, client): """Publish message to a GCP pub/sub topic """ return client.execute_command('publish', { 'topic': self.data['transport']['topic'], 'body': { 'messages': { ...
Sets headers on Mimetext message def set_mimetext_headers(self, message, subject, from_addr, to_addrs, cc_addrs, priority): """Sets headers on Mimetext message""" message['Subject'] = subject message['From'] = from_addr message['To'] = ', '.join(to_addrs) if cc_addrs: ...
meta model subscriber on resource registration. We watch for PHD event that provides affected entities and register the health-event filter to the resources. def register_resources(klass, registry, resource_class): """ meta model subscriber on resource registration. We watch for PHD e...
Create a lambda code archive for running custodian. Lambda archive currently always includes `c7n` and `pkg_resources`. Add additional packages in the mode block. Example policy that includes additional packages .. code-block:: yaml policy: name: lambda-archive-example re...
Add the named Python modules to the archive. For consistency's sake we only add ``*.py`` files, not ``*.pyc``. We also don't add other files, including compiled modules. You'll have to add such files manually using :py:meth:`add_file`. def add_modules(self, ignore, *modules): """Add the...
Add ``*.py`` files under the directory ``path`` to the archive. def add_directory(self, path, ignore=None): """Add ``*.py`` files under the directory ``path`` to the archive. """ for root, dirs, files in os.walk(path): arc_prefix = os.path.relpath(root, os.path.dirname(path)) ...
Add the file at ``src`` to the archive. If ``dest`` is ``None`` then it is added under just the original filename. So ``add_file('foo/bar.txt')`` ends up at ``bar.txt`` in the archive, while ``add_file('bar.txt', 'foo/bar.txt')`` ends up at ``foo/bar.txt``. def add_file(self, src, dest...
This is a special case of :py:meth:`add_file` that helps for adding a ``py`` when a ``pyc`` may be present as well. So for example, if ``__file__`` is ``foo.pyc`` and you do: .. code-block:: python archive.add_py_file(__file__) then this method will add ``foo.py`` instead if...
Add file contents to the archive under ``dest``. If ``dest`` is a path, it will be added compressed and world-readable (user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for custom behavior. def add_contents(self, dest, contents): """Add file contents to the archive und...
Close the zip file. Note underlying tempfile is removed when archive is garbage collected. def close(self): """Close the zip file. Note underlying tempfile is removed when archive is garbage collected. """ self._closed = True self._zip_file.close() log.debug( ...
Return the b64 encoded sha256 checksum of the archive. def get_checksum(self, encoder=base64.b64encode, hasher=hashlib.sha256): """Return the b64 encoded sha256 checksum of the archive.""" assert self._closed, "Archive not closed" with open(self._temp_archive_file.name, 'rb') as fh: ...
Return a read-only :py:class:`~zipfile.ZipFile`. def get_reader(self): """Return a read-only :py:class:`~zipfile.ZipFile`.""" assert self._closed, "Archive not closed" buf = io.BytesIO(self.get_bytes()) return zipfile.ZipFile(buf, mode='r')
Create or update an alias for the given function. def publish_alias(self, func_data, alias): """Create or update an alias for the given function. """ if not alias: return func_data['FunctionArn'] func_name = func_data['FunctionName'] func_version = func_data['Version...
Returns a sqlite row factory that returns a dictionary def row_factory(cursor, row): """Returns a sqlite row factory that returns a dictionary""" d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
Get the resource's tag value. def get_tag_value(resource, tag, utf_8=False): """Get the resource's tag value.""" tags = {k.lower(): v for k, v in resource.get('tags', {}).items()} value = tags.get(tag, False) if value is not False: if utf_8: value =...
report on guard duty enablement by account def report(config, tags, accounts, master, debug, region): """report on guard duty enablement by account""" accounts_config, master_info, executor = guardian_init( config, debug, master, accounts, tags) session = get_session( master_info.get('role...
suspend guard duty in the given accounts. def disable(config, tags, accounts, master, debug, suspend, disable_detector, delete_detector, dissociate, region): """suspend guard duty in the given accounts.""" accounts_config, master_info, executor = guardian_init( config, debug, master, accoun...
enable guard duty on a set of accounts def enable(config, master, tags, accounts, debug, message, region): """enable guard duty on a set of accounts""" accounts_config, master_info, executor = guardian_init( config, debug, master, accounts, tags) regions = expand_regions(region) for r in region...
Return all the security group names configured in this action. def get_action_group_names(self): """Return all the security group names configured in this action.""" return self.get_group_names( list(itertools.chain( *[self._get_array('add'), self._get_arra...
Resolve security names to security groups resources. def get_groups_by_names(self, names): """Resolve security names to security groups resources.""" if not names: return [] client = utils.local_session( self.manager.session_factory).client('ec2') sgs = self.mana...
Resolve any security group names to the corresponding group ids With the context of a given network attached resource. def resolve_group_names(self, r, target_group_ids, groups): """Resolve any security group names to the corresponding group ids With the context of a given network attached re...
Resolve the resources security groups that need be modified. Specifically handles symbolic names that match annotations from policy filters for groups being removed. def resolve_remove_symbols(self, r, target_group_ids, rgroups): """Resolve the resources security groups that need be modified. ...
Return lists of security groups to set on each resource For each input resource, parse the various add/remove/isolation- group policies for 'modify-security-groups' to find the resulting set of VPC security groups to attach to that resource. Returns a list of lists containing the resul...
jsonschema generation helper params: - type_name: name of the type - inherits: list of document fragments that are required via anyOf[$ref] - rinherit: use another schema as a base for this, basically work around inherits issues with additionalProperties and type enums. - alias...
Return a mapping of key value to resources with the corresponding value. Key may be specified as dotted form for nested dictionary lookup def group_by(resources, key): """Return a mapping of key value to resources with the corresponding value. Key may be specified as dotted form for nested dictionary loo...
Some sources from apis return lowerCased where as describe calls always return TitleCase, this function turns the former to the later def camelResource(obj): """Some sources from apis return lowerCased where as describe calls always return TitleCase, this function turns the former to the later """ ...
Return a list of ec2 instances for the query. def query_instances(session, client=None, **query): """Return a list of ec2 instances for the query. """ if client is None: client = session.client('ec2') p = client.get_paginator('describe_instances') results = p.paginate(**query) return li...
Cache a session thread local for up to 45m def local_session(factory): """Cache a session thread local for up to 45m""" factory_region = getattr(factory, 'region', 'global') s = getattr(CONN_CACHE, factory_region, {}).get('session') t = getattr(CONN_CACHE, factory_region, {}).get('time') n = time....
>>> x = {} >>> set_annotation(x, 'marker', 'a') >>> annotation(x, 'marker') ['a'] def set_annotation(i, k, v): """ >>> x = {} >>> set_annotation(x, 'marker', 'a') >>> annotation(x, 'marker') ['a'] """ if not isinstance(i, dict): raise ValueError("Can only annotate dictio...
Generate an Amazon Resource Name. See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html. def generate_arn( service, resource, partition='aws', region=None, account_id=None, resource_type=None, separator='/'): """Generate an Amazon Resource Name. See http://docs.aws.a...
Return an identifier for a snapshot of a database or cluster. def snapshot_identifier(prefix, db_identifier): """Return an identifier for a snapshot of a database or cluster. """ now = datetime.now() return '%s-%s-%s' % (prefix, db_identifier, now.strftime('%Y-%m-%d-%H-%M'))
Decorator for retry boto3 api call on transient errors. https://www.awsarchitectureblog.com/2015/03/backoff.html https://en.wikipedia.org/wiki/Exponential_backoff :param codes: A sequence of retryable error codes. :param max_attempts: The max number of retries, by default the delay time is ...
Geometric backoff sequence w/ jitter def backoff_delays(start, stop, factor=2.0, jitter=False): """Geometric backoff sequence w/ jitter """ cur = start while cur <= stop: if jitter: yield cur - (cur * random.random()) else: yield cur cur = cur * factor
Process cidr ranges. def parse_cidr(value): """Process cidr ranges.""" klass = IPv4Network if '/' not in value: klass = ipaddress.ip_address try: v = klass(six.text_type(value)) except (ipaddress.AddressValueError, ValueError): v = None return v
Generic wrapper to log uncaught exceptions in a function. When we cross concurrent.futures executor boundaries we lose our traceback information, and when doing bulk operations we may tolerate transient failures on a partial subset. However we still want to have full accounting of the error in the logs...
Reformat schema to be in a more displayable format. def reformat_schema(model): """ Reformat schema to be in a more displayable format. """ if not hasattr(model, 'schema'): return "Model '{}' does not have a schema".format(model) if 'properties' not in model.schema: return "Schema in unexp...
Format all string values in an object. Return the updated object def format_string_values(obj, err_fallback=(IndexError, KeyError), *args, **kwargs): """ Format all string values in an object. Return the updated object """ if isinstance(obj, dict): new = {} for key in obj.keys()...
Retrieve dax resources for serverless policies or related resources def get_resources(self, ids, cache=True): """Retrieve dax resources for serverless policies or related resources """ client = local_session(self.manager.session_factory).client('dax') return client.describe_clusters(Clu...
Generate a c7n-org gcp projects config file def main(output): """ Generate a c7n-org gcp projects config file """ client = Session().client('cloudresourcemanager', 'v1', 'projects') results = [] for page in client.execute_paged_query('list', {}): for project in page.get('projects', []...
Query a set of resources. def filter(self, resource_manager, **params): """Query a set of resources.""" m = self.resolve(resource_manager.resource_type) client = resource_manager.get_client() enum_op, list_op, extra_args = m.enum_spec parent_type, annotate_parent = m.parent_sp...
Return an iterator resource attribute filters configured. def get_attr_filters(self): """Return an iterator resource attribute filters configured. """ for f in self.data.keys(): if f not in self.multi_attrs: continue fv = self.data[f] if isins...
add CloudTrail permissions to an S3 policy, preserving existing def cloudtrail_policy(original, bucket_name, account_id, bucket_region): '''add CloudTrail permissions to an S3 policy, preserving existing''' ct_actions = [ { 'Action': 's3:GetBucketAcl', 'Effect': 'Allow', ...
Returns all extant rds engine upgrades. As a nested mapping of engine type to known versions and their upgrades. Defaults to minor upgrades, but configurable to major. Example:: >>> _get_engine_upgrades(client) { 'oracle-se2': {'12.1.0.2.v2': '12.1.0.2.v5', ...
Create a local output directory per execution. We've seen occassional (1/100000) perm issues with lambda on temp directory and changing unix execution users (2015-2018), so use a per execution temp space. With firecracker lambdas this may be outdated. def get_local_output_dir(): """Create a local outp...
Get policy lambda execution configuration. cli parameters are serialized into the policy lambda config, we merge those with any policy specific execution options. --assume role and -s output directory get special handling, as to disambiguate any cli context. account id is sourced from the config ...