INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
send the given policy change
def send(self, change): """send the given policy change""" self.buf.append(change) if len(self.buf) % self.BUF_SIZE == 0: self.flush()
Bookkeeping on internal data structures while iterating a stream.
def _process_stream_delta(self, delta_stream): """Bookkeeping on internal data structures while iterating a stream.""" for pchange in delta_stream: if pchange.kind == ChangeType.ADD: self.policy_files.setdefault( pchange.file_path, PolicyCollection()).add(...
flush any buffered messages
def flush(self): """flush any buffered messages""" buf = self.buf self.buf = [] if buf: self._flush(buf)
Download firehose archive, aggregate records in memory and write back.
def process_firehose_archive(bucket, key): """Download firehose archive, aggregate records in memory and write back.""" data = {} with tempfile.NamedTemporaryFile(mode='w+b') as fh: s3.download_file(bucket, key, fh.name) log.warning("Downloaded Key Size:%s Key:%s", sizeof...
Split up a firehose s3 object into records Firehose cloudwatch log delivery of flow logs does not delimit record boundaries. We have to use knowledge of content to split the records on boundaries. In the context of flow logs we're dealing with delimited records.
def records_iter(fh, buffer_size=1024 * 1024 * 16): """Split up a firehose s3 object into records Firehose cloudwatch log delivery of flow logs does not delimit record boundaries. We have to use knowledge of content to split the records on boundaries. In the context of flow logs we're dealing with ...
Get an active session in the target account.
def get_session(self, account_id): """Get an active session in the target account.""" if account_id not in self.account_sessions: if account_id not in self.config['accounts']: raise AccountNotFound("account:%s is unknown" % account_id) self.account_sessions[accou...
Scope a schema error to its policy name and resource.
def policy_error_scope(error, data): """Scope a schema error to its policy name and resource.""" err_path = list(error.absolute_path) if err_path[0] != 'policies': return error pdata = data['policies'][err_path[1]] pdata.get('name', 'unknown') error.message = "Error on policy:{} resource...
Try to find the best error for humans to resolve The jsonschema.exceptions.best_match error is based purely on a mix of a strong match (ie. not anyOf, oneOf) and schema depth, this often yields odd results that are semantically confusing, instead we can use a bit of structural knowledge of schema to ...
def specific_error(error): """Try to find the best error for humans to resolve The jsonschema.exceptions.best_match error is based purely on a mix of a strong match (ie. not anyOf, oneOf) and schema depth, this often yields odd results that are semantically confusing, instead we can use a bit of st...
get a resource manager or a given resource type. assumes the query is for the same underlying cloud provider.
def get_resource_manager(self, resource_type, data=None): """get a resource manager or a given resource type. assumes the query is for the same underlying cloud provider. """ if '.' in resource_type: provider_name, resource_type = resource_type.split('.', 1) else: ...
Augment ElasticBeanstalk Environments with their tags.
def _eb_env_tags(envs, session_factory, retry): """Augment ElasticBeanstalk Environments with their tags.""" client = local_session(session_factory).client('elasticbeanstalk') def process_tags(eb_env): try: eb_env['Tags'] = retry( client.list_tags_for_resource, ...
Assemble a document representing all the config state around a bucket. TODO: Refactor this, the logic here feels quite muddled.
def assemble_bucket(item): """Assemble a document representing all the config state around a bucket. TODO: Refactor this, the logic here feels quite muddled. """ factory, b = item s = factory() c = s.client('s3') # Bucket Location, Current Client Location, Default Location b_location = ...
Tries to get the bucket region from Location.LocationConstraint Special cases: LocationConstraint EU defaults to eu-west-1 LocationConstraint null defaults to us-east-1 Args: b (object): A bucket object Returns: string: an aws region string
def get_region(b): """Tries to get the bucket region from Location.LocationConstraint Special cases: LocationConstraint EU defaults to eu-west-1 LocationConstraint null defaults to us-east-1 Args: b (object): A bucket object Returns: string: an aws region string ""...
Expand each list of cidr, prefix list, user id group pair by port/protocol as an individual rule. The console ux automatically expands them out as addition/removal is per this expansion, the describe calls automatically group them.
def expand_permissions(self, permissions): """Expand each list of cidr, prefix list, user id group pair by port/protocol as an individual rule. The console ux automatically expands them out as addition/removal is per this expansion, the describe calls automatically group them. "...
Format a policy's extant records into a report.
def report(policies, start_date, options, output_fh, raw_output_fh=None): """Format a policy's extant records into a report.""" regions = set([p.options.region for p in policies]) policy_names = set([p.name for p in policies]) formatter = Formatter( policies[0].resource_manager.resource_type, ...
Only the first record for each id
def uniq_by_id(self, records): """Only the first record for each id""" uniq = [] keys = set() for rec in records: rec_id = rec[self._id_field] if rec_id not in keys: uniq.append(rec) keys.add(rec_id) return uniq
scan org repo status hooks
def run(organization, hook_context, github_url, github_token, verbose, metrics=False, since=None, assume=None, region=None): """scan org repo status hooks""" logging.basicConfig(level=logging.DEBUG) since = dateparser.parse( since, settings={ 'RETURN_AS_TIMEZONE_AWARE': True, 'T...
expand any variables in the action to_from/cc_from fields.
def expand_variables(self, message): """expand any variables in the action to_from/cc_from fields. """ p = copy.deepcopy(self.data) if 'to_from' in self.data: to_from = self.data['to_from'].copy() to_from['url'] = to_from['url'].format(**message) if 'e...
Resources preparation for transport. If we have sensitive or overly large resource metadata we want to remove or additional serialization we need to perform, this provides a mechanism. TODO: consider alternative implementations, at min look at adding provider as additional disc...
def prepare_resources(self, resources): """Resources preparation for transport. If we have sensitive or overly large resource metadata we want to remove or additional serialization we need to perform, this provides a mechanism. TODO: consider alternative implementations, at min...
validate config file
def validate(config): """validate config file""" with open(config) as fh: content = fh.read() try: data = yaml.safe_load(content) except Exception: log.error("config file: %s is not valid yaml", config) raise try: jsonschema.validate(data, CONFIG_SCHEMA) ...
subscribe accounts log groups to target account log group destination
def subscribe(config, accounts, region, merge, debug): """subscribe accounts log groups to target account log group destination""" config = validate.callback(config) subscription = config.get('subscription') if subscription is None: log.error("config file: logs subscription missing") sy...
run export across accounts and log groups specified in config.
def run(config, start, end, accounts, region, debug): """run export across accounts and log groups specified in config.""" config = validate.callback(config) destination = config.get('destination') start = start and parse(start) or start end = end and parse(end) or datetime.now() executor = debu...
simple decorator that will auto fan out async style in lambda. outside of lambda, this will invoke synchrously.
def lambdafan(func): """simple decorator that will auto fan out async style in lambda. outside of lambda, this will invoke synchrously. """ if 'AWS_LAMBDA_FUNCTION_NAME' not in os.environ: return func @functools.wraps(func) def scaleout(*args, **kw): client = boto3.client('lamb...
Filter log groups by shell patterns.
def filter_group_names(groups, patterns): """Filter log groups by shell patterns. """ group_names = [g['logGroupName'] for g in groups] matched = set() for p in patterns: matched.update(fnmatch.filter(group_names, p)) return [g for g in groups if g['logGroupName'] in matched]
Filter log groups by their creation date. Also sets group specific value for start to the minimum of creation date or start.
def filter_creation_date(groups, start, end): """Filter log groups by their creation date. Also sets group specific value for start to the minimum of creation date or start. """ results = [] for g in groups: created = datetime.fromtimestamp(g['creationTime'] / 1000.0) if created...
Filter log groups where the last write was before the start date.
def filter_last_write(client, groups, start): """Filter log groups where the last write was before the start date. """ retry = get_retry(('ThrottlingException',)) def process_group(group_set): matched = [] for g in group_set: streams = retry( client.describe_...
Filter days where the bucket already has extant export keys.
def filter_extant_exports(client, bucket, prefix, days, start, end=None): """Filter days where the bucket already has extant export keys. """ end = end or datetime.now() # days = [start + timedelta(i) for i in range((end-start).days)] try: tag_set = client.get_object_tagging(Bucket=bucket, K...
Check iam permissions for log export access in each account
def access(config, region, accounts=()): """Check iam permissions for log export access in each account""" config = validate.callback(config) accounts_report = [] def check_access(account): accounts_report.append(account) session = get_session(account['role'], region) identity =...
size of exported records for a given day.
def size(config, accounts=(), day=None, group=None, human=True, region=None): """size of exported records for a given day.""" config = validate.callback(config) destination = config.get('destination') client = boto3.Session().client('s3') day = parse(day) def export_size(client, account): ...
sync last recorded export to actual Use --dryrun to check status.
def sync(config, group, accounts=(), dryrun=False, region=None): """sync last recorded export to actual Use --dryrun to check status. """ config = validate.callback(config) destination = config.get('destination') client = boto3.Session().client('s3') for account in config.get('accounts', (...
report current export state status
def status(config, group, accounts=(), region=None): """report current export state status""" config = validate.callback(config) destination = config.get('destination') client = boto3.Session().client('s3') for account in config.get('accounts', ()): if accounts and account['name'] not in ac...
Find exports for a given account
def get_exports(client, bucket, prefix, latest=True): """Find exports for a given account """ keys = client.list_objects_v2( Bucket=bucket, Prefix=prefix, Delimiter='/').get('CommonPrefixes', []) found = [] years = [] for y in keys: part = y['Prefix'].rsplit('/', 2)[-2] i...
export a given log group to s3
def export(group, bucket, prefix, start, end, role, poll_period=120, session=None, name="", region=None): """export a given log group to s3""" start = start and isinstance(start, six.string_types) and parse(start) or start end = (end and isinstance(start, six.string_types) and parse(en...
Lambda globals cache.
def init(): """ Lambda globals cache. """ global sqs, logs, config if config is None: with open('config.json') as fh: config = json.load(fh) if sqs is None: sqs = boto3.client('sqs') if logs is None: logs = boto3.client('logs')
CLI - Replay / Index
def process_log_group(config): """CLI - Replay / Index """ from c7n.credentials import SessionFactory factory = SessionFactory( config.region, config.profile, assume_role=config.role) session = factory() client = session.client('logs') params = dict(logGroupName=config.log_group, ...
Extract a sentry traceback structure, From a python formatted traceback string per python stdlib traceback.print_exc()
def parse_traceback(msg, site_path="site-packages", in_app_prefix="c7n"): """Extract a sentry traceback structure, From a python formatted traceback string per python stdlib traceback.print_exc() """ data = {} lines = list(filter(None, msg.split('\n'))) data['frames'] = [] err_ctx = No...
Lambda Entrypoint - Log Subscriber Format log events and relay to sentry (direct or sqs)
def process_log_event(event, context): """Lambda Entrypoint - Log Subscriber Format log events and relay to sentry (direct or sqs) """ init() # Grab the actual error log payload serialized = event['awslogs'].pop('data') data = json.loads(zlib.decompress( base64.b64decode(serialized)...
Lambda function provisioning. Self contained within the component, to allow for easier reuse.
def get_function(session_factory, name, handler, runtime, role, log_groups, project, account_name, account_id, sentry_dsn, pattern="Traceback"): """Lambda function provisioning. Self contained within the component, to allow for easier reuse. ...
Break an iterable into lists of size
def chunks(iterable, size=50): """Break an iterable into lists of size""" batch = [] for n in iterable: batch.append(n) if len(batch) % size == 0: yield batch batch = [] if batch: yield batch
daemon queue worker for config notifications
def worker_config(queue, s3_key, period, verbose): """daemon queue worker for config notifications""" logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO)) logging.getLogger('botocore').setLevel(logging.WARNING) logging.getLogger('s3transfer').setLevel(logging.WARNING) queue, regio...
Analyze flow log records for application and generate metrics per period
def list_app_resources( app, env, resources, cmdb, start, end, tz): """Analyze flow log records for application and generate metrics per period""" logging.basicConfig(level=logging.INFO) start, end = get_dates(start, end, tz) all_resources = [] for rtype_name in resources: rtype = R...
load resources into resource database.
def load_resources(bucket, prefix, region, account_config, accounts, assume, start, end, resources, store, db, verbose, debug): """load resources into resource database.""" logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO)) logging.getLogger('botocore').setLevel(loggin...
Load external plugins. Custodian is intended to interact with internal and external systems that are not suitable for embedding into the custodian code base.
def load_plugins(self): """ Load external plugins. Custodian is intended to interact with internal and external systems that are not suitable for embedding into the custodian code base. """ try: from pkg_resources import iter_entry_points except ImportError: ...
Submit a function for serialized execution on sqs
def submit(self, func, *args, **kwargs): """Submit a function for serialized execution on sqs """ self.op_sequence += 1 self.sqs.send_message( QueueUrl=self.map_queue, MessageBody=utils.dumps({'args': args, 'kwargs': kwargs}), MessageAttributes={ ...
Fetch results from separate queue
def gather(self): """Fetch results from separate queue """ limit = self.op_sequence - self.op_sequence_start results = MessageIterator(self.sqs, self.reduce_queue, limit) for m in results: # sequence_id from above msg_id = int(m['MessageAttributes']['seque...
normalize tag format on ecs resources to match common aws format.
def ecs_tag_normalize(resources): """normalize tag format on ecs resources to match common aws format.""" for r in resources: if 'tags' in r: r['Tags'] = [{'Key': t['key'], 'Value': t['value']} for t in r['tags']] r.pop('tags')
Retrieve ecs resources for serverless policies or related resources Requires arns in new format. https://docs.aws.amazon.com/AmazonECS/latest/userguide/ecs-resource-ids.html
def get_resources(self, ids, cache=True): """Retrieve ecs resources for serverless policies or related resources Requires arns in new format. https://docs.aws.amazon.com/AmazonECS/latest/userguide/ecs-resource-ids.html """ cluster_resources = {} for i in ids: ...
resource types used by the collection.
def resource_types(self): """resource types used by the collection.""" rtypes = set() for p in self.policies: rtypes.add(p.resource_type) return rtypes
Retrieve any associated metrics for the policy.
def get_metrics(self, start, end, period): """Retrieve any associated metrics for the policy.""" values = {} default_dimensions = { 'Policy': self.policy.name, 'ResType': self.policy.resource_type, 'Scope': 'Policy'} metrics = list(self.POLICY_METRICS) #...
Run policy in push mode against given event. Lambda automatically generates cloud watch logs, and metrics for us, albeit with some deficienies, metrics no longer count against valid resources matches, but against execution. If metrics execution option is enabled, custodian will generat...
def run(self, event, lambda_context): """Run policy in push mode against given event. Lambda automatically generates cloud watch logs, and metrics for us, albeit with some deficienies, metrics no longer count against valid resources matches, but against execution. If metrics ex...
Get runtime variables for policy interpolation. Runtime variables are merged with the passed in variables if any.
def get_variables(self, variables=None): """Get runtime variables for policy interpolation. Runtime variables are merged with the passed in variables if any. """ # Global policy variable expansion, we have to carry forward on # various filter/action local vocabularies. W...
Expand variables in policy data. Updates the policy data in-place.
def expand_variables(self, variables): """Expand variables in policy data. Updates the policy data in-place. """ # format string values returns a copy updated = utils.format_string_values(self.data, **variables) # Several keys should only be expanded at runtime, perserv...
get permissions needed by this policy
def get_permissions(self): """get permissions needed by this policy""" permissions = set() permissions.update(self.resource_manager.get_permissions()) for f in self.resource_manager.filters: permissions.update(f.get_permissions()) for a in self.resource_manager.action...
Handle various client side errors when describing snapshots
def extract_bad_snapshot(e): """Handle various client side errors when describing snapshots""" msg = e.response['Error']['Message'] error = e.response['Error']['Code'] e_snap_id = None if error == 'InvalidSnapshot.NotFound': e_snap_id = msg[msg.find("'") + 1:msg.rfind...
STS Role assume a boto3.Session With automatic credential renewal. Args: role_arn: iam role arn to assume session_name: client session identifier session: an optional extant session, note session is captured in a function closure for renewing the sts assumed role. :return: a boto3...
def assumed_session(role_arn, session_name, session=None, region=None, external_id=None): """STS Role assume a boto3.Session With automatic credential renewal. Args: role_arn: iam role arn to assume session_name: client session identifier session: an optional extant session, note session...
Does the resource tag schedule and policy match the current time.
def process_resource_schedule(self, i, value, time_type): """Does the resource tag schedule and policy match the current time.""" rid = i[self.id_key] # this is to normalize trailing semicolons which when done allows # dateutil.parser.parse to process: value='off=(m-f,1);' properly. ...
Get the resource's tag value specifying its schedule.
def get_tag_value(self, i): """Get the resource's tag value specifying its schedule.""" # Look for the tag, Normalize tag key and tag value found = False for t in i.get('Tags', ()): if t['Key'].lower() == self.tag_key: found = t['Value'] break ...
convert the tag to a dictionary, taking values as is This method name and purpose are opaque... and not true.
def raw_data(tag_value): """convert the tag to a dictionary, taking values as is This method name and purpose are opaque... and not true. """ data = {} pieces = [] for p in tag_value.split(' '): pieces.extend(p.split(';')) # parse components ...
test that provided tag keys are valid
def keys_are_valid(self, tag_value): """test that provided tag keys are valid""" for key in ScheduleParser.raw_data(tag_value): if key not in ('on', 'off', 'tz'): return False return True
Garbage collect old custodian policies based on prefix. We attempt to introspect to find the event sources for a policy but without the old configuration this is implicit.
def resources_gc_prefix(options, policy_config, policy_collection): """Garbage collect old custodian policies based on prefix. We attempt to introspect to find the event sources for a policy but without the old configuration this is implicit. """ # Classify policies by region policy_regions = ...
Get a boto3 sesssion potentially cross account sts assumed assumed sessions are automatically refreshed.
def get_session(account_info): """Get a boto3 sesssion potentially cross account sts assumed assumed sessions are automatically refreshed. """ s = getattr(CONN_CACHE, '%s-session' % account_info['name'], None) if s is not None: return s if account_info.get('role'): s = assumed_s...
Bulk invoke a function via queues Uses internal implementation details of rq.
def bulk_invoke(func, args, nargs): """Bulk invoke a function via queues Uses internal implementation details of rq. """ # for comparison, simplest thing that works # for i in nargs: # argv = list(args) # argv.append(i) # func.delay(*argv) # some variances between cpy and ...
Context manager for dealing with s3 errors in one place bid: bucket_id in form of account_name:bucket_name
def bucket_ops(bid, api=""): """Context manager for dealing with s3 errors in one place bid: bucket_id in form of account_name:bucket_name """ try: yield 42 except ClientError as e: code = e.response['Error']['Code'] log.info( "bucket error bucket:%s error:%s", ...
Remove bits in content results to minimize memory utilization. TODO: evolve this to a key filter on metadata, like date
def page_strip(page, versioned): """Remove bits in content results to minimize memory utilization. TODO: evolve this to a key filter on metadata, like date """ # page strip filtering should be conditional page.pop('ResponseMetadata', None) contents_key = versioned and 'Versions' or 'Contents' ...
Scan all buckets in an account and schedule processing
def process_account(account_info): """Scan all buckets in an account and schedule processing""" log = logging.getLogger('salactus.bucket-iterator') log.info("processing account %s", account_info) session = get_session(account_info) client = session.client('s3', config=s3config) buckets = client....
Process a collection of buckets. For each bucket fetch location, versioning and size and then kickoff processing strategy based on size.
def process_bucket_set(account_info, buckets): """Process a collection of buckets. For each bucket fetch location, versioning and size and then kickoff processing strategy based on size. """ region_clients = {} log = logging.getLogger('salactus.bucket-set') log.info("processing account %s",...
Select and dispatch an object source for a bucket. Choices are bucket partition, inventory, or direct pagination.
def dispatch_object_source(client, account_info, bid, bucket_info): """Select and dispatch an object source for a bucket. Choices are bucket partition, inventory, or direct pagination. """ if (account_info.get('inventory') and bucket_info['keycount'] > account_info['inventory'].get...
Use set of keys as selector for character superset Note this isn't optimal, its probabilistic on the keyset char population.
def get_keys_charset(keys, bid): """ Use set of keys as selector for character superset Note this isn't optimal, its probabilistic on the keyset char population. """ # use the keys found to sample possible chars chars = set() for k in keys: chars.update(k[:4]) remainder = chars ...
Try to detect the best partitioning strategy for a large bucket Consider nested buckets with common prefixes, and flat buckets.
def detect_partition_strategy(bid, delimiters=('/', '-'), prefix=''): """Try to detect the best partitioning strategy for a large bucket Consider nested buckets with common prefixes, and flat buckets. """ account, bucket = bid.split(":", 1) region = connection.hget('bucket-regions', bid) versio...
Split up a bucket keyspace into smaller sets for parallel iteration.
def process_bucket_partitions( bid, prefix_set=('',), partition='/', strategy=None, limit=4): """Split up a bucket keyspace into smaller sets for parallel iteration. """ if strategy is None: return detect_partition_strategy(bid) account, bucket = bid.split(':', 1) region = connectio...
Load last inventory dump and feed as key source.
def process_bucket_inventory(bid, inventory_bucket, inventory_prefix): """Load last inventory dump and feed as key source. """ log.info("Loading bucket %s keys from inventory s3://%s/%s", bid, inventory_bucket, inventory_prefix) account, bucket = bid.split(':', 1) region = connection.hg...
Bucket pagination
def process_bucket_iterator(bid, prefix="", delimiter="", **continuation): """Bucket pagination """ log.info("Iterating keys bucket %s prefix %s delimiter %s", bid, prefix, delimiter) account, bucket = bid.split(':', 1) region = connection.hget('bucket-regions', bid) versioned = bo...
Retry support for resourcegroup tagging apis. The resource group tagging api typically returns a 200 status code with embedded resource specific errors. To enable resource specific retry on throttles, we extract those, perform backoff w/ jitter and continue. Other errors are immediately raised. We...
def universal_retry(method, ResourceARNList, **kw): """Retry support for resourcegroup tagging apis. The resource group tagging api typically returns a 200 status code with embedded resource specific errors. To enable resource specific retry on throttles, we extract those, perform backoff w/ jitter and...
Returns a list of tags from resource and user supplied in the format: [{'Key': 'key', 'Value': 'value'}] Due to drift on implementation on copy-tags/tags used throughout the code base, the following options are supported: copy_tags (Tags to copy from the resource): - list of str, e.g. ['...
def coalesce_copy_user_tags(resource, copy_tags, user_tags): """ Returns a list of tags from resource and user supplied in the format: [{'Key': 'key', 'Value': 'value'}] Due to drift on implementation on copy-tags/tags used throughout the code base, the following options are supported: cop...
Move source tag value to destination tag value - Collect value from old tag - Delete old tag - Create new tag & assign stored value
def process_rename(self, client, tag_value, resource_set): """ Move source tag value to destination tag value - Collect value from old tag - Delete old tag - Create new tag & assign stored value """ self.log.info("Renaming tag on %s instances" % (len(resource_set...
Transform tag value - Collect value from tag - Transform Tag value - Assign new value for key
def process_transform(self, tag_value, resource_set): """ Transform tag value - Collect value from tag - Transform Tag value - Assign new value for key """ self.log.info("Transforming tag value on %s instances" % ( len(resource_set))) key = se...
Returns a mapping of {resource_id: {tagkey: tagvalue}}
def get_resource_tag_map(self, r_type, ids): """ Returns a mapping of {resource_id: {tagkey: tagvalue}} """ manager = self.manager.get_resource_manager(r_type) r_id = manager.resource_type.id # TODO only fetch resource with the given ids. return { r[r_...
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_names.add(a['LaunchConfigurationName']) if not 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.filter(self.manager, **params)
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)
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 == 'n': click.echo('Abort!') ...
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('botocore').setLevel(level=logging.WARNING) ...
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 format_accounts_csv or format_ac...
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, tagprefix=None, not_bucke...
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_buckets = {b.bucket_id: b for b in prev.bu...
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...
def inspect_partitions(bucket): """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 at...
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 click.echo("Bucket: %s" % found.nam...
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): account, bucket = j....
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, conn).count) for q in Que...
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=q.connection) click.e...
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 = { 'subscription_id': sub['subscrip...
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_retries: response = self.orig_send(request, headers, content, **kwargs) ...
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 ...
def get_principal_dictionary(graph_client, object_ids, raise_on_graph_call_error=False): """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_...
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 :return: The resolved value or an empty string if unsuccessful. """ if hasattr(graph_object, 'user_principal_name'): return graph_object.user_...
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) """ if range_str == '*': return PortsRangeHelper.PortsRange(start=0, end=65535) s = range_str.split('-')...
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 'destinationPortRange' in properties: return [PortsRangeHelper._get_port_range(properties['destinationP...
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 ranges for i in range(r.start, r.end + 1)])
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 """ pattern = re.compile('^\\d+(-\\d+)?(,\\d+(-\\d+)?)*$') if pattern.match(ports) is None: return False ...
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'] """ if len(data) == 0: return [] # Transform diff_ports list to the ranges list first = 0 ...
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(default - Deny) based on the provided Network Security Group object, direction and protocol. """ rules = nsg['properties']['securityRules'] rule...