text_prompt stringlengths 100 17.7k ⌀ | code_prompt stringlengths 7 9.86k ⌀ |
|---|---|
<SYSTEM_TASK:>
Plot an histogram of the data.
<END_TASK>
<USER_TASK:>
Description:
def histogram(series, **kwargs):
"""Plot an histogram of the data.
Parameters
----------
series: Series
The data to plot.
Returns
-------
str
The resulting image encoded as a string.
""" |
imgdata = BytesIO()
plot = _plot_histogram(series, **kwargs)
plot.figure.subplots_adjust(left=0.15, right=0.95, top=0.9, bottom=0.1, wspace=0, hspace=0)
plot.figure.savefig(imgdata)
imgdata.seek(0)
result_string = 'data:image/png;base64,' + quote(base64.b64encode(imgdata.getvalue()))
# TODO... |
<SYSTEM_TASK:>
Factory func for filters.
<END_TASK>
<USER_TASK:>
Description:
def factory(self, data, manager=None):
"""Factory func for filters.
data - policy config for filters
manager - resource type manager (ec2, s3, etc)
""" |
# Make the syntax a little nicer for common cases.
if isinstance(data, dict) and len(data) == 1 and 'type' not in data:
op = list(data.keys())[0]
if op == 'or':
return Or(data, self, manager)
elif op == 'and':
return And(data, self, m... |
<SYSTEM_TASK:>
Determine the immediate parent boolean operator for a filter
<END_TASK>
<USER_TASK:>
Description:
def get_block_operator(self):
"""Determine the immediate parent boolean operator for a filter""" |
# Top level operator is `and`
block_stack = ['and']
for f in self.manager.iter_filters(block_end=True):
if f is None:
block_stack.pop()
continue
if f.type in ('and', 'or', 'not'):
block_stack.append(f.type)
if f... |
<SYSTEM_TASK:>
Specific validation for `resource_count` type
<END_TASK>
<USER_TASK:>
Description:
def _validate_resource_count(self):
""" Specific validation for `resource_count` type
The `resource_count` type works a little differently because it operates
on the entire set of resources. It:
... |
for field in ('op', 'value'):
if field not in self.data:
raise PolicyValidationError(
"Missing '%s' in value filter %s" % (field, self.data))
if not (isinstance(self.data['value'], int) or
isinstance(self.data['value'], list)):
... |
<SYSTEM_TASK:>
Given an inventory csv file, return an iterator over keys
<END_TASK>
<USER_TASK:>
Description:
def load_manifest_file(client, bucket, schema, versioned, ifilters, key_info):
"""Given an inventory csv file, return an iterator over keys
""" |
# To avoid thundering herd downloads, we do an immediate yield for
# interspersed i/o
yield None
# Inline these values to avoid the local var lookup, they are constants
# rKey = schema['Key'] # 1
# rIsLatest = schema['IsLatest'] # 3
# rVersionId = schema['VersionId'] # 2
with tempfile... |
<SYSTEM_TASK:>
Given an inventory location for a bucket, return an iterator over keys
<END_TASK>
<USER_TASK:>
Description:
def load_bucket_inventory(
client, inventory_bucket, inventory_prefix, versioned, ifilters):
"""Given an inventory location for a bucket, return an iterator over keys
on the most r... |
now = datetime.datetime.now()
key_prefix = "%s/%s" % (inventory_prefix, now.strftime('%Y-%m-'))
keys = client.list_objects(
Bucket=inventory_bucket, Prefix=key_prefix).get('Contents', [])
keys = [k['Key'] for k in keys if k['Key'].endswith('.json')]
keys.sort()
if not keys:
# no... |
<SYSTEM_TASK:>
Generator to generate a set of keys from
<END_TASK>
<USER_TASK:>
Description:
def random_chain(generators):
"""Generator to generate a set of keys from
from a set of generators, each generator is selected
at random and consumed to exhaustion.
""" |
while generators:
g = random.choice(generators)
try:
v = g.next()
if v is None:
continue
yield v
except StopIteration:
generators.remove(g) |
<SYSTEM_TASK:>
Check a bucket for a named inventory, and return the destination.
<END_TASK>
<USER_TASK:>
Description:
def get_bucket_inventory(client, bucket, inventory_id):
"""Check a bucket for a named inventory, and return the destination.""" |
inventories = client.list_bucket_inventory_configurations(
Bucket=bucket).get('InventoryConfigurationList', [])
inventories = {i['Id']: i for i in inventories}
found = fnmatch.filter(inventories, inventory_id)
if not found:
return None
i = inventories[found.pop()]
s3_info = i['... |
<SYSTEM_TASK:>
You can customize the automated documentation by altering
<END_TASK>
<USER_TASK:>
Description:
def create_html_file(config):
""" You can customize the automated documentation by altering
the code directly in this script or the associated jinja2 template
""" |
logging.debug("Starting create_html_file")
logging.debug(
"\tjinja2_template_file = {}"
.format(config['jinja2_template_filename']))
logging.debug(
"\ttrendered_filename = {}"
.format(config['rendered_filename']))
ts = time.time()
timestamp = datetime.datetime.utcfr... |
<SYSTEM_TASK:>
Update this function to help build the link to your file
<END_TASK>
<USER_TASK:>
Description:
def get_file_url(path, config):
""" Update this function to help build the link to your file
""" |
file_url_regex = re.compile(config['file_url_regex'])
new_path = re.sub(file_url_regex, config['file_url_base'], path)
return new_path |
<SYSTEM_TASK:>
Gather policy information from files
<END_TASK>
<USER_TASK:>
Description:
def gather_file_data(config):
""" Gather policy information from files
""" |
file_regex = re.compile(config['file_regex'])
category_regex = re.compile(config['category_regex'])
policies = {}
for root, dirs, files in os.walk(config['c7n_policy_directory']):
for file in files:
if file_regex.match(file):
file_path = root + '/' + file
... |
<SYSTEM_TASK:>
Return all github repositories in an organization.
<END_TASK>
<USER_TASK:>
Description:
def github_repos(organization, github_url, github_token):
"""Return all github repositories in an organization.""" |
# Get github repos
headers = {"Authorization": "token {}".format(github_token)}
next_cursor = None
while next_cursor is not False:
params = {'query': query, 'variables': {
'organization': organization, 'cursor': next_cursor}}
response = requests.post(github_url, headers=hea... |
<SYSTEM_TASK:>
Stream changes for repos in a GitHub organization.
<END_TASK>
<USER_TASK:>
Description:
def org_stream(ctx, organization, github_url, github_token, clone_dir,
verbose, filter, exclude, stream_uri, assume):
"""Stream changes for repos in a GitHub organization.
""" |
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and logging.DEBUG or logging.INFO))
log.info("Checkout/Update org repos")
repos = ctx.invoke(
org_checkout,
organization=organization,
github_url=github_url,
github... |
<SYSTEM_TASK:>
Checkout repositories from a GitHub organization.
<END_TASK>
<USER_TASK:>
Description:
def org_checkout(organization, github_url, github_token, clone_dir,
verbose, filter, exclude):
"""Checkout repositories from a GitHub organization.""" |
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and logging.DEBUG or logging.INFO))
callbacks = pygit2.RemoteCallbacks(
pygit2.UserPass(github_token, 'x-oauth-basic'))
repos = []
for r in github_repos(organization, github_url, gith... |
<SYSTEM_TASK:>
Policy diff between two arbitrary revisions.
<END_TASK>
<USER_TASK:>
Description:
def diff(repo_uri, source, target, output, verbose):
"""Policy diff between two arbitrary revisions.
Revision specifiers for source and target can use fancy git refspec syntax
for symbolics, dates, etc.
Se... |
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(logging.WARNING)
if repo_uri is None:
repo_uri = pygit2.discover_repository(os.getcwd())
repo = pygit2.Repos... |
<SYSTEM_TASK:>
Stream git history policy changes to destination.
<END_TASK>
<USER_TASK:>
Description:
def stream(repo_uri, stream_uri, verbose, assume, sort, before=None, after=None):
"""Stream git history policy changes to destination.
Default stream destination is a summary of the policy changes to stdout, ... |
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(logging.WARNING)
if before:
before = parse(before)
if after:
after = parse(after)
if sort:
... |
<SYSTEM_TASK:>
return the named subset of policies
<END_TASK>
<USER_TASK:>
Description:
def select(self, names):
"""return the named subset of policies""" |
return PolicyCollection(
[p for p in self.policies if p.name in names], self.options) |
<SYSTEM_TASK:>
Show policies changes between arbitrary commits.
<END_TASK>
<USER_TASK:>
Description:
def delta_commits(self, baseline, target):
"""Show policies changes between arbitrary commits.
The common use form is comparing the heads of two branches.
""" |
baseline_files = self._get_policy_fents(baseline.tree)
target_files = self._get_policy_fents(target.tree)
baseline_policies = PolicyCollection()
target_policies = PolicyCollection()
# Added
for f in set(target_files) - set(baseline_files):
target_policies +... |
<SYSTEM_TASK:>
Return an iterator of policy changes along a commit lineage in a repo.
<END_TASK>
<USER_TASK:>
Description:
def delta_stream(self, target='HEAD', limit=None,
sort=pygit2.GIT_SORT_TIME | pygit2.GIT_SORT_REVERSE,
after=None, before=None):
"""Return an itera... |
if target == 'HEAD':
target = self.repo.head.target
commits = []
for commit in self.repo.walk(target, sort):
cdate = commit_date(commit)
log.debug(
"processing commit id:%s date:%s parents:%d msg:%s",
str(commit.id)[:6], cdate... |
<SYSTEM_TASK:>
Bookkeeping on internal data structures while iterating a stream.
<END_TASK>
<USER_TASK:>
Description:
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(pchange.policy)
elif pchange.kind == ChangeType.REMOVE:
self.policy_files[pchange.file_path].remov... |
<SYSTEM_TASK:>
send the given policy change
<END_TASK>
<USER_TASK:>
Description:
def send(self, change):
"""send the given policy change""" |
self.buf.append(change)
if len(self.buf) % self.BUF_SIZE == 0:
self.flush() |
<SYSTEM_TASK:>
flush any buffered messages
<END_TASK>
<USER_TASK:>
Description:
def flush(self):
"""flush any buffered messages""" |
buf = self.buf
self.buf = []
if buf:
self._flush(buf) |
<SYSTEM_TASK:>
Download firehose archive, aggregate records in memory and write back.
<END_TASK>
<USER_TASK:>
Description:
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_fmt(os.path.getsize(fh.name)), key)
fh.seek(0, 0)
record_count = 0
iteration_count = 0
for... |
<SYSTEM_TASK:>
Split up a firehose s3 object into records
<END_TASK>
<USER_TASK:>
Description:
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 cont... |
buf = None
while True:
chunk = fh.read(buffer_size)
if not chunk:
if buf:
yield json.loads(buf)
return
if buf:
chunk = b"%s%s" % (buf, chunk)
buf = None
while chunk:
idx = chunk.find(b'}{')
i... |
<SYSTEM_TASK:>
Get an active session in the target account.
<END_TASK>
<USER_TASK:>
Description:
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[account_id] = s = assumed_session(
self.config['accounts'][account_id]['role'], "S... |
<SYSTEM_TASK:>
Scope a schema error to its policy name and resource.
<END_TASK>
<USER_TASK:>
Description:
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:{}\n".format(
pdata.get('name', 'unknown'), pdata.get('resource', 'unknown')) + error.messa... |
<SYSTEM_TASK:>
Try to find the best error for humans to resolve
<END_TASK>
<USER_TASK:>
Description:
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,
... |
if error.validator not in ('anyOf', 'oneOf'):
return error
r = t = None
if isinstance(error.instance, dict):
t = error.instance.get('type')
r = error.instance.get('resource')
if r is not None:
found = None
for idx, v in enumerate(error.validator_value):
... |
<SYSTEM_TASK:>
get a resource manager or a given resource type.
<END_TASK>
<USER_TASK:>
Description:
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:
provider_name = self.ctx.policy.provider_name
provider_resources = clouds[provider_name].resources
klass = provider_resources.get(resource_type)
if klass is None:
... |
<SYSTEM_TASK:>
Augment ElasticBeanstalk Environments with their tags.
<END_TASK>
<USER_TASK:>
Description:
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,
ResourceArn=eb_env['EnvironmentArn'])['ResourceTags']
except client.exceptions.ResourceNotFoundE... |
<SYSTEM_TASK:>
Assemble a document representing all the config state around a bucket.
<END_TASK>
<USER_TASK:>
Description:
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 = c_location = location = "us-east-1"
methods = list(S3_AUGMENT_TABLE)
for m, k, default, select in methods:
try:
method = getattr(c, m)
... |
<SYSTEM_TASK:>
Tries to get the bucket region from Location.LocationConstraint
<END_TASK>
<USER_TASK:>
Description:
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 t... |
remap = {None: 'us-east-1', 'EU': 'eu-west-1'}
region = b.get('Location', {}).get('LocationConstraint')
return remap.get(region, region) |
<SYSTEM_TASK:>
Format a policy's extant records into a report.
<END_TASK>
<USER_TASK:>
Description:
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,
extra_fields=options.field,
include_default_fields=not options.no_default_fields,
include_region=len(regions)... |
<SYSTEM_TASK:>
Retrieve all s3 records for the given policy output url
<END_TASK>
<USER_TASK:>
Description:
def record_set(session_factory, bucket, key_prefix, start_date, specify_hour=False):
"""Retrieve all s3 records for the given policy output url
From the given start date.
""" |
s3 = local_session(session_factory).client('s3')
records = []
key_count = 0
date = start_date.strftime('%Y/%m/%d')
if specify_hour:
date += "/{}".format(start_date.hour)
else:
date += "/00"
marker = "{}/{}/resources.json.gz".format(key_prefix.strip("/"), date)
p = s... |
<SYSTEM_TASK:>
Only the first record for each id
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Resources preparation for transport.
<END_TASK>
<USER_TASK:>
Description:
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
... |
handler = getattr(self, "prepare_%s" % (
self.manager.type.replace('-', '_')),
None)
if handler is None:
return resources
return handler(resources) |
<SYSTEM_TASK:>
run export across accounts and log groups specified in config.
<END_TASK>
<USER_TASK:>
Description:
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 = debug and MainThreadExecutor or ThreadPoolExecutor
with executor(max_workers=32) as w:
futures = {}
for accoun... |
<SYSTEM_TASK:>
simple decorator that will auto fan out async style in lambda.
<END_TASK>
<USER_TASK:>
Description:
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('lambda')
client.invoke(
FunctionName=os.environ['AWS_LAMBDA_FUNCTION_NAME'],
InvocationType='Event',
Payload=dum... |
<SYSTEM_TASK:>
Filter log groups by shell patterns.
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Filter log groups by their creation date.
<END_TASK>
<USER_TASK:>
Description:
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 > end:
continue
if created > start:
g['exportStart'] = created
else:
g['exportStart'] = start
results.append(g)
return results |
<SYSTEM_TASK:>
Filter log groups where the last write was before the start date.
<END_TASK>
<USER_TASK:>
Description:
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_log_streams,
logGroupName=g['logGroupName'],
orderBy='LastEventTime',
limit=1,... |
<SYSTEM_TASK:>
Filter days where the bucket already has extant export keys.
<END_TASK>
<USER_TASK:>
Description:
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, Key=prefix).get('TagSet', [])
except ClientError as e:
if e.response['Error']['Code'] != 'NoSuchKey':
raise
tag_set = ... |
<SYSTEM_TASK:>
size of exported records for a given day.
<END_TASK>
<USER_TASK:>
Description:
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):
paginator = client.get_paginator('list_objects_v2')
count = 0
size = 0
session = get_session(account['... |
<SYSTEM_TASK:>
report current export state status
<END_TASK>
<USER_TASK:>
Description:
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 accounts:
continue
session = get_session(account['role'], region)
acco... |
<SYSTEM_TASK:>
Find exports for a given account
<END_TASK>
<USER_TASK:>
Description:
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]
if not part.isdigit():
continue
year = int(part)
years.append(year)
i... |
<SYSTEM_TASK:>
Lambda Entrypoint - Log Subscriber
<END_TASK>
<USER_TASK:>
Description:
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), 16 + zlib.MAX_WBITS))
msg = get_sentry_message(config, data)
if msg is None:
return
if config['sentry_dsn']:
# Delive... |
<SYSTEM_TASK:>
Break an iterable into lists of size
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Load external plugins.
<END_TASK>
<USER_TASK:>
Description:
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:
return
for ep in iter_entry_points(group="custodian.%s" % self.plugin_type):
f = ep.load()
f() |
<SYSTEM_TASK:>
Submit a function for serialized execution on sqs
<END_TASK>
<USER_TASK:>
Description:
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={
'sequence_id': {
'StringValue': str(self.op_sequence),
'DataTy... |
<SYSTEM_TASK:>
Fetch results from separate queue
<END_TASK>
<USER_TASK:>
Description:
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']['sequence_id']['StringValue'])
if (not msg_id > self.op_sequence_sta... |
<SYSTEM_TASK:>
normalize tag format on ecs resources to match common aws format.
<END_TASK>
<USER_TASK:>
Description:
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') |
<SYSTEM_TASK:>
Retrieve any associated metrics for the policy.
<END_TASK>
<USER_TASK:>
Description:
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)
# Support action, and filter custom metrics
for el in itertools.chain(
self.polic... |
<SYSTEM_TASK:>
Run policy in push mode against given event.
<END_TASK>
<USER_TASK:>
Description:
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 lo... |
from c7n.actions import EventAction
mode = self.policy.data.get('mode', {})
if not bool(mode.get("log", True)):
root = logging.getLogger()
map(root.removeHandler, root.handlers[:])
root.handlers = [logging.NullHandler()]
resources = self.resolve_res... |
<SYSTEM_TASK:>
Get runtime variables for policy interpolation.
<END_TASK>
<USER_TASK:>
Description:
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. Where possible defer
# by using a format string.
#
# See https://github.com/capitalone/cloud-custodian/issues/2330
if not variables:
variables = {}
... |
<SYSTEM_TASK:>
Expand variables in policy data.
<END_TASK>
<USER_TASK:>
Description:
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, perserve them.
if 'member-role' in updated.get('mode', {}):
updated['mode']['member-role'] = self.data['mode']['member-role'... |
<SYSTEM_TASK:>
get permissions needed by this policy
<END_TASK>
<USER_TASK:>
Description:
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.actions:
permissions.update(a.get_permissions())
return permissi... |
<SYSTEM_TASK:>
Handle various client side errors when describing snapshots
<END_TASK>
<USER_TASK:>
Description:
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("'")]
log.warning("Snapshot not found %s" % e_snap_id)
elif error == 'InvalidSnap... |
<SYSTEM_TASK:>
STS Role assume a boto3.Session
<END_TASK>
<USER_TASK:>
Description:
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_nam... |
if session is None:
session = Session()
retry = get_retry(('Throttling',))
def refresh():
parameters = {"RoleArn": role_arn, "RoleSessionName": session_name}
if external_id is not None:
parameters['ExternalId'] = external_id
credentials = retry(
... |
<SYSTEM_TASK:>
Does the resource tag schedule and policy match the current time.
<END_TASK>
<USER_TASK:>
Description:
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.
# before this normalization, some cases would silently fail.
value = ';'.join(filter(None, value.split(';')))
if self... |
<SYSTEM_TASK:>
Get the resource's tag value specifying its schedule.
<END_TASK>
<USER_TASK:>
Description:
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
if found is False:
return False
# enforce utf8, or do translate tab... |
<SYSTEM_TASK:>
convert the tag to a dictionary, taking values as is
<END_TASK>
<USER_TASK:>
Description:
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
for piece in pieces:
kv = piece.split('=')
# components must by key=value
if not len(kv) == 2:
continue
... |
<SYSTEM_TASK:>
test that provided tag keys are valid
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Garbage collect old custodian policies based on prefix.
<END_TASK>
<USER_TASK:>
Description:
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 with... |
# Classify policies by region
policy_regions = {}
for p in policy_collection:
if p.execution_mode == 'poll':
continue
policy_regions.setdefault(p.options.region, []).append(p)
regions = get_gc_regions(options.regions)
for r in regions:
region_gc(options, r, pol... |
<SYSTEM_TASK:>
Get a boto3 sesssion potentially cross account sts assumed
<END_TASK>
<USER_TASK:>
Description:
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_session(account_info['role'], SESSION_NAME)
else:
s = boto3.Session()
setattr(CONN_CACHE, '%s-session' % account_info['name'], s)
return... |
<SYSTEM_TASK:>
Context manager for dealing with s3 errors in one place
<END_TASK>
<USER_TASK:>
Description:
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",
bid,
e.response['Error']['Code'])
if code == "NoSuchBucket":
pass
elif code == 'AccessDenied':
... |
<SYSTEM_TASK:>
Remove bits in content results to minimize memory utilization.
<END_TASK>
<USER_TASK:>
Description:
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'
contents = page.get(contents_key, ())
# aggressive size
if versioned:
keys = []
for k in contents:
if k['IsLatest']:
... |
<SYSTEM_TASK:>
Scan all buckets in an account and schedule processing
<END_TASK>
<USER_TASK:>
Description:
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.list_buckets()['Buckets']
connection.hset(
'bucket-accounts', account_info['name'], js... |
<SYSTEM_TASK:>
Process a collection of buckets.
<END_TASK>
<USER_TASK:>
Description:
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", account_info)
session = get_session(account_info)
client = session.client('s3', config=s3config)
for b in buckets:
bid = bucket_id(account_info, b)
with bucket_ops(bid):
... |
<SYSTEM_TASK:>
Select and dispatch an object source for a bucket.
<END_TASK>
<USER_TASK:>
Description:
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('bucket-size-threshold',
DEFAULT_INVENTORY_BUCKET_SIZE_THRESHOLD)):
inventory_info = get_bucket_inventory(
client,
bucket_info... |
<SYSTEM_TASK:>
Use set of keys as selector for character superset
<END_TASK>
<USER_TASK:>
Description:
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
# Normalize charsets for matching
normalized = {}
for n, sset in [
("p", set(string.punctuation)),
("w", set(string.whitespace))
]:
m = chars... |
<SYSTEM_TASK:>
Try to detect the best partitioning strategy for a large bucket
<END_TASK>
<USER_TASK:>
Description:
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 buc... |
account, bucket = bid.split(":", 1)
region = connection.hget('bucket-regions', bid)
versioned = bool(int(connection.hget('bucket-versions', bid)))
size = int(float(connection.hget('bucket-sizes', bid)))
session = get_session(
json.loads(connection.hget('bucket-accounts', account)))
s3 =... |
<SYSTEM_TASK:>
Load last inventory dump and feed as key source.
<END_TASK>
<USER_TASK:>
Description:
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.hget('bucket-regions', bid)
versioned = bool(int(connection.hget('bucket-versions', bid)))
session = boto3.Session()
s3 = se... |
<SYSTEM_TASK:>
Retry support for resourcegroup tagging apis.
<END_TASK>
<USER_TASK:>
Description:
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. T... |
max_attempts = 6
for idx, delay in enumerate(
utils.backoff_delays(1.5, 2 ** 8, jitter=True)):
response = method(ResourceARNList=ResourceARNList, **kw)
failures = response.get('FailedResourcesMap', {})
if not failures:
return response
errors = {}
... |
<SYSTEM_TASK:>
Return a mapping of launch configs for the given set of asgs
<END_TASK>
<USER_TASK:>
Description:
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_names:
return {}
lc_resources = self.manager.get_resource_manager('launch-config')
... |
<SYSTEM_TASK:>
Support server side filtering on arns or names
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Run across a set of accounts and buckets.
<END_TASK>
<USER_TASK:>
Description:
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)
if debug:
def invoke(f, *args, **kw):
# if f.func_name == 'process_keyset':
# key_count = len(... |
<SYSTEM_TASK:>
Delete all persistent cluster state.
<END_TASK>
<USER_TASK:>
Description:
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!')
else:
click.echo('Invalid input :(') |
<SYSTEM_TASK:>
Report on stats by account
<END_TASK>
<USER_TASK:>
Description:
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_accounts_plain)
if region:
for a in accounts:
a.buckets = [b for b in a.buckets if b.region in region]
accounts = [a for a in accounts if a.bucket_count]
i... |
<SYSTEM_TASK:>
watch scan rates across the cluster
<END_TASK>
<USER_TASK:>
Description:
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.buckets()}
totals = {'scanned': 0, 'krate': 0, 'lrate': ... |
<SYSTEM_TASK:>
Discover the partitions on a bucket via introspection.
<END_TASK>
<USER_TASK:>
Description:
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 bucke... |
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s: %(name)s:%(levelname)s %(message)s")
logging.getLogger('botocore').setLevel(level=logging.WARNING)
state = db.db()
# add db.bucket accessor
found = None
for b in state.buckets():
if b.name == bucket:
... |
<SYSTEM_TASK:>
Show all information known on a bucket.
<END_TASK>
<USER_TASK:>
Description:
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.name)
click.echo("Account: %s" % found.account)
click.echo("Region: %s" ... |
<SYSTEM_TASK:>
Extracts ports ranges from the NSG rule object
<END_TASK>
<USER_TASK:>
Description:
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['destinationPortRange'])]
else:
return [PortsRangeHelper._get_port_range(r)
for r in properties['destinationPortRanges']] |
<SYSTEM_TASK:>
Given an arbitrary resource attempt to resolve back to a qualified name.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Get extant locks for the given account.
<END_TASK>
<USER_TASK:>
Description:
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()) |
<SYSTEM_TASK:>
Get the lock status for a given resource.
<END_TASK>
<USER_TASK:>
Description:
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_account_id(account_id)
params = parent_id and {'parent_id': parent_id} or None
return self.http.get(
"%s/%s/locks/%s" % (self.endpoint, account_id, resource_id),
params=params, auth=self.get_api_auth()) |
<SYSTEM_TASK:>
report on a cross account policy execution.
<END_TASK>
<USER_TASK:>
Description:
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 ... |
accounts_config, custodian_config, executor = init(
config, use, debug, verbose, accounts, tags, policy,
resource=resource, policy_tags=policy_tags)
resource_types = set()
for p in custodian_config.get('policies'):
resource_types.add(p['resource'])
if len(resource_types) > 1:
... |
<SYSTEM_TASK:>
run an aws script across accounts
<END_TASK>
<USER_TASK:>
Description:
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, accounts, tags, (), ())
if echo:
print("command to run: `%s`" % (" ".join(script_args)))
return
# Support fully quoted scripts, which are ... |
<SYSTEM_TASK:>
Execute a set of policies on an account.
<END_TASK>
<USER_TASK:>
Description:
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 = None
CONN_CACHE.time = None
# allow users to specify interpolated output paths
if '{' not in output_path:
output_path = os.path.join(output_path, account['name'], region)
cache_path = os.path.join(c... |
<SYSTEM_TASK:>
run a custodian policy across accounts
<END_TASK>
<USER_TASK:>
Description:
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(
config, use, debug, verbose, accounts, tags, policy, policy_tags=policy_tags)
policy_counts = Counter()
success = True
if metrics_uri:
metrics = metrics_uri
if not cache_path:
cache_path = os.path.expanduser("~/.cache/c7n... |
<SYSTEM_TASK:>
Ensure all logging output has been flushed.
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
start thread transports.
<END_TASK>
<USER_TASK:>
Description:
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(thread)
thread.daemon = True
thread.start() |
<SYSTEM_TASK:>
Handle various client side errors when describing images
<END_TASK>
<USER_TASK:>
Description:
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':
e_ami_ids = [
e_ami_id.strip() for e_ami_id
in msg[msg.find("'[") + 2:msg.rfind("]'")].split(',')]
log.w... |
<SYSTEM_TASK:>
format config for lambda exec
<END_TASK>
<USER_TASK:>
Description:
def format_json(config):
"""format config for lambda exec
""" |
with open(config) as fh:
print(json.dumps(yaml.safe_load(fh.read()), indent=2)) |
<SYSTEM_TASK:>
Attempt to acquire any pending locks.
<END_TASK>
<USER_TASK:>
Description:
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 = results.pop('Payload').read()
pprint.pprint(results)
pprint.pprint(json.loads(content)) |
<SYSTEM_TASK:>
Check config status in an account.
<END_TASK>
<USER_TASK:>
Description:
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({
c['name']: dict(
snapshot=str(
c['configSnapshotDeliveryInfo'].get('l... |
<SYSTEM_TASK:>
run local app server, assumes into the account
<END_TASK>
<USER_TASK:>
Description:
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 definitions")
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('botocore').setLevel(logging.WARNING)
if controller.db.pro... |
<SYSTEM_TASK:>
Given a class, return its docstring.
<END_TASK>
<USER_TASK:>
Description:
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 cls in inspect.getmro(starting_class):
if inspect.getdoc(cls):
return inspect.getdoc(cls) |
<SYSTEM_TASK:>
For tab-completion via argcomplete, return completion options.
<END_TASK>
<USER_TASK:>
Description:
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 h... |
from c7n import schema
load_resources()
components = prefix.split('.')
if components[0] in provider.clouds.keys():
cloud_provider = components.pop(0)
provider_resources = provider.resources(cloud_provider)
else:
cloud_provider = 'aws'
provider_resources = provider.r... |
<SYSTEM_TASK:>
Determine the start and end dates based on user-supplied options.
<END_TASK>
<USER_TASK:>
Description:
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)
if options.start and options.end:
start = options.start
end = options.end
else:
end = datetime.utcnow()
start = end - timedelta(options.days)
... |
<SYSTEM_TASK:>
EC2 API and AWOL Tags
<END_TASK>
<USER_TASK:>
Description:
def augment(self, resources):
"""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.
... |
# First if we're in event based lambda go ahead and skip this,
# tags can't be trusted in ec2 instances immediately post creation.
if not resources or self.manager.data.get(
'mode', {}).get('type', '') in (
'cloudtrail', 'ec2-instance-state'):
ret... |
<SYSTEM_TASK:>
Create a lambda code archive for running custodian.
<END_TASK>
<USER_TASK:>
Description:
def custodian_archive(packages=None):
"""Create a lambda code archive for running custodian.
Lambda archive currently always includes `c7n` and
`pkg_resources`. Add additional packages in the mode block.... |
modules = {'c7n', 'pkg_resources'}
if packages:
modules = filter(None, modules.union(packages))
return PythonPackageArchive(*sorted(modules)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.