repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
foremast/foremast
|
src/foremast/elb/destroy_elb/__main__.py
|
main
|
def main():
"""Destroy any ELB related Resources."""
logging.basicConfig(format=LOGGING_FORMAT)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
assert destroy_elb(**vars(args))
|
python
|
def main():
"""Destroy any ELB related Resources."""
logging.basicConfig(format=LOGGING_FORMAT)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
assert destroy_elb(**vars(args))
|
[
"def",
"main",
"(",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"LOGGING_FORMAT",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"add_debug",
"(",
"parser",
")",
"add_app",
"(",
"parser",
")",
"add_env",
"(",
"parser",
")",
"add_region",
"(",
"parser",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"logging",
".",
"getLogger",
"(",
"__package__",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
".",
"setLevel",
"(",
"args",
".",
"debug",
")",
"assert",
"destroy_elb",
"(",
"*",
"*",
"vars",
"(",
"args",
")",
")"
] |
Destroy any ELB related Resources.
|
[
"Destroy",
"any",
"ELB",
"related",
"Resources",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/elb/destroy_elb/__main__.py#L27-L40
|
train
|
foremast/foremast
|
src/foremast/utils/security_group.py
|
get_security_group_id
|
def get_security_group_id(name='', env='', region=''):
"""Get a security group ID.
Args:
name (str): Security Group name to find.
env (str): Deployment environment to search.
region (str): AWS Region to search.
Returns:
str: ID of Security Group, e.g. sg-xxxx.
Raises:
AssertionError: Call to Gate API was not successful.
SpinnakerSecurityGroupError: Security Group _name_ was not found for
_env_ in _region_.
"""
vpc_id = get_vpc_id(env, region)
LOG.info('Find %s sg in %s [%s] in %s', name, env, region, vpc_id)
url = '{0}/securityGroups/{1}/{2}/{3}?vpcId={4}'.format(API_URL, env, region, name, vpc_id)
response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
assert response.ok
result = response.json()
try:
security_group_id = result['id']
except KeyError:
msg = 'Security group ({0}) not found'.format(name)
raise SpinnakerSecurityGroupError(msg)
LOG.info('Found: %s', security_group_id)
return security_group_id
|
python
|
def get_security_group_id(name='', env='', region=''):
"""Get a security group ID.
Args:
name (str): Security Group name to find.
env (str): Deployment environment to search.
region (str): AWS Region to search.
Returns:
str: ID of Security Group, e.g. sg-xxxx.
Raises:
AssertionError: Call to Gate API was not successful.
SpinnakerSecurityGroupError: Security Group _name_ was not found for
_env_ in _region_.
"""
vpc_id = get_vpc_id(env, region)
LOG.info('Find %s sg in %s [%s] in %s', name, env, region, vpc_id)
url = '{0}/securityGroups/{1}/{2}/{3}?vpcId={4}'.format(API_URL, env, region, name, vpc_id)
response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
assert response.ok
result = response.json()
try:
security_group_id = result['id']
except KeyError:
msg = 'Security group ({0}) not found'.format(name)
raise SpinnakerSecurityGroupError(msg)
LOG.info('Found: %s', security_group_id)
return security_group_id
|
[
"def",
"get_security_group_id",
"(",
"name",
"=",
"''",
",",
"env",
"=",
"''",
",",
"region",
"=",
"''",
")",
":",
"vpc_id",
"=",
"get_vpc_id",
"(",
"env",
",",
"region",
")",
"LOG",
".",
"info",
"(",
"'Find %s sg in %s [%s] in %s'",
",",
"name",
",",
"env",
",",
"region",
",",
"vpc_id",
")",
"url",
"=",
"'{0}/securityGroups/{1}/{2}/{3}?vpcId={4}'",
".",
"format",
"(",
"API_URL",
",",
"env",
",",
"region",
",",
"name",
",",
"vpc_id",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"verify",
"=",
"GATE_CA_BUNDLE",
",",
"cert",
"=",
"GATE_CLIENT_CERT",
")",
"assert",
"response",
".",
"ok",
"result",
"=",
"response",
".",
"json",
"(",
")",
"try",
":",
"security_group_id",
"=",
"result",
"[",
"'id'",
"]",
"except",
"KeyError",
":",
"msg",
"=",
"'Security group ({0}) not found'",
".",
"format",
"(",
"name",
")",
"raise",
"SpinnakerSecurityGroupError",
"(",
"msg",
")",
"LOG",
".",
"info",
"(",
"'Found: %s'",
",",
"security_group_id",
")",
"return",
"security_group_id"
] |
Get a security group ID.
Args:
name (str): Security Group name to find.
env (str): Deployment environment to search.
region (str): AWS Region to search.
Returns:
str: ID of Security Group, e.g. sg-xxxx.
Raises:
AssertionError: Call to Gate API was not successful.
SpinnakerSecurityGroupError: Security Group _name_ was not found for
_env_ in _region_.
|
[
"Get",
"a",
"security",
"group",
"ID",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/security_group.py#L30-L63
|
train
|
foremast/foremast
|
src/foremast/utils/security_group.py
|
remove_duplicate_sg
|
def remove_duplicate_sg(security_groups):
"""Removes duplicate Security Groups that share a same name alias
Args:
security_groups (list): A list of security group id to compare against SECURITYGROUP_REPLACEMENTS
Returns:
security_groups (list): A list of security groups with duplicate aliases removed
"""
for each_sg, duplicate_sg_name in SECURITYGROUP_REPLACEMENTS.items():
if each_sg in security_groups and duplicate_sg_name in security_groups:
LOG.info('Duplicate SG found. Removing %s in favor of %s.', duplicate_sg_name, each_sg)
security_groups.remove(duplicate_sg_name)
return security_groups
|
python
|
def remove_duplicate_sg(security_groups):
"""Removes duplicate Security Groups that share a same name alias
Args:
security_groups (list): A list of security group id to compare against SECURITYGROUP_REPLACEMENTS
Returns:
security_groups (list): A list of security groups with duplicate aliases removed
"""
for each_sg, duplicate_sg_name in SECURITYGROUP_REPLACEMENTS.items():
if each_sg in security_groups and duplicate_sg_name in security_groups:
LOG.info('Duplicate SG found. Removing %s in favor of %s.', duplicate_sg_name, each_sg)
security_groups.remove(duplicate_sg_name)
return security_groups
|
[
"def",
"remove_duplicate_sg",
"(",
"security_groups",
")",
":",
"for",
"each_sg",
",",
"duplicate_sg_name",
"in",
"SECURITYGROUP_REPLACEMENTS",
".",
"items",
"(",
")",
":",
"if",
"each_sg",
"in",
"security_groups",
"and",
"duplicate_sg_name",
"in",
"security_groups",
":",
"LOG",
".",
"info",
"(",
"'Duplicate SG found. Removing %s in favor of %s.'",
",",
"duplicate_sg_name",
",",
"each_sg",
")",
"security_groups",
".",
"remove",
"(",
"duplicate_sg_name",
")",
"return",
"security_groups"
] |
Removes duplicate Security Groups that share a same name alias
Args:
security_groups (list): A list of security group id to compare against SECURITYGROUP_REPLACEMENTS
Returns:
security_groups (list): A list of security groups with duplicate aliases removed
|
[
"Removes",
"duplicate",
"Security",
"Groups",
"that",
"share",
"a",
"same",
"name",
"alias"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/security_group.py#L66-L80
|
train
|
foremast/foremast
|
src/foremast/utils/encoding.py
|
generate_encoded_user_data
|
def generate_encoded_user_data(
env='dev',
region='us-east-1',
generated=None,
group_name='',
pipeline_type='',
canary=False,
):
r"""Generate base64 encoded User Data.
Args:
env (str): Deployment environment, e.g. dev, stage.
region (str): AWS Region, e.g. us-east-1.
generated (gogoutils.Generator): Generated naming formats.
group_name (str): Application group nane, e.g. core.
pipeline_type (str): Type of Foremast Pipeline to configure.
Returns:
str: base64 encoded User Data script.
#!/bin/bash
export CLOUD_ENVIRONMENT=dev
export CLOUD_ENVIRONMENT_C=dev
export CLOUD_ENVIRONMENT_P=dev
export CLOUD_ENVIRONMENT_S=dev
export CLOUD_APP=coreforrest
export CLOUD_APP_GROUP=forrest
export CLOUD_STACK=forrest
export EC2_REGION=us-east-1
export CLOUD_DOMAIN=dev.example.com
printenv | grep 'CLOUD\|EC2' | awk '$0="export "$0'>> /etc/gogo/cloud_env
"""
# We need to handle the case of prodp and prods for different URL generation
if env in ["prod", "prodp", "prods"]:
env_c, env_p, env_s = "prod", "prodp", "prods"
else:
env_c, env_p, env_s = env, env, env
user_data = get_template(
template_file='infrastructure/user_data.sh.j2',
env=env,
env_c=env_c,
env_p=env_p,
env_s=env_s,
region=region,
app_name=generated.app_name(),
group_name=group_name,
pipeline_type=pipeline_type,
canary=canary,
formats=generated,
)
return base64.b64encode(user_data.encode()).decode()
|
python
|
def generate_encoded_user_data(
env='dev',
region='us-east-1',
generated=None,
group_name='',
pipeline_type='',
canary=False,
):
r"""Generate base64 encoded User Data.
Args:
env (str): Deployment environment, e.g. dev, stage.
region (str): AWS Region, e.g. us-east-1.
generated (gogoutils.Generator): Generated naming formats.
group_name (str): Application group nane, e.g. core.
pipeline_type (str): Type of Foremast Pipeline to configure.
Returns:
str: base64 encoded User Data script.
#!/bin/bash
export CLOUD_ENVIRONMENT=dev
export CLOUD_ENVIRONMENT_C=dev
export CLOUD_ENVIRONMENT_P=dev
export CLOUD_ENVIRONMENT_S=dev
export CLOUD_APP=coreforrest
export CLOUD_APP_GROUP=forrest
export CLOUD_STACK=forrest
export EC2_REGION=us-east-1
export CLOUD_DOMAIN=dev.example.com
printenv | grep 'CLOUD\|EC2' | awk '$0="export "$0'>> /etc/gogo/cloud_env
"""
# We need to handle the case of prodp and prods for different URL generation
if env in ["prod", "prodp", "prods"]:
env_c, env_p, env_s = "prod", "prodp", "prods"
else:
env_c, env_p, env_s = env, env, env
user_data = get_template(
template_file='infrastructure/user_data.sh.j2',
env=env,
env_c=env_c,
env_p=env_p,
env_s=env_s,
region=region,
app_name=generated.app_name(),
group_name=group_name,
pipeline_type=pipeline_type,
canary=canary,
formats=generated,
)
return base64.b64encode(user_data.encode()).decode()
|
[
"def",
"generate_encoded_user_data",
"(",
"env",
"=",
"'dev'",
",",
"region",
"=",
"'us-east-1'",
",",
"generated",
"=",
"None",
",",
"group_name",
"=",
"''",
",",
"pipeline_type",
"=",
"''",
",",
"canary",
"=",
"False",
",",
")",
":",
"# We need to handle the case of prodp and prods for different URL generation",
"if",
"env",
"in",
"[",
"\"prod\"",
",",
"\"prodp\"",
",",
"\"prods\"",
"]",
":",
"env_c",
",",
"env_p",
",",
"env_s",
"=",
"\"prod\"",
",",
"\"prodp\"",
",",
"\"prods\"",
"else",
":",
"env_c",
",",
"env_p",
",",
"env_s",
"=",
"env",
",",
"env",
",",
"env",
"user_data",
"=",
"get_template",
"(",
"template_file",
"=",
"'infrastructure/user_data.sh.j2'",
",",
"env",
"=",
"env",
",",
"env_c",
"=",
"env_c",
",",
"env_p",
"=",
"env_p",
",",
"env_s",
"=",
"env_s",
",",
"region",
"=",
"region",
",",
"app_name",
"=",
"generated",
".",
"app_name",
"(",
")",
",",
"group_name",
"=",
"group_name",
",",
"pipeline_type",
"=",
"pipeline_type",
",",
"canary",
"=",
"canary",
",",
"formats",
"=",
"generated",
",",
")",
"return",
"base64",
".",
"b64encode",
"(",
"user_data",
".",
"encode",
"(",
")",
")",
".",
"decode",
"(",
")"
] |
r"""Generate base64 encoded User Data.
Args:
env (str): Deployment environment, e.g. dev, stage.
region (str): AWS Region, e.g. us-east-1.
generated (gogoutils.Generator): Generated naming formats.
group_name (str): Application group nane, e.g. core.
pipeline_type (str): Type of Foremast Pipeline to configure.
Returns:
str: base64 encoded User Data script.
#!/bin/bash
export CLOUD_ENVIRONMENT=dev
export CLOUD_ENVIRONMENT_C=dev
export CLOUD_ENVIRONMENT_P=dev
export CLOUD_ENVIRONMENT_S=dev
export CLOUD_APP=coreforrest
export CLOUD_APP_GROUP=forrest
export CLOUD_STACK=forrest
export EC2_REGION=us-east-1
export CLOUD_DOMAIN=dev.example.com
printenv | grep 'CLOUD\|EC2' | awk '$0="export "$0'>> /etc/gogo/cloud_env
|
[
"r",
"Generate",
"base64",
"encoded",
"User",
"Data",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/encoding.py#L22-L74
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
prepare_infrastructure
|
def prepare_infrastructure():
"""Entry point for preparing the infrastructure in a specific env."""
runner = ForemastRunner()
runner.write_configs()
runner.create_app()
archaius = runner.configs[runner.env]['app']['archaius_enabled']
eureka = runner.configs[runner.env]['app']['eureka_enabled']
deploy_type = runner.configs['pipeline']['type']
if deploy_type not in ['s3', 'datapipeline']:
runner.create_iam()
# TODO: Refactor Archaius to be fully featured
if archaius:
runner.create_archaius()
runner.create_secgroups()
if eureka:
LOG.info("Eureka Enabled, skipping ELB and DNS setup")
elif deploy_type == "lambda":
LOG.info("Lambda Enabled, skipping ELB and DNS setup")
runner.create_awslambda()
elif deploy_type == "s3":
runner.create_s3app()
elif deploy_type == 'datapipeline':
runner.create_datapipeline()
else:
LOG.info("No Eureka, running ELB and DNS setup")
runner.create_elb()
runner.create_dns()
runner.slack_notify()
runner.cleanup()
|
python
|
def prepare_infrastructure():
"""Entry point for preparing the infrastructure in a specific env."""
runner = ForemastRunner()
runner.write_configs()
runner.create_app()
archaius = runner.configs[runner.env]['app']['archaius_enabled']
eureka = runner.configs[runner.env]['app']['eureka_enabled']
deploy_type = runner.configs['pipeline']['type']
if deploy_type not in ['s3', 'datapipeline']:
runner.create_iam()
# TODO: Refactor Archaius to be fully featured
if archaius:
runner.create_archaius()
runner.create_secgroups()
if eureka:
LOG.info("Eureka Enabled, skipping ELB and DNS setup")
elif deploy_type == "lambda":
LOG.info("Lambda Enabled, skipping ELB and DNS setup")
runner.create_awslambda()
elif deploy_type == "s3":
runner.create_s3app()
elif deploy_type == 'datapipeline':
runner.create_datapipeline()
else:
LOG.info("No Eureka, running ELB and DNS setup")
runner.create_elb()
runner.create_dns()
runner.slack_notify()
runner.cleanup()
|
[
"def",
"prepare_infrastructure",
"(",
")",
":",
"runner",
"=",
"ForemastRunner",
"(",
")",
"runner",
".",
"write_configs",
"(",
")",
"runner",
".",
"create_app",
"(",
")",
"archaius",
"=",
"runner",
".",
"configs",
"[",
"runner",
".",
"env",
"]",
"[",
"'app'",
"]",
"[",
"'archaius_enabled'",
"]",
"eureka",
"=",
"runner",
".",
"configs",
"[",
"runner",
".",
"env",
"]",
"[",
"'app'",
"]",
"[",
"'eureka_enabled'",
"]",
"deploy_type",
"=",
"runner",
".",
"configs",
"[",
"'pipeline'",
"]",
"[",
"'type'",
"]",
"if",
"deploy_type",
"not",
"in",
"[",
"'s3'",
",",
"'datapipeline'",
"]",
":",
"runner",
".",
"create_iam",
"(",
")",
"# TODO: Refactor Archaius to be fully featured",
"if",
"archaius",
":",
"runner",
".",
"create_archaius",
"(",
")",
"runner",
".",
"create_secgroups",
"(",
")",
"if",
"eureka",
":",
"LOG",
".",
"info",
"(",
"\"Eureka Enabled, skipping ELB and DNS setup\"",
")",
"elif",
"deploy_type",
"==",
"\"lambda\"",
":",
"LOG",
".",
"info",
"(",
"\"Lambda Enabled, skipping ELB and DNS setup\"",
")",
"runner",
".",
"create_awslambda",
"(",
")",
"elif",
"deploy_type",
"==",
"\"s3\"",
":",
"runner",
".",
"create_s3app",
"(",
")",
"elif",
"deploy_type",
"==",
"'datapipeline'",
":",
"runner",
".",
"create_datapipeline",
"(",
")",
"else",
":",
"LOG",
".",
"info",
"(",
"\"No Eureka, running ELB and DNS setup\"",
")",
"runner",
".",
"create_elb",
"(",
")",
"runner",
".",
"create_dns",
"(",
")",
"runner",
".",
"slack_notify",
"(",
")",
"runner",
".",
"cleanup",
"(",
")"
] |
Entry point for preparing the infrastructure in a specific env.
|
[
"Entry",
"point",
"for",
"preparing",
"the",
"infrastructure",
"in",
"a",
"specific",
"env",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L250-L283
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
prepare_app_pipeline
|
def prepare_app_pipeline():
"""Entry point for application setup and initial pipeline in Spinnaker."""
runner = ForemastRunner()
runner.write_configs()
runner.create_app()
runner.create_pipeline()
runner.cleanup()
|
python
|
def prepare_app_pipeline():
"""Entry point for application setup and initial pipeline in Spinnaker."""
runner = ForemastRunner()
runner.write_configs()
runner.create_app()
runner.create_pipeline()
runner.cleanup()
|
[
"def",
"prepare_app_pipeline",
"(",
")",
":",
"runner",
"=",
"ForemastRunner",
"(",
")",
"runner",
".",
"write_configs",
"(",
")",
"runner",
".",
"create_app",
"(",
")",
"runner",
".",
"create_pipeline",
"(",
")",
"runner",
".",
"cleanup",
"(",
")"
] |
Entry point for application setup and initial pipeline in Spinnaker.
|
[
"Entry",
"point",
"for",
"application",
"setup",
"and",
"initial",
"pipeline",
"in",
"Spinnaker",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L286-L292
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
prepare_onetime_pipeline
|
def prepare_onetime_pipeline():
"""Entry point for single use pipeline setup in the defined app."""
runner = ForemastRunner()
runner.write_configs()
runner.create_pipeline(onetime=os.getenv('ENV'))
runner.cleanup()
|
python
|
def prepare_onetime_pipeline():
"""Entry point for single use pipeline setup in the defined app."""
runner = ForemastRunner()
runner.write_configs()
runner.create_pipeline(onetime=os.getenv('ENV'))
runner.cleanup()
|
[
"def",
"prepare_onetime_pipeline",
"(",
")",
":",
"runner",
"=",
"ForemastRunner",
"(",
")",
"runner",
".",
"write_configs",
"(",
")",
"runner",
".",
"create_pipeline",
"(",
"onetime",
"=",
"os",
".",
"getenv",
"(",
"'ENV'",
")",
")",
"runner",
".",
"cleanup",
"(",
")"
] |
Entry point for single use pipeline setup in the defined app.
|
[
"Entry",
"point",
"for",
"single",
"use",
"pipeline",
"setup",
"in",
"the",
"defined",
"app",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L295-L300
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.write_configs
|
def write_configs(self):
"""Generate the configurations needed for pipes."""
utils.banner("Generating Configs")
if not self.runway_dir:
app_configs = configs.process_git_configs(git_short=self.git_short)
else:
app_configs = configs.process_runway_configs(runway_dir=self.runway_dir)
self.configs = configs.write_variables(
app_configs=app_configs, out_file=self.raw_path, git_short=self.git_short)
|
python
|
def write_configs(self):
"""Generate the configurations needed for pipes."""
utils.banner("Generating Configs")
if not self.runway_dir:
app_configs = configs.process_git_configs(git_short=self.git_short)
else:
app_configs = configs.process_runway_configs(runway_dir=self.runway_dir)
self.configs = configs.write_variables(
app_configs=app_configs, out_file=self.raw_path, git_short=self.git_short)
|
[
"def",
"write_configs",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Generating Configs\"",
")",
"if",
"not",
"self",
".",
"runway_dir",
":",
"app_configs",
"=",
"configs",
".",
"process_git_configs",
"(",
"git_short",
"=",
"self",
".",
"git_short",
")",
"else",
":",
"app_configs",
"=",
"configs",
".",
"process_runway_configs",
"(",
"runway_dir",
"=",
"self",
".",
"runway_dir",
")",
"self",
".",
"configs",
"=",
"configs",
".",
"write_variables",
"(",
"app_configs",
"=",
"app_configs",
",",
"out_file",
"=",
"self",
".",
"raw_path",
",",
"git_short",
"=",
"self",
".",
"git_short",
")"
] |
Generate the configurations needed for pipes.
|
[
"Generate",
"the",
"configurations",
"needed",
"for",
"pipes",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L72-L81
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.create_app
|
def create_app(self):
"""Create the spinnaker application."""
utils.banner("Creating Spinnaker App")
spinnakerapp = app.SpinnakerApp(app=self.app, email=self.email, project=self.group, repo=self.repo,
pipeline_config=self.configs['pipeline'])
spinnakerapp.create_app()
|
python
|
def create_app(self):
"""Create the spinnaker application."""
utils.banner("Creating Spinnaker App")
spinnakerapp = app.SpinnakerApp(app=self.app, email=self.email, project=self.group, repo=self.repo,
pipeline_config=self.configs['pipeline'])
spinnakerapp.create_app()
|
[
"def",
"create_app",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Creating Spinnaker App\"",
")",
"spinnakerapp",
"=",
"app",
".",
"SpinnakerApp",
"(",
"app",
"=",
"self",
".",
"app",
",",
"email",
"=",
"self",
".",
"email",
",",
"project",
"=",
"self",
".",
"group",
",",
"repo",
"=",
"self",
".",
"repo",
",",
"pipeline_config",
"=",
"self",
".",
"configs",
"[",
"'pipeline'",
"]",
")",
"spinnakerapp",
".",
"create_app",
"(",
")"
] |
Create the spinnaker application.
|
[
"Create",
"the",
"spinnaker",
"application",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L83-L88
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.create_iam
|
def create_iam(self):
"""Create IAM resources."""
utils.banner("Creating IAM")
iam.create_iam_resources(env=self.env, app=self.app)
|
python
|
def create_iam(self):
"""Create IAM resources."""
utils.banner("Creating IAM")
iam.create_iam_resources(env=self.env, app=self.app)
|
[
"def",
"create_iam",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Creating IAM\"",
")",
"iam",
".",
"create_iam_resources",
"(",
"env",
"=",
"self",
".",
"env",
",",
"app",
"=",
"self",
".",
"app",
")"
] |
Create IAM resources.
|
[
"Create",
"IAM",
"resources",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L124-L127
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.create_archaius
|
def create_archaius(self):
"""Create S3 bucket for Archaius."""
utils.banner("Creating S3")
s3.init_properties(env=self.env, app=self.app)
|
python
|
def create_archaius(self):
"""Create S3 bucket for Archaius."""
utils.banner("Creating S3")
s3.init_properties(env=self.env, app=self.app)
|
[
"def",
"create_archaius",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Creating S3\"",
")",
"s3",
".",
"init_properties",
"(",
"env",
"=",
"self",
".",
"env",
",",
"app",
"=",
"self",
".",
"app",
")"
] |
Create S3 bucket for Archaius.
|
[
"Create",
"S3",
"bucket",
"for",
"Archaius",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L129-L132
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.create_s3app
|
def create_s3app(self):
"""Create S3 infra for s3 applications"""
utils.banner("Creating S3 App Infrastructure")
primary_region = self.configs['pipeline']['primary_region']
s3obj = s3.S3Apps(app=self.app,
env=self.env,
region=self.region,
prop_path=self.json_path,
primary_region=primary_region)
s3obj.create_bucket()
|
python
|
def create_s3app(self):
"""Create S3 infra for s3 applications"""
utils.banner("Creating S3 App Infrastructure")
primary_region = self.configs['pipeline']['primary_region']
s3obj = s3.S3Apps(app=self.app,
env=self.env,
region=self.region,
prop_path=self.json_path,
primary_region=primary_region)
s3obj.create_bucket()
|
[
"def",
"create_s3app",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Creating S3 App Infrastructure\"",
")",
"primary_region",
"=",
"self",
".",
"configs",
"[",
"'pipeline'",
"]",
"[",
"'primary_region'",
"]",
"s3obj",
"=",
"s3",
".",
"S3Apps",
"(",
"app",
"=",
"self",
".",
"app",
",",
"env",
"=",
"self",
".",
"env",
",",
"region",
"=",
"self",
".",
"region",
",",
"prop_path",
"=",
"self",
".",
"json_path",
",",
"primary_region",
"=",
"primary_region",
")",
"s3obj",
".",
"create_bucket",
"(",
")"
] |
Create S3 infra for s3 applications
|
[
"Create",
"S3",
"infra",
"for",
"s3",
"applications"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L134-L143
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.deploy_s3app
|
def deploy_s3app(self):
"""Deploys artifacts contents to S3 bucket"""
utils.banner("Deploying S3 App")
primary_region = self.configs['pipeline']['primary_region']
s3obj = s3.S3Deployment(
app=self.app,
env=self.env,
region=self.region,
prop_path=self.json_path,
artifact_path=self.artifact_path,
artifact_version=self.artifact_version,
primary_region=primary_region)
s3obj.upload_artifacts()
|
python
|
def deploy_s3app(self):
"""Deploys artifacts contents to S3 bucket"""
utils.banner("Deploying S3 App")
primary_region = self.configs['pipeline']['primary_region']
s3obj = s3.S3Deployment(
app=self.app,
env=self.env,
region=self.region,
prop_path=self.json_path,
artifact_path=self.artifact_path,
artifact_version=self.artifact_version,
primary_region=primary_region)
s3obj.upload_artifacts()
|
[
"def",
"deploy_s3app",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Deploying S3 App\"",
")",
"primary_region",
"=",
"self",
".",
"configs",
"[",
"'pipeline'",
"]",
"[",
"'primary_region'",
"]",
"s3obj",
"=",
"s3",
".",
"S3Deployment",
"(",
"app",
"=",
"self",
".",
"app",
",",
"env",
"=",
"self",
".",
"env",
",",
"region",
"=",
"self",
".",
"region",
",",
"prop_path",
"=",
"self",
".",
"json_path",
",",
"artifact_path",
"=",
"self",
".",
"artifact_path",
",",
"artifact_version",
"=",
"self",
".",
"artifact_version",
",",
"primary_region",
"=",
"primary_region",
")",
"s3obj",
".",
"upload_artifacts",
"(",
")"
] |
Deploys artifacts contents to S3 bucket
|
[
"Deploys",
"artifacts",
"contents",
"to",
"S3",
"bucket"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L145-L157
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.promote_s3app
|
def promote_s3app(self):
"""promotes S3 deployment to LATEST"""
utils.banner("Promoting S3 App")
primary_region = self.configs['pipeline']['primary_region']
s3obj = s3.S3Deployment(
app=self.app,
env=self.env,
region=self.region,
prop_path=self.json_path,
artifact_path=self.artifact_path,
artifact_version=self.artifact_version,
primary_region=primary_region)
s3obj.promote_artifacts(promote_stage=self.promote_stage)
|
python
|
def promote_s3app(self):
"""promotes S3 deployment to LATEST"""
utils.banner("Promoting S3 App")
primary_region = self.configs['pipeline']['primary_region']
s3obj = s3.S3Deployment(
app=self.app,
env=self.env,
region=self.region,
prop_path=self.json_path,
artifact_path=self.artifact_path,
artifact_version=self.artifact_version,
primary_region=primary_region)
s3obj.promote_artifacts(promote_stage=self.promote_stage)
|
[
"def",
"promote_s3app",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Promoting S3 App\"",
")",
"primary_region",
"=",
"self",
".",
"configs",
"[",
"'pipeline'",
"]",
"[",
"'primary_region'",
"]",
"s3obj",
"=",
"s3",
".",
"S3Deployment",
"(",
"app",
"=",
"self",
".",
"app",
",",
"env",
"=",
"self",
".",
"env",
",",
"region",
"=",
"self",
".",
"region",
",",
"prop_path",
"=",
"self",
".",
"json_path",
",",
"artifact_path",
"=",
"self",
".",
"artifact_path",
",",
"artifact_version",
"=",
"self",
".",
"artifact_version",
",",
"primary_region",
"=",
"primary_region",
")",
"s3obj",
".",
"promote_artifacts",
"(",
"promote_stage",
"=",
"self",
".",
"promote_stage",
")"
] |
promotes S3 deployment to LATEST
|
[
"promotes",
"S3",
"deployment",
"to",
"LATEST"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L159-L171
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.create_elb
|
def create_elb(self):
"""Create the ELB for the defined environment."""
utils.banner("Creating ELB")
elbobj = elb.SpinnakerELB(app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
elbobj.create_elb()
|
python
|
def create_elb(self):
"""Create the ELB for the defined environment."""
utils.banner("Creating ELB")
elbobj = elb.SpinnakerELB(app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
elbobj.create_elb()
|
[
"def",
"create_elb",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Creating ELB\"",
")",
"elbobj",
"=",
"elb",
".",
"SpinnakerELB",
"(",
"app",
"=",
"self",
".",
"app",
",",
"env",
"=",
"self",
".",
"env",
",",
"region",
"=",
"self",
".",
"region",
",",
"prop_path",
"=",
"self",
".",
"json_path",
")",
"elbobj",
".",
"create_elb",
"(",
")"
] |
Create the ELB for the defined environment.
|
[
"Create",
"the",
"ELB",
"for",
"the",
"defined",
"environment",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L191-L195
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.create_dns
|
def create_dns(self):
"""Create DNS for the defined app and environment."""
utils.banner("Creating DNS")
elb_subnet = self.configs[self.env]['elb']['subnet_purpose']
regions = self.configs[self.env]['regions']
failover = self.configs[self.env]['dns']['failover_dns']
primary_region = self.configs['pipeline']['primary_region']
regionspecific_dns = self.configs[self.env]['dns']['region_specific']
dnsobj = dns.SpinnakerDns(
app=self.app, env=self.env, region=self.region, prop_path=self.json_path, elb_subnet=elb_subnet)
if len(regions) > 1 and failover:
dnsobj.create_elb_dns(regionspecific=True)
dnsobj.create_failover_dns(primary_region=primary_region)
else:
if regionspecific_dns:
dnsobj.create_elb_dns(regionspecific=True)
if self.region == primary_region:
dnsobj.create_elb_dns(regionspecific=False)
|
python
|
def create_dns(self):
"""Create DNS for the defined app and environment."""
utils.banner("Creating DNS")
elb_subnet = self.configs[self.env]['elb']['subnet_purpose']
regions = self.configs[self.env]['regions']
failover = self.configs[self.env]['dns']['failover_dns']
primary_region = self.configs['pipeline']['primary_region']
regionspecific_dns = self.configs[self.env]['dns']['region_specific']
dnsobj = dns.SpinnakerDns(
app=self.app, env=self.env, region=self.region, prop_path=self.json_path, elb_subnet=elb_subnet)
if len(regions) > 1 and failover:
dnsobj.create_elb_dns(regionspecific=True)
dnsobj.create_failover_dns(primary_region=primary_region)
else:
if regionspecific_dns:
dnsobj.create_elb_dns(regionspecific=True)
if self.region == primary_region:
dnsobj.create_elb_dns(regionspecific=False)
|
[
"def",
"create_dns",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Creating DNS\"",
")",
"elb_subnet",
"=",
"self",
".",
"configs",
"[",
"self",
".",
"env",
"]",
"[",
"'elb'",
"]",
"[",
"'subnet_purpose'",
"]",
"regions",
"=",
"self",
".",
"configs",
"[",
"self",
".",
"env",
"]",
"[",
"'regions'",
"]",
"failover",
"=",
"self",
".",
"configs",
"[",
"self",
".",
"env",
"]",
"[",
"'dns'",
"]",
"[",
"'failover_dns'",
"]",
"primary_region",
"=",
"self",
".",
"configs",
"[",
"'pipeline'",
"]",
"[",
"'primary_region'",
"]",
"regionspecific_dns",
"=",
"self",
".",
"configs",
"[",
"self",
".",
"env",
"]",
"[",
"'dns'",
"]",
"[",
"'region_specific'",
"]",
"dnsobj",
"=",
"dns",
".",
"SpinnakerDns",
"(",
"app",
"=",
"self",
".",
"app",
",",
"env",
"=",
"self",
".",
"env",
",",
"region",
"=",
"self",
".",
"region",
",",
"prop_path",
"=",
"self",
".",
"json_path",
",",
"elb_subnet",
"=",
"elb_subnet",
")",
"if",
"len",
"(",
"regions",
")",
">",
"1",
"and",
"failover",
":",
"dnsobj",
".",
"create_elb_dns",
"(",
"regionspecific",
"=",
"True",
")",
"dnsobj",
".",
"create_failover_dns",
"(",
"primary_region",
"=",
"primary_region",
")",
"else",
":",
"if",
"regionspecific_dns",
":",
"dnsobj",
".",
"create_elb_dns",
"(",
"regionspecific",
"=",
"True",
")",
"if",
"self",
".",
"region",
"==",
"primary_region",
":",
"dnsobj",
".",
"create_elb_dns",
"(",
"regionspecific",
"=",
"False",
")"
] |
Create DNS for the defined app and environment.
|
[
"Create",
"DNS",
"for",
"the",
"defined",
"app",
"and",
"environment",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L197-L217
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.create_autoscaling_policy
|
def create_autoscaling_policy(self):
"""Create Scaling Policy for app in environment"""
utils.banner("Creating Scaling Policy")
policyobj = autoscaling_policy.AutoScalingPolicy(
app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
policyobj.create_policy()
|
python
|
def create_autoscaling_policy(self):
"""Create Scaling Policy for app in environment"""
utils.banner("Creating Scaling Policy")
policyobj = autoscaling_policy.AutoScalingPolicy(
app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
policyobj.create_policy()
|
[
"def",
"create_autoscaling_policy",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Creating Scaling Policy\"",
")",
"policyobj",
"=",
"autoscaling_policy",
".",
"AutoScalingPolicy",
"(",
"app",
"=",
"self",
".",
"app",
",",
"env",
"=",
"self",
".",
"env",
",",
"region",
"=",
"self",
".",
"region",
",",
"prop_path",
"=",
"self",
".",
"json_path",
")",
"policyobj",
".",
"create_policy",
"(",
")"
] |
Create Scaling Policy for app in environment
|
[
"Create",
"Scaling",
"Policy",
"for",
"app",
"in",
"environment"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L219-L224
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.create_datapipeline
|
def create_datapipeline(self):
"""Creates data pipeline and adds definition"""
utils.banner("Creating Data Pipeline")
dpobj = datapipeline.AWSDataPipeline(app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
dpobj.create_datapipeline()
dpobj.set_pipeline_definition()
if self.configs[self.env].get('datapipeline').get('activate_on_deploy'):
dpobj.activate_pipeline()
|
python
|
def create_datapipeline(self):
"""Creates data pipeline and adds definition"""
utils.banner("Creating Data Pipeline")
dpobj = datapipeline.AWSDataPipeline(app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
dpobj.create_datapipeline()
dpobj.set_pipeline_definition()
if self.configs[self.env].get('datapipeline').get('activate_on_deploy'):
dpobj.activate_pipeline()
|
[
"def",
"create_datapipeline",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Creating Data Pipeline\"",
")",
"dpobj",
"=",
"datapipeline",
".",
"AWSDataPipeline",
"(",
"app",
"=",
"self",
".",
"app",
",",
"env",
"=",
"self",
".",
"env",
",",
"region",
"=",
"self",
".",
"region",
",",
"prop_path",
"=",
"self",
".",
"json_path",
")",
"dpobj",
".",
"create_datapipeline",
"(",
")",
"dpobj",
".",
"set_pipeline_definition",
"(",
")",
"if",
"self",
".",
"configs",
"[",
"self",
".",
"env",
"]",
".",
"get",
"(",
"'datapipeline'",
")",
".",
"get",
"(",
"'activate_on_deploy'",
")",
":",
"dpobj",
".",
"activate_pipeline",
"(",
")"
] |
Creates data pipeline and adds definition
|
[
"Creates",
"data",
"pipeline",
"and",
"adds",
"definition"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L226-L233
|
train
|
foremast/foremast
|
src/foremast/runner.py
|
ForemastRunner.slack_notify
|
def slack_notify(self):
"""Send out a slack notification."""
utils.banner("Sending slack notification")
if self.env.startswith("prod"):
notify = slacknotify.SlackNotification(app=self.app, env=self.env, prop_path=self.json_path)
notify.post_message()
else:
LOG.info("No slack message sent, not production environment")
|
python
|
def slack_notify(self):
"""Send out a slack notification."""
utils.banner("Sending slack notification")
if self.env.startswith("prod"):
notify = slacknotify.SlackNotification(app=self.app, env=self.env, prop_path=self.json_path)
notify.post_message()
else:
LOG.info("No slack message sent, not production environment")
|
[
"def",
"slack_notify",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Sending slack notification\"",
")",
"if",
"self",
".",
"env",
".",
"startswith",
"(",
"\"prod\"",
")",
":",
"notify",
"=",
"slacknotify",
".",
"SlackNotification",
"(",
"app",
"=",
"self",
".",
"app",
",",
"env",
"=",
"self",
".",
"env",
",",
"prop_path",
"=",
"self",
".",
"json_path",
")",
"notify",
".",
"post_message",
"(",
")",
"else",
":",
"LOG",
".",
"info",
"(",
"\"No slack message sent, not production environment\"",
")"
] |
Send out a slack notification.
|
[
"Send",
"out",
"a",
"slack",
"notification",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/runner.py#L235-L243
|
train
|
foremast/foremast
|
src/foremast/args.py
|
add_debug
|
def add_debug(parser):
"""Add a `debug` flag to the _parser_."""
parser.add_argument(
'-d', '--debug', action='store_const', const=logging.DEBUG, default=logging.INFO, help='Set DEBUG output')
|
python
|
def add_debug(parser):
"""Add a `debug` flag to the _parser_."""
parser.add_argument(
'-d', '--debug', action='store_const', const=logging.DEBUG, default=logging.INFO, help='Set DEBUG output')
|
[
"def",
"add_debug",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--debug'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"logging",
".",
"DEBUG",
",",
"default",
"=",
"logging",
".",
"INFO",
",",
"help",
"=",
"'Set DEBUG output'",
")"
] |
Add a `debug` flag to the _parser_.
|
[
"Add",
"a",
"debug",
"flag",
"to",
"the",
"_parser_",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/args.py#L28-L31
|
train
|
foremast/foremast
|
src/foremast/args.py
|
add_env
|
def add_env(parser):
"""Add an `env` flag to the _parser_."""
parser.add_argument(
'-e', '--env', choices=ENVS, default=os.getenv('ENV', default='dev'), help='Deploy environment, overrides $ENV')
|
python
|
def add_env(parser):
"""Add an `env` flag to the _parser_."""
parser.add_argument(
'-e', '--env', choices=ENVS, default=os.getenv('ENV', default='dev'), help='Deploy environment, overrides $ENV')
|
[
"def",
"add_env",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'-e'",
",",
"'--env'",
",",
"choices",
"=",
"ENVS",
",",
"default",
"=",
"os",
".",
"getenv",
"(",
"'ENV'",
",",
"default",
"=",
"'dev'",
")",
",",
"help",
"=",
"'Deploy environment, overrides $ENV'",
")"
] |
Add an `env` flag to the _parser_.
|
[
"Add",
"an",
"env",
"flag",
"to",
"the",
"_parser_",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/args.py#L34-L37
|
train
|
foremast/foremast
|
src/foremast/autoscaling_policy/__main__.py
|
main
|
def main():
"""CLI entrypoint for scaling policy creation"""
logging.basicConfig(format=LOGGING_FORMAT)
log = logging.getLogger(__name__)
parser = argparse.ArgumentParser()
add_debug(parser)
add_app(parser)
add_properties(parser)
add_env(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
log.debug('Parsed arguments: %s', args)
asgpolicy = AutoScalingPolicy(app=args.app, prop_path=args.properties, env=args.env, region=args.region)
asgpolicy.create_policy()
|
python
|
def main():
"""CLI entrypoint for scaling policy creation"""
logging.basicConfig(format=LOGGING_FORMAT)
log = logging.getLogger(__name__)
parser = argparse.ArgumentParser()
add_debug(parser)
add_app(parser)
add_properties(parser)
add_env(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
log.debug('Parsed arguments: %s', args)
asgpolicy = AutoScalingPolicy(app=args.app, prop_path=args.properties, env=args.env, region=args.region)
asgpolicy.create_policy()
|
[
"def",
"main",
"(",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"LOGGING_FORMAT",
")",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"add_debug",
"(",
"parser",
")",
"add_app",
"(",
"parser",
")",
"add_properties",
"(",
"parser",
")",
"add_env",
"(",
"parser",
")",
"add_region",
"(",
"parser",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"logging",
".",
"getLogger",
"(",
"__package__",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
".",
"setLevel",
"(",
"args",
".",
"debug",
")",
"log",
".",
"debug",
"(",
"'Parsed arguments: %s'",
",",
"args",
")",
"asgpolicy",
"=",
"AutoScalingPolicy",
"(",
"app",
"=",
"args",
".",
"app",
",",
"prop_path",
"=",
"args",
".",
"properties",
",",
"env",
"=",
"args",
".",
"env",
",",
"region",
"=",
"args",
".",
"region",
")",
"asgpolicy",
".",
"create_policy",
"(",
")"
] |
CLI entrypoint for scaling policy creation
|
[
"CLI",
"entrypoint",
"for",
"scaling",
"policy",
"creation"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/autoscaling_policy/__main__.py#L29-L48
|
train
|
foremast/foremast
|
src/foremast/awslambda/__main__.py
|
main
|
def main():
"""Create Lambda events."""
logging.basicConfig(format=LOGGING_FORMAT)
log = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_properties(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
log.debug('Parsed arguments: %s', args)
lambda_function = LambdaFunction(app=args.app, env=args.env, region=args.region, prop_path=args.properties)
lambda_function.create_lambda_function()
lambda_event = LambdaEvent(app=args.app, env=args.env, region=args.region, prop_path=args.properties)
lambda_event.create_lambda_events()
|
python
|
def main():
"""Create Lambda events."""
logging.basicConfig(format=LOGGING_FORMAT)
log = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_properties(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
log.debug('Parsed arguments: %s', args)
lambda_function = LambdaFunction(app=args.app, env=args.env, region=args.region, prop_path=args.properties)
lambda_function.create_lambda_function()
lambda_event = LambdaEvent(app=args.app, env=args.env, region=args.region, prop_path=args.properties)
lambda_event.create_lambda_events()
|
[
"def",
"main",
"(",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"LOGGING_FORMAT",
")",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"add_debug",
"(",
"parser",
")",
"add_app",
"(",
"parser",
")",
"add_env",
"(",
"parser",
")",
"add_properties",
"(",
"parser",
")",
"add_region",
"(",
"parser",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"logging",
".",
"getLogger",
"(",
"__package__",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
".",
"setLevel",
"(",
"args",
".",
"debug",
")",
"log",
".",
"debug",
"(",
"'Parsed arguments: %s'",
",",
"args",
")",
"lambda_function",
"=",
"LambdaFunction",
"(",
"app",
"=",
"args",
".",
"app",
",",
"env",
"=",
"args",
".",
"env",
",",
"region",
"=",
"args",
".",
"region",
",",
"prop_path",
"=",
"args",
".",
"properties",
")",
"lambda_function",
".",
"create_lambda_function",
"(",
")",
"lambda_event",
"=",
"LambdaEvent",
"(",
"app",
"=",
"args",
".",
"app",
",",
"env",
"=",
"args",
".",
"env",
",",
"region",
"=",
"args",
".",
"region",
",",
"prop_path",
"=",
"args",
".",
"properties",
")",
"lambda_event",
".",
"create_lambda_events",
"(",
")"
] |
Create Lambda events.
|
[
"Create",
"Lambda",
"events",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/awslambda/__main__.py#L29-L51
|
train
|
foremast/foremast
|
src/foremast/utils/slack.py
|
post_slack_message
|
def post_slack_message(message=None, channel=None, username=None, icon_emoji=None):
"""Format the message and post to the appropriate slack channel.
Args:
message (str): Message to post to slack
channel (str): Desired channel. Must start with #
"""
LOG.debug('Slack Channel: %s\nSlack Message: %s', channel, message)
slack = slacker.Slacker(SLACK_TOKEN)
try:
slack.chat.post_message(channel=channel, text=message, username=username, icon_emoji=icon_emoji)
LOG.info('Message posted to %s', channel)
except slacker.Error:
LOG.info("error posted message to %s", channel)
|
python
|
def post_slack_message(message=None, channel=None, username=None, icon_emoji=None):
"""Format the message and post to the appropriate slack channel.
Args:
message (str): Message to post to slack
channel (str): Desired channel. Must start with #
"""
LOG.debug('Slack Channel: %s\nSlack Message: %s', channel, message)
slack = slacker.Slacker(SLACK_TOKEN)
try:
slack.chat.post_message(channel=channel, text=message, username=username, icon_emoji=icon_emoji)
LOG.info('Message posted to %s', channel)
except slacker.Error:
LOG.info("error posted message to %s", channel)
|
[
"def",
"post_slack_message",
"(",
"message",
"=",
"None",
",",
"channel",
"=",
"None",
",",
"username",
"=",
"None",
",",
"icon_emoji",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"'Slack Channel: %s\\nSlack Message: %s'",
",",
"channel",
",",
"message",
")",
"slack",
"=",
"slacker",
".",
"Slacker",
"(",
"SLACK_TOKEN",
")",
"try",
":",
"slack",
".",
"chat",
".",
"post_message",
"(",
"channel",
"=",
"channel",
",",
"text",
"=",
"message",
",",
"username",
"=",
"username",
",",
"icon_emoji",
"=",
"icon_emoji",
")",
"LOG",
".",
"info",
"(",
"'Message posted to %s'",
",",
"channel",
")",
"except",
"slacker",
".",
"Error",
":",
"LOG",
".",
"info",
"(",
"\"error posted message to %s\"",
",",
"channel",
")"
] |
Format the message and post to the appropriate slack channel.
Args:
message (str): Message to post to slack
channel (str): Desired channel. Must start with #
|
[
"Format",
"the",
"message",
"and",
"post",
"to",
"the",
"appropriate",
"slack",
"channel",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/slack.py#L26-L40
|
train
|
foremast/foremast
|
src/foremast/dns/destroy_dns/destroy_dns.py
|
destroy_dns
|
def destroy_dns(app='', env='dev', **_):
"""Destroy DNS records.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
regions (str): AWS region.
Returns:
bool: True upon successful completion.
"""
client = boto3.Session(profile_name=env).client('route53')
generated = get_details(app=app, env=env)
record = generated.dns_elb()
zone_ids = get_dns_zone_ids(env=env, facing='external')
for zone_id in zone_ids:
record_sets = client.list_resource_record_sets(
HostedZoneId=zone_id, StartRecordName=record, StartRecordType='CNAME', MaxItems='1')
for found_record in record_sets['ResourceRecordSets']:
assert destroy_record(client=client, found_record=found_record, record=record, zone_id=zone_id)
return True
|
python
|
def destroy_dns(app='', env='dev', **_):
"""Destroy DNS records.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
regions (str): AWS region.
Returns:
bool: True upon successful completion.
"""
client = boto3.Session(profile_name=env).client('route53')
generated = get_details(app=app, env=env)
record = generated.dns_elb()
zone_ids = get_dns_zone_ids(env=env, facing='external')
for zone_id in zone_ids:
record_sets = client.list_resource_record_sets(
HostedZoneId=zone_id, StartRecordName=record, StartRecordType='CNAME', MaxItems='1')
for found_record in record_sets['ResourceRecordSets']:
assert destroy_record(client=client, found_record=found_record, record=record, zone_id=zone_id)
return True
|
[
"def",
"destroy_dns",
"(",
"app",
"=",
"''",
",",
"env",
"=",
"'dev'",
",",
"*",
"*",
"_",
")",
":",
"client",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
")",
".",
"client",
"(",
"'route53'",
")",
"generated",
"=",
"get_details",
"(",
"app",
"=",
"app",
",",
"env",
"=",
"env",
")",
"record",
"=",
"generated",
".",
"dns_elb",
"(",
")",
"zone_ids",
"=",
"get_dns_zone_ids",
"(",
"env",
"=",
"env",
",",
"facing",
"=",
"'external'",
")",
"for",
"zone_id",
"in",
"zone_ids",
":",
"record_sets",
"=",
"client",
".",
"list_resource_record_sets",
"(",
"HostedZoneId",
"=",
"zone_id",
",",
"StartRecordName",
"=",
"record",
",",
"StartRecordType",
"=",
"'CNAME'",
",",
"MaxItems",
"=",
"'1'",
")",
"for",
"found_record",
"in",
"record_sets",
"[",
"'ResourceRecordSets'",
"]",
":",
"assert",
"destroy_record",
"(",
"client",
"=",
"client",
",",
"found_record",
"=",
"found_record",
",",
"record",
"=",
"record",
",",
"zone_id",
"=",
"zone_id",
")",
"return",
"True"
] |
Destroy DNS records.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
regions (str): AWS region.
Returns:
bool: True upon successful completion.
|
[
"Destroy",
"DNS",
"records",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/dns/destroy_dns/destroy_dns.py#L27-L52
|
train
|
foremast/foremast
|
src/foremast/dns/destroy_dns/destroy_dns.py
|
destroy_record
|
def destroy_record(client=None, found_record=None, record='', zone_id=''):
"""Destroy an individual DNS record.
Args:
client (botocore.client.Route53): Route 53 boto3 client.
found_record (dict): Route 53 record set::
{'Name': 'unicorn.forrest.dev.example.com.',
'ResourceRecords':
[{'Value':
'internal-unicornforrest-1777489395.us-east-1.elb.amazonaws.com'
}],
'TTL': 60,
'Type': 'CNAME'}
record (str): Application DNS record name. e.g.
zone_id (str): Route 53 Hosted Zone ID, e.g. /hostedzone/ZSVGJWJ979WQD.
Returns:
bool: True upon successful completion.
"""
LOG.debug('Found DNS record: %s', found_record)
if found_record['Name'].strip('.') == record:
dns_json = get_template(template_file='destroy/destroy_dns.json.j2', record=json.dumps(found_record))
dns_dict = json.loads(dns_json)
client.change_resource_record_sets(HostedZoneId=zone_id, ChangeBatch=dns_dict)
LOG.info('Destroyed "%s" in %s', found_record['Name'], zone_id)
else:
LOG.info('DNS record "%s" missing from %s.', record, zone_id)
LOG.debug('Found someone else\'s record: %s', found_record['Name'])
return True
|
python
|
def destroy_record(client=None, found_record=None, record='', zone_id=''):
"""Destroy an individual DNS record.
Args:
client (botocore.client.Route53): Route 53 boto3 client.
found_record (dict): Route 53 record set::
{'Name': 'unicorn.forrest.dev.example.com.',
'ResourceRecords':
[{'Value':
'internal-unicornforrest-1777489395.us-east-1.elb.amazonaws.com'
}],
'TTL': 60,
'Type': 'CNAME'}
record (str): Application DNS record name. e.g.
zone_id (str): Route 53 Hosted Zone ID, e.g. /hostedzone/ZSVGJWJ979WQD.
Returns:
bool: True upon successful completion.
"""
LOG.debug('Found DNS record: %s', found_record)
if found_record['Name'].strip('.') == record:
dns_json = get_template(template_file='destroy/destroy_dns.json.j2', record=json.dumps(found_record))
dns_dict = json.loads(dns_json)
client.change_resource_record_sets(HostedZoneId=zone_id, ChangeBatch=dns_dict)
LOG.info('Destroyed "%s" in %s', found_record['Name'], zone_id)
else:
LOG.info('DNS record "%s" missing from %s.', record, zone_id)
LOG.debug('Found someone else\'s record: %s', found_record['Name'])
return True
|
[
"def",
"destroy_record",
"(",
"client",
"=",
"None",
",",
"found_record",
"=",
"None",
",",
"record",
"=",
"''",
",",
"zone_id",
"=",
"''",
")",
":",
"LOG",
".",
"debug",
"(",
"'Found DNS record: %s'",
",",
"found_record",
")",
"if",
"found_record",
"[",
"'Name'",
"]",
".",
"strip",
"(",
"'.'",
")",
"==",
"record",
":",
"dns_json",
"=",
"get_template",
"(",
"template_file",
"=",
"'destroy/destroy_dns.json.j2'",
",",
"record",
"=",
"json",
".",
"dumps",
"(",
"found_record",
")",
")",
"dns_dict",
"=",
"json",
".",
"loads",
"(",
"dns_json",
")",
"client",
".",
"change_resource_record_sets",
"(",
"HostedZoneId",
"=",
"zone_id",
",",
"ChangeBatch",
"=",
"dns_dict",
")",
"LOG",
".",
"info",
"(",
"'Destroyed \"%s\" in %s'",
",",
"found_record",
"[",
"'Name'",
"]",
",",
"zone_id",
")",
"else",
":",
"LOG",
".",
"info",
"(",
"'DNS record \"%s\" missing from %s.'",
",",
"record",
",",
"zone_id",
")",
"LOG",
".",
"debug",
"(",
"'Found someone else\\'s record: %s'",
",",
"found_record",
"[",
"'Name'",
"]",
")",
"return",
"True"
] |
Destroy an individual DNS record.
Args:
client (botocore.client.Route53): Route 53 boto3 client.
found_record (dict): Route 53 record set::
{'Name': 'unicorn.forrest.dev.example.com.',
'ResourceRecords':
[{'Value':
'internal-unicornforrest-1777489395.us-east-1.elb.amazonaws.com'
}],
'TTL': 60,
'Type': 'CNAME'}
record (str): Application DNS record name. e.g.
zone_id (str): Route 53 Hosted Zone ID, e.g. /hostedzone/ZSVGJWJ979WQD.
Returns:
bool: True upon successful completion.
|
[
"Destroy",
"an",
"individual",
"DNS",
"record",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/dns/destroy_dns/destroy_dns.py#L55-L88
|
train
|
foremast/foremast
|
src/foremast/awslambda/sns_event/sns_event.py
|
create_sns_event
|
def create_sns_event(app_name, env, region, rules):
"""Create SNS lambda event from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): Trigger rules from the settings
"""
session = boto3.Session(profile_name=env, region_name=region)
sns_client = session.client('sns')
topic_name = rules.get('topic')
lambda_alias_arn = get_lambda_alias_arn(app=app_name, account=env, region=region)
topic_arn = get_sns_topic_arn(topic_name=topic_name, account=env, region=region)
protocol = 'lambda'
statement_id = '{}_sns_{}'.format(app_name, topic_name)
principal = 'sns.amazonaws.com'
add_lambda_permissions(
function=lambda_alias_arn,
statement_id=statement_id,
action='lambda:InvokeFunction',
principal=principal,
source_arn=topic_arn,
env=env,
region=region)
sns_client.subscribe(TopicArn=topic_arn, Protocol=protocol, Endpoint=lambda_alias_arn)
LOG.debug("SNS Lambda event created")
LOG.info("Created SNS event subscription on topic %s", topic_name)
|
python
|
def create_sns_event(app_name, env, region, rules):
"""Create SNS lambda event from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): Trigger rules from the settings
"""
session = boto3.Session(profile_name=env, region_name=region)
sns_client = session.client('sns')
topic_name = rules.get('topic')
lambda_alias_arn = get_lambda_alias_arn(app=app_name, account=env, region=region)
topic_arn = get_sns_topic_arn(topic_name=topic_name, account=env, region=region)
protocol = 'lambda'
statement_id = '{}_sns_{}'.format(app_name, topic_name)
principal = 'sns.amazonaws.com'
add_lambda_permissions(
function=lambda_alias_arn,
statement_id=statement_id,
action='lambda:InvokeFunction',
principal=principal,
source_arn=topic_arn,
env=env,
region=region)
sns_client.subscribe(TopicArn=topic_arn, Protocol=protocol, Endpoint=lambda_alias_arn)
LOG.debug("SNS Lambda event created")
LOG.info("Created SNS event subscription on topic %s", topic_name)
|
[
"def",
"create_sns_event",
"(",
"app_name",
",",
"env",
",",
"region",
",",
"rules",
")",
":",
"session",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
",",
"region_name",
"=",
"region",
")",
"sns_client",
"=",
"session",
".",
"client",
"(",
"'sns'",
")",
"topic_name",
"=",
"rules",
".",
"get",
"(",
"'topic'",
")",
"lambda_alias_arn",
"=",
"get_lambda_alias_arn",
"(",
"app",
"=",
"app_name",
",",
"account",
"=",
"env",
",",
"region",
"=",
"region",
")",
"topic_arn",
"=",
"get_sns_topic_arn",
"(",
"topic_name",
"=",
"topic_name",
",",
"account",
"=",
"env",
",",
"region",
"=",
"region",
")",
"protocol",
"=",
"'lambda'",
"statement_id",
"=",
"'{}_sns_{}'",
".",
"format",
"(",
"app_name",
",",
"topic_name",
")",
"principal",
"=",
"'sns.amazonaws.com'",
"add_lambda_permissions",
"(",
"function",
"=",
"lambda_alias_arn",
",",
"statement_id",
"=",
"statement_id",
",",
"action",
"=",
"'lambda:InvokeFunction'",
",",
"principal",
"=",
"principal",
",",
"source_arn",
"=",
"topic_arn",
",",
"env",
"=",
"env",
",",
"region",
"=",
"region",
")",
"sns_client",
".",
"subscribe",
"(",
"TopicArn",
"=",
"topic_arn",
",",
"Protocol",
"=",
"protocol",
",",
"Endpoint",
"=",
"lambda_alias_arn",
")",
"LOG",
".",
"debug",
"(",
"\"SNS Lambda event created\"",
")",
"LOG",
".",
"info",
"(",
"\"Created SNS event subscription on topic %s\"",
",",
"topic_name",
")"
] |
Create SNS lambda event from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): Trigger rules from the settings
|
[
"Create",
"SNS",
"lambda",
"event",
"from",
"rules",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/awslambda/sns_event/sns_event.py#L27-L58
|
train
|
foremast/foremast
|
src/foremast/awslambda/sns_event/destroy_sns_event/destroy_sns_event.py
|
destroy_sns_event
|
def destroy_sns_event(app_name, env, region):
""" Destroy all Lambda SNS subscriptions.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
Returns:
boolean: True if subscription destroyed successfully
"""
session = boto3.Session(profile_name=env, region_name=region)
sns_client = session.client('sns')
lambda_subscriptions = get_sns_subscriptions(app_name=app_name, env=env, region=region)
for subscription_arn in lambda_subscriptions:
sns_client.unsubscribe(SubscriptionArn=subscription_arn)
LOG.debug("Lambda SNS event deleted")
return True
|
python
|
def destroy_sns_event(app_name, env, region):
""" Destroy all Lambda SNS subscriptions.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
Returns:
boolean: True if subscription destroyed successfully
"""
session = boto3.Session(profile_name=env, region_name=region)
sns_client = session.client('sns')
lambda_subscriptions = get_sns_subscriptions(app_name=app_name, env=env, region=region)
for subscription_arn in lambda_subscriptions:
sns_client.unsubscribe(SubscriptionArn=subscription_arn)
LOG.debug("Lambda SNS event deleted")
return True
|
[
"def",
"destroy_sns_event",
"(",
"app_name",
",",
"env",
",",
"region",
")",
":",
"session",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
",",
"region_name",
"=",
"region",
")",
"sns_client",
"=",
"session",
".",
"client",
"(",
"'sns'",
")",
"lambda_subscriptions",
"=",
"get_sns_subscriptions",
"(",
"app_name",
"=",
"app_name",
",",
"env",
"=",
"env",
",",
"region",
"=",
"region",
")",
"for",
"subscription_arn",
"in",
"lambda_subscriptions",
":",
"sns_client",
".",
"unsubscribe",
"(",
"SubscriptionArn",
"=",
"subscription_arn",
")",
"LOG",
".",
"debug",
"(",
"\"Lambda SNS event deleted\"",
")",
"return",
"True"
] |
Destroy all Lambda SNS subscriptions.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
Returns:
boolean: True if subscription destroyed successfully
|
[
"Destroy",
"all",
"Lambda",
"SNS",
"subscriptions",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/awslambda/sns_event/destroy_sns_event/destroy_sns_event.py#L27-L47
|
train
|
foremast/foremast
|
src/foremast/elb/destroy_elb/destroy_elb.py
|
destroy_elb
|
def destroy_elb(app='', env='dev', region='us-east-1', **_):
"""Destroy ELB Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
True upon successful completion.
"""
task_json = get_template(
template_file='destroy/destroy_elb.json.j2',
app=app,
env=env,
region=region,
vpc=get_vpc_id(account=env, region=region))
wait_for_task(task_json)
return True
|
python
|
def destroy_elb(app='', env='dev', region='us-east-1', **_):
"""Destroy ELB Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
True upon successful completion.
"""
task_json = get_template(
template_file='destroy/destroy_elb.json.j2',
app=app,
env=env,
region=region,
vpc=get_vpc_id(account=env, region=region))
wait_for_task(task_json)
return True
|
[
"def",
"destroy_elb",
"(",
"app",
"=",
"''",
",",
"env",
"=",
"'dev'",
",",
"region",
"=",
"'us-east-1'",
",",
"*",
"*",
"_",
")",
":",
"task_json",
"=",
"get_template",
"(",
"template_file",
"=",
"'destroy/destroy_elb.json.j2'",
",",
"app",
"=",
"app",
",",
"env",
"=",
"env",
",",
"region",
"=",
"region",
",",
"vpc",
"=",
"get_vpc_id",
"(",
"account",
"=",
"env",
",",
"region",
"=",
"region",
")",
")",
"wait_for_task",
"(",
"task_json",
")",
"return",
"True"
] |
Destroy ELB Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
True upon successful completion.
|
[
"Destroy",
"ELB",
"Resources",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/elb/destroy_elb/destroy_elb.py#L21-L41
|
train
|
foremast/foremast
|
src/foremast/pipeline/clean_pipelines.py
|
delete_pipeline
|
def delete_pipeline(app='', pipeline_name=''):
"""Delete _pipeline_name_ from _app_."""
safe_pipeline_name = normalize_pipeline_name(name=pipeline_name)
LOG.warning('Deleting Pipeline: %s', safe_pipeline_name)
url = '{host}/pipelines/{app}/{pipeline}'.format(host=API_URL, app=app, pipeline=safe_pipeline_name)
response = requests.delete(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
if not response.ok:
LOG.debug('Delete response code: %d', response.status_code)
if response.status_code == requests.status_codes.codes['method_not_allowed']:
raise SpinnakerPipelineDeletionFailed('Failed to delete "{0}" from "{1}", '
'possibly invalid Pipeline name.'.format(safe_pipeline_name, app))
else:
LOG.debug('Pipeline missing, no delete required.')
LOG.debug('Deleted "%s" Pipeline response:\n%s', safe_pipeline_name, response.text)
return response.text
|
python
|
def delete_pipeline(app='', pipeline_name=''):
"""Delete _pipeline_name_ from _app_."""
safe_pipeline_name = normalize_pipeline_name(name=pipeline_name)
LOG.warning('Deleting Pipeline: %s', safe_pipeline_name)
url = '{host}/pipelines/{app}/{pipeline}'.format(host=API_URL, app=app, pipeline=safe_pipeline_name)
response = requests.delete(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
if not response.ok:
LOG.debug('Delete response code: %d', response.status_code)
if response.status_code == requests.status_codes.codes['method_not_allowed']:
raise SpinnakerPipelineDeletionFailed('Failed to delete "{0}" from "{1}", '
'possibly invalid Pipeline name.'.format(safe_pipeline_name, app))
else:
LOG.debug('Pipeline missing, no delete required.')
LOG.debug('Deleted "%s" Pipeline response:\n%s', safe_pipeline_name, response.text)
return response.text
|
[
"def",
"delete_pipeline",
"(",
"app",
"=",
"''",
",",
"pipeline_name",
"=",
"''",
")",
":",
"safe_pipeline_name",
"=",
"normalize_pipeline_name",
"(",
"name",
"=",
"pipeline_name",
")",
"LOG",
".",
"warning",
"(",
"'Deleting Pipeline: %s'",
",",
"safe_pipeline_name",
")",
"url",
"=",
"'{host}/pipelines/{app}/{pipeline}'",
".",
"format",
"(",
"host",
"=",
"API_URL",
",",
"app",
"=",
"app",
",",
"pipeline",
"=",
"safe_pipeline_name",
")",
"response",
"=",
"requests",
".",
"delete",
"(",
"url",
",",
"verify",
"=",
"GATE_CA_BUNDLE",
",",
"cert",
"=",
"GATE_CLIENT_CERT",
")",
"if",
"not",
"response",
".",
"ok",
":",
"LOG",
".",
"debug",
"(",
"'Delete response code: %d'",
",",
"response",
".",
"status_code",
")",
"if",
"response",
".",
"status_code",
"==",
"requests",
".",
"status_codes",
".",
"codes",
"[",
"'method_not_allowed'",
"]",
":",
"raise",
"SpinnakerPipelineDeletionFailed",
"(",
"'Failed to delete \"{0}\" from \"{1}\", '",
"'possibly invalid Pipeline name.'",
".",
"format",
"(",
"safe_pipeline_name",
",",
"app",
")",
")",
"else",
":",
"LOG",
".",
"debug",
"(",
"'Pipeline missing, no delete required.'",
")",
"LOG",
".",
"debug",
"(",
"'Deleted \"%s\" Pipeline response:\\n%s'",
",",
"safe_pipeline_name",
",",
"response",
".",
"text",
")",
"return",
"response",
".",
"text"
] |
Delete _pipeline_name_ from _app_.
|
[
"Delete",
"_pipeline_name_",
"from",
"_app_",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/pipeline/clean_pipelines.py#L28-L47
|
train
|
foremast/foremast
|
src/foremast/pipeline/clean_pipelines.py
|
clean_pipelines
|
def clean_pipelines(app='', settings=None):
"""Delete Pipelines for regions not defined in application.json files.
For Pipelines named **app_name [region]**, _region_ will need to appear
in at least one application.json file. All other names are assumed
unamanaged.
Args:
app (str): Application name
settings (dict): imported configuration settings
Returns:
True: Upon successful completion.
Raises:
SpinnakerPipelineCreationFailed: Missing application.json file from
`create-configs`.
"""
pipelines = get_all_pipelines(app=app)
envs = settings['pipeline']['env']
LOG.debug('Find Regions in: %s', envs)
regions = set()
for env in envs:
try:
regions.update(settings[env]['regions'])
except KeyError:
error_msg = 'Missing "{}/application-master-{}.json".'.format(RUNWAY_BASE_PATH, env)
raise SpinnakerPipelineCreationFailed(error_msg)
LOG.debug('Regions defined: %s', regions)
for pipeline in pipelines:
pipeline_name = pipeline['name']
try:
region = check_managed_pipeline(name=pipeline_name, app_name=app)
except ValueError:
LOG.info('"%s" is not managed.', pipeline_name)
continue
LOG.debug('Check "%s" in defined Regions.', region)
if region not in regions:
delete_pipeline(app=app, pipeline_name=pipeline_name)
return True
|
python
|
def clean_pipelines(app='', settings=None):
"""Delete Pipelines for regions not defined in application.json files.
For Pipelines named **app_name [region]**, _region_ will need to appear
in at least one application.json file. All other names are assumed
unamanaged.
Args:
app (str): Application name
settings (dict): imported configuration settings
Returns:
True: Upon successful completion.
Raises:
SpinnakerPipelineCreationFailed: Missing application.json file from
`create-configs`.
"""
pipelines = get_all_pipelines(app=app)
envs = settings['pipeline']['env']
LOG.debug('Find Regions in: %s', envs)
regions = set()
for env in envs:
try:
regions.update(settings[env]['regions'])
except KeyError:
error_msg = 'Missing "{}/application-master-{}.json".'.format(RUNWAY_BASE_PATH, env)
raise SpinnakerPipelineCreationFailed(error_msg)
LOG.debug('Regions defined: %s', regions)
for pipeline in pipelines:
pipeline_name = pipeline['name']
try:
region = check_managed_pipeline(name=pipeline_name, app_name=app)
except ValueError:
LOG.info('"%s" is not managed.', pipeline_name)
continue
LOG.debug('Check "%s" in defined Regions.', region)
if region not in regions:
delete_pipeline(app=app, pipeline_name=pipeline_name)
return True
|
[
"def",
"clean_pipelines",
"(",
"app",
"=",
"''",
",",
"settings",
"=",
"None",
")",
":",
"pipelines",
"=",
"get_all_pipelines",
"(",
"app",
"=",
"app",
")",
"envs",
"=",
"settings",
"[",
"'pipeline'",
"]",
"[",
"'env'",
"]",
"LOG",
".",
"debug",
"(",
"'Find Regions in: %s'",
",",
"envs",
")",
"regions",
"=",
"set",
"(",
")",
"for",
"env",
"in",
"envs",
":",
"try",
":",
"regions",
".",
"update",
"(",
"settings",
"[",
"env",
"]",
"[",
"'regions'",
"]",
")",
"except",
"KeyError",
":",
"error_msg",
"=",
"'Missing \"{}/application-master-{}.json\".'",
".",
"format",
"(",
"RUNWAY_BASE_PATH",
",",
"env",
")",
"raise",
"SpinnakerPipelineCreationFailed",
"(",
"error_msg",
")",
"LOG",
".",
"debug",
"(",
"'Regions defined: %s'",
",",
"regions",
")",
"for",
"pipeline",
"in",
"pipelines",
":",
"pipeline_name",
"=",
"pipeline",
"[",
"'name'",
"]",
"try",
":",
"region",
"=",
"check_managed_pipeline",
"(",
"name",
"=",
"pipeline_name",
",",
"app_name",
"=",
"app",
")",
"except",
"ValueError",
":",
"LOG",
".",
"info",
"(",
"'\"%s\" is not managed.'",
",",
"pipeline_name",
")",
"continue",
"LOG",
".",
"debug",
"(",
"'Check \"%s\" in defined Regions.'",
",",
"region",
")",
"if",
"region",
"not",
"in",
"regions",
":",
"delete_pipeline",
"(",
"app",
"=",
"app",
",",
"pipeline_name",
"=",
"pipeline_name",
")",
"return",
"True"
] |
Delete Pipelines for regions not defined in application.json files.
For Pipelines named **app_name [region]**, _region_ will need to appear
in at least one application.json file. All other names are assumed
unamanaged.
Args:
app (str): Application name
settings (dict): imported configuration settings
Returns:
True: Upon successful completion.
Raises:
SpinnakerPipelineCreationFailed: Missing application.json file from
`create-configs`.
|
[
"Delete",
"Pipelines",
"for",
"regions",
"not",
"defined",
"in",
"application",
".",
"json",
"files",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/pipeline/clean_pipelines.py#L50-L96
|
train
|
foremast/foremast
|
src/foremast/consts.py
|
extract_formats
|
def extract_formats(config_handle):
"""Get application formats.
See :class:`gogoutils.Formats` for available options.
Args:
config_handle (configparser.ConfigParser): Instance of configurations.
Returns:
dict: Formats in ``{$format_type: $format_pattern}``.
"""
configurations = dict(config_handle)
formats = dict(configurations.get('formats', {}))
return formats
|
python
|
def extract_formats(config_handle):
"""Get application formats.
See :class:`gogoutils.Formats` for available options.
Args:
config_handle (configparser.ConfigParser): Instance of configurations.
Returns:
dict: Formats in ``{$format_type: $format_pattern}``.
"""
configurations = dict(config_handle)
formats = dict(configurations.get('formats', {}))
return formats
|
[
"def",
"extract_formats",
"(",
"config_handle",
")",
":",
"configurations",
"=",
"dict",
"(",
"config_handle",
")",
"formats",
"=",
"dict",
"(",
"configurations",
".",
"get",
"(",
"'formats'",
",",
"{",
"}",
")",
")",
"return",
"formats"
] |
Get application formats.
See :class:`gogoutils.Formats` for available options.
Args:
config_handle (configparser.ConfigParser): Instance of configurations.
Returns:
dict: Formats in ``{$format_type: $format_pattern}``.
|
[
"Get",
"application",
"formats",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/consts.py#L77-L91
|
train
|
foremast/foremast
|
src/foremast/consts.py
|
load_dynamic_config
|
def load_dynamic_config(config_file=DEFAULT_DYNAMIC_CONFIG_FILE):
"""Load and parse dynamic config"""
dynamic_configurations = {}
# Insert config path so we can import it
sys.path.insert(0, path.dirname(path.abspath(config_file)))
try:
config_module = __import__('config')
dynamic_configurations = config_module.CONFIG
except ImportError:
# Provide a default if config not found
LOG.error('ImportError: Unable to load dynamic config. Check config.py file imports!')
return dynamic_configurations
|
python
|
def load_dynamic_config(config_file=DEFAULT_DYNAMIC_CONFIG_FILE):
"""Load and parse dynamic config"""
dynamic_configurations = {}
# Insert config path so we can import it
sys.path.insert(0, path.dirname(path.abspath(config_file)))
try:
config_module = __import__('config')
dynamic_configurations = config_module.CONFIG
except ImportError:
# Provide a default if config not found
LOG.error('ImportError: Unable to load dynamic config. Check config.py file imports!')
return dynamic_configurations
|
[
"def",
"load_dynamic_config",
"(",
"config_file",
"=",
"DEFAULT_DYNAMIC_CONFIG_FILE",
")",
":",
"dynamic_configurations",
"=",
"{",
"}",
"# Insert config path so we can import it",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"path",
".",
"dirname",
"(",
"path",
".",
"abspath",
"(",
"config_file",
")",
")",
")",
"try",
":",
"config_module",
"=",
"__import__",
"(",
"'config'",
")",
"dynamic_configurations",
"=",
"config_module",
".",
"CONFIG",
"except",
"ImportError",
":",
"# Provide a default if config not found",
"LOG",
".",
"error",
"(",
"'ImportError: Unable to load dynamic config. Check config.py file imports!'",
")",
"return",
"dynamic_configurations"
] |
Load and parse dynamic config
|
[
"Load",
"and",
"parse",
"dynamic",
"config"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/consts.py#L94-L108
|
train
|
foremast/foremast
|
src/foremast/consts.py
|
_remove_empty_entries
|
def _remove_empty_entries(entries):
"""Remove empty entries in a list"""
valid_entries = []
for entry in set(entries):
if entry:
valid_entries.append(entry)
return sorted(valid_entries)
|
python
|
def _remove_empty_entries(entries):
"""Remove empty entries in a list"""
valid_entries = []
for entry in set(entries):
if entry:
valid_entries.append(entry)
return sorted(valid_entries)
|
[
"def",
"_remove_empty_entries",
"(",
"entries",
")",
":",
"valid_entries",
"=",
"[",
"]",
"for",
"entry",
"in",
"set",
"(",
"entries",
")",
":",
"if",
"entry",
":",
"valid_entries",
".",
"append",
"(",
"entry",
")",
"return",
"sorted",
"(",
"valid_entries",
")"
] |
Remove empty entries in a list
|
[
"Remove",
"empty",
"entries",
"in",
"a",
"list"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/consts.py#L144-L150
|
train
|
foremast/foremast
|
src/foremast/consts.py
|
_convert_string_to_native
|
def _convert_string_to_native(value):
"""Convert a string to its native python type"""
result = None
try:
result = ast.literal_eval(str(value))
except (SyntaxError, ValueError):
# Likely a string
result = value.split(',')
return result
|
python
|
def _convert_string_to_native(value):
"""Convert a string to its native python type"""
result = None
try:
result = ast.literal_eval(str(value))
except (SyntaxError, ValueError):
# Likely a string
result = value.split(',')
return result
|
[
"def",
"_convert_string_to_native",
"(",
"value",
")",
":",
"result",
"=",
"None",
"try",
":",
"result",
"=",
"ast",
".",
"literal_eval",
"(",
"str",
"(",
"value",
")",
")",
"except",
"(",
"SyntaxError",
",",
"ValueError",
")",
":",
"# Likely a string",
"result",
"=",
"value",
".",
"split",
"(",
"','",
")",
"return",
"result"
] |
Convert a string to its native python type
|
[
"Convert",
"a",
"string",
"to",
"its",
"native",
"python",
"type"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/consts.py#L153-L162
|
train
|
foremast/foremast
|
src/foremast/consts.py
|
_generate_security_groups
|
def _generate_security_groups(config_key):
"""Read config file and generate security group dict by environment.
Args:
config_key (str): Configuration file key
Returns:
dict: of environments in {'env1': ['group1', 'group2']} format
"""
raw_default_groups = validate_key_values(CONFIG, 'base', config_key, default='')
default_groups = _convert_string_to_native(raw_default_groups)
LOG.debug('Default security group for %s is %s', config_key, default_groups)
entries = {}
for env in ENVS:
entries[env] = []
if isinstance(default_groups, (list)):
groups = _remove_empty_entries(default_groups)
for env in entries:
entries[env] = groups
elif isinstance(default_groups, (dict)):
entries.update(default_groups)
LOG.debug('Generated security group: %s', entries)
return entries
|
python
|
def _generate_security_groups(config_key):
"""Read config file and generate security group dict by environment.
Args:
config_key (str): Configuration file key
Returns:
dict: of environments in {'env1': ['group1', 'group2']} format
"""
raw_default_groups = validate_key_values(CONFIG, 'base', config_key, default='')
default_groups = _convert_string_to_native(raw_default_groups)
LOG.debug('Default security group for %s is %s', config_key, default_groups)
entries = {}
for env in ENVS:
entries[env] = []
if isinstance(default_groups, (list)):
groups = _remove_empty_entries(default_groups)
for env in entries:
entries[env] = groups
elif isinstance(default_groups, (dict)):
entries.update(default_groups)
LOG.debug('Generated security group: %s', entries)
return entries
|
[
"def",
"_generate_security_groups",
"(",
"config_key",
")",
":",
"raw_default_groups",
"=",
"validate_key_values",
"(",
"CONFIG",
",",
"'base'",
",",
"config_key",
",",
"default",
"=",
"''",
")",
"default_groups",
"=",
"_convert_string_to_native",
"(",
"raw_default_groups",
")",
"LOG",
".",
"debug",
"(",
"'Default security group for %s is %s'",
",",
"config_key",
",",
"default_groups",
")",
"entries",
"=",
"{",
"}",
"for",
"env",
"in",
"ENVS",
":",
"entries",
"[",
"env",
"]",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"default_groups",
",",
"(",
"list",
")",
")",
":",
"groups",
"=",
"_remove_empty_entries",
"(",
"default_groups",
")",
"for",
"env",
"in",
"entries",
":",
"entries",
"[",
"env",
"]",
"=",
"groups",
"elif",
"isinstance",
"(",
"default_groups",
",",
"(",
"dict",
")",
")",
":",
"entries",
".",
"update",
"(",
"default_groups",
")",
"LOG",
".",
"debug",
"(",
"'Generated security group: %s'",
",",
"entries",
")",
"return",
"entries"
] |
Read config file and generate security group dict by environment.
Args:
config_key (str): Configuration file key
Returns:
dict: of environments in {'env1': ['group1', 'group2']} format
|
[
"Read",
"config",
"file",
"and",
"generate",
"security",
"group",
"dict",
"by",
"environment",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/consts.py#L165-L190
|
train
|
foremast/foremast
|
src/foremast/datapipeline/datapipeline.py
|
AWSDataPipeline.create_datapipeline
|
def create_datapipeline(self):
"""Creates the data pipeline if it does not already exist
Returns:
dict: the response of the Boto3 command
"""
tags = [{"key": "app_group", "value": self.group}, {"key": "app_name", "value": self.app_name}]
response = self.client.create_pipeline(
name=self.datapipeline_data.get('name', self.app_name),
uniqueId=self.app_name,
description=self.datapipeline_data['description'],
tags=tags)
self.pipeline_id = response.get('pipelineId')
LOG.debug(response)
LOG.info("Successfully configured Data Pipeline - %s", self.app_name)
return response
|
python
|
def create_datapipeline(self):
"""Creates the data pipeline if it does not already exist
Returns:
dict: the response of the Boto3 command
"""
tags = [{"key": "app_group", "value": self.group}, {"key": "app_name", "value": self.app_name}]
response = self.client.create_pipeline(
name=self.datapipeline_data.get('name', self.app_name),
uniqueId=self.app_name,
description=self.datapipeline_data['description'],
tags=tags)
self.pipeline_id = response.get('pipelineId')
LOG.debug(response)
LOG.info("Successfully configured Data Pipeline - %s", self.app_name)
return response
|
[
"def",
"create_datapipeline",
"(",
"self",
")",
":",
"tags",
"=",
"[",
"{",
"\"key\"",
":",
"\"app_group\"",
",",
"\"value\"",
":",
"self",
".",
"group",
"}",
",",
"{",
"\"key\"",
":",
"\"app_name\"",
",",
"\"value\"",
":",
"self",
".",
"app_name",
"}",
"]",
"response",
"=",
"self",
".",
"client",
".",
"create_pipeline",
"(",
"name",
"=",
"self",
".",
"datapipeline_data",
".",
"get",
"(",
"'name'",
",",
"self",
".",
"app_name",
")",
",",
"uniqueId",
"=",
"self",
".",
"app_name",
",",
"description",
"=",
"self",
".",
"datapipeline_data",
"[",
"'description'",
"]",
",",
"tags",
"=",
"tags",
")",
"self",
".",
"pipeline_id",
"=",
"response",
".",
"get",
"(",
"'pipelineId'",
")",
"LOG",
".",
"debug",
"(",
"response",
")",
"LOG",
".",
"info",
"(",
"\"Successfully configured Data Pipeline - %s\"",
",",
"self",
".",
"app_name",
")",
"return",
"response"
] |
Creates the data pipeline if it does not already exist
Returns:
dict: the response of the Boto3 command
|
[
"Creates",
"the",
"data",
"pipeline",
"if",
"it",
"does",
"not",
"already",
"exist"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/datapipeline/datapipeline.py#L53-L70
|
train
|
foremast/foremast
|
src/foremast/datapipeline/datapipeline.py
|
AWSDataPipeline.set_pipeline_definition
|
def set_pipeline_definition(self):
"""Translates the json definition and puts it on created pipeline
Returns:
dict: the response of the Boto3 command
"""
if not self.pipeline_id:
self.get_pipeline_id()
json_def = self.datapipeline_data['json_definition']
try:
pipelineobjects = translator.definition_to_api_objects(json_def)
parameterobjects = translator.definition_to_api_parameters(json_def)
parametervalues = translator.definition_to_parameter_values(json_def)
except translator.PipelineDefinitionError as error:
LOG.warning(error)
raise DataPipelineDefinitionError
response = self.client.put_pipeline_definition(
pipelineId=self.pipeline_id,
pipelineObjects=pipelineobjects,
parameterObjects=parameterobjects,
parameterValues=parametervalues)
LOG.debug(response)
LOG.info("Successfully applied pipeline definition")
return response
|
python
|
def set_pipeline_definition(self):
"""Translates the json definition and puts it on created pipeline
Returns:
dict: the response of the Boto3 command
"""
if not self.pipeline_id:
self.get_pipeline_id()
json_def = self.datapipeline_data['json_definition']
try:
pipelineobjects = translator.definition_to_api_objects(json_def)
parameterobjects = translator.definition_to_api_parameters(json_def)
parametervalues = translator.definition_to_parameter_values(json_def)
except translator.PipelineDefinitionError as error:
LOG.warning(error)
raise DataPipelineDefinitionError
response = self.client.put_pipeline_definition(
pipelineId=self.pipeline_id,
pipelineObjects=pipelineobjects,
parameterObjects=parameterobjects,
parameterValues=parametervalues)
LOG.debug(response)
LOG.info("Successfully applied pipeline definition")
return response
|
[
"def",
"set_pipeline_definition",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"pipeline_id",
":",
"self",
".",
"get_pipeline_id",
"(",
")",
"json_def",
"=",
"self",
".",
"datapipeline_data",
"[",
"'json_definition'",
"]",
"try",
":",
"pipelineobjects",
"=",
"translator",
".",
"definition_to_api_objects",
"(",
"json_def",
")",
"parameterobjects",
"=",
"translator",
".",
"definition_to_api_parameters",
"(",
"json_def",
")",
"parametervalues",
"=",
"translator",
".",
"definition_to_parameter_values",
"(",
"json_def",
")",
"except",
"translator",
".",
"PipelineDefinitionError",
"as",
"error",
":",
"LOG",
".",
"warning",
"(",
"error",
")",
"raise",
"DataPipelineDefinitionError",
"response",
"=",
"self",
".",
"client",
".",
"put_pipeline_definition",
"(",
"pipelineId",
"=",
"self",
".",
"pipeline_id",
",",
"pipelineObjects",
"=",
"pipelineobjects",
",",
"parameterObjects",
"=",
"parameterobjects",
",",
"parameterValues",
"=",
"parametervalues",
")",
"LOG",
".",
"debug",
"(",
"response",
")",
"LOG",
".",
"info",
"(",
"\"Successfully applied pipeline definition\"",
")",
"return",
"response"
] |
Translates the json definition and puts it on created pipeline
Returns:
dict: the response of the Boto3 command
|
[
"Translates",
"the",
"json",
"definition",
"and",
"puts",
"it",
"on",
"created",
"pipeline"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/datapipeline/datapipeline.py#L72-L98
|
train
|
foremast/foremast
|
src/foremast/datapipeline/datapipeline.py
|
AWSDataPipeline.get_pipeline_id
|
def get_pipeline_id(self):
"""Finds the pipeline ID for configured pipeline"""
all_pipelines = []
paginiator = self.client.get_paginator('list_pipelines')
for page in paginiator.paginate():
all_pipelines.extend(page['pipelineIdList'])
for pipeline in all_pipelines:
if pipeline['name'] == self.datapipeline_data.get('name', self.app_name):
self.pipeline_id = pipeline['id']
LOG.info("Pipeline ID Found")
return
LOG.info("Pipeline ID Not Found for %s", self.app_name)
|
python
|
def get_pipeline_id(self):
"""Finds the pipeline ID for configured pipeline"""
all_pipelines = []
paginiator = self.client.get_paginator('list_pipelines')
for page in paginiator.paginate():
all_pipelines.extend(page['pipelineIdList'])
for pipeline in all_pipelines:
if pipeline['name'] == self.datapipeline_data.get('name', self.app_name):
self.pipeline_id = pipeline['id']
LOG.info("Pipeline ID Found")
return
LOG.info("Pipeline ID Not Found for %s", self.app_name)
|
[
"def",
"get_pipeline_id",
"(",
"self",
")",
":",
"all_pipelines",
"=",
"[",
"]",
"paginiator",
"=",
"self",
".",
"client",
".",
"get_paginator",
"(",
"'list_pipelines'",
")",
"for",
"page",
"in",
"paginiator",
".",
"paginate",
"(",
")",
":",
"all_pipelines",
".",
"extend",
"(",
"page",
"[",
"'pipelineIdList'",
"]",
")",
"for",
"pipeline",
"in",
"all_pipelines",
":",
"if",
"pipeline",
"[",
"'name'",
"]",
"==",
"self",
".",
"datapipeline_data",
".",
"get",
"(",
"'name'",
",",
"self",
".",
"app_name",
")",
":",
"self",
".",
"pipeline_id",
"=",
"pipeline",
"[",
"'id'",
"]",
"LOG",
".",
"info",
"(",
"\"Pipeline ID Found\"",
")",
"return",
"LOG",
".",
"info",
"(",
"\"Pipeline ID Not Found for %s\"",
",",
"self",
".",
"app_name",
")"
] |
Finds the pipeline ID for configured pipeline
|
[
"Finds",
"the",
"pipeline",
"ID",
"for",
"configured",
"pipeline"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/datapipeline/datapipeline.py#L100-L113
|
train
|
foremast/foremast
|
src/foremast/datapipeline/datapipeline.py
|
AWSDataPipeline.activate_pipeline
|
def activate_pipeline(self):
"""Activates a deployed pipeline, useful for OnDemand pipelines"""
self.client.activate_pipeline(pipelineId=self.pipeline_id)
LOG.info("Activated Pipeline %s", self.pipeline_id)
|
python
|
def activate_pipeline(self):
"""Activates a deployed pipeline, useful for OnDemand pipelines"""
self.client.activate_pipeline(pipelineId=self.pipeline_id)
LOG.info("Activated Pipeline %s", self.pipeline_id)
|
[
"def",
"activate_pipeline",
"(",
"self",
")",
":",
"self",
".",
"client",
".",
"activate_pipeline",
"(",
"pipelineId",
"=",
"self",
".",
"pipeline_id",
")",
"LOG",
".",
"info",
"(",
"\"Activated Pipeline %s\"",
",",
"self",
".",
"pipeline_id",
")"
] |
Activates a deployed pipeline, useful for OnDemand pipelines
|
[
"Activates",
"a",
"deployed",
"pipeline",
"useful",
"for",
"OnDemand",
"pipelines"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/datapipeline/datapipeline.py#L115-L118
|
train
|
foremast/foremast
|
src/foremast/utils/dns.py
|
get_dns_zone_ids
|
def get_dns_zone_ids(env='dev', facing='internal'):
"""Get Route 53 Hosted Zone IDs for _env_.
Args:
env (str): Deployment environment.
facing (str): Type of ELB, external or internal.
Returns:
list: Hosted Zone IDs for _env_. Only *PrivateZone* when _facing_ is
internal.
"""
client = boto3.Session(profile_name=env).client('route53')
zones = client.list_hosted_zones_by_name(DNSName='.'.join([env, DOMAIN]))
zone_ids = []
for zone in zones['HostedZones']:
LOG.debug('Found Hosted Zone: %s', zone)
if facing == 'external' or zone['Config']['PrivateZone']:
LOG.info('Using %(Id)s for "%(Name)s", %(Config)s', zone)
zone_ids.append(zone['Id'])
LOG.debug('Zone IDs: %s', zone_ids)
return zone_ids
|
python
|
def get_dns_zone_ids(env='dev', facing='internal'):
"""Get Route 53 Hosted Zone IDs for _env_.
Args:
env (str): Deployment environment.
facing (str): Type of ELB, external or internal.
Returns:
list: Hosted Zone IDs for _env_. Only *PrivateZone* when _facing_ is
internal.
"""
client = boto3.Session(profile_name=env).client('route53')
zones = client.list_hosted_zones_by_name(DNSName='.'.join([env, DOMAIN]))
zone_ids = []
for zone in zones['HostedZones']:
LOG.debug('Found Hosted Zone: %s', zone)
if facing == 'external' or zone['Config']['PrivateZone']:
LOG.info('Using %(Id)s for "%(Name)s", %(Config)s', zone)
zone_ids.append(zone['Id'])
LOG.debug('Zone IDs: %s', zone_ids)
return zone_ids
|
[
"def",
"get_dns_zone_ids",
"(",
"env",
"=",
"'dev'",
",",
"facing",
"=",
"'internal'",
")",
":",
"client",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
")",
".",
"client",
"(",
"'route53'",
")",
"zones",
"=",
"client",
".",
"list_hosted_zones_by_name",
"(",
"DNSName",
"=",
"'.'",
".",
"join",
"(",
"[",
"env",
",",
"DOMAIN",
"]",
")",
")",
"zone_ids",
"=",
"[",
"]",
"for",
"zone",
"in",
"zones",
"[",
"'HostedZones'",
"]",
":",
"LOG",
".",
"debug",
"(",
"'Found Hosted Zone: %s'",
",",
"zone",
")",
"if",
"facing",
"==",
"'external'",
"or",
"zone",
"[",
"'Config'",
"]",
"[",
"'PrivateZone'",
"]",
":",
"LOG",
".",
"info",
"(",
"'Using %(Id)s for \"%(Name)s\", %(Config)s'",
",",
"zone",
")",
"zone_ids",
".",
"append",
"(",
"zone",
"[",
"'Id'",
"]",
")",
"LOG",
".",
"debug",
"(",
"'Zone IDs: %s'",
",",
"zone_ids",
")",
"return",
"zone_ids"
] |
Get Route 53 Hosted Zone IDs for _env_.
Args:
env (str): Deployment environment.
facing (str): Type of ELB, external or internal.
Returns:
list: Hosted Zone IDs for _env_. Only *PrivateZone* when _facing_ is
internal.
|
[
"Get",
"Route",
"53",
"Hosted",
"Zone",
"IDs",
"for",
"_env_",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/dns.py#L31-L56
|
train
|
foremast/foremast
|
src/foremast/utils/dns.py
|
update_dns_zone_record
|
def update_dns_zone_record(env, zone_id, **kwargs):
"""Create a Route53 CNAME record in _env_ zone.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
Keyword Args:
dns_name (str): FQDN of application's dns entry to add/update.
dns_name_aws (str): FQDN of AWS resource
dns_ttl (int): DNS time-to-live (ttl)
"""
client = boto3.Session(profile_name=env).client('route53')
response = {}
hosted_zone_info = client.get_hosted_zone(Id=zone_id)
zone_name = hosted_zone_info['HostedZone']['Name'].rstrip('.')
dns_name = kwargs.get('dns_name')
if dns_name and dns_name.endswith(zone_name):
dns_name_aws = kwargs.get('dns_name_aws')
# This is what will be added to DNS
dns_json = get_template(template_file='infrastructure/dns_upsert.json.j2', **kwargs)
LOG.info('Attempting to create DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id,
zone_name)
try:
response = client.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch=json.loads(dns_json), )
LOG.info('Upserted DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id, zone_name)
except botocore.exceptions.ClientError as error:
LOG.info('Error creating DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id,
zone_name)
LOG.debug(error)
else:
LOG.info('Skipping creating DNS record %s in non-matching Hosted Zone %s (%s)', dns_name, zone_id, zone_name)
LOG.debug('Route53 JSON Response: \n%s', pformat(response))
|
python
|
def update_dns_zone_record(env, zone_id, **kwargs):
"""Create a Route53 CNAME record in _env_ zone.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
Keyword Args:
dns_name (str): FQDN of application's dns entry to add/update.
dns_name_aws (str): FQDN of AWS resource
dns_ttl (int): DNS time-to-live (ttl)
"""
client = boto3.Session(profile_name=env).client('route53')
response = {}
hosted_zone_info = client.get_hosted_zone(Id=zone_id)
zone_name = hosted_zone_info['HostedZone']['Name'].rstrip('.')
dns_name = kwargs.get('dns_name')
if dns_name and dns_name.endswith(zone_name):
dns_name_aws = kwargs.get('dns_name_aws')
# This is what will be added to DNS
dns_json = get_template(template_file='infrastructure/dns_upsert.json.j2', **kwargs)
LOG.info('Attempting to create DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id,
zone_name)
try:
response = client.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch=json.loads(dns_json), )
LOG.info('Upserted DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id, zone_name)
except botocore.exceptions.ClientError as error:
LOG.info('Error creating DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id,
zone_name)
LOG.debug(error)
else:
LOG.info('Skipping creating DNS record %s in non-matching Hosted Zone %s (%s)', dns_name, zone_id, zone_name)
LOG.debug('Route53 JSON Response: \n%s', pformat(response))
|
[
"def",
"update_dns_zone_record",
"(",
"env",
",",
"zone_id",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
")",
".",
"client",
"(",
"'route53'",
")",
"response",
"=",
"{",
"}",
"hosted_zone_info",
"=",
"client",
".",
"get_hosted_zone",
"(",
"Id",
"=",
"zone_id",
")",
"zone_name",
"=",
"hosted_zone_info",
"[",
"'HostedZone'",
"]",
"[",
"'Name'",
"]",
".",
"rstrip",
"(",
"'.'",
")",
"dns_name",
"=",
"kwargs",
".",
"get",
"(",
"'dns_name'",
")",
"if",
"dns_name",
"and",
"dns_name",
".",
"endswith",
"(",
"zone_name",
")",
":",
"dns_name_aws",
"=",
"kwargs",
".",
"get",
"(",
"'dns_name_aws'",
")",
"# This is what will be added to DNS",
"dns_json",
"=",
"get_template",
"(",
"template_file",
"=",
"'infrastructure/dns_upsert.json.j2'",
",",
"*",
"*",
"kwargs",
")",
"LOG",
".",
"info",
"(",
"'Attempting to create DNS record %s (%s) in Hosted Zone %s (%s)'",
",",
"dns_name",
",",
"dns_name_aws",
",",
"zone_id",
",",
"zone_name",
")",
"try",
":",
"response",
"=",
"client",
".",
"change_resource_record_sets",
"(",
"HostedZoneId",
"=",
"zone_id",
",",
"ChangeBatch",
"=",
"json",
".",
"loads",
"(",
"dns_json",
")",
",",
")",
"LOG",
".",
"info",
"(",
"'Upserted DNS record %s (%s) in Hosted Zone %s (%s)'",
",",
"dns_name",
",",
"dns_name_aws",
",",
"zone_id",
",",
"zone_name",
")",
"except",
"botocore",
".",
"exceptions",
".",
"ClientError",
"as",
"error",
":",
"LOG",
".",
"info",
"(",
"'Error creating DNS record %s (%s) in Hosted Zone %s (%s)'",
",",
"dns_name",
",",
"dns_name_aws",
",",
"zone_id",
",",
"zone_name",
")",
"LOG",
".",
"debug",
"(",
"error",
")",
"else",
":",
"LOG",
".",
"info",
"(",
"'Skipping creating DNS record %s in non-matching Hosted Zone %s (%s)'",
",",
"dns_name",
",",
"zone_id",
",",
"zone_name",
")",
"LOG",
".",
"debug",
"(",
"'Route53 JSON Response: \\n%s'",
",",
"pformat",
"(",
"response",
")",
")"
] |
Create a Route53 CNAME record in _env_ zone.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
Keyword Args:
dns_name (str): FQDN of application's dns entry to add/update.
dns_name_aws (str): FQDN of AWS resource
dns_ttl (int): DNS time-to-live (ttl)
|
[
"Create",
"a",
"Route53",
"CNAME",
"record",
"in",
"_env_",
"zone",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/dns.py#L59-L96
|
train
|
foremast/foremast
|
src/foremast/utils/dns.py
|
find_existing_record
|
def find_existing_record(env, zone_id, dns_name, check_key=None, check_value=None):
"""Check if a specific DNS record exists.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
check_key(str): Key to look for in record. Example: "Type"
check_value(str): Value to look for with check_key. Example: "CNAME"
Returns:
json: Found Record. Returns None if no record found
"""
client = boto3.Session(profile_name=env).client('route53')
pager = client.get_paginator('list_resource_record_sets')
existingrecord = None
for rset in pager.paginate(HostedZoneId=zone_id):
for record in rset['ResourceRecordSets']:
if check_key:
if record['Name'].rstrip('.') == dns_name and record.get(check_key) == check_value:
LOG.info("Found existing record: %s", record)
existingrecord = record
break
return existingrecord
|
python
|
def find_existing_record(env, zone_id, dns_name, check_key=None, check_value=None):
"""Check if a specific DNS record exists.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
check_key(str): Key to look for in record. Example: "Type"
check_value(str): Value to look for with check_key. Example: "CNAME"
Returns:
json: Found Record. Returns None if no record found
"""
client = boto3.Session(profile_name=env).client('route53')
pager = client.get_paginator('list_resource_record_sets')
existingrecord = None
for rset in pager.paginate(HostedZoneId=zone_id):
for record in rset['ResourceRecordSets']:
if check_key:
if record['Name'].rstrip('.') == dns_name and record.get(check_key) == check_value:
LOG.info("Found existing record: %s", record)
existingrecord = record
break
return existingrecord
|
[
"def",
"find_existing_record",
"(",
"env",
",",
"zone_id",
",",
"dns_name",
",",
"check_key",
"=",
"None",
",",
"check_value",
"=",
"None",
")",
":",
"client",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
")",
".",
"client",
"(",
"'route53'",
")",
"pager",
"=",
"client",
".",
"get_paginator",
"(",
"'list_resource_record_sets'",
")",
"existingrecord",
"=",
"None",
"for",
"rset",
"in",
"pager",
".",
"paginate",
"(",
"HostedZoneId",
"=",
"zone_id",
")",
":",
"for",
"record",
"in",
"rset",
"[",
"'ResourceRecordSets'",
"]",
":",
"if",
"check_key",
":",
"if",
"record",
"[",
"'Name'",
"]",
".",
"rstrip",
"(",
"'.'",
")",
"==",
"dns_name",
"and",
"record",
".",
"get",
"(",
"check_key",
")",
"==",
"check_value",
":",
"LOG",
".",
"info",
"(",
"\"Found existing record: %s\"",
",",
"record",
")",
"existingrecord",
"=",
"record",
"break",
"return",
"existingrecord"
] |
Check if a specific DNS record exists.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
check_key(str): Key to look for in record. Example: "Type"
check_value(str): Value to look for with check_key. Example: "CNAME"
Returns:
json: Found Record. Returns None if no record found
|
[
"Check",
"if",
"a",
"specific",
"DNS",
"record",
"exists",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/dns.py#L99-L123
|
train
|
foremast/foremast
|
src/foremast/utils/dns.py
|
delete_existing_cname
|
def delete_existing_cname(env, zone_id, dns_name):
"""Delete an existing CNAME record.
This is used when updating to multi-region for deleting old records. The
record can not just be upserted since it changes types.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
"""
client = boto3.Session(profile_name=env).client('route53')
startrecord = None
newrecord_name = dns_name
startrecord = find_existing_record(env, zone_id, newrecord_name, check_key='Type', check_value='CNAME')
if startrecord:
LOG.info("Deleting old record: %s", newrecord_name)
_response = client.change_resource_record_sets(
HostedZoneId=zone_id, ChangeBatch={'Changes': [{
'Action': 'DELETE',
'ResourceRecordSet': startrecord
}]})
LOG.debug('Response from deleting %s: %s', dns_name, _response)
|
python
|
def delete_existing_cname(env, zone_id, dns_name):
"""Delete an existing CNAME record.
This is used when updating to multi-region for deleting old records. The
record can not just be upserted since it changes types.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
"""
client = boto3.Session(profile_name=env).client('route53')
startrecord = None
newrecord_name = dns_name
startrecord = find_existing_record(env, zone_id, newrecord_name, check_key='Type', check_value='CNAME')
if startrecord:
LOG.info("Deleting old record: %s", newrecord_name)
_response = client.change_resource_record_sets(
HostedZoneId=zone_id, ChangeBatch={'Changes': [{
'Action': 'DELETE',
'ResourceRecordSet': startrecord
}]})
LOG.debug('Response from deleting %s: %s', dns_name, _response)
|
[
"def",
"delete_existing_cname",
"(",
"env",
",",
"zone_id",
",",
"dns_name",
")",
":",
"client",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
")",
".",
"client",
"(",
"'route53'",
")",
"startrecord",
"=",
"None",
"newrecord_name",
"=",
"dns_name",
"startrecord",
"=",
"find_existing_record",
"(",
"env",
",",
"zone_id",
",",
"newrecord_name",
",",
"check_key",
"=",
"'Type'",
",",
"check_value",
"=",
"'CNAME'",
")",
"if",
"startrecord",
":",
"LOG",
".",
"info",
"(",
"\"Deleting old record: %s\"",
",",
"newrecord_name",
")",
"_response",
"=",
"client",
".",
"change_resource_record_sets",
"(",
"HostedZoneId",
"=",
"zone_id",
",",
"ChangeBatch",
"=",
"{",
"'Changes'",
":",
"[",
"{",
"'Action'",
":",
"'DELETE'",
",",
"'ResourceRecordSet'",
":",
"startrecord",
"}",
"]",
"}",
")",
"LOG",
".",
"debug",
"(",
"'Response from deleting %s: %s'",
",",
"dns_name",
",",
"_response",
")"
] |
Delete an existing CNAME record.
This is used when updating to multi-region for deleting old records. The
record can not just be upserted since it changes types.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
|
[
"Delete",
"an",
"existing",
"CNAME",
"record",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/dns.py#L126-L148
|
train
|
foremast/foremast
|
src/foremast/utils/dns.py
|
update_failover_dns_record
|
def update_failover_dns_record(env, zone_id, **kwargs):
"""Create a Failover Route53 alias record in _env_ zone.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
Keyword Args:
dns_name (str): FQDN of application's dns entry to add/update.
dns_ttl (int): DNS time-to-live (ttl)
elb_aws_dns (str): DNS A Record of ELB from AWS
elb_dns_zone_id (str): Zone ID of ELB DNS
failover_state (str): if the record is primary or secondary
primary_region (str): Primary AWS region for DNS
"""
client = boto3.Session(profile_name=env).client('route53')
response = {}
hosted_zone_info = client.get_hosted_zone(Id=zone_id)
zone_name = hosted_zone_info['HostedZone']['Name'].rstrip('.')
dns_name = kwargs.get('dns_name')
# Check that the primary record exists
failover_state = kwargs.get('failover_state')
if failover_state.lower() != 'primary':
primary_record = find_existing_record(env, zone_id, dns_name, check_key='Failover', check_value='PRIMARY')
if not primary_record:
raise PrimaryDNSRecordNotFound("Primary Failover DNS record not found: {}".format(dns_name))
if dns_name and dns_name.endswith(zone_name):
dns_json = get_template(template_file='infrastructure/dns_failover_upsert.json.j2', **kwargs)
LOG.info('Attempting to create DNS Failover record %s (%s) in Hosted Zone %s (%s)', dns_name,
kwargs['elb_aws_dns'], zone_id, zone_name)
try:
delete_existing_cname(env, zone_id, dns_name)
response = client.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch=json.loads(dns_json), )
LOG.info('Upserted DNS Failover record %s (%s) in Hosted Zone %s (%s)', dns_name, kwargs['elb_aws_dns'],
zone_id, zone_name)
except botocore.exceptions.ClientError as error:
LOG.info('Error creating DNS Failover record %s (%s) in Hosted Zone %s (%s)', dns_name,
kwargs['elb_aws_dns'], zone_id, zone_name)
LOG.debug(error)
else:
LOG.info('Skipping creating DNS record %s in non-matching Hosted Zone %s (%s)', dns_name, zone_id, zone_name)
LOG.debug('Route53 JSON Response: \n%s', pformat(response))
|
python
|
def update_failover_dns_record(env, zone_id, **kwargs):
"""Create a Failover Route53 alias record in _env_ zone.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
Keyword Args:
dns_name (str): FQDN of application's dns entry to add/update.
dns_ttl (int): DNS time-to-live (ttl)
elb_aws_dns (str): DNS A Record of ELB from AWS
elb_dns_zone_id (str): Zone ID of ELB DNS
failover_state (str): if the record is primary or secondary
primary_region (str): Primary AWS region for DNS
"""
client = boto3.Session(profile_name=env).client('route53')
response = {}
hosted_zone_info = client.get_hosted_zone(Id=zone_id)
zone_name = hosted_zone_info['HostedZone']['Name'].rstrip('.')
dns_name = kwargs.get('dns_name')
# Check that the primary record exists
failover_state = kwargs.get('failover_state')
if failover_state.lower() != 'primary':
primary_record = find_existing_record(env, zone_id, dns_name, check_key='Failover', check_value='PRIMARY')
if not primary_record:
raise PrimaryDNSRecordNotFound("Primary Failover DNS record not found: {}".format(dns_name))
if dns_name and dns_name.endswith(zone_name):
dns_json = get_template(template_file='infrastructure/dns_failover_upsert.json.j2', **kwargs)
LOG.info('Attempting to create DNS Failover record %s (%s) in Hosted Zone %s (%s)', dns_name,
kwargs['elb_aws_dns'], zone_id, zone_name)
try:
delete_existing_cname(env, zone_id, dns_name)
response = client.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch=json.loads(dns_json), )
LOG.info('Upserted DNS Failover record %s (%s) in Hosted Zone %s (%s)', dns_name, kwargs['elb_aws_dns'],
zone_id, zone_name)
except botocore.exceptions.ClientError as error:
LOG.info('Error creating DNS Failover record %s (%s) in Hosted Zone %s (%s)', dns_name,
kwargs['elb_aws_dns'], zone_id, zone_name)
LOG.debug(error)
else:
LOG.info('Skipping creating DNS record %s in non-matching Hosted Zone %s (%s)', dns_name, zone_id, zone_name)
LOG.debug('Route53 JSON Response: \n%s', pformat(response))
|
[
"def",
"update_failover_dns_record",
"(",
"env",
",",
"zone_id",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
")",
".",
"client",
"(",
"'route53'",
")",
"response",
"=",
"{",
"}",
"hosted_zone_info",
"=",
"client",
".",
"get_hosted_zone",
"(",
"Id",
"=",
"zone_id",
")",
"zone_name",
"=",
"hosted_zone_info",
"[",
"'HostedZone'",
"]",
"[",
"'Name'",
"]",
".",
"rstrip",
"(",
"'.'",
")",
"dns_name",
"=",
"kwargs",
".",
"get",
"(",
"'dns_name'",
")",
"# Check that the primary record exists",
"failover_state",
"=",
"kwargs",
".",
"get",
"(",
"'failover_state'",
")",
"if",
"failover_state",
".",
"lower",
"(",
")",
"!=",
"'primary'",
":",
"primary_record",
"=",
"find_existing_record",
"(",
"env",
",",
"zone_id",
",",
"dns_name",
",",
"check_key",
"=",
"'Failover'",
",",
"check_value",
"=",
"'PRIMARY'",
")",
"if",
"not",
"primary_record",
":",
"raise",
"PrimaryDNSRecordNotFound",
"(",
"\"Primary Failover DNS record not found: {}\"",
".",
"format",
"(",
"dns_name",
")",
")",
"if",
"dns_name",
"and",
"dns_name",
".",
"endswith",
"(",
"zone_name",
")",
":",
"dns_json",
"=",
"get_template",
"(",
"template_file",
"=",
"'infrastructure/dns_failover_upsert.json.j2'",
",",
"*",
"*",
"kwargs",
")",
"LOG",
".",
"info",
"(",
"'Attempting to create DNS Failover record %s (%s) in Hosted Zone %s (%s)'",
",",
"dns_name",
",",
"kwargs",
"[",
"'elb_aws_dns'",
"]",
",",
"zone_id",
",",
"zone_name",
")",
"try",
":",
"delete_existing_cname",
"(",
"env",
",",
"zone_id",
",",
"dns_name",
")",
"response",
"=",
"client",
".",
"change_resource_record_sets",
"(",
"HostedZoneId",
"=",
"zone_id",
",",
"ChangeBatch",
"=",
"json",
".",
"loads",
"(",
"dns_json",
")",
",",
")",
"LOG",
".",
"info",
"(",
"'Upserted DNS Failover record %s (%s) in Hosted Zone %s (%s)'",
",",
"dns_name",
",",
"kwargs",
"[",
"'elb_aws_dns'",
"]",
",",
"zone_id",
",",
"zone_name",
")",
"except",
"botocore",
".",
"exceptions",
".",
"ClientError",
"as",
"error",
":",
"LOG",
".",
"info",
"(",
"'Error creating DNS Failover record %s (%s) in Hosted Zone %s (%s)'",
",",
"dns_name",
",",
"kwargs",
"[",
"'elb_aws_dns'",
"]",
",",
"zone_id",
",",
"zone_name",
")",
"LOG",
".",
"debug",
"(",
"error",
")",
"else",
":",
"LOG",
".",
"info",
"(",
"'Skipping creating DNS record %s in non-matching Hosted Zone %s (%s)'",
",",
"dns_name",
",",
"zone_id",
",",
"zone_name",
")",
"LOG",
".",
"debug",
"(",
"'Route53 JSON Response: \\n%s'",
",",
"pformat",
"(",
"response",
")",
")"
] |
Create a Failover Route53 alias record in _env_ zone.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
Keyword Args:
dns_name (str): FQDN of application's dns entry to add/update.
dns_ttl (int): DNS time-to-live (ttl)
elb_aws_dns (str): DNS A Record of ELB from AWS
elb_dns_zone_id (str): Zone ID of ELB DNS
failover_state (str): if the record is primary or secondary
primary_region (str): Primary AWS region for DNS
|
[
"Create",
"a",
"Failover",
"Route53",
"alias",
"record",
"in",
"_env_",
"zone",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/dns.py#L151-L198
|
train
|
foremast/foremast
|
src/foremast/awslambda/cloudwatch_log_event/cloudwatch_log_event.py
|
create_cloudwatch_log_event
|
def create_cloudwatch_log_event(app_name, env, region, rules):
"""Create cloudwatch log event for lambda from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): Trigger rules from the settings
"""
session = boto3.Session(profile_name=env, region_name=region)
cloudwatch_client = session.client('logs')
log_group = rules.get('log_group')
filter_name = rules.get('filter_name')
filter_pattern = rules.get('filter_pattern')
if not log_group:
LOG.critical('Log group is required and no "log_group" is defined!')
raise InvalidEventConfiguration('Log group is required and no "log_group" is defined!')
if not filter_name:
LOG.critical('Filter name is required and no filter_name is defined!')
raise InvalidEventConfiguration('Filter name is required and no filter_name is defined!')
if filter_pattern is None:
LOG.critical('Filter pattern is required and no filter_pattern is defined!')
raise InvalidEventConfiguration('Filter pattern is required and no filter_pattern is defined!')
lambda_alias_arn = get_lambda_alias_arn(app=app_name, account=env, region=region)
statement_id = '{}_cloudwatchlog_{}'.format(app_name, filter_name.replace(" ", "_"))
principal = 'logs.{}.amazonaws.com'.format(region)
account_id = get_env_credential(env=env)['accountId']
source_arn = "arn:aws:logs:{0}:{1}:log-group:{2}:*".format(region, account_id, log_group)
add_lambda_permissions(
function=lambda_alias_arn,
statement_id=statement_id,
action='lambda:InvokeFunction',
principal=principal,
source_arn=source_arn,
env=env,
region=region)
cloudwatch_client.put_subscription_filter(
logGroupName=log_group, filterName=filter_name, filterPattern=filter_pattern, destinationArn=lambda_alias_arn)
LOG.info("Created Cloudwatch log event with filter: %s", filter_pattern)
|
python
|
def create_cloudwatch_log_event(app_name, env, region, rules):
"""Create cloudwatch log event for lambda from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): Trigger rules from the settings
"""
session = boto3.Session(profile_name=env, region_name=region)
cloudwatch_client = session.client('logs')
log_group = rules.get('log_group')
filter_name = rules.get('filter_name')
filter_pattern = rules.get('filter_pattern')
if not log_group:
LOG.critical('Log group is required and no "log_group" is defined!')
raise InvalidEventConfiguration('Log group is required and no "log_group" is defined!')
if not filter_name:
LOG.critical('Filter name is required and no filter_name is defined!')
raise InvalidEventConfiguration('Filter name is required and no filter_name is defined!')
if filter_pattern is None:
LOG.critical('Filter pattern is required and no filter_pattern is defined!')
raise InvalidEventConfiguration('Filter pattern is required and no filter_pattern is defined!')
lambda_alias_arn = get_lambda_alias_arn(app=app_name, account=env, region=region)
statement_id = '{}_cloudwatchlog_{}'.format(app_name, filter_name.replace(" ", "_"))
principal = 'logs.{}.amazonaws.com'.format(region)
account_id = get_env_credential(env=env)['accountId']
source_arn = "arn:aws:logs:{0}:{1}:log-group:{2}:*".format(region, account_id, log_group)
add_lambda_permissions(
function=lambda_alias_arn,
statement_id=statement_id,
action='lambda:InvokeFunction',
principal=principal,
source_arn=source_arn,
env=env,
region=region)
cloudwatch_client.put_subscription_filter(
logGroupName=log_group, filterName=filter_name, filterPattern=filter_pattern, destinationArn=lambda_alias_arn)
LOG.info("Created Cloudwatch log event with filter: %s", filter_pattern)
|
[
"def",
"create_cloudwatch_log_event",
"(",
"app_name",
",",
"env",
",",
"region",
",",
"rules",
")",
":",
"session",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
",",
"region_name",
"=",
"region",
")",
"cloudwatch_client",
"=",
"session",
".",
"client",
"(",
"'logs'",
")",
"log_group",
"=",
"rules",
".",
"get",
"(",
"'log_group'",
")",
"filter_name",
"=",
"rules",
".",
"get",
"(",
"'filter_name'",
")",
"filter_pattern",
"=",
"rules",
".",
"get",
"(",
"'filter_pattern'",
")",
"if",
"not",
"log_group",
":",
"LOG",
".",
"critical",
"(",
"'Log group is required and no \"log_group\" is defined!'",
")",
"raise",
"InvalidEventConfiguration",
"(",
"'Log group is required and no \"log_group\" is defined!'",
")",
"if",
"not",
"filter_name",
":",
"LOG",
".",
"critical",
"(",
"'Filter name is required and no filter_name is defined!'",
")",
"raise",
"InvalidEventConfiguration",
"(",
"'Filter name is required and no filter_name is defined!'",
")",
"if",
"filter_pattern",
"is",
"None",
":",
"LOG",
".",
"critical",
"(",
"'Filter pattern is required and no filter_pattern is defined!'",
")",
"raise",
"InvalidEventConfiguration",
"(",
"'Filter pattern is required and no filter_pattern is defined!'",
")",
"lambda_alias_arn",
"=",
"get_lambda_alias_arn",
"(",
"app",
"=",
"app_name",
",",
"account",
"=",
"env",
",",
"region",
"=",
"region",
")",
"statement_id",
"=",
"'{}_cloudwatchlog_{}'",
".",
"format",
"(",
"app_name",
",",
"filter_name",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
")",
"principal",
"=",
"'logs.{}.amazonaws.com'",
".",
"format",
"(",
"region",
")",
"account_id",
"=",
"get_env_credential",
"(",
"env",
"=",
"env",
")",
"[",
"'accountId'",
"]",
"source_arn",
"=",
"\"arn:aws:logs:{0}:{1}:log-group:{2}:*\"",
".",
"format",
"(",
"region",
",",
"account_id",
",",
"log_group",
")",
"add_lambda_permissions",
"(",
"function",
"=",
"lambda_alias_arn",
",",
"statement_id",
"=",
"statement_id",
",",
"action",
"=",
"'lambda:InvokeFunction'",
",",
"principal",
"=",
"principal",
",",
"source_arn",
"=",
"source_arn",
",",
"env",
"=",
"env",
",",
"region",
"=",
"region",
")",
"cloudwatch_client",
".",
"put_subscription_filter",
"(",
"logGroupName",
"=",
"log_group",
",",
"filterName",
"=",
"filter_name",
",",
"filterPattern",
"=",
"filter_pattern",
",",
"destinationArn",
"=",
"lambda_alias_arn",
")",
"LOG",
".",
"info",
"(",
"\"Created Cloudwatch log event with filter: %s\"",
",",
"filter_pattern",
")"
] |
Create cloudwatch log event for lambda from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): Trigger rules from the settings
|
[
"Create",
"cloudwatch",
"log",
"event",
"for",
"lambda",
"from",
"rules",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/awslambda/cloudwatch_log_event/cloudwatch_log_event.py#L28-L75
|
train
|
foremast/foremast
|
src/foremast/autoscaling_policy/create_policy.py
|
AutoScalingPolicy.prepare_policy_template
|
def prepare_policy_template(self, scaling_type, period_sec, server_group):
"""Renders scaling policy templates based on configs and variables.
After rendering, POSTs the json to Spinnaker for creation.
Args:
scaling_type (str): ``scale_up`` or ``scaling_down``. Type of policy
period_sec (int): Period of time to look at metrics for determining scale
server_group (str): The name of the server group to render template for
"""
template_kwargs = {
'app': self.app,
'env': self.env,
'region': self.region,
'server_group': server_group,
'period_sec': period_sec,
'scaling_policy': self.settings['asg']['scaling_policy'],
}
if scaling_type == 'scale_up':
template_kwargs['operation'] = 'increase'
template_kwargs['comparisonOperator'] = 'GreaterThanThreshold'
template_kwargs['scalingAdjustment'] = 1
elif scaling_type == 'scale_down':
cur_threshold = int(self.settings['asg']['scaling_policy']['threshold'])
self.settings['asg']['scaling_policy']['threshold'] = floor(cur_threshold * 0.5)
template_kwargs['operation'] = 'decrease'
template_kwargs['comparisonOperator'] = 'LessThanThreshold'
template_kwargs['scalingAdjustment'] = -1
rendered_template = get_template(template_file='infrastructure/autoscaling_policy.json.j2', **template_kwargs)
self.log.info('Creating a %s policy in %s for %s', scaling_type, self.env, self.app)
wait_for_task(rendered_template)
self.log.info('Successfully created a %s policy in %s for %s', scaling_type, self.env, self.app)
|
python
|
def prepare_policy_template(self, scaling_type, period_sec, server_group):
"""Renders scaling policy templates based on configs and variables.
After rendering, POSTs the json to Spinnaker for creation.
Args:
scaling_type (str): ``scale_up`` or ``scaling_down``. Type of policy
period_sec (int): Period of time to look at metrics for determining scale
server_group (str): The name of the server group to render template for
"""
template_kwargs = {
'app': self.app,
'env': self.env,
'region': self.region,
'server_group': server_group,
'period_sec': period_sec,
'scaling_policy': self.settings['asg']['scaling_policy'],
}
if scaling_type == 'scale_up':
template_kwargs['operation'] = 'increase'
template_kwargs['comparisonOperator'] = 'GreaterThanThreshold'
template_kwargs['scalingAdjustment'] = 1
elif scaling_type == 'scale_down':
cur_threshold = int(self.settings['asg']['scaling_policy']['threshold'])
self.settings['asg']['scaling_policy']['threshold'] = floor(cur_threshold * 0.5)
template_kwargs['operation'] = 'decrease'
template_kwargs['comparisonOperator'] = 'LessThanThreshold'
template_kwargs['scalingAdjustment'] = -1
rendered_template = get_template(template_file='infrastructure/autoscaling_policy.json.j2', **template_kwargs)
self.log.info('Creating a %s policy in %s for %s', scaling_type, self.env, self.app)
wait_for_task(rendered_template)
self.log.info('Successfully created a %s policy in %s for %s', scaling_type, self.env, self.app)
|
[
"def",
"prepare_policy_template",
"(",
"self",
",",
"scaling_type",
",",
"period_sec",
",",
"server_group",
")",
":",
"template_kwargs",
"=",
"{",
"'app'",
":",
"self",
".",
"app",
",",
"'env'",
":",
"self",
".",
"env",
",",
"'region'",
":",
"self",
".",
"region",
",",
"'server_group'",
":",
"server_group",
",",
"'period_sec'",
":",
"period_sec",
",",
"'scaling_policy'",
":",
"self",
".",
"settings",
"[",
"'asg'",
"]",
"[",
"'scaling_policy'",
"]",
",",
"}",
"if",
"scaling_type",
"==",
"'scale_up'",
":",
"template_kwargs",
"[",
"'operation'",
"]",
"=",
"'increase'",
"template_kwargs",
"[",
"'comparisonOperator'",
"]",
"=",
"'GreaterThanThreshold'",
"template_kwargs",
"[",
"'scalingAdjustment'",
"]",
"=",
"1",
"elif",
"scaling_type",
"==",
"'scale_down'",
":",
"cur_threshold",
"=",
"int",
"(",
"self",
".",
"settings",
"[",
"'asg'",
"]",
"[",
"'scaling_policy'",
"]",
"[",
"'threshold'",
"]",
")",
"self",
".",
"settings",
"[",
"'asg'",
"]",
"[",
"'scaling_policy'",
"]",
"[",
"'threshold'",
"]",
"=",
"floor",
"(",
"cur_threshold",
"*",
"0.5",
")",
"template_kwargs",
"[",
"'operation'",
"]",
"=",
"'decrease'",
"template_kwargs",
"[",
"'comparisonOperator'",
"]",
"=",
"'LessThanThreshold'",
"template_kwargs",
"[",
"'scalingAdjustment'",
"]",
"=",
"-",
"1",
"rendered_template",
"=",
"get_template",
"(",
"template_file",
"=",
"'infrastructure/autoscaling_policy.json.j2'",
",",
"*",
"*",
"template_kwargs",
")",
"self",
".",
"log",
".",
"info",
"(",
"'Creating a %s policy in %s for %s'",
",",
"scaling_type",
",",
"self",
".",
"env",
",",
"self",
".",
"app",
")",
"wait_for_task",
"(",
"rendered_template",
")",
"self",
".",
"log",
".",
"info",
"(",
"'Successfully created a %s policy in %s for %s'",
",",
"scaling_type",
",",
"self",
".",
"env",
",",
"self",
".",
"app",
")"
] |
Renders scaling policy templates based on configs and variables.
After rendering, POSTs the json to Spinnaker for creation.
Args:
scaling_type (str): ``scale_up`` or ``scaling_down``. Type of policy
period_sec (int): Period of time to look at metrics for determining scale
server_group (str): The name of the server group to render template for
|
[
"Renders",
"scaling",
"policy",
"templates",
"based",
"on",
"configs",
"and",
"variables",
".",
"After",
"rendering",
"POSTs",
"the",
"json",
"to",
"Spinnaker",
"for",
"creation",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/autoscaling_policy/create_policy.py#L56-L88
|
train
|
foremast/foremast
|
src/foremast/autoscaling_policy/create_policy.py
|
AutoScalingPolicy.create_policy
|
def create_policy(self):
"""Wrapper function. Gets the server group, sets sane defaults,
deletes existing policies, and then runs self.prepare_policy_template
for scaling up and scaling down policies.
This function acts as the main driver for the scaling policy creationprocess
"""
if not self.settings['asg']['scaling_policy']:
self.log.info("No scaling policy found, skipping...")
return
server_group = self.get_server_group()
# Find all existing and remove them
scaling_policies = self.get_all_existing(server_group)
for policy in scaling_policies:
for subpolicy in policy:
self.delete_existing_policy(subpolicy, server_group)
if self.settings['asg']['scaling_policy']['period_minutes']:
period_sec = int(self.settings['asg']['scaling_policy']['period_minutes']) * 60
else:
period_sec = 1800
self.prepare_policy_template('scale_up', period_sec, server_group)
if self.settings['asg']['scaling_policy'].get('scale_down', True):
self.prepare_policy_template('scale_down', period_sec, server_group)
|
python
|
def create_policy(self):
"""Wrapper function. Gets the server group, sets sane defaults,
deletes existing policies, and then runs self.prepare_policy_template
for scaling up and scaling down policies.
This function acts as the main driver for the scaling policy creationprocess
"""
if not self.settings['asg']['scaling_policy']:
self.log.info("No scaling policy found, skipping...")
return
server_group = self.get_server_group()
# Find all existing and remove them
scaling_policies = self.get_all_existing(server_group)
for policy in scaling_policies:
for subpolicy in policy:
self.delete_existing_policy(subpolicy, server_group)
if self.settings['asg']['scaling_policy']['period_minutes']:
period_sec = int(self.settings['asg']['scaling_policy']['period_minutes']) * 60
else:
period_sec = 1800
self.prepare_policy_template('scale_up', period_sec, server_group)
if self.settings['asg']['scaling_policy'].get('scale_down', True):
self.prepare_policy_template('scale_down', period_sec, server_group)
|
[
"def",
"create_policy",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"settings",
"[",
"'asg'",
"]",
"[",
"'scaling_policy'",
"]",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"No scaling policy found, skipping...\"",
")",
"return",
"server_group",
"=",
"self",
".",
"get_server_group",
"(",
")",
"# Find all existing and remove them",
"scaling_policies",
"=",
"self",
".",
"get_all_existing",
"(",
"server_group",
")",
"for",
"policy",
"in",
"scaling_policies",
":",
"for",
"subpolicy",
"in",
"policy",
":",
"self",
".",
"delete_existing_policy",
"(",
"subpolicy",
",",
"server_group",
")",
"if",
"self",
".",
"settings",
"[",
"'asg'",
"]",
"[",
"'scaling_policy'",
"]",
"[",
"'period_minutes'",
"]",
":",
"period_sec",
"=",
"int",
"(",
"self",
".",
"settings",
"[",
"'asg'",
"]",
"[",
"'scaling_policy'",
"]",
"[",
"'period_minutes'",
"]",
")",
"*",
"60",
"else",
":",
"period_sec",
"=",
"1800",
"self",
".",
"prepare_policy_template",
"(",
"'scale_up'",
",",
"period_sec",
",",
"server_group",
")",
"if",
"self",
".",
"settings",
"[",
"'asg'",
"]",
"[",
"'scaling_policy'",
"]",
".",
"get",
"(",
"'scale_down'",
",",
"True",
")",
":",
"self",
".",
"prepare_policy_template",
"(",
"'scale_down'",
",",
"period_sec",
",",
"server_group",
")"
] |
Wrapper function. Gets the server group, sets sane defaults,
deletes existing policies, and then runs self.prepare_policy_template
for scaling up and scaling down policies.
This function acts as the main driver for the scaling policy creationprocess
|
[
"Wrapper",
"function",
".",
"Gets",
"the",
"server",
"group",
"sets",
"sane",
"defaults",
"deletes",
"existing",
"policies",
"and",
"then",
"runs",
"self",
".",
"prepare_policy_template",
"for",
"scaling",
"up",
"and",
"scaling",
"down",
"policies",
".",
"This",
"function",
"acts",
"as",
"the",
"main",
"driver",
"for",
"the",
"scaling",
"policy",
"creationprocess"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/autoscaling_policy/create_policy.py#L90-L115
|
train
|
foremast/foremast
|
src/foremast/autoscaling_policy/create_policy.py
|
AutoScalingPolicy.get_server_group
|
def get_server_group(self):
"""Finds the most recently deployed server group for the application.
This is the server group that the scaling policy will be applied to.
Returns:
server_group (str): Name of the newest server group
"""
api_url = "{0}/applications/{1}".format(API_URL, self.app)
response = requests.get(api_url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
for server_group in response.json()['clusters'][self.env]:
return server_group['serverGroups'][-1]
|
python
|
def get_server_group(self):
"""Finds the most recently deployed server group for the application.
This is the server group that the scaling policy will be applied to.
Returns:
server_group (str): Name of the newest server group
"""
api_url = "{0}/applications/{1}".format(API_URL, self.app)
response = requests.get(api_url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
for server_group in response.json()['clusters'][self.env]:
return server_group['serverGroups'][-1]
|
[
"def",
"get_server_group",
"(",
"self",
")",
":",
"api_url",
"=",
"\"{0}/applications/{1}\"",
".",
"format",
"(",
"API_URL",
",",
"self",
".",
"app",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"api_url",
",",
"verify",
"=",
"GATE_CA_BUNDLE",
",",
"cert",
"=",
"GATE_CLIENT_CERT",
")",
"for",
"server_group",
"in",
"response",
".",
"json",
"(",
")",
"[",
"'clusters'",
"]",
"[",
"self",
".",
"env",
"]",
":",
"return",
"server_group",
"[",
"'serverGroups'",
"]",
"[",
"-",
"1",
"]"
] |
Finds the most recently deployed server group for the application.
This is the server group that the scaling policy will be applied to.
Returns:
server_group (str): Name of the newest server group
|
[
"Finds",
"the",
"most",
"recently",
"deployed",
"server",
"group",
"for",
"the",
"application",
".",
"This",
"is",
"the",
"server",
"group",
"that",
"the",
"scaling",
"policy",
"will",
"be",
"applied",
"to",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/autoscaling_policy/create_policy.py#L117-L127
|
train
|
foremast/foremast
|
src/foremast/autoscaling_policy/create_policy.py
|
AutoScalingPolicy.delete_existing_policy
|
def delete_existing_policy(self, scaling_policy, server_group):
"""Given a scaling_policy and server_group, deletes the existing scaling_policy.
Scaling policies need to be deleted instead of upserted for consistency.
Args:
scaling_policy (json): the scaling_policy json from Spinnaker that should be deleted
server_group (str): the affected server_group
"""
self.log.info("Deleting policy %s on %s", scaling_policy['policyName'], server_group)
delete_dict = {
"application":
self.app,
"description":
"Delete scaling policy",
"job": [{
"policyName": scaling_policy['policyName'],
"serverGroupName": server_group,
"credentials": self.env,
"region": self.region,
"provider": "aws",
"type": "deleteScalingPolicy",
"user": "foremast-autoscaling-policy"
}]
}
wait_for_task(json.dumps(delete_dict))
|
python
|
def delete_existing_policy(self, scaling_policy, server_group):
"""Given a scaling_policy and server_group, deletes the existing scaling_policy.
Scaling policies need to be deleted instead of upserted for consistency.
Args:
scaling_policy (json): the scaling_policy json from Spinnaker that should be deleted
server_group (str): the affected server_group
"""
self.log.info("Deleting policy %s on %s", scaling_policy['policyName'], server_group)
delete_dict = {
"application":
self.app,
"description":
"Delete scaling policy",
"job": [{
"policyName": scaling_policy['policyName'],
"serverGroupName": server_group,
"credentials": self.env,
"region": self.region,
"provider": "aws",
"type": "deleteScalingPolicy",
"user": "foremast-autoscaling-policy"
}]
}
wait_for_task(json.dumps(delete_dict))
|
[
"def",
"delete_existing_policy",
"(",
"self",
",",
"scaling_policy",
",",
"server_group",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Deleting policy %s on %s\"",
",",
"scaling_policy",
"[",
"'policyName'",
"]",
",",
"server_group",
")",
"delete_dict",
"=",
"{",
"\"application\"",
":",
"self",
".",
"app",
",",
"\"description\"",
":",
"\"Delete scaling policy\"",
",",
"\"job\"",
":",
"[",
"{",
"\"policyName\"",
":",
"scaling_policy",
"[",
"'policyName'",
"]",
",",
"\"serverGroupName\"",
":",
"server_group",
",",
"\"credentials\"",
":",
"self",
".",
"env",
",",
"\"region\"",
":",
"self",
".",
"region",
",",
"\"provider\"",
":",
"\"aws\"",
",",
"\"type\"",
":",
"\"deleteScalingPolicy\"",
",",
"\"user\"",
":",
"\"foremast-autoscaling-policy\"",
"}",
"]",
"}",
"wait_for_task",
"(",
"json",
".",
"dumps",
"(",
"delete_dict",
")",
")"
] |
Given a scaling_policy and server_group, deletes the existing scaling_policy.
Scaling policies need to be deleted instead of upserted for consistency.
Args:
scaling_policy (json): the scaling_policy json from Spinnaker that should be deleted
server_group (str): the affected server_group
|
[
"Given",
"a",
"scaling_policy",
"and",
"server_group",
"deletes",
"the",
"existing",
"scaling_policy",
".",
"Scaling",
"policies",
"need",
"to",
"be",
"deleted",
"instead",
"of",
"upserted",
"for",
"consistency",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/autoscaling_policy/create_policy.py#L129-L153
|
train
|
foremast/foremast
|
src/foremast/autoscaling_policy/create_policy.py
|
AutoScalingPolicy.get_all_existing
|
def get_all_existing(self, server_group):
"""Finds all existing scaling policies for an application
Returns:
scalingpolicies (list): List of all existing scaling policies for the application
"""
self.log.info("Checking for existing scaling policy")
url = "{0}/applications/{1}/clusters/{2}/{1}/serverGroups".format(API_URL, self.app, self.env)
response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
assert response.ok, "Error looking for existing Autoscaling Policy for {0}: {1}".format(self.app, response.text)
scalingpolicies = []
for servergroup in response.json():
if servergroup['scalingPolicies'] and servergroup['asg']['autoScalingGroupName'] == server_group:
self.log.info("Found policies on %s", server_group)
scalingpolicies.append(servergroup['scalingPolicies'])
self.log.debug("Scaling policies: %s", scalingpolicies)
return scalingpolicies
|
python
|
def get_all_existing(self, server_group):
"""Finds all existing scaling policies for an application
Returns:
scalingpolicies (list): List of all existing scaling policies for the application
"""
self.log.info("Checking for existing scaling policy")
url = "{0}/applications/{1}/clusters/{2}/{1}/serverGroups".format(API_URL, self.app, self.env)
response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
assert response.ok, "Error looking for existing Autoscaling Policy for {0}: {1}".format(self.app, response.text)
scalingpolicies = []
for servergroup in response.json():
if servergroup['scalingPolicies'] and servergroup['asg']['autoScalingGroupName'] == server_group:
self.log.info("Found policies on %s", server_group)
scalingpolicies.append(servergroup['scalingPolicies'])
self.log.debug("Scaling policies: %s", scalingpolicies)
return scalingpolicies
|
[
"def",
"get_all_existing",
"(",
"self",
",",
"server_group",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Checking for existing scaling policy\"",
")",
"url",
"=",
"\"{0}/applications/{1}/clusters/{2}/{1}/serverGroups\"",
".",
"format",
"(",
"API_URL",
",",
"self",
".",
"app",
",",
"self",
".",
"env",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"verify",
"=",
"GATE_CA_BUNDLE",
",",
"cert",
"=",
"GATE_CLIENT_CERT",
")",
"assert",
"response",
".",
"ok",
",",
"\"Error looking for existing Autoscaling Policy for {0}: {1}\"",
".",
"format",
"(",
"self",
".",
"app",
",",
"response",
".",
"text",
")",
"scalingpolicies",
"=",
"[",
"]",
"for",
"servergroup",
"in",
"response",
".",
"json",
"(",
")",
":",
"if",
"servergroup",
"[",
"'scalingPolicies'",
"]",
"and",
"servergroup",
"[",
"'asg'",
"]",
"[",
"'autoScalingGroupName'",
"]",
"==",
"server_group",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Found policies on %s\"",
",",
"server_group",
")",
"scalingpolicies",
".",
"append",
"(",
"servergroup",
"[",
"'scalingPolicies'",
"]",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Scaling policies: %s\"",
",",
"scalingpolicies",
")",
"return",
"scalingpolicies"
] |
Finds all existing scaling policies for an application
Returns:
scalingpolicies (list): List of all existing scaling policies for the application
|
[
"Finds",
"all",
"existing",
"scaling",
"policies",
"for",
"an",
"application"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/autoscaling_policy/create_policy.py#L155-L172
|
train
|
foremast/foremast
|
src/foremast/awslambda/cloudwatch_event/destroy_cloudwatch_event/destroy_cloudwatch_event.py
|
destroy_cloudwatch_event
|
def destroy_cloudwatch_event(app='', env='dev', region=''):
"""Destroy Cloudwatch event subscription.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
bool: True upon successful completion.
"""
session = boto3.Session(profile_name=env, region_name=region)
cloudwatch_client = session.client('events')
event_rules = get_cloudwatch_event_rule(app_name=app, account=env, region=region)
for rule in event_rules:
cloudwatch_client.remove_targets(Rule=rule, Ids=[app])
return True
|
python
|
def destroy_cloudwatch_event(app='', env='dev', region=''):
"""Destroy Cloudwatch event subscription.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
bool: True upon successful completion.
"""
session = boto3.Session(profile_name=env, region_name=region)
cloudwatch_client = session.client('events')
event_rules = get_cloudwatch_event_rule(app_name=app, account=env, region=region)
for rule in event_rules:
cloudwatch_client.remove_targets(Rule=rule, Ids=[app])
return True
|
[
"def",
"destroy_cloudwatch_event",
"(",
"app",
"=",
"''",
",",
"env",
"=",
"'dev'",
",",
"region",
"=",
"''",
")",
":",
"session",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
",",
"region_name",
"=",
"region",
")",
"cloudwatch_client",
"=",
"session",
".",
"client",
"(",
"'events'",
")",
"event_rules",
"=",
"get_cloudwatch_event_rule",
"(",
"app_name",
"=",
"app",
",",
"account",
"=",
"env",
",",
"region",
"=",
"region",
")",
"for",
"rule",
"in",
"event_rules",
":",
"cloudwatch_client",
".",
"remove_targets",
"(",
"Rule",
"=",
"rule",
",",
"Ids",
"=",
"[",
"app",
"]",
")",
"return",
"True"
] |
Destroy Cloudwatch event subscription.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
bool: True upon successful completion.
|
[
"Destroy",
"Cloudwatch",
"event",
"subscription",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/awslambda/cloudwatch_event/destroy_cloudwatch_event/destroy_cloudwatch_event.py#L26-L45
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps.create_bucket
|
def create_bucket(self):
"""Create or update bucket based on app name."""
bucket_exists = self._bucket_exists()
if self.s3props.get('shared_bucket_target'):
if bucket_exists:
LOG.info('App uses shared bucket - %s ', self.bucket)
else:
LOG.error("Shared bucket %s does not exist", self.bucket)
raise S3SharedBucketNotFound
else:
if self.region == 'us-east-1':
_response = self.s3client.create_bucket(ACL=self.s3props['bucket_acl'], Bucket=self.bucket)
else:
if not bucket_exists:
_response = self.s3client.create_bucket(ACL=self.s3props['bucket_acl'], Bucket=self.bucket,
CreateBucketConfiguration={
'LocationConstraint': self.region})
else:
_response = "bucket already exists, skipping create for non-standard region buckets."
LOG.debug('Response creating bucket: %s', _response)
LOG.info('%s - S3 Bucket Upserted', self.bucket)
self._put_bucket_policy()
self._put_bucket_website()
self._put_bucket_logging()
self._put_bucket_lifecycle()
self._put_bucket_versioning()
self._put_bucket_encryption()
self._put_bucket_tagging()
|
python
|
def create_bucket(self):
"""Create or update bucket based on app name."""
bucket_exists = self._bucket_exists()
if self.s3props.get('shared_bucket_target'):
if bucket_exists:
LOG.info('App uses shared bucket - %s ', self.bucket)
else:
LOG.error("Shared bucket %s does not exist", self.bucket)
raise S3SharedBucketNotFound
else:
if self.region == 'us-east-1':
_response = self.s3client.create_bucket(ACL=self.s3props['bucket_acl'], Bucket=self.bucket)
else:
if not bucket_exists:
_response = self.s3client.create_bucket(ACL=self.s3props['bucket_acl'], Bucket=self.bucket,
CreateBucketConfiguration={
'LocationConstraint': self.region})
else:
_response = "bucket already exists, skipping create for non-standard region buckets."
LOG.debug('Response creating bucket: %s', _response)
LOG.info('%s - S3 Bucket Upserted', self.bucket)
self._put_bucket_policy()
self._put_bucket_website()
self._put_bucket_logging()
self._put_bucket_lifecycle()
self._put_bucket_versioning()
self._put_bucket_encryption()
self._put_bucket_tagging()
|
[
"def",
"create_bucket",
"(",
"self",
")",
":",
"bucket_exists",
"=",
"self",
".",
"_bucket_exists",
"(",
")",
"if",
"self",
".",
"s3props",
".",
"get",
"(",
"'shared_bucket_target'",
")",
":",
"if",
"bucket_exists",
":",
"LOG",
".",
"info",
"(",
"'App uses shared bucket - %s '",
",",
"self",
".",
"bucket",
")",
"else",
":",
"LOG",
".",
"error",
"(",
"\"Shared bucket %s does not exist\"",
",",
"self",
".",
"bucket",
")",
"raise",
"S3SharedBucketNotFound",
"else",
":",
"if",
"self",
".",
"region",
"==",
"'us-east-1'",
":",
"_response",
"=",
"self",
".",
"s3client",
".",
"create_bucket",
"(",
"ACL",
"=",
"self",
".",
"s3props",
"[",
"'bucket_acl'",
"]",
",",
"Bucket",
"=",
"self",
".",
"bucket",
")",
"else",
":",
"if",
"not",
"bucket_exists",
":",
"_response",
"=",
"self",
".",
"s3client",
".",
"create_bucket",
"(",
"ACL",
"=",
"self",
".",
"s3props",
"[",
"'bucket_acl'",
"]",
",",
"Bucket",
"=",
"self",
".",
"bucket",
",",
"CreateBucketConfiguration",
"=",
"{",
"'LocationConstraint'",
":",
"self",
".",
"region",
"}",
")",
"else",
":",
"_response",
"=",
"\"bucket already exists, skipping create for non-standard region buckets.\"",
"LOG",
".",
"debug",
"(",
"'Response creating bucket: %s'",
",",
"_response",
")",
"LOG",
".",
"info",
"(",
"'%s - S3 Bucket Upserted'",
",",
"self",
".",
"bucket",
")",
"self",
".",
"_put_bucket_policy",
"(",
")",
"self",
".",
"_put_bucket_website",
"(",
")",
"self",
".",
"_put_bucket_logging",
"(",
")",
"self",
".",
"_put_bucket_lifecycle",
"(",
")",
"self",
".",
"_put_bucket_versioning",
"(",
")",
"self",
".",
"_put_bucket_encryption",
"(",
")",
"self",
".",
"_put_bucket_tagging",
"(",
")"
] |
Create or update bucket based on app name.
|
[
"Create",
"or",
"update",
"bucket",
"based",
"on",
"app",
"name",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L65-L92
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps._bucket_exists
|
def _bucket_exists(self):
"""Check if the bucket exists."""
try:
self.s3client.get_bucket_location(Bucket=self.bucket)
return True
except ClientError as error:
LOG.error(error)
return False
|
python
|
def _bucket_exists(self):
"""Check if the bucket exists."""
try:
self.s3client.get_bucket_location(Bucket=self.bucket)
return True
except ClientError as error:
LOG.error(error)
return False
|
[
"def",
"_bucket_exists",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"s3client",
".",
"get_bucket_location",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
")",
"return",
"True",
"except",
"ClientError",
"as",
"error",
":",
"LOG",
".",
"error",
"(",
"error",
")",
"return",
"False"
] |
Check if the bucket exists.
|
[
"Check",
"if",
"the",
"bucket",
"exists",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L94-L101
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps._put_bucket_policy
|
def _put_bucket_policy(self):
"""Attach a bucket policy to app bucket."""
if self.s3props['bucket_policy']:
policy_str = json.dumps(self.s3props['bucket_policy'])
_response = self.s3client.put_bucket_policy(Bucket=self.bucket, Policy=policy_str)
else:
_response = self.s3client.delete_bucket_policy(Bucket=self.bucket)
LOG.debug('Response adding bucket policy: %s', _response)
LOG.info('S3 Bucket Policy Attached')
|
python
|
def _put_bucket_policy(self):
"""Attach a bucket policy to app bucket."""
if self.s3props['bucket_policy']:
policy_str = json.dumps(self.s3props['bucket_policy'])
_response = self.s3client.put_bucket_policy(Bucket=self.bucket, Policy=policy_str)
else:
_response = self.s3client.delete_bucket_policy(Bucket=self.bucket)
LOG.debug('Response adding bucket policy: %s', _response)
LOG.info('S3 Bucket Policy Attached')
|
[
"def",
"_put_bucket_policy",
"(",
"self",
")",
":",
"if",
"self",
".",
"s3props",
"[",
"'bucket_policy'",
"]",
":",
"policy_str",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"s3props",
"[",
"'bucket_policy'",
"]",
")",
"_response",
"=",
"self",
".",
"s3client",
".",
"put_bucket_policy",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
",",
"Policy",
"=",
"policy_str",
")",
"else",
":",
"_response",
"=",
"self",
".",
"s3client",
".",
"delete_bucket_policy",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
")",
"LOG",
".",
"debug",
"(",
"'Response adding bucket policy: %s'",
",",
"_response",
")",
"LOG",
".",
"info",
"(",
"'S3 Bucket Policy Attached'",
")"
] |
Attach a bucket policy to app bucket.
|
[
"Attach",
"a",
"bucket",
"policy",
"to",
"app",
"bucket",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L103-L111
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps._put_bucket_website
|
def _put_bucket_website(self):
"""Configure static website on S3 bucket."""
if self.s3props['website']['enabled']:
website_config = {
'ErrorDocument': {
'Key': self.s3props['website']['error_document']
},
'IndexDocument': {
'Suffix': self.s3props['website']['index_suffix']
}
}
_response = self.s3client.put_bucket_website(Bucket=self.bucket, WebsiteConfiguration=website_config)
self._put_bucket_cors()
self._set_bucket_dns()
else:
_response = self.s3client.delete_bucket_website(Bucket=self.bucket)
self._put_bucket_cors()
LOG.debug('Response setting up S3 website: %s', _response)
LOG.info('S3 website settings updated')
|
python
|
def _put_bucket_website(self):
"""Configure static website on S3 bucket."""
if self.s3props['website']['enabled']:
website_config = {
'ErrorDocument': {
'Key': self.s3props['website']['error_document']
},
'IndexDocument': {
'Suffix': self.s3props['website']['index_suffix']
}
}
_response = self.s3client.put_bucket_website(Bucket=self.bucket, WebsiteConfiguration=website_config)
self._put_bucket_cors()
self._set_bucket_dns()
else:
_response = self.s3client.delete_bucket_website(Bucket=self.bucket)
self._put_bucket_cors()
LOG.debug('Response setting up S3 website: %s', _response)
LOG.info('S3 website settings updated')
|
[
"def",
"_put_bucket_website",
"(",
"self",
")",
":",
"if",
"self",
".",
"s3props",
"[",
"'website'",
"]",
"[",
"'enabled'",
"]",
":",
"website_config",
"=",
"{",
"'ErrorDocument'",
":",
"{",
"'Key'",
":",
"self",
".",
"s3props",
"[",
"'website'",
"]",
"[",
"'error_document'",
"]",
"}",
",",
"'IndexDocument'",
":",
"{",
"'Suffix'",
":",
"self",
".",
"s3props",
"[",
"'website'",
"]",
"[",
"'index_suffix'",
"]",
"}",
"}",
"_response",
"=",
"self",
".",
"s3client",
".",
"put_bucket_website",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
",",
"WebsiteConfiguration",
"=",
"website_config",
")",
"self",
".",
"_put_bucket_cors",
"(",
")",
"self",
".",
"_set_bucket_dns",
"(",
")",
"else",
":",
"_response",
"=",
"self",
".",
"s3client",
".",
"delete_bucket_website",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
")",
"self",
".",
"_put_bucket_cors",
"(",
")",
"LOG",
".",
"debug",
"(",
"'Response setting up S3 website: %s'",
",",
"_response",
")",
"LOG",
".",
"info",
"(",
"'S3 website settings updated'",
")"
] |
Configure static website on S3 bucket.
|
[
"Configure",
"static",
"website",
"on",
"S3",
"bucket",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L113-L131
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps._set_bucket_dns
|
def _set_bucket_dns(self):
"""Create CNAME for S3 endpoint."""
# Different regions have different s3 endpoint formats
dotformat_regions = ["eu-west-2", "eu-central-1", "ap-northeast-2", "ap-south-1", "ca-central-1", "us-east-2"]
if self.region in dotformat_regions:
s3_endpoint = "{0}.s3-website.{1}.amazonaws.com".format(self.bucket, self.region)
else:
s3_endpoint = "{0}.s3-website-{1}.amazonaws.com".format(self.bucket, self.region)
zone_ids = get_dns_zone_ids(env=self.env, facing="public")
dns_kwargs = {
'dns_name': self.bucket,
'dns_name_aws': s3_endpoint,
'dns_ttl': self.properties['dns']['ttl']
}
for zone_id in zone_ids:
LOG.debug('zone_id: %s', zone_id)
update_dns_zone_record(self.env, zone_id, **dns_kwargs)
LOG.info("Created DNS %s for Bucket", self.bucket)
|
python
|
def _set_bucket_dns(self):
"""Create CNAME for S3 endpoint."""
# Different regions have different s3 endpoint formats
dotformat_regions = ["eu-west-2", "eu-central-1", "ap-northeast-2", "ap-south-1", "ca-central-1", "us-east-2"]
if self.region in dotformat_regions:
s3_endpoint = "{0}.s3-website.{1}.amazonaws.com".format(self.bucket, self.region)
else:
s3_endpoint = "{0}.s3-website-{1}.amazonaws.com".format(self.bucket, self.region)
zone_ids = get_dns_zone_ids(env=self.env, facing="public")
dns_kwargs = {
'dns_name': self.bucket,
'dns_name_aws': s3_endpoint,
'dns_ttl': self.properties['dns']['ttl']
}
for zone_id in zone_ids:
LOG.debug('zone_id: %s', zone_id)
update_dns_zone_record(self.env, zone_id, **dns_kwargs)
LOG.info("Created DNS %s for Bucket", self.bucket)
|
[
"def",
"_set_bucket_dns",
"(",
"self",
")",
":",
"# Different regions have different s3 endpoint formats",
"dotformat_regions",
"=",
"[",
"\"eu-west-2\"",
",",
"\"eu-central-1\"",
",",
"\"ap-northeast-2\"",
",",
"\"ap-south-1\"",
",",
"\"ca-central-1\"",
",",
"\"us-east-2\"",
"]",
"if",
"self",
".",
"region",
"in",
"dotformat_regions",
":",
"s3_endpoint",
"=",
"\"{0}.s3-website.{1}.amazonaws.com\"",
".",
"format",
"(",
"self",
".",
"bucket",
",",
"self",
".",
"region",
")",
"else",
":",
"s3_endpoint",
"=",
"\"{0}.s3-website-{1}.amazonaws.com\"",
".",
"format",
"(",
"self",
".",
"bucket",
",",
"self",
".",
"region",
")",
"zone_ids",
"=",
"get_dns_zone_ids",
"(",
"env",
"=",
"self",
".",
"env",
",",
"facing",
"=",
"\"public\"",
")",
"dns_kwargs",
"=",
"{",
"'dns_name'",
":",
"self",
".",
"bucket",
",",
"'dns_name_aws'",
":",
"s3_endpoint",
",",
"'dns_ttl'",
":",
"self",
".",
"properties",
"[",
"'dns'",
"]",
"[",
"'ttl'",
"]",
"}",
"for",
"zone_id",
"in",
"zone_ids",
":",
"LOG",
".",
"debug",
"(",
"'zone_id: %s'",
",",
"zone_id",
")",
"update_dns_zone_record",
"(",
"self",
".",
"env",
",",
"zone_id",
",",
"*",
"*",
"dns_kwargs",
")",
"LOG",
".",
"info",
"(",
"\"Created DNS %s for Bucket\"",
",",
"self",
".",
"bucket",
")"
] |
Create CNAME for S3 endpoint.
|
[
"Create",
"CNAME",
"for",
"S3",
"endpoint",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L133-L152
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps._put_bucket_cors
|
def _put_bucket_cors(self):
"""Adds bucket cors configuration."""
if self.s3props['cors']['enabled'] and self.s3props['website']['enabled']:
cors_config = {}
cors_rules = []
for each_rule in self.s3props['cors']['cors_rules']:
cors_rules.append({
'AllowedHeaders': each_rule['cors_headers'],
'AllowedMethods': each_rule['cors_methods'],
'AllowedOrigins': each_rule['cors_origins'],
'ExposeHeaders': each_rule['cors_expose_headers'],
'MaxAgeSeconds': each_rule['cors_max_age']
})
cors_config = {
'CORSRules': cors_rules
}
LOG.debug(cors_config)
_response = self.s3client.put_bucket_cors(Bucket=self.bucket, CORSConfiguration=cors_config)
else:
_response = self.s3client.delete_bucket_cors(Bucket=self.bucket)
LOG.debug('Response setting up S3 CORS: %s', _response)
LOG.info('S3 CORS configuration updated')
|
python
|
def _put_bucket_cors(self):
"""Adds bucket cors configuration."""
if self.s3props['cors']['enabled'] and self.s3props['website']['enabled']:
cors_config = {}
cors_rules = []
for each_rule in self.s3props['cors']['cors_rules']:
cors_rules.append({
'AllowedHeaders': each_rule['cors_headers'],
'AllowedMethods': each_rule['cors_methods'],
'AllowedOrigins': each_rule['cors_origins'],
'ExposeHeaders': each_rule['cors_expose_headers'],
'MaxAgeSeconds': each_rule['cors_max_age']
})
cors_config = {
'CORSRules': cors_rules
}
LOG.debug(cors_config)
_response = self.s3client.put_bucket_cors(Bucket=self.bucket, CORSConfiguration=cors_config)
else:
_response = self.s3client.delete_bucket_cors(Bucket=self.bucket)
LOG.debug('Response setting up S3 CORS: %s', _response)
LOG.info('S3 CORS configuration updated')
|
[
"def",
"_put_bucket_cors",
"(",
"self",
")",
":",
"if",
"self",
".",
"s3props",
"[",
"'cors'",
"]",
"[",
"'enabled'",
"]",
"and",
"self",
".",
"s3props",
"[",
"'website'",
"]",
"[",
"'enabled'",
"]",
":",
"cors_config",
"=",
"{",
"}",
"cors_rules",
"=",
"[",
"]",
"for",
"each_rule",
"in",
"self",
".",
"s3props",
"[",
"'cors'",
"]",
"[",
"'cors_rules'",
"]",
":",
"cors_rules",
".",
"append",
"(",
"{",
"'AllowedHeaders'",
":",
"each_rule",
"[",
"'cors_headers'",
"]",
",",
"'AllowedMethods'",
":",
"each_rule",
"[",
"'cors_methods'",
"]",
",",
"'AllowedOrigins'",
":",
"each_rule",
"[",
"'cors_origins'",
"]",
",",
"'ExposeHeaders'",
":",
"each_rule",
"[",
"'cors_expose_headers'",
"]",
",",
"'MaxAgeSeconds'",
":",
"each_rule",
"[",
"'cors_max_age'",
"]",
"}",
")",
"cors_config",
"=",
"{",
"'CORSRules'",
":",
"cors_rules",
"}",
"LOG",
".",
"debug",
"(",
"cors_config",
")",
"_response",
"=",
"self",
".",
"s3client",
".",
"put_bucket_cors",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
",",
"CORSConfiguration",
"=",
"cors_config",
")",
"else",
":",
"_response",
"=",
"self",
".",
"s3client",
".",
"delete_bucket_cors",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
")",
"LOG",
".",
"debug",
"(",
"'Response setting up S3 CORS: %s'",
",",
"_response",
")",
"LOG",
".",
"info",
"(",
"'S3 CORS configuration updated'",
")"
] |
Adds bucket cors configuration.
|
[
"Adds",
"bucket",
"cors",
"configuration",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L154-L175
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps._put_bucket_encryption
|
def _put_bucket_encryption(self):
"""Adds bucket encryption configuration."""
if self.s3props['encryption']['enabled']:
encryption_config = {'Rules': [{}]}
encryption_config = {
'Rules': self.s3props['encryption']['encryption_rules']
}
LOG.debug(encryption_config)
_response = self.s3client.put_bucket_encryption(Bucket=self.bucket,
ServerSideEncryptionConfiguration=encryption_config)
else:
_response = self.s3client.delete_bucket_encryption(Bucket=self.bucket)
LOG.debug('Response setting up S3 encryption: %s', _response)
LOG.info('S3 encryption configuration updated')
|
python
|
def _put_bucket_encryption(self):
"""Adds bucket encryption configuration."""
if self.s3props['encryption']['enabled']:
encryption_config = {'Rules': [{}]}
encryption_config = {
'Rules': self.s3props['encryption']['encryption_rules']
}
LOG.debug(encryption_config)
_response = self.s3client.put_bucket_encryption(Bucket=self.bucket,
ServerSideEncryptionConfiguration=encryption_config)
else:
_response = self.s3client.delete_bucket_encryption(Bucket=self.bucket)
LOG.debug('Response setting up S3 encryption: %s', _response)
LOG.info('S3 encryption configuration updated')
|
[
"def",
"_put_bucket_encryption",
"(",
"self",
")",
":",
"if",
"self",
".",
"s3props",
"[",
"'encryption'",
"]",
"[",
"'enabled'",
"]",
":",
"encryption_config",
"=",
"{",
"'Rules'",
":",
"[",
"{",
"}",
"]",
"}",
"encryption_config",
"=",
"{",
"'Rules'",
":",
"self",
".",
"s3props",
"[",
"'encryption'",
"]",
"[",
"'encryption_rules'",
"]",
"}",
"LOG",
".",
"debug",
"(",
"encryption_config",
")",
"_response",
"=",
"self",
".",
"s3client",
".",
"put_bucket_encryption",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
",",
"ServerSideEncryptionConfiguration",
"=",
"encryption_config",
")",
"else",
":",
"_response",
"=",
"self",
".",
"s3client",
".",
"delete_bucket_encryption",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
")",
"LOG",
".",
"debug",
"(",
"'Response setting up S3 encryption: %s'",
",",
"_response",
")",
"LOG",
".",
"info",
"(",
"'S3 encryption configuration updated'",
")"
] |
Adds bucket encryption configuration.
|
[
"Adds",
"bucket",
"encryption",
"configuration",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L177-L190
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps._put_bucket_lifecycle
|
def _put_bucket_lifecycle(self):
"""Adds bucket lifecycle configuration."""
status = 'deleted'
if self.s3props['lifecycle']['enabled']:
lifecycle_config = {
'Rules': self.s3props['lifecycle']['lifecycle_rules']
}
LOG.debug('Lifecycle Config: %s', lifecycle_config)
_response = self.s3client.put_bucket_lifecycle_configuration(Bucket=self.bucket,
LifecycleConfiguration=lifecycle_config)
status = 'applied'
else:
_response = self.s3client.delete_bucket_lifecycle(Bucket=self.bucket)
LOG.debug('Response setting up S3 lifecycle: %s', _response)
LOG.info('S3 lifecycle configuration %s', status)
|
python
|
def _put_bucket_lifecycle(self):
"""Adds bucket lifecycle configuration."""
status = 'deleted'
if self.s3props['lifecycle']['enabled']:
lifecycle_config = {
'Rules': self.s3props['lifecycle']['lifecycle_rules']
}
LOG.debug('Lifecycle Config: %s', lifecycle_config)
_response = self.s3client.put_bucket_lifecycle_configuration(Bucket=self.bucket,
LifecycleConfiguration=lifecycle_config)
status = 'applied'
else:
_response = self.s3client.delete_bucket_lifecycle(Bucket=self.bucket)
LOG.debug('Response setting up S3 lifecycle: %s', _response)
LOG.info('S3 lifecycle configuration %s', status)
|
[
"def",
"_put_bucket_lifecycle",
"(",
"self",
")",
":",
"status",
"=",
"'deleted'",
"if",
"self",
".",
"s3props",
"[",
"'lifecycle'",
"]",
"[",
"'enabled'",
"]",
":",
"lifecycle_config",
"=",
"{",
"'Rules'",
":",
"self",
".",
"s3props",
"[",
"'lifecycle'",
"]",
"[",
"'lifecycle_rules'",
"]",
"}",
"LOG",
".",
"debug",
"(",
"'Lifecycle Config: %s'",
",",
"lifecycle_config",
")",
"_response",
"=",
"self",
".",
"s3client",
".",
"put_bucket_lifecycle_configuration",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
",",
"LifecycleConfiguration",
"=",
"lifecycle_config",
")",
"status",
"=",
"'applied'",
"else",
":",
"_response",
"=",
"self",
".",
"s3client",
".",
"delete_bucket_lifecycle",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
")",
"LOG",
".",
"debug",
"(",
"'Response setting up S3 lifecycle: %s'",
",",
"_response",
")",
"LOG",
".",
"info",
"(",
"'S3 lifecycle configuration %s'",
",",
"status",
")"
] |
Adds bucket lifecycle configuration.
|
[
"Adds",
"bucket",
"lifecycle",
"configuration",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L192-L206
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps._put_bucket_logging
|
def _put_bucket_logging(self):
"""Adds bucket logging policy to bucket for s3 access requests"""
logging_config = {}
if self.s3props['logging']['enabled']:
logging_config = {
'LoggingEnabled': {
'TargetBucket': self.s3props['logging']['logging_bucket'],
'TargetGrants': self.s3props['logging']['logging_grants'],
'TargetPrefix': self.s3props['logging']['logging_bucket_prefix']
}
}
_response = self.s3client.put_bucket_logging(Bucket=self.bucket, BucketLoggingStatus=logging_config)
LOG.debug('Response setting up S3 logging: %s', _response)
LOG.info('S3 logging configuration updated')
|
python
|
def _put_bucket_logging(self):
"""Adds bucket logging policy to bucket for s3 access requests"""
logging_config = {}
if self.s3props['logging']['enabled']:
logging_config = {
'LoggingEnabled': {
'TargetBucket': self.s3props['logging']['logging_bucket'],
'TargetGrants': self.s3props['logging']['logging_grants'],
'TargetPrefix': self.s3props['logging']['logging_bucket_prefix']
}
}
_response = self.s3client.put_bucket_logging(Bucket=self.bucket, BucketLoggingStatus=logging_config)
LOG.debug('Response setting up S3 logging: %s', _response)
LOG.info('S3 logging configuration updated')
|
[
"def",
"_put_bucket_logging",
"(",
"self",
")",
":",
"logging_config",
"=",
"{",
"}",
"if",
"self",
".",
"s3props",
"[",
"'logging'",
"]",
"[",
"'enabled'",
"]",
":",
"logging_config",
"=",
"{",
"'LoggingEnabled'",
":",
"{",
"'TargetBucket'",
":",
"self",
".",
"s3props",
"[",
"'logging'",
"]",
"[",
"'logging_bucket'",
"]",
",",
"'TargetGrants'",
":",
"self",
".",
"s3props",
"[",
"'logging'",
"]",
"[",
"'logging_grants'",
"]",
",",
"'TargetPrefix'",
":",
"self",
".",
"s3props",
"[",
"'logging'",
"]",
"[",
"'logging_bucket_prefix'",
"]",
"}",
"}",
"_response",
"=",
"self",
".",
"s3client",
".",
"put_bucket_logging",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
",",
"BucketLoggingStatus",
"=",
"logging_config",
")",
"LOG",
".",
"debug",
"(",
"'Response setting up S3 logging: %s'",
",",
"_response",
")",
"LOG",
".",
"info",
"(",
"'S3 logging configuration updated'",
")"
] |
Adds bucket logging policy to bucket for s3 access requests
|
[
"Adds",
"bucket",
"logging",
"policy",
"to",
"bucket",
"for",
"s3",
"access",
"requests"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L208-L221
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps._put_bucket_tagging
|
def _put_bucket_tagging(self):
"""Add bucket tags to bucket."""
all_tags = self.s3props['tagging']['tags']
all_tags.update({'app_group': self.group, 'app_name': self.app_name})
tag_set = generate_s3_tags.generated_tag_data(all_tags)
tagging_config = {'TagSet': tag_set}
self.s3client.put_bucket_tagging(Bucket=self.bucket, Tagging=tagging_config)
LOG.info("Adding tagging %s for Bucket", tag_set)
|
python
|
def _put_bucket_tagging(self):
"""Add bucket tags to bucket."""
all_tags = self.s3props['tagging']['tags']
all_tags.update({'app_group': self.group, 'app_name': self.app_name})
tag_set = generate_s3_tags.generated_tag_data(all_tags)
tagging_config = {'TagSet': tag_set}
self.s3client.put_bucket_tagging(Bucket=self.bucket, Tagging=tagging_config)
LOG.info("Adding tagging %s for Bucket", tag_set)
|
[
"def",
"_put_bucket_tagging",
"(",
"self",
")",
":",
"all_tags",
"=",
"self",
".",
"s3props",
"[",
"'tagging'",
"]",
"[",
"'tags'",
"]",
"all_tags",
".",
"update",
"(",
"{",
"'app_group'",
":",
"self",
".",
"group",
",",
"'app_name'",
":",
"self",
".",
"app_name",
"}",
")",
"tag_set",
"=",
"generate_s3_tags",
".",
"generated_tag_data",
"(",
"all_tags",
")",
"tagging_config",
"=",
"{",
"'TagSet'",
":",
"tag_set",
"}",
"self",
".",
"s3client",
".",
"put_bucket_tagging",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
",",
"Tagging",
"=",
"tagging_config",
")",
"LOG",
".",
"info",
"(",
"\"Adding tagging %s for Bucket\"",
",",
"tag_set",
")"
] |
Add bucket tags to bucket.
|
[
"Add",
"bucket",
"tags",
"to",
"bucket",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L223-L232
|
train
|
foremast/foremast
|
src/foremast/s3/s3apps.py
|
S3Apps._put_bucket_versioning
|
def _put_bucket_versioning(self):
"""Adds bucket versioning policy to bucket"""
status = 'Suspended'
if self.s3props['versioning']['enabled']:
status = 'Enabled'
versioning_config = {
'MFADelete': self.s3props['versioning']['mfa_delete'],
'Status': status
}
_response = self.s3client.put_bucket_versioning(Bucket=self.bucket, VersioningConfiguration=versioning_config)
LOG.debug('Response setting up S3 versioning: %s', _response)
LOG.info('S3 versioning configuration updated')
|
python
|
def _put_bucket_versioning(self):
"""Adds bucket versioning policy to bucket"""
status = 'Suspended'
if self.s3props['versioning']['enabled']:
status = 'Enabled'
versioning_config = {
'MFADelete': self.s3props['versioning']['mfa_delete'],
'Status': status
}
_response = self.s3client.put_bucket_versioning(Bucket=self.bucket, VersioningConfiguration=versioning_config)
LOG.debug('Response setting up S3 versioning: %s', _response)
LOG.info('S3 versioning configuration updated')
|
[
"def",
"_put_bucket_versioning",
"(",
"self",
")",
":",
"status",
"=",
"'Suspended'",
"if",
"self",
".",
"s3props",
"[",
"'versioning'",
"]",
"[",
"'enabled'",
"]",
":",
"status",
"=",
"'Enabled'",
"versioning_config",
"=",
"{",
"'MFADelete'",
":",
"self",
".",
"s3props",
"[",
"'versioning'",
"]",
"[",
"'mfa_delete'",
"]",
",",
"'Status'",
":",
"status",
"}",
"_response",
"=",
"self",
".",
"s3client",
".",
"put_bucket_versioning",
"(",
"Bucket",
"=",
"self",
".",
"bucket",
",",
"VersioningConfiguration",
"=",
"versioning_config",
")",
"LOG",
".",
"debug",
"(",
"'Response setting up S3 versioning: %s'",
",",
"_response",
")",
"LOG",
".",
"info",
"(",
"'S3 versioning configuration updated'",
")"
] |
Adds bucket versioning policy to bucket
|
[
"Adds",
"bucket",
"versioning",
"policy",
"to",
"bucket"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/s3/s3apps.py#L234-L247
|
train
|
foremast/foremast
|
src/foremast/configs/prepare_configs.py
|
process_git_configs
|
def process_git_configs(git_short=''):
"""Retrieve _application.json_ files from GitLab.
Args:
git_short (str): Short Git representation of repository, e.g.
forrest/core.
Returns:
collections.defaultdict: Configurations stored for each environment
found.
"""
LOG.info('Processing application.json files from GitLab "%s".', git_short)
file_lookup = FileLookup(git_short=git_short)
app_configs = process_configs(file_lookup,
RUNWAY_BASE_PATH + '/application-master-{env}.json',
RUNWAY_BASE_PATH + '/pipeline.json')
commit_obj = file_lookup.project.commits.get('master')
config_commit = commit_obj.attributes['id']
LOG.info('Commit ID used: %s', config_commit)
app_configs['pipeline']['config_commit'] = config_commit
return app_configs
|
python
|
def process_git_configs(git_short=''):
"""Retrieve _application.json_ files from GitLab.
Args:
git_short (str): Short Git representation of repository, e.g.
forrest/core.
Returns:
collections.defaultdict: Configurations stored for each environment
found.
"""
LOG.info('Processing application.json files from GitLab "%s".', git_short)
file_lookup = FileLookup(git_short=git_short)
app_configs = process_configs(file_lookup,
RUNWAY_BASE_PATH + '/application-master-{env}.json',
RUNWAY_BASE_PATH + '/pipeline.json')
commit_obj = file_lookup.project.commits.get('master')
config_commit = commit_obj.attributes['id']
LOG.info('Commit ID used: %s', config_commit)
app_configs['pipeline']['config_commit'] = config_commit
return app_configs
|
[
"def",
"process_git_configs",
"(",
"git_short",
"=",
"''",
")",
":",
"LOG",
".",
"info",
"(",
"'Processing application.json files from GitLab \"%s\".'",
",",
"git_short",
")",
"file_lookup",
"=",
"FileLookup",
"(",
"git_short",
"=",
"git_short",
")",
"app_configs",
"=",
"process_configs",
"(",
"file_lookup",
",",
"RUNWAY_BASE_PATH",
"+",
"'/application-master-{env}.json'",
",",
"RUNWAY_BASE_PATH",
"+",
"'/pipeline.json'",
")",
"commit_obj",
"=",
"file_lookup",
".",
"project",
".",
"commits",
".",
"get",
"(",
"'master'",
")",
"config_commit",
"=",
"commit_obj",
".",
"attributes",
"[",
"'id'",
"]",
"LOG",
".",
"info",
"(",
"'Commit ID used: %s'",
",",
"config_commit",
")",
"app_configs",
"[",
"'pipeline'",
"]",
"[",
"'config_commit'",
"]",
"=",
"config_commit",
"return",
"app_configs"
] |
Retrieve _application.json_ files from GitLab.
Args:
git_short (str): Short Git representation of repository, e.g.
forrest/core.
Returns:
collections.defaultdict: Configurations stored for each environment
found.
|
[
"Retrieve",
"_application",
".",
"json_",
"files",
"from",
"GitLab",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/configs/prepare_configs.py#L26-L46
|
train
|
foremast/foremast
|
src/foremast/configs/prepare_configs.py
|
process_runway_configs
|
def process_runway_configs(runway_dir=''):
"""Read the _application.json_ files.
Args:
runway_dir (str): Name of runway directory with app.json files.
Returns:
collections.defaultdict: Configurations stored for each environment
found.
"""
LOG.info('Processing application.json files from local directory "%s".', runway_dir)
file_lookup = FileLookup(runway_dir=runway_dir)
app_configs = process_configs(file_lookup, 'application-master-{env}.json', 'pipeline.json')
return app_configs
|
python
|
def process_runway_configs(runway_dir=''):
"""Read the _application.json_ files.
Args:
runway_dir (str): Name of runway directory with app.json files.
Returns:
collections.defaultdict: Configurations stored for each environment
found.
"""
LOG.info('Processing application.json files from local directory "%s".', runway_dir)
file_lookup = FileLookup(runway_dir=runway_dir)
app_configs = process_configs(file_lookup, 'application-master-{env}.json', 'pipeline.json')
return app_configs
|
[
"def",
"process_runway_configs",
"(",
"runway_dir",
"=",
"''",
")",
":",
"LOG",
".",
"info",
"(",
"'Processing application.json files from local directory \"%s\".'",
",",
"runway_dir",
")",
"file_lookup",
"=",
"FileLookup",
"(",
"runway_dir",
"=",
"runway_dir",
")",
"app_configs",
"=",
"process_configs",
"(",
"file_lookup",
",",
"'application-master-{env}.json'",
",",
"'pipeline.json'",
")",
"return",
"app_configs"
] |
Read the _application.json_ files.
Args:
runway_dir (str): Name of runway directory with app.json files.
Returns:
collections.defaultdict: Configurations stored for each environment
found.
|
[
"Read",
"the",
"_application",
".",
"json_",
"files",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/configs/prepare_configs.py#L49-L62
|
train
|
foremast/foremast
|
src/foremast/configs/prepare_configs.py
|
process_configs
|
def process_configs(file_lookup, app_config_format, pipeline_config):
"""Processes the configs from lookup sources.
Args:
file_lookup (FileLookup): Source to look for file/config
app_config_format (str): The format for application config files.
pipeline_config (str): Name/path of the pipeline config
Returns:
dict: Retreived application config
"""
app_configs = collections.defaultdict(dict)
for env in ENVS:
file_json = app_config_format.format(env=env)
try:
env_config = file_lookup.json(filename=file_json)
app_configs[env] = apply_region_configs(env_config)
except FileNotFoundError:
LOG.critical('Application configuration not available for %s.', env)
continue
try:
app_configs['pipeline'] = file_lookup.json(filename=pipeline_config)
except FileNotFoundError:
LOG.warning('Unable to process pipeline.json. Using defaults.')
app_configs['pipeline'] = {'env': ['stage', 'prod']}
LOG.debug('Application configs:\n%s', app_configs)
return app_configs
|
python
|
def process_configs(file_lookup, app_config_format, pipeline_config):
"""Processes the configs from lookup sources.
Args:
file_lookup (FileLookup): Source to look for file/config
app_config_format (str): The format for application config files.
pipeline_config (str): Name/path of the pipeline config
Returns:
dict: Retreived application config
"""
app_configs = collections.defaultdict(dict)
for env in ENVS:
file_json = app_config_format.format(env=env)
try:
env_config = file_lookup.json(filename=file_json)
app_configs[env] = apply_region_configs(env_config)
except FileNotFoundError:
LOG.critical('Application configuration not available for %s.', env)
continue
try:
app_configs['pipeline'] = file_lookup.json(filename=pipeline_config)
except FileNotFoundError:
LOG.warning('Unable to process pipeline.json. Using defaults.')
app_configs['pipeline'] = {'env': ['stage', 'prod']}
LOG.debug('Application configs:\n%s', app_configs)
return app_configs
|
[
"def",
"process_configs",
"(",
"file_lookup",
",",
"app_config_format",
",",
"pipeline_config",
")",
":",
"app_configs",
"=",
"collections",
".",
"defaultdict",
"(",
"dict",
")",
"for",
"env",
"in",
"ENVS",
":",
"file_json",
"=",
"app_config_format",
".",
"format",
"(",
"env",
"=",
"env",
")",
"try",
":",
"env_config",
"=",
"file_lookup",
".",
"json",
"(",
"filename",
"=",
"file_json",
")",
"app_configs",
"[",
"env",
"]",
"=",
"apply_region_configs",
"(",
"env_config",
")",
"except",
"FileNotFoundError",
":",
"LOG",
".",
"critical",
"(",
"'Application configuration not available for %s.'",
",",
"env",
")",
"continue",
"try",
":",
"app_configs",
"[",
"'pipeline'",
"]",
"=",
"file_lookup",
".",
"json",
"(",
"filename",
"=",
"pipeline_config",
")",
"except",
"FileNotFoundError",
":",
"LOG",
".",
"warning",
"(",
"'Unable to process pipeline.json. Using defaults.'",
")",
"app_configs",
"[",
"'pipeline'",
"]",
"=",
"{",
"'env'",
":",
"[",
"'stage'",
",",
"'prod'",
"]",
"}",
"LOG",
".",
"debug",
"(",
"'Application configs:\\n%s'",
",",
"app_configs",
")",
"return",
"app_configs"
] |
Processes the configs from lookup sources.
Args:
file_lookup (FileLookup): Source to look for file/config
app_config_format (str): The format for application config files.
pipeline_config (str): Name/path of the pipeline config
Returns:
dict: Retreived application config
|
[
"Processes",
"the",
"configs",
"from",
"lookup",
"sources",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/configs/prepare_configs.py#L65-L93
|
train
|
foremast/foremast
|
src/foremast/configs/prepare_configs.py
|
apply_region_configs
|
def apply_region_configs(env_config):
"""Override default env configs with region specific configs and nest
all values under a region
Args:
env_config (dict): The environment specific config.
Return:
dict: Newly updated dictionary with region overrides applied.
"""
new_config = env_config.copy()
for region in env_config.get('regions', REGIONS):
if isinstance(env_config.get('regions'), dict):
region_specific_config = env_config['regions'][region]
new_config[region] = dict(DeepChainMap(region_specific_config, env_config))
else:
new_config[region] = env_config.copy()
LOG.debug('Region Specific Config:\n%s', new_config)
return new_config
|
python
|
def apply_region_configs(env_config):
"""Override default env configs with region specific configs and nest
all values under a region
Args:
env_config (dict): The environment specific config.
Return:
dict: Newly updated dictionary with region overrides applied.
"""
new_config = env_config.copy()
for region in env_config.get('regions', REGIONS):
if isinstance(env_config.get('regions'), dict):
region_specific_config = env_config['regions'][region]
new_config[region] = dict(DeepChainMap(region_specific_config, env_config))
else:
new_config[region] = env_config.copy()
LOG.debug('Region Specific Config:\n%s', new_config)
return new_config
|
[
"def",
"apply_region_configs",
"(",
"env_config",
")",
":",
"new_config",
"=",
"env_config",
".",
"copy",
"(",
")",
"for",
"region",
"in",
"env_config",
".",
"get",
"(",
"'regions'",
",",
"REGIONS",
")",
":",
"if",
"isinstance",
"(",
"env_config",
".",
"get",
"(",
"'regions'",
")",
",",
"dict",
")",
":",
"region_specific_config",
"=",
"env_config",
"[",
"'regions'",
"]",
"[",
"region",
"]",
"new_config",
"[",
"region",
"]",
"=",
"dict",
"(",
"DeepChainMap",
"(",
"region_specific_config",
",",
"env_config",
")",
")",
"else",
":",
"new_config",
"[",
"region",
"]",
"=",
"env_config",
".",
"copy",
"(",
")",
"LOG",
".",
"debug",
"(",
"'Region Specific Config:\\n%s'",
",",
"new_config",
")",
"return",
"new_config"
] |
Override default env configs with region specific configs and nest
all values under a region
Args:
env_config (dict): The environment specific config.
Return:
dict: Newly updated dictionary with region overrides applied.
|
[
"Override",
"default",
"env",
"configs",
"with",
"region",
"specific",
"configs",
"and",
"nest",
"all",
"values",
"under",
"a",
"region"
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/configs/prepare_configs.py#L96-L114
|
train
|
foremast/foremast
|
src/foremast/iam/create_iam.py
|
create_iam_resources
|
def create_iam_resources(env='dev', app='', **_):
"""Create the IAM Resources for the application.
Args:
env (str): Deployment environment/account, i.e. dev, stage, prod.
app (str): Spinnaker Application name.
Returns:
True upon successful completion.
"""
session = boto3.session.Session(profile_name=env)
client = session.client('iam')
app_properties = get_properties(env='pipeline')
generated = get_details(env=env, app=app)
generated_iam = generated.iam()
app_details = collections.namedtuple('AppDetails', generated_iam.keys())
details = app_details(**generated_iam)
LOG.debug('Application details: %s', details)
deployment_type = app_properties['type']
role_trust_template = get_template(
'infrastructure/iam/trust/{0}_role.json.j2'.format(deployment_type), formats=generated)
resource_action(
client,
action='create_role',
log_format='Created Role: %(RoleName)s',
RoleName=details.role,
AssumeRolePolicyDocument=role_trust_template)
resource_action(
client,
action='create_instance_profile',
log_format='Created Instance Profile: %(InstanceProfileName)s',
InstanceProfileName=details.profile)
attach_profile_to_role(client, role_name=details.role, profile_name=details.profile)
iam_policy = construct_policy(app=app, group=details.group, env=env, pipeline_settings=app_properties)
if iam_policy:
resource_action(
client,
action='put_role_policy',
log_format='Added IAM Policy: %(PolicyName)s',
RoleName=details.role,
PolicyName=details.policy,
PolicyDocument=iam_policy)
resource_action(client, action='create_user', log_format='Created User: %(UserName)s', UserName=details.user)
resource_action(client, action='create_group', log_format='Created Group: %(GroupName)s', GroupName=details.group)
resource_action(
client,
action='add_user_to_group',
log_format='Added User to Group: %(UserName)s -> %(GroupName)s',
GroupName=details.group,
UserName=details.user)
return True
|
python
|
def create_iam_resources(env='dev', app='', **_):
"""Create the IAM Resources for the application.
Args:
env (str): Deployment environment/account, i.e. dev, stage, prod.
app (str): Spinnaker Application name.
Returns:
True upon successful completion.
"""
session = boto3.session.Session(profile_name=env)
client = session.client('iam')
app_properties = get_properties(env='pipeline')
generated = get_details(env=env, app=app)
generated_iam = generated.iam()
app_details = collections.namedtuple('AppDetails', generated_iam.keys())
details = app_details(**generated_iam)
LOG.debug('Application details: %s', details)
deployment_type = app_properties['type']
role_trust_template = get_template(
'infrastructure/iam/trust/{0}_role.json.j2'.format(deployment_type), formats=generated)
resource_action(
client,
action='create_role',
log_format='Created Role: %(RoleName)s',
RoleName=details.role,
AssumeRolePolicyDocument=role_trust_template)
resource_action(
client,
action='create_instance_profile',
log_format='Created Instance Profile: %(InstanceProfileName)s',
InstanceProfileName=details.profile)
attach_profile_to_role(client, role_name=details.role, profile_name=details.profile)
iam_policy = construct_policy(app=app, group=details.group, env=env, pipeline_settings=app_properties)
if iam_policy:
resource_action(
client,
action='put_role_policy',
log_format='Added IAM Policy: %(PolicyName)s',
RoleName=details.role,
PolicyName=details.policy,
PolicyDocument=iam_policy)
resource_action(client, action='create_user', log_format='Created User: %(UserName)s', UserName=details.user)
resource_action(client, action='create_group', log_format='Created Group: %(GroupName)s', GroupName=details.group)
resource_action(
client,
action='add_user_to_group',
log_format='Added User to Group: %(UserName)s -> %(GroupName)s',
GroupName=details.group,
UserName=details.user)
return True
|
[
"def",
"create_iam_resources",
"(",
"env",
"=",
"'dev'",
",",
"app",
"=",
"''",
",",
"*",
"*",
"_",
")",
":",
"session",
"=",
"boto3",
".",
"session",
".",
"Session",
"(",
"profile_name",
"=",
"env",
")",
"client",
"=",
"session",
".",
"client",
"(",
"'iam'",
")",
"app_properties",
"=",
"get_properties",
"(",
"env",
"=",
"'pipeline'",
")",
"generated",
"=",
"get_details",
"(",
"env",
"=",
"env",
",",
"app",
"=",
"app",
")",
"generated_iam",
"=",
"generated",
".",
"iam",
"(",
")",
"app_details",
"=",
"collections",
".",
"namedtuple",
"(",
"'AppDetails'",
",",
"generated_iam",
".",
"keys",
"(",
")",
")",
"details",
"=",
"app_details",
"(",
"*",
"*",
"generated_iam",
")",
"LOG",
".",
"debug",
"(",
"'Application details: %s'",
",",
"details",
")",
"deployment_type",
"=",
"app_properties",
"[",
"'type'",
"]",
"role_trust_template",
"=",
"get_template",
"(",
"'infrastructure/iam/trust/{0}_role.json.j2'",
".",
"format",
"(",
"deployment_type",
")",
",",
"formats",
"=",
"generated",
")",
"resource_action",
"(",
"client",
",",
"action",
"=",
"'create_role'",
",",
"log_format",
"=",
"'Created Role: %(RoleName)s'",
",",
"RoleName",
"=",
"details",
".",
"role",
",",
"AssumeRolePolicyDocument",
"=",
"role_trust_template",
")",
"resource_action",
"(",
"client",
",",
"action",
"=",
"'create_instance_profile'",
",",
"log_format",
"=",
"'Created Instance Profile: %(InstanceProfileName)s'",
",",
"InstanceProfileName",
"=",
"details",
".",
"profile",
")",
"attach_profile_to_role",
"(",
"client",
",",
"role_name",
"=",
"details",
".",
"role",
",",
"profile_name",
"=",
"details",
".",
"profile",
")",
"iam_policy",
"=",
"construct_policy",
"(",
"app",
"=",
"app",
",",
"group",
"=",
"details",
".",
"group",
",",
"env",
"=",
"env",
",",
"pipeline_settings",
"=",
"app_properties",
")",
"if",
"iam_policy",
":",
"resource_action",
"(",
"client",
",",
"action",
"=",
"'put_role_policy'",
",",
"log_format",
"=",
"'Added IAM Policy: %(PolicyName)s'",
",",
"RoleName",
"=",
"details",
".",
"role",
",",
"PolicyName",
"=",
"details",
".",
"policy",
",",
"PolicyDocument",
"=",
"iam_policy",
")",
"resource_action",
"(",
"client",
",",
"action",
"=",
"'create_user'",
",",
"log_format",
"=",
"'Created User: %(UserName)s'",
",",
"UserName",
"=",
"details",
".",
"user",
")",
"resource_action",
"(",
"client",
",",
"action",
"=",
"'create_group'",
",",
"log_format",
"=",
"'Created Group: %(GroupName)s'",
",",
"GroupName",
"=",
"details",
".",
"group",
")",
"resource_action",
"(",
"client",
",",
"action",
"=",
"'add_user_to_group'",
",",
"log_format",
"=",
"'Added User to Group: %(UserName)s -> %(GroupName)s'",
",",
"GroupName",
"=",
"details",
".",
"group",
",",
"UserName",
"=",
"details",
".",
"user",
")",
"return",
"True"
] |
Create the IAM Resources for the application.
Args:
env (str): Deployment environment/account, i.e. dev, stage, prod.
app (str): Spinnaker Application name.
Returns:
True upon successful completion.
|
[
"Create",
"the",
"IAM",
"Resources",
"for",
"the",
"application",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/iam/create_iam.py#L29-L87
|
train
|
foremast/foremast
|
src/foremast/iam/create_iam.py
|
attach_profile_to_role
|
def attach_profile_to_role(client, role_name='forrest_unicorn_role', profile_name='forrest_unicorn_profile'):
"""Attach an IAM Instance Profile _profile_name_ to Role _role_name_.
Args:
role_name (str): Name of Role.
profile_name (str): Name of Instance Profile.
Returns:
True upon successful completion.
"""
current_instance_profiles = resource_action(
client,
action='list_instance_profiles_for_role',
log_format='Found Instance Profiles for %(RoleName)s.',
RoleName=role_name)['InstanceProfiles']
for profile in current_instance_profiles:
if profile['InstanceProfileName'] == profile_name:
LOG.info('Found Instance Profile attached to Role: %s -> %s', profile_name, role_name)
break
else:
for remove_profile in current_instance_profiles:
resource_action(
client,
action='remove_role_from_instance_profile',
log_format='Removed Instance Profile from Role: '
'%(InstanceProfileName)s -> %(RoleName)s',
InstanceProfileName=remove_profile['InstanceProfileName'],
RoleName=role_name)
resource_action(
client,
action='add_role_to_instance_profile',
log_format='Added Instance Profile to Role: '
'%(InstanceProfileName)s -> %(RoleName)s',
InstanceProfileName=profile_name,
RoleName=role_name)
return True
|
python
|
def attach_profile_to_role(client, role_name='forrest_unicorn_role', profile_name='forrest_unicorn_profile'):
"""Attach an IAM Instance Profile _profile_name_ to Role _role_name_.
Args:
role_name (str): Name of Role.
profile_name (str): Name of Instance Profile.
Returns:
True upon successful completion.
"""
current_instance_profiles = resource_action(
client,
action='list_instance_profiles_for_role',
log_format='Found Instance Profiles for %(RoleName)s.',
RoleName=role_name)['InstanceProfiles']
for profile in current_instance_profiles:
if profile['InstanceProfileName'] == profile_name:
LOG.info('Found Instance Profile attached to Role: %s -> %s', profile_name, role_name)
break
else:
for remove_profile in current_instance_profiles:
resource_action(
client,
action='remove_role_from_instance_profile',
log_format='Removed Instance Profile from Role: '
'%(InstanceProfileName)s -> %(RoleName)s',
InstanceProfileName=remove_profile['InstanceProfileName'],
RoleName=role_name)
resource_action(
client,
action='add_role_to_instance_profile',
log_format='Added Instance Profile to Role: '
'%(InstanceProfileName)s -> %(RoleName)s',
InstanceProfileName=profile_name,
RoleName=role_name)
return True
|
[
"def",
"attach_profile_to_role",
"(",
"client",
",",
"role_name",
"=",
"'forrest_unicorn_role'",
",",
"profile_name",
"=",
"'forrest_unicorn_profile'",
")",
":",
"current_instance_profiles",
"=",
"resource_action",
"(",
"client",
",",
"action",
"=",
"'list_instance_profiles_for_role'",
",",
"log_format",
"=",
"'Found Instance Profiles for %(RoleName)s.'",
",",
"RoleName",
"=",
"role_name",
")",
"[",
"'InstanceProfiles'",
"]",
"for",
"profile",
"in",
"current_instance_profiles",
":",
"if",
"profile",
"[",
"'InstanceProfileName'",
"]",
"==",
"profile_name",
":",
"LOG",
".",
"info",
"(",
"'Found Instance Profile attached to Role: %s -> %s'",
",",
"profile_name",
",",
"role_name",
")",
"break",
"else",
":",
"for",
"remove_profile",
"in",
"current_instance_profiles",
":",
"resource_action",
"(",
"client",
",",
"action",
"=",
"'remove_role_from_instance_profile'",
",",
"log_format",
"=",
"'Removed Instance Profile from Role: '",
"'%(InstanceProfileName)s -> %(RoleName)s'",
",",
"InstanceProfileName",
"=",
"remove_profile",
"[",
"'InstanceProfileName'",
"]",
",",
"RoleName",
"=",
"role_name",
")",
"resource_action",
"(",
"client",
",",
"action",
"=",
"'add_role_to_instance_profile'",
",",
"log_format",
"=",
"'Added Instance Profile to Role: '",
"'%(InstanceProfileName)s -> %(RoleName)s'",
",",
"InstanceProfileName",
"=",
"profile_name",
",",
"RoleName",
"=",
"role_name",
")",
"return",
"True"
] |
Attach an IAM Instance Profile _profile_name_ to Role _role_name_.
Args:
role_name (str): Name of Role.
profile_name (str): Name of Instance Profile.
Returns:
True upon successful completion.
|
[
"Attach",
"an",
"IAM",
"Instance",
"Profile",
"_profile_name_",
"to",
"Role",
"_role_name_",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/iam/create_iam.py#L90-L128
|
train
|
foremast/foremast
|
src/foremast/utils/elb.py
|
find_elb
|
def find_elb(name='', env='', region=''):
"""Get an application's AWS elb dns name.
Args:
name (str): ELB name
env (str): Environment/account of ELB
region (str): AWS Region
Returns:
str: elb DNS record
"""
LOG.info('Find %s ELB in %s [%s].', name, env, region)
url = '{0}/applications/{1}/loadBalancers'.format(API_URL, name)
response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
assert response.ok
elb_dns = None
accounts = response.json()
for account in accounts:
if account['account'] == env and account['region'] == region:
elb_dns = account['dnsname']
break
else:
raise SpinnakerElbNotFound('Elb for "{0}" in region {1} not found'.format(name, region))
LOG.info('Found: %s', elb_dns)
return elb_dns
|
python
|
def find_elb(name='', env='', region=''):
"""Get an application's AWS elb dns name.
Args:
name (str): ELB name
env (str): Environment/account of ELB
region (str): AWS Region
Returns:
str: elb DNS record
"""
LOG.info('Find %s ELB in %s [%s].', name, env, region)
url = '{0}/applications/{1}/loadBalancers'.format(API_URL, name)
response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
assert response.ok
elb_dns = None
accounts = response.json()
for account in accounts:
if account['account'] == env and account['region'] == region:
elb_dns = account['dnsname']
break
else:
raise SpinnakerElbNotFound('Elb for "{0}" in region {1} not found'.format(name, region))
LOG.info('Found: %s', elb_dns)
return elb_dns
|
[
"def",
"find_elb",
"(",
"name",
"=",
"''",
",",
"env",
"=",
"''",
",",
"region",
"=",
"''",
")",
":",
"LOG",
".",
"info",
"(",
"'Find %s ELB in %s [%s].'",
",",
"name",
",",
"env",
",",
"region",
")",
"url",
"=",
"'{0}/applications/{1}/loadBalancers'",
".",
"format",
"(",
"API_URL",
",",
"name",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"verify",
"=",
"GATE_CA_BUNDLE",
",",
"cert",
"=",
"GATE_CLIENT_CERT",
")",
"assert",
"response",
".",
"ok",
"elb_dns",
"=",
"None",
"accounts",
"=",
"response",
".",
"json",
"(",
")",
"for",
"account",
"in",
"accounts",
":",
"if",
"account",
"[",
"'account'",
"]",
"==",
"env",
"and",
"account",
"[",
"'region'",
"]",
"==",
"region",
":",
"elb_dns",
"=",
"account",
"[",
"'dnsname'",
"]",
"break",
"else",
":",
"raise",
"SpinnakerElbNotFound",
"(",
"'Elb for \"{0}\" in region {1} not found'",
".",
"format",
"(",
"name",
",",
"region",
")",
")",
"LOG",
".",
"info",
"(",
"'Found: %s'",
",",
"elb_dns",
")",
"return",
"elb_dns"
] |
Get an application's AWS elb dns name.
Args:
name (str): ELB name
env (str): Environment/account of ELB
region (str): AWS Region
Returns:
str: elb DNS record
|
[
"Get",
"an",
"application",
"s",
"AWS",
"elb",
"dns",
"name",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/elb.py#L30-L58
|
train
|
foremast/foremast
|
src/foremast/utils/elb.py
|
find_elb_dns_zone_id
|
def find_elb_dns_zone_id(name='', env='dev', region='us-east-1'):
"""Get an application's AWS elb dns zone id.
Args:
name (str): ELB name
env (str): Environment/account of ELB
region (str): AWS Region
Returns:
str: elb DNS zone ID
"""
LOG.info('Find %s ELB DNS Zone ID in %s [%s].', name, env, region)
client = boto3.Session(profile_name=env).client('elb', region_name=region)
elbs = client.describe_load_balancers(LoadBalancerNames=[name])
return elbs['LoadBalancerDescriptions'][0]['CanonicalHostedZoneNameID']
|
python
|
def find_elb_dns_zone_id(name='', env='dev', region='us-east-1'):
"""Get an application's AWS elb dns zone id.
Args:
name (str): ELB name
env (str): Environment/account of ELB
region (str): AWS Region
Returns:
str: elb DNS zone ID
"""
LOG.info('Find %s ELB DNS Zone ID in %s [%s].', name, env, region)
client = boto3.Session(profile_name=env).client('elb', region_name=region)
elbs = client.describe_load_balancers(LoadBalancerNames=[name])
return elbs['LoadBalancerDescriptions'][0]['CanonicalHostedZoneNameID']
|
[
"def",
"find_elb_dns_zone_id",
"(",
"name",
"=",
"''",
",",
"env",
"=",
"'dev'",
",",
"region",
"=",
"'us-east-1'",
")",
":",
"LOG",
".",
"info",
"(",
"'Find %s ELB DNS Zone ID in %s [%s].'",
",",
"name",
",",
"env",
",",
"region",
")",
"client",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
")",
".",
"client",
"(",
"'elb'",
",",
"region_name",
"=",
"region",
")",
"elbs",
"=",
"client",
".",
"describe_load_balancers",
"(",
"LoadBalancerNames",
"=",
"[",
"name",
"]",
")",
"return",
"elbs",
"[",
"'LoadBalancerDescriptions'",
"]",
"[",
"0",
"]",
"[",
"'CanonicalHostedZoneNameID'",
"]"
] |
Get an application's AWS elb dns zone id.
Args:
name (str): ELB name
env (str): Environment/account of ELB
region (str): AWS Region
Returns:
str: elb DNS zone ID
|
[
"Get",
"an",
"application",
"s",
"AWS",
"elb",
"dns",
"zone",
"id",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/elb.py#L61-L76
|
train
|
foremast/foremast
|
src/foremast/version.py
|
get_version
|
def get_version():
"""Retrieve package version."""
version = 'Not installed.'
try:
version = pkg_resources.get_distribution(__package__).version
except pkg_resources.DistributionNotFound:
pass
return version
|
python
|
def get_version():
"""Retrieve package version."""
version = 'Not installed.'
try:
version = pkg_resources.get_distribution(__package__).version
except pkg_resources.DistributionNotFound:
pass
return version
|
[
"def",
"get_version",
"(",
")",
":",
"version",
"=",
"'Not installed.'",
"try",
":",
"version",
"=",
"pkg_resources",
".",
"get_distribution",
"(",
"__package__",
")",
".",
"version",
"except",
"pkg_resources",
".",
"DistributionNotFound",
":",
"pass",
"return",
"version"
] |
Retrieve package version.
|
[
"Retrieve",
"package",
"version",
"."
] |
fb70f29b8ce532f061685a17d120486e47b215ba
|
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/version.py#L5-L14
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.loop
|
async def loop(self):
"""
Return bot's main loop as coroutine. Use with asyncio.
:Example:
>>> loop = asyncio.get_event_loop()
>>> loop.run_until_complete(bot.loop())
or
>>> loop = asyncio.get_event_loop()
>>> loop.create_task(bot.loop())
"""
self._running = True
while self._running:
updates = await self.api_call(
"getUpdates", offset=self._offset + 1, timeout=self.api_timeout
)
self._process_updates(updates)
|
python
|
async def loop(self):
"""
Return bot's main loop as coroutine. Use with asyncio.
:Example:
>>> loop = asyncio.get_event_loop()
>>> loop.run_until_complete(bot.loop())
or
>>> loop = asyncio.get_event_loop()
>>> loop.create_task(bot.loop())
"""
self._running = True
while self._running:
updates = await self.api_call(
"getUpdates", offset=self._offset + 1, timeout=self.api_timeout
)
self._process_updates(updates)
|
[
"async",
"def",
"loop",
"(",
"self",
")",
":",
"self",
".",
"_running",
"=",
"True",
"while",
"self",
".",
"_running",
":",
"updates",
"=",
"await",
"self",
".",
"api_call",
"(",
"\"getUpdates\"",
",",
"offset",
"=",
"self",
".",
"_offset",
"+",
"1",
",",
"timeout",
"=",
"self",
".",
"api_timeout",
")",
"self",
".",
"_process_updates",
"(",
"updates",
")"
] |
Return bot's main loop as coroutine. Use with asyncio.
:Example:
>>> loop = asyncio.get_event_loop()
>>> loop.run_until_complete(bot.loop())
or
>>> loop = asyncio.get_event_loop()
>>> loop.create_task(bot.loop())
|
[
"Return",
"bot",
"s",
"main",
"loop",
"as",
"coroutine",
".",
"Use",
"with",
"asyncio",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L134-L153
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.run
|
def run(self, debug=False, reload=None):
"""
Convenience method for running bots in getUpdates mode
:param bool debug: Enable debug logging and automatic reloading
:param bool reload: Automatically reload bot on code change
:Example:
>>> if __name__ == '__main__':
>>> bot.run()
"""
loop = asyncio.get_event_loop()
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
if reload is None:
reload = debug
bot_loop = asyncio.ensure_future(self.loop())
try:
if reload:
loop.run_until_complete(run_with_reloader(loop, bot_loop, self.stop))
else:
loop.run_until_complete(bot_loop)
# User cancels
except KeyboardInterrupt:
logger.debug("User cancelled")
bot_loop.cancel()
self.stop()
# Stop loop
finally:
if AIOHTTP_23:
loop.run_until_complete(self.session.close())
logger.debug("Closing loop")
loop.stop()
loop.close()
|
python
|
def run(self, debug=False, reload=None):
"""
Convenience method for running bots in getUpdates mode
:param bool debug: Enable debug logging and automatic reloading
:param bool reload: Automatically reload bot on code change
:Example:
>>> if __name__ == '__main__':
>>> bot.run()
"""
loop = asyncio.get_event_loop()
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
if reload is None:
reload = debug
bot_loop = asyncio.ensure_future(self.loop())
try:
if reload:
loop.run_until_complete(run_with_reloader(loop, bot_loop, self.stop))
else:
loop.run_until_complete(bot_loop)
# User cancels
except KeyboardInterrupt:
logger.debug("User cancelled")
bot_loop.cancel()
self.stop()
# Stop loop
finally:
if AIOHTTP_23:
loop.run_until_complete(self.session.close())
logger.debug("Closing loop")
loop.stop()
loop.close()
|
[
"def",
"run",
"(",
"self",
",",
"debug",
"=",
"False",
",",
"reload",
"=",
"None",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"debug",
"else",
"logging",
".",
"INFO",
")",
"if",
"reload",
"is",
"None",
":",
"reload",
"=",
"debug",
"bot_loop",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"loop",
"(",
")",
")",
"try",
":",
"if",
"reload",
":",
"loop",
".",
"run_until_complete",
"(",
"run_with_reloader",
"(",
"loop",
",",
"bot_loop",
",",
"self",
".",
"stop",
")",
")",
"else",
":",
"loop",
".",
"run_until_complete",
"(",
"bot_loop",
")",
"# User cancels",
"except",
"KeyboardInterrupt",
":",
"logger",
".",
"debug",
"(",
"\"User cancelled\"",
")",
"bot_loop",
".",
"cancel",
"(",
")",
"self",
".",
"stop",
"(",
")",
"# Stop loop",
"finally",
":",
"if",
"AIOHTTP_23",
":",
"loop",
".",
"run_until_complete",
"(",
"self",
".",
"session",
".",
"close",
"(",
")",
")",
"logger",
".",
"debug",
"(",
"\"Closing loop\"",
")",
"loop",
".",
"stop",
"(",
")",
"loop",
".",
"close",
"(",
")"
] |
Convenience method for running bots in getUpdates mode
:param bool debug: Enable debug logging and automatic reloading
:param bool reload: Automatically reload bot on code change
:Example:
>>> if __name__ == '__main__':
>>> bot.run()
|
[
"Convenience",
"method",
"for",
"running",
"bots",
"in",
"getUpdates",
"mode"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L155-L196
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.run_webhook
|
def run_webhook(self, webhook_url, **options):
"""
Convenience method for running bots in webhook mode
:Example:
>>> if __name__ == '__main__':
>>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken")
Additional documentation on https://core.telegram.org/bots/api#setwebhook
"""
loop = asyncio.get_event_loop()
loop.run_until_complete(self.set_webhook(webhook_url, **options))
if webhook_url:
url = urlparse(webhook_url)
app = self.create_webhook_app(url.path, loop)
host = os.environ.get("HOST", "0.0.0.0")
port = int(os.environ.get("PORT", 0)) or url.port
if AIOHTTP_23:
app.on_cleanup.append(lambda _: self.session.close())
web.run_app(app, host=host, port=port)
else:
loop.run_until_complete(self.session.close())
|
python
|
def run_webhook(self, webhook_url, **options):
"""
Convenience method for running bots in webhook mode
:Example:
>>> if __name__ == '__main__':
>>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken")
Additional documentation on https://core.telegram.org/bots/api#setwebhook
"""
loop = asyncio.get_event_loop()
loop.run_until_complete(self.set_webhook(webhook_url, **options))
if webhook_url:
url = urlparse(webhook_url)
app = self.create_webhook_app(url.path, loop)
host = os.environ.get("HOST", "0.0.0.0")
port = int(os.environ.get("PORT", 0)) or url.port
if AIOHTTP_23:
app.on_cleanup.append(lambda _: self.session.close())
web.run_app(app, host=host, port=port)
else:
loop.run_until_complete(self.session.close())
|
[
"def",
"run_webhook",
"(",
"self",
",",
"webhook_url",
",",
"*",
"*",
"options",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"loop",
".",
"run_until_complete",
"(",
"self",
".",
"set_webhook",
"(",
"webhook_url",
",",
"*",
"*",
"options",
")",
")",
"if",
"webhook_url",
":",
"url",
"=",
"urlparse",
"(",
"webhook_url",
")",
"app",
"=",
"self",
".",
"create_webhook_app",
"(",
"url",
".",
"path",
",",
"loop",
")",
"host",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"HOST\"",
",",
"\"0.0.0.0\"",
")",
"port",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"PORT\"",
",",
"0",
")",
")",
"or",
"url",
".",
"port",
"if",
"AIOHTTP_23",
":",
"app",
".",
"on_cleanup",
".",
"append",
"(",
"lambda",
"_",
":",
"self",
".",
"session",
".",
"close",
"(",
")",
")",
"web",
".",
"run_app",
"(",
"app",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
")",
"else",
":",
"loop",
".",
"run_until_complete",
"(",
"self",
".",
"session",
".",
"close",
"(",
")",
")"
] |
Convenience method for running bots in webhook mode
:Example:
>>> if __name__ == '__main__':
>>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken")
Additional documentation on https://core.telegram.org/bots/api#setwebhook
|
[
"Convenience",
"method",
"for",
"running",
"bots",
"in",
"webhook",
"mode"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L198-L222
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.command
|
def command(self, regexp):
"""
Register a new command
:param str regexp: Regular expression matching the command to register
:Example:
>>> @bot.command(r"/echo (.+)")
>>> def echo(chat, match):
>>> return chat.reply(match.group(1))
"""
def decorator(fn):
self.add_command(regexp, fn)
return fn
return decorator
|
python
|
def command(self, regexp):
"""
Register a new command
:param str regexp: Regular expression matching the command to register
:Example:
>>> @bot.command(r"/echo (.+)")
>>> def echo(chat, match):
>>> return chat.reply(match.group(1))
"""
def decorator(fn):
self.add_command(regexp, fn)
return fn
return decorator
|
[
"def",
"command",
"(",
"self",
",",
"regexp",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"self",
".",
"add_command",
"(",
"regexp",
",",
"fn",
")",
"return",
"fn",
"return",
"decorator"
] |
Register a new command
:param str regexp: Regular expression matching the command to register
:Example:
>>> @bot.command(r"/echo (.+)")
>>> def echo(chat, match):
>>> return chat.reply(match.group(1))
|
[
"Register",
"a",
"new",
"command"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L236-L253
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.inline
|
def inline(self, callback):
"""
Set callback for inline queries
:Example:
>>> @bot.inline
>>> def echo(iq):
>>> return iq.answer([
>>> {"type": "text", "title": "test", "id": "0"}
>>> ])
>>> @bot.inline(r"myinline-(.+)")
>>> def echo(chat, iq, match):
>>> return iq.answer([
>>> {"type": "text", "title": "test", "id": "0"}
>>> ])
"""
if callable(callback):
self._default_inline = callback
return callback
elif isinstance(callback, str):
def decorator(fn):
self.add_inline(callback, fn)
return fn
return decorator
else:
raise TypeError("str expected {} given".format(type(callback)))
|
python
|
def inline(self, callback):
"""
Set callback for inline queries
:Example:
>>> @bot.inline
>>> def echo(iq):
>>> return iq.answer([
>>> {"type": "text", "title": "test", "id": "0"}
>>> ])
>>> @bot.inline(r"myinline-(.+)")
>>> def echo(chat, iq, match):
>>> return iq.answer([
>>> {"type": "text", "title": "test", "id": "0"}
>>> ])
"""
if callable(callback):
self._default_inline = callback
return callback
elif isinstance(callback, str):
def decorator(fn):
self.add_inline(callback, fn)
return fn
return decorator
else:
raise TypeError("str expected {} given".format(type(callback)))
|
[
"def",
"inline",
"(",
"self",
",",
"callback",
")",
":",
"if",
"callable",
"(",
"callback",
")",
":",
"self",
".",
"_default_inline",
"=",
"callback",
"return",
"callback",
"elif",
"isinstance",
"(",
"callback",
",",
"str",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"self",
".",
"add_inline",
"(",
"callback",
",",
"fn",
")",
"return",
"fn",
"return",
"decorator",
"else",
":",
"raise",
"TypeError",
"(",
"\"str expected {} given\"",
".",
"format",
"(",
"type",
"(",
"callback",
")",
")",
")"
] |
Set callback for inline queries
:Example:
>>> @bot.inline
>>> def echo(iq):
>>> return iq.answer([
>>> {"type": "text", "title": "test", "id": "0"}
>>> ])
>>> @bot.inline(r"myinline-(.+)")
>>> def echo(chat, iq, match):
>>> return iq.answer([
>>> {"type": "text", "title": "test", "id": "0"}
>>> ])
|
[
"Set",
"callback",
"for",
"inline",
"queries"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L276-L305
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.callback
|
def callback(self, callback):
"""
Set callback for callback queries
:Example:
>>> @bot.callback
>>> def echo(chat, cq):
>>> return cq.answer()
>>> @bot.callback(r"buttonclick-(.+)")
>>> def echo(chat, cq, match):
>>> return chat.reply(match.group(1))
"""
if callable(callback):
self._default_callback = callback
return callback
elif isinstance(callback, str):
def decorator(fn):
self.add_callback(callback, fn)
return fn
return decorator
else:
raise TypeError("str expected {} given".format(type(callback)))
|
python
|
def callback(self, callback):
"""
Set callback for callback queries
:Example:
>>> @bot.callback
>>> def echo(chat, cq):
>>> return cq.answer()
>>> @bot.callback(r"buttonclick-(.+)")
>>> def echo(chat, cq, match):
>>> return chat.reply(match.group(1))
"""
if callable(callback):
self._default_callback = callback
return callback
elif isinstance(callback, str):
def decorator(fn):
self.add_callback(callback, fn)
return fn
return decorator
else:
raise TypeError("str expected {} given".format(type(callback)))
|
[
"def",
"callback",
"(",
"self",
",",
"callback",
")",
":",
"if",
"callable",
"(",
"callback",
")",
":",
"self",
".",
"_default_callback",
"=",
"callback",
"return",
"callback",
"elif",
"isinstance",
"(",
"callback",
",",
"str",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"self",
".",
"add_callback",
"(",
"callback",
",",
"fn",
")",
"return",
"fn",
"return",
"decorator",
"else",
":",
"raise",
"TypeError",
"(",
"\"str expected {} given\"",
".",
"format",
"(",
"type",
"(",
"callback",
")",
")",
")"
] |
Set callback for callback queries
:Example:
>>> @bot.callback
>>> def echo(chat, cq):
>>> return cq.answer()
>>> @bot.callback(r"buttonclick-(.+)")
>>> def echo(chat, cq, match):
>>> return chat.reply(match.group(1))
|
[
"Set",
"callback",
"for",
"callback",
"queries"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L313-L338
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.handle
|
def handle(self, msg_type):
"""
Set handler for specific message type
:Example:
>>> @bot.handle("audio")
>>> def handle(chat, audio):
>>> pass
"""
def wrap(callback):
self._handlers[msg_type] = callback
return callback
return wrap
|
python
|
def handle(self, msg_type):
"""
Set handler for specific message type
:Example:
>>> @bot.handle("audio")
>>> def handle(chat, audio):
>>> pass
"""
def wrap(callback):
self._handlers[msg_type] = callback
return callback
return wrap
|
[
"def",
"handle",
"(",
"self",
",",
"msg_type",
")",
":",
"def",
"wrap",
"(",
"callback",
")",
":",
"self",
".",
"_handlers",
"[",
"msg_type",
"]",
"=",
"callback",
"return",
"callback",
"return",
"wrap"
] |
Set handler for specific message type
:Example:
>>> @bot.handle("audio")
>>> def handle(chat, audio):
>>> pass
|
[
"Set",
"handler",
"for",
"specific",
"message",
"type"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L359-L374
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.api_call
|
def api_call(self, method, **params):
"""
Call Telegram API.
See https://core.telegram.org/bots/api for reference.
:param str method: Telegram API method
:param params: Arguments for the method call
"""
coro = self._api_call(method, **params)
# Explicitly ensure that API call is executed
return asyncio.ensure_future(coro)
|
python
|
def api_call(self, method, **params):
"""
Call Telegram API.
See https://core.telegram.org/bots/api for reference.
:param str method: Telegram API method
:param params: Arguments for the method call
"""
coro = self._api_call(method, **params)
# Explicitly ensure that API call is executed
return asyncio.ensure_future(coro)
|
[
"def",
"api_call",
"(",
"self",
",",
"method",
",",
"*",
"*",
"params",
")",
":",
"coro",
"=",
"self",
".",
"_api_call",
"(",
"method",
",",
"*",
"*",
"params",
")",
"# Explicitly ensure that API call is executed",
"return",
"asyncio",
".",
"ensure_future",
"(",
"coro",
")"
] |
Call Telegram API.
See https://core.telegram.org/bots/api for reference.
:param str method: Telegram API method
:param params: Arguments for the method call
|
[
"Call",
"Telegram",
"API",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L400-L411
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.send_message
|
def send_message(self, chat_id, text, **options):
"""
Send a text message to chat
:param int chat_id: ID of the chat to send the message to
:param str text: Text to send
:param options: Additional sendMessage options
(see https://core.telegram.org/bots/api#sendmessage)
"""
return self.api_call("sendMessage", chat_id=chat_id, text=text, **options)
|
python
|
def send_message(self, chat_id, text, **options):
"""
Send a text message to chat
:param int chat_id: ID of the chat to send the message to
:param str text: Text to send
:param options: Additional sendMessage options
(see https://core.telegram.org/bots/api#sendmessage)
"""
return self.api_call("sendMessage", chat_id=chat_id, text=text, **options)
|
[
"def",
"send_message",
"(",
"self",
",",
"chat_id",
",",
"text",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"api_call",
"(",
"\"sendMessage\"",
",",
"chat_id",
"=",
"chat_id",
",",
"text",
"=",
"text",
",",
"*",
"*",
"options",
")"
] |
Send a text message to chat
:param int chat_id: ID of the chat to send the message to
:param str text: Text to send
:param options: Additional sendMessage options
(see https://core.telegram.org/bots/api#sendmessage)
|
[
"Send",
"a",
"text",
"message",
"to",
"chat"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L461-L470
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.edit_message_text
|
def edit_message_text(self, chat_id, message_id, text, **options):
"""
Edit a text message in a chat
:param int chat_id: ID of the chat the message to edit is in
:param int message_id: ID of the message to edit
:param str text: Text to edit the message to
:param options: Additional API options
"""
return self.api_call(
"editMessageText",
chat_id=chat_id,
message_id=message_id,
text=text,
**options
)
|
python
|
def edit_message_text(self, chat_id, message_id, text, **options):
"""
Edit a text message in a chat
:param int chat_id: ID of the chat the message to edit is in
:param int message_id: ID of the message to edit
:param str text: Text to edit the message to
:param options: Additional API options
"""
return self.api_call(
"editMessageText",
chat_id=chat_id,
message_id=message_id,
text=text,
**options
)
|
[
"def",
"edit_message_text",
"(",
"self",
",",
"chat_id",
",",
"message_id",
",",
"text",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"api_call",
"(",
"\"editMessageText\"",
",",
"chat_id",
"=",
"chat_id",
",",
"message_id",
"=",
"message_id",
",",
"text",
"=",
"text",
",",
"*",
"*",
"options",
")"
] |
Edit a text message in a chat
:param int chat_id: ID of the chat the message to edit is in
:param int message_id: ID of the message to edit
:param str text: Text to edit the message to
:param options: Additional API options
|
[
"Edit",
"a",
"text",
"message",
"in",
"a",
"chat"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L472-L487
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.edit_message_reply_markup
|
def edit_message_reply_markup(self, chat_id, message_id, reply_markup, **options):
"""
Edit a reply markup of message in a chat
:param int chat_id: ID of the chat the message to edit is in
:param int message_id: ID of the message to edit
:param str reply_markup: New inline keyboard markup for the message
:param options: Additional API options
"""
return self.api_call(
"editMessageReplyMarkup",
chat_id=chat_id,
message_id=message_id,
reply_markup=reply_markup,
**options
)
|
python
|
def edit_message_reply_markup(self, chat_id, message_id, reply_markup, **options):
"""
Edit a reply markup of message in a chat
:param int chat_id: ID of the chat the message to edit is in
:param int message_id: ID of the message to edit
:param str reply_markup: New inline keyboard markup for the message
:param options: Additional API options
"""
return self.api_call(
"editMessageReplyMarkup",
chat_id=chat_id,
message_id=message_id,
reply_markup=reply_markup,
**options
)
|
[
"def",
"edit_message_reply_markup",
"(",
"self",
",",
"chat_id",
",",
"message_id",
",",
"reply_markup",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"api_call",
"(",
"\"editMessageReplyMarkup\"",
",",
"chat_id",
"=",
"chat_id",
",",
"message_id",
"=",
"message_id",
",",
"reply_markup",
"=",
"reply_markup",
",",
"*",
"*",
"options",
")"
] |
Edit a reply markup of message in a chat
:param int chat_id: ID of the chat the message to edit is in
:param int message_id: ID of the message to edit
:param str reply_markup: New inline keyboard markup for the message
:param options: Additional API options
|
[
"Edit",
"a",
"reply",
"markup",
"of",
"message",
"in",
"a",
"chat"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L489-L504
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.download_file
|
def download_file(self, file_path, range=None):
"""
Download a file from Telegram servers
"""
headers = {"range": range} if range else None
url = "{0}/file/bot{1}/{2}".format(API_URL, self.api_token, file_path)
return self.session.get(
url, headers=headers, proxy=self.proxy, proxy_auth=self.proxy_auth
)
|
python
|
def download_file(self, file_path, range=None):
"""
Download a file from Telegram servers
"""
headers = {"range": range} if range else None
url = "{0}/file/bot{1}/{2}".format(API_URL, self.api_token, file_path)
return self.session.get(
url, headers=headers, proxy=self.proxy, proxy_auth=self.proxy_auth
)
|
[
"def",
"download_file",
"(",
"self",
",",
"file_path",
",",
"range",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"\"range\"",
":",
"range",
"}",
"if",
"range",
"else",
"None",
"url",
"=",
"\"{0}/file/bot{1}/{2}\"",
".",
"format",
"(",
"API_URL",
",",
"self",
".",
"api_token",
",",
"file_path",
")",
"return",
"self",
".",
"session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"proxy",
"=",
"self",
".",
"proxy",
",",
"proxy_auth",
"=",
"self",
".",
"proxy_auth",
")"
] |
Download a file from Telegram servers
|
[
"Download",
"a",
"file",
"from",
"Telegram",
"servers"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L516-L524
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.get_user_profile_photos
|
def get_user_profile_photos(self, user_id, **options):
"""
Get a list of profile pictures for a user
:param int user_id: Unique identifier of the target user
:param options: Additional getUserProfilePhotos options (see
https://core.telegram.org/bots/api#getuserprofilephotos)
"""
return self.api_call("getUserProfilePhotos", user_id=str(user_id), **options)
|
python
|
def get_user_profile_photos(self, user_id, **options):
"""
Get a list of profile pictures for a user
:param int user_id: Unique identifier of the target user
:param options: Additional getUserProfilePhotos options (see
https://core.telegram.org/bots/api#getuserprofilephotos)
"""
return self.api_call("getUserProfilePhotos", user_id=str(user_id), **options)
|
[
"def",
"get_user_profile_photos",
"(",
"self",
",",
"user_id",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"api_call",
"(",
"\"getUserProfilePhotos\"",
",",
"user_id",
"=",
"str",
"(",
"user_id",
")",
",",
"*",
"*",
"options",
")"
] |
Get a list of profile pictures for a user
:param int user_id: Unique identifier of the target user
:param options: Additional getUserProfilePhotos options (see
https://core.telegram.org/bots/api#getuserprofilephotos)
|
[
"Get",
"a",
"list",
"of",
"profile",
"pictures",
"for",
"a",
"user"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L526-L534
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.webhook_handle
|
async def webhook_handle(self, request):
"""
aiohttp.web handle for processing web hooks
:Example:
>>> from aiohttp import web
>>> app = web.Application()
>>> app.router.add_route('/webhook')
"""
update = await request.json(loads=self.json_deserialize)
self._process_update(update)
return web.Response()
|
python
|
async def webhook_handle(self, request):
"""
aiohttp.web handle for processing web hooks
:Example:
>>> from aiohttp import web
>>> app = web.Application()
>>> app.router.add_route('/webhook')
"""
update = await request.json(loads=self.json_deserialize)
self._process_update(update)
return web.Response()
|
[
"async",
"def",
"webhook_handle",
"(",
"self",
",",
"request",
")",
":",
"update",
"=",
"await",
"request",
".",
"json",
"(",
"loads",
"=",
"self",
".",
"json_deserialize",
")",
"self",
".",
"_process_update",
"(",
"update",
")",
"return",
"web",
".",
"Response",
"(",
")"
] |
aiohttp.web handle for processing web hooks
:Example:
>>> from aiohttp import web
>>> app = web.Application()
>>> app.router.add_route('/webhook')
|
[
"aiohttp",
".",
"web",
"handle",
"for",
"processing",
"web",
"hooks"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L547-L559
|
train
|
szastupov/aiotg
|
aiotg/bot.py
|
Bot.create_webhook_app
|
def create_webhook_app(self, path, loop=None):
"""
Shorthand for creating aiohttp.web.Application with registered webhook hanlde
"""
app = web.Application(loop=loop)
app.router.add_route("POST", path, self.webhook_handle)
return app
|
python
|
def create_webhook_app(self, path, loop=None):
"""
Shorthand for creating aiohttp.web.Application with registered webhook hanlde
"""
app = web.Application(loop=loop)
app.router.add_route("POST", path, self.webhook_handle)
return app
|
[
"def",
"create_webhook_app",
"(",
"self",
",",
"path",
",",
"loop",
"=",
"None",
")",
":",
"app",
"=",
"web",
".",
"Application",
"(",
"loop",
"=",
"loop",
")",
"app",
".",
"router",
".",
"add_route",
"(",
"\"POST\"",
",",
"path",
",",
"self",
".",
"webhook_handle",
")",
"return",
"app"
] |
Shorthand for creating aiohttp.web.Application with registered webhook hanlde
|
[
"Shorthand",
"for",
"creating",
"aiohttp",
".",
"web",
".",
"Application",
"with",
"registered",
"webhook",
"hanlde"
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L561-L567
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.send_text
|
def send_text(self, text, **options):
"""
Send a text message to the chat.
:param str text: Text of the message to send
:param options: Additional sendMessage options (see
https://core.telegram.org/bots/api#sendmessage
"""
return self.bot.send_message(self.id, text, **options)
|
python
|
def send_text(self, text, **options):
"""
Send a text message to the chat.
:param str text: Text of the message to send
:param options: Additional sendMessage options (see
https://core.telegram.org/bots/api#sendmessage
"""
return self.bot.send_message(self.id, text, **options)
|
[
"def",
"send_text",
"(",
"self",
",",
"text",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"bot",
".",
"send_message",
"(",
"self",
".",
"id",
",",
"text",
",",
"*",
"*",
"options",
")"
] |
Send a text message to the chat.
:param str text: Text of the message to send
:param options: Additional sendMessage options (see
https://core.telegram.org/bots/api#sendmessage
|
[
"Send",
"a",
"text",
"message",
"to",
"the",
"chat",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L11-L19
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.reply
|
def reply(self, text, markup=None, parse_mode=None):
"""
Reply to the message this `Chat` object is based on.
:param str text: Text of the message to send
:param dict markup: Markup options
:param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or
``None``)
"""
if markup is None:
markup = {}
return self.send_text(
text,
reply_to_message_id=self.message["message_id"],
disable_web_page_preview="true",
reply_markup=self.bot.json_serialize(markup),
parse_mode=parse_mode,
)
|
python
|
def reply(self, text, markup=None, parse_mode=None):
"""
Reply to the message this `Chat` object is based on.
:param str text: Text of the message to send
:param dict markup: Markup options
:param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or
``None``)
"""
if markup is None:
markup = {}
return self.send_text(
text,
reply_to_message_id=self.message["message_id"],
disable_web_page_preview="true",
reply_markup=self.bot.json_serialize(markup),
parse_mode=parse_mode,
)
|
[
"def",
"reply",
"(",
"self",
",",
"text",
",",
"markup",
"=",
"None",
",",
"parse_mode",
"=",
"None",
")",
":",
"if",
"markup",
"is",
"None",
":",
"markup",
"=",
"{",
"}",
"return",
"self",
".",
"send_text",
"(",
"text",
",",
"reply_to_message_id",
"=",
"self",
".",
"message",
"[",
"\"message_id\"",
"]",
",",
"disable_web_page_preview",
"=",
"\"true\"",
",",
"reply_markup",
"=",
"self",
".",
"bot",
".",
"json_serialize",
"(",
"markup",
")",
",",
"parse_mode",
"=",
"parse_mode",
",",
")"
] |
Reply to the message this `Chat` object is based on.
:param str text: Text of the message to send
:param dict markup: Markup options
:param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or
``None``)
|
[
"Reply",
"to",
"the",
"message",
"this",
"Chat",
"object",
"is",
"based",
"on",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L21-L39
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.edit_text
|
def edit_text(self, message_id, text, markup=None, parse_mode=None):
"""
Edit the message in this chat.
:param int message_id: ID of the message to edit
:param str text: Text to edit the message to
:param dict markup: Markup options
:param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or
``None``)
"""
if markup is None:
markup = {}
return self.bot.edit_message_text(
self.id,
message_id,
text,
reply_markup=self.bot.json_serialize(markup),
parse_mode=parse_mode,
)
|
python
|
def edit_text(self, message_id, text, markup=None, parse_mode=None):
"""
Edit the message in this chat.
:param int message_id: ID of the message to edit
:param str text: Text to edit the message to
:param dict markup: Markup options
:param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or
``None``)
"""
if markup is None:
markup = {}
return self.bot.edit_message_text(
self.id,
message_id,
text,
reply_markup=self.bot.json_serialize(markup),
parse_mode=parse_mode,
)
|
[
"def",
"edit_text",
"(",
"self",
",",
"message_id",
",",
"text",
",",
"markup",
"=",
"None",
",",
"parse_mode",
"=",
"None",
")",
":",
"if",
"markup",
"is",
"None",
":",
"markup",
"=",
"{",
"}",
"return",
"self",
".",
"bot",
".",
"edit_message_text",
"(",
"self",
".",
"id",
",",
"message_id",
",",
"text",
",",
"reply_markup",
"=",
"self",
".",
"bot",
".",
"json_serialize",
"(",
"markup",
")",
",",
"parse_mode",
"=",
"parse_mode",
",",
")"
] |
Edit the message in this chat.
:param int message_id: ID of the message to edit
:param str text: Text to edit the message to
:param dict markup: Markup options
:param str parse_mode: Text parsing mode (``"Markdown"``, ``"HTML"`` or
``None``)
|
[
"Edit",
"the",
"message",
"in",
"this",
"chat",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L41-L60
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.edit_reply_markup
|
def edit_reply_markup(self, message_id, markup):
"""
Edit only reply markup of the message in this chat.
:param int message_id: ID of the message to edit
:param dict markup: Markup options
"""
return self.bot.edit_message_reply_markup(
self.id, message_id, reply_markup=self.bot.json_serialize(markup)
)
|
python
|
def edit_reply_markup(self, message_id, markup):
"""
Edit only reply markup of the message in this chat.
:param int message_id: ID of the message to edit
:param dict markup: Markup options
"""
return self.bot.edit_message_reply_markup(
self.id, message_id, reply_markup=self.bot.json_serialize(markup)
)
|
[
"def",
"edit_reply_markup",
"(",
"self",
",",
"message_id",
",",
"markup",
")",
":",
"return",
"self",
".",
"bot",
".",
"edit_message_reply_markup",
"(",
"self",
".",
"id",
",",
"message_id",
",",
"reply_markup",
"=",
"self",
".",
"bot",
".",
"json_serialize",
"(",
"markup",
")",
")"
] |
Edit only reply markup of the message in this chat.
:param int message_id: ID of the message to edit
:param dict markup: Markup options
|
[
"Edit",
"only",
"reply",
"markup",
"of",
"the",
"message",
"in",
"this",
"chat",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L62-L71
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.get_chat_member
|
def get_chat_member(self, user_id):
"""
Get information about a member of a chat.
:param int user_id: Unique identifier of the target user
"""
return self.bot.api_call(
"getChatMember", chat_id=str(self.id), user_id=str(user_id)
)
|
python
|
def get_chat_member(self, user_id):
"""
Get information about a member of a chat.
:param int user_id: Unique identifier of the target user
"""
return self.bot.api_call(
"getChatMember", chat_id=str(self.id), user_id=str(user_id)
)
|
[
"def",
"get_chat_member",
"(",
"self",
",",
"user_id",
")",
":",
"return",
"self",
".",
"bot",
".",
"api_call",
"(",
"\"getChatMember\"",
",",
"chat_id",
"=",
"str",
"(",
"self",
".",
"id",
")",
",",
"user_id",
"=",
"str",
"(",
"user_id",
")",
")"
] |
Get information about a member of a chat.
:param int user_id: Unique identifier of the target user
|
[
"Get",
"information",
"about",
"a",
"member",
"of",
"a",
"chat",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L91-L99
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.send_sticker
|
def send_sticker(self, sticker, **options):
"""
Send a sticker to the chat.
:param sticker: Sticker to send (file or string)
:param options: Additional sendSticker options (see
https://core.telegram.org/bots/api#sendsticker)
"""
return self.bot.api_call(
"sendSticker", chat_id=str(self.id), sticker=sticker, **options
)
|
python
|
def send_sticker(self, sticker, **options):
"""
Send a sticker to the chat.
:param sticker: Sticker to send (file or string)
:param options: Additional sendSticker options (see
https://core.telegram.org/bots/api#sendsticker)
"""
return self.bot.api_call(
"sendSticker", chat_id=str(self.id), sticker=sticker, **options
)
|
[
"def",
"send_sticker",
"(",
"self",
",",
"sticker",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"bot",
".",
"api_call",
"(",
"\"sendSticker\"",
",",
"chat_id",
"=",
"str",
"(",
"self",
".",
"id",
")",
",",
"sticker",
"=",
"sticker",
",",
"*",
"*",
"options",
")"
] |
Send a sticker to the chat.
:param sticker: Sticker to send (file or string)
:param options: Additional sendSticker options (see
https://core.telegram.org/bots/api#sendsticker)
|
[
"Send",
"a",
"sticker",
"to",
"the",
"chat",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L101-L111
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.send_audio
|
def send_audio(self, audio, **options):
"""
Send an mp3 audio file to the chat.
:param audio: Object containing the audio data
:param options: Additional sendAudio options (see
https://core.telegram.org/bots/api#sendaudio)
:Example:
>>> with open("foo.mp3", "rb") as f:
>>> await chat.send_audio(f, performer="Foo", title="Eversong")
"""
return self.bot.api_call(
"sendAudio", chat_id=str(self.id), audio=audio, **options
)
|
python
|
def send_audio(self, audio, **options):
"""
Send an mp3 audio file to the chat.
:param audio: Object containing the audio data
:param options: Additional sendAudio options (see
https://core.telegram.org/bots/api#sendaudio)
:Example:
>>> with open("foo.mp3", "rb") as f:
>>> await chat.send_audio(f, performer="Foo", title="Eversong")
"""
return self.bot.api_call(
"sendAudio", chat_id=str(self.id), audio=audio, **options
)
|
[
"def",
"send_audio",
"(",
"self",
",",
"audio",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"bot",
".",
"api_call",
"(",
"\"sendAudio\"",
",",
"chat_id",
"=",
"str",
"(",
"self",
".",
"id",
")",
",",
"audio",
"=",
"audio",
",",
"*",
"*",
"options",
")"
] |
Send an mp3 audio file to the chat.
:param audio: Object containing the audio data
:param options: Additional sendAudio options (see
https://core.telegram.org/bots/api#sendaudio)
:Example:
>>> with open("foo.mp3", "rb") as f:
>>> await chat.send_audio(f, performer="Foo", title="Eversong")
|
[
"Send",
"an",
"mp3",
"audio",
"file",
"to",
"the",
"chat",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L113-L128
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.send_photo
|
def send_photo(self, photo, caption="", **options):
"""
Send a photo to the chat.
:param photo: Object containing the photo data
:param str caption: Photo caption (optional)
:param options: Additional sendPhoto options (see
https://core.telegram.org/bots/api#sendphoto)
:Example:
>>> with open("foo.png", "rb") as f:
>>> await chat.send_photo(f, caption="Would you look at this!")
"""
return self.bot.api_call(
"sendPhoto", chat_id=str(self.id), photo=photo, caption=caption, **options
)
|
python
|
def send_photo(self, photo, caption="", **options):
"""
Send a photo to the chat.
:param photo: Object containing the photo data
:param str caption: Photo caption (optional)
:param options: Additional sendPhoto options (see
https://core.telegram.org/bots/api#sendphoto)
:Example:
>>> with open("foo.png", "rb") as f:
>>> await chat.send_photo(f, caption="Would you look at this!")
"""
return self.bot.api_call(
"sendPhoto", chat_id=str(self.id), photo=photo, caption=caption, **options
)
|
[
"def",
"send_photo",
"(",
"self",
",",
"photo",
",",
"caption",
"=",
"\"\"",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"bot",
".",
"api_call",
"(",
"\"sendPhoto\"",
",",
"chat_id",
"=",
"str",
"(",
"self",
".",
"id",
")",
",",
"photo",
"=",
"photo",
",",
"caption",
"=",
"caption",
",",
"*",
"*",
"options",
")"
] |
Send a photo to the chat.
:param photo: Object containing the photo data
:param str caption: Photo caption (optional)
:param options: Additional sendPhoto options (see
https://core.telegram.org/bots/api#sendphoto)
:Example:
>>> with open("foo.png", "rb") as f:
>>> await chat.send_photo(f, caption="Would you look at this!")
|
[
"Send",
"a",
"photo",
"to",
"the",
"chat",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L130-L146
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.send_video
|
def send_video(self, video, caption="", **options):
"""
Send an mp4 video file to the chat.
:param video: Object containing the video data
:param str caption: Video caption (optional)
:param options: Additional sendVideo options (see
https://core.telegram.org/bots/api#sendvideo)
:Example:
>>> with open("foo.mp4", "rb") as f:
>>> await chat.send_video(f)
"""
return self.bot.api_call(
"sendVideo", chat_id=str(self.id), video=video, caption=caption, **options
)
|
python
|
def send_video(self, video, caption="", **options):
"""
Send an mp4 video file to the chat.
:param video: Object containing the video data
:param str caption: Video caption (optional)
:param options: Additional sendVideo options (see
https://core.telegram.org/bots/api#sendvideo)
:Example:
>>> with open("foo.mp4", "rb") as f:
>>> await chat.send_video(f)
"""
return self.bot.api_call(
"sendVideo", chat_id=str(self.id), video=video, caption=caption, **options
)
|
[
"def",
"send_video",
"(",
"self",
",",
"video",
",",
"caption",
"=",
"\"\"",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"bot",
".",
"api_call",
"(",
"\"sendVideo\"",
",",
"chat_id",
"=",
"str",
"(",
"self",
".",
"id",
")",
",",
"video",
"=",
"video",
",",
"caption",
"=",
"caption",
",",
"*",
"*",
"options",
")"
] |
Send an mp4 video file to the chat.
:param video: Object containing the video data
:param str caption: Video caption (optional)
:param options: Additional sendVideo options (see
https://core.telegram.org/bots/api#sendvideo)
:Example:
>>> with open("foo.mp4", "rb") as f:
>>> await chat.send_video(f)
|
[
"Send",
"an",
"mp4",
"video",
"file",
"to",
"the",
"chat",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L148-L164
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.send_document
|
def send_document(self, document, caption="", **options):
"""
Send a general file.
:param document: Object containing the document data
:param str caption: Document caption (optional)
:param options: Additional sendDocument options (see
https://core.telegram.org/bots/api#senddocument)
:Example:
>>> with open("file.doc", "rb") as f:
>>> await chat.send_document(f)
"""
return self.bot.api_call(
"sendDocument",
chat_id=str(self.id),
document=document,
caption=caption,
**options
)
|
python
|
def send_document(self, document, caption="", **options):
"""
Send a general file.
:param document: Object containing the document data
:param str caption: Document caption (optional)
:param options: Additional sendDocument options (see
https://core.telegram.org/bots/api#senddocument)
:Example:
>>> with open("file.doc", "rb") as f:
>>> await chat.send_document(f)
"""
return self.bot.api_call(
"sendDocument",
chat_id=str(self.id),
document=document,
caption=caption,
**options
)
|
[
"def",
"send_document",
"(",
"self",
",",
"document",
",",
"caption",
"=",
"\"\"",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"bot",
".",
"api_call",
"(",
"\"sendDocument\"",
",",
"chat_id",
"=",
"str",
"(",
"self",
".",
"id",
")",
",",
"document",
"=",
"document",
",",
"caption",
"=",
"caption",
",",
"*",
"*",
"options",
")"
] |
Send a general file.
:param document: Object containing the document data
:param str caption: Document caption (optional)
:param options: Additional sendDocument options (see
https://core.telegram.org/bots/api#senddocument)
:Example:
>>> with open("file.doc", "rb") as f:
>>> await chat.send_document(f)
|
[
"Send",
"a",
"general",
"file",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L166-L186
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.send_voice
|
def send_voice(self, voice, **options):
"""
Send an OPUS-encoded .ogg audio file.
:param voice: Object containing the audio data
:param options: Additional sendVoice options (see
https://core.telegram.org/bots/api#sendvoice)
:Example:
>>> with open("voice.ogg", "rb") as f:
>>> await chat.send_voice(f)
"""
return self.bot.api_call(
"sendVoice", chat_id=str(self.id), voice=voice, **options
)
|
python
|
def send_voice(self, voice, **options):
"""
Send an OPUS-encoded .ogg audio file.
:param voice: Object containing the audio data
:param options: Additional sendVoice options (see
https://core.telegram.org/bots/api#sendvoice)
:Example:
>>> with open("voice.ogg", "rb") as f:
>>> await chat.send_voice(f)
"""
return self.bot.api_call(
"sendVoice", chat_id=str(self.id), voice=voice, **options
)
|
[
"def",
"send_voice",
"(",
"self",
",",
"voice",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"bot",
".",
"api_call",
"(",
"\"sendVoice\"",
",",
"chat_id",
"=",
"str",
"(",
"self",
".",
"id",
")",
",",
"voice",
"=",
"voice",
",",
"*",
"*",
"options",
")"
] |
Send an OPUS-encoded .ogg audio file.
:param voice: Object containing the audio data
:param options: Additional sendVoice options (see
https://core.telegram.org/bots/api#sendvoice)
:Example:
>>> with open("voice.ogg", "rb") as f:
>>> await chat.send_voice(f)
|
[
"Send",
"an",
"OPUS",
"-",
"encoded",
".",
"ogg",
"audio",
"file",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L188-L203
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.send_location
|
def send_location(self, latitude, longitude, **options):
"""
Send a point on the map.
:param float latitude: Latitude of the location
:param float longitude: Longitude of the location
:param options: Additional sendLocation options (see
https://core.telegram.org/bots/api#sendlocation)
"""
return self.bot.api_call(
"sendLocation",
chat_id=self.id,
latitude=latitude,
longitude=longitude,
**options
)
|
python
|
def send_location(self, latitude, longitude, **options):
"""
Send a point on the map.
:param float latitude: Latitude of the location
:param float longitude: Longitude of the location
:param options: Additional sendLocation options (see
https://core.telegram.org/bots/api#sendlocation)
"""
return self.bot.api_call(
"sendLocation",
chat_id=self.id,
latitude=latitude,
longitude=longitude,
**options
)
|
[
"def",
"send_location",
"(",
"self",
",",
"latitude",
",",
"longitude",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"bot",
".",
"api_call",
"(",
"\"sendLocation\"",
",",
"chat_id",
"=",
"self",
".",
"id",
",",
"latitude",
"=",
"latitude",
",",
"longitude",
"=",
"longitude",
",",
"*",
"*",
"options",
")"
] |
Send a point on the map.
:param float latitude: Latitude of the location
:param float longitude: Longitude of the location
:param options: Additional sendLocation options (see
https://core.telegram.org/bots/api#sendlocation)
|
[
"Send",
"a",
"point",
"on",
"the",
"map",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L205-L220
|
train
|
szastupov/aiotg
|
aiotg/chat.py
|
Chat.send_venue
|
def send_venue(self, latitude, longitude, title, address, **options):
"""
Send information about a venue.
:param float latitude: Latitude of the location
:param float longitude: Longitude of the location
:param str title: Name of the venue
:param str address: Address of the venue
:param options: Additional sendVenue options (see
https://core.telegram.org/bots/api#sendvenue)
"""
return self.bot.api_call(
"sendVenue",
chat_id=self.id,
latitude=latitude,
longitude=longitude,
title=title,
address=address,
**options
)
|
python
|
def send_venue(self, latitude, longitude, title, address, **options):
"""
Send information about a venue.
:param float latitude: Latitude of the location
:param float longitude: Longitude of the location
:param str title: Name of the venue
:param str address: Address of the venue
:param options: Additional sendVenue options (see
https://core.telegram.org/bots/api#sendvenue)
"""
return self.bot.api_call(
"sendVenue",
chat_id=self.id,
latitude=latitude,
longitude=longitude,
title=title,
address=address,
**options
)
|
[
"def",
"send_venue",
"(",
"self",
",",
"latitude",
",",
"longitude",
",",
"title",
",",
"address",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"bot",
".",
"api_call",
"(",
"\"sendVenue\"",
",",
"chat_id",
"=",
"self",
".",
"id",
",",
"latitude",
"=",
"latitude",
",",
"longitude",
"=",
"longitude",
",",
"title",
"=",
"title",
",",
"address",
"=",
"address",
",",
"*",
"*",
"options",
")"
] |
Send information about a venue.
:param float latitude: Latitude of the location
:param float longitude: Longitude of the location
:param str title: Name of the venue
:param str address: Address of the venue
:param options: Additional sendVenue options (see
https://core.telegram.org/bots/api#sendvenue)
|
[
"Send",
"information",
"about",
"a",
"venue",
"."
] |
eed81a6a728c02120f1d730a6e8b8fe50263c010
|
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L222-L241
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.