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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
pandas-profiling/pandas-profiling | pandas_profiling/plot.py | mini_histogram | def mini_histogram(series, **kwargs):
"""Plot a small (mini) histogram of the data.
Parameters
----------
series: Series
The data to plot.
Returns
-------
str
The resulting image encoded as a string.
"""
imgdata = BytesIO()
plot = _plot_histogram(series, figsize... | python | def mini_histogram(series, **kwargs):
"""Plot a small (mini) histogram of the data.
Parameters
----------
series: Series
The data to plot.
Returns
-------
str
The resulting image encoded as a string.
"""
imgdata = BytesIO()
plot = _plot_histogram(series, figsize... | [
"def",
"mini_histogram",
"(",
"series",
",",
"*",
"*",
"kwargs",
")",
":",
"imgdata",
"=",
"BytesIO",
"(",
")",
"plot",
"=",
"_plot_histogram",
"(",
"series",
",",
"figsize",
"=",
"(",
"2",
",",
"0.75",
")",
",",
"*",
"*",
"kwargs",
")",
"plot",
".... | Plot a small (mini) histogram of the data.
Parameters
----------
series: Series
The data to plot.
Returns
-------
str
The resulting image encoded as a string. | [
"Plot",
"a",
"small",
"(",
"mini",
")",
"histogram",
"of",
"the",
"data",
"."
] | 003d236daee8b7aca39c62708b18d59bced0bc03 | https://github.com/pandas-profiling/pandas-profiling/blob/003d236daee8b7aca39c62708b18d59bced0bc03/pandas_profiling/plot.py#L83-L116 | train |
pandas-profiling/pandas-profiling | pandas_profiling/plot.py | correlation_matrix | def correlation_matrix(corrdf, title, **kwargs):
"""Plot image of a matrix correlation.
Parameters
----------
corrdf: DataFrame
The matrix correlation to plot.
title: str
The matrix title
Returns
-------
str, The resulting image encoded as a string.
"""
imgdata = ... | python | def correlation_matrix(corrdf, title, **kwargs):
"""Plot image of a matrix correlation.
Parameters
----------
corrdf: DataFrame
The matrix correlation to plot.
title: str
The matrix title
Returns
-------
str, The resulting image encoded as a string.
"""
imgdata = ... | [
"def",
"correlation_matrix",
"(",
"corrdf",
",",
"title",
",",
"*",
"*",
"kwargs",
")",
":",
"imgdata",
"=",
"BytesIO",
"(",
")",
"fig_cor",
",",
"axes_cor",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
")",
"labels",
"=",
"corrdf",
".",
"columns... | Plot image of a matrix correlation.
Parameters
----------
corrdf: DataFrame
The matrix correlation to plot.
title: str
The matrix title
Returns
-------
str, The resulting image encoded as a string. | [
"Plot",
"image",
"of",
"a",
"matrix",
"correlation",
".",
"Parameters",
"----------",
"corrdf",
":",
"DataFrame",
"The",
"matrix",
"correlation",
"to",
"plot",
".",
"title",
":",
"str",
"The",
"matrix",
"title",
"Returns",
"-------",
"str",
"The",
"resulting",... | 003d236daee8b7aca39c62708b18d59bced0bc03 | https://github.com/pandas-profiling/pandas-profiling/blob/003d236daee8b7aca39c62708b18d59bced0bc03/pandas_profiling/plot.py#L118-L145 | train |
pandas-profiling/pandas-profiling | pandas_profiling/base.py | get_groupby_statistic | def get_groupby_statistic(data):
"""Calculate value counts and distinct count of a variable (technically a Series).
The result is cached by column name in a global variable to avoid recomputing.
Parameters
----------
data : Series
The data type of the Series.
Returns
-------
l... | python | def get_groupby_statistic(data):
"""Calculate value counts and distinct count of a variable (technically a Series).
The result is cached by column name in a global variable to avoid recomputing.
Parameters
----------
data : Series
The data type of the Series.
Returns
-------
l... | [
"def",
"get_groupby_statistic",
"(",
"data",
")",
":",
"if",
"data",
".",
"name",
"is",
"not",
"None",
"and",
"data",
".",
"name",
"in",
"_VALUE_COUNTS_MEMO",
":",
"return",
"_VALUE_COUNTS_MEMO",
"[",
"data",
".",
"name",
"]",
"value_counts_with_nan",
"=",
"... | Calculate value counts and distinct count of a variable (technically a Series).
The result is cached by column name in a global variable to avoid recomputing.
Parameters
----------
data : Series
The data type of the Series.
Returns
-------
list
value count and distinct cou... | [
"Calculate",
"value",
"counts",
"and",
"distinct",
"count",
"of",
"a",
"variable",
"(",
"technically",
"a",
"Series",
")",
"."
] | 003d236daee8b7aca39c62708b18d59bced0bc03 | https://github.com/pandas-profiling/pandas-profiling/blob/003d236daee8b7aca39c62708b18d59bced0bc03/pandas_profiling/base.py#L29-L60 | train |
pandas-profiling/pandas-profiling | pandas_profiling/base.py | get_vartype | def get_vartype(data):
"""Infer the type of a variable (technically a Series).
The types supported are split in standard types and special types.
Standard types:
* Categorical (`TYPE_CAT`): the default type if no other one can be determined
* Numerical (`TYPE_NUM`): if it contains numbers
... | python | def get_vartype(data):
"""Infer the type of a variable (technically a Series).
The types supported are split in standard types and special types.
Standard types:
* Categorical (`TYPE_CAT`): the default type if no other one can be determined
* Numerical (`TYPE_NUM`): if it contains numbers
... | [
"def",
"get_vartype",
"(",
"data",
")",
":",
"if",
"data",
".",
"name",
"is",
"not",
"None",
"and",
"data",
".",
"name",
"in",
"_MEMO",
":",
"return",
"_MEMO",
"[",
"data",
".",
"name",
"]",
"vartype",
"=",
"None",
"try",
":",
"distinct_count",
"=",
... | Infer the type of a variable (technically a Series).
The types supported are split in standard types and special types.
Standard types:
* Categorical (`TYPE_CAT`): the default type if no other one can be determined
* Numerical (`TYPE_NUM`): if it contains numbers
* Boolean (`TYPE_BOOL`... | [
"Infer",
"the",
"type",
"of",
"a",
"variable",
"(",
"technically",
"a",
"Series",
")",
"."
] | 003d236daee8b7aca39c62708b18d59bced0bc03 | https://github.com/pandas-profiling/pandas-profiling/blob/003d236daee8b7aca39c62708b18d59bced0bc03/pandas_profiling/base.py#L63-L123 | train |
cloud-custodian/cloud-custodian | c7n/filters/core.py | FilterRegistry.factory | def factory(self, data, manager=None):
"""Factory func for filters.
data - policy config for filters
manager - resource type manager (ec2, s3, etc)
"""
# Make the syntax a little nicer for common cases.
if isinstance(data, dict) and len(data) == 1 and 'type' not in data... | python | def factory(self, data, manager=None):
"""Factory func for filters.
data - policy config for filters
manager - resource type manager (ec2, s3, etc)
"""
# Make the syntax a little nicer for common cases.
if isinstance(data, dict) and len(data) == 1 and 'type' not in data... | [
"def",
"factory",
"(",
"self",
",",
"data",
",",
"manager",
"=",
"None",
")",
":",
"# Make the syntax a little nicer for common cases.",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
"and",
"len",
"(",
"data",
")",
"==",
"1",
"and",
"'type'",
"not",
"... | Factory func for filters.
data - policy config for filters
manager - resource type manager (ec2, s3, etc) | [
"Factory",
"func",
"for",
"filters",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/core.py#L132-L164 | train |
cloud-custodian/cloud-custodian | c7n/filters/core.py | Filter.get_block_operator | def get_block_operator(self):
"""Determine the immediate parent boolean operator for a filter"""
# Top level operator is `and`
block_stack = ['and']
for f in self.manager.iter_filters(block_end=True):
if f is None:
block_stack.pop()
continue
... | python | def get_block_operator(self):
"""Determine the immediate parent boolean operator for a filter"""
# Top level operator is `and`
block_stack = ['and']
for f in self.manager.iter_filters(block_end=True):
if f is None:
block_stack.pop()
continue
... | [
"def",
"get_block_operator",
"(",
"self",
")",
":",
"# Top level operator is `and`",
"block_stack",
"=",
"[",
"'and'",
"]",
"for",
"f",
"in",
"self",
".",
"manager",
".",
"iter_filters",
"(",
"block_end",
"=",
"True",
")",
":",
"if",
"f",
"is",
"None",
":"... | Determine the immediate parent boolean operator for a filter | [
"Determine",
"the",
"immediate",
"parent",
"boolean",
"operator",
"for",
"a",
"filter"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/core.py#L198-L210 | train |
cloud-custodian/cloud-custodian | c7n/filters/core.py | ValueFilter._validate_resource_count | def _validate_resource_count(self):
""" Specific validation for `resource_count` type
The `resource_count` type works a little differently because it operates
on the entire set of resources. It:
- does not require `key`
- `value` must be a number
- supports a subs... | python | def _validate_resource_count(self):
""" Specific validation for `resource_count` type
The `resource_count` type works a little differently because it operates
on the entire set of resources. It:
- does not require `key`
- `value` must be a number
- supports a subs... | [
"def",
"_validate_resource_count",
"(",
"self",
")",
":",
"for",
"field",
"in",
"(",
"'op'",
",",
"'value'",
")",
":",
"if",
"field",
"not",
"in",
"self",
".",
"data",
":",
"raise",
"PolicyValidationError",
"(",
"\"Missing '%s' in value filter %s\"",
"%",
"(",... | Specific validation for `resource_count` type
The `resource_count` type works a little differently because it operates
on the entire set of resources. It:
- does not require `key`
- `value` must be a number
- supports a subset of the OPERATORS list | [
"Specific",
"validation",
"for",
"resource_count",
"type"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/core.py#L387-L411 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/inventory.py | load_manifest_file | def load_manifest_file(client, bucket, schema, versioned, ifilters, key_info):
"""Given an inventory csv file, return an iterator over keys
"""
# To avoid thundering herd downloads, we do an immediate yield for
# interspersed i/o
yield None
# Inline these values to avoid the local var lookup, t... | python | def load_manifest_file(client, bucket, schema, versioned, ifilters, key_info):
"""Given an inventory csv file, return an iterator over keys
"""
# To avoid thundering herd downloads, we do an immediate yield for
# interspersed i/o
yield None
# Inline these values to avoid the local var lookup, t... | [
"def",
"load_manifest_file",
"(",
"client",
",",
"bucket",
",",
"schema",
",",
"versioned",
",",
"ifilters",
",",
"key_info",
")",
":",
"# To avoid thundering herd downloads, we do an immediate yield for",
"# interspersed i/o",
"yield",
"None",
"# Inline these values to avoid... | Given an inventory csv file, return an iterator over keys | [
"Given",
"an",
"inventory",
"csv",
"file",
"return",
"an",
"iterator",
"over",
"keys"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/inventory.py#L32-L62 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/inventory.py | load_bucket_inventory | def load_bucket_inventory(
client, inventory_bucket, inventory_prefix, versioned, ifilters):
"""Given an inventory location for a bucket, return an iterator over keys
on the most recent delivered manifest.
"""
now = datetime.datetime.now()
key_prefix = "%s/%s" % (inventory_prefix, now.strft... | python | def load_bucket_inventory(
client, inventory_bucket, inventory_prefix, versioned, ifilters):
"""Given an inventory location for a bucket, return an iterator over keys
on the most recent delivered manifest.
"""
now = datetime.datetime.now()
key_prefix = "%s/%s" % (inventory_prefix, now.strft... | [
"def",
"load_bucket_inventory",
"(",
"client",
",",
"inventory_bucket",
",",
"inventory_prefix",
",",
"versioned",
",",
"ifilters",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"key_prefix",
"=",
"\"%s/%s\"",
"%",
"(",
"inventory_pr... | Given an inventory location for a bucket, return an iterator over keys
on the most recent delivered manifest. | [
"Given",
"an",
"inventory",
"location",
"for",
"a",
"bucket",
"return",
"an",
"iterator",
"over",
"keys"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/inventory.py#L75-L102 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/inventory.py | random_chain | def random_chain(generators):
"""Generator to generate a set of keys from
from a set of generators, each generator is selected
at random and consumed to exhaustion.
"""
while generators:
g = random.choice(generators)
try:
v = g.next()
if v is None:
... | python | def random_chain(generators):
"""Generator to generate a set of keys from
from a set of generators, each generator is selected
at random and consumed to exhaustion.
"""
while generators:
g = random.choice(generators)
try:
v = g.next()
if v is None:
... | [
"def",
"random_chain",
"(",
"generators",
")",
":",
"while",
"generators",
":",
"g",
"=",
"random",
".",
"choice",
"(",
"generators",
")",
"try",
":",
"v",
"=",
"g",
".",
"next",
"(",
")",
"if",
"v",
"is",
"None",
":",
"continue",
"yield",
"v",
"ex... | Generator to generate a set of keys from
from a set of generators, each generator is selected
at random and consumed to exhaustion. | [
"Generator",
"to",
"generate",
"a",
"set",
"of",
"keys",
"from",
"from",
"a",
"set",
"of",
"generators",
"each",
"generator",
"is",
"selected",
"at",
"random",
"and",
"consumed",
"to",
"exhaustion",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/inventory.py#L105-L118 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/inventory.py | get_bucket_inventory | def get_bucket_inventory(client, bucket, inventory_id):
"""Check a bucket for a named inventory, and return the destination."""
inventories = client.list_bucket_inventory_configurations(
Bucket=bucket).get('InventoryConfigurationList', [])
inventories = {i['Id']: i for i in inventories}
found = ... | python | def get_bucket_inventory(client, bucket, inventory_id):
"""Check a bucket for a named inventory, and return the destination."""
inventories = client.list_bucket_inventory_configurations(
Bucket=bucket).get('InventoryConfigurationList', [])
inventories = {i['Id']: i for i in inventories}
found = ... | [
"def",
"get_bucket_inventory",
"(",
"client",
",",
"bucket",
",",
"inventory_id",
")",
":",
"inventories",
"=",
"client",
".",
"list_bucket_inventory_configurations",
"(",
"Bucket",
"=",
"bucket",
")",
".",
"get",
"(",
"'InventoryConfigurationList'",
",",
"[",
"]"... | Check a bucket for a named inventory, and return the destination. | [
"Check",
"a",
"bucket",
"for",
"a",
"named",
"inventory",
"and",
"return",
"the",
"destination",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/inventory.py#L121-L133 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_autodoc/c7n-autodoc.py | create_html_file | def create_html_file(config):
""" You can customize the automated documentation by altering
the code directly in this script or the associated jinja2 template
"""
logging.debug("Starting create_html_file")
logging.debug(
"\tjinja2_template_file = {}"
.format(config['jinja2_templa... | python | def create_html_file(config):
""" You can customize the automated documentation by altering
the code directly in this script or the associated jinja2 template
"""
logging.debug("Starting create_html_file")
logging.debug(
"\tjinja2_template_file = {}"
.format(config['jinja2_templa... | [
"def",
"create_html_file",
"(",
"config",
")",
":",
"logging",
".",
"debug",
"(",
"\"Starting create_html_file\"",
")",
"logging",
".",
"debug",
"(",
"\"\\tjinja2_template_file = {}\"",
".",
"format",
"(",
"config",
"[",
"'jinja2_template_filename'",
"]",
")",
")",
... | You can customize the automated documentation by altering
the code directly in this script or the associated jinja2 template | [
"You",
"can",
"customize",
"the",
"automated",
"documentation",
"by",
"altering",
"the",
"code",
"directly",
"in",
"this",
"script",
"or",
"the",
"associated",
"jinja2",
"template"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_autodoc/c7n-autodoc.py#L28-L65 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_autodoc/c7n-autodoc.py | get_file_url | def get_file_url(path, config):
""" Update this function to help build the link to your file
"""
file_url_regex = re.compile(config['file_url_regex'])
new_path = re.sub(file_url_regex, config['file_url_base'], path)
return new_path | python | def get_file_url(path, config):
""" Update this function to help build the link to your file
"""
file_url_regex = re.compile(config['file_url_regex'])
new_path = re.sub(file_url_regex, config['file_url_base'], path)
return new_path | [
"def",
"get_file_url",
"(",
"path",
",",
"config",
")",
":",
"file_url_regex",
"=",
"re",
".",
"compile",
"(",
"config",
"[",
"'file_url_regex'",
"]",
")",
"new_path",
"=",
"re",
".",
"sub",
"(",
"file_url_regex",
",",
"config",
"[",
"'file_url_base'",
"]"... | Update this function to help build the link to your file | [
"Update",
"this",
"function",
"to",
"help",
"build",
"the",
"link",
"to",
"your",
"file"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_autodoc/c7n-autodoc.py#L68-L73 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_autodoc/c7n-autodoc.py | gather_file_data | def gather_file_data(config):
""" Gather policy information from files
"""
file_regex = re.compile(config['file_regex'])
category_regex = re.compile(config['category_regex'])
policies = {}
for root, dirs, files in os.walk(config['c7n_policy_directory']):
for file in files:
i... | python | def gather_file_data(config):
""" Gather policy information from files
"""
file_regex = re.compile(config['file_regex'])
category_regex = re.compile(config['category_regex'])
policies = {}
for root, dirs, files in os.walk(config['c7n_policy_directory']):
for file in files:
i... | [
"def",
"gather_file_data",
"(",
"config",
")",
":",
"file_regex",
"=",
"re",
".",
"compile",
"(",
"config",
"[",
"'file_regex'",
"]",
")",
"category_regex",
"=",
"re",
".",
"compile",
"(",
"config",
"[",
"'category_regex'",
"]",
")",
"policies",
"=",
"{",
... | Gather policy information from files | [
"Gather",
"policy",
"information",
"from",
"files"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_autodoc/c7n-autodoc.py#L76-L108 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_autodoc/c7n-autodoc.py | upload_to_s3 | def upload_to_s3(file_path, config):
""" Upload html file to S3
"""
logging.info("Uploading file to S3 bucket: %s", config['s3_bucket_name'])
s3 = boto3.resource('s3')
s3_filename = config['s3_bucket_path'] + config['rendered_filename']
s3.Bucket(config['s3_bucket_name']).upload_file(
fi... | python | def upload_to_s3(file_path, config):
""" Upload html file to S3
"""
logging.info("Uploading file to S3 bucket: %s", config['s3_bucket_name'])
s3 = boto3.resource('s3')
s3_filename = config['s3_bucket_path'] + config['rendered_filename']
s3.Bucket(config['s3_bucket_name']).upload_file(
fi... | [
"def",
"upload_to_s3",
"(",
"file_path",
",",
"config",
")",
":",
"logging",
".",
"info",
"(",
"\"Uploading file to S3 bucket: %s\"",
",",
"config",
"[",
"'s3_bucket_name'",
"]",
")",
"s3",
"=",
"boto3",
".",
"resource",
"(",
"'s3'",
")",
"s3_filename",
"=",
... | Upload html file to S3 | [
"Upload",
"html",
"file",
"to",
"S3"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_autodoc/c7n-autodoc.py#L111-L119 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | github_repos | def github_repos(organization, github_url, github_token):
"""Return all github repositories in an organization."""
# Get github repos
headers = {"Authorization": "token {}".format(github_token)}
next_cursor = None
while next_cursor is not False:
params = {'query': query, 'variables': {
... | python | def github_repos(organization, github_url, github_token):
"""Return all github repositories in an organization."""
# Get github repos
headers = {"Authorization": "token {}".format(github_token)}
next_cursor = None
while next_cursor is not False:
params = {'query': query, 'variables': {
... | [
"def",
"github_repos",
"(",
"organization",
",",
"github_url",
",",
"github_token",
")",
":",
"# Get github repos",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"\"token {}\"",
".",
"format",
"(",
"github_token",
")",
"}",
"next_cursor",
"=",
"None",
"while",
... | Return all github repositories in an organization. | [
"Return",
"all",
"github",
"repositories",
"in",
"an",
"organization",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L671-L696 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | org_stream | def org_stream(ctx, organization, github_url, github_token, clone_dir,
verbose, filter, exclude, stream_uri, assume):
"""Stream changes for repos in a GitHub organization.
"""
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and log... | python | def org_stream(ctx, organization, github_url, github_token, clone_dir,
verbose, filter, exclude, stream_uri, assume):
"""Stream changes for repos in a GitHub organization.
"""
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and log... | [
"def",
"org_stream",
"(",
"ctx",
",",
"organization",
",",
"github_url",
",",
"github_token",
",",
"clone_dir",
",",
"verbose",
",",
"filter",
",",
"exclude",
",",
"stream_uri",
",",
"assume",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"\... | Stream changes for repos in a GitHub organization. | [
"Stream",
"changes",
"for",
"repos",
"in",
"a",
"GitHub",
"organization",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L716-L744 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | org_checkout | def org_checkout(organization, github_url, github_token, clone_dir,
verbose, filter, exclude):
"""Checkout repositories from a GitHub organization."""
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and logging.DEBUG or logging.INFO)... | python | def org_checkout(organization, github_url, github_token, clone_dir,
verbose, filter, exclude):
"""Checkout repositories from a GitHub organization."""
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and logging.DEBUG or logging.INFO)... | [
"def",
"org_checkout",
"(",
"organization",
",",
"github_url",
",",
"github_token",
",",
"clone_dir",
",",
"verbose",
",",
"filter",
",",
"exclude",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"\"%(asctime)s: %(name)s:%(levelname)s %(message)s\"",
"... | Checkout repositories from a GitHub organization. | [
"Checkout",
"repositories",
"from",
"a",
"GitHub",
"organization",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L758-L801 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | diff | def diff(repo_uri, source, target, output, verbose):
"""Policy diff between two arbitrary revisions.
Revision specifiers for source and target can use fancy git refspec syntax
for symbolics, dates, etc.
See: https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection
Default revision selection is... | python | def diff(repo_uri, source, target, output, verbose):
"""Policy diff between two arbitrary revisions.
Revision specifiers for source and target can use fancy git refspec syntax
for symbolics, dates, etc.
See: https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection
Default revision selection is... | [
"def",
"diff",
"(",
"repo_uri",
",",
"source",
",",
"target",
",",
"output",
",",
"verbose",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"\"%(asctime)s: %(name)s:%(levelname)s %(message)s\"",
",",
"level",
"=",
"(",
"verbose",
"and",
"logging",
... | Policy diff between two arbitrary revisions.
Revision specifiers for source and target can use fancy git refspec syntax
for symbolics, dates, etc.
See: https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection
Default revision selection is dependent on current working tree
branch. The intent is... | [
"Policy",
"diff",
"between",
"two",
"arbitrary",
"revisions",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L842-L885 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | stream | def stream(repo_uri, stream_uri, verbose, assume, sort, before=None, after=None):
"""Stream git history policy changes to destination.
Default stream destination is a summary of the policy changes to stdout, one
per line. Also supported for stdout streaming is `jsonline`.
AWS Kinesis and SQS destinat... | python | def stream(repo_uri, stream_uri, verbose, assume, sort, before=None, after=None):
"""Stream git history policy changes to destination.
Default stream destination is a summary of the policy changes to stdout, one
per line. Also supported for stdout streaming is `jsonline`.
AWS Kinesis and SQS destinat... | [
"def",
"stream",
"(",
"repo_uri",
",",
"stream_uri",
",",
"verbose",
",",
"assume",
",",
"sort",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"\"%(asctime)s: %(name)s:%(levelname)s %(messag... | Stream git history policy changes to destination.
Default stream destination is a summary of the policy changes to stdout, one
per line. Also supported for stdout streaming is `jsonline`.
AWS Kinesis and SQS destinations are specified by providing the ARN.
Database destinations are supported by prov... | [
"Stream",
"git",
"history",
"policy",
"changes",
"to",
"destination",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L901-L949 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | PolicyCollection.select | def select(self, names):
"""return the named subset of policies"""
return PolicyCollection(
[p for p in self.policies if p.name in names], self.options) | python | def select(self, names):
"""return the named subset of policies"""
return PolicyCollection(
[p for p in self.policies if p.name in names], self.options) | [
"def",
"select",
"(",
"self",
",",
"names",
")",
":",
"return",
"PolicyCollection",
"(",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"policies",
"if",
"p",
".",
"name",
"in",
"names",
"]",
",",
"self",
".",
"options",
")"
] | return the named subset of policies | [
"return",
"the",
"named",
"subset",
"of",
"policies"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L220-L223 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | PolicyRepo.delta_commits | def delta_commits(self, baseline, target):
"""Show policies changes between arbitrary commits.
The common use form is comparing the heads of two branches.
"""
baseline_files = self._get_policy_fents(baseline.tree)
target_files = self._get_policy_fents(target.tree)
basel... | python | def delta_commits(self, baseline, target):
"""Show policies changes between arbitrary commits.
The common use form is comparing the heads of two branches.
"""
baseline_files = self._get_policy_fents(baseline.tree)
target_files = self._get_policy_fents(target.tree)
basel... | [
"def",
"delta_commits",
"(",
"self",
",",
"baseline",
",",
"target",
")",
":",
"baseline_files",
"=",
"self",
".",
"_get_policy_fents",
"(",
"baseline",
".",
"tree",
")",
"target_files",
"=",
"self",
".",
"_get_policy_fents",
"(",
"target",
".",
"tree",
")",... | Show policies changes between arbitrary commits.
The common use form is comparing the heads of two branches. | [
"Show",
"policies",
"changes",
"between",
"arbitrary",
"commits",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L298-L325 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | PolicyRepo.delta_stream | def delta_stream(self, target='HEAD', limit=None,
sort=pygit2.GIT_SORT_TIME | pygit2.GIT_SORT_REVERSE,
after=None, before=None):
"""Return an iterator of policy changes along a commit lineage in a repo.
"""
if target == 'HEAD':
target = self.... | python | def delta_stream(self, target='HEAD', limit=None,
sort=pygit2.GIT_SORT_TIME | pygit2.GIT_SORT_REVERSE,
after=None, before=None):
"""Return an iterator of policy changes along a commit lineage in a repo.
"""
if target == 'HEAD':
target = self.... | [
"def",
"delta_stream",
"(",
"self",
",",
"target",
"=",
"'HEAD'",
",",
"limit",
"=",
"None",
",",
"sort",
"=",
"pygit2",
".",
"GIT_SORT_TIME",
"|",
"pygit2",
".",
"GIT_SORT_REVERSE",
",",
"after",
"=",
"None",
",",
"before",
"=",
"None",
")",
":",
"if"... | Return an iterator of policy changes along a commit lineage in a repo. | [
"Return",
"an",
"iterator",
"of",
"policy",
"changes",
"along",
"a",
"commit",
"lineage",
"in",
"a",
"repo",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L327-L356 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | PolicyRepo._process_stream_delta | def _process_stream_delta(self, delta_stream):
"""Bookkeeping on internal data structures while iterating a stream."""
for pchange in delta_stream:
if pchange.kind == ChangeType.ADD:
self.policy_files.setdefault(
pchange.file_path, PolicyCollection()).add(... | python | def _process_stream_delta(self, delta_stream):
"""Bookkeeping on internal data structures while iterating a stream."""
for pchange in delta_stream:
if pchange.kind == ChangeType.ADD:
self.policy_files.setdefault(
pchange.file_path, PolicyCollection()).add(... | [
"def",
"_process_stream_delta",
"(",
"self",
",",
"delta_stream",
")",
":",
"for",
"pchange",
"in",
"delta_stream",
":",
"if",
"pchange",
".",
"kind",
"==",
"ChangeType",
".",
"ADD",
":",
"self",
".",
"policy_files",
".",
"setdefault",
"(",
"pchange",
".",
... | Bookkeeping on internal data structures while iterating a stream. | [
"Bookkeeping",
"on",
"internal",
"data",
"structures",
"while",
"iterating",
"a",
"stream",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L437-L456 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | Transport.send | def send(self, change):
"""send the given policy change"""
self.buf.append(change)
if len(self.buf) % self.BUF_SIZE == 0:
self.flush() | python | def send(self, change):
"""send the given policy change"""
self.buf.append(change)
if len(self.buf) % self.BUF_SIZE == 0:
self.flush() | [
"def",
"send",
"(",
"self",
",",
"change",
")",
":",
"self",
".",
"buf",
".",
"append",
"(",
"change",
")",
"if",
"len",
"(",
"self",
".",
"buf",
")",
"%",
"self",
".",
"BUF_SIZE",
"==",
"0",
":",
"self",
".",
"flush",
"(",
")"
] | send the given policy change | [
"send",
"the",
"given",
"policy",
"change"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L487-L491 | train |
cloud-custodian/cloud-custodian | tools/c7n_policystream/policystream.py | Transport.flush | def flush(self):
"""flush any buffered messages"""
buf = self.buf
self.buf = []
if buf:
self._flush(buf) | python | def flush(self):
"""flush any buffered messages"""
buf = self.buf
self.buf = []
if buf:
self._flush(buf) | [
"def",
"flush",
"(",
"self",
")",
":",
"buf",
"=",
"self",
".",
"buf",
"self",
".",
"buf",
"=",
"[",
"]",
"if",
"buf",
":",
"self",
".",
"_flush",
"(",
"buf",
")"
] | flush any buffered messages | [
"flush",
"any",
"buffered",
"messages"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_policystream/policystream.py#L493-L498 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/flowdeliver.py | process_firehose_archive | def process_firehose_archive(bucket, key):
"""Download firehose archive, aggregate records in memory and write back."""
data = {}
with tempfile.NamedTemporaryFile(mode='w+b') as fh:
s3.download_file(bucket, key, fh.name)
log.warning("Downloaded Key Size:%s Key:%s",
sizeof... | python | def process_firehose_archive(bucket, key):
"""Download firehose archive, aggregate records in memory and write back."""
data = {}
with tempfile.NamedTemporaryFile(mode='w+b') as fh:
s3.download_file(bucket, key, fh.name)
log.warning("Downloaded Key Size:%s Key:%s",
sizeof... | [
"def",
"process_firehose_archive",
"(",
"bucket",
",",
"key",
")",
":",
"data",
"=",
"{",
"}",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w+b'",
")",
"as",
"fh",
":",
"s3",
".",
"download_file",
"(",
"bucket",
",",
"key",
",",
"... | Download firehose archive, aggregate records in memory and write back. | [
"Download",
"firehose",
"archive",
"aggregate",
"records",
"in",
"memory",
"and",
"write",
"back",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/flowdeliver.py#L64-L93 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/flowdeliver.py | records_iter | def records_iter(fh, buffer_size=1024 * 1024 * 16):
"""Split up a firehose s3 object into records
Firehose cloudwatch log delivery of flow logs does not delimit
record boundaries. We have to use knowledge of content to split
the records on boundaries. In the context of flow logs we're
dealing with ... | python | def records_iter(fh, buffer_size=1024 * 1024 * 16):
"""Split up a firehose s3 object into records
Firehose cloudwatch log delivery of flow logs does not delimit
record boundaries. We have to use knowledge of content to split
the records on boundaries. In the context of flow logs we're
dealing with ... | [
"def",
"records_iter",
"(",
"fh",
",",
"buffer_size",
"=",
"1024",
"*",
"1024",
"*",
"16",
")",
":",
"buf",
"=",
"None",
"while",
"True",
":",
"chunk",
"=",
"fh",
".",
"read",
"(",
"buffer_size",
")",
"if",
"not",
"chunk",
":",
"if",
"buf",
":",
... | Split up a firehose s3 object into records
Firehose cloudwatch log delivery of flow logs does not delimit
record boundaries. We have to use knowledge of content to split
the records on boundaries. In the context of flow logs we're
dealing with delimited records. | [
"Split",
"up",
"a",
"firehose",
"s3",
"object",
"into",
"records"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/flowdeliver.py#L138-L164 | train |
cloud-custodian/cloud-custodian | tools/sandbox/c7n_sphere11/c7n_sphere11/controller.py | Controller.get_session | def get_session(self, account_id):
"""Get an active session in the target account."""
if account_id not in self.account_sessions:
if account_id not in self.config['accounts']:
raise AccountNotFound("account:%s is unknown" % account_id)
self.account_sessions[accou... | python | def get_session(self, account_id):
"""Get an active session in the target account."""
if account_id not in self.account_sessions:
if account_id not in self.config['accounts']:
raise AccountNotFound("account:%s is unknown" % account_id)
self.account_sessions[accou... | [
"def",
"get_session",
"(",
"self",
",",
"account_id",
")",
":",
"if",
"account_id",
"not",
"in",
"self",
".",
"account_sessions",
":",
"if",
"account_id",
"not",
"in",
"self",
".",
"config",
"[",
"'accounts'",
"]",
":",
"raise",
"AccountNotFound",
"(",
"\"... | Get an active session in the target account. | [
"Get",
"an",
"active",
"session",
"in",
"the",
"target",
"account",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/controller.py#L50-L60 | train |
cloud-custodian/cloud-custodian | c7n/schema.py | policy_error_scope | def policy_error_scope(error, data):
"""Scope a schema error to its policy name and resource."""
err_path = list(error.absolute_path)
if err_path[0] != 'policies':
return error
pdata = data['policies'][err_path[1]]
pdata.get('name', 'unknown')
error.message = "Error on policy:{} resource... | python | def policy_error_scope(error, data):
"""Scope a schema error to its policy name and resource."""
err_path = list(error.absolute_path)
if err_path[0] != 'policies':
return error
pdata = data['policies'][err_path[1]]
pdata.get('name', 'unknown')
error.message = "Error on policy:{} resource... | [
"def",
"policy_error_scope",
"(",
"error",
",",
"data",
")",
":",
"err_path",
"=",
"list",
"(",
"error",
".",
"absolute_path",
")",
"if",
"err_path",
"[",
"0",
"]",
"!=",
"'policies'",
":",
"return",
"error",
"pdata",
"=",
"data",
"[",
"'policies'",
"]",... | Scope a schema error to its policy name and resource. | [
"Scope",
"a",
"schema",
"error",
"to",
"its",
"policy",
"name",
"and",
"resource",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/schema.py#L82-L91 | train |
cloud-custodian/cloud-custodian | c7n/schema.py | specific_error | def specific_error(error):
"""Try to find the best error for humans to resolve
The jsonschema.exceptions.best_match error is based purely on a
mix of a strong match (ie. not anyOf, oneOf) and schema depth,
this often yields odd results that are semantically confusing,
instead we can use a bit of st... | python | def specific_error(error):
"""Try to find the best error for humans to resolve
The jsonschema.exceptions.best_match error is based purely on a
mix of a strong match (ie. not anyOf, oneOf) and schema depth,
this often yields odd results that are semantically confusing,
instead we can use a bit of st... | [
"def",
"specific_error",
"(",
"error",
")",
":",
"if",
"error",
".",
"validator",
"not",
"in",
"(",
"'anyOf'",
",",
"'oneOf'",
")",
":",
"return",
"error",
"r",
"=",
"t",
"=",
"None",
"if",
"isinstance",
"(",
"error",
".",
"instance",
",",
"dict",
")... | Try to find the best error for humans to resolve
The jsonschema.exceptions.best_match error is based purely on a
mix of a strong match (ie. not anyOf, oneOf) and schema depth,
this often yields odd results that are semantically confusing,
instead we can use a bit of structural knowledge of schema to
... | [
"Try",
"to",
"find",
"the",
"best",
"error",
"for",
"humans",
"to",
"resolve"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/schema.py#L94-L146 | train |
cloud-custodian/cloud-custodian | c7n/manager.py | ResourceManager.get_resource_manager | def get_resource_manager(self, resource_type, data=None):
"""get a resource manager or a given resource type.
assumes the query is for the same underlying cloud provider.
"""
if '.' in resource_type:
provider_name, resource_type = resource_type.split('.', 1)
else:
... | python | def get_resource_manager(self, resource_type, data=None):
"""get a resource manager or a given resource type.
assumes the query is for the same underlying cloud provider.
"""
if '.' in resource_type:
provider_name, resource_type = resource_type.split('.', 1)
else:
... | [
"def",
"get_resource_manager",
"(",
"self",
",",
"resource_type",
",",
"data",
"=",
"None",
")",
":",
"if",
"'.'",
"in",
"resource_type",
":",
"provider_name",
",",
"resource_type",
"=",
"resource_type",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"else",
":"... | get a resource manager or a given resource type.
assumes the query is for the same underlying cloud provider. | [
"get",
"a",
"resource",
"manager",
"or",
"a",
"given",
"resource",
"type",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/manager.py#L76-L95 | train |
cloud-custodian/cloud-custodian | c7n/resources/elasticbeanstalk.py | _eb_env_tags | def _eb_env_tags(envs, session_factory, retry):
"""Augment ElasticBeanstalk Environments with their tags."""
client = local_session(session_factory).client('elasticbeanstalk')
def process_tags(eb_env):
try:
eb_env['Tags'] = retry(
client.list_tags_for_resource,
... | python | def _eb_env_tags(envs, session_factory, retry):
"""Augment ElasticBeanstalk Environments with their tags."""
client = local_session(session_factory).client('elasticbeanstalk')
def process_tags(eb_env):
try:
eb_env['Tags'] = retry(
client.list_tags_for_resource,
... | [
"def",
"_eb_env_tags",
"(",
"envs",
",",
"session_factory",
",",
"retry",
")",
":",
"client",
"=",
"local_session",
"(",
"session_factory",
")",
".",
"client",
"(",
"'elasticbeanstalk'",
")",
"def",
"process_tags",
"(",
"eb_env",
")",
":",
"try",
":",
"eb_en... | Augment ElasticBeanstalk Environments with their tags. | [
"Augment",
"ElasticBeanstalk",
"Environments",
"with",
"their",
"tags",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/elasticbeanstalk.py#L77-L93 | train |
cloud-custodian/cloud-custodian | c7n/resources/s3.py | assemble_bucket | def assemble_bucket(item):
"""Assemble a document representing all the config state around a bucket.
TODO: Refactor this, the logic here feels quite muddled.
"""
factory, b = item
s = factory()
c = s.client('s3')
# Bucket Location, Current Client Location, Default Location
b_location = ... | python | def assemble_bucket(item):
"""Assemble a document representing all the config state around a bucket.
TODO: Refactor this, the logic here feels quite muddled.
"""
factory, b = item
s = factory()
c = s.client('s3')
# Bucket Location, Current Client Location, Default Location
b_location = ... | [
"def",
"assemble_bucket",
"(",
"item",
")",
":",
"factory",
",",
"b",
"=",
"item",
"s",
"=",
"factory",
"(",
")",
"c",
"=",
"s",
".",
"client",
"(",
"'s3'",
")",
"# Bucket Location, Current Client Location, Default Location",
"b_location",
"=",
"c_location",
"... | Assemble a document representing all the config state around a bucket.
TODO: Refactor this, the logic here feels quite muddled. | [
"Assemble",
"a",
"document",
"representing",
"all",
"the",
"config",
"state",
"around",
"a",
"bucket",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/s3.py#L406-L473 | train |
cloud-custodian/cloud-custodian | c7n/resources/s3.py | get_region | def get_region(b):
"""Tries to get the bucket region from Location.LocationConstraint
Special cases:
LocationConstraint EU defaults to eu-west-1
LocationConstraint null defaults to us-east-1
Args:
b (object): A bucket object
Returns:
string: an aws region string
""... | python | def get_region(b):
"""Tries to get the bucket region from Location.LocationConstraint
Special cases:
LocationConstraint EU defaults to eu-west-1
LocationConstraint null defaults to us-east-1
Args:
b (object): A bucket object
Returns:
string: an aws region string
""... | [
"def",
"get_region",
"(",
"b",
")",
":",
"remap",
"=",
"{",
"None",
":",
"'us-east-1'",
",",
"'EU'",
":",
"'eu-west-1'",
"}",
"region",
"=",
"b",
".",
"get",
"(",
"'Location'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'LocationConstraint'",
")",
"return... | Tries to get the bucket region from Location.LocationConstraint
Special cases:
LocationConstraint EU defaults to eu-west-1
LocationConstraint null defaults to us-east-1
Args:
b (object): A bucket object
Returns:
string: an aws region string | [
"Tries",
"to",
"get",
"the",
"bucket",
"region",
"from",
"Location",
".",
"LocationConstraint"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/s3.py#L531-L546 | train |
cloud-custodian/cloud-custodian | c7n/resources/vpc.py | SGPermission.expand_permissions | def expand_permissions(self, permissions):
"""Expand each list of cidr, prefix list, user id group pair
by port/protocol as an individual rule.
The console ux automatically expands them out as addition/removal is
per this expansion, the describe calls automatically group them.
"... | python | def expand_permissions(self, permissions):
"""Expand each list of cidr, prefix list, user id group pair
by port/protocol as an individual rule.
The console ux automatically expands them out as addition/removal is
per this expansion, the describe calls automatically group them.
"... | [
"def",
"expand_permissions",
"(",
"self",
",",
"permissions",
")",
":",
"for",
"p",
"in",
"permissions",
":",
"np",
"=",
"dict",
"(",
"p",
")",
"values",
"=",
"{",
"}",
"for",
"k",
"in",
"(",
"u'IpRanges'",
",",
"u'Ipv6Ranges'",
",",
"u'PrefixListIds'",
... | Expand each list of cidr, prefix list, user id group pair
by port/protocol as an individual rule.
The console ux automatically expands them out as addition/removal is
per this expansion, the describe calls automatically group them. | [
"Expand",
"each",
"list",
"of",
"cidr",
"prefix",
"list",
"user",
"id",
"group",
"pair",
"by",
"port",
"/",
"protocol",
"as",
"an",
"individual",
"rule",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/vpc.py#L1088-L1110 | train |
cloud-custodian/cloud-custodian | c7n/reports/csvout.py | report | def report(policies, start_date, options, output_fh, raw_output_fh=None):
"""Format a policy's extant records into a report."""
regions = set([p.options.region for p in policies])
policy_names = set([p.name for p in policies])
formatter = Formatter(
policies[0].resource_manager.resource_type,
... | python | def report(policies, start_date, options, output_fh, raw_output_fh=None):
"""Format a policy's extant records into a report."""
regions = set([p.options.region for p in policies])
policy_names = set([p.name for p in policies])
formatter = Formatter(
policies[0].resource_manager.resource_type,
... | [
"def",
"report",
"(",
"policies",
",",
"start_date",
",",
"options",
",",
"output_fh",
",",
"raw_output_fh",
"=",
"None",
")",
":",
"regions",
"=",
"set",
"(",
"[",
"p",
".",
"options",
".",
"region",
"for",
"p",
"in",
"policies",
"]",
")",
"policy_nam... | Format a policy's extant records into a report. | [
"Format",
"a",
"policy",
"s",
"extant",
"records",
"into",
"a",
"report",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/reports/csvout.py#L66-L112 | train |
cloud-custodian/cloud-custodian | c7n/reports/csvout.py | record_set | def record_set(session_factory, bucket, key_prefix, start_date, specify_hour=False):
"""Retrieve all s3 records for the given policy output url
From the given start date.
"""
s3 = local_session(session_factory).client('s3')
records = []
key_count = 0
date = start_date.strftime('%Y/%m/%d'... | python | def record_set(session_factory, bucket, key_prefix, start_date, specify_hour=False):
"""Retrieve all s3 records for the given policy output url
From the given start date.
"""
s3 = local_session(session_factory).client('s3')
records = []
key_count = 0
date = start_date.strftime('%Y/%m/%d'... | [
"def",
"record_set",
"(",
"session_factory",
",",
"bucket",
",",
"key_prefix",
",",
"start_date",
",",
"specify_hour",
"=",
"False",
")",
":",
"s3",
"=",
"local_session",
"(",
"session_factory",
")",
".",
"client",
"(",
"'s3'",
")",
"records",
"=",
"[",
"]... | Retrieve all s3 records for the given policy output url
From the given start date. | [
"Retrieve",
"all",
"s3",
"records",
"for",
"the",
"given",
"policy",
"output",
"url"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/reports/csvout.py#L238-L278 | train |
cloud-custodian/cloud-custodian | c7n/reports/csvout.py | Formatter.uniq_by_id | def uniq_by_id(self, records):
"""Only the first record for each id"""
uniq = []
keys = set()
for rec in records:
rec_id = rec[self._id_field]
if rec_id not in keys:
uniq.append(rec)
keys.add(rec_id)
return uniq | python | def uniq_by_id(self, records):
"""Only the first record for each id"""
uniq = []
keys = set()
for rec in records:
rec_id = rec[self._id_field]
if rec_id not in keys:
uniq.append(rec)
keys.add(rec_id)
return uniq | [
"def",
"uniq_by_id",
"(",
"self",
",",
"records",
")",
":",
"uniq",
"=",
"[",
"]",
"keys",
"=",
"set",
"(",
")",
"for",
"rec",
"in",
"records",
":",
"rec_id",
"=",
"rec",
"[",
"self",
".",
"_id_field",
"]",
"if",
"rec_id",
"not",
"in",
"keys",
":... | Only the first record for each id | [
"Only",
"the",
"first",
"record",
"for",
"each",
"id"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/reports/csvout.py#L192-L201 | train |
cloud-custodian/cloud-custodian | tools/ops/org-pr-monitor.py | run | def run(organization, hook_context, github_url, github_token,
verbose, metrics=False, since=None, assume=None, region=None):
"""scan org repo status hooks"""
logging.basicConfig(level=logging.DEBUG)
since = dateparser.parse(
since, settings={
'RETURN_AS_TIMEZONE_AWARE': True, 'T... | python | def run(organization, hook_context, github_url, github_token,
verbose, metrics=False, since=None, assume=None, region=None):
"""scan org repo status hooks"""
logging.basicConfig(level=logging.DEBUG)
since = dateparser.parse(
since, settings={
'RETURN_AS_TIMEZONE_AWARE': True, 'T... | [
"def",
"run",
"(",
"organization",
",",
"hook_context",
",",
"github_url",
",",
"github_token",
",",
"verbose",
",",
"metrics",
"=",
"False",
",",
"since",
"=",
"None",
",",
"assume",
"=",
"None",
",",
"region",
"=",
"None",
")",
":",
"logging",
".",
"... | scan org repo status hooks | [
"scan",
"org",
"repo",
"status",
"hooks"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/ops/org-pr-monitor.py#L143-L201 | train |
cloud-custodian/cloud-custodian | c7n/actions/notify.py | BaseNotify.expand_variables | def expand_variables(self, message):
"""expand any variables in the action to_from/cc_from fields.
"""
p = copy.deepcopy(self.data)
if 'to_from' in self.data:
to_from = self.data['to_from'].copy()
to_from['url'] = to_from['url'].format(**message)
if 'e... | python | def expand_variables(self, message):
"""expand any variables in the action to_from/cc_from fields.
"""
p = copy.deepcopy(self.data)
if 'to_from' in self.data:
to_from = self.data['to_from'].copy()
to_from['url'] = to_from['url'].format(**message)
if 'e... | [
"def",
"expand_variables",
"(",
"self",
",",
"message",
")",
":",
"p",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"data",
")",
"if",
"'to_from'",
"in",
"self",
".",
"data",
":",
"to_from",
"=",
"self",
".",
"data",
"[",
"'to_from'",
"]",
".",
... | expand any variables in the action to_from/cc_from fields. | [
"expand",
"any",
"variables",
"in",
"the",
"action",
"to_from",
"/",
"cc_from",
"fields",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/actions/notify.py#L30-L46 | train |
cloud-custodian/cloud-custodian | c7n/actions/notify.py | Notify.prepare_resources | def prepare_resources(self, resources):
"""Resources preparation for transport.
If we have sensitive or overly large resource metadata we want to
remove or additional serialization we need to perform, this
provides a mechanism.
TODO: consider alternative implementations, at min... | python | def prepare_resources(self, resources):
"""Resources preparation for transport.
If we have sensitive or overly large resource metadata we want to
remove or additional serialization we need to perform, this
provides a mechanism.
TODO: consider alternative implementations, at min... | [
"def",
"prepare_resources",
"(",
"self",
",",
"resources",
")",
":",
"handler",
"=",
"getattr",
"(",
"self",
",",
"\"prepare_%s\"",
"%",
"(",
"self",
".",
"manager",
".",
"type",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
",",
"None",
")",
"if... | Resources preparation for transport.
If we have sensitive or overly large resource metadata we want to
remove or additional serialization we need to perform, this
provides a mechanism.
TODO: consider alternative implementations, at min look at adding
provider as additional disc... | [
"Resources",
"preparation",
"for",
"transport",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/actions/notify.py#L191-L208 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | validate | def validate(config):
"""validate config file"""
with open(config) as fh:
content = fh.read()
try:
data = yaml.safe_load(content)
except Exception:
log.error("config file: %s is not valid yaml", config)
raise
try:
jsonschema.validate(data, CONFIG_SCHEMA)
... | python | def validate(config):
"""validate config file"""
with open(config) as fh:
content = fh.read()
try:
data = yaml.safe_load(content)
except Exception:
log.error("config file: %s is not valid yaml", config)
raise
try:
jsonschema.validate(data, CONFIG_SCHEMA)
... | [
"def",
"validate",
"(",
"config",
")",
":",
"with",
"open",
"(",
"config",
")",
"as",
"fh",
":",
"content",
"=",
"fh",
".",
"read",
"(",
")",
"try",
":",
"data",
"=",
"yaml",
".",
"safe_load",
"(",
"content",
")",
"except",
"Exception",
":",
"log",... | validate config file | [
"validate",
"config",
"file"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L124-L142 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | subscribe | def subscribe(config, accounts, region, merge, debug):
"""subscribe accounts log groups to target account log group destination"""
config = validate.callback(config)
subscription = config.get('subscription')
if subscription is None:
log.error("config file: logs subscription missing")
sy... | python | def subscribe(config, accounts, region, merge, debug):
"""subscribe accounts log groups to target account log group destination"""
config = validate.callback(config)
subscription = config.get('subscription')
if subscription is None:
log.error("config file: logs subscription missing")
sy... | [
"def",
"subscribe",
"(",
"config",
",",
"accounts",
",",
"region",
",",
"merge",
",",
"debug",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"subscription",
"=",
"config",
".",
"get",
"(",
"'subscription'",
")",
"if",
"subscri... | subscribe accounts log groups to target account log group destination | [
"subscribe",
"accounts",
"log",
"groups",
"to",
"target",
"account",
"log",
"group",
"destination"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L171-L251 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | run | def run(config, start, end, accounts, region, debug):
"""run export across accounts and log groups specified in config."""
config = validate.callback(config)
destination = config.get('destination')
start = start and parse(start) or start
end = end and parse(end) or datetime.now()
executor = debu... | python | def run(config, start, end, accounts, region, debug):
"""run export across accounts and log groups specified in config."""
config = validate.callback(config)
destination = config.get('destination')
start = start and parse(start) or start
end = end and parse(end) or datetime.now()
executor = debu... | [
"def",
"run",
"(",
"config",
",",
"start",
",",
"end",
",",
"accounts",
",",
"region",
",",
"debug",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"destination",
"=",
"config",
".",
"get",
"(",
"'destination'",
")",
"start",... | run export across accounts and log groups specified in config. | [
"run",
"export",
"across",
"accounts",
"and",
"log",
"groups",
"specified",
"in",
"config",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L261-L281 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | lambdafan | def lambdafan(func):
"""simple decorator that will auto fan out async style in lambda.
outside of lambda, this will invoke synchrously.
"""
if 'AWS_LAMBDA_FUNCTION_NAME' not in os.environ:
return func
@functools.wraps(func)
def scaleout(*args, **kw):
client = boto3.client('lamb... | python | def lambdafan(func):
"""simple decorator that will auto fan out async style in lambda.
outside of lambda, this will invoke synchrously.
"""
if 'AWS_LAMBDA_FUNCTION_NAME' not in os.environ:
return func
@functools.wraps(func)
def scaleout(*args, **kw):
client = boto3.client('lamb... | [
"def",
"lambdafan",
"(",
"func",
")",
":",
"if",
"'AWS_LAMBDA_FUNCTION_NAME'",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"func",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"scaleout",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
... | simple decorator that will auto fan out async style in lambda.
outside of lambda, this will invoke synchrously. | [
"simple",
"decorator",
"that",
"will",
"auto",
"fan",
"out",
"async",
"style",
"in",
"lambda",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L284-L304 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | filter_group_names | def filter_group_names(groups, patterns):
"""Filter log groups by shell patterns.
"""
group_names = [g['logGroupName'] for g in groups]
matched = set()
for p in patterns:
matched.update(fnmatch.filter(group_names, p))
return [g for g in groups if g['logGroupName'] in matched] | python | def filter_group_names(groups, patterns):
"""Filter log groups by shell patterns.
"""
group_names = [g['logGroupName'] for g in groups]
matched = set()
for p in patterns:
matched.update(fnmatch.filter(group_names, p))
return [g for g in groups if g['logGroupName'] in matched] | [
"def",
"filter_group_names",
"(",
"groups",
",",
"patterns",
")",
":",
"group_names",
"=",
"[",
"g",
"[",
"'logGroupName'",
"]",
"for",
"g",
"in",
"groups",
"]",
"matched",
"=",
"set",
"(",
")",
"for",
"p",
"in",
"patterns",
":",
"matched",
".",
"updat... | Filter log groups by shell patterns. | [
"Filter",
"log",
"groups",
"by",
"shell",
"patterns",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L362-L369 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | filter_creation_date | def filter_creation_date(groups, start, end):
"""Filter log groups by their creation date.
Also sets group specific value for start to the minimum
of creation date or start.
"""
results = []
for g in groups:
created = datetime.fromtimestamp(g['creationTime'] / 1000.0)
if created... | python | def filter_creation_date(groups, start, end):
"""Filter log groups by their creation date.
Also sets group specific value for start to the minimum
of creation date or start.
"""
results = []
for g in groups:
created = datetime.fromtimestamp(g['creationTime'] / 1000.0)
if created... | [
"def",
"filter_creation_date",
"(",
"groups",
",",
"start",
",",
"end",
")",
":",
"results",
"=",
"[",
"]",
"for",
"g",
"in",
"groups",
":",
"created",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"g",
"[",
"'creationTime'",
"]",
"/",
"1000.0",
")",
"if... | Filter log groups by their creation date.
Also sets group specific value for start to the minimum
of creation date or start. | [
"Filter",
"log",
"groups",
"by",
"their",
"creation",
"date",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L372-L388 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | filter_last_write | def filter_last_write(client, groups, start):
"""Filter log groups where the last write was before the start date.
"""
retry = get_retry(('ThrottlingException',))
def process_group(group_set):
matched = []
for g in group_set:
streams = retry(
client.describe_... | python | def filter_last_write(client, groups, start):
"""Filter log groups where the last write was before the start date.
"""
retry = get_retry(('ThrottlingException',))
def process_group(group_set):
matched = []
for g in group_set:
streams = retry(
client.describe_... | [
"def",
"filter_last_write",
"(",
"client",
",",
"groups",
",",
"start",
")",
":",
"retry",
"=",
"get_retry",
"(",
"(",
"'ThrottlingException'",
",",
")",
")",
"def",
"process_group",
"(",
"group_set",
")",
":",
"matched",
"=",
"[",
"]",
"for",
"g",
"in",... | Filter log groups where the last write was before the start date. | [
"Filter",
"log",
"groups",
"where",
"the",
"last",
"write",
"was",
"before",
"the",
"start",
"date",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L391-L430 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | filter_extant_exports | def filter_extant_exports(client, bucket, prefix, days, start, end=None):
"""Filter days where the bucket already has extant export keys.
"""
end = end or datetime.now()
# days = [start + timedelta(i) for i in range((end-start).days)]
try:
tag_set = client.get_object_tagging(Bucket=bucket, K... | python | def filter_extant_exports(client, bucket, prefix, days, start, end=None):
"""Filter days where the bucket already has extant export keys.
"""
end = end or datetime.now()
# days = [start + timedelta(i) for i in range((end-start).days)]
try:
tag_set = client.get_object_tagging(Bucket=bucket, K... | [
"def",
"filter_extant_exports",
"(",
"client",
",",
"bucket",
",",
"prefix",
",",
"days",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"end",
"=",
"end",
"or",
"datetime",
".",
"now",
"(",
")",
"# days = [start + timedelta(i) for i in range((end-start).days)... | Filter days where the bucket already has extant export keys. | [
"Filter",
"days",
"where",
"the",
"bucket",
"already",
"has",
"extant",
"export",
"keys",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L433-L451 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | access | def access(config, region, accounts=()):
"""Check iam permissions for log export access in each account"""
config = validate.callback(config)
accounts_report = []
def check_access(account):
accounts_report.append(account)
session = get_session(account['role'], region)
identity =... | python | def access(config, region, accounts=()):
"""Check iam permissions for log export access in each account"""
config = validate.callback(config)
accounts_report = []
def check_access(account):
accounts_report.append(account)
session = get_session(account['role'], region)
identity =... | [
"def",
"access",
"(",
"config",
",",
"region",
",",
"accounts",
"=",
"(",
")",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"accounts_report",
"=",
"[",
"]",
"def",
"check_access",
"(",
"account",
")",
":",
"accounts_report",... | Check iam permissions for log export access in each account | [
"Check",
"iam",
"permissions",
"for",
"log",
"export",
"access",
"in",
"each",
"account"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L458-L492 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | size | def size(config, accounts=(), day=None, group=None, human=True, region=None):
"""size of exported records for a given day."""
config = validate.callback(config)
destination = config.get('destination')
client = boto3.Session().client('s3')
day = parse(day)
def export_size(client, account):
... | python | def size(config, accounts=(), day=None, group=None, human=True, region=None):
"""size of exported records for a given day."""
config = validate.callback(config)
destination = config.get('destination')
client = boto3.Session().client('s3')
day = parse(day)
def export_size(client, account):
... | [
"def",
"size",
"(",
"config",
",",
"accounts",
"=",
"(",
")",
",",
"day",
"=",
"None",
",",
"group",
"=",
"None",
",",
"human",
"=",
"True",
",",
"region",
"=",
"None",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"de... | size of exported records for a given day. | [
"size",
"of",
"exported",
"records",
"for",
"a",
"given",
"day",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L514-L563 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | sync | def sync(config, group, accounts=(), dryrun=False, region=None):
"""sync last recorded export to actual
Use --dryrun to check status.
"""
config = validate.callback(config)
destination = config.get('destination')
client = boto3.Session().client('s3')
for account in config.get('accounts', (... | python | def sync(config, group, accounts=(), dryrun=False, region=None):
"""sync last recorded export to actual
Use --dryrun to check status.
"""
config = validate.callback(config)
destination = config.get('destination')
client = boto3.Session().client('s3')
for account in config.get('accounts', (... | [
"def",
"sync",
"(",
"config",
",",
"group",
",",
"accounts",
"=",
"(",
")",
",",
"dryrun",
"=",
"False",
",",
"region",
"=",
"None",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"destination",
"=",
"config",
".",
"get",
... | sync last recorded export to actual
Use --dryrun to check status. | [
"sync",
"last",
"recorded",
"export",
"to",
"actual"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L572-L659 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | status | def status(config, group, accounts=(), region=None):
"""report current export state status"""
config = validate.callback(config)
destination = config.get('destination')
client = boto3.Session().client('s3')
for account in config.get('accounts', ()):
if accounts and account['name'] not in ac... | python | def status(config, group, accounts=(), region=None):
"""report current export state status"""
config = validate.callback(config)
destination = config.get('destination')
client = boto3.Session().client('s3')
for account in config.get('accounts', ()):
if accounts and account['name'] not in ac... | [
"def",
"status",
"(",
"config",
",",
"group",
",",
"accounts",
"=",
"(",
")",
",",
"region",
"=",
"None",
")",
":",
"config",
"=",
"validate",
".",
"callback",
"(",
"config",
")",
"destination",
"=",
"config",
".",
"get",
"(",
"'destination'",
")",
"... | report current export state status | [
"report",
"current",
"export",
"state",
"status"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L667-L706 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | get_exports | def get_exports(client, bucket, prefix, latest=True):
"""Find exports for a given account
"""
keys = client.list_objects_v2(
Bucket=bucket, Prefix=prefix, Delimiter='/').get('CommonPrefixes', [])
found = []
years = []
for y in keys:
part = y['Prefix'].rsplit('/', 2)[-2]
i... | python | def get_exports(client, bucket, prefix, latest=True):
"""Find exports for a given account
"""
keys = client.list_objects_v2(
Bucket=bucket, Prefix=prefix, Delimiter='/').get('CommonPrefixes', [])
found = []
years = []
for y in keys:
part = y['Prefix'].rsplit('/', 2)[-2]
i... | [
"def",
"get_exports",
"(",
"client",
",",
"bucket",
",",
"prefix",
",",
"latest",
"=",
"True",
")",
":",
"keys",
"=",
"client",
".",
"list_objects_v2",
"(",
"Bucket",
"=",
"bucket",
",",
"Prefix",
"=",
"prefix",
",",
"Delimiter",
"=",
"'/'",
")",
".",
... | Find exports for a given account | [
"Find",
"exports",
"for",
"a",
"given",
"account"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L709-L762 | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | export | def export(group, bucket, prefix, start, end, role, poll_period=120,
session=None, name="", region=None):
"""export a given log group to s3"""
start = start and isinstance(start, six.string_types) and parse(start) or start
end = (end and isinstance(start, six.string_types) and
parse(en... | python | def export(group, bucket, prefix, start, end, role, poll_period=120,
session=None, name="", region=None):
"""export a given log group to s3"""
start = start and isinstance(start, six.string_types) and parse(start) or start
end = (end and isinstance(start, six.string_types) and
parse(en... | [
"def",
"export",
"(",
"group",
",",
"bucket",
",",
"prefix",
",",
"start",
",",
"end",
",",
"role",
",",
"poll_period",
"=",
"120",
",",
"session",
"=",
"None",
",",
"name",
"=",
"\"\"",
",",
"region",
"=",
"None",
")",
":",
"start",
"=",
"start",
... | export a given log group to s3 | [
"export",
"a",
"given",
"log",
"group",
"to",
"s3"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L777-L910 | train |
cloud-custodian/cloud-custodian | tools/c7n_sentry/c7n_sentry/c7nsentry.py | init | def init():
""" Lambda globals cache.
"""
global sqs, logs, config
if config is None:
with open('config.json') as fh:
config = json.load(fh)
if sqs is None:
sqs = boto3.client('sqs')
if logs is None:
logs = boto3.client('logs') | python | def init():
""" Lambda globals cache.
"""
global sqs, logs, config
if config is None:
with open('config.json') as fh:
config = json.load(fh)
if sqs is None:
sqs = boto3.client('sqs')
if logs is None:
logs = boto3.client('logs') | [
"def",
"init",
"(",
")",
":",
"global",
"sqs",
",",
"logs",
",",
"config",
"if",
"config",
"is",
"None",
":",
"with",
"open",
"(",
"'config.json'",
")",
"as",
"fh",
":",
"config",
"=",
"json",
".",
"load",
"(",
"fh",
")",
"if",
"sqs",
"is",
"None... | Lambda globals cache. | [
"Lambda",
"globals",
"cache",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_sentry/c7n_sentry/c7nsentry.py#L84-L94 | train |
cloud-custodian/cloud-custodian | tools/c7n_sentry/c7n_sentry/c7nsentry.py | process_log_event | def process_log_event(event, context):
"""Lambda Entrypoint - Log Subscriber
Format log events and relay to sentry (direct or sqs)
"""
init()
# Grab the actual error log payload
serialized = event['awslogs'].pop('data')
data = json.loads(zlib.decompress(
base64.b64decode(serialized)... | python | def process_log_event(event, context):
"""Lambda Entrypoint - Log Subscriber
Format log events and relay to sentry (direct or sqs)
"""
init()
# Grab the actual error log payload
serialized = event['awslogs'].pop('data')
data = json.loads(zlib.decompress(
base64.b64decode(serialized)... | [
"def",
"process_log_event",
"(",
"event",
",",
"context",
")",
":",
"init",
"(",
")",
"# Grab the actual error log payload",
"serialized",
"=",
"event",
"[",
"'awslogs'",
"]",
".",
"pop",
"(",
"'data'",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"zlib",
... | Lambda Entrypoint - Log Subscriber
Format log events and relay to sentry (direct or sqs) | [
"Lambda",
"Entrypoint",
"-",
"Log",
"Subscriber"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_sentry/c7n_sentry/c7nsentry.py#L97-L116 | train |
cloud-custodian/cloud-custodian | tools/c7n_sentry/c7n_sentry/c7nsentry.py | process_log_group | def process_log_group(config):
"""CLI - Replay / Index
"""
from c7n.credentials import SessionFactory
factory = SessionFactory(
config.region, config.profile, assume_role=config.role)
session = factory()
client = session.client('logs')
params = dict(logGroupName=config.log_group,
... | python | def process_log_group(config):
"""CLI - Replay / Index
"""
from c7n.credentials import SessionFactory
factory = SessionFactory(
config.region, config.profile, assume_role=config.role)
session = factory()
client = session.client('logs')
params = dict(logGroupName=config.log_group,
... | [
"def",
"process_log_group",
"(",
"config",
")",
":",
"from",
"c7n",
".",
"credentials",
"import",
"SessionFactory",
"factory",
"=",
"SessionFactory",
"(",
"config",
".",
"region",
",",
"config",
".",
"profile",
",",
"assume_role",
"=",
"config",
".",
"role",
... | CLI - Replay / Index | [
"CLI",
"-",
"Replay",
"/",
"Index"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_sentry/c7n_sentry/c7nsentry.py#L125-L169 | train |
cloud-custodian/cloud-custodian | tools/c7n_sentry/c7n_sentry/c7nsentry.py | parse_traceback | def parse_traceback(msg, site_path="site-packages", in_app_prefix="c7n"):
"""Extract a sentry traceback structure,
From a python formatted traceback string per python stdlib
traceback.print_exc()
"""
data = {}
lines = list(filter(None, msg.split('\n')))
data['frames'] = []
err_ctx = No... | python | def parse_traceback(msg, site_path="site-packages", in_app_prefix="c7n"):
"""Extract a sentry traceback structure,
From a python formatted traceback string per python stdlib
traceback.print_exc()
"""
data = {}
lines = list(filter(None, msg.split('\n')))
data['frames'] = []
err_ctx = No... | [
"def",
"parse_traceback",
"(",
"msg",
",",
"site_path",
"=",
"\"site-packages\"",
",",
"in_app_prefix",
"=",
"\"c7n\"",
")",
":",
"data",
"=",
"{",
"}",
"lines",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"msg",
".",
"split",
"(",
"'\\n'",
")",
")",... | Extract a sentry traceback structure,
From a python formatted traceback string per python stdlib
traceback.print_exc() | [
"Extract",
"a",
"sentry",
"traceback",
"structure"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_sentry/c7n_sentry/c7nsentry.py#L280-L319 | train |
cloud-custodian/cloud-custodian | tools/c7n_sentry/c7n_sentry/c7nsentry.py | get_function | def get_function(session_factory, name, handler, runtime, role,
log_groups,
project, account_name, account_id,
sentry_dsn,
pattern="Traceback"):
"""Lambda function provisioning.
Self contained within the component, to allow for easier reuse.
... | python | def get_function(session_factory, name, handler, runtime, role,
log_groups,
project, account_name, account_id,
sentry_dsn,
pattern="Traceback"):
"""Lambda function provisioning.
Self contained within the component, to allow for easier reuse.
... | [
"def",
"get_function",
"(",
"session_factory",
",",
"name",
",",
"handler",
",",
"runtime",
",",
"role",
",",
"log_groups",
",",
"project",
",",
"account_name",
",",
"account_id",
",",
"sentry_dsn",
",",
"pattern",
"=",
"\"Traceback\"",
")",
":",
"# Lazy impor... | Lambda function provisioning.
Self contained within the component, to allow for easier reuse. | [
"Lambda",
"function",
"provisioning",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_sentry/c7n_sentry/c7nsentry.py#L322-L361 | train |
cloud-custodian/cloud-custodian | tools/sandbox/zerodark/zerodark/ipdb.py | chunks | def chunks(iterable, size=50):
"""Break an iterable into lists of size"""
batch = []
for n in iterable:
batch.append(n)
if len(batch) % size == 0:
yield batch
batch = []
if batch:
yield batch | python | def chunks(iterable, size=50):
"""Break an iterable into lists of size"""
batch = []
for n in iterable:
batch.append(n)
if len(batch) % size == 0:
yield batch
batch = []
if batch:
yield batch | [
"def",
"chunks",
"(",
"iterable",
",",
"size",
"=",
"50",
")",
":",
"batch",
"=",
"[",
"]",
"for",
"n",
"in",
"iterable",
":",
"batch",
".",
"append",
"(",
"n",
")",
"if",
"len",
"(",
"batch",
")",
"%",
"size",
"==",
"0",
":",
"yield",
"batch",... | Break an iterable into lists of size | [
"Break",
"an",
"iterable",
"into",
"lists",
"of",
"size"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/zerodark/zerodark/ipdb.py#L527-L536 | train |
cloud-custodian/cloud-custodian | tools/sandbox/zerodark/zerodark/ipdb.py | worker_config | def worker_config(queue, s3_key, period, verbose):
"""daemon queue worker for config notifications"""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(logging.WARNING)
logging.getLogger('s3transfer').setLevel(logging.WARNING)
queue, regio... | python | def worker_config(queue, s3_key, period, verbose):
"""daemon queue worker for config notifications"""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(logging.WARNING)
logging.getLogger('s3transfer').setLevel(logging.WARNING)
queue, regio... | [
"def",
"worker_config",
"(",
"queue",
",",
"s3_key",
",",
"period",
",",
"verbose",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"(",
"verbose",
"and",
"logging",
".",
"DEBUG",
"or",
"logging",
".",
"INFO",
")",
")",
"logging",
".",
"get... | daemon queue worker for config notifications | [
"daemon",
"queue",
"worker",
"for",
"config",
"notifications"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/zerodark/zerodark/ipdb.py#L566-L587 | train |
cloud-custodian/cloud-custodian | tools/sandbox/zerodark/zerodark/ipdb.py | list_app_resources | def list_app_resources(
app, env, resources, cmdb, start, end, tz):
"""Analyze flow log records for application and generate metrics per period"""
logging.basicConfig(level=logging.INFO)
start, end = get_dates(start, end, tz)
all_resources = []
for rtype_name in resources:
rtype = R... | python | def list_app_resources(
app, env, resources, cmdb, start, end, tz):
"""Analyze flow log records for application and generate metrics per period"""
logging.basicConfig(level=logging.INFO)
start, end = get_dates(start, end, tz)
all_resources = []
for rtype_name in resources:
rtype = R... | [
"def",
"list_app_resources",
"(",
"app",
",",
"env",
",",
"resources",
",",
"cmdb",
",",
"start",
",",
"end",
",",
"tz",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
")",
"start",
",",
"end",
"=",
"get_dates",
"... | Analyze flow log records for application and generate metrics per period | [
"Analyze",
"flow",
"log",
"records",
"for",
"application",
"and",
"generate",
"metrics",
"per",
"period"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/zerodark/zerodark/ipdb.py#L617-L628 | train |
cloud-custodian/cloud-custodian | tools/sandbox/zerodark/zerodark/ipdb.py | load_resources | def load_resources(bucket, prefix, region, account_config, accounts,
assume, start, end, resources, store, db, verbose, debug):
"""load resources into resource database."""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(loggin... | python | def load_resources(bucket, prefix, region, account_config, accounts,
assume, start, end, resources, store, db, verbose, debug):
"""load resources into resource database."""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(loggin... | [
"def",
"load_resources",
"(",
"bucket",
",",
"prefix",
",",
"region",
",",
"account_config",
",",
"accounts",
",",
"assume",
",",
"start",
",",
"end",
",",
"resources",
",",
"store",
",",
"db",
",",
"verbose",
",",
"debug",
")",
":",
"logging",
".",
"b... | load resources into resource database. | [
"load",
"resources",
"into",
"resource",
"database",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/zerodark/zerodark/ipdb.py#L646-L702 | train |
cloud-custodian/cloud-custodian | c7n/registry.py | PluginRegistry.load_plugins | def load_plugins(self):
""" Load external plugins.
Custodian is intended to interact with internal and external systems
that are not suitable for embedding into the custodian code base.
"""
try:
from pkg_resources import iter_entry_points
except ImportError:
... | python | def load_plugins(self):
""" Load external plugins.
Custodian is intended to interact with internal and external systems
that are not suitable for embedding into the custodian code base.
"""
try:
from pkg_resources import iter_entry_points
except ImportError:
... | [
"def",
"load_plugins",
"(",
"self",
")",
":",
"try",
":",
"from",
"pkg_resources",
"import",
"iter_entry_points",
"except",
"ImportError",
":",
"return",
"for",
"ep",
"in",
"iter_entry_points",
"(",
"group",
"=",
"\"custodian.%s\"",
"%",
"self",
".",
"plugin_typ... | Load external plugins.
Custodian is intended to interact with internal and external systems
that are not suitable for embedding into the custodian code base. | [
"Load",
"external",
"plugins",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/registry.py#L106-L118 | train |
cloud-custodian/cloud-custodian | c7n/sqsexec.py | SQSExecutor.submit | def submit(self, func, *args, **kwargs):
"""Submit a function for serialized execution on sqs
"""
self.op_sequence += 1
self.sqs.send_message(
QueueUrl=self.map_queue,
MessageBody=utils.dumps({'args': args, 'kwargs': kwargs}),
MessageAttributes={
... | python | def submit(self, func, *args, **kwargs):
"""Submit a function for serialized execution on sqs
"""
self.op_sequence += 1
self.sqs.send_message(
QueueUrl=self.map_queue,
MessageBody=utils.dumps({'args': args, 'kwargs': kwargs}),
MessageAttributes={
... | [
"def",
"submit",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"op_sequence",
"+=",
"1",
"self",
".",
"sqs",
".",
"send_message",
"(",
"QueueUrl",
"=",
"self",
".",
"map_queue",
",",
"MessageBody",
"=",
... | Submit a function for serialized execution on sqs | [
"Submit",
"a",
"function",
"for",
"serialized",
"execution",
"on",
"sqs"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/sqsexec.py#L56-L78 | train |
cloud-custodian/cloud-custodian | c7n/sqsexec.py | SQSExecutor.gather | def gather(self):
"""Fetch results from separate queue
"""
limit = self.op_sequence - self.op_sequence_start
results = MessageIterator(self.sqs, self.reduce_queue, limit)
for m in results:
# sequence_id from above
msg_id = int(m['MessageAttributes']['seque... | python | def gather(self):
"""Fetch results from separate queue
"""
limit = self.op_sequence - self.op_sequence_start
results = MessageIterator(self.sqs, self.reduce_queue, limit)
for m in results:
# sequence_id from above
msg_id = int(m['MessageAttributes']['seque... | [
"def",
"gather",
"(",
"self",
")",
":",
"limit",
"=",
"self",
".",
"op_sequence",
"-",
"self",
".",
"op_sequence_start",
"results",
"=",
"MessageIterator",
"(",
"self",
".",
"sqs",
",",
"self",
".",
"reduce_queue",
",",
"limit",
")",
"for",
"m",
"in",
... | Fetch results from separate queue | [
"Fetch",
"results",
"from",
"separate",
"queue"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/sqsexec.py#L80-L95 | train |
cloud-custodian/cloud-custodian | c7n/resources/ecs.py | ecs_tag_normalize | def ecs_tag_normalize(resources):
"""normalize tag format on ecs resources to match common aws format."""
for r in resources:
if 'tags' in r:
r['Tags'] = [{'Key': t['key'], 'Value': t['value']} for t in r['tags']]
r.pop('tags') | python | def ecs_tag_normalize(resources):
"""normalize tag format on ecs resources to match common aws format."""
for r in resources:
if 'tags' in r:
r['Tags'] = [{'Key': t['key'], 'Value': t['value']} for t in r['tags']]
r.pop('tags') | [
"def",
"ecs_tag_normalize",
"(",
"resources",
")",
":",
"for",
"r",
"in",
"resources",
":",
"if",
"'tags'",
"in",
"r",
":",
"r",
"[",
"'Tags'",
"]",
"=",
"[",
"{",
"'Key'",
":",
"t",
"[",
"'key'",
"]",
",",
"'Value'",
":",
"t",
"[",
"'value'",
"]... | normalize tag format on ecs resources to match common aws format. | [
"normalize",
"tag",
"format",
"on",
"ecs",
"resources",
"to",
"match",
"common",
"aws",
"format",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/ecs.py#L28-L33 | train |
cloud-custodian/cloud-custodian | c7n/resources/ecs.py | ECSClusterResourceDescribeSource.get_resources | def get_resources(self, ids, cache=True):
"""Retrieve ecs resources for serverless policies or related resources
Requires arns in new format.
https://docs.aws.amazon.com/AmazonECS/latest/userguide/ecs-resource-ids.html
"""
cluster_resources = {}
for i in ids:
... | python | def get_resources(self, ids, cache=True):
"""Retrieve ecs resources for serverless policies or related resources
Requires arns in new format.
https://docs.aws.amazon.com/AmazonECS/latest/userguide/ecs-resource-ids.html
"""
cluster_resources = {}
for i in ids:
... | [
"def",
"get_resources",
"(",
"self",
",",
"ids",
",",
"cache",
"=",
"True",
")",
":",
"cluster_resources",
"=",
"{",
"}",
"for",
"i",
"in",
"ids",
":",
"_",
",",
"ident",
"=",
"i",
".",
"rsplit",
"(",
"':'",
",",
"1",
")",
"parts",
"=",
"ident",
... | Retrieve ecs resources for serverless policies or related resources
Requires arns in new format.
https://docs.aws.amazon.com/AmazonECS/latest/userguide/ecs-resource-ids.html | [
"Retrieve",
"ecs",
"resources",
"for",
"serverless",
"policies",
"or",
"related",
"resources"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/ecs.py#L97-L116 | train |
cloud-custodian/cloud-custodian | c7n/policy.py | PolicyCollection.resource_types | def resource_types(self):
"""resource types used by the collection."""
rtypes = set()
for p in self.policies:
rtypes.add(p.resource_type)
return rtypes | python | def resource_types(self):
"""resource types used by the collection."""
rtypes = set()
for p in self.policies:
rtypes.add(p.resource_type)
return rtypes | [
"def",
"resource_types",
"(",
"self",
")",
":",
"rtypes",
"=",
"set",
"(",
")",
"for",
"p",
"in",
"self",
".",
"policies",
":",
"rtypes",
".",
"add",
"(",
"p",
".",
"resource_type",
")",
"return",
"rtypes"
] | resource types used by the collection. | [
"resource",
"types",
"used",
"by",
"the",
"collection",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L118-L123 | train |
cloud-custodian/cloud-custodian | c7n/policy.py | PolicyExecutionMode.get_metrics | def get_metrics(self, start, end, period):
"""Retrieve any associated metrics for the policy."""
values = {}
default_dimensions = {
'Policy': self.policy.name, 'ResType': self.policy.resource_type,
'Scope': 'Policy'}
metrics = list(self.POLICY_METRICS)
#... | python | def get_metrics(self, start, end, period):
"""Retrieve any associated metrics for the policy."""
values = {}
default_dimensions = {
'Policy': self.policy.name, 'ResType': self.policy.resource_type,
'Scope': 'Policy'}
metrics = list(self.POLICY_METRICS)
#... | [
"def",
"get_metrics",
"(",
"self",
",",
"start",
",",
"end",
",",
"period",
")",
":",
"values",
"=",
"{",
"}",
"default_dimensions",
"=",
"{",
"'Policy'",
":",
"self",
".",
"policy",
".",
"name",
",",
"'ResType'",
":",
"self",
".",
"policy",
".",
"re... | Retrieve any associated metrics for the policy. | [
"Retrieve",
"any",
"associated",
"metrics",
"for",
"the",
"policy",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L153-L190 | train |
cloud-custodian/cloud-custodian | c7n/policy.py | LambdaMode.run | def run(self, event, lambda_context):
"""Run policy in push mode against given event.
Lambda automatically generates cloud watch logs, and metrics
for us, albeit with some deficienies, metrics no longer count
against valid resources matches, but against execution.
If metrics ex... | python | def run(self, event, lambda_context):
"""Run policy in push mode against given event.
Lambda automatically generates cloud watch logs, and metrics
for us, albeit with some deficienies, metrics no longer count
against valid resources matches, but against execution.
If metrics ex... | [
"def",
"run",
"(",
"self",
",",
"event",
",",
"lambda_context",
")",
":",
"from",
"c7n",
".",
"actions",
"import",
"EventAction",
"mode",
"=",
"self",
".",
"policy",
".",
"data",
".",
"get",
"(",
"'mode'",
",",
"{",
"}",
")",
"if",
"not",
"bool",
"... | Run policy in push mode against given event.
Lambda automatically generates cloud watch logs, and metrics
for us, albeit with some deficienies, metrics no longer count
against valid resources matches, but against execution.
If metrics execution option is enabled, custodian will generat... | [
"Run",
"policy",
"in",
"push",
"mode",
"against",
"given",
"event",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L426-L481 | train |
cloud-custodian/cloud-custodian | c7n/policy.py | Policy.get_variables | def get_variables(self, variables=None):
"""Get runtime variables for policy interpolation.
Runtime variables are merged with the passed in variables
if any.
"""
# Global policy variable expansion, we have to carry forward on
# various filter/action local vocabularies. W... | python | def get_variables(self, variables=None):
"""Get runtime variables for policy interpolation.
Runtime variables are merged with the passed in variables
if any.
"""
# Global policy variable expansion, we have to carry forward on
# various filter/action local vocabularies. W... | [
"def",
"get_variables",
"(",
"self",
",",
"variables",
"=",
"None",
")",
":",
"# Global policy variable expansion, we have to carry forward on",
"# various filter/action local vocabularies. Where possible defer",
"# by using a format string.",
"#",
"# See https://github.com/capitalone/cl... | Get runtime variables for policy interpolation.
Runtime variables are merged with the passed in variables
if any. | [
"Get",
"runtime",
"variables",
"for",
"policy",
"interpolation",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L836-L880 | train |
cloud-custodian/cloud-custodian | c7n/policy.py | Policy.expand_variables | def expand_variables(self, variables):
"""Expand variables in policy data.
Updates the policy data in-place.
"""
# format string values returns a copy
updated = utils.format_string_values(self.data, **variables)
# Several keys should only be expanded at runtime, perserv... | python | def expand_variables(self, variables):
"""Expand variables in policy data.
Updates the policy data in-place.
"""
# format string values returns a copy
updated = utils.format_string_values(self.data, **variables)
# Several keys should only be expanded at runtime, perserv... | [
"def",
"expand_variables",
"(",
"self",
",",
"variables",
")",
":",
"# format string values returns a copy",
"updated",
"=",
"utils",
".",
"format_string_values",
"(",
"self",
".",
"data",
",",
"*",
"*",
"variables",
")",
"# Several keys should only be expanded at runti... | Expand variables in policy data.
Updates the policy data in-place. | [
"Expand",
"variables",
"in",
"policy",
"data",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L882-L906 | train |
cloud-custodian/cloud-custodian | c7n/policy.py | Policy.get_permissions | def get_permissions(self):
"""get permissions needed by this policy"""
permissions = set()
permissions.update(self.resource_manager.get_permissions())
for f in self.resource_manager.filters:
permissions.update(f.get_permissions())
for a in self.resource_manager.action... | python | def get_permissions(self):
"""get permissions needed by this policy"""
permissions = set()
permissions.update(self.resource_manager.get_permissions())
for f in self.resource_manager.filters:
permissions.update(f.get_permissions())
for a in self.resource_manager.action... | [
"def",
"get_permissions",
"(",
"self",
")",
":",
"permissions",
"=",
"set",
"(",
")",
"permissions",
".",
"update",
"(",
"self",
".",
"resource_manager",
".",
"get_permissions",
"(",
")",
")",
"for",
"f",
"in",
"self",
".",
"resource_manager",
".",
"filter... | get permissions needed by this policy | [
"get",
"permissions",
"needed",
"by",
"this",
"policy"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L930-L938 | train |
cloud-custodian/cloud-custodian | c7n/resources/ebs.py | ErrorHandler.extract_bad_snapshot | def extract_bad_snapshot(e):
"""Handle various client side errors when describing snapshots"""
msg = e.response['Error']['Message']
error = e.response['Error']['Code']
e_snap_id = None
if error == 'InvalidSnapshot.NotFound':
e_snap_id = msg[msg.find("'") + 1:msg.rfind... | python | def extract_bad_snapshot(e):
"""Handle various client side errors when describing snapshots"""
msg = e.response['Error']['Message']
error = e.response['Error']['Code']
e_snap_id = None
if error == 'InvalidSnapshot.NotFound':
e_snap_id = msg[msg.find("'") + 1:msg.rfind... | [
"def",
"extract_bad_snapshot",
"(",
"e",
")",
":",
"msg",
"=",
"e",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Message'",
"]",
"error",
"=",
"e",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Code'",
"]",
"e_snap_id",
"=",
"None",
"if",
"error",
"==... | Handle various client side errors when describing snapshots | [
"Handle",
"various",
"client",
"side",
"errors",
"when",
"describing",
"snapshots"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/resources/ebs.py#L116-L127 | train |
cloud-custodian/cloud-custodian | c7n/credentials.py | assumed_session | def assumed_session(role_arn, session_name, session=None, region=None, external_id=None):
"""STS Role assume a boto3.Session
With automatic credential renewal.
Args:
role_arn: iam role arn to assume
session_name: client session identifier
session: an optional extant session, note session... | python | def assumed_session(role_arn, session_name, session=None, region=None, external_id=None):
"""STS Role assume a boto3.Session
With automatic credential renewal.
Args:
role_arn: iam role arn to assume
session_name: client session identifier
session: an optional extant session, note session... | [
"def",
"assumed_session",
"(",
"role_arn",
",",
"session_name",
",",
"session",
"=",
"None",
",",
"region",
"=",
"None",
",",
"external_id",
"=",
"None",
")",
":",
"if",
"session",
"is",
"None",
":",
"session",
"=",
"Session",
"(",
")",
"retry",
"=",
"... | STS Role assume a boto3.Session
With automatic credential renewal.
Args:
role_arn: iam role arn to assume
session_name: client session identifier
session: an optional extant session, note session is captured
in a function closure for renewing the sts assumed role.
:return: a boto3... | [
"STS",
"Role",
"assume",
"a",
"boto3",
".",
"Session"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/credentials.py#L73-L125 | train |
cloud-custodian/cloud-custodian | c7n/filters/offhours.py | Time.process_resource_schedule | def process_resource_schedule(self, i, value, time_type):
"""Does the resource tag schedule and policy match the current time."""
rid = i[self.id_key]
# this is to normalize trailing semicolons which when done allows
# dateutil.parser.parse to process: value='off=(m-f,1);' properly.
... | python | def process_resource_schedule(self, i, value, time_type):
"""Does the resource tag schedule and policy match the current time."""
rid = i[self.id_key]
# this is to normalize trailing semicolons which when done allows
# dateutil.parser.parse to process: value='off=(m-f,1);' properly.
... | [
"def",
"process_resource_schedule",
"(",
"self",
",",
"i",
",",
"value",
",",
"time_type",
")",
":",
"rid",
"=",
"i",
"[",
"self",
".",
"id_key",
"]",
"# this is to normalize trailing semicolons which when done allows",
"# dateutil.parser.parse to process: value='off=(m-f,1... | Does the resource tag schedule and policy match the current time. | [
"Does",
"the",
"resource",
"tag",
"schedule",
"and",
"policy",
"match",
"the",
"current",
"time",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/offhours.py#L398-L438 | train |
cloud-custodian/cloud-custodian | c7n/filters/offhours.py | Time.get_tag_value | def get_tag_value(self, i):
"""Get the resource's tag value specifying its schedule."""
# Look for the tag, Normalize tag key and tag value
found = False
for t in i.get('Tags', ()):
if t['Key'].lower() == self.tag_key:
found = t['Value']
break
... | python | def get_tag_value(self, i):
"""Get the resource's tag value specifying its schedule."""
# Look for the tag, Normalize tag key and tag value
found = False
for t in i.get('Tags', ()):
if t['Key'].lower() == self.tag_key:
found = t['Value']
break
... | [
"def",
"get_tag_value",
"(",
"self",
",",
"i",
")",
":",
"# Look for the tag, Normalize tag key and tag value",
"found",
"=",
"False",
"for",
"t",
"in",
"i",
".",
"get",
"(",
"'Tags'",
",",
"(",
")",
")",
":",
"if",
"t",
"[",
"'Key'",
"]",
".",
"lower",
... | Get the resource's tag value specifying its schedule. | [
"Get",
"the",
"resource",
"s",
"tag",
"value",
"specifying",
"its",
"schedule",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/offhours.py#L448-L463 | train |
cloud-custodian/cloud-custodian | c7n/filters/offhours.py | ScheduleParser.raw_data | def raw_data(tag_value):
"""convert the tag to a dictionary, taking values as is
This method name and purpose are opaque... and not true.
"""
data = {}
pieces = []
for p in tag_value.split(' '):
pieces.extend(p.split(';'))
# parse components
... | python | def raw_data(tag_value):
"""convert the tag to a dictionary, taking values as is
This method name and purpose are opaque... and not true.
"""
data = {}
pieces = []
for p in tag_value.split(' '):
pieces.extend(p.split(';'))
# parse components
... | [
"def",
"raw_data",
"(",
"tag_value",
")",
":",
"data",
"=",
"{",
"}",
"pieces",
"=",
"[",
"]",
"for",
"p",
"in",
"tag_value",
".",
"split",
"(",
"' '",
")",
":",
"pieces",
".",
"extend",
"(",
"p",
".",
"split",
"(",
"';'",
")",
")",
"# parse comp... | convert the tag to a dictionary, taking values as is
This method name and purpose are opaque... and not true. | [
"convert",
"the",
"tag",
"to",
"a",
"dictionary",
"taking",
"values",
"as",
"is"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/offhours.py#L577-L594 | train |
cloud-custodian/cloud-custodian | c7n/filters/offhours.py | ScheduleParser.keys_are_valid | def keys_are_valid(self, tag_value):
"""test that provided tag keys are valid"""
for key in ScheduleParser.raw_data(tag_value):
if key not in ('on', 'off', 'tz'):
return False
return True | python | def keys_are_valid(self, tag_value):
"""test that provided tag keys are valid"""
for key in ScheduleParser.raw_data(tag_value):
if key not in ('on', 'off', 'tz'):
return False
return True | [
"def",
"keys_are_valid",
"(",
"self",
",",
"tag_value",
")",
":",
"for",
"key",
"in",
"ScheduleParser",
".",
"raw_data",
"(",
"tag_value",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'on'",
",",
"'off'",
",",
"'tz'",
")",
":",
"return",
"False",
"return"... | test that provided tag keys are valid | [
"test",
"that",
"provided",
"tag",
"keys",
"are",
"valid"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/filters/offhours.py#L596-L601 | train |
cloud-custodian/cloud-custodian | tools/ops/mugc.py | resources_gc_prefix | def resources_gc_prefix(options, policy_config, policy_collection):
"""Garbage collect old custodian policies based on prefix.
We attempt to introspect to find the event sources for a policy
but without the old configuration this is implicit.
"""
# Classify policies by region
policy_regions = ... | python | def resources_gc_prefix(options, policy_config, policy_collection):
"""Garbage collect old custodian policies based on prefix.
We attempt to introspect to find the event sources for a policy
but without the old configuration this is implicit.
"""
# Classify policies by region
policy_regions = ... | [
"def",
"resources_gc_prefix",
"(",
"options",
",",
"policy_config",
",",
"policy_collection",
")",
":",
"# Classify policies by region",
"policy_regions",
"=",
"{",
"}",
"for",
"p",
"in",
"policy_collection",
":",
"if",
"p",
".",
"execution_mode",
"==",
"'poll'",
... | Garbage collect old custodian policies based on prefix.
We attempt to introspect to find the event sources for a policy
but without the old configuration this is implicit. | [
"Garbage",
"collect",
"old",
"custodian",
"policies",
"based",
"on",
"prefix",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/ops/mugc.py#L113-L129 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | get_session | def get_session(account_info):
"""Get a boto3 sesssion potentially cross account sts assumed
assumed sessions are automatically refreshed.
"""
s = getattr(CONN_CACHE, '%s-session' % account_info['name'], None)
if s is not None:
return s
if account_info.get('role'):
s = assumed_s... | python | def get_session(account_info):
"""Get a boto3 sesssion potentially cross account sts assumed
assumed sessions are automatically refreshed.
"""
s = getattr(CONN_CACHE, '%s-session' % account_info['name'], None)
if s is not None:
return s
if account_info.get('role'):
s = assumed_s... | [
"def",
"get_session",
"(",
"account_info",
")",
":",
"s",
"=",
"getattr",
"(",
"CONN_CACHE",
",",
"'%s-session'",
"%",
"account_info",
"[",
"'name'",
"]",
",",
"None",
")",
"if",
"s",
"is",
"not",
"None",
":",
"return",
"s",
"if",
"account_info",
".",
... | Get a boto3 sesssion potentially cross account sts assumed
assumed sessions are automatically refreshed. | [
"Get",
"a",
"boto3",
"sesssion",
"potentially",
"cross",
"account",
"sts",
"assumed"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L136-L149 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | bulk_invoke | def bulk_invoke(func, args, nargs):
"""Bulk invoke a function via queues
Uses internal implementation details of rq.
"""
# for comparison, simplest thing that works
# for i in nargs:
# argv = list(args)
# argv.append(i)
# func.delay(*argv)
# some variances between cpy and ... | python | def bulk_invoke(func, args, nargs):
"""Bulk invoke a function via queues
Uses internal implementation details of rq.
"""
# for comparison, simplest thing that works
# for i in nargs:
# argv = list(args)
# argv.append(i)
# func.delay(*argv)
# some variances between cpy and ... | [
"def",
"bulk_invoke",
"(",
"func",
",",
"args",
",",
"nargs",
")",
":",
"# for comparison, simplest thing that works",
"# for i in nargs:",
"# argv = list(args)",
"# argv.append(i)",
"# func.delay(*argv)",
"# some variances between cpy and pypy, sniff detect",
"for",
"clos... | Bulk invoke a function via queues
Uses internal implementation details of rq. | [
"Bulk",
"invoke",
"a",
"function",
"via",
"queues"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L160-L193 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | bucket_ops | def bucket_ops(bid, api=""):
"""Context manager for dealing with s3 errors in one place
bid: bucket_id in form of account_name:bucket_name
"""
try:
yield 42
except ClientError as e:
code = e.response['Error']['Code']
log.info(
"bucket error bucket:%s error:%s",
... | python | def bucket_ops(bid, api=""):
"""Context manager for dealing with s3 errors in one place
bid: bucket_id in form of account_name:bucket_name
"""
try:
yield 42
except ClientError as e:
code = e.response['Error']['Code']
log.info(
"bucket error bucket:%s error:%s",
... | [
"def",
"bucket_ops",
"(",
"bid",
",",
"api",
"=",
"\"\"",
")",
":",
"try",
":",
"yield",
"42",
"except",
"ClientError",
"as",
"e",
":",
"code",
"=",
"e",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Code'",
"]",
"log",
".",
"info",
"(",
"\"bucket e... | Context manager for dealing with s3 errors in one place
bid: bucket_id in form of account_name:bucket_name | [
"Context",
"manager",
"for",
"dealing",
"with",
"s3",
"errors",
"in",
"one",
"place"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L197-L225 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | page_strip | def page_strip(page, versioned):
"""Remove bits in content results to minimize memory utilization.
TODO: evolve this to a key filter on metadata, like date
"""
# page strip filtering should be conditional
page.pop('ResponseMetadata', None)
contents_key = versioned and 'Versions' or 'Contents'
... | python | def page_strip(page, versioned):
"""Remove bits in content results to minimize memory utilization.
TODO: evolve this to a key filter on metadata, like date
"""
# page strip filtering should be conditional
page.pop('ResponseMetadata', None)
contents_key = versioned and 'Versions' or 'Contents'
... | [
"def",
"page_strip",
"(",
"page",
",",
"versioned",
")",
":",
"# page strip filtering should be conditional",
"page",
".",
"pop",
"(",
"'ResponseMetadata'",
",",
"None",
")",
"contents_key",
"=",
"versioned",
"and",
"'Versions'",
"or",
"'Contents'",
"contents",
"=",... | Remove bits in content results to minimize memory utilization.
TODO: evolve this to a key filter on metadata, like date | [
"Remove",
"bits",
"in",
"content",
"results",
"to",
"minimize",
"memory",
"utilization",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L228-L262 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | process_account | def process_account(account_info):
"""Scan all buckets in an account and schedule processing"""
log = logging.getLogger('salactus.bucket-iterator')
log.info("processing account %s", account_info)
session = get_session(account_info)
client = session.client('s3', config=s3config)
buckets = client.... | python | def process_account(account_info):
"""Scan all buckets in an account and schedule processing"""
log = logging.getLogger('salactus.bucket-iterator')
log.info("processing account %s", account_info)
session = get_session(account_info)
client = session.client('s3', config=s3config)
buckets = client.... | [
"def",
"process_account",
"(",
"account_info",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'salactus.bucket-iterator'",
")",
"log",
".",
"info",
"(",
"\"processing account %s\"",
",",
"account_info",
")",
"session",
"=",
"get_session",
"(",
"account_i... | Scan all buckets in an account and schedule processing | [
"Scan",
"all",
"buckets",
"in",
"an",
"account",
"and",
"schedule",
"processing"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L287-L314 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | process_bucket_set | def process_bucket_set(account_info, buckets):
"""Process a collection of buckets.
For each bucket fetch location, versioning and size and
then kickoff processing strategy based on size.
"""
region_clients = {}
log = logging.getLogger('salactus.bucket-set')
log.info("processing account %s",... | python | def process_bucket_set(account_info, buckets):
"""Process a collection of buckets.
For each bucket fetch location, versioning and size and
then kickoff processing strategy based on size.
"""
region_clients = {}
log = logging.getLogger('salactus.bucket-set')
log.info("processing account %s",... | [
"def",
"process_bucket_set",
"(",
"account_info",
",",
"buckets",
")",
":",
"region_clients",
"=",
"{",
"}",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'salactus.bucket-set'",
")",
"log",
".",
"info",
"(",
"\"processing account %s\"",
",",
"account_info",
")... | Process a collection of buckets.
For each bucket fetch location, versioning and size and
then kickoff processing strategy based on size. | [
"Process",
"a",
"collection",
"of",
"buckets",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L318-L385 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | dispatch_object_source | def dispatch_object_source(client, account_info, bid, bucket_info):
"""Select and dispatch an object source for a bucket.
Choices are bucket partition, inventory, or direct pagination.
"""
if (account_info.get('inventory') and
bucket_info['keycount'] >
account_info['inventory'].get... | python | def dispatch_object_source(client, account_info, bid, bucket_info):
"""Select and dispatch an object source for a bucket.
Choices are bucket partition, inventory, or direct pagination.
"""
if (account_info.get('inventory') and
bucket_info['keycount'] >
account_info['inventory'].get... | [
"def",
"dispatch_object_source",
"(",
"client",
",",
"account_info",
",",
"bid",
",",
"bucket_info",
")",
":",
"if",
"(",
"account_info",
".",
"get",
"(",
"'inventory'",
")",
"and",
"bucket_info",
"[",
"'keycount'",
"]",
">",
"account_info",
"[",
"'inventory'"... | Select and dispatch an object source for a bucket.
Choices are bucket partition, inventory, or direct pagination. | [
"Select",
"and",
"dispatch",
"an",
"object",
"source",
"for",
"a",
"bucket",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L388-L410 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | get_keys_charset | def get_keys_charset(keys, bid):
""" Use set of keys as selector for character superset
Note this isn't optimal, its probabilistic on the keyset char population.
"""
# use the keys found to sample possible chars
chars = set()
for k in keys:
chars.update(k[:4])
remainder = chars
... | python | def get_keys_charset(keys, bid):
""" Use set of keys as selector for character superset
Note this isn't optimal, its probabilistic on the keyset char population.
"""
# use the keys found to sample possible chars
chars = set()
for k in keys:
chars.update(k[:4])
remainder = chars
... | [
"def",
"get_keys_charset",
"(",
"keys",
",",
"bid",
")",
":",
"# use the keys found to sample possible chars",
"chars",
"=",
"set",
"(",
")",
"for",
"k",
"in",
"keys",
":",
"chars",
".",
"update",
"(",
"k",
"[",
":",
"4",
"]",
")",
"remainder",
"=",
"cha... | Use set of keys as selector for character superset
Note this isn't optimal, its probabilistic on the keyset char population. | [
"Use",
"set",
"of",
"keys",
"as",
"selector",
"for",
"character",
"superset"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L507-L544 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | detect_partition_strategy | def detect_partition_strategy(bid, delimiters=('/', '-'), prefix=''):
"""Try to detect the best partitioning strategy for a large bucket
Consider nested buckets with common prefixes, and flat buckets.
"""
account, bucket = bid.split(":", 1)
region = connection.hget('bucket-regions', bid)
versio... | python | def detect_partition_strategy(bid, delimiters=('/', '-'), prefix=''):
"""Try to detect the best partitioning strategy for a large bucket
Consider nested buckets with common prefixes, and flat buckets.
"""
account, bucket = bid.split(":", 1)
region = connection.hget('bucket-regions', bid)
versio... | [
"def",
"detect_partition_strategy",
"(",
"bid",
",",
"delimiters",
"=",
"(",
"'/'",
",",
"'-'",
")",
",",
"prefix",
"=",
"''",
")",
":",
"account",
",",
"bucket",
"=",
"bid",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"region",
"=",
"connection",
"."... | Try to detect the best partitioning strategy for a large bucket
Consider nested buckets with common prefixes, and flat buckets. | [
"Try",
"to",
"detect",
"the",
"best",
"partitioning",
"strategy",
"for",
"a",
"large",
"bucket"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L547-L608 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | process_bucket_partitions | def process_bucket_partitions(
bid, prefix_set=('',), partition='/', strategy=None, limit=4):
"""Split up a bucket keyspace into smaller sets for parallel iteration.
"""
if strategy is None:
return detect_partition_strategy(bid)
account, bucket = bid.split(':', 1)
region = connectio... | python | def process_bucket_partitions(
bid, prefix_set=('',), partition='/', strategy=None, limit=4):
"""Split up a bucket keyspace into smaller sets for parallel iteration.
"""
if strategy is None:
return detect_partition_strategy(bid)
account, bucket = bid.split(':', 1)
region = connectio... | [
"def",
"process_bucket_partitions",
"(",
"bid",
",",
"prefix_set",
"=",
"(",
"''",
",",
")",
",",
"partition",
"=",
"'/'",
",",
"strategy",
"=",
"None",
",",
"limit",
"=",
"4",
")",
":",
"if",
"strategy",
"is",
"None",
":",
"return",
"detect_partition_st... | Split up a bucket keyspace into smaller sets for parallel iteration. | [
"Split",
"up",
"a",
"bucket",
"keyspace",
"into",
"smaller",
"sets",
"for",
"parallel",
"iteration",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L613-L703 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | process_bucket_inventory | def process_bucket_inventory(bid, inventory_bucket, inventory_prefix):
"""Load last inventory dump and feed as key source.
"""
log.info("Loading bucket %s keys from inventory s3://%s/%s",
bid, inventory_bucket, inventory_prefix)
account, bucket = bid.split(':', 1)
region = connection.hg... | python | def process_bucket_inventory(bid, inventory_bucket, inventory_prefix):
"""Load last inventory dump and feed as key source.
"""
log.info("Loading bucket %s keys from inventory s3://%s/%s",
bid, inventory_bucket, inventory_prefix)
account, bucket = bid.split(':', 1)
region = connection.hg... | [
"def",
"process_bucket_inventory",
"(",
"bid",
",",
"inventory_bucket",
",",
"inventory_prefix",
")",
":",
"log",
".",
"info",
"(",
"\"Loading bucket %s keys from inventory s3://%s/%s\"",
",",
"bid",
",",
"inventory_bucket",
",",
"inventory_prefix",
")",
"account",
",",... | Load last inventory dump and feed as key source. | [
"Load",
"last",
"inventory",
"dump",
"and",
"feed",
"as",
"key",
"source",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L708-L735 | train |
cloud-custodian/cloud-custodian | tools/c7n_salactus/c7n_salactus/worker.py | process_bucket_iterator | def process_bucket_iterator(bid, prefix="", delimiter="", **continuation):
"""Bucket pagination
"""
log.info("Iterating keys bucket %s prefix %s delimiter %s",
bid, prefix, delimiter)
account, bucket = bid.split(':', 1)
region = connection.hget('bucket-regions', bid)
versioned = bo... | python | def process_bucket_iterator(bid, prefix="", delimiter="", **continuation):
"""Bucket pagination
"""
log.info("Iterating keys bucket %s prefix %s delimiter %s",
bid, prefix, delimiter)
account, bucket = bid.split(':', 1)
region = connection.hget('bucket-regions', bid)
versioned = bo... | [
"def",
"process_bucket_iterator",
"(",
"bid",
",",
"prefix",
"=",
"\"\"",
",",
"delimiter",
"=",
"\"\"",
",",
"*",
"*",
"continuation",
")",
":",
"log",
".",
"info",
"(",
"\"Iterating keys bucket %s prefix %s delimiter %s\"",
",",
"bid",
",",
"prefix",
",",
"d... | Bucket pagination | [
"Bucket",
"pagination"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_salactus/c7n_salactus/worker.py#L740-L785 | train |
cloud-custodian/cloud-custodian | c7n/tags.py | universal_retry | def universal_retry(method, ResourceARNList, **kw):
"""Retry support for resourcegroup tagging apis.
The resource group tagging api typically returns a 200 status code
with embedded resource specific errors. To enable resource specific
retry on throttles, we extract those, perform backoff w/ jitter and... | python | def universal_retry(method, ResourceARNList, **kw):
"""Retry support for resourcegroup tagging apis.
The resource group tagging api typically returns a 200 status code
with embedded resource specific errors. To enable resource specific
retry on throttles, we extract those, perform backoff w/ jitter and... | [
"def",
"universal_retry",
"(",
"method",
",",
"ResourceARNList",
",",
"*",
"*",
"kw",
")",
":",
"max_attempts",
"=",
"6",
"for",
"idx",
",",
"delay",
"in",
"enumerate",
"(",
"utils",
".",
"backoff_delays",
"(",
"1.5",
",",
"2",
"**",
"8",
",",
"jitter"... | Retry support for resourcegroup tagging apis.
The resource group tagging api typically returns a 200 status code
with embedded resource specific errors. To enable resource specific
retry on throttles, we extract those, perform backoff w/ jitter and
continue. Other errors are immediately raised.
We... | [
"Retry",
"support",
"for",
"resourcegroup",
"tagging",
"apis",
"."
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/tags.py#L1094-L1134 | train |
cloud-custodian/cloud-custodian | c7n/tags.py | coalesce_copy_user_tags | def coalesce_copy_user_tags(resource, copy_tags, user_tags):
"""
Returns a list of tags from resource and user supplied in
the format: [{'Key': 'key', 'Value': 'value'}]
Due to drift on implementation on copy-tags/tags used throughout
the code base, the following options are supported:
cop... | python | def coalesce_copy_user_tags(resource, copy_tags, user_tags):
"""
Returns a list of tags from resource and user supplied in
the format: [{'Key': 'key', 'Value': 'value'}]
Due to drift on implementation on copy-tags/tags used throughout
the code base, the following options are supported:
cop... | [
"def",
"coalesce_copy_user_tags",
"(",
"resource",
",",
"copy_tags",
",",
"user_tags",
")",
":",
"assert",
"isinstance",
"(",
"copy_tags",
",",
"bool",
")",
"or",
"isinstance",
"(",
"copy_tags",
",",
"list",
")",
"assert",
"isinstance",
"(",
"user_tags",
",",
... | Returns a list of tags from resource and user supplied in
the format: [{'Key': 'key', 'Value': 'value'}]
Due to drift on implementation on copy-tags/tags used throughout
the code base, the following options are supported:
copy_tags (Tags to copy from the resource):
- list of str, e.g. ['... | [
"Returns",
"a",
"list",
"of",
"tags",
"from",
"resource",
"and",
"user",
"supplied",
"in",
"the",
"format",
":",
"[",
"{",
"Key",
":",
"key",
"Value",
":",
"value",
"}",
"]"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/tags.py#L1137-L1185 | train |
cloud-custodian/cloud-custodian | c7n/tags.py | RenameTag.process_rename | def process_rename(self, client, tag_value, resource_set):
"""
Move source tag value to destination tag value
- Collect value from old tag
- Delete old tag
- Create new tag & assign stored value
"""
self.log.info("Renaming tag on %s instances" % (len(resource_set... | python | def process_rename(self, client, tag_value, resource_set):
"""
Move source tag value to destination tag value
- Collect value from old tag
- Delete old tag
- Create new tag & assign stored value
"""
self.log.info("Renaming tag on %s instances" % (len(resource_set... | [
"def",
"process_rename",
"(",
"self",
",",
"client",
",",
"tag_value",
",",
"resource_set",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Renaming tag on %s instances\"",
"%",
"(",
"len",
"(",
"resource_set",
")",
")",
")",
"old_key",
"=",
"self",
"."... | Move source tag value to destination tag value
- Collect value from old tag
- Delete old tag
- Create new tag & assign stored value | [
"Move",
"source",
"tag",
"value",
"to",
"destination",
"tag",
"value"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/tags.py#L515-L540 | train |
cloud-custodian/cloud-custodian | c7n/tags.py | NormalizeTag.process_transform | def process_transform(self, tag_value, resource_set):
"""
Transform tag value
- Collect value from tag
- Transform Tag value
- Assign new value for key
"""
self.log.info("Transforming tag value on %s instances" % (
len(resource_set)))
key = se... | python | def process_transform(self, tag_value, resource_set):
"""
Transform tag value
- Collect value from tag
- Transform Tag value
- Assign new value for key
"""
self.log.info("Transforming tag value on %s instances" % (
len(resource_set)))
key = se... | [
"def",
"process_transform",
"(",
"self",
",",
"tag_value",
",",
"resource_set",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Transforming tag value on %s instances\"",
"%",
"(",
"len",
"(",
"resource_set",
")",
")",
")",
"key",
"=",
"self",
".",
"data"... | Transform tag value
- Collect value from tag
- Transform Tag value
- Assign new value for key | [
"Transform",
"tag",
"value"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/tags.py#L758-L776 | train |
cloud-custodian/cloud-custodian | c7n/tags.py | CopyRelatedResourceTag.get_resource_tag_map | def get_resource_tag_map(self, r_type, ids):
"""
Returns a mapping of {resource_id: {tagkey: tagvalue}}
"""
manager = self.manager.get_resource_manager(r_type)
r_id = manager.resource_type.id
# TODO only fetch resource with the given ids.
return {
r[r_... | python | def get_resource_tag_map(self, r_type, ids):
"""
Returns a mapping of {resource_id: {tagkey: tagvalue}}
"""
manager = self.manager.get_resource_manager(r_type)
r_id = manager.resource_type.id
# TODO only fetch resource with the given ids.
return {
r[r_... | [
"def",
"get_resource_tag_map",
"(",
"self",
",",
"r_type",
",",
"ids",
")",
":",
"manager",
"=",
"self",
".",
"manager",
".",
"get_resource_manager",
"(",
"r_type",
")",
"r_id",
"=",
"manager",
".",
"resource_type",
".",
"id",
"# TODO only fetch resource with th... | Returns a mapping of {resource_id: {tagkey: tagvalue}} | [
"Returns",
"a",
"mapping",
"of",
"{",
"resource_id",
":",
"{",
"tagkey",
":",
"tagvalue",
"}}"
] | 52ef732eb3d7bc939d1579faf519314814695c08 | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/tags.py#L1071-L1081 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.