partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | Transport.send | send the given policy change | tools/c7n_policystream/policystream.py | def send(self, change):
"""send the given policy change"""
self.buf.append(change)
if len(self.buf) % self.BUF_SIZE == 0:
self.flush() | def send(self, change):
"""send the given policy change"""
self.buf.append(change)
if len(self.buf) % self.BUF_SIZE == 0:
self.flush() | [
"send",
"the",
"given",
"policy",
"change"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L487-L491 | [
"def",
"send",
"(",
"self",
",",
"change",
")",
":",
"self",
".",
"buf",
".",
"append",
"(",
"change",
")",
"if",
"len",
"(",
"self",
".",
"buf",
")",
"%",
"self",
".",
"BUF_SIZE",
"==",
"0",
":",
"self",
".",
"flush",
"(",
")"
] | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | Transport.flush | flush any buffered messages | tools/c7n_policystream/policystream.py | def flush(self):
"""flush any buffered messages"""
buf = self.buf
self.buf = []
if buf:
self._flush(buf) | def flush(self):
"""flush any buffered messages"""
buf = self.buf
self.buf = []
if buf:
self._flush(buf) | [
"flush",
"any",
"buffered",
"messages"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L493-L498 | [
"def",
"flush",
"(",
"self",
")",
":",
"buf",
"=",
"self",
".",
"buf",
"self",
".",
"buf",
"=",
"[",
"]",
"if",
"buf",
":",
"self",
".",
"_flush",
"(",
"buf",
")"
] | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | process_firehose_archive | Download firehose archive, aggregate records in memory and write back. | tools/c7n_logexporter/c7n_logexporter/flowdeliver.py | 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... | 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... | [
"Download",
"firehose",
"archive",
"aggregate",
"records",
"in",
"memory",
"and",
"write",
"back",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/flowdeliver.py#L64-L93 | [
"def",
"process_firehose_archive",
"(",
"bucket",
",",
"key",
")",
":",
"data",
"=",
"{",
"}",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w+b'",
")",
"as",
"fh",
":",
"s3",
".",
"download_file",
"(",
"bucket",
",",
"key",
",",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | records_iter | 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. | tools/c7n_logexporter/c7n_logexporter/flowdeliver.py | 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 ... | 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 ... | [
"Split",
"up",
"a",
"firehose",
"s3",
"object",
"into",
"records"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/flowdeliver.py#L138-L164 | [
"def",
"records_iter",
"(",
"fh",
",",
"buffer_size",
"=",
"1024",
"*",
"1024",
"*",
"16",
")",
":",
"buf",
"=",
"None",
"while",
"True",
":",
"chunk",
"=",
"fh",
".",
"read",
"(",
"buffer_size",
")",
"if",
"not",
"chunk",
":",
"if",
"buf",
":",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | Controller.get_session | Get an active session in the target account. | tools/sandbox/c7n_sphere11/c7n_sphere11/controller.py | 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... | 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... | [
"Get",
"an",
"active",
"session",
"in",
"the",
"target",
"account",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/controller.py#L50-L60 | [
"def",
"get_session",
"(",
"self",
",",
"account_id",
")",
":",
"if",
"account_id",
"not",
"in",
"self",
".",
"account_sessions",
":",
"if",
"account_id",
"not",
"in",
"self",
".",
"config",
"[",
"'accounts'",
"]",
":",
"raise",
"AccountNotFound",
"(",
"\"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | policy_error_scope | Scope a schema error to its policy name and resource. | c7n/schema.py | 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... | 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... | [
"Scope",
"a",
"schema",
"error",
"to",
"its",
"policy",
"name",
"and",
"resource",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/schema.py#L82-L91 | [
"def",
"policy_error_scope",
"(",
"error",
",",
"data",
")",
":",
"err_path",
"=",
"list",
"(",
"error",
".",
"absolute_path",
")",
"if",
"err_path",
"[",
"0",
"]",
"!=",
"'policies'",
":",
"return",
"error",
"pdata",
"=",
"data",
"[",
"'policies'",
"]",... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | specific_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 structural knowledge of schema to
... | c7n/schema.py | 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... | 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... | [
"Try",
"to",
"find",
"the",
"best",
"error",
"for",
"humans",
"to",
"resolve"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/schema.py#L94-L146 | [
"def",
"specific_error",
"(",
"error",
")",
":",
"if",
"error",
".",
"validator",
"not",
"in",
"(",
"'anyOf'",
",",
"'oneOf'",
")",
":",
"return",
"error",
"r",
"=",
"t",
"=",
"None",
"if",
"isinstance",
"(",
"error",
".",
"instance",
",",
"dict",
")... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | ResourceManager.get_resource_manager | get a resource manager or a given resource type.
assumes the query is for the same underlying cloud provider. | c7n/manager.py | 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:
... | 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:
... | [
"get",
"a",
"resource",
"manager",
"or",
"a",
"given",
"resource",
"type",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/manager.py#L76-L95 | [
"def",
"get_resource_manager",
"(",
"self",
",",
"resource_type",
",",
"data",
"=",
"None",
")",
":",
"if",
"'.'",
"in",
"resource_type",
":",
"provider_name",
",",
"resource_type",
"=",
"resource_type",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"else",
":"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | _eb_env_tags | Augment ElasticBeanstalk Environments with their tags. | c7n/resources/elasticbeanstalk.py | 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,
... | 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,
... | [
"Augment",
"ElasticBeanstalk",
"Environments",
"with",
"their",
"tags",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/elasticbeanstalk.py#L77-L93 | [
"def",
"_eb_env_tags",
"(",
"envs",
",",
"session_factory",
",",
"retry",
")",
":",
"client",
"=",
"local_session",
"(",
"session_factory",
")",
".",
"client",
"(",
"'elasticbeanstalk'",
")",
"def",
"process_tags",
"(",
"eb_env",
")",
":",
"try",
":",
"eb_en... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | assemble_bucket | Assemble a document representing all the config state around a bucket.
TODO: Refactor this, the logic here feels quite muddled. | c7n/resources/s3.py | 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 = ... | 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 = ... | [
"Assemble",
"a",
"document",
"representing",
"all",
"the",
"config",
"state",
"around",
"a",
"bucket",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/s3.py#L406-L473 | [
"def",
"assemble_bucket",
"(",
"item",
")",
":",
"factory",
",",
"b",
"=",
"item",
"s",
"=",
"factory",
"(",
")",
"c",
"=",
"s",
".",
"client",
"(",
"'s3'",
")",
"# Bucket Location, Current Client Location, Default Location",
"b_location",
"=",
"c_location",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | get_region | 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 | c7n/resources/s3.py | 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
""... | 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
""... | [
"Tries",
"to",
"get",
"the",
"bucket",
"region",
"from",
"Location",
".",
"LocationConstraint"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/s3.py#L531-L546 | [
"def",
"get_region",
"(",
"b",
")",
":",
"remap",
"=",
"{",
"None",
":",
"'us-east-1'",
",",
"'EU'",
":",
"'eu-west-1'",
"}",
"region",
"=",
"b",
".",
"get",
"(",
"'Location'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'LocationConstraint'",
")",
"return... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | SGPermission.expand_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. | c7n/resources/vpc.py | 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.
"... | 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.
"... | [
"Expand",
"each",
"list",
"of",
"cidr",
"prefix",
"list",
"user",
"id",
"group",
"pair",
"by",
"port",
"/",
"protocol",
"as",
"an",
"individual",
"rule",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/vpc.py#L1088-L1110 | [
"def",
"expand_permissions",
"(",
"self",
",",
"permissions",
")",
":",
"for",
"p",
"in",
"permissions",
":",
"np",
"=",
"dict",
"(",
"p",
")",
"values",
"=",
"{",
"}",
"for",
"k",
"in",
"(",
"u'IpRanges'",
",",
"u'Ipv6Ranges'",
",",
"u'PrefixListIds'",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | report | Format a policy's extant records into a report. | c7n/reports/csvout.py | 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,
... | 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,
... | [
"Format",
"a",
"policy",
"s",
"extant",
"records",
"into",
"a",
"report",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/reports/csvout.py#L66-L112 | [
"def",
"report",
"(",
"policies",
",",
"start_date",
",",
"options",
",",
"output_fh",
",",
"raw_output_fh",
"=",
"None",
")",
":",
"regions",
"=",
"set",
"(",
"[",
"p",
".",
"options",
".",
"region",
"for",
"p",
"in",
"policies",
"]",
")",
"policy_nam... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | record_set | Retrieve all s3 records for the given policy output url
From the given start date. | c7n/reports/csvout.py | 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'... | 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'... | [
"Retrieve",
"all",
"s3",
"records",
"for",
"the",
"given",
"policy",
"output",
"url"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/reports/csvout.py#L238-L278 | [
"def",
"record_set",
"(",
"session_factory",
",",
"bucket",
",",
"key_prefix",
",",
"start_date",
",",
"specify_hour",
"=",
"False",
")",
":",
"s3",
"=",
"local_session",
"(",
"session_factory",
")",
".",
"client",
"(",
"'s3'",
")",
"records",
"=",
"[",
"]... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | Formatter.uniq_by_id | Only the first record for each id | c7n/reports/csvout.py | 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 | 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 | [
"Only",
"the",
"first",
"record",
"for",
"each",
"id"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/reports/csvout.py#L192-L201 | [
"def",
"uniq_by_id",
"(",
"self",
",",
"records",
")",
":",
"uniq",
"=",
"[",
"]",
"keys",
"=",
"set",
"(",
")",
"for",
"rec",
"in",
"records",
":",
"rec_id",
"=",
"rec",
"[",
"self",
".",
"_id_field",
"]",
"if",
"rec_id",
"not",
"in",
"keys",
":... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | run | scan org repo status hooks | tools/ops/org-pr-monitor.py | 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... | 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... | [
"scan",
"org",
"repo",
"status",
"hooks"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/ops/org-pr-monitor.py#L143-L201 | [
"def",
"run",
"(",
"organization",
",",
"hook_context",
",",
"github_url",
",",
"github_token",
",",
"verbose",
",",
"metrics",
"=",
"False",
",",
"since",
"=",
"None",
",",
"assume",
"=",
"None",
",",
"region",
"=",
"None",
")",
":",
"logging",
".",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | BaseNotify.expand_variables | expand any variables in the action to_from/cc_from fields. | c7n/actions/notify.py | 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... | 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... | [
"expand",
"any",
"variables",
"in",
"the",
"action",
"to_from",
"/",
"cc_from",
"fields",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/actions/notify.py#L30-L46 | [
"def",
"expand_variables",
"(",
"self",
",",
"message",
")",
":",
"p",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"data",
")",
"if",
"'to_from'",
"in",
"self",
".",
"data",
":",
"to_from",
"=",
"self",
".",
"data",
"[",
"'to_from'",
"]",
".",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | Notify.prepare_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 look at adding
provider as additional disc... | c7n/actions/notify.py | 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... | 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... | [
"Resources",
"preparation",
"for",
"transport",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/actions/notify.py#L191-L208 | [
"def",
"prepare_resources",
"(",
"self",
",",
"resources",
")",
":",
"handler",
"=",
"getattr",
"(",
"self",
",",
"\"prepare_%s\"",
"%",
"(",
"self",
".",
"manager",
".",
"type",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
",",
"None",
")",
"if... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | validate | validate config file | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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)
... | 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)
... | [
"validate",
"config",
"file"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L124-L142 | [
"def",
"validate",
"(",
"config",
")",
":",
"with",
"open",
"(",
"config",
")",
"as",
"fh",
":",
"content",
"=",
"fh",
".",
"read",
"(",
")",
"try",
":",
"data",
"=",
"yaml",
".",
"safe_load",
"(",
"content",
")",
"except",
"Exception",
":",
"log",... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | subscribe | subscribe accounts log groups to target account log group destination | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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... | 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... | [
"subscribe",
"accounts",
"log",
"groups",
"to",
"target",
"account",
"log",
"group",
"destination"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L171-L251 | [
"def",
"subscribe",
"(",
"config",
",",
"accounts",
",",
"region",
",",
"merge",
",",
"debug",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"subscription",
"=",
"config",
".",
"get",
"(",
"'subscription'",
")",
"if",
"subscri... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | run | run export across accounts and log groups specified in config. | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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... | 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... | [
"run",
"export",
"across",
"accounts",
"and",
"log",
"groups",
"specified",
"in",
"config",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L261-L281 | [
"def",
"run",
"(",
"config",
",",
"start",
",",
"end",
",",
"accounts",
",",
"region",
",",
"debug",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"destination",
"=",
"config",
".",
"get",
"(",
"'destination'",
")",
"start",... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | lambdafan | simple decorator that will auto fan out async style in lambda.
outside of lambda, this will invoke synchrously. | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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... | 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... | [
"simple",
"decorator",
"that",
"will",
"auto",
"fan",
"out",
"async",
"style",
"in",
"lambda",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L284-L304 | [
"def",
"lambdafan",
"(",
"func",
")",
":",
"if",
"'AWS_LAMBDA_FUNCTION_NAME'",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"func",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"scaleout",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | filter_group_names | Filter log groups by shell patterns. | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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] | 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",
"shell",
"patterns",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L362-L369 | [
"def",
"filter_group_names",
"(",
"groups",
",",
"patterns",
")",
":",
"group_names",
"=",
"[",
"g",
"[",
"'logGroupName'",
"]",
"for",
"g",
"in",
"groups",
"]",
"matched",
"=",
"set",
"(",
")",
"for",
"p",
"in",
"patterns",
":",
"matched",
".",
"updat... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | filter_creation_date | Filter log groups by their creation date.
Also sets group specific value for start to the minimum
of creation date or start. | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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... | 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",
"by",
"their",
"creation",
"date",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L372-L388 | [
"def",
"filter_creation_date",
"(",
"groups",
",",
"start",
",",
"end",
")",
":",
"results",
"=",
"[",
"]",
"for",
"g",
"in",
"groups",
":",
"created",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"g",
"[",
"'creationTime'",
"]",
"/",
"1000.0",
")",
"if... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | filter_last_write | Filter log groups where the last write was before the start date. | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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_... | 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",
"log",
"groups",
"where",
"the",
"last",
"write",
"was",
"before",
"the",
"start",
"date",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L391-L430 | [
"def",
"filter_last_write",
"(",
"client",
",",
"groups",
",",
"start",
")",
":",
"retry",
"=",
"get_retry",
"(",
"(",
"'ThrottlingException'",
",",
")",
")",
"def",
"process_group",
"(",
"group_set",
")",
":",
"matched",
"=",
"[",
"]",
"for",
"g",
"in",... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | filter_extant_exports | Filter days where the bucket already has extant export keys. | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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... | 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... | [
"Filter",
"days",
"where",
"the",
"bucket",
"already",
"has",
"extant",
"export",
"keys",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L433-L451 | [
"def",
"filter_extant_exports",
"(",
"client",
",",
"bucket",
",",
"prefix",
",",
"days",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"end",
"=",
"end",
"or",
"datetime",
".",
"now",
"(",
")",
"# days = [start + timedelta(i) for i in range((end-start).days)... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | access | Check iam permissions for log export access in each account | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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 =... | 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 =... | [
"Check",
"iam",
"permissions",
"for",
"log",
"export",
"access",
"in",
"each",
"account"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L458-L492 | [
"def",
"access",
"(",
"config",
",",
"region",
",",
"accounts",
"=",
"(",
")",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"accounts_report",
"=",
"[",
"]",
"def",
"check_access",
"(",
"account",
")",
":",
"accounts_report",... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | size | size of exported records for a given day. | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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):
... | 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):
... | [
"size",
"of",
"exported",
"records",
"for",
"a",
"given",
"day",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L514-L563 | [
"def",
"size",
"(",
"config",
",",
"accounts",
"=",
"(",
")",
",",
"day",
"=",
"None",
",",
"group",
"=",
"None",
",",
"human",
"=",
"True",
",",
"region",
"=",
"None",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"de... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | sync | sync last recorded export to actual
Use --dryrun to check status. | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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', (... | 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', (... | [
"sync",
"last",
"recorded",
"export",
"to",
"actual"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L572-L659 | [
"def",
"sync",
"(",
"config",
",",
"group",
",",
"accounts",
"=",
"(",
")",
",",
"dryrun",
"=",
"False",
",",
"region",
"=",
"None",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"destination",
"=",
"config",
".",
"get",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | status | report current export state status | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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... | 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... | [
"report",
"current",
"export",
"state",
"status"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L667-L706 | [
"def",
"status",
"(",
"config",
",",
"group",
",",
"accounts",
"=",
"(",
")",
",",
"region",
"=",
"None",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"destination",
"=",
"config",
".",
"get",
"(",
"'destination'",
")",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | get_exports | Find exports for a given account | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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... | 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... | [
"Find",
"exports",
"for",
"a",
"given",
"account"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L709-L762 | [
"def",
"get_exports",
"(",
"client",
",",
"bucket",
",",
"prefix",
",",
"latest",
"=",
"True",
")",
":",
"keys",
"=",
"client",
".",
"list_objects_v2",
"(",
"Bucket",
"=",
"bucket",
",",
"Prefix",
"=",
"prefix",
",",
"Delimiter",
"=",
"'/'",
")",
".",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | export | export a given log group to s3 | tools/c7n_logexporter/c7n_logexporter/exporter.py | 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... | 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... | [
"export",
"a",
"given",
"log",
"group",
"to",
"s3"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L777-L910 | [
"def",
"export",
"(",
"group",
",",
"bucket",
",",
"prefix",
",",
"start",
",",
"end",
",",
"role",
",",
"poll_period",
"=",
"120",
",",
"session",
"=",
"None",
",",
"name",
"=",
"\"\"",
",",
"region",
"=",
"None",
")",
":",
"start",
"=",
"start",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | init | Lambda globals cache. | tools/c7n_sentry/c7n_sentry/c7nsentry.py | 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') | 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') | [
"Lambda",
"globals",
"cache",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_sentry/c7n_sentry/c7nsentry.py#L84-L94 | [
"def",
"init",
"(",
")",
":",
"global",
"sqs",
",",
"logs",
",",
"config",
"if",
"config",
"is",
"None",
":",
"with",
"open",
"(",
"'config.json'",
")",
"as",
"fh",
":",
"config",
"=",
"json",
".",
"load",
"(",
"fh",
")",
"if",
"sqs",
"is",
"None... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | process_log_event | Lambda Entrypoint - Log Subscriber
Format log events and relay to sentry (direct or sqs) | tools/c7n_sentry/c7n_sentry/c7nsentry.py | 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)... | 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",
"Entrypoint",
"-",
"Log",
"Subscriber"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_sentry/c7n_sentry/c7nsentry.py#L97-L116 | [
"def",
"process_log_event",
"(",
"event",
",",
"context",
")",
":",
"init",
"(",
")",
"# Grab the actual error log payload",
"serialized",
"=",
"event",
"[",
"'awslogs'",
"]",
".",
"pop",
"(",
"'data'",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"zlib",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | process_log_group | CLI - Replay / Index | tools/c7n_sentry/c7n_sentry/c7nsentry.py | 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,
... | 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,
... | [
"CLI",
"-",
"Replay",
"/",
"Index"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_sentry/c7n_sentry/c7nsentry.py#L125-L169 | [
"def",
"process_log_group",
"(",
"config",
")",
":",
"from",
"c7n",
".",
"credentials",
"import",
"SessionFactory",
"factory",
"=",
"SessionFactory",
"(",
"config",
".",
"region",
",",
"config",
".",
"profile",
",",
"assume_role",
"=",
"config",
".",
"role",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | parse_traceback | Extract a sentry traceback structure,
From a python formatted traceback string per python stdlib
traceback.print_exc() | tools/c7n_sentry/c7n_sentry/c7nsentry.py | 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... | 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... | [
"Extract",
"a",
"sentry",
"traceback",
"structure"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_sentry/c7n_sentry/c7nsentry.py#L280-L319 | [
"def",
"parse_traceback",
"(",
"msg",
",",
"site_path",
"=",
"\"site-packages\"",
",",
"in_app_prefix",
"=",
"\"c7n\"",
")",
":",
"data",
"=",
"{",
"}",
"lines",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"msg",
".",
"split",
"(",
"'\\n'",
")",
")",... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | get_function | Lambda function provisioning.
Self contained within the component, to allow for easier reuse. | tools/c7n_sentry/c7n_sentry/c7nsentry.py | 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.
... | 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.
... | [
"Lambda",
"function",
"provisioning",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_sentry/c7n_sentry/c7nsentry.py#L322-L361 | [
"def",
"get_function",
"(",
"session_factory",
",",
"name",
",",
"handler",
",",
"runtime",
",",
"role",
",",
"log_groups",
",",
"project",
",",
"account_name",
",",
"account_id",
",",
"sentry_dsn",
",",
"pattern",
"=",
"\"Traceback\"",
")",
":",
"# Lazy impor... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | chunks | Break an iterable into lists of size | tools/sandbox/zerodark/zerodark/ipdb.py | 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 | 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 | [
"Break",
"an",
"iterable",
"into",
"lists",
"of",
"size"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/zerodark/zerodark/ipdb.py#L527-L536 | [
"def",
"chunks",
"(",
"iterable",
",",
"size",
"=",
"50",
")",
":",
"batch",
"=",
"[",
"]",
"for",
"n",
"in",
"iterable",
":",
"batch",
".",
"append",
"(",
"n",
")",
"if",
"len",
"(",
"batch",
")",
"%",
"size",
"==",
"0",
":",
"yield",
"batch",... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | worker_config | daemon queue worker for config notifications | tools/sandbox/zerodark/zerodark/ipdb.py | 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... | 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... | [
"daemon",
"queue",
"worker",
"for",
"config",
"notifications"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/zerodark/zerodark/ipdb.py#L566-L587 | [
"def",
"worker_config",
"(",
"queue",
",",
"s3_key",
",",
"period",
",",
"verbose",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"(",
"verbose",
"and",
"logging",
".",
"DEBUG",
"or",
"logging",
".",
"INFO",
")",
")",
"logging",
".",
"get... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | list_app_resources | Analyze flow log records for application and generate metrics per period | tools/sandbox/zerodark/zerodark/ipdb.py | 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... | 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... | [
"Analyze",
"flow",
"log",
"records",
"for",
"application",
"and",
"generate",
"metrics",
"per",
"period"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/zerodark/zerodark/ipdb.py#L617-L628 | [
"def",
"list_app_resources",
"(",
"app",
",",
"env",
",",
"resources",
",",
"cmdb",
",",
"start",
",",
"end",
",",
"tz",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
")",
"start",
",",
"end",
"=",
"get_dates",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | load_resources | load resources into resource database. | tools/sandbox/zerodark/zerodark/ipdb.py | 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... | 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",
"resources",
"into",
"resource",
"database",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/zerodark/zerodark/ipdb.py#L646-L702 | [
"def",
"load_resources",
"(",
"bucket",
",",
"prefix",
",",
"region",
",",
"account_config",
",",
"accounts",
",",
"assume",
",",
"start",
",",
"end",
",",
"resources",
",",
"store",
",",
"db",
",",
"verbose",
",",
"debug",
")",
":",
"logging",
".",
"b... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | PluginRegistry.load_plugins | Load external plugins.
Custodian is intended to interact with internal and external systems
that are not suitable for embedding into the custodian code base. | c7n/registry.py | 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:
... | 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:
... | [
"Load",
"external",
"plugins",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/registry.py#L106-L118 | [
"def",
"load_plugins",
"(",
"self",
")",
":",
"try",
":",
"from",
"pkg_resources",
"import",
"iter_entry_points",
"except",
"ImportError",
":",
"return",
"for",
"ep",
"in",
"iter_entry_points",
"(",
"group",
"=",
"\"custodian.%s\"",
"%",
"self",
".",
"plugin_typ... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | SQSExecutor.submit | Submit a function for serialized execution on sqs | c7n/sqsexec.py | 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={
... | 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={
... | [
"Submit",
"a",
"function",
"for",
"serialized",
"execution",
"on",
"sqs"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/sqsexec.py#L56-L78 | [
"def",
"submit",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"op_sequence",
"+=",
"1",
"self",
".",
"sqs",
".",
"send_message",
"(",
"QueueUrl",
"=",
"self",
".",
"map_queue",
",",
"MessageBody",
"=",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | SQSExecutor.gather | Fetch results from separate queue | c7n/sqsexec.py | 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... | 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... | [
"Fetch",
"results",
"from",
"separate",
"queue"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/sqsexec.py#L80-L95 | [
"def",
"gather",
"(",
"self",
")",
":",
"limit",
"=",
"self",
".",
"op_sequence",
"-",
"self",
".",
"op_sequence_start",
"results",
"=",
"MessageIterator",
"(",
"self",
".",
"sqs",
",",
"self",
".",
"reduce_queue",
",",
"limit",
")",
"for",
"m",
"in",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | ecs_tag_normalize | normalize tag format on ecs resources to match common aws format. | c7n/resources/ecs.py | 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') | 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') | [
"normalize",
"tag",
"format",
"on",
"ecs",
"resources",
"to",
"match",
"common",
"aws",
"format",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/ecs.py#L28-L33 | [
"def",
"ecs_tag_normalize",
"(",
"resources",
")",
":",
"for",
"r",
"in",
"resources",
":",
"if",
"'tags'",
"in",
"r",
":",
"r",
"[",
"'Tags'",
"]",
"=",
"[",
"{",
"'Key'",
":",
"t",
"[",
"'key'",
"]",
",",
"'Value'",
":",
"t",
"[",
"'value'",
"]... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | ECSClusterResourceDescribeSource.get_resources | 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 | c7n/resources/ecs.py | 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:
... | 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:
... | [
"Retrieve",
"ecs",
"resources",
"for",
"serverless",
"policies",
"or",
"related",
"resources"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/ecs.py#L97-L116 | [
"def",
"get_resources",
"(",
"self",
",",
"ids",
",",
"cache",
"=",
"True",
")",
":",
"cluster_resources",
"=",
"{",
"}",
"for",
"i",
"in",
"ids",
":",
"_",
",",
"ident",
"=",
"i",
".",
"rsplit",
"(",
"':'",
",",
"1",
")",
"parts",
"=",
"ident",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | PolicyCollection.resource_types | resource types used by the collection. | c7n/policy.py | def resource_types(self):
"""resource types used by the collection."""
rtypes = set()
for p in self.policies:
rtypes.add(p.resource_type)
return rtypes | def resource_types(self):
"""resource types used by the collection."""
rtypes = set()
for p in self.policies:
rtypes.add(p.resource_type)
return rtypes | [
"resource",
"types",
"used",
"by",
"the",
"collection",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L118-L123 | [
"def",
"resource_types",
"(",
"self",
")",
":",
"rtypes",
"=",
"set",
"(",
")",
"for",
"p",
"in",
"self",
".",
"policies",
":",
"rtypes",
".",
"add",
"(",
"p",
".",
"resource_type",
")",
"return",
"rtypes"
] | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | PolicyExecutionMode.get_metrics | Retrieve any associated metrics for the policy. | c7n/policy.py | 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)
#... | 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)
#... | [
"Retrieve",
"any",
"associated",
"metrics",
"for",
"the",
"policy",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L153-L190 | [
"def",
"get_metrics",
"(",
"self",
",",
"start",
",",
"end",
",",
"period",
")",
":",
"values",
"=",
"{",
"}",
"default_dimensions",
"=",
"{",
"'Policy'",
":",
"self",
".",
"policy",
".",
"name",
",",
"'ResType'",
":",
"self",
".",
"policy",
".",
"re... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | LambdaMode.run | 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... | c7n/policy.py | 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... | 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... | [
"Run",
"policy",
"in",
"push",
"mode",
"against",
"given",
"event",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L426-L481 | [
"def",
"run",
"(",
"self",
",",
"event",
",",
"lambda_context",
")",
":",
"from",
"c7n",
".",
"actions",
"import",
"EventAction",
"mode",
"=",
"self",
".",
"policy",
".",
"data",
".",
"get",
"(",
"'mode'",
",",
"{",
"}",
")",
"if",
"not",
"bool",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | Policy.get_variables | Get runtime variables for policy interpolation.
Runtime variables are merged with the passed in variables
if any. | c7n/policy.py | 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... | 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... | [
"Get",
"runtime",
"variables",
"for",
"policy",
"interpolation",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L836-L880 | [
"def",
"get_variables",
"(",
"self",
",",
"variables",
"=",
"None",
")",
":",
"# 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/cl... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | Policy.expand_variables | Expand variables in policy data.
Updates the policy data in-place. | c7n/policy.py | 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... | 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... | [
"Expand",
"variables",
"in",
"policy",
"data",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L882-L906 | [
"def",
"expand_variables",
"(",
"self",
",",
"variables",
")",
":",
"# format string values returns a copy",
"updated",
"=",
"utils",
".",
"format_string_values",
"(",
"self",
".",
"data",
",",
"*",
"*",
"variables",
")",
"# Several keys should only be expanded at runti... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | Policy.get_permissions | get permissions needed by this policy | c7n/policy.py | 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... | 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... | [
"get",
"permissions",
"needed",
"by",
"this",
"policy"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L930-L938 | [
"def",
"get_permissions",
"(",
"self",
")",
":",
"permissions",
"=",
"set",
"(",
")",
"permissions",
".",
"update",
"(",
"self",
".",
"resource_manager",
".",
"get_permissions",
"(",
")",
")",
"for",
"f",
"in",
"self",
".",
"resource_manager",
".",
"filter... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | ErrorHandler.extract_bad_snapshot | Handle various client side errors when describing snapshots | c7n/resources/ebs.py | 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... | 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... | [
"Handle",
"various",
"client",
"side",
"errors",
"when",
"describing",
"snapshots"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/ebs.py#L116-L127 | [
"def",
"extract_bad_snapshot",
"(",
"e",
")",
":",
"msg",
"=",
"e",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Message'",
"]",
"error",
"=",
"e",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Code'",
"]",
"e_snap_id",
"=",
"None",
"if",
"error",
"==... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | assumed_session | 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... | c7n/credentials.py | 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... | 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... | [
"STS",
"Role",
"assume",
"a",
"boto3",
".",
"Session"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/credentials.py#L73-L125 | [
"def",
"assumed_session",
"(",
"role_arn",
",",
"session_name",
",",
"session",
"=",
"None",
",",
"region",
"=",
"None",
",",
"external_id",
"=",
"None",
")",
":",
"if",
"session",
"is",
"None",
":",
"session",
"=",
"Session",
"(",
")",
"retry",
"=",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | Time.process_resource_schedule | Does the resource tag schedule and policy match the current time. | c7n/filters/offhours.py | 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.
... | 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.
... | [
"Does",
"the",
"resource",
"tag",
"schedule",
"and",
"policy",
"match",
"the",
"current",
"time",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/offhours.py#L398-L438 | [
"def",
"process_resource_schedule",
"(",
"self",
",",
"i",
",",
"value",
",",
"time_type",
")",
":",
"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... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | Time.get_tag_value | Get the resource's tag value specifying its schedule. | c7n/filters/offhours.py | 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
... | 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
... | [
"Get",
"the",
"resource",
"s",
"tag",
"value",
"specifying",
"its",
"schedule",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/offhours.py#L448-L463 | [
"def",
"get_tag_value",
"(",
"self",
",",
"i",
")",
":",
"# Look for the tag, Normalize tag key and tag value",
"found",
"=",
"False",
"for",
"t",
"in",
"i",
".",
"get",
"(",
"'Tags'",
",",
"(",
")",
")",
":",
"if",
"t",
"[",
"'Key'",
"]",
".",
"lower",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | ScheduleParser.raw_data | convert the tag to a dictionary, taking values as is
This method name and purpose are opaque... and not true. | c7n/filters/offhours.py | 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
... | 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
... | [
"convert",
"the",
"tag",
"to",
"a",
"dictionary",
"taking",
"values",
"as",
"is"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/offhours.py#L577-L594 | [
"def",
"raw_data",
"(",
"tag_value",
")",
":",
"data",
"=",
"{",
"}",
"pieces",
"=",
"[",
"]",
"for",
"p",
"in",
"tag_value",
".",
"split",
"(",
"' '",
")",
":",
"pieces",
".",
"extend",
"(",
"p",
".",
"split",
"(",
"';'",
")",
")",
"# parse comp... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | ScheduleParser.keys_are_valid | test that provided tag keys are valid | c7n/filters/offhours.py | 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 | 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 | [
"test",
"that",
"provided",
"tag",
"keys",
"are",
"valid"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/offhours.py#L596-L601 | [
"def",
"keys_are_valid",
"(",
"self",
",",
"tag_value",
")",
":",
"for",
"key",
"in",
"ScheduleParser",
".",
"raw_data",
"(",
"tag_value",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'on'",
",",
"'off'",
",",
"'tz'",
")",
":",
"return",
"False",
"return"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | resources_gc_prefix | 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. | tools/ops/mugc.py | 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 = ... | 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 = ... | [
"Garbage",
"collect",
"old",
"custodian",
"policies",
"based",
"on",
"prefix",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/ops/mugc.py#L113-L129 | [
"def",
"resources_gc_prefix",
"(",
"options",
",",
"policy_config",
",",
"policy_collection",
")",
":",
"# Classify policies by region",
"policy_regions",
"=",
"{",
"}",
"for",
"p",
"in",
"policy_collection",
":",
"if",
"p",
".",
"execution_mode",
"==",
"'poll'",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | get_session | Get a boto3 sesssion potentially cross account sts assumed
assumed sessions are automatically refreshed. | tools/c7n_salactus/c7n_salactus/worker.py | 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... | 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... | [
"Get",
"a",
"boto3",
"sesssion",
"potentially",
"cross",
"account",
"sts",
"assumed"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L136-L149 | [
"def",
"get_session",
"(",
"account_info",
")",
":",
"s",
"=",
"getattr",
"(",
"CONN_CACHE",
",",
"'%s-session'",
"%",
"account_info",
"[",
"'name'",
"]",
",",
"None",
")",
"if",
"s",
"is",
"not",
"None",
":",
"return",
"s",
"if",
"account_info",
".",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | bulk_invoke | Bulk invoke a function via queues
Uses internal implementation details of rq. | tools/c7n_salactus/c7n_salactus/worker.py | 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 ... | 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 ... | [
"Bulk",
"invoke",
"a",
"function",
"via",
"queues"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L160-L193 | [
"def",
"bulk_invoke",
"(",
"func",
",",
"args",
",",
"nargs",
")",
":",
"# for comparison, simplest thing that works",
"# for i in nargs:",
"# argv = list(args)",
"# argv.append(i)",
"# func.delay(*argv)",
"# some variances between cpy and pypy, sniff detect",
"for",
"clos... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | bucket_ops | Context manager for dealing with s3 errors in one place
bid: bucket_id in form of account_name:bucket_name | tools/c7n_salactus/c7n_salactus/worker.py | 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",
... | 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",
... | [
"Context",
"manager",
"for",
"dealing",
"with",
"s3",
"errors",
"in",
"one",
"place"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L197-L225 | [
"def",
"bucket_ops",
"(",
"bid",
",",
"api",
"=",
"\"\"",
")",
":",
"try",
":",
"yield",
"42",
"except",
"ClientError",
"as",
"e",
":",
"code",
"=",
"e",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Code'",
"]",
"log",
".",
"info",
"(",
"\"bucket e... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | page_strip | Remove bits in content results to minimize memory utilization.
TODO: evolve this to a key filter on metadata, like date | tools/c7n_salactus/c7n_salactus/worker.py | 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'
... | 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'
... | [
"Remove",
"bits",
"in",
"content",
"results",
"to",
"minimize",
"memory",
"utilization",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L228-L262 | [
"def",
"page_strip",
"(",
"page",
",",
"versioned",
")",
":",
"# page strip filtering should be conditional",
"page",
".",
"pop",
"(",
"'ResponseMetadata'",
",",
"None",
")",
"contents_key",
"=",
"versioned",
"and",
"'Versions'",
"or",
"'Contents'",
"contents",
"=",... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | process_account | Scan all buckets in an account and schedule processing | tools/c7n_salactus/c7n_salactus/worker.py | 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.... | 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.... | [
"Scan",
"all",
"buckets",
"in",
"an",
"account",
"and",
"schedule",
"processing"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L287-L314 | [
"def",
"process_account",
"(",
"account_info",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'salactus.bucket-iterator'",
")",
"log",
".",
"info",
"(",
"\"processing account %s\"",
",",
"account_info",
")",
"session",
"=",
"get_session",
"(",
"account_i... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | process_bucket_set | Process a collection of buckets.
For each bucket fetch location, versioning and size and
then kickoff processing strategy based on size. | tools/c7n_salactus/c7n_salactus/worker.py | 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",... | 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",... | [
"Process",
"a",
"collection",
"of",
"buckets",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L318-L385 | [
"def",
"process_bucket_set",
"(",
"account_info",
",",
"buckets",
")",
":",
"region_clients",
"=",
"{",
"}",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'salactus.bucket-set'",
")",
"log",
".",
"info",
"(",
"\"processing account %s\"",
",",
"account_info",
")... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | dispatch_object_source | Select and dispatch an object source for a bucket.
Choices are bucket partition, inventory, or direct pagination. | tools/c7n_salactus/c7n_salactus/worker.py | 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... | 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... | [
"Select",
"and",
"dispatch",
"an",
"object",
"source",
"for",
"a",
"bucket",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L388-L410 | [
"def",
"dispatch_object_source",
"(",
"client",
",",
"account_info",
",",
"bid",
",",
"bucket_info",
")",
":",
"if",
"(",
"account_info",
".",
"get",
"(",
"'inventory'",
")",
"and",
"bucket_info",
"[",
"'keycount'",
"]",
">",
"account_info",
"[",
"'inventory'"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | get_keys_charset | Use set of keys as selector for character superset
Note this isn't optimal, its probabilistic on the keyset char population. | tools/c7n_salactus/c7n_salactus/worker.py | 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
... | 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
... | [
"Use",
"set",
"of",
"keys",
"as",
"selector",
"for",
"character",
"superset"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L507-L544 | [
"def",
"get_keys_charset",
"(",
"keys",
",",
"bid",
")",
":",
"# use the keys found to sample possible chars",
"chars",
"=",
"set",
"(",
")",
"for",
"k",
"in",
"keys",
":",
"chars",
".",
"update",
"(",
"k",
"[",
":",
"4",
"]",
")",
"remainder",
"=",
"cha... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | detect_partition_strategy | Try to detect the best partitioning strategy for a large bucket
Consider nested buckets with common prefixes, and flat buckets. | tools/c7n_salactus/c7n_salactus/worker.py | 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... | 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... | [
"Try",
"to",
"detect",
"the",
"best",
"partitioning",
"strategy",
"for",
"a",
"large",
"bucket"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L547-L608 | [
"def",
"detect_partition_strategy",
"(",
"bid",
",",
"delimiters",
"=",
"(",
"'/'",
",",
"'-'",
")",
",",
"prefix",
"=",
"''",
")",
":",
"account",
",",
"bucket",
"=",
"bid",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"region",
"=",
"connection",
"."... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | process_bucket_partitions | Split up a bucket keyspace into smaller sets for parallel iteration. | tools/c7n_salactus/c7n_salactus/worker.py | 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... | 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... | [
"Split",
"up",
"a",
"bucket",
"keyspace",
"into",
"smaller",
"sets",
"for",
"parallel",
"iteration",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L613-L703 | [
"def",
"process_bucket_partitions",
"(",
"bid",
",",
"prefix_set",
"=",
"(",
"''",
",",
")",
",",
"partition",
"=",
"'/'",
",",
"strategy",
"=",
"None",
",",
"limit",
"=",
"4",
")",
":",
"if",
"strategy",
"is",
"None",
":",
"return",
"detect_partition_st... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | process_bucket_inventory | Load last inventory dump and feed as key source. | tools/c7n_salactus/c7n_salactus/worker.py | 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... | 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... | [
"Load",
"last",
"inventory",
"dump",
"and",
"feed",
"as",
"key",
"source",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L708-L735 | [
"def",
"process_bucket_inventory",
"(",
"bid",
",",
"inventory_bucket",
",",
"inventory_prefix",
")",
":",
"log",
".",
"info",
"(",
"\"Loading bucket %s keys from inventory s3://%s/%s\"",
",",
"bid",
",",
"inventory_bucket",
",",
"inventory_prefix",
")",
"account",
",",... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | process_bucket_iterator | Bucket pagination | tools/c7n_salactus/c7n_salactus/worker.py | 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... | 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... | [
"Bucket",
"pagination"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L740-L785 | [
"def",
"process_bucket_iterator",
"(",
"bid",
",",
"prefix",
"=",
"\"\"",
",",
"delimiter",
"=",
"\"\"",
",",
"*",
"*",
"continuation",
")",
":",
"log",
".",
"info",
"(",
"\"Iterating keys bucket %s prefix %s delimiter %s\"",
",",
"bid",
",",
"prefix",
",",
"d... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | universal_retry | 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... | c7n/tags.py | 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... | 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... | [
"Retry",
"support",
"for",
"resourcegroup",
"tagging",
"apis",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/tags.py#L1094-L1134 | [
"def",
"universal_retry",
"(",
"method",
",",
"ResourceARNList",
",",
"*",
"*",
"kw",
")",
":",
"max_attempts",
"=",
"6",
"for",
"idx",
",",
"delay",
"in",
"enumerate",
"(",
"utils",
".",
"backoff_delays",
"(",
"1.5",
",",
"2",
"**",
"8",
",",
"jitter"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | coalesce_copy_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:
copy_tags (Tags to copy from the resource):
- list of str, e.g. ['... | c7n/tags.py | 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... | 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... | [
"Returns",
"a",
"list",
"of",
"tags",
"from",
"resource",
"and",
"user",
"supplied",
"in",
"the",
"format",
":",
"[",
"{",
"Key",
":",
"key",
"Value",
":",
"value",
"}",
"]"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/tags.py#L1137-L1185 | [
"def",
"coalesce_copy_user_tags",
"(",
"resource",
",",
"copy_tags",
",",
"user_tags",
")",
":",
"assert",
"isinstance",
"(",
"copy_tags",
",",
"bool",
")",
"or",
"isinstance",
"(",
"copy_tags",
",",
"list",
")",
"assert",
"isinstance",
"(",
"user_tags",
",",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | RenameTag.process_rename | Move source tag value to destination tag value
- Collect value from old tag
- Delete old tag
- Create new tag & assign stored value | c7n/tags.py | 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... | 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... | [
"Move",
"source",
"tag",
"value",
"to",
"destination",
"tag",
"value"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/tags.py#L515-L540 | [
"def",
"process_rename",
"(",
"self",
",",
"client",
",",
"tag_value",
",",
"resource_set",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Renaming tag on %s instances\"",
"%",
"(",
"len",
"(",
"resource_set",
")",
")",
")",
"old_key",
"=",
"self",
"."... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | NormalizeTag.process_transform | Transform tag value
- Collect value from tag
- Transform Tag value
- Assign new value for key | c7n/tags.py | 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... | 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... | [
"Transform",
"tag",
"value"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/tags.py#L758-L776 | [
"def",
"process_transform",
"(",
"self",
",",
"tag_value",
",",
"resource_set",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Transforming tag value on %s instances\"",
"%",
"(",
"len",
"(",
"resource_set",
")",
")",
")",
"key",
"=",
"self",
".",
"data"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | CopyRelatedResourceTag.get_resource_tag_map | Returns a mapping of {resource_id: {tagkey: tagvalue}} | c7n/tags.py | 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_... | 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_... | [
"Returns",
"a",
"mapping",
"of",
"{",
"resource_id",
":",
"{",
"tagkey",
":",
"tagvalue",
"}}"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/tags.py#L1071-L1081 | [
"def",
"get_resource_tag_map",
"(",
"self",
",",
"r_type",
",",
"ids",
")",
":",
"manager",
"=",
"self",
".",
"manager",
".",
"get_resource_manager",
"(",
"r_type",
")",
"r_id",
"=",
"manager",
".",
"resource_type",
".",
"id",
"# TODO only fetch resource with th... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | LaunchInfo.get_launch_configs | Return a mapping of launch configs for the given set of asgs | c7n/resources/asg.py | 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_... | 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_... | [
"Return",
"a",
"mapping",
"of",
"launch",
"configs",
"for",
"the",
"given",
"set",
"of",
"asgs"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/asg.py#L103-L119 | [
"def",
"get_launch_configs",
"(",
"self",
",",
"asgs",
")",
":",
"config_names",
"=",
"set",
"(",
")",
"for",
"a",
"in",
"asgs",
":",
"if",
"'LaunchConfigurationName'",
"not",
"in",
"a",
":",
"continue",
"config_names",
".",
"add",
"(",
"a",
"[",
"'Launc... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | DescribeAppElb.get_resources | Support server side filtering on arns or names | c7n/resources/appelb.py | 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) | 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) | [
"Support",
"server",
"side",
"filtering",
"on",
"arns",
"or",
"names"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/appelb.py#L81-L88 | [
"def",
"get_resources",
"(",
"self",
",",
"ids",
",",
"cache",
"=",
"True",
")",
":",
"if",
"ids",
"[",
"0",
"]",
".",
"startswith",
"(",
"'arn:'",
")",
":",
"params",
"=",
"{",
"'LoadBalancerArns'",
":",
"ids",
"}",
"else",
":",
"params",
"=",
"{"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | validate | Validate a configuration file. | tools/c7n_salactus/c7n_salactus/cli.py | def validate(config):
"""Validate a configuration file."""
with open(config) as fh:
data = utils.yaml_load(fh.read())
jsonschema.validate(data, CONFIG_SCHEMA) | def validate(config):
"""Validate a configuration file."""
with open(config) as fh:
data = utils.yaml_load(fh.read())
jsonschema.validate(data, CONFIG_SCHEMA) | [
"Validate",
"a",
"configuration",
"file",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L168-L172 | [
"def",
"validate",
"(",
"config",
")",
":",
"with",
"open",
"(",
"config",
")",
"as",
"fh",
":",
"data",
"=",
"utils",
".",
"yaml_load",
"(",
"fh",
".",
"read",
"(",
")",
")",
"jsonschema",
".",
"validate",
"(",
"data",
",",
"CONFIG_SCHEMA",
")"
] | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | run | Run across a set of accounts and buckets. | tools/c7n_salactus/c7n_salactus/cli.py | 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)
... | 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)
... | [
"Run",
"across",
"a",
"set",
"of",
"accounts",
"and",
"buckets",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L190-L238 | [
"def",
"run",
"(",
"config",
",",
"tag",
",",
"bucket",
",",
"account",
",",
"not_bucket",
",",
"not_account",
",",
"debug",
",",
"region",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"\"%(asc... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | reset | Delete all persistent cluster state. | tools/c7n_salactus/c7n_salactus/cli.py | 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!')
... | 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!')
... | [
"Delete",
"all",
"persistent",
"cluster",
"state",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L253-L265 | [
"def",
"reset",
"(",
"c7n_async",
"=",
"None",
")",
":",
"click",
".",
"echo",
"(",
"'Delete db? Are you Sure? [yn] '",
",",
"nl",
"=",
"False",
")",
"c",
"=",
"click",
".",
"getchar",
"(",
")",
"click",
".",
"echo",
"(",
")",
"if",
"c",
"==",
"'y'",... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | workers | Show information on salactus workers. (slow) | tools/c7n_salactus/c7n_salactus/cli.py | 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)) | 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)) | [
"Show",
"information",
"on",
"salactus",
"workers",
".",
"(",
"slow",
")"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L269-L276 | [
"def",
"workers",
"(",
")",
":",
"counter",
"=",
"Counter",
"(",
")",
"for",
"w",
"in",
"Worker",
".",
"all",
"(",
"connection",
"=",
"worker",
".",
"connection",
")",
":",
"for",
"q",
"in",
"w",
".",
"queues",
":",
"counter",
"[",
"q",
".",
"nam... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | accounts | Report on stats by account | tools/c7n_salactus/c7n_salactus/cli.py | 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... | 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",
"account"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L335-L382 | [
"def",
"accounts",
"(",
"dbpath",
",",
"output",
",",
"format",
",",
"account",
",",
"config",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"tagprefix",
"=",
"None",
",",
"region",
"=",
"(",
")",
",",
"not_region",
"=",
"(",
")",
",",
"not_bucket",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | buckets | Report on stats by bucket | tools/c7n_salactus/c7n_salactus/cli.py | 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... | 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... | [
"Report",
"on",
"stats",
"by",
"bucket"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L470-L528 | [
"def",
"buckets",
"(",
"bucket",
"=",
"None",
",",
"account",
"=",
"None",
",",
"matched",
"=",
"False",
",",
"kdenied",
"=",
"False",
",",
"errors",
"=",
"False",
",",
"dbpath",
"=",
"None",
",",
"size",
"=",
"None",
",",
"denied",
"=",
"False",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | watch | watch scan rates across the cluster | tools/c7n_salactus/c7n_salactus/cli.py | 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... | 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... | [
"watch",
"scan",
"rates",
"across",
"the",
"cluster"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L533-L582 | [
"def",
"watch",
"(",
"limit",
")",
":",
"period",
"=",
"5.0",
"prev",
"=",
"db",
".",
"db",
"(",
")",
"prev_totals",
"=",
"None",
"while",
"True",
":",
"click",
".",
"clear",
"(",
")",
"time",
".",
"sleep",
"(",
"period",
")",
"cur",
"=",
"db",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | inspect_partitions | 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... | tools/c7n_salactus/c7n_salactus/cli.py | 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... | 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... | [
"Discover",
"the",
"partitions",
"on",
"a",
"bucket",
"via",
"introspection",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L587-L641 | [
"def",
"inspect_partitions",
"(",
"bucket",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"\"%(asctime)s: %(name)s:%(levelname)s %(message)s\"",
")",
"logging",
".",
"getLogger",
"(",
"'botocore'",
")",
"."... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | inspect_bucket | Show all information known on a bucket. | tools/c7n_salactus/c7n_salactus/cli.py | 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... | 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",
"all",
"information",
"known",
"on",
"a",
"bucket",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L646-L675 | [
"def",
"inspect_bucket",
"(",
"bucket",
")",
":",
"state",
"=",
"db",
".",
"db",
"(",
")",
"found",
"=",
"None",
"for",
"b",
"in",
"state",
".",
"buckets",
"(",
")",
":",
"if",
"b",
".",
"name",
"==",
"bucket",
":",
"found",
"=",
"b",
"if",
"no... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | inspect_queue | Show contents of a queue. | tools/c7n_salactus/c7n_salactus/cli.py | 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.... | 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.... | [
"Show",
"contents",
"of",
"a",
"queue",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L685-L745 | [
"def",
"inspect_queue",
"(",
"queue",
",",
"state",
",",
"limit",
",",
"bucket",
")",
":",
"if",
"not",
"HAVE_BIN_LIBS",
":",
"click",
".",
"echo",
"(",
"\"missing required binary libs (lz4, msgpack)\"",
")",
"return",
"conn",
"=",
"worker",
".",
"connection",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | queues | Report on progress by queues. | tools/c7n_salactus/c7n_salactus/cli.py | 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... | 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... | [
"Report",
"on",
"progress",
"by",
"queues",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L749-L766 | [
"def",
"queues",
"(",
")",
":",
"conn",
"=",
"worker",
".",
"connection",
"failure_q",
"=",
"None",
"def",
"_repr",
"(",
"q",
")",
":",
"return",
"\"running:%d pending:%d finished:%d\"",
"%",
"(",
"StartedJobRegistry",
"(",
"q",
".",
"name",
",",
"conn",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | failures | Show any unexpected failures | tools/c7n_salactus/c7n_salactus/cli.py | 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... | 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... | [
"Show",
"any",
"unexpected",
"failures"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L770-L782 | [
"def",
"failures",
"(",
")",
":",
"if",
"not",
"HAVE_BIN_LIBS",
":",
"click",
".",
"echo",
"(",
"\"missing required binary libs (lz4, msgpack)\"",
")",
"return",
"q",
"=",
"Queue",
"(",
"'failed'",
",",
"connection",
"=",
"worker",
".",
"connection",
")",
"for... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | main | Generate a c7n-org subscriptions config file | tools/c7n_org/scripts/azuresubs.py | 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... | 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... | [
"Generate",
"a",
"c7n",
"-",
"org",
"subscriptions",
"config",
"file"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_org/scripts/azuresubs.py#L27-L46 | [
"def",
"main",
"(",
"output",
")",
":",
"client",
"=",
"SubscriptionClient",
"(",
"Session",
"(",
")",
".",
"get_credentials",
"(",
")",
")",
"subs",
"=",
"[",
"sub",
".",
"serialize",
"(",
"True",
")",
"for",
"sub",
"in",
"client",
".",
"subscriptions... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | custodian_azure_send_override | Overrides ServiceClient.send() function to implement retries & log headers | tools/c7n_azure/c7n_azure/utils.py | 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)
... | 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)
... | [
"Overrides",
"ServiceClient",
".",
"send",
"()",
"function",
"to",
"implement",
"retries",
"&",
"log",
"headers"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L111-L143 | [
"def",
"custodian_azure_send_override",
"(",
"self",
",",
"request",
",",
"headers",
"=",
"None",
",",
"content",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"retries",
"=",
"0",
"max_retries",
"=",
"3",
"while",
"retries",
"<",
"max_retries",
":",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | GraphHelper.get_principal_dictionary | 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 ... | tools/c7n_azure/c7n_azure/utils.py | 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_... | 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_... | [
"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",
"Azu... | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L200-L237 | [
"def",
"get_principal_dictionary",
"(",
"graph_client",
",",
"object_ids",
",",
"raise_on_graph_call_error",
"=",
"False",
")",
":",
"if",
"not",
"object_ids",
":",
"return",
"{",
"}",
"object_params",
"=",
"GetObjectsParameters",
"(",
"include_directory_object_referenc... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | GraphHelper.get_principal_name | Attempts to resolve a principal name.
:param graph_object: the Azure AD Graph Object
:return: The resolved value or an empty string if unsuccessful. | tools/c7n_azure/c7n_azure/utils.py | 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_... | 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_... | [
"Attempts",
"to",
"resolve",
"a",
"principal",
"name",
".",
":",
"param",
"graph_object",
":",
"the",
"Azure",
"AD",
"Graph",
"Object",
":",
"return",
":",
"The",
"resolved",
"value",
"or",
"an",
"empty",
"string",
"if",
"unsuccessful",
"."
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L240-L251 | [
"def",
"get_principal_name",
"(",
"graph_object",
")",
":",
"if",
"hasattr",
"(",
"graph_object",
",",
"'user_principal_name'",
")",
":",
"return",
"graph_object",
".",
"user_principal_name",
"elif",
"hasattr",
"(",
"graph_object",
",",
"'service_principal_names'",
")... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | PortsRangeHelper._get_port_range | Given a string with a port or port range: '80', '80-120'
Returns tuple with range start and end ports: (80, 80), (80, 120) | tools/c7n_azure/c7n_azure/utils.py | 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('-')... | 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('-')... | [
"Given",
"a",
"string",
"with",
"a",
"port",
"or",
"port",
"range",
":",
"80",
"80",
"-",
"120",
"Returns",
"tuple",
"with",
"range",
"start",
"and",
"end",
"ports",
":",
"(",
"80",
"80",
")",
"(",
"80",
"120",
")"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L259-L270 | [
"def",
"_get_port_range",
"(",
"range_str",
")",
":",
"if",
"range_str",
"==",
"'*'",
":",
"return",
"PortsRangeHelper",
".",
"PortsRange",
"(",
"start",
"=",
"0",
",",
"end",
"=",
"65535",
")",
"s",
"=",
"range_str",
".",
"split",
"(",
"'-'",
")",
"if... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | PortsRangeHelper._get_rule_port_ranges | Extracts ports ranges from the NSG rule object
Returns an array of PortsRange tuples | tools/c7n_azure/c7n_azure/utils.py | 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... | 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... | [
"Extracts",
"ports",
"ranges",
"from",
"the",
"NSG",
"rule",
"object",
"Returns",
"an",
"array",
"of",
"PortsRange",
"tuples"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L280-L289 | [
"def",
"_get_rule_port_ranges",
"(",
"rule",
")",
":",
"properties",
"=",
"rule",
"[",
"'properties'",
"]",
"if",
"'destinationPortRange'",
"in",
"properties",
":",
"return",
"[",
"PortsRangeHelper",
".",
"_get_port_range",
"(",
"properties",
"[",
"'destinationPortR... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | PortsRangeHelper._port_ranges_to_set | Converts array of port ranges to the set of integers
Example: [(10-12), (20,20)] -> {10, 11, 12, 20} | tools/c7n_azure/c7n_azure/utils.py | 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)]) | 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)]) | [
"Converts",
"array",
"of",
"port",
"ranges",
"to",
"the",
"set",
"of",
"integers",
"Example",
":",
"[",
"(",
"10",
"-",
"12",
")",
"(",
"20",
"20",
")",
"]",
"-",
">",
"{",
"10",
"11",
"12",
"20",
"}"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L292-L296 | [
"def",
"_port_ranges_to_set",
"(",
"ranges",
")",
":",
"return",
"set",
"(",
"[",
"i",
"for",
"r",
"in",
"ranges",
"for",
"i",
"in",
"range",
"(",
"r",
".",
"start",
",",
"r",
".",
"end",
"+",
"1",
")",
"]",
")"
] | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | PortsRangeHelper.validate_ports_string | Validate that provided string has proper port numbers:
1. port number < 65535
2. range start < range end | tools/c7n_azure/c7n_azure/utils.py | 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
... | 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
... | [
"Validate",
"that",
"provided",
"string",
"has",
"proper",
"port",
"numbers",
":",
"1",
".",
"port",
"number",
"<",
"65535",
"2",
".",
"range",
"start",
"<",
"range",
"end"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L299-L312 | [
"def",
"validate_ports_string",
"(",
"ports",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'^\\\\d+(-\\\\d+)?(,\\\\d+(-\\\\d+)?)*$'",
")",
"if",
"pattern",
".",
"match",
"(",
"ports",
")",
"is",
"None",
":",
"return",
"False",
"ranges",
"=",
"PortsRan... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | PortsRangeHelper.get_ports_strings_from_list | Transform a list of port numbers to the list of strings with port ranges
Example: [10, 12, 13, 14, 15] -> ['10', '12-15'] | tools/c7n_azure/c7n_azure/utils.py | 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
... | 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
... | [
"Transform",
"a",
"list",
"of",
"port",
"numbers",
"to",
"the",
"list",
"of",
"strings",
"with",
"port",
"ranges",
"Example",
":",
"[",
"10",
"12",
"13",
"14",
"15",
"]",
"-",
">",
"[",
"10",
"12",
"-",
"15",
"]"
] | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L330-L349 | [
"def",
"get_ports_strings_from_list",
"(",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"[",
"]",
"# Transform diff_ports list to the ranges list",
"first",
"=",
"0",
"result",
"=",
"[",
"]",
"for",
"it",
"in",
"range",
"(",
"... | 52ef732eb3d7bc939d1579faf519314814695c08 |
train | PortsRangeHelper.build_ports_dict | 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. | tools/c7n_azure/c7n_azure/utils.py | 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... | 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... | [
"Build",
"entire",
"ports",
"array",
"filled",
"with",
"True",
"(",
"Allow",
")",
"False",
"(",
"Deny",
")",
"and",
"None",
"(",
"default",
"-",
"Deny",
")",
"based",
"on",
"the",
"provided",
"Network",
"Security",
"Group",
"object",
"direction",
"and",
... | cloud-custodian/cloud-custodian | python | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L352-L380 | [
"def",
"build_ports_dict",
"(",
"nsg",
",",
"direction_key",
",",
"ip_protocol",
")",
":",
"rules",
"=",
"nsg",
"[",
"'properties'",
"]",
"[",
"'securityRules'",
"]",
"rules",
"=",
"sorted",
"(",
"rules",
",",
"key",
"=",
"lambda",
"k",
":",
"k",
"[",
... | 52ef732eb3d7bc939d1579faf519314814695c08 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.