docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Generate a filename to be used by packer.
Args:
provider (str): Name of Spinnaker provider.
region (str): Name of provider region to use.
builder (str): Name of builder process type.
Returns:
str: Generated filename based on parameters. | def generate_packer_filename(provider, region, builder):
filename = '{0}_{1}_{2}.json'.format(provider, region, builder)
return filename | 440,810 |
Retrieve template.
Args:
template_file (str): Name of template file.
Returns:
jinja2.Template: Template ready to render.
Raises:
AssertionError: Configured path for templates does not exist.
:obj:`foremast.exceptions.ForemastTemplateNotFound`: Requested template
... | def get_template_object(template_file=''):
jinja_template_paths_obj = []
if TEMPLATES_PATH:
external_templates = pathlib.Path(TEMPLATES_PATH).expanduser().resolve()
assert os.path.isdir(external_templates), 'External template path "{0}" not found'.format(external_templates)
jinja_t... | 440,814 |
Get the Jinja2 template and renders with dict _kwargs_.
Args:
template_file (str): name of the template file
kwargs: Keywords to use for rendering the Jinja2 template.
Returns:
String of rendered JSON template. | def get_template(template_file='', **kwargs):
template = get_template_object(template_file)
LOG.info('Rendering template %s', template.filename)
for key, value in kwargs.items():
LOG.debug('%s => %s', key, value)
rendered_json = template.render(**kwargs)
LOG.debug('Rendered JSON:\n%s'... | 440,815 |
Create Spinnaker Task.
Args:
task_data (str): Task JSON definition.
Returns:
str: Spinnaker Task ID.
Raises:
AssertionError: Error response from Spinnaker. | def post_task(task_data, task_uri='/tasks'):
url = '{}/{}'.format(API_URL, task_uri.lstrip('/'))
if isinstance(task_data, str):
task_json = task_data
else:
task_json = json.dumps(task_data)
resp = requests.post(url, data=task_json, headers=HEADERS, verify=GATE_CA_BUNDLE, cert=GATE... | 440,817 |
Check Spinnaker Task status.
Args:
taskid (str): Existing Spinnaker Task ID.
Returns:
str: Task status. | def _check_task(taskid):
try:
taskurl = taskid.get('ref', '0000')
except AttributeError:
taskurl = taskid
taskid = taskurl.split('/tasks/')[-1]
LOG.info('Checking taskid %s', taskid)
url = '{}/tasks/{}'.format(API_URL, taskid)
task_response = requests.get(url, headers=HEA... | 440,818 |
Wrap check_task.
Args:
taskid (str): Existing Spinnaker Task ID.
timeout (int, optional): Consider Task failed after given seconds.
wait (int, optional): Seconds to pause between polling attempts.
Returns:
str: Task status.
Raises:
AssertionError: API did not respo... | def check_task(taskid, timeout=DEFAULT_TASK_TIMEOUT, wait=2):
max_attempts = int(timeout / wait)
try:
return retry_call(
partial(_check_task, taskid),
max_attempts=max_attempts,
wait=wait,
exceptions=(AssertionError, ValueError), )
except ValueErr... | 440,819 |
Run task and check the result.
Args:
task_data (str): the task json to execute
Returns:
str: Task status. | def wait_for_task(task_data, task_uri='/tasks'):
taskid = post_task(task_data, task_uri)
if isinstance(task_data, str):
json_data = json.loads(task_data)
else:
json_data = task_data
# inspect the task to see if a timeout is configured
job = json_data['job'][0]
env = job.ge... | 440,820 |
Make sure _application.properties_ file exists in S3.
For Applications with Archaius support, there needs to be a file where the
cloud environment variable points to.
Args:
env (str): Deployment environment/account, i.e. dev, stage, prod.
app (str): GitLab Project name.
Returns:
... | def init_properties(env='dev', app='unnecessary', **_):
aws_env = boto3.session.Session(profile_name=env)
s3client = aws_env.resource('s3')
generated = get_details(app=app, env=env)
archaius = generated.archaius()
archaius_file = ('{path}/application.properties').format(path=archaius['path'])... | 440,822 |
Create cloudwatch 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 (dict): Trigger rules from the settings | def create_cloudwatch_event(app_name, env, region, rules):
session = boto3.Session(profile_name=env, region_name=region)
cloudwatch_client = session.client('events')
rule_name = rules.get('rule_name')
schedule = rules.get('schedule')
rule_description = rules.get('rule_description')
json_in... | 440,823 |
Create the specified resource.
Args:
parent_id (str): The resource ID of the parent resource in API Gateway | def create_resource(self, parent_id=""):
resource_name = self.trigger_settings.get('resource', '')
resource_name = resource_name.replace('/', '')
if not self.resource_id:
created_resource = self.client.create_resource(
restApiId=self.api_id, parentId=parent_i... | 440,837 |
Process rules into cidr and non-cidr lists.
Args:
rules (list): Allowed Security Group ports and protocols.
Returns:
(list, list): Security Group reference rules and custom CIDR rules. | def _process_rules(self, rules):
cidr = []
non_cidr = []
for rule in rules:
if '.' in rule['app']:
self.log.debug('Custom CIDR rule: %s', rule)
self._validate_cidr(rule)
cidr.append(rule)
else:
self... | 440,843 |
Add cidr rules to security group via boto.
Args:
rules (list): Allowed Security Group ports and protocols.
Returns:
True: Upon successful completion.
Raises:
SpinnakerSecurityGroupError: boto3 call failed to add CIDR block to
Security Group. | def add_cidr_rules(self, rules):
session = boto3.session.Session(profile_name=self.env, region_name=self.region)
client = session.client('ec2')
group_id = get_security_group_id(self.app_name, self.env, self.region)
for rule in rules:
data = {
'DryRu... | 440,845 |
Create a normalized ingress rule.
Args:
app (str): Application name
rule (dict or int): Allowed Security Group ports and protocols.
Returns:
dict: Contains app, start_port, end_port, protocol, cross_account_env and cross_account_vpc_id | def create_ingress_rule(self, app, rule):
if isinstance(rule, dict):
# Advanced
start_port = rule.get('start_port')
end_port = rule.get('end_port')
protocol = rule.get('protocol', 'tcp')
requested_cross_account = rule.get('env', self.env)
... | 440,850 |
Get lambda ARN.
Args:
account (str): AWS account name.
region (str): Region name, e.g. us-east-1
app (str): Lambda function name
Returns:
str: ARN for requested lambda function | def get_lambda_arn(app, account, region):
session = boto3.Session(profile_name=account, region_name=region)
lambda_client = session.client('lambda')
lambda_arn = None
paginator = lambda_client.get_paginator('list_functions')
for lambda_functions in paginator.paginate():
for lambda_fun... | 440,851 |
Get lambda alias ARN. Assumes that account name is equal to alias name.
Args:
account (str): AWS account name.
region (str): Region name, e.g. us-east-1
app (str): Lambda function name
Returns:
str: ARN for requested lambda alias | def get_lambda_alias_arn(app, account, region):
session = boto3.Session(profile_name=account, region_name=region)
lambda_client = session.client('lambda')
lambda_aliases = lambda_client.list_aliases(FunctionName=app)
matched_alias = None
for alias in lambda_aliases['Aliases']:
if alia... | 440,852 |
Add permission to Lambda for the event trigger.
Args:
function (str): Lambda function name
statement_id (str): IAM policy statement (principal) id
action (str): Lambda action to allow
principal (str): AWS principal to add permissions
source_arn (str): ARN of the source of th... | def add_lambda_permissions(function='',
statement_id='',
action='lambda:InvokeFunction',
principal='',
source_arn='',
env='',
region='us-east-1'):
se... | 440,853 |
Remove all foremast-* permissions from lambda.
Args:
app_name (str): Application name
env (str): AWS environment
region (str): AWS region | def remove_all_lambda_permissions(app_name='', env='', region='us-east-1'):
session = boto3.Session(profile_name=env, region_name=region)
lambda_client = session.client('lambda')
legacy_prefix = app_name + "_"
lambda_arn = get_lambda_arn(app_name, env, region)
lambda_alias_arn = get_lambda_ali... | 440,854 |
Attaches listerner policies to an ELB
Args:
json_data (json): return data from ELB upsert | def add_listener_policy(self, json_data):
env = boto3.session.Session(profile_name=self.env, region_name=self.region)
elbclient = env.client('elb')
# create stickiness policy if set in configs
stickiness = {}
elb_settings = self.properties['elb']
if elb_settings... | 440,859 |
Attaches backend server policies to an ELB
Args:
json_data (json): return data from ELB upsert | def add_backend_policy(self, json_data):
env = boto3.session.Session(profile_name=self.env, region_name=self.region)
elbclient = env.client('elb')
# Attach backend server policies to created ELB
for job in json.loads(json_data)['job']:
for listener in job['listeners... | 440,860 |
Configure load balancer attributes such as idle timeout, connection draining, etc
Args:
json_data (json): return data from ELB upsert | def configure_attributes(self, json_data):
env = boto3.session.Session(profile_name=self.env, region_name=self.region)
elbclient = env.client('elb')
elb_settings = self.properties['elb']
LOG.debug('Block ELB Settings Pre Configure Load Balancer Attributes:\n%s', pformat(elb_set... | 440,862 |
Set Health Check path, port, and protocol.
Args:
health_target (str): The health target. ie ``HTTP:80``
Returns:
HealthCheck: A **collections.namedtuple** class with *path*, *port*,
*proto*, and *target* attributes. | def splay_health(health_target):
HealthCheck = collections.namedtuple('HealthCheck', ['path', 'port', 'proto', 'target'])
proto, health_port_path = health_target.split(':')
port, *health_path = health_port_path.split('/')
if proto == 'TCP':
path = ''
elif not health_path:
path... | 440,863 |
Send Pipeline JSON to Spinnaker.
Args:
pipeline (dict, str): New Pipeline to create. | def post_pipeline(self, pipeline):
if isinstance(pipeline, str):
pipeline_str = pipeline
else:
pipeline_str = json.dumps(pipeline)
pipeline_json = json.loads(pipeline_str)
# Note pipeline name is manual
name = '{0} (onetime-{1})'.format(pipeline... | 440,865 |
Send Pipeline JSON to Spinnaker.
Args:
pipeline (json): json of the pipeline to be created in Spinnaker | def post_pipeline(self, pipeline):
url = "{0}/pipelines".format(API_URL)
if isinstance(pipeline, str):
pipeline_json = pipeline
else:
pipeline_json = json.dumps(pipeline)
pipeline_dict = json.loads(pipeline_json)
self.log.debug('Pipeline JSON:\... | 440,874 |
Generate the base Pipeline wrapper.
This renders the non-repeatable stages in a pipeline, like jenkins, baking, tagging and notifications.
Args:
region (str): AWS Region.
Returns:
dict: Rendered Pipeline wrapper. | def render_wrapper(self, region='us-east-1'):
base = self.settings['pipeline']['base']
if self.base:
base = self.base
email = self.settings['pipeline']['notifications']['email']
slack = self.settings['pipeline']['notifications']['slack']
baking_process = se... | 440,875 |
Compare desired pipeline with existing pipelines.
Args:
region (str): Region of desired pipeline.
onetime (bool): Looks for different pipeline if Onetime
Returns:
str: pipeline_id if existing, empty string of not. | def compare_with_existing(self, region='us-east-1', onetime=False):
pipelines = self.get_existing_pipelines()
pipeline_id = None
found = False
for pipeline in pipelines:
correct_app_and_region = (pipeline['application'] == self.app_name) and (region in pipeline['name... | 440,877 |
Look up AMI ID.
Use _name_ to find AMI ID. If no ami_base_url or gitlab_token is provided,
_name_ is returned as the ami id.
Args:
region (str): AWS Region to find AMI ID.
name (str): Simple AMI base name to lookup.
Returns:
str: AMI ID for _name_ in _region_. | def ami_lookup(region='us-east-1', name='tomcat8'):
if AMI_JSON_URL:
ami_dict = _get_ami_dict(AMI_JSON_URL)
ami_id = ami_dict[region][name]
elif GITLAB_TOKEN:
warn_user('Use AMI_JSON_URL feature instead.')
ami_contents = _get_ami_file(region=region)
ami_dict = json.l... | 440,879 |
Get file from Gitlab.
Args:
region (str): AWS Region to find AMI ID.
Returns:
str: Contents in json format. | def _get_ami_file(region='us-east-1'):
LOG.info("Getting AMI from Gitlab")
lookup = FileLookup(git_short='devops/ansible')
filename = 'scripts/{0}.json'.format(region)
ami_contents = lookup.remote_file(filename=filename, branch='master')
LOG.debug('AMI file contents in %s: %s', filename, ami_co... | 440,880 |
Get ami from a web url.
Args:
region (str): AWS Region to find AMI ID.
Returns:
dict: Contents in dictionary format. | def _get_ami_dict(json_url):
LOG.info("Getting AMI from %s", json_url)
response = requests.get(json_url)
assert response.ok, "Error getting ami info from {}".format(json_url)
ami_dict = response.json()
LOG.debug('AMI json contents: %s', ami_dict)
return ami_dict | 440,881 |
Read the local file in _self.runway_dir_.
Args:
filename (str): Name of file to retrieve relative to root of
_runway_dir_.
Returns:
str: Contents of local file.
Raises:
FileNotFoundError: Requested file missing. | def local_file(self, filename):
LOG.info('Retrieving "%s" from "%s".', filename, self.runway_dir)
file_contents = ''
file_path = os.path.join(self.runway_dir, filename)
try:
with open(file_path, 'rt') as lookup_file:
file_contents = lookup_file.rea... | 440,884 |
Read the remote file on Git Server.
Args:
branch (str): Git Branch to find file.
filename (str): Name of file to retrieve relative to root of
repository.
Returns:
str: Contents of remote file.
Raises:
FileNotFoundError: Requested... | def remote_file(self, branch='master', filename=''):
LOG.info('Retrieving "%s" from "%s".', filename, self.git_short)
file_contents = ''
try:
file_blob = self.project.files.get(file_path=filename, ref=branch)
except gitlab.exceptions.GitlabGetError:
fil... | 440,885 |
Retrieve _filename_ from GitLab.
Args:
branch (str): Git Branch to find file.
filename (str): Name of file to retrieve relative to root of Git
repository, or _runway_dir_ if specified.
Returns:
str: Contents of file. | def get(self, branch='master', filename=''):
file_contents = ''
if self.runway_dir:
file_contents = self.local_file(filename=filename)
else:
file_contents = self.remote_file(branch=branch, filename=filename)
return file_contents | 440,886 |
Retrieve _filename_ from GitLab.
Args:
branch (str): Git Branch to find file.
filename (str): Name of file to retrieve.
Returns:
dict: Decoded JSON.
Raises:
SystemExit: Invalid JSON provided. | def json(self, branch='master', filename=''):
file_contents = self.get(branch=branch, filename=filename)
try:
json_dict = json.loads(file_contents)
# TODO: Use json.JSONDecodeError when Python 3.4 has been deprecated
except ValueError as error:
msg = ('"... | 440,887 |
Center _text_ in a banner _width_ wide with _border_ characters.
Args:
text (str): What to write in the banner
border (str): Border character
width (int): How long the border should be | def banner(text, border='=', width=80):
text_padding = '{0:^%d}' % (width)
LOG.info(border * width)
LOG.info(text_padding.format(text))
LOG.info(border * width) | 440,888 |
Get SNS topic ARN.
Args:
topic_name (str): Name of the topic to lookup.
account (str): Environment, e.g. dev
region (str): Region name, e.g. us-east-1
Returns:
str: ARN for requested topic name | def get_sns_topic_arn(topic_name, account, region):
if topic_name.count(':') == 5 and topic_name.startswith('arn:aws:sns:'):
return topic_name
session = boto3.Session(profile_name=account, region_name=region)
sns_client = session.client('sns')
topics = sns_client.list_topics()['Topics']
... | 440,889 |
Get contents of _properties_file_ for the _env_.
Args:
properties_file (str): File name of `create-configs` JSON output.
env (str): Environment to read optionally.
region (str): Region to get specific configs for.
Returns:
dict: JSON loaded Application properties for _env_.
... | def get_properties(properties_file='raw.properties.json', env=None, region=None):
with open(properties_file, 'rt') as file_handle:
properties = json.load(file_handle)
env_properties = properties.get(env, properties)
contents = env_properties.get(region, env_properties)
LOG.debug('Found pro... | 440,893 |
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.
... | 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... | 440,895 |
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 | 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)
securit... | 440,896 |
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 # | 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)
... | 440,923 |
Convert :obj:`dict` to S3 Tag list.
Args:
tags (dict): Dictonary of tag key and tag value passed.
Returns:
list: List of dictionaries. | def generated_tag_data(tags):
generated_tags = []
for key, value in tags.items():
generated_tags.append({
'Key': key,
'Value': value,
})
return generated_tags | 440,924 |
Destroy DNS records.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
regions (str): AWS region.
Returns:
bool: True upon successful completion. | 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_resour... | 440,925 |
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 | 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(t... | 440,927 |
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 | 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.u... | 440,928 |
Destroy ELB Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
True upon successful completion. | 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 | 440,929 |
Warn when *key* is missing from configuration *section*.
Args:
config_handle (configparser.ConfigParser): Instance of configurations.
section (str): Name of configuration section to retrieve.
key (str): Configuration key to look up.
default (object): Default object to use when *key*... | def validate_key_values(config_handle, section, key, default=None):
if section not in config_handle:
LOG.info('Section missing from configurations: [%s]', section)
try:
value = config_handle[section][key]
except KeyError:
LOG.warning('[%s] missing key "%s", using %r.', section,... | 440,932 |
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}``. | def extract_formats(config_handle):
configurations = dict(config_handle)
formats = dict(configurations.get('formats', {}))
return formats | 440,933 |
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 | 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:
... | 440,938 |
AWS Data Pipeline object.
Args:
app (str): Application name
env (str): Environment/Account
region (str): AWS Region
prop_path (str): Path of environment property file | def __init__(self, app=None, env=None, region='us-east-1', prop_path=None):
self.app_name = app
self.env = env
self.region = region
self.properties = get_properties(prop_path, env=self.env, region=self.region)
self.datapipeline_data = self.properties['datapipeline']
... | 440,939 |
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. | 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 fac... | 440,944 |
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 (t... | 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 a... | 440,945 |
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 ... | 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... | 440,946 |
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... | 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("De... | 440,947 |
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 | 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')
i... | 440,949 |
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
... | 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.... | 440,951 |
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 serv... | 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... | 440,954 |
Destroy Cloudwatch event subscription.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
bool: True upon successful completion. | 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_cli... | 440,956 |
S3 application object. Setups Bucket and policies for S3 applications.
Args:
app (str): Application name
env (str): Environment/Account
region (str): AWS Region
prop_path (str): Path of environment property file
primary_region (str): The primary regio... | def __init__(self, app, env, region, prop_path, primary_region='us-east-1'):
self.app_name = app
self.env = env
self.region = region
boto_sess = boto3.session.Session(profile_name=env)
self.s3client = boto_sess.client('s3')
self.generated = get_details(app=app, e... | 440,957 |
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. | 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',
... | 440,969 |
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. | 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 | 440,970 |
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 | 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_con... | 440,971 |
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. | 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_specifi... | 440,972 |
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. | 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... | 440,973 |
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. | 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... | 440,974 |
Recursively retrieve value for _key_ in dict.
Args:
key (str): dict key to get all items for | def __getitem__(self, key):
for mapping in self.maps:
try:
value = mapping[key]
map_value = value
if isinstance(value, dict):
map_value = dict(DeepChainMap(*list(mapping.get(key, {}) for mapping in self.maps)))
... | 440,975 |
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 | 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 = respons... | 440,976 |
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 | 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['LoadBalancerDe... | 440,977 |
Create a recursive list of children.
Parameters:
level (int): The depth level to continue fetching children from
(default is -1, to get children to the utter depths)
intermediate (bool): Also include the intermediate children
(default is True)
Re... | def rchildren(self, level=-1, intermediate=True):
try:
return self._rchildren[(level, intermediate)]
except KeyError:
rchildren = []
if self.children and level:
if intermediate or level==1:
rchildren.extend(self.childre... | 443,336 |
Create a new `TermList`.
Arguments:
elements (collections.Iterable, optional): an Iterable
that yields `Term` objects.
Raises:
TypeError: when the given ``elements`` are not instances
of `Term`. | def __init__(self, elements=None):
super(TermList, self).__init__()
self._contents = set()
try:
for t in elements or []:
super(TermList, self).append(t)
self._contents.add(t.id)
except AttributeError:
raise TypeError('TermL... | 443,338 |
Parse a typedef line.
The typedef is organized as a succesion of ``key:value`` pairs
that are extracted into the same dictionnary until a new
header is encountered
Arguments:
line (str): the line containing a typedef statement | def _parse_typedef(line, _rawtypedef):
if "[Typedef]" in line:
_rawtypedef.append(collections.defaultdict(list))
else:
key, value = line.split(':', 1)
_rawtypedef[-1][key.strip()].append(value.strip()) | 443,348 |
Parse a term line.
The term is organized as a succesion of ``key:value`` pairs
that are extracted into the same dictionnary until a new
header is encountered
Arguments:
line (str): the line containing a term statement | def _parse_term(_rawterms):
line = yield
_rawterms.append(collections.defaultdict(list))
while True:
line = yield
if "[Term]" in line:
_rawterms.append(collections.defaultdict(list))
else:
key, value = line.split(':', 1... | 443,349 |
Create a new synonym type.
Arguments:
name (str): the name of the synonym type.
desc (str): the description of the synonym type.
scope (str, optional): the scope modifier. | def __init__(self, name, desc, scope=None):
self.name = name
self.desc = desc
if scope in {'BROAD', 'NARROW', 'EXACT', 'RELATED', None}:
self.scope = scope
elif scope in {six.b('BROAD'), six.b('NARROW'), six.b('EXACT'), six.b('RELATED')}:
self.scope = sco... | 443,351 |
Create a new synonym.
Arguments:
desc (str): a description of the synonym.
scope (str, optional): the scope of the synonym (either
EXACT, BROAD, NARROW or RELATED).
syn_type (SynonymType, optional): the type of synonym if
relying on a synonym ... | def __init__(self, desc, scope=None, syn_type=None, xref=None):
if isinstance(desc, six.binary_type):
self.desc = desc.decode('utf-8')
elif isinstance(desc, six.text_type):
self.desc = desc
else:
raise ValueError("desc must be bytes or str, not {}".fo... | 443,355 |
Set the connection's database name property.
Args:
value: New name of the database. String.
Returns:
Nothing. | def dbname(self, value):
self._dbname = value
self._connectionXML.set('dbname', value) | 443,410 |
Set the connection's server property.
Args:
value: New server. String.
Returns:
Nothing. | def server(self, value):
self._server = value
self._connectionXML.set('server', value) | 443,411 |
Set the connection's username property.
Args:
value: New username value. String.
Returns:
Nothing. | def username(self, value):
self._username = value
self._connectionXML.set('username', value) | 443,412 |
Set the connection's dbclass property.
Args:
value: New dbclass value. String.
Returns:
Nothing. | def dbclass(self, value):
if not is_valid_dbclass(value):
raise AttributeError("'{}' is not a valid database type".format(value))
self._class = value
self._connectionXML.set('class', value) | 443,413 |
Set the connection's port property.
Args:
value: New port value. String.
Returns:
Nothing. | def port(self, value):
self._port = value
# If port is None we remove the element and don't write it to XML
if value is None:
try:
del self._connectionXML.attrib['port']
except KeyError:
pass
else:
self._connec... | 443,414 |
Set the connection's query_band property.
Args:
value: New query_band value. String.
Returns:
Nothing. | def query_band(self, value):
self._query_band = value
# If query band is None we remove the element and don't write it to XML
if value is None:
try:
del self._connectionXML.attrib['query-band-spec']
except KeyError:
pass
e... | 443,415 |
Set the connection's initial_sql property.
Args:
value: New initial_sql value. String.
Returns:
Nothing. | def initial_sql(self, value):
self._initial_sql = value
# If initial_sql is None we remove the element and don't write it to XML
if value is None:
try:
del self._connectionXML.attrib['one-time-sql']
except KeyError:
pass
e... | 443,416 |
Save our file with the name provided.
Args:
new_filename: New name for the workbook file. String.
Returns:
Nothing. | def save_as(self, new_filename):
xfile._save_file(self._filename, self._datasourceTree, new_filename) | 443,430 |
Save our file with the name provided.
Args:
new_filename: New name for the workbook file. String.
Returns:
Nothing. | def save_as(self, new_filename):
xfile._save_file(
self._filename, self._workbookTree, new_filename) | 443,437 |
漂亮地打印一个节点
Args:
node (TYPE): Description | def pretty_print(node):
for pre, _, node in RenderTree(node):
print('{}{}'.format(pre, node.name)) | 443,790 |
初始化方法
某些APK可能存在大量的方法,可能会相当耗时,根据情况加限制
Args:
limit (int, optional): 方法数量限制,超过该值,则不获取方法
Returns:
TYPE: 方法集合 | def _init_methods(self, limit=10000):
methods = set()
if not self.dex_files:
self._init_dex_files()
count = 0
for dex_file in self.dex_files:
count += dex_file.method_ids.size
if limit < count:
return
for dex_file in self.dex... | 443,794 |
Send a message through Fleetspeak.
Args:
message: A message protocol buffer.
Returns:
Size of the message in bytes.
Raises:
ValueError: If message is not a common_pb2.Message. | def Send(self, message):
if not isinstance(message, common_pb2.Message):
raise ValueError("Send requires a fleetspeak.Message")
if message.destination.service_name == "system":
raise ValueError(
"Only predefined messages can have destination.service_name == \"system\"")
return s... | 444,045 |
Reads n characters from the input stream, or until EOF.
This is equivalent to the current CPython implementation of read(n), but
not guaranteed by the docs.
Args:
n: int
Returns:
string | def _ReadN(self, n):
ret = ""
while True:
chunk = self._read_file.read(n - len(ret))
ret += chunk
if len(ret) == n or not chunk:
return ret | 444,052 |
Create a Sender.
Args:
channel: The grpc.Channel over which we should send messages.
service_name: The name of the service that we are running as.
stub: If set, used instead of AdminStub(channel). Intended to ease
unit tests. | def __init__(self, channel, service_name, stub=None):
if stub:
self._stub = stub
else:
self._stub = admin_pb2_grpc.AdminStub(channel)
self._service_name = service_name
self._shutdown = False
self._shutdown_cv = threading.Condition()
self._keep_alive_thread = threading.Thread(t... | 444,057 |
Retries an operation until success or deadline.
Args:
func: The function to run. Must take a timeout, in seconds, as a single
parameter. If it raises grpc.RpcError and deadline has not be reached,
it will be run again.
timeout: Retries will continue until timeout seconds have passed. | def _RetryLoop(self, func, timeout=None):
timeout = timeout or self.DEFAULT_TIMEOUT
deadline = time.time() + timeout
sleep = 1
while True:
try:
return func(timeout)
except grpc.RpcError:
if time.time() + sleep > deadline:
raise
time.sleep(sleep)
... | 444,059 |
Inserts a message into the Fleetspeak server.
Sets message.source, if unset.
Args:
message: common_pb2.Message
The message to send.
timeout: How many seconds to try for.
Raises:
grpc.RpcError: if the RPC fails.
InvalidArgument: if message is not a common_pb2.Message. | def InsertMessage(self, message, timeout=None):
if not isinstance(message, common_pb2.Message):
raise InvalidArgument("Attempt to send unexpected message type: %s" %
message.__class__.__name__)
if not message.HasField("source"):
message.source.service_name = self._s... | 444,060 |
Provides basic information about Fleetspeak clients.
Args:
request: fleetspeak.admin.ListClientsRequest
timeout: How many seconds to try for.
Returns: fleetspeak.admin.ListClientsResponse | def ListClients(self, request, timeout=None):
return self._RetryLoop(
lambda t: self._stub.ListClients(request, timeout=t)) | 444,061 |
Starts naive bayes automated run
Args:
automated_run (xcessiv.models.AutomatedRun): Automated run object
session: Valid SQLAlchemy session
path (str, unicode): Path to project folder | def start_naive_bayes(automated_run, session, path):
module = functions.import_string_code_as_module(automated_run.source)
random_state = 8 if not hasattr(module, 'random_state') else module.random_state
assert module.metric_to_optimize in automated_run.base_learner_origin.metric_generators
# get ... | 444,357 |
Starts a TPOT automated run that exports directly to base learner setup
Args:
automated_run (xcessiv.models.AutomatedRun): Automated run object
session: Valid SQLAlchemy session
path (str, unicode): Path to project folder | def start_tpot(automated_run, session, path):
module = functions.import_string_code_as_module(automated_run.source)
extraction = session.query(models.Extraction).first()
X, y = extraction.return_train_dataset()
tpot_learner = module.tpot_learner
tpot_learner.fit(X, y)
temp_filename = os... | 444,358 |
Generates data statistics for the given data extraction setup stored
in Xcessiv notebook.
This is in rqtasks.py but not as a job yet. Temporarily call this directly
while I'm figuring out Javascript lel.
Args:
path (str, unicode): Path to xcessiv notebook | def extraction_data_statistics(path):
with functions.DBContextManager(path) as session:
extraction = session.query(models.Extraction).first()
X, y = extraction.return_main_dataset()
functions.verify_dataset(X, y)
if extraction.test_dataset['method'] == 'split_from_main':
... | 444,360 |
Generates meta-features for specified base learner
After generation of meta-features, the file is saved into the meta-features folder
Args:
path (str): Path to Xcessiv notebook
base_learner_id (str): Base learner ID | def generate_meta_features(path, base_learner_id):
with functions.DBContextManager(path) as session:
base_learner = session.query(models.BaseLearner).filter_by(id=base_learner_id).first()
if not base_learner:
raise exceptions.UserError('Base learner {} '
... | 444,361 |
Starts automated run. This will automatically create
base learners until the run finishes or errors out.
Args:
path (str): Path to Xcessiv notebook
automated_run_id (str): Automated Run ID | def start_automated_run(path, automated_run_id):
with functions.DBContextManager(path) as session:
automated_run = session.query(models.AutomatedRun).filter_by(id=automated_run_id).first()
if not automated_run:
raise exceptions.UserError('Automated run {} '
... | 444,362 |
Evaluates the ensemble and updates the database when finished/
Args:
path (str): Path to Xcessiv notebook
ensemble_id (str): Ensemble ID | def evaluate_stacked_ensemble(path, ensemble_id):
with functions.DBContextManager(path) as session:
stacked_ensemble = session.query(models.StackedEnsemble).filter_by(
id=ensemble_id).first()
if not stacked_ensemble:
raise exceptions.UserError('Stacked ensemble {} '
... | 444,363 |
Returns SHA256 checksum of a file
Args:
path (string): Absolute file path of file to hash
block_size (int, optional): Number of bytes to read per block | def hash_file(path, block_size=65536):
sha256 = hashlib.sha256()
with open(path, 'rb') as f:
for block in iter(lambda: f.read(block_size), b''):
sha256.update(block)
return sha256.hexdigest() | 444,364 |
Used to import an object from an absolute path.
This function takes an absolute path and imports it as a Python module.
It then returns the object with name `object` from the imported module.
Args:
path (string): Absolute file path of .py file to import
object (string): Name of object to ... | def import_object_from_path(path, object):
with open(path) as f:
return import_object_from_string_code(f.read(), object) | 444,365 |
Used to import an object from arbitrary passed code.
Passed in code is treated as a module and is imported and added
to `sys.modules` with its SHA256 hash as key.
Args:
code (string): Python code to import as module
object (string): Name of object to extract from imported module | def import_object_from_string_code(code, object):
sha256 = hashlib.sha256(code.encode('UTF-8')).hexdigest()
module = imp.new_module(sha256)
try:
exec_(code, module.__dict__)
except Exception as e:
raise exceptions.UserError('User code exception', exception_message=str(e))
sys.mo... | 444,366 |
Used to run arbitrary passed code as a module
Args:
code (string): Python code to import as module
Returns:
module: Python module | def import_string_code_as_module(code):
sha256 = hashlib.sha256(code.encode('UTF-8')).hexdigest()
module = imp.new_module(sha256)
try:
exec_(code, module.__dict__)
except Exception as e:
raise exceptions.UserError('User code exception', exception_message=str(e))
sys.modules[sha2... | 444,367 |
This function ensures that the dictionary is JSON serializable. If not,
keys with non-serializable values are removed from the return value.
Args:
json (dict): Dictionary to convert to serializable
Returns:
new_dict (dict): New dictionary with non JSON serializable values removed | def make_serializable(json):
new_dict = dict()
for key, value in iteritems(json):
if is_valid_json(value):
new_dict[key] = value
return new_dict | 444,369 |
Returns sample dataset
Args:
dataset_properties (dict): Dictionary corresponding to the properties of the dataset
used to verify the estimator and metric generators.
Returns:
X (array-like): Features array
y (array-like): Labels array
splits (iterator): This is an... | def get_sample_dataset(dataset_properties):
kwargs = dataset_properties.copy()
data_type = kwargs.pop('type')
if data_type == 'multiclass':
try:
X, y = datasets.make_classification(random_state=8, **kwargs)
splits = model_selection.StratifiedKFold(n_splits=2, random_stat... | 444,370 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.