repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
cloud-custodian/cloud-custodian | c7n/resources/asg.py | LaunchInfo.get_launch_configs | 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_... | python | 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",
")",
":",
"config_names",
"=",
"set",
"(",
")",
"for",
"a",
"in",
"asgs",
":",
"if",
"'LaunchConfigurationName'",
"not",
"in",
"a",
":",
"continue",
"config_names",
".",
"add",
"(",
"a",
"[",
"'Launc... | Return a mapping of launch configs for the given set of asgs | [
"Return",
"a",
"mapping",
"of",
"launch",
"configs",
"for",
"the",
"given",
"set",
"of",
"asgs"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/asg.py#L103-L119 | train |
cloud-custodian/cloud-custodian | c7n/resources/appelb.py | DescribeAppElb.get_resources | 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) | python | 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",
")",
":",
"if",
"ids",
"[",
"0",
"]",
".",
"startswith",
"(",
"'arn:'",
")",
":",
"params",
"=",
"{",
"'LoadBalancerArns'",
":",
"ids",
"}",
"else",
":",
"params",
"=",
"{"... | Support server side filtering on arns or names | [
"Support",
"server",
"side",
"filtering",
"on",
"arns",
"or",
"names"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/appelb.py#L81-L88 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | validate | def validate(config):
"""Validate a configuration file."""
with open(config) as fh:
data = utils.yaml_load(fh.read())
jsonschema.validate(data, CONFIG_SCHEMA) | python | 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",
")",
":",
"with",
"open",
"(",
"config",
")",
"as",
"fh",
":",
"data",
"=",
"utils",
".",
"yaml_load",
"(",
"fh",
".",
"read",
"(",
")",
")",
"jsonschema",
".",
"validate",
"(",
"data",
",",
"CONFIG_SCHEMA",
")"
] | Validate a configuration file. | [
"Validate",
"a",
"configuration",
"file",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L168-L172 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | run | 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)
... | python | 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",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"\"%(asc... | Run across a set of accounts and buckets. | [
"Run",
"across",
"a",
"set",
"of",
"accounts",
"and",
"buckets",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L190-L238 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | reset | 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!')
... | python | 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",
")",
":",
"click",
".",
"echo",
"(",
"'Delete db? Are you Sure? [yn] '",
",",
"nl",
"=",
"False",
")",
"c",
"=",
"click",
".",
"getchar",
"(",
")",
"click",
".",
"echo",
"(",
")",
"if",
"c",
"==",
"'y'",... | Delete all persistent cluster state. | [
"Delete",
"all",
"persistent",
"cluster",
"state",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L253-L265 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | workers | 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)) | python | 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",
"(",
")",
":",
"counter",
"=",
"Counter",
"(",
")",
"for",
"w",
"in",
"Worker",
".",
"all",
"(",
"connection",
"=",
"worker",
".",
"connection",
")",
":",
"for",
"q",
"in",
"w",
".",
"queues",
":",
"counter",
"[",
"q",
".",
"nam... | Show information on salactus workers. (slow) | [
"Show",
"information",
"on",
"salactus",
"workers",
".",
"(",
"slow",
")"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L269-L276 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | accounts | 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... | python | 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",
"... | Report on stats by account | [
"Report",
"on",
"stats",
"by",
"account"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L335-L382 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | buckets | 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... | python | 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",
"... | Report on stats by bucket | [
"Report",
"on",
"stats",
"by",
"bucket"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L470-L528 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | watch | 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... | python | 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",
")",
":",
"period",
"=",
"5.0",
"prev",
"=",
"db",
".",
"db",
"(",
")",
"prev_totals",
"=",
"None",
"while",
"True",
":",
"click",
".",
"clear",
"(",
")",
"time",
".",
"sleep",
"(",
"period",
")",
"cur",
"=",
"db",
... | watch scan rates across the cluster | [
"watch",
"scan",
"rates",
"across",
"the",
"cluster"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L533-L582 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | inspect_partitions | 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... | python | 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",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"\"%(asctime)s: %(name)s:%(levelname)s %(message)s\"",
")",
"logging",
".",
"getLogger",
"(",
"'botocore'",
")",
"."... | 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... | [
"Discover",
"the",
"partitions",
"on",
"a",
"bucket",
"via",
"introspection",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L587-L641 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | inspect_bucket | def inspect_bucket(bucket):
"""Show all information known on a bucket."""
state = db.db()
found = None
for b in state.buckets():
if b.name == bucket:
found = b
if not found:
click.echo("no bucket named: %s" % bucket)
return
click.echo("Bucket: %s" % found.nam... | python | 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",
")",
":",
"state",
"=",
"db",
".",
"db",
"(",
")",
"found",
"=",
"None",
"for",
"b",
"in",
"state",
".",
"buckets",
"(",
")",
":",
"if",
"b",
".",
"name",
"==",
"bucket",
":",
"found",
"=",
"b",
"if",
"no... | Show all information known on a bucket. | [
"Show",
"all",
"information",
"known",
"on",
"a",
"bucket",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L646-L675 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | inspect_queue | def inspect_queue(queue, state, limit, bucket):
"""Show contents of a queue."""
if not HAVE_BIN_LIBS:
click.echo("missing required binary libs (lz4, msgpack)")
return
conn = worker.connection
def job_row(j):
if isinstance(j.args[0], basestring):
account, bucket = j.... | python | 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",
")",
":",
"if",
"not",
"HAVE_BIN_LIBS",
":",
"click",
".",
"echo",
"(",
"\"missing required binary libs (lz4, msgpack)\"",
")",
"return",
"conn",
"=",
"worker",
".",
"connection",
... | Show contents of a queue. | [
"Show",
"contents",
"of",
"a",
"queue",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L685-L745 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | queues | def queues():
"""Report on progress by queues."""
conn = worker.connection
failure_q = None
def _repr(q):
return "running:%d pending:%d finished:%d" % (
StartedJobRegistry(q.name, conn).count,
q.count,
FinishedJobRegistry(q.name, conn).count)
for q in Que... | python | 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",
"(",
")",
":",
"conn",
"=",
"worker",
".",
"connection",
"failure_q",
"=",
"None",
"def",
"_repr",
"(",
"q",
")",
":",
"return",
"\"running:%d pending:%d finished:%d\"",
"%",
"(",
"StartedJobRegistry",
"(",
"q",
".",
"name",
",",
"conn",
"... | Report on progress by queues. | [
"Report",
"on",
"progress",
"by",
"queues",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L749-L766 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/cli.py | failures | def failures():
"""Show any unexpected failures"""
if not HAVE_BIN_LIBS:
click.echo("missing required binary libs (lz4, msgpack)")
return
q = Queue('failed', connection=worker.connection)
for i in q.get_job_ids():
j = q.job_class.fetch(i, connection=q.connection)
click.e... | python | 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",
"(",
")",
":",
"if",
"not",
"HAVE_BIN_LIBS",
":",
"click",
".",
"echo",
"(",
"\"missing required binary libs (lz4, msgpack)\"",
")",
"return",
"q",
"=",
"Queue",
"(",
"'failed'",
",",
"connection",
"=",
"worker",
".",
"connection",
")",
"for... | Show any unexpected failures | [
"Show",
"any",
"unexpected",
"failures"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/cli.py#L770-L782 | train |
cloud-custodian/cloud-custodian | tools/c7n_org/scripts/azuresubs.py | main | 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... | python | 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",
")",
":",
"client",
"=",
"SubscriptionClient",
"(",
"Session",
"(",
")",
".",
"get_credentials",
"(",
")",
")",
"subs",
"=",
"[",
"sub",
".",
"serialize",
"(",
"True",
")",
"for",
"sub",
"in",
"client",
".",
"subscriptions... | Generate a c7n-org subscriptions config file | [
"Generate",
"a",
"c7n",
"-",
"org",
"subscriptions",
"config",
"file"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_org/scripts/azuresubs.py#L27-L46 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/utils.py | custodian_azure_send_override | 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)
... | python | 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",
")",
":",
"retries",
"=",
"0",
"max_retries",
"=",
"3",
"while",
"retries",
"<",
"max_retries",
":",
"... | Overrides ServiceClient.send() function to implement retries & log headers | [
"Overrides",
"ServiceClient",
".",
"send",
"()",
"function",
"to",
"implement",
"retries",
"&",
"log",
"headers"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L111-L143 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/utils.py | GraphHelper.get_principal_dictionary | 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_... | python | 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",
")",
":",
"if",
"not",
"object_ids",
":",
"return",
"{",
"}",
"object_params",
"=",
"GetObjectsParameters",
"(",
"include_directory_object_referenc... | 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 ... | [
"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... | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L200-L237 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/utils.py | GraphHelper.get_principal_name | 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_... | python | 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",
")",
":",
"if",
"hasattr",
"(",
"graph_object",
",",
"'user_principal_name'",
")",
":",
"return",
"graph_object",
".",
"user_principal_name",
"elif",
"hasattr",
"(",
"graph_object",
",",
"'service_principal_names'",
")... | Attempts to resolve a principal name.
:param graph_object: the Azure AD Graph Object
:return: The resolved value or an empty string if unsuccessful. | [
"Attempts",
"to",
"resolve",
"a",
"principal",
"name",
".",
":",
"param",
"graph_object",
":",
"the",
"Azure",
"AD",
"Graph",
"Object",
":",
"return",
":",
"The",
"resolved",
"value",
"or",
"an",
"empty",
"string",
"if",
"unsuccessful",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L240-L251 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/utils.py | PortsRangeHelper._get_port_range | 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('-')... | python | 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",
")",
":",
"if",
"range_str",
"==",
"'*'",
":",
"return",
"PortsRangeHelper",
".",
"PortsRange",
"(",
"start",
"=",
"0",
",",
"end",
"=",
"65535",
")",
"s",
"=",
"range_str",
".",
"split",
"(",
"'-'",
")",
"if... | Given a string with a port or port range: '80', '80-120'
Returns tuple with range start and end ports: (80, 80), (80, 120) | [
"Given",
"a",
"string",
"with",
"a",
"port",
"or",
"port",
"range",
":",
"80",
"80",
"-",
"120",
"Returns",
"tuple",
"with",
"range",
"start",
"and",
"end",
"ports",
":",
"(",
"80",
"80",
")",
"(",
"80",
"120",
")"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L259-L270 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/utils.py | PortsRangeHelper._get_rule_port_ranges | 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... | python | 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",
")",
":",
"properties",
"=",
"rule",
"[",
"'properties'",
"]",
"if",
"'destinationPortRange'",
"in",
"properties",
":",
"return",
"[",
"PortsRangeHelper",
".",
"_get_port_range",
"(",
"properties",
"[",
"'destinationPortR... | Extracts ports ranges from the NSG rule object
Returns an array of PortsRange tuples | [
"Extracts",
"ports",
"ranges",
"from",
"the",
"NSG",
"rule",
"object",
"Returns",
"an",
"array",
"of",
"PortsRange",
"tuples"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L280-L289 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/utils.py | PortsRangeHelper._port_ranges_to_set | 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)]) | python | 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",
")",
":",
"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} | [
"Converts",
"array",
"of",
"port",
"ranges",
"to",
"the",
"set",
"of",
"integers",
"Example",
":",
"[",
"(",
"10",
"-",
"12",
")",
"(",
"20",
"20",
")",
"]",
"-",
">",
"{",
"10",
"11",
"12",
"20",
"}"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L292-L296 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/utils.py | PortsRangeHelper.validate_ports_string | 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
... | python | 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",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'^\\\\d+(-\\\\d+)?(,\\\\d+(-\\\\d+)?)*$'",
")",
"if",
"pattern",
".",
"match",
"(",
"ports",
")",
"is",
"None",
":",
"return",
"False",
"ranges",
"=",
"PortsRan... | Validate that provided string has proper port numbers:
1. port number < 65535
2. range start < range end | [
"Validate",
"that",
"provided",
"string",
"has",
"proper",
"port",
"numbers",
":",
"1",
".",
"port",
"number",
"<",
"65535",
"2",
".",
"range",
"start",
"<",
"range",
"end"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L299-L312 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/utils.py | PortsRangeHelper.get_ports_strings_from_list | 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
... | python | 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",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"[",
"]",
"# Transform diff_ports list to the ranges list",
"first",
"=",
"0",
"result",
"=",
"[",
"]",
"for",
"it",
"in",
"range",
"(",
"... | Transform a list of port numbers to the list of strings with port ranges
Example: [10, 12, 13, 14, 15] -> ['10', '12-15'] | [
"Transform",
"a",
"list",
"of",
"port",
"numbers",
"to",
"the",
"list",
"of",
"strings",
"with",
"port",
"ranges",
"Example",
":",
"[",
"10",
"12",
"13",
"14",
"15",
"]",
"-",
">",
"[",
"10",
"12",
"-",
"15",
"]"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L330-L349 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/utils.py | PortsRangeHelper.build_ports_dict | 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... | python | 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",
")",
":",
"rules",
"=",
"nsg",
"[",
"'properties'",
"]",
"[",
"'securityRules'",
"]",
"rules",
"=",
"sorted",
"(",
"rules",
",",
"key",
"=",
"lambda",
"k",
":",
"k",
"[",
... | 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. | [
"Build",
"entire",
"ports",
"array",
"filled",
"with",
"True",
"(",
"Allow",
")",
"False",
"(",
"Deny",
")",
"and",
"None",
"(",
"default",
"-",
"Deny",
")",
"based",
"on",
"the",
"provided",
"Network",
"Security",
"Group",
"object",
"direction",
"and",
... | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/utils.py#L352-L380 | train |
cloud-custodian/cloud-custodian | tools/c7n_gcp/c7n_gcp/actions/cscc.py | PostFinding.get_name | def get_name(self, r):
"""Given an arbitrary resource attempt to resolve back to a qualified name."""
namer = ResourceNameAdapters[self.manager.resource_type.service]
return namer(r) | python | def get_name(self, r):
"""Given an arbitrary resource attempt to resolve back to a qualified name."""
namer = ResourceNameAdapters[self.manager.resource_type.service]
return namer(r) | [
"def",
"get_name",
"(",
"self",
",",
"r",
")",
":",
"namer",
"=",
"ResourceNameAdapters",
"[",
"self",
".",
"manager",
".",
"resource_type",
".",
"service",
"]",
"return",
"namer",
"(",
"r",
")"
] | Given an arbitrary resource attempt to resolve back to a qualified name. | [
"Given",
"an",
"arbitrary",
"resource",
"attempt",
"to",
"resolve",
"back",
"to",
"a",
"qualified",
"name",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_gcp/c7n_gcp/actions/cscc.py#L137-L140 | train |
cloud-custodian/cloud-custodian | tools/dev/license-headers.py | update_headers | def update_headers(src_tree):
"""Main."""
print("src tree", src_tree)
for root, dirs, files in os.walk(src_tree):
py_files = fnmatch.filter(files, "*.py")
for f in py_files:
print("checking", f)
p = os.path.join(root, f)
with open(p) as fh:
... | python | def update_headers(src_tree):
"""Main."""
print("src tree", src_tree)
for root, dirs, files in os.walk(src_tree):
py_files = fnmatch.filter(files, "*.py")
for f in py_files:
print("checking", f)
p = os.path.join(root, f)
with open(p) as fh:
... | [
"def",
"update_headers",
"(",
"src_tree",
")",
":",
"print",
"(",
"\"src tree\"",
",",
"src_tree",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"src_tree",
")",
":",
"py_files",
"=",
"fnmatch",
".",
"filter",
"(",
"files... | Main. | [
"Main",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/dev/license-headers.py#L45-L60 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/cli.py | list_locks | def list_locks(account_id, resource_type=None, resource_id=None):
"""Show extant locks and unlocks.
"""
locks = Client(BASE_URL, account_id).list_locks().json()
for r in locks:
if 'LockDate' in r:
r['LockDate'] = datetime.fromtimestamp(r['LockDate'])
if 'RevisionDate' in r:
... | python | def list_locks(account_id, resource_type=None, resource_id=None):
"""Show extant locks and unlocks.
"""
locks = Client(BASE_URL, account_id).list_locks().json()
for r in locks:
if 'LockDate' in r:
r['LockDate'] = datetime.fromtimestamp(r['LockDate'])
if 'RevisionDate' in r:
... | [
"def",
"list_locks",
"(",
"account_id",
",",
"resource_type",
"=",
"None",
",",
"resource_id",
"=",
"None",
")",
":",
"locks",
"=",
"Client",
"(",
"BASE_URL",
",",
"account_id",
")",
".",
"list_locks",
"(",
")",
".",
"json",
"(",
")",
"for",
"r",
"in",... | Show extant locks and unlocks. | [
"Show",
"extant",
"locks",
"and",
"unlocks",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/cli.py#L38-L52 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/cli.py | lock_status | def lock_status(account_id, resource_id, parent_id):
"""Show extant locks' status
"""
return output(
Client(BASE_URL, account_id).lock_status(resource_id, parent_id)) | python | def lock_status(account_id, resource_id, parent_id):
"""Show extant locks' status
"""
return output(
Client(BASE_URL, account_id).lock_status(resource_id, parent_id)) | [
"def",
"lock_status",
"(",
"account_id",
",",
"resource_id",
",",
"parent_id",
")",
":",
"return",
"output",
"(",
"Client",
"(",
"BASE_URL",
",",
"account_id",
")",
".",
"lock_status",
"(",
"resource_id",
",",
"parent_id",
")",
")"
] | Show extant locks' status | [
"Show",
"extant",
"locks",
"status"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/cli.py#L67-L71 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/cli.py | lock | def lock(account_id, resource_id, region):
"""Lock a resource
"""
return output(
Client(BASE_URL, account_id).lock(resource_id, region)) | python | def lock(account_id, resource_id, region):
"""Lock a resource
"""
return output(
Client(BASE_URL, account_id).lock(resource_id, region)) | [
"def",
"lock",
"(",
"account_id",
",",
"resource_id",
",",
"region",
")",
":",
"return",
"output",
"(",
"Client",
"(",
"BASE_URL",
",",
"account_id",
")",
".",
"lock",
"(",
"resource_id",
",",
"region",
")",
")"
] | Lock a resource | [
"Lock",
"a",
"resource"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/cli.py#L78-L82 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/client.py | Client.list_locks | def list_locks(self, account_id=None):
"""Get extant locks for the given account.
"""
account_id = self.get_account_id(account_id)
return self.http.get(
"%s/%s/locks" % (self.endpoint, account_id),
auth=self.get_api_auth()) | python | def list_locks(self, account_id=None):
"""Get extant locks for the given account.
"""
account_id = self.get_account_id(account_id)
return self.http.get(
"%s/%s/locks" % (self.endpoint, account_id),
auth=self.get_api_auth()) | [
"def",
"list_locks",
"(",
"self",
",",
"account_id",
"=",
"None",
")",
":",
"account_id",
"=",
"self",
".",
"get_account_id",
"(",
"account_id",
")",
"return",
"self",
".",
"http",
".",
"get",
"(",
"\"%s/%s/locks\"",
"%",
"(",
"self",
".",
"endpoint",
",... | Get extant locks for the given account. | [
"Get",
"extant",
"locks",
"for",
"the",
"given",
"account",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/client.py#L41-L47 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/client.py | Client.lock_status | def lock_status(self, resource_id, parent_id=None, account_id=None):
"""Get the lock status for a given resource.
for security groups, parent id is their vpc.
"""
account_id = self.get_account_id(account_id)
params = parent_id and {'parent_id': parent_id} or None
return ... | python | def lock_status(self, resource_id, parent_id=None, account_id=None):
"""Get the lock status for a given resource.
for security groups, parent id is their vpc.
"""
account_id = self.get_account_id(account_id)
params = parent_id and {'parent_id': parent_id} or None
return ... | [
"def",
"lock_status",
"(",
"self",
",",
"resource_id",
",",
"parent_id",
"=",
"None",
",",
"account_id",
"=",
"None",
")",
":",
"account_id",
"=",
"self",
".",
"get_account_id",
"(",
"account_id",
")",
"params",
"=",
"parent_id",
"and",
"{",
"'parent_id'",
... | Get the lock status for a given resource.
for security groups, parent id is their vpc. | [
"Get",
"the",
"lock",
"status",
"for",
"a",
"given",
"resource",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/client.py#L49-L58 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/client.py | Client.lock | def lock(self, resource_id, region, account_id=None):
"""Lock a given resource
"""
account_id = self.get_account_id(account_id)
return self.http.post(
"%s/%s/locks/%s/lock" % (self.endpoint, account_id, resource_id),
json={'region': region},
auth=self.... | python | def lock(self, resource_id, region, account_id=None):
"""Lock a given resource
"""
account_id = self.get_account_id(account_id)
return self.http.post(
"%s/%s/locks/%s/lock" % (self.endpoint, account_id, resource_id),
json={'region': region},
auth=self.... | [
"def",
"lock",
"(",
"self",
",",
"resource_id",
",",
"region",
",",
"account_id",
"=",
"None",
")",
":",
"account_id",
"=",
"self",
".",
"get_account_id",
"(",
"account_id",
")",
"return",
"self",
".",
"http",
".",
"post",
"(",
"\"%s/%s/locks/%s/lock\"",
"... | Lock a given resource | [
"Lock",
"a",
"given",
"resource"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/client.py#L60-L67 | train |
cloud-custodian/cloud-custodian | tools/c7n_org/c7n_org/cli.py | report | def report(config, output, use, output_dir, accounts,
field, no_default_fields, tags, region, debug, verbose,
policy, policy_tags, format, resource, cache_path):
"""report on a cross account policy execution."""
accounts_config, custodian_config, executor = init(
config, use, debug... | python | def report(config, output, use, output_dir, accounts,
field, no_default_fields, tags, region, debug, verbose,
policy, policy_tags, format, resource, cache_path):
"""report on a cross account policy execution."""
accounts_config, custodian_config, executor = init(
config, use, debug... | [
"def",
"report",
"(",
"config",
",",
"output",
",",
"use",
",",
"output_dir",
",",
"accounts",
",",
"field",
",",
"no_default_fields",
",",
"tags",
",",
"region",
",",
"debug",
",",
"verbose",
",",
"policy",
",",
"policy_tags",
",",
"format",
",",
"resou... | report on a cross account policy execution. | [
"report",
"on",
"a",
"cross",
"account",
"policy",
"execution",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_org/c7n_org/cli.py#L322-L386 | train |
cloud-custodian/cloud-custodian | tools/c7n_org/c7n_org/cli.py | run_script | def run_script(config, output_dir, accounts, tags, region, echo, serial, script_args):
"""run an aws script across accounts"""
# TODO count up on success / error / error list by account
accounts_config, custodian_config, executor = init(
config, None, serial, True, accounts, tags, (), ())
if ec... | python | def run_script(config, output_dir, accounts, tags, region, echo, serial, script_args):
"""run an aws script across accounts"""
# TODO count up on success / error / error list by account
accounts_config, custodian_config, executor = init(
config, None, serial, True, accounts, tags, (), ())
if ec... | [
"def",
"run_script",
"(",
"config",
",",
"output_dir",
",",
"accounts",
",",
"tags",
",",
"region",
",",
"echo",
",",
"serial",
",",
"script_args",
")",
":",
"# TODO count up on success / error / error list by account",
"accounts_config",
",",
"custodian_config",
",",... | run an aws script across accounts | [
"run",
"an",
"aws",
"script",
"across",
"accounts"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_org/c7n_org/cli.py#L434-L472 | train |
cloud-custodian/cloud-custodian | tools/c7n_org/c7n_org/cli.py | run_account | def run_account(account, region, policies_config, output_path,
cache_period, cache_path, metrics, dryrun, debug):
"""Execute a set of policies on an account.
"""
logging.getLogger('custodian.output').setLevel(logging.ERROR + 1)
CONN_CACHE.session = None
CONN_CACHE.time = None
# ... | python | def run_account(account, region, policies_config, output_path,
cache_period, cache_path, metrics, dryrun, debug):
"""Execute a set of policies on an account.
"""
logging.getLogger('custodian.output').setLevel(logging.ERROR + 1)
CONN_CACHE.session = None
CONN_CACHE.time = None
# ... | [
"def",
"run_account",
"(",
"account",
",",
"region",
",",
"policies_config",
",",
"output_path",
",",
"cache_period",
",",
"cache_path",
",",
"metrics",
",",
"dryrun",
",",
"debug",
")",
":",
"logging",
".",
"getLogger",
"(",
"'custodian.output'",
")",
".",
... | Execute a set of policies on an account. | [
"Execute",
"a",
"set",
"of",
"policies",
"on",
"an",
"account",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_org/c7n_org/cli.py#L492-L570 | train |
cloud-custodian/cloud-custodian | tools/c7n_org/c7n_org/cli.py | run | def run(config, use, output_dir, accounts, tags, region,
policy, policy_tags, cache_period, cache_path, metrics,
dryrun, debug, verbose, metrics_uri):
"""run a custodian policy across accounts"""
accounts_config, custodian_config, executor = init(
config, use, debug, verbose, accounts, t... | python | def run(config, use, output_dir, accounts, tags, region,
policy, policy_tags, cache_period, cache_path, metrics,
dryrun, debug, verbose, metrics_uri):
"""run a custodian policy across accounts"""
accounts_config, custodian_config, executor = init(
config, use, debug, verbose, accounts, t... | [
"def",
"run",
"(",
"config",
",",
"use",
",",
"output_dir",
",",
"accounts",
",",
"tags",
",",
"region",
",",
"policy",
",",
"policy_tags",
",",
"cache_period",
",",
"cache_path",
",",
"metrics",
",",
"dryrun",
",",
"debug",
",",
"verbose",
",",
"metrics... | run a custodian policy across accounts | [
"run",
"a",
"custodian",
"policy",
"across",
"accounts"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_org/c7n_org/cli.py#L595-L646 | train |
cloud-custodian/cloud-custodian | c7n/log.py | CloudWatchLogHandler.emit | def emit(self, message):
"""Send logs"""
# We're sending messages asynchronously, bubble to caller when
# we've detected an error on the message. This isn't great,
# but options once we've gone async without a deferred/promise
# aren't great.
if self.transport and self.tr... | python | def emit(self, message):
"""Send logs"""
# We're sending messages asynchronously, bubble to caller when
# we've detected an error on the message. This isn't great,
# but options once we've gone async without a deferred/promise
# aren't great.
if self.transport and self.tr... | [
"def",
"emit",
"(",
"self",
",",
"message",
")",
":",
"# We're sending messages asynchronously, bubble to caller when",
"# we've detected an error on the message. This isn't great,",
"# but options once we've gone async without a deferred/promise",
"# aren't great.",
"if",
"self",
".",
... | Send logs | [
"Send",
"logs"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/log.py#L100-L121 | train |
cloud-custodian/cloud-custodian | c7n/log.py | CloudWatchLogHandler.flush | def flush(self):
"""Ensure all logging output has been flushed."""
if self.shutdown:
return
self.flush_buffers(force=True)
self.queue.put(FLUSH_MARKER)
self.queue.join() | python | def flush(self):
"""Ensure all logging output has been flushed."""
if self.shutdown:
return
self.flush_buffers(force=True)
self.queue.put(FLUSH_MARKER)
self.queue.join() | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"shutdown",
":",
"return",
"self",
".",
"flush_buffers",
"(",
"force",
"=",
"True",
")",
"self",
".",
"queue",
".",
"put",
"(",
"FLUSH_MARKER",
")",
"self",
".",
"queue",
".",
"join",
"(",
"... | Ensure all logging output has been flushed. | [
"Ensure",
"all",
"logging",
"output",
"has",
"been",
"flushed",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/log.py#L123-L129 | train |
cloud-custodian/cloud-custodian | c7n/log.py | CloudWatchLogHandler.format_message | def format_message(self, msg):
"""format message."""
return {'timestamp': int(msg.created * 1000),
'message': self.format(msg),
'stream': self.log_stream or msg.name,
'group': self.log_group} | python | def format_message(self, msg):
"""format message."""
return {'timestamp': int(msg.created * 1000),
'message': self.format(msg),
'stream': self.log_stream or msg.name,
'group': self.log_group} | [
"def",
"format_message",
"(",
"self",
",",
"msg",
")",
":",
"return",
"{",
"'timestamp'",
":",
"int",
"(",
"msg",
".",
"created",
"*",
"1000",
")",
",",
"'message'",
":",
"self",
".",
"format",
"(",
"msg",
")",
",",
"'stream'",
":",
"self",
".",
"l... | format message. | [
"format",
"message",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/log.py#L143-L148 | train |
cloud-custodian/cloud-custodian | c7n/log.py | CloudWatchLogHandler.start_transports | def start_transports(self):
"""start thread transports."""
self.transport = Transport(
self.queue, self.batch_size, self.batch_interval,
self.session_factory)
thread = threading.Thread(target=self.transport.loop)
self.threads.append(thread)
thread.daemon =... | python | def start_transports(self):
"""start thread transports."""
self.transport = Transport(
self.queue, self.batch_size, self.batch_interval,
self.session_factory)
thread = threading.Thread(target=self.transport.loop)
self.threads.append(thread)
thread.daemon =... | [
"def",
"start_transports",
"(",
"self",
")",
":",
"self",
".",
"transport",
"=",
"Transport",
"(",
"self",
".",
"queue",
",",
"self",
".",
"batch_size",
",",
"self",
".",
"batch_interval",
",",
"self",
".",
"session_factory",
")",
"thread",
"=",
"threading... | start thread transports. | [
"start",
"thread",
"transports",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/log.py#L150-L158 | train |
cloud-custodian/cloud-custodian | c7n/resources/ami.py | ErrorHandler.extract_bad_ami | def extract_bad_ami(e):
"""Handle various client side errors when describing images"""
msg = e.response['Error']['Message']
error = e.response['Error']['Code']
e_ami_ids = None
if error == 'InvalidAMIID.NotFound':
e_ami_ids = [
e_ami_id.strip() for e_a... | python | def extract_bad_ami(e):
"""Handle various client side errors when describing images"""
msg = e.response['Error']['Message']
error = e.response['Error']['Code']
e_ami_ids = None
if error == 'InvalidAMIID.NotFound':
e_ami_ids = [
e_ami_id.strip() for e_a... | [
"def",
"extract_bad_ami",
"(",
"e",
")",
":",
"msg",
"=",
"e",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Message'",
"]",
"error",
"=",
"e",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Code'",
"]",
"e_ami_ids",
"=",
"None",
"if",
"error",
"==",
... | Handle various client side errors when describing images | [
"Handle",
"various",
"client",
"side",
"errors",
"when",
"describing",
"images"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/ami.py#L82-L95 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py | format_json | def format_json(config):
"""format config for lambda exec
"""
with open(config) as fh:
print(json.dumps(yaml.safe_load(fh.read()), indent=2)) | python | def format_json(config):
"""format config for lambda exec
"""
with open(config) as fh:
print(json.dumps(yaml.safe_load(fh.read()), indent=2)) | [
"def",
"format_json",
"(",
"config",
")",
":",
"with",
"open",
"(",
"config",
")",
"as",
"fh",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"yaml",
".",
"safe_load",
"(",
"fh",
".",
"read",
"(",
")",
")",
",",
"indent",
"=",
"2",
")",
")"
] | format config for lambda exec | [
"format",
"config",
"for",
"lambda",
"exec"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py#L40-L44 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py | check | def check():
"""Sanity check api deployment
"""
t = time.time()
results = Client(BASE_URL).version()
print("Endpoint", BASE_URL)
print("Response Time %0.2f" % (time.time() - t))
print("Headers")
for k, v in results.headers.items():
print(" %s: %s" % (k, v))
print("Body")
... | python | def check():
"""Sanity check api deployment
"""
t = time.time()
results = Client(BASE_URL).version()
print("Endpoint", BASE_URL)
print("Response Time %0.2f" % (time.time() - t))
print("Headers")
for k, v in results.headers.items():
print(" %s: %s" % (k, v))
print("Body")
... | [
"def",
"check",
"(",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"results",
"=",
"Client",
"(",
"BASE_URL",
")",
".",
"version",
"(",
")",
"print",
"(",
"\"Endpoint\"",
",",
"BASE_URL",
")",
"print",
"(",
"\"Response Time %0.2f\"",
"%",
"(",
"... | Sanity check api deployment | [
"Sanity",
"check",
"api",
"deployment"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py#L71-L82 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py | metrics | def metrics(function, api, start, period):
"""lambda/api/db metrics"""
from c7n.mu import LambdaManager
manager = LambdaManager(boto3.Session)
start = parse_date(start)
period = int(abs(parse_timedelta(period).total_seconds()))
print("Lambda Metrics")
metrics = manager.metrics(
[{'F... | python | def metrics(function, api, start, period):
"""lambda/api/db metrics"""
from c7n.mu import LambdaManager
manager = LambdaManager(boto3.Session)
start = parse_date(start)
period = int(abs(parse_timedelta(period).total_seconds()))
print("Lambda Metrics")
metrics = manager.metrics(
[{'F... | [
"def",
"metrics",
"(",
"function",
",",
"api",
",",
"start",
",",
"period",
")",
":",
"from",
"c7n",
".",
"mu",
"import",
"LambdaManager",
"manager",
"=",
"LambdaManager",
"(",
"boto3",
".",
"Session",
")",
"start",
"=",
"parse_date",
"(",
"start",
")",
... | lambda/api/db metrics | [
"lambda",
"/",
"api",
"/",
"db",
"metrics"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py#L92-L127 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py | records | def records(account_id):
"""Fetch locks data
"""
s = boto3.Session()
table = s.resource('dynamodb').Table('Sphere11.Dev.ResourceLocks')
results = table.scan()
for r in results['Items']:
if 'LockDate' in r:
r['LockDate'] = datetime.fromtimestamp(r['LockDate'])
if 'Rev... | python | def records(account_id):
"""Fetch locks data
"""
s = boto3.Session()
table = s.resource('dynamodb').Table('Sphere11.Dev.ResourceLocks')
results = table.scan()
for r in results['Items']:
if 'LockDate' in r:
r['LockDate'] = datetime.fromtimestamp(r['LockDate'])
if 'Rev... | [
"def",
"records",
"(",
"account_id",
")",
":",
"s",
"=",
"boto3",
".",
"Session",
"(",
")",
"table",
"=",
"s",
".",
"resource",
"(",
"'dynamodb'",
")",
".",
"Table",
"(",
"'Sphere11.Dev.ResourceLocks'",
")",
"results",
"=",
"table",
".",
"scan",
"(",
"... | Fetch locks data | [
"Fetch",
"locks",
"data"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py#L197-L213 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py | flush_pending | def flush_pending(function):
"""Attempt to acquire any pending locks.
"""
s = boto3.Session()
client = s.client('lambda')
results = client.invoke(
FunctionName=function,
Payload=json.dumps({'detail-type': 'Scheduled Event'})
)
content = results.pop('Payload').read()
pprin... | python | def flush_pending(function):
"""Attempt to acquire any pending locks.
"""
s = boto3.Session()
client = s.client('lambda')
results = client.invoke(
FunctionName=function,
Payload=json.dumps({'detail-type': 'Scheduled Event'})
)
content = results.pop('Payload').read()
pprin... | [
"def",
"flush_pending",
"(",
"function",
")",
":",
"s",
"=",
"boto3",
".",
"Session",
"(",
")",
"client",
"=",
"s",
".",
"client",
"(",
"'lambda'",
")",
"results",
"=",
"client",
".",
"invoke",
"(",
"FunctionName",
"=",
"function",
",",
"Payload",
"=",... | Attempt to acquire any pending locks. | [
"Attempt",
"to",
"acquire",
"any",
"pending",
"locks",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py#L218-L229 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py | config_status | def config_status():
""" Check config status in an account.
"""
s = boto3.Session()
client = s.client('config')
channels = client.describe_delivery_channel_status()[
'DeliveryChannelsStatus']
for c in channels:
print(yaml.safe_dump({
c['name']: dict(
s... | python | def config_status():
""" Check config status in an account.
"""
s = boto3.Session()
client = s.client('config')
channels = client.describe_delivery_channel_status()[
'DeliveryChannelsStatus']
for c in channels:
print(yaml.safe_dump({
c['name']: dict(
s... | [
"def",
"config_status",
"(",
")",
":",
"s",
"=",
"boto3",
".",
"Session",
"(",
")",
"client",
"=",
"s",
".",
"client",
"(",
"'config'",
")",
"channels",
"=",
"client",
".",
"describe_delivery_channel_status",
"(",
")",
"[",
"'DeliveryChannelsStatus'",
"]",
... | Check config status in an account. | [
"Check",
"config",
"status",
"in",
"an",
"account",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py#L233-L250 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py | local | def local(reload, port):
"""run local app server, assumes into the account
"""
import logging
from bottle import run
from app import controller, app
from c7n.resources import load_resources
load_resources()
print("Loaded resources definitions")
logging.basicConfig(level=logging.DEBUG... | python | def local(reload, port):
"""run local app server, assumes into the account
"""
import logging
from bottle import run
from app import controller, app
from c7n.resources import load_resources
load_resources()
print("Loaded resources definitions")
logging.basicConfig(level=logging.DEBUG... | [
"def",
"local",
"(",
"reload",
",",
"port",
")",
":",
"import",
"logging",
"from",
"bottle",
"import",
"run",
"from",
"app",
"import",
"controller",
",",
"app",
"from",
"c7n",
".",
"resources",
"import",
"load_resources",
"load_resources",
"(",
")",
"print",... | run local app server, assumes into the account | [
"run",
"local",
"app",
"server",
"assumes",
"into",
"the",
"account"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py#L263-L276 | train |
cloud-custodian/cloud-custodian | c7n/commands.py | _schema_get_docstring | def _schema_get_docstring(starting_class):
""" Given a class, return its docstring.
If no docstring is present for the class, search base classes in MRO for a
docstring.
"""
for cls in inspect.getmro(starting_class):
if inspect.getdoc(cls):
return inspect.getdoc(cls) | python | def _schema_get_docstring(starting_class):
""" Given a class, return its docstring.
If no docstring is present for the class, search base classes in MRO for a
docstring.
"""
for cls in inspect.getmro(starting_class):
if inspect.getdoc(cls):
return inspect.getdoc(cls) | [
"def",
"_schema_get_docstring",
"(",
"starting_class",
")",
":",
"for",
"cls",
"in",
"inspect",
".",
"getmro",
"(",
"starting_class",
")",
":",
"if",
"inspect",
".",
"getdoc",
"(",
"cls",
")",
":",
"return",
"inspect",
".",
"getdoc",
"(",
"cls",
")"
] | Given a class, return its docstring.
If no docstring is present for the class, search base classes in MRO for a
docstring. | [
"Given",
"a",
"class",
"return",
"its",
"docstring",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/commands.py#L316-L324 | train |
cloud-custodian/cloud-custodian | c7n/commands.py | schema_completer | def schema_completer(prefix):
""" For tab-completion via argcomplete, return completion options.
For the given prefix so far, return the possible options. Note that
filtering via startswith happens after this list is returned.
"""
from c7n import schema
load_resources()
components = prefix... | python | def schema_completer(prefix):
""" For tab-completion via argcomplete, return completion options.
For the given prefix so far, return the possible options. Note that
filtering via startswith happens after this list is returned.
"""
from c7n import schema
load_resources()
components = prefix... | [
"def",
"schema_completer",
"(",
"prefix",
")",
":",
"from",
"c7n",
"import",
"schema",
"load_resources",
"(",
")",
"components",
"=",
"prefix",
".",
"split",
"(",
"'.'",
")",
"if",
"components",
"[",
"0",
"]",
"in",
"provider",
".",
"clouds",
".",
"keys"... | For tab-completion via argcomplete, return completion options.
For the given prefix so far, return the possible options. Note that
filtering via startswith happens after this list is returned. | [
"For",
"tab",
"-",
"completion",
"via",
"argcomplete",
"return",
"completion",
"options",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/commands.py#L327-L370 | train |
cloud-custodian/cloud-custodian | c7n/commands.py | schema_cmd | def schema_cmd(options):
""" Print info about the resources, actions and filters available. """
from c7n import schema
if options.json:
schema.json_dump(options.resource)
return
load_resources()
resource_mapping = schema.resource_vocabulary()
if options.summary:
schema.... | python | def schema_cmd(options):
""" Print info about the resources, actions and filters available. """
from c7n import schema
if options.json:
schema.json_dump(options.resource)
return
load_resources()
resource_mapping = schema.resource_vocabulary()
if options.summary:
schema.... | [
"def",
"schema_cmd",
"(",
"options",
")",
":",
"from",
"c7n",
"import",
"schema",
"if",
"options",
".",
"json",
":",
"schema",
".",
"json_dump",
"(",
"options",
".",
"resource",
")",
"return",
"load_resources",
"(",
")",
"resource_mapping",
"=",
"schema",
... | Print info about the resources, actions and filters available. | [
"Print",
"info",
"about",
"the",
"resources",
"actions",
"and",
"filters",
"available",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/commands.py#L373-L502 | train |
cloud-custodian/cloud-custodian | c7n/commands.py | _metrics_get_endpoints | def _metrics_get_endpoints(options):
""" Determine the start and end dates based on user-supplied options. """
if bool(options.start) ^ bool(options.end):
log.error('--start and --end must be specified together')
sys.exit(1)
if options.start and options.end:
start = options.start
... | python | def _metrics_get_endpoints(options):
""" Determine the start and end dates based on user-supplied options. """
if bool(options.start) ^ bool(options.end):
log.error('--start and --end must be specified together')
sys.exit(1)
if options.start and options.end:
start = options.start
... | [
"def",
"_metrics_get_endpoints",
"(",
"options",
")",
":",
"if",
"bool",
"(",
"options",
".",
"start",
")",
"^",
"bool",
"(",
"options",
".",
"end",
")",
":",
"log",
".",
"error",
"(",
"'--start and --end must be specified together'",
")",
"sys",
".",
"exit"... | Determine the start and end dates based on user-supplied options. | [
"Determine",
"the",
"start",
"and",
"end",
"dates",
"based",
"on",
"user",
"-",
"supplied",
"options",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/commands.py#L529-L542 | train |
cloud-custodian/cloud-custodian | c7n/resources/ec2.py | extract_instance_id | def extract_instance_id(state_error):
"Extract an instance id from an error"
instance_id = None
match = RE_ERROR_INSTANCE_ID.search(str(state_error))
if match:
instance_id = match.groupdict().get('instance_id')
if match is None or instance_id is None:
raise ValueError("Could not extr... | python | def extract_instance_id(state_error):
"Extract an instance id from an error"
instance_id = None
match = RE_ERROR_INSTANCE_ID.search(str(state_error))
if match:
instance_id = match.groupdict().get('instance_id')
if match is None or instance_id is None:
raise ValueError("Could not extr... | [
"def",
"extract_instance_id",
"(",
"state_error",
")",
":",
"instance_id",
"=",
"None",
"match",
"=",
"RE_ERROR_INSTANCE_ID",
".",
"search",
"(",
"str",
"(",
"state_error",
")",
")",
"if",
"match",
":",
"instance_id",
"=",
"match",
".",
"groupdict",
"(",
")"... | Extract an instance id from an error | [
"Extract",
"an",
"instance",
"id",
"from",
"an",
"error"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/ec2.py#L1011-L1019 | train |
cloud-custodian/cloud-custodian | c7n/resources/ec2.py | DescribeEC2.augment | def augment(self, resources):
"""EC2 API and AWOL Tags
While ec2 api generally returns tags when doing describe_x on for
various resources, it may also silently fail to do so unless a tag
is used as a filter.
See footnote on for official documentation.
https://docs.aws.... | python | def augment(self, resources):
"""EC2 API and AWOL Tags
While ec2 api generally returns tags when doing describe_x on for
various resources, it may also silently fail to do so unless a tag
is used as a filter.
See footnote on for official documentation.
https://docs.aws.... | [
"def",
"augment",
"(",
"self",
",",
"resources",
")",
":",
"# First if we're in event based lambda go ahead and skip this,",
"# tags can't be trusted in ec2 instances immediately post creation.",
"if",
"not",
"resources",
"or",
"self",
".",
"manager",
".",
"data",
".",
"get",... | EC2 API and AWOL Tags
While ec2 api generally returns tags when doing describe_x on for
various resources, it may also silently fail to do so unless a tag
is used as a filter.
See footnote on for official documentation.
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_... | [
"EC2",
"API",
"and",
"AWOL",
"Tags"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/ec2.py#L122-L172 | train |
cloud-custodian/cloud-custodian | c7n/filters/securityhub.py | SecurityHubFindingFilter.register_resources | def register_resources(klass, registry, resource_class):
""" meta model subscriber on resource registration.
SecurityHub Findings Filter
"""
for rtype, resource_manager in registry.items():
if not resource_manager.has_arn():
continue
if 'post-find... | python | def register_resources(klass, registry, resource_class):
""" meta model subscriber on resource registration.
SecurityHub Findings Filter
"""
for rtype, resource_manager in registry.items():
if not resource_manager.has_arn():
continue
if 'post-find... | [
"def",
"register_resources",
"(",
"klass",
",",
"registry",
",",
"resource_class",
")",
":",
"for",
"rtype",
",",
"resource_manager",
"in",
"registry",
".",
"items",
"(",
")",
":",
"if",
"not",
"resource_manager",
".",
"has_arn",
"(",
")",
":",
"continue",
... | meta model subscriber on resource registration.
SecurityHub Findings Filter | [
"meta",
"model",
"subscriber",
"on",
"resource",
"registration",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/securityhub.py#L57-L67 | train |
cloud-custodian/cloud-custodian | tools/c7n_gcp/c7n_gcp/actions/notify.py | Notify.publish_message | def publish_message(self, message, client):
"""Publish message to a GCP pub/sub topic
"""
return client.execute_command('publish', {
'topic': self.data['transport']['topic'],
'body': {
'messages': {
'data': self.pack(message)
... | python | def publish_message(self, message, client):
"""Publish message to a GCP pub/sub topic
"""
return client.execute_command('publish', {
'topic': self.data['transport']['topic'],
'body': {
'messages': {
'data': self.pack(message)
... | [
"def",
"publish_message",
"(",
"self",
",",
"message",
",",
"client",
")",
":",
"return",
"client",
".",
"execute_command",
"(",
"'publish'",
",",
"{",
"'topic'",
":",
"self",
".",
"data",
"[",
"'transport'",
"]",
"[",
"'topic'",
"]",
",",
"'body'",
":",... | Publish message to a GCP pub/sub topic | [
"Publish",
"message",
"to",
"a",
"GCP",
"pub",
"/",
"sub",
"topic"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_gcp/c7n_gcp/actions/notify.py#L99-L109 | train |
cloud-custodian/cloud-custodian | tools/c7n_mailer/c7n_mailer/email_delivery.py | EmailDelivery.set_mimetext_headers | def set_mimetext_headers(self, message, subject, from_addr, to_addrs, cc_addrs, priority):
"""Sets headers on Mimetext message"""
message['Subject'] = subject
message['From'] = from_addr
message['To'] = ', '.join(to_addrs)
if cc_addrs:
message['Cc'] = ', '.join(cc_ad... | python | def set_mimetext_headers(self, message, subject, from_addr, to_addrs, cc_addrs, priority):
"""Sets headers on Mimetext message"""
message['Subject'] = subject
message['From'] = from_addr
message['To'] = ', '.join(to_addrs)
if cc_addrs:
message['Cc'] = ', '.join(cc_ad... | [
"def",
"set_mimetext_headers",
"(",
"self",
",",
"message",
",",
"subject",
",",
"from_addr",
",",
"to_addrs",
",",
"cc_addrs",
",",
"priority",
")",
":",
"message",
"[",
"'Subject'",
"]",
"=",
"subject",
"message",
"[",
"'From'",
"]",
"=",
"from_addr",
"m... | Sets headers on Mimetext message | [
"Sets",
"headers",
"on",
"Mimetext",
"message"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_mailer/c7n_mailer/email_delivery.py#L265-L279 | train |
cloud-custodian/cloud-custodian | c7n/filters/health.py | HealthEventFilter.register_resources | def register_resources(klass, registry, resource_class):
""" meta model subscriber on resource registration.
We watch for PHD event that provides affected entities and register
the health-event filter to the resources.
"""
services = {'acm-certificate', 'directconnect', 'dms-ins... | python | def register_resources(klass, registry, resource_class):
""" meta model subscriber on resource registration.
We watch for PHD event that provides affected entities and register
the health-event filter to the resources.
"""
services = {'acm-certificate', 'directconnect', 'dms-ins... | [
"def",
"register_resources",
"(",
"klass",
",",
"registry",
",",
"resource_class",
")",
":",
"services",
"=",
"{",
"'acm-certificate'",
",",
"'directconnect'",
",",
"'dms-instance'",
",",
"'directory'",
",",
"'ec2'",
",",
"'dynamodb-table'",
",",
"'cache-cluster'",
... | meta model subscriber on resource registration.
We watch for PHD event that provides affected entities and register
the health-event filter to the resources. | [
"meta",
"model",
"subscriber",
"on",
"resource",
"registration",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/health.py#L104-L114 | train |
cloud-custodian/cloud-custodian | c7n/mu.py | custodian_archive | def custodian_archive(packages=None):
"""Create a lambda code archive for running custodian.
Lambda archive currently always includes `c7n` and
`pkg_resources`. Add additional packages in the mode block.
Example policy that includes additional packages
.. code-block:: yaml
policy:
... | python | def custodian_archive(packages=None):
"""Create a lambda code archive for running custodian.
Lambda archive currently always includes `c7n` and
`pkg_resources`. Add additional packages in the mode block.
Example policy that includes additional packages
.. code-block:: yaml
policy:
... | [
"def",
"custodian_archive",
"(",
"packages",
"=",
"None",
")",
":",
"modules",
"=",
"{",
"'c7n'",
",",
"'pkg_resources'",
"}",
"if",
"packages",
":",
"modules",
"=",
"filter",
"(",
"None",
",",
"modules",
".",
"union",
"(",
"packages",
")",
")",
"return"... | Create a lambda code archive for running custodian.
Lambda archive currently always includes `c7n` and
`pkg_resources`. Add additional packages in the mode block.
Example policy that includes additional packages
.. code-block:: yaml
policy:
name: lambda-archive-example
re... | [
"Create",
"a",
"lambda",
"code",
"archive",
"for",
"running",
"custodian",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L254-L277 | train |
cloud-custodian/cloud-custodian | c7n/mu.py | PythonPackageArchive.add_modules | def add_modules(self, ignore, *modules):
"""Add the named Python modules to the archive. For consistency's sake
we only add ``*.py`` files, not ``*.pyc``. We also don't add other
files, including compiled modules. You'll have to add such files
manually using :py:meth:`add_file`.
... | python | def add_modules(self, ignore, *modules):
"""Add the named Python modules to the archive. For consistency's sake
we only add ``*.py`` files, not ``*.pyc``. We also don't add other
files, including compiled modules. You'll have to add such files
manually using :py:meth:`add_file`.
... | [
"def",
"add_modules",
"(",
"self",
",",
"ignore",
",",
"*",
"modules",
")",
":",
"for",
"module_name",
"in",
"modules",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"if",
"hasattr",
"(",
"module",
",",
"'__path__'",
")",
... | Add the named Python modules to the archive. For consistency's sake
we only add ``*.py`` files, not ``*.pyc``. We also don't add other
files, including compiled modules. You'll have to add such files
manually using :py:meth:`add_file`. | [
"Add",
"the",
"named",
"Python",
"modules",
"to",
"the",
"archive",
".",
"For",
"consistency",
"s",
"sake",
"we",
"only",
"add",
"*",
".",
"py",
"files",
"not",
"*",
".",
"pyc",
".",
"We",
"also",
"don",
"t",
"add",
"other",
"files",
"including",
"co... | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L91-L131 | train |
cloud-custodian/cloud-custodian | c7n/mu.py | PythonPackageArchive.add_directory | def add_directory(self, path, ignore=None):
"""Add ``*.py`` files under the directory ``path`` to the archive.
"""
for root, dirs, files in os.walk(path):
arc_prefix = os.path.relpath(root, os.path.dirname(path))
# py3 remove pyc cache dirs.
if '__pycache__' i... | python | def add_directory(self, path, ignore=None):
"""Add ``*.py`` files under the directory ``path`` to the archive.
"""
for root, dirs, files in os.walk(path):
arc_prefix = os.path.relpath(root, os.path.dirname(path))
# py3 remove pyc cache dirs.
if '__pycache__' i... | [
"def",
"add_directory",
"(",
"self",
",",
"path",
",",
"ignore",
"=",
"None",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"arc_prefix",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"root",
"... | Add ``*.py`` files under the directory ``path`` to the archive. | [
"Add",
"*",
".",
"py",
"files",
"under",
"the",
"directory",
"path",
"to",
"the",
"archive",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L133-L152 | train |
cloud-custodian/cloud-custodian | c7n/mu.py | PythonPackageArchive.add_file | def add_file(self, src, dest=None):
"""Add the file at ``src`` to the archive.
If ``dest`` is ``None`` then it is added under just the original
filename. So ``add_file('foo/bar.txt')`` ends up at ``bar.txt`` in the
archive, while ``add_file('bar.txt', 'foo/bar.txt')`` ends up at
... | python | def add_file(self, src, dest=None):
"""Add the file at ``src`` to the archive.
If ``dest`` is ``None`` then it is added under just the original
filename. So ``add_file('foo/bar.txt')`` ends up at ``bar.txt`` in the
archive, while ``add_file('bar.txt', 'foo/bar.txt')`` ends up at
... | [
"def",
"add_file",
"(",
"self",
",",
"src",
",",
"dest",
"=",
"None",
")",
":",
"dest",
"=",
"dest",
"or",
"os",
".",
"path",
".",
"basename",
"(",
"src",
")",
"with",
"open",
"(",
"src",
",",
"'rb'",
")",
"as",
"fp",
":",
"contents",
"=",
"fp"... | Add the file at ``src`` to the archive.
If ``dest`` is ``None`` then it is added under just the original
filename. So ``add_file('foo/bar.txt')`` ends up at ``bar.txt`` in the
archive, while ``add_file('bar.txt', 'foo/bar.txt')`` ends up at
``foo/bar.txt``. | [
"Add",
"the",
"file",
"at",
"src",
"to",
"the",
"archive",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L154-L166 | train |
cloud-custodian/cloud-custodian | c7n/mu.py | PythonPackageArchive.add_py_file | def add_py_file(self, src, dest=None):
"""This is a special case of :py:meth:`add_file` that helps for adding
a ``py`` when a ``pyc`` may be present as well. So for example, if
``__file__`` is ``foo.pyc`` and you do:
.. code-block:: python
archive.add_py_file(__file__)
... | python | def add_py_file(self, src, dest=None):
"""This is a special case of :py:meth:`add_file` that helps for adding
a ``py`` when a ``pyc`` may be present as well. So for example, if
``__file__`` is ``foo.pyc`` and you do:
.. code-block:: python
archive.add_py_file(__file__)
... | [
"def",
"add_py_file",
"(",
"self",
",",
"src",
",",
"dest",
"=",
"None",
")",
":",
"src",
"=",
"src",
"[",
":",
"-",
"1",
"]",
"if",
"src",
".",
"endswith",
"(",
"'.pyc'",
")",
"else",
"src",
"self",
".",
"add_file",
"(",
"src",
",",
"dest",
")... | This is a special case of :py:meth:`add_file` that helps for adding
a ``py`` when a ``pyc`` may be present as well. So for example, if
``__file__`` is ``foo.pyc`` and you do:
.. code-block:: python
archive.add_py_file(__file__)
then this method will add ``foo.py`` instead if... | [
"This",
"is",
"a",
"special",
"case",
"of",
":",
"py",
":",
"meth",
":",
"add_file",
"that",
"helps",
"for",
"adding",
"a",
"py",
"when",
"a",
"pyc",
"may",
"be",
"present",
"as",
"well",
".",
"So",
"for",
"example",
"if",
"__file__",
"is",
"foo",
... | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L168-L182 | train |
cloud-custodian/cloud-custodian | c7n/mu.py | PythonPackageArchive.add_contents | def add_contents(self, dest, contents):
"""Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for
custom behavior.
"""
assert not self.... | python | def add_contents(self, dest, contents):
"""Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for
custom behavior.
"""
assert not self.... | [
"def",
"add_contents",
"(",
"self",
",",
"dest",
",",
"contents",
")",
":",
"assert",
"not",
"self",
".",
"_closed",
",",
"\"Archive closed\"",
"if",
"not",
"isinstance",
"(",
"dest",
",",
"zipfile",
".",
"ZipInfo",
")",
":",
"dest",
"=",
"zinfo",
"(",
... | Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for
custom behavior. | [
"Add",
"file",
"contents",
"to",
"the",
"archive",
"under",
"dest",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L184-L199 | train |
cloud-custodian/cloud-custodian | c7n/mu.py | PythonPackageArchive.close | def close(self):
"""Close the zip file.
Note underlying tempfile is removed when archive is garbage collected.
"""
self._closed = True
self._zip_file.close()
log.debug(
"Created custodian serverless archive size: %0.2fmb",
(os.path.getsize(self._t... | python | def close(self):
"""Close the zip file.
Note underlying tempfile is removed when archive is garbage collected.
"""
self._closed = True
self._zip_file.close()
log.debug(
"Created custodian serverless archive size: %0.2fmb",
(os.path.getsize(self._t... | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_closed",
"=",
"True",
"self",
".",
"_zip_file",
".",
"close",
"(",
")",
"log",
".",
"debug",
"(",
"\"Created custodian serverless archive size: %0.2fmb\"",
",",
"(",
"os",
".",
"path",
".",
"getsize",
"... | Close the zip file.
Note underlying tempfile is removed when archive is garbage collected. | [
"Close",
"the",
"zip",
"file",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L201-L212 | train |
cloud-custodian/cloud-custodian | c7n/mu.py | PythonPackageArchive.get_checksum | def get_checksum(self, encoder=base64.b64encode, hasher=hashlib.sha256):
"""Return the b64 encoded sha256 checksum of the archive."""
assert self._closed, "Archive not closed"
with open(self._temp_archive_file.name, 'rb') as fh:
return encoder(checksum(fh, hasher())).decode('ascii') | python | def get_checksum(self, encoder=base64.b64encode, hasher=hashlib.sha256):
"""Return the b64 encoded sha256 checksum of the archive."""
assert self._closed, "Archive not closed"
with open(self._temp_archive_file.name, 'rb') as fh:
return encoder(checksum(fh, hasher())).decode('ascii') | [
"def",
"get_checksum",
"(",
"self",
",",
"encoder",
"=",
"base64",
".",
"b64encode",
",",
"hasher",
"=",
"hashlib",
".",
"sha256",
")",
":",
"assert",
"self",
".",
"_closed",
",",
"\"Archive not closed\"",
"with",
"open",
"(",
"self",
".",
"_temp_archive_fil... | Return the b64 encoded sha256 checksum of the archive. | [
"Return",
"the",
"b64",
"encoded",
"sha256",
"checksum",
"of",
"the",
"archive",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L219-L223 | train |
cloud-custodian/cloud-custodian | c7n/mu.py | PythonPackageArchive.get_reader | def get_reader(self):
"""Return a read-only :py:class:`~zipfile.ZipFile`."""
assert self._closed, "Archive not closed"
buf = io.BytesIO(self.get_bytes())
return zipfile.ZipFile(buf, mode='r') | python | def get_reader(self):
"""Return a read-only :py:class:`~zipfile.ZipFile`."""
assert self._closed, "Archive not closed"
buf = io.BytesIO(self.get_bytes())
return zipfile.ZipFile(buf, mode='r') | [
"def",
"get_reader",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_closed",
",",
"\"Archive not closed\"",
"buf",
"=",
"io",
".",
"BytesIO",
"(",
"self",
".",
"get_bytes",
"(",
")",
")",
"return",
"zipfile",
".",
"ZipFile",
"(",
"buf",
",",
"mode",
"... | Return a read-only :py:class:`~zipfile.ZipFile`. | [
"Return",
"a",
"read",
"-",
"only",
":",
"py",
":",
"class",
":",
"~zipfile",
".",
"ZipFile",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L235-L239 | train |
cloud-custodian/cloud-custodian | c7n/mu.py | LambdaManager.publish_alias | def publish_alias(self, func_data, alias):
"""Create or update an alias for the given function.
"""
if not alias:
return func_data['FunctionArn']
func_name = func_data['FunctionName']
func_version = func_data['Version']
exists = resource_exists(
s... | python | def publish_alias(self, func_data, alias):
"""Create or update an alias for the given function.
"""
if not alias:
return func_data['FunctionArn']
func_name = func_data['FunctionName']
func_version = func_data['Version']
exists = resource_exists(
s... | [
"def",
"publish_alias",
"(",
"self",
",",
"func_data",
",",
"alias",
")",
":",
"if",
"not",
"alias",
":",
"return",
"func_data",
"[",
"'FunctionArn'",
"]",
"func_name",
"=",
"func_data",
"[",
"'FunctionName'",
"]",
"func_version",
"=",
"func_data",
"[",
"'Ve... | Create or update an alias for the given function. | [
"Create",
"or",
"update",
"an",
"alias",
"for",
"the",
"given",
"function",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L520-L546 | train |
cloud-custodian/cloud-custodian | tools/sandbox/zerodark/zerodark/utils.py | row_factory | def row_factory(cursor, row):
"""Returns a sqlite row factory that returns a dictionary"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | python | def row_factory(cursor, row):
"""Returns a sqlite row factory that returns a dictionary"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | [
"def",
"row_factory",
"(",
"cursor",
",",
"row",
")",
":",
"d",
"=",
"{",
"}",
"for",
"idx",
",",
"col",
"in",
"enumerate",
"(",
"cursor",
".",
"description",
")",
":",
"d",
"[",
"col",
"[",
"0",
"]",
"]",
"=",
"row",
"[",
"idx",
"]",
"return",... | Returns a sqlite row factory that returns a dictionary | [
"Returns",
"a",
"sqlite",
"row",
"factory",
"that",
"returns",
"a",
"dictionary"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/zerodark/zerodark/utils.py#L25-L30 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/tags.py | TagHelper.get_tag_value | def get_tag_value(resource, tag, utf_8=False):
"""Get the resource's tag value."""
tags = {k.lower(): v for k, v in resource.get('tags', {}).items()}
value = tags.get(tag, False)
if value is not False:
if utf_8:
value = value.encode('utf8').decode('u... | python | def get_tag_value(resource, tag, utf_8=False):
"""Get the resource's tag value."""
tags = {k.lower(): v for k, v in resource.get('tags', {}).items()}
value = tags.get(tag, False)
if value is not False:
if utf_8:
value = value.encode('utf8').decode('u... | [
"def",
"get_tag_value",
"(",
"resource",
",",
"tag",
",",
"utf_8",
"=",
"False",
")",
":",
"tags",
"=",
"{",
"k",
".",
"lower",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"resource",
".",
"get",
"(",
"'tags'",
",",
"{",
"}",
")",
".",
"i... | Get the resource's tag value. | [
"Get",
"the",
"resource",
"s",
"tag",
"value",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/tags.py#L99-L108 | train |
cloud-custodian/cloud-custodian | tools/c7n_guardian/c7n_guardian/cli.py | report | def report(config, tags, accounts, master, debug, region):
"""report on guard duty enablement by account"""
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
session = get_session(
master_info.get('role'), 'c7n-guardian',
master_info.get(... | python | def report(config, tags, accounts, master, debug, region):
"""report on guard duty enablement by account"""
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
session = get_session(
master_info.get('role'), 'c7n-guardian',
master_info.get(... | [
"def",
"report",
"(",
"config",
",",
"tags",
",",
"accounts",
",",
"master",
",",
"debug",
",",
"region",
")",
":",
"accounts_config",
",",
"master_info",
",",
"executor",
"=",
"guardian_init",
"(",
"config",
",",
"debug",
",",
"master",
",",
"accounts",
... | report on guard duty enablement by account | [
"report",
"on",
"guard",
"duty",
"enablement",
"by",
"account"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_guardian/c7n_guardian/cli.py#L52-L88 | train |
cloud-custodian/cloud-custodian | tools/c7n_guardian/c7n_guardian/cli.py | disable | def disable(config, tags, accounts, master, debug,
suspend, disable_detector, delete_detector, dissociate, region):
"""suspend guard duty in the given accounts."""
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
if sum(map(int, (suspend, di... | python | def disable(config, tags, accounts, master, debug,
suspend, disable_detector, delete_detector, dissociate, region):
"""suspend guard duty in the given accounts."""
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
if sum(map(int, (suspend, di... | [
"def",
"disable",
"(",
"config",
",",
"tags",
",",
"accounts",
",",
"master",
",",
"debug",
",",
"suspend",
",",
"disable_detector",
",",
"delete_detector",
",",
"dissociate",
",",
"region",
")",
":",
"accounts_config",
",",
"master_info",
",",
"executor",
"... | suspend guard duty in the given accounts. | [
"suspend",
"guard",
"duty",
"in",
"the",
"given",
"accounts",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_guardian/c7n_guardian/cli.py#L106-L167 | train |
cloud-custodian/cloud-custodian | tools/c7n_guardian/c7n_guardian/cli.py | enable | def enable(config, master, tags, accounts, debug, message, region):
"""enable guard duty on a set of accounts"""
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
regions = expand_regions(region)
for r in regions:
log.info("Processing Region:%... | python | def enable(config, master, tags, accounts, debug, message, region):
"""enable guard duty on a set of accounts"""
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
regions = expand_regions(region)
for r in regions:
log.info("Processing Region:%... | [
"def",
"enable",
"(",
"config",
",",
"master",
",",
"tags",
",",
"accounts",
",",
"debug",
",",
"message",
",",
"region",
")",
":",
"accounts_config",
",",
"master_info",
",",
"executor",
"=",
"guardian_init",
"(",
"config",
",",
"debug",
",",
"master",
... | enable guard duty on a set of accounts | [
"enable",
"guard",
"duty",
"on",
"a",
"set",
"of",
"accounts"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_guardian/c7n_guardian/cli.py#L195-L202 | train |
cloud-custodian/cloud-custodian | c7n/actions/network.py | ModifyVpcSecurityGroupsAction.get_action_group_names | def get_action_group_names(self):
"""Return all the security group names configured in this action."""
return self.get_group_names(
list(itertools.chain(
*[self._get_array('add'),
self._get_array('remove'),
self._get_array('isolation-group'... | python | def get_action_group_names(self):
"""Return all the security group names configured in this action."""
return self.get_group_names(
list(itertools.chain(
*[self._get_array('add'),
self._get_array('remove'),
self._get_array('isolation-group'... | [
"def",
"get_action_group_names",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_group_names",
"(",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"[",
"self",
".",
"_get_array",
"(",
"'add'",
")",
",",
"self",
".",
"_get_array",
"(",
"'remove'",
"... | Return all the security group names configured in this action. | [
"Return",
"all",
"the",
"security",
"group",
"names",
"configured",
"in",
"this",
"action",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/actions/network.py#L107-L113 | train |
cloud-custodian/cloud-custodian | c7n/actions/network.py | ModifyVpcSecurityGroupsAction.get_groups_by_names | def get_groups_by_names(self, names):
"""Resolve security names to security groups resources."""
if not names:
return []
client = utils.local_session(
self.manager.session_factory).client('ec2')
sgs = self.manager.retry(
client.describe_security_groups... | python | def get_groups_by_names(self, names):
"""Resolve security names to security groups resources."""
if not names:
return []
client = utils.local_session(
self.manager.session_factory).client('ec2')
sgs = self.manager.retry(
client.describe_security_groups... | [
"def",
"get_groups_by_names",
"(",
"self",
",",
"names",
")",
":",
"if",
"not",
"names",
":",
"return",
"[",
"]",
"client",
"=",
"utils",
".",
"local_session",
"(",
"self",
".",
"manager",
".",
"session_factory",
")",
".",
"client",
"(",
"'ec2'",
")",
... | Resolve security names to security groups resources. | [
"Resolve",
"security",
"names",
"to",
"security",
"groups",
"resources",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/actions/network.py#L128-L150 | train |
cloud-custodian/cloud-custodian | c7n/actions/network.py | ModifyVpcSecurityGroupsAction.resolve_group_names | def resolve_group_names(self, r, target_group_ids, groups):
"""Resolve any security group names to the corresponding group ids
With the context of a given network attached resource.
"""
names = self.get_group_names(target_group_ids)
if not names:
return target_group_... | python | def resolve_group_names(self, r, target_group_ids, groups):
"""Resolve any security group names to the corresponding group ids
With the context of a given network attached resource.
"""
names = self.get_group_names(target_group_ids)
if not names:
return target_group_... | [
"def",
"resolve_group_names",
"(",
"self",
",",
"r",
",",
"target_group_ids",
",",
"groups",
")",
":",
"names",
"=",
"self",
".",
"get_group_names",
"(",
"target_group_ids",
")",
"if",
"not",
"names",
":",
"return",
"target_group_ids",
"target_group_ids",
"=",
... | Resolve any security group names to the corresponding group ids
With the context of a given network attached resource. | [
"Resolve",
"any",
"security",
"group",
"names",
"to",
"the",
"corresponding",
"group",
"ids"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/actions/network.py#L152-L182 | train |
cloud-custodian/cloud-custodian | c7n/actions/network.py | ModifyVpcSecurityGroupsAction.resolve_remove_symbols | def resolve_remove_symbols(self, r, target_group_ids, rgroups):
"""Resolve the resources security groups that need be modified.
Specifically handles symbolic names that match annotations from policy filters
for groups being removed.
"""
if 'matched' in target_group_ids:
... | python | def resolve_remove_symbols(self, r, target_group_ids, rgroups):
"""Resolve the resources security groups that need be modified.
Specifically handles symbolic names that match annotations from policy filters
for groups being removed.
"""
if 'matched' in target_group_ids:
... | [
"def",
"resolve_remove_symbols",
"(",
"self",
",",
"r",
",",
"target_group_ids",
",",
"rgroups",
")",
":",
"if",
"'matched'",
"in",
"target_group_ids",
":",
"return",
"r",
".",
"get",
"(",
"'c7n:matched-security-groups'",
",",
"(",
")",
")",
"elif",
"'network-... | Resolve the resources security groups that need be modified.
Specifically handles symbolic names that match annotations from policy filters
for groups being removed. | [
"Resolve",
"the",
"resources",
"security",
"groups",
"that",
"need",
"be",
"modified",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/actions/network.py#L184-L198 | train |
cloud-custodian/cloud-custodian | c7n/actions/network.py | ModifyVpcSecurityGroupsAction.get_groups | def get_groups(self, resources):
"""Return lists of security groups to set on each resource
For each input resource, parse the various add/remove/isolation-
group policies for 'modify-security-groups' to find the resulting
set of VPC security groups to attach to that resource.
... | python | def get_groups(self, resources):
"""Return lists of security groups to set on each resource
For each input resource, parse the various add/remove/isolation-
group policies for 'modify-security-groups' to find the resulting
set of VPC security groups to attach to that resource.
... | [
"def",
"get_groups",
"(",
"self",
",",
"resources",
")",
":",
"resolved_groups",
"=",
"self",
".",
"get_groups_by_names",
"(",
"self",
".",
"get_action_group_names",
"(",
")",
")",
"return_groups",
"=",
"[",
"]",
"for",
"idx",
",",
"r",
"in",
"enumerate",
... | Return lists of security groups to set on each resource
For each input resource, parse the various add/remove/isolation-
group policies for 'modify-security-groups' to find the resulting
set of VPC security groups to attach to that resource.
Returns a list of lists containing the resul... | [
"Return",
"lists",
"of",
"security",
"groups",
"to",
"set",
"on",
"each",
"resource"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/actions/network.py#L200-L241 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | type_schema | def type_schema(
type_name, inherits=None, rinherit=None,
aliases=None, required=None, **props):
"""jsonschema generation helper
params:
- type_name: name of the type
- inherits: list of document fragments that are required via anyOf[$ref]
- rinherit: use another schema as a base... | python | def type_schema(
type_name, inherits=None, rinherit=None,
aliases=None, required=None, **props):
"""jsonschema generation helper
params:
- type_name: name of the type
- inherits: list of document fragments that are required via anyOf[$ref]
- rinherit: use another schema as a base... | [
"def",
"type_schema",
"(",
"type_name",
",",
"inherits",
"=",
"None",
",",
"rinherit",
"=",
"None",
",",
"aliases",
"=",
"None",
",",
"required",
"=",
"None",
",",
"*",
"*",
"props",
")",
":",
"if",
"aliases",
":",
"type_names",
"=",
"[",
"type_name",
... | jsonschema generation helper
params:
- type_name: name of the type
- inherits: list of document fragments that are required via anyOf[$ref]
- rinherit: use another schema as a base for this, basically work around
inherits issues with additionalProperties and type enums.
- alias... | [
"jsonschema",
"generation",
"helper"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L130-L174 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | group_by | def group_by(resources, key):
"""Return a mapping of key value to resources with the corresponding value.
Key may be specified as dotted form for nested dictionary lookup
"""
resource_map = {}
parts = key.split('.')
for r in resources:
v = r
for k in parts:
v = v.get... | python | def group_by(resources, key):
"""Return a mapping of key value to resources with the corresponding value.
Key may be specified as dotted form for nested dictionary lookup
"""
resource_map = {}
parts = key.split('.')
for r in resources:
v = r
for k in parts:
v = v.get... | [
"def",
"group_by",
"(",
"resources",
",",
"key",
")",
":",
"resource_map",
"=",
"{",
"}",
"parts",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"for",
"r",
"in",
"resources",
":",
"v",
"=",
"r",
"for",
"k",
"in",
"parts",
":",
"v",
"=",
"v",
".",... | Return a mapping of key value to resources with the corresponding value.
Key may be specified as dotted form for nested dictionary lookup | [
"Return",
"a",
"mapping",
"of",
"key",
"value",
"to",
"resources",
"with",
"the",
"corresponding",
"value",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L185-L199 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | camelResource | def camelResource(obj):
"""Some sources from apis return lowerCased where as describe calls
always return TitleCase, this function turns the former to the later
"""
if not isinstance(obj, dict):
return obj
for k in list(obj.keys()):
v = obj.pop(k)
obj["%s%s" % (k[0].upper(),... | python | def camelResource(obj):
"""Some sources from apis return lowerCased where as describe calls
always return TitleCase, this function turns the former to the later
"""
if not isinstance(obj, dict):
return obj
for k in list(obj.keys()):
v = obj.pop(k)
obj["%s%s" % (k[0].upper(),... | [
"def",
"camelResource",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"obj",
"for",
"k",
"in",
"list",
"(",
"obj",
".",
"keys",
"(",
")",
")",
":",
"v",
"=",
"obj",
".",
"pop",
"(",
"k",
")",
"o... | Some sources from apis return lowerCased where as describe calls
always return TitleCase, this function turns the former to the later | [
"Some",
"sources",
"from",
"apis",
"return",
"lowerCased",
"where",
"as",
"describe",
"calls"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L214-L228 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | query_instances | def query_instances(session, client=None, **query):
"""Return a list of ec2 instances for the query.
"""
if client is None:
client = session.client('ec2')
p = client.get_paginator('describe_instances')
results = p.paginate(**query)
return list(itertools.chain(
*[r["Instances"] fo... | python | def query_instances(session, client=None, **query):
"""Return a list of ec2 instances for the query.
"""
if client is None:
client = session.client('ec2')
p = client.get_paginator('describe_instances')
results = p.paginate(**query)
return list(itertools.chain(
*[r["Instances"] fo... | [
"def",
"query_instances",
"(",
"session",
",",
"client",
"=",
"None",
",",
"*",
"*",
"query",
")",
":",
"if",
"client",
"is",
"None",
":",
"client",
"=",
"session",
".",
"client",
"(",
"'ec2'",
")",
"p",
"=",
"client",
".",
"get_paginator",
"(",
"'de... | Return a list of ec2 instances for the query. | [
"Return",
"a",
"list",
"of",
"ec2",
"instances",
"for",
"the",
"query",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L242-L251 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | local_session | def local_session(factory):
"""Cache a session thread local for up to 45m"""
factory_region = getattr(factory, 'region', 'global')
s = getattr(CONN_CACHE, factory_region, {}).get('session')
t = getattr(CONN_CACHE, factory_region, {}).get('time')
n = time.time()
if s is not None and t + (60 * 45... | python | def local_session(factory):
"""Cache a session thread local for up to 45m"""
factory_region = getattr(factory, 'region', 'global')
s = getattr(CONN_CACHE, factory_region, {}).get('session')
t = getattr(CONN_CACHE, factory_region, {}).get('time')
n = time.time()
if s is not None and t + (60 * 45... | [
"def",
"local_session",
"(",
"factory",
")",
":",
"factory_region",
"=",
"getattr",
"(",
"factory",
",",
"'region'",
",",
"'global'",
")",
"s",
"=",
"getattr",
"(",
"CONN_CACHE",
",",
"factory_region",
",",
"{",
"}",
")",
".",
"get",
"(",
"'session'",
")... | Cache a session thread local for up to 45m | [
"Cache",
"a",
"session",
"thread",
"local",
"for",
"up",
"to",
"45m"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L257-L269 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | set_annotation | def set_annotation(i, k, v):
"""
>>> x = {}
>>> set_annotation(x, 'marker', 'a')
>>> annotation(x, 'marker')
['a']
"""
if not isinstance(i, dict):
raise ValueError("Can only annotate dictionaries")
if not isinstance(v, list):
v = [v]
if k in i:
ev = i.get(k)... | python | def set_annotation(i, k, v):
"""
>>> x = {}
>>> set_annotation(x, 'marker', 'a')
>>> annotation(x, 'marker')
['a']
"""
if not isinstance(i, dict):
raise ValueError("Can only annotate dictionaries")
if not isinstance(v, list):
v = [v]
if k in i:
ev = i.get(k)... | [
"def",
"set_annotation",
"(",
"i",
",",
"k",
",",
"v",
")",
":",
"if",
"not",
"isinstance",
"(",
"i",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"Can only annotate dictionaries\"",
")",
"if",
"not",
"isinstance",
"(",
"v",
",",
"list",
")",
"... | >>> x = {}
>>> set_annotation(x, 'marker', 'a')
>>> annotation(x, 'marker')
['a'] | [
">>>",
"x",
"=",
"{}",
">>>",
"set_annotation",
"(",
"x",
"marker",
"a",
")",
">>>",
"annotation",
"(",
"x",
"marker",
")",
"[",
"a",
"]"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L281-L299 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | generate_arn | def generate_arn(
service, resource, partition='aws',
region=None, account_id=None, resource_type=None, separator='/'):
"""Generate an Amazon Resource Name.
See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html.
"""
if region and region in REGION_PARTITION_MAP:
... | python | def generate_arn(
service, resource, partition='aws',
region=None, account_id=None, resource_type=None, separator='/'):
"""Generate an Amazon Resource Name.
See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html.
"""
if region and region in REGION_PARTITION_MAP:
... | [
"def",
"generate_arn",
"(",
"service",
",",
"resource",
",",
"partition",
"=",
"'aws'",
",",
"region",
"=",
"None",
",",
"account_id",
"=",
"None",
",",
"resource_type",
"=",
"None",
",",
"separator",
"=",
"'/'",
")",
":",
"if",
"region",
"and",
"region"... | Generate an Amazon Resource Name.
See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html. | [
"Generate",
"an",
"Amazon",
"Resource",
"Name",
".",
"See",
"http",
":",
"//",
"docs",
".",
"aws",
".",
"amazon",
".",
"com",
"/",
"general",
"/",
"latest",
"/",
"gr",
"/",
"aws",
"-",
"arns",
"-",
"and",
"-",
"namespaces",
".",
"html",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L325-L341 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | snapshot_identifier | def snapshot_identifier(prefix, db_identifier):
"""Return an identifier for a snapshot of a database or cluster.
"""
now = datetime.now()
return '%s-%s-%s' % (prefix, db_identifier, now.strftime('%Y-%m-%d-%H-%M')) | python | def snapshot_identifier(prefix, db_identifier):
"""Return an identifier for a snapshot of a database or cluster.
"""
now = datetime.now()
return '%s-%s-%s' % (prefix, db_identifier, now.strftime('%Y-%m-%d-%H-%M')) | [
"def",
"snapshot_identifier",
"(",
"prefix",
",",
"db_identifier",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"return",
"'%s-%s-%s'",
"%",
"(",
"prefix",
",",
"db_identifier",
",",
"now",
".",
"strftime",
"(",
"'%Y-%m-%d-%H-%M'",
")",
")"
] | Return an identifier for a snapshot of a database or cluster. | [
"Return",
"an",
"identifier",
"for",
"a",
"snapshot",
"of",
"a",
"database",
"or",
"cluster",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L344-L348 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | get_retry | def get_retry(codes=(), max_attempts=8, min_delay=1, log_retries=False):
"""Decorator for retry boto3 api call on transient errors.
https://www.awsarchitectureblog.com/2015/03/backoff.html
https://en.wikipedia.org/wiki/Exponential_backoff
:param codes: A sequence of retryable error codes.
:param m... | python | def get_retry(codes=(), max_attempts=8, min_delay=1, log_retries=False):
"""Decorator for retry boto3 api call on transient errors.
https://www.awsarchitectureblog.com/2015/03/backoff.html
https://en.wikipedia.org/wiki/Exponential_backoff
:param codes: A sequence of retryable error codes.
:param m... | [
"def",
"get_retry",
"(",
"codes",
"=",
"(",
")",
",",
"max_attempts",
"=",
"8",
",",
"min_delay",
"=",
"1",
",",
"log_retries",
"=",
"False",
")",
":",
"max_delay",
"=",
"max",
"(",
"min_delay",
",",
"2",
")",
"**",
"max_attempts",
"def",
"_retry",
"... | Decorator for retry boto3 api call on transient errors.
https://www.awsarchitectureblog.com/2015/03/backoff.html
https://en.wikipedia.org/wiki/Exponential_backoff
:param codes: A sequence of retryable error codes.
:param max_attempts: The max number of retries, by default the delay
time is ... | [
"Decorator",
"for",
"retry",
"boto3",
"api",
"call",
"on",
"transient",
"errors",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L351-L387 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | backoff_delays | def backoff_delays(start, stop, factor=2.0, jitter=False):
"""Geometric backoff sequence w/ jitter
"""
cur = start
while cur <= stop:
if jitter:
yield cur - (cur * random.random())
else:
yield cur
cur = cur * factor | python | def backoff_delays(start, stop, factor=2.0, jitter=False):
"""Geometric backoff sequence w/ jitter
"""
cur = start
while cur <= stop:
if jitter:
yield cur - (cur * random.random())
else:
yield cur
cur = cur * factor | [
"def",
"backoff_delays",
"(",
"start",
",",
"stop",
",",
"factor",
"=",
"2.0",
",",
"jitter",
"=",
"False",
")",
":",
"cur",
"=",
"start",
"while",
"cur",
"<=",
"stop",
":",
"if",
"jitter",
":",
"yield",
"cur",
"-",
"(",
"cur",
"*",
"random",
".",
... | Geometric backoff sequence w/ jitter | [
"Geometric",
"backoff",
"sequence",
"w",
"/",
"jitter"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L390-L399 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | parse_cidr | def parse_cidr(value):
"""Process cidr ranges."""
klass = IPv4Network
if '/' not in value:
klass = ipaddress.ip_address
try:
v = klass(six.text_type(value))
except (ipaddress.AddressValueError, ValueError):
v = None
return v | python | def parse_cidr(value):
"""Process cidr ranges."""
klass = IPv4Network
if '/' not in value:
klass = ipaddress.ip_address
try:
v = klass(six.text_type(value))
except (ipaddress.AddressValueError, ValueError):
v = None
return v | [
"def",
"parse_cidr",
"(",
"value",
")",
":",
"klass",
"=",
"IPv4Network",
"if",
"'/'",
"not",
"in",
"value",
":",
"klass",
"=",
"ipaddress",
".",
"ip_address",
"try",
":",
"v",
"=",
"klass",
"(",
"six",
".",
"text_type",
"(",
"value",
")",
")",
"exce... | Process cidr ranges. | [
"Process",
"cidr",
"ranges",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L402-L411 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | worker | def worker(f):
"""Generic wrapper to log uncaught exceptions in a function.
When we cross concurrent.futures executor boundaries we lose our
traceback information, and when doing bulk operations we may tolerate
transient failures on a partial subset. However we still want to have
full accounting of... | python | def worker(f):
"""Generic wrapper to log uncaught exceptions in a function.
When we cross concurrent.futures executor boundaries we lose our
traceback information, and when doing bulk operations we may tolerate
transient failures on a partial subset. However we still want to have
full accounting of... | [
"def",
"worker",
"(",
"f",
")",
":",
"def",
"_f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"except",
"Exception",
":",
"worker_log",
".",
"exception",
"(",
"'Error i... | Generic wrapper to log uncaught exceptions in a function.
When we cross concurrent.futures executor boundaries we lose our
traceback information, and when doing bulk operations we may tolerate
transient failures on a partial subset. However we still want to have
full accounting of the error in the logs... | [
"Generic",
"wrapper",
"to",
"log",
"uncaught",
"exceptions",
"in",
"a",
"function",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L428-L446 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | reformat_schema | def reformat_schema(model):
""" Reformat schema to be in a more displayable format. """
if not hasattr(model, 'schema'):
return "Model '{}' does not have a schema".format(model)
if 'properties' not in model.schema:
return "Schema in unexpected format."
ret = copy.deepcopy(model.schema[... | python | def reformat_schema(model):
""" Reformat schema to be in a more displayable format. """
if not hasattr(model, 'schema'):
return "Model '{}' does not have a schema".format(model)
if 'properties' not in model.schema:
return "Schema in unexpected format."
ret = copy.deepcopy(model.schema[... | [
"def",
"reformat_schema",
"(",
"model",
")",
":",
"if",
"not",
"hasattr",
"(",
"model",
",",
"'schema'",
")",
":",
"return",
"\"Model '{}' does not have a schema\"",
".",
"format",
"(",
"model",
")",
"if",
"'properties'",
"not",
"in",
"model",
".",
"schema",
... | Reformat schema to be in a more displayable format. | [
"Reformat",
"schema",
"to",
"be",
"in",
"a",
"more",
"displayable",
"format",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L449-L466 | train |
cloud-custodian/cloud-custodian | c7n/utils.py | format_string_values | def format_string_values(obj, err_fallback=(IndexError, KeyError), *args, **kwargs):
"""
Format all string values in an object.
Return the updated object
"""
if isinstance(obj, dict):
new = {}
for key in obj.keys():
new[key] = format_string_values(obj[key], *args, **kwarg... | python | def format_string_values(obj, err_fallback=(IndexError, KeyError), *args, **kwargs):
"""
Format all string values in an object.
Return the updated object
"""
if isinstance(obj, dict):
new = {}
for key in obj.keys():
new[key] = format_string_values(obj[key], *args, **kwarg... | [
"def",
"format_string_values",
"(",
"obj",
",",
"err_fallback",
"=",
"(",
"IndexError",
",",
"KeyError",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"new",
"=",
"{",
"}",
"for",
"... | Format all string values in an object.
Return the updated object | [
"Format",
"all",
"string",
"values",
"in",
"an",
"object",
".",
"Return",
"the",
"updated",
"object"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/utils.py#L501-L522 | train |
cloud-custodian/cloud-custodian | c7n/resources/dynamodb.py | DescribeDaxCluster.get_resources | def get_resources(self, ids, cache=True):
"""Retrieve dax resources for serverless policies or related resources
"""
client = local_session(self.manager.session_factory).client('dax')
return client.describe_clusters(ClusterNames=ids).get('Clusters') | python | def get_resources(self, ids, cache=True):
"""Retrieve dax resources for serverless policies or related resources
"""
client = local_session(self.manager.session_factory).client('dax')
return client.describe_clusters(ClusterNames=ids).get('Clusters') | [
"def",
"get_resources",
"(",
"self",
",",
"ids",
",",
"cache",
"=",
"True",
")",
":",
"client",
"=",
"local_session",
"(",
"self",
".",
"manager",
".",
"session_factory",
")",
".",
"client",
"(",
"'dax'",
")",
"return",
"client",
".",
"describe_clusters",
... | Retrieve dax resources for serverless policies or related resources | [
"Retrieve",
"dax",
"resources",
"for",
"serverless",
"policies",
"or",
"related",
"resources"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/dynamodb.py#L435-L439 | train |
cloud-custodian/cloud-custodian | tools/c7n_org/scripts/gcpprojects.py | main | def main(output):
"""
Generate a c7n-org gcp projects config file
"""
client = Session().client('cloudresourcemanager', 'v1', 'projects')
results = []
for page in client.execute_paged_query('list', {}):
for project in page.get('projects', []):
if project['lifecycleState'] ... | python | def main(output):
"""
Generate a c7n-org gcp projects config file
"""
client = Session().client('cloudresourcemanager', 'v1', 'projects')
results = []
for page in client.execute_paged_query('list', {}):
for project in page.get('projects', []):
if project['lifecycleState'] ... | [
"def",
"main",
"(",
"output",
")",
":",
"client",
"=",
"Session",
"(",
")",
".",
"client",
"(",
"'cloudresourcemanager'",
",",
"'v1'",
",",
"'projects'",
")",
"results",
"=",
"[",
"]",
"for",
"page",
"in",
"client",
".",
"execute_paged_query",
"(",
"'lis... | Generate a c7n-org gcp projects config file | [
"Generate",
"a",
"c7n",
"-",
"org",
"gcp",
"projects",
"config",
"file"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_org/scripts/gcpprojects.py#L27-L52 | train |
cloud-custodian/cloud-custodian | tools/c7n_azure/c7n_azure/query.py | ChildResourceQuery.filter | def filter(self, resource_manager, **params):
"""Query a set of resources."""
m = self.resolve(resource_manager.resource_type)
client = resource_manager.get_client()
enum_op, list_op, extra_args = m.enum_spec
parent_type, annotate_parent = m.parent_spec
parents = self.m... | python | def filter(self, resource_manager, **params):
"""Query a set of resources."""
m = self.resolve(resource_manager.resource_type)
client = resource_manager.get_client()
enum_op, list_op, extra_args = m.enum_spec
parent_type, annotate_parent = m.parent_spec
parents = self.m... | [
"def",
"filter",
"(",
"self",
",",
"resource_manager",
",",
"*",
"*",
"params",
")",
":",
"m",
"=",
"self",
".",
"resolve",
"(",
"resource_manager",
".",
"resource_type",
")",
"client",
"=",
"resource_manager",
".",
"get_client",
"(",
")",
"enum_op",
",",
... | Query a set of resources. | [
"Query",
"a",
"set",
"of",
"resources",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_azure/c7n_azure/query.py#L81-L106 | train |
cloud-custodian/cloud-custodian | c7n/filters/multiattr.py | MultiAttrFilter.get_attr_filters | def get_attr_filters(self):
"""Return an iterator resource attribute filters configured.
"""
for f in self.data.keys():
if f not in self.multi_attrs:
continue
fv = self.data[f]
if isinstance(fv, dict):
fv['key'] = f
... | python | def get_attr_filters(self):
"""Return an iterator resource attribute filters configured.
"""
for f in self.data.keys():
if f not in self.multi_attrs:
continue
fv = self.data[f]
if isinstance(fv, dict):
fv['key'] = f
... | [
"def",
"get_attr_filters",
"(",
"self",
")",
":",
"for",
"f",
"in",
"self",
".",
"data",
".",
"keys",
"(",
")",
":",
"if",
"f",
"not",
"in",
"self",
".",
"multi_attrs",
":",
"continue",
"fv",
"=",
"self",
".",
"data",
"[",
"f",
"]",
"if",
"isinst... | Return an iterator resource attribute filters configured. | [
"Return",
"an",
"iterator",
"resource",
"attribute",
"filters",
"configured",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/multiattr.py#L48-L61 | train |
cloud-custodian/cloud-custodian | c7n/resources/account.py | cloudtrail_policy | def cloudtrail_policy(original, bucket_name, account_id, bucket_region):
'''add CloudTrail permissions to an S3 policy, preserving existing'''
ct_actions = [
{
'Action': 's3:GetBucketAcl',
'Effect': 'Allow',
'Principal': {'Service': 'cloudtrail.amazonaws.com'},
... | python | def cloudtrail_policy(original, bucket_name, account_id, bucket_region):
'''add CloudTrail permissions to an S3 policy, preserving existing'''
ct_actions = [
{
'Action': 's3:GetBucketAcl',
'Effect': 'Allow',
'Principal': {'Service': 'cloudtrail.amazonaws.com'},
... | [
"def",
"cloudtrail_policy",
"(",
"original",
",",
"bucket_name",
",",
"account_id",
",",
"bucket_region",
")",
":",
"ct_actions",
"=",
"[",
"{",
"'Action'",
":",
"'s3:GetBucketAcl'",
",",
"'Effect'",
":",
"'Allow'",
",",
"'Principal'",
":",
"{",
"'Service'",
"... | add CloudTrail permissions to an S3 policy, preserving existing | [
"add",
"CloudTrail",
"permissions",
"to",
"an",
"S3",
"policy",
"preserving",
"existing"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/account.py#L654-L690 | train |
cloud-custodian/cloud-custodian | c7n/resources/rds.py | _get_available_engine_upgrades | def _get_available_engine_upgrades(client, major=False):
"""Returns all extant rds engine upgrades.
As a nested mapping of engine type to known versions
and their upgrades.
Defaults to minor upgrades, but configurable to major.
Example::
>>> _get_engine_upgrades(client)
{
'o... | python | def _get_available_engine_upgrades(client, major=False):
"""Returns all extant rds engine upgrades.
As a nested mapping of engine type to known versions
and their upgrades.
Defaults to minor upgrades, but configurable to major.
Example::
>>> _get_engine_upgrades(client)
{
'o... | [
"def",
"_get_available_engine_upgrades",
"(",
"client",
",",
"major",
"=",
"False",
")",
":",
"results",
"=",
"{",
"}",
"engine_versions",
"=",
"client",
".",
"describe_db_engine_versions",
"(",
")",
"[",
"'DBEngineVersions'",
"]",
"for",
"v",
"in",
"engine_vers... | Returns all extant rds engine upgrades.
As a nested mapping of engine type to known versions
and their upgrades.
Defaults to minor upgrades, but configurable to major.
Example::
>>> _get_engine_upgrades(client)
{
'oracle-se2': {'12.1.0.2.v2': '12.1.0.2.v5',
... | [
"Returns",
"all",
"extant",
"rds",
"engine",
"upgrades",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/rds.py#L224-L257 | train |
cloud-custodian/cloud-custodian | c7n/handler.py | get_local_output_dir | def get_local_output_dir():
"""Create a local output directory per execution.
We've seen occassional (1/100000) perm issues with lambda on temp
directory and changing unix execution users (2015-2018), so use a
per execution temp space. With firecracker lambdas this may be outdated.
"""
output_d... | python | def get_local_output_dir():
"""Create a local output directory per execution.
We've seen occassional (1/100000) perm issues with lambda on temp
directory and changing unix execution users (2015-2018), so use a
per execution temp space. With firecracker lambdas this may be outdated.
"""
output_d... | [
"def",
"get_local_output_dir",
"(",
")",
":",
"output_dir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'C7N_OUTPUT_DIR'",
",",
"'/tmp/'",
"+",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",... | Create a local output directory per execution.
We've seen occassional (1/100000) perm issues with lambda on temp
directory and changing unix execution users (2015-2018), so use a
per execution temp space. With firecracker lambdas this may be outdated. | [
"Create",
"a",
"local",
"output",
"directory",
"per",
"execution",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/handler.py#L65-L78 | train |
cloud-custodian/cloud-custodian | c7n/handler.py | init_config | def init_config(policy_config):
"""Get policy lambda execution configuration.
cli parameters are serialized into the policy lambda config,
we merge those with any policy specific execution options.
--assume role and -s output directory get special handling, as
to disambiguate any cli context.
... | python | def init_config(policy_config):
"""Get policy lambda execution configuration.
cli parameters are serialized into the policy lambda config,
we merge those with any policy specific execution options.
--assume role and -s output directory get special handling, as
to disambiguate any cli context.
... | [
"def",
"init_config",
"(",
"policy_config",
")",
":",
"global",
"account_id",
"exec_options",
"=",
"policy_config",
".",
"get",
"(",
"'execution-options'",
",",
"{",
"}",
")",
"# Remove some configuration options that don't make sense to translate from",
"# cli to lambda auto... | Get policy lambda execution configuration.
cli parameters are serialized into the policy lambda config,
we merge those with any policy specific execution options.
--assume role and -s output directory get special handling, as
to disambiguate any cli context.
account id is sourced from the config ... | [
"Get",
"policy",
"lambda",
"execution",
"configuration",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/handler.py#L81-L137 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.