desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'determine value type passed'
@staticmethod def parse_value(inc_value, vtype=''):
true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON'] false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF'] if (isinstance(inc_value, str) and ('bool' in vtype)): if ((inc_value not in true_bools) and (inc_value not in false_bools...
'run through a list of edits and process them one-by-one'
@staticmethod def process_edits(edits, yamlfile):
results = [] for edit in edits: value = Yedit.parse_value(edit['value'], edit.get('value_type', '')) if (edit.get('action') == 'update'): curr_value = Yedit.get_curr_value(Yedit.parse_value(edit.get('curr_value')), edit.get('curr_value_format')) rval = yamlfile.update(edi...
'perform the idempotent crud operations'
@staticmethod def run_ansible(params):
yamlfile = Yedit(filename=params['src'], backup=params['backup'], separator=params['separator']) state = params['state'] if params['src']: rval = yamlfile.load() if ((yamlfile.yaml_dict is None) and (state != 'present')): return {'failed': True, 'msg': ('Error opening file ...
'Constructor for RepoqueryCLI'
def __init__(self, verbose=False):
self.verbose = verbose self.verbose = True
'Base command for repoquery'
def _repoquery_cmd(self, cmd, output=False, output_type='json'):
cmds = ['/usr/bin/repoquery', '--plugins', '--quiet'] cmds.extend(cmd) rval = {} results = '' err = None if self.verbose: print(' '.join(cmds)) (returncode, stdout, stderr) = _run(cmds) rval = {'returncode': returncode, 'results': results, 'cmd': ' '.join(cmds)} if (ret...
'Constructor for YumList'
def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose):
super(Repoquery, self).__init__(None) self.name = name self.query_type = query_type self.show_duplicates = show_duplicates self.match_version = match_version self.ignore_excluders = ignore_excluders self.verbose = verbose if self.match_version: self.show_duplicates = True sel...
'build the repoquery cmd options'
def build_cmd(self):
repo_cmd = [] repo_cmd.append(('--pkgnarrow=' + self.query_type)) repo_cmd.append(('--queryformat=' + self.query_format)) if self.show_duplicates: repo_cmd.append('--show-duplicates') if self.ignore_excluders: repo_cmd.append(('--config=' + self.tmp_file.name)) repo_cmd.append(se...
'format the package data into something that can be presented'
@staticmethod def process_versions(query_output):
version_dict = defaultdict(dict) for version in query_output.decode().split('\n'): pkg_info = version.split('|') pkg_version = {} pkg_version['version'] = pkg_info[0] pkg_version['release'] = pkg_info[1] pkg_version['arch'] = pkg_info[2] pkg_version['repo'] = pkg_...
'Gather and present the versions of each package'
def format_versions(self, formatted_versions):
versions_dict = {} versions_dict['available_versions_full'] = list(formatted_versions.keys()) if self.match_version: versions_dict['matched_versions_full'] = [] versions_dict['requested_match_version'] = self.match_version versions_dict['matched_versions'] = [] versions_dict['ava...
'perform a repoquery'
def repoquery(self):
if self.ignore_excluders: self.tmp_file = tempfile.NamedTemporaryFile() with open('/etc/yum.conf', 'r') as file_handler: yum_conf_lines = file_handler.readlines() yum_conf_lines = [('exclude=' if l.startswith('exclude=') else l) for l in yum_conf_lines] with open(self.tmp...
'run the ansible idempotent code'
@staticmethod def run_ansible(params, check_mode):
repoquery = Repoquery(params['name'], params['query_type'], params['show_duplicates'], params['match_version'], params['ignore_excluders'], params['verbose']) state = params['state'] if (state == 'list'): results = repoquery.repoquery() if (results['returncode'] != 0): return {'f...
'This function will return the number of replicas based on the results from the defined openshift.hosted.router.replicas OR the query from oc_obj on openshift nodes with a selector OR default to 1'
@staticmethod def get_router_replicas(replicas=None, router_nodes=None):
if (replicas is not None): return replicas replicas = 1 if (isinstance(router_nodes, dict) and ('results' in router_nodes) and ('results' in router_nodes['results']) and isinstance(router_nodes['results']['results'], list) and (len(router_nodes['results']['results']) > 0) and ('items' in router_node...
'returns a mapping of filters to methods'
def filters(self):
return {'get_router_replicas': self.get_router_replicas}
'Returns named certificates list with correct fields for the master config file.'
@staticmethod def oo_named_certificates_list(named_certificates):
return [{'certFile': named_certificate['certfile'], 'keyFile': named_certificate['keyfile'], 'names': named_certificate['names']} for named_certificate in named_certificates]
'returns a mapping of filters to methods'
def filters(self):
return {'oo_named_certificates_list': self.oo_named_certificates_list}
'Returns the names of the filters provided by this class'
def filters(self):
return {'map_from_pairs': map_from_pairs}
'Creates a new FilterModule for ose version checking.'
def __init__(self):
self._filters = {} for (major, minor_start, minor_end) in self.versions: for minor in range(minor_start, minor_end): func_name = 'oo_version_gte_{}_{}'.format(major, minor) func = gte_function_builder(func_name, '{}.{}.0'.format(major, minor)) self._filters[func_name]...
'Return the filters mapping.'
def filters(self):
return self._filters
'returns a mapping of filters to methods'
def filters(self):
return {'oo_select_keys': oo_select_keys, 'oo_select_keys_from_list': oo_select_keys_from_list, 'oo_chomp_commit_offset': oo_chomp_commit_offset, 'oo_collect': oo_collect, 'oo_flatten': oo_flatten, 'oo_pdb': oo_pdb, 'oo_prepend_strings_in_list': oo_prepend_strings_in_list, 'oo_ami_selector': oo_ami_selector, 'oo_ec...
'Navigates the complicated logic of when to set dnsIP In all situations if they\'ve set openshift_dns_ip use that For 1.0/3.0 installs we use the openshift_master_cluster_vip, openshift_node_first_master_ip, else None For 1.1/3.1 installs we use openshift_master_cluster_vip, else None (product will use kube svc ip) For...
@staticmethod def get_dns_ip(openshift_dns_ip, hostvars):
if (not issubclass(type(hostvars), dict)): raise errors.AnsibleFilterError('|failed expects hostvars is a dict') if (openshift_dns_ip is not None): return openshift_dns_ip if bool(hostvars['openshift']['common']['use_dnsmasq']): return hostvars['ansible_default_ipv4'][...
'returns a mapping of filters to methods'
def filters(self):
return {'get_dns_ip': self.get_dns_ip}
'Check that we ran load facts with expected inputs.'
def _verify_load_facts(self, load_facts_mock):
load_facts_args = load_facts_mock.call_args[0] self.assertEquals(os.path.join(self.work_dir, 'hosts'), load_facts_args[0]) self.assertEquals(os.path.join(self.work_dir, 'playbooks/byo/openshift_facts.yml'), load_facts_args[1]) env_vars = load_facts_args[2] self.assertEquals(os.path.join(self.work_di...
'Check that we ran playbook with expected inputs.'
def _verify_run_playbook(self, run_playbook_mock, exp_hosts_len, exp_hosts_to_run_on_len):
hosts = run_playbook_mock.call_args[0][1] hosts_to_run_on = run_playbook_mock.call_args[0][2] self.assertEquals(exp_hosts_len, len(hosts)) self.assertEquals(exp_hosts_to_run_on_len, len(hosts_to_run_on))
'Tests cli_installer.py:get_hosts_to_run_on. That method has quite a few subtle branches in the logic. The goal with this method is simply to handle all the messy stuff here and allow the main test cases to be easily read. The basic idea is to modify mock_facts to return a version indicating OpenShift is already ins...
def _verify_get_hosts_to_run_on(self, mock_facts, load_facts_mock, run_playbook_mock, cli_input, exp_hosts_len=None, exp_hosts_to_run_on_len=None, force=None):
load_facts_mock.return_value = (mock_facts, 0) run_playbook_mock.return_value = 0 if cli_input: self.cli_args.append('install') result = self.runner.invoke(cli.cli, self.cli_args, input=cli_input) else: config_file = self.write_config(os.path.join(self.work_dir, 'ooinstall.conf')...
'Write given config to a temporary file which will be cleaned up in teardown. Returns full path to the file.'
def write_config(self, path, config_str):
cfg_file = open(path, 'w') cfg_file.write(config_str) cfg_file.close() return path
'Verify a host entry wraps openshift_node_labels value in double quotes'
def test_inventory_file_quotes_node_labels(self):
yaml_props = {'ip': '192.168.0.1', 'hostname': 'a.example.com', 'connect_to': 'a-private.example.com', 'public_ip': '192.168.0.1', 'public_hostname': 'a.example.com', 'new_host': True, 'roles': ['node'], 'node_labels': {'region': 'infra'}} new_node = Host(**yaml_props) inventory = cStringIO() ooinstall....
'Verify debug_env debugs specific env variables'
def test_utils_debug_env_all_debugged(self):
with mock.patch('ooinstall.utils.installer_log') as _il: debug_env(self.debug_all_params) self.assertEqual(len(self.debug_all_params), _il.debug.call_count) six.assertCountEqual(self, self.expected, _il.debug.call_args_list)
'Verify debug_env skips non-wanted env variables'
def test_utils_debug_env_some_debugged(self):
debug_some_params = copy.deepcopy(self.debug_all_params) debug_some_params['MG_FRBBR'] = 'SKIPPED' with mock.patch('ooinstall.utils.installer_log') as _il: debug_env(debug_some_params) self.assertLess(_il.debug.call_count, len(debug_some_params)) six.assertCountEqual(self, self.expec...
'Verify is_valid_hostname can detect None or too-long hostnames'
def test_utils_is_valid_hostname_invalid(self):
empty_hostname = '' res = is_valid_hostname(empty_hostname) self.assertFalse(res) none_hostname = None res = is_valid_hostname(none_hostname) self.assertFalse(res) too_long_hostname = ('a' * 256) res = is_valid_hostname(too_long_hostname) self.assertFalse(res)
'Verify is_valid_hostname can parse hostnames with trailing periods'
def test_utils_is_valid_hostname_ends_with_dot(self):
hostname = 'foo.example.com.' res = is_valid_hostname(hostname) self.assertTrue(res)
'Verify is_valid_hostname can parse regular hostnames'
def test_utils_is_valid_hostname_normal_hostname(self):
hostname = 'foo.example.com' res = is_valid_hostname(hostname) self.assertTrue(res)
'Used when exporting to yaml.'
def to_dict(self):
d = {} for prop in ['ip', 'hostname', 'public_ip', 'public_hostname', 'connect_to', 'preconfigured', 'containerized', 'schedulable', 'roles', 'node_labels']: if getattr(self, prop): d[prop] = getattr(self, prop) for (variable, value) in self.other_variables.items(): d[variable] =...
'Does this host have the etcd role'
def is_etcd(self):
return ('etcd' in self.roles)
'Will this host be a dedicated node. (not a master)'
def is_dedicated_node(self):
return (self.is_node() and (not self.is_master()))
'Will this host be a node marked as schedulable.'
def is_schedulable_node(self, all_hosts):
if (not self.is_node()): return False if (not self.is_master()): return True masters = [host for host in all_hosts if host.is_master()] nodes = [host for host in all_hosts if host.is_node()] if (len(masters) == len(nodes)): return True return False
'Used when exporting to yaml.'
def to_dict(self):
d = {} for prop in ['name', 'variables']: if getattr(self, prop): d[prop] = getattr(self, prop) return d
'Determine which host facts are not defined in the config. Returns a hash of host to a list of the missing facts.'
def calc_missing_facts(self):
result = {} for host in self.deployment.hosts: missing_facts = [] if host.preconfigured: required_facts = PRECONFIGURED_REQUIRED_FACTS else: required_facts = DEFAULT_REQUIRED_FACTS for required_fact in required_facts: if (not getattr(host, requ...
'decorator to mark a class method as returning model values'
@staticmethod def prop(model_name):
def dec(f): f.__returns_model__ = model_name return f return dec
'A dictionary of the urls to be mocked with this service and the handlers that should be called in their place'
@property def urls(self):
url_bases = self._url_module.url_bases unformatted_paths = self._url_module.url_paths urls = {} for url_base in url_bases: for (url_path, handler) in unformatted_paths.items(): url = url_path.format(url_base) urls[url] = handler return urls
'A dictionary of the paths of the urls to be mocked with this service and the handlers that should be called in their place'
@property def url_paths(self):
unformatted_paths = self._url_module.url_paths paths = {} for (unformatted_path, handler) in unformatted_paths.items(): path = unformatted_path.format(u'') paths[path] = handler return paths
'A list containing the url_bases extracted from urls.py'
@property def url_bases(self):
return self._url_module.url_bases
'The url paths that will be used for the flask server'
@property def flask_paths(self):
paths = {} for (url_path, handler) in self.url_paths.items(): url_path = convert_regex_to_flask_path(url_path) paths[url_path] = handler return paths
'Given a querystring of ?LaunchConfigurationNames.member.1=my-test-1&LaunchConfigurationNames.member.2=my-test-2 this will return [\'my-test-1\', \'my-test-2\']'
def _get_multi_param(self, param_prefix):
if param_prefix.endswith(u'.'): prefix = param_prefix else: prefix = (param_prefix + u'.') values = [] index = 1 while True: try: values.append(self.querystring[(prefix + str(index))][0]) except KeyError: break else: index +...
'Given a parameter dict of \'Instances.SlaveInstanceType\': [\'m1.small\'], \'Instances.InstanceCount\': [\'1\'] returns "SlaveInstanceType": "m1.small", "InstanceCount": "1",'
def _get_dict_param(self, param_prefix):
params = {} for (key, value) in self.querystring.items(): if key.startswith(param_prefix): params[camelcase_to_underscores(key.replace(param_prefix, u''))] = value[0] return params
'Given a query dict like \'Steps.member.1.Name\': [\'example1\'], \'Steps.member.1.ActionOnFailure\': [\'TERMINATE_JOB_FLOW\'], \'Steps.member.1.HadoopJarStep.Jar\': [\'streaming1.jar\'], \'Steps.member.2.Name\': [\'example2\'], \'Steps.member.2.ActionOnFailure\': [\'TERMINATE_JOB_FLOW\'], \'Steps.member.2.HadoopJarSte...
def _get_list_prefix(self, param_prefix):
results = [] param_index = 1 while True: index_prefix = u'{0}.{1}.'.format(param_prefix, param_index) new_items = {} for (key, value) in self.querystring.items(): if key.startswith(index_prefix): new_items[camelcase_to_underscores(key.replace(index_prefix,...
'Set the RecursiveDictRef object to keep reference to dict object (dic) at the key.'
def set_reference(self, key, dic):
self.key = key self.dic = dic
'Produce a JSON with a valid API response syntax for operation, but with type information. Each node represented by a key has the value containing field type, e.g., output_spec["SomeBooleanNode"] => {"type": "boolean"}'
def output_spec(self, operation):
try: op = self.operations[operation] except KeyError: raise ValueError(u'Invalid operation: {}'.format(operation)) if (u'output' not in op): return {} shape = self.shapes[op[u'output'][u'shape']] return self._expand(shape)
'True of any of the list elements starts with needle'
@staticmethod def _list_element_starts_with(items, needle):
for item in items: if item.startswith(needle): return True return False
'Compares this type against comparison filters'
def compare(self, range_comparison, range_objs):
range_values = [obj.cast_value for obj in range_objs] comparison_func = get_comparison_func(range_comparison) return comparison_func(self.cast_value, *range_values)
'Given a set of keys, extracts the key and range key'
def get_table_keys_name(self, table_name, keys):
table = self.tables.get(table_name) if (not table): return (None, None) else: if (len(keys) == 1): for key in keys: if (key in table.hash_key_names): return (key, None) (potential_hash, potential_range) = (None, None) for key in...
'Parses request headers and extracts part od the X-Amz-Target that corresponds to a method of DynamoHandler ie: X-Amz-Target: DynamoDB_20111205.ListTables -> ListTables'
def get_endpoint_name(self, headers):
match = (headers.get(u'x-amz-target') or headers.get(u'X-Amz-Target')) if match: return match.split(u'.')[1]
'http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/as-scale-based-on-demand.html If PercentChangeInCapacity returns a value between 0 and 1, Auto Scaling will round it off to 1. If the PercentChangeInCapacity returns a value greater than 1, Auto Scaling will round it off to the lower value. For example, if P...
def change_capacity_percent(self, group_name, scaling_adjustment):
group = self.autoscaling_groups[group_name] percent_change = (1 + (scaling_adjustment / 100.0)) desired_capacity = (group.desired_capacity * percent_change) if (group.desired_capacity < desired_capacity < (group.desired_capacity + 1)): desired_capacity = (group.desired_capacity + 1) else: ...
'SWF timeouts can happen on different objects (workflow executions, activity tasks, decision tasks) and should be processed in order. A specific timeout can change the workflow execution state and have an impact on other timeouts: for instance, if the workflow execution timeouts, subsequent timeouts on activity or deci...
def _process_timeouts(self):
timeout_candidates = [] timeout_candidates.append(self.first_timeout()) for task in self.decision_tasks: timeout_candidates.append(task.first_timeout()) for task in self.activity_tasks: timeout_candidates.append(task.first_timeout()) timeout_candidates = list(filter(None, timeout_can...
'Performs some basic validations on decisions. The real SWF service seems to break early and *not* process any decision if there\'s a validation problem, such as a malformed decision for instance. I didn\'t find an explicit documentation for that though, so criticisms welcome.'
def validate_decisions(self, decisions):
problems = [] for dcs in decisions[:(-1)]: close_decision_types = [u'CompleteWorkflowExecution', u'FailWorkflowExecution', u'CancelWorkflowExecution'] if (dcs[u'decisionType'] in close_decision_types): raise SWFValidationException(u'Close must be last decision in li...
'Handles a Decision according to SWF docs. See: http://docs.aws.amazon.com/amazonswf/latest/apireference/API_Decision.html'
def handle_decisions(self, event_id, decisions):
for decision in decisions: decision_type = decision[u'decisionType'] attributes_key = u'{0}DecisionAttributes'.format(decapitalize(decision_type)) attributes = decision.get(attributes_key, {}) if (decision_type == u'CompleteWorkflowExecution'): self.complete(event_id, att...
'Attempt to parse the post based on the content-type passed. Return the regular body if not'
def parse_request_body(self, body):
PARSING_FUNCTIONS = {u'application/json': json.loads, u'text/json': json.loads, u'application/x-www-form-urlencoded': self.parse_querystring} FALLBACK_FUNCTION = (lambda x: x) content_type = self.headers.get(u'content-type', u'') do_parse = PARSING_FUNCTIONS.get(content_type, FALLBACK_FUNCTION) try:...
'Returns this fake socket\'s own StringIO buffer. If there is an entry associated with the socket, the file descriptor gets filled in with the entry data before being returned.'
def makefile(self, mode=u'r', bufsize=(-1)):
self._mode = mode self._bufsize = bufsize if self._entry: self._entry.fill_filekind(self.fd) return self.fd
'Sends data to the remote server. This method is called when HTTPretty identifies that someone is trying to send non-http data. The received bytes are written in this socket\'s StringIO buffer so that HTTPretty can return it accordingly when necessary.'
def real_sendall(self, data, *args, **kw):
if (not self.truesock): raise UnmockedError() if (not self.is_http): return self.truesock.sendall(data, *args, **kw) self.truesock.connect(self._address) self.truesock.setblocking(1) self.truesock.sendall(data, *args, **kw) should_continue = True while should_continue: ...
'Cycle through available responses, but only once. Any subsequent requests will receive the last response'
def get_next_entry(self, method, info, request):
if (method not in self.current_entries): self.current_entries[method] = 0 entries_for_method = [e for e in self.entries if (e.method == method)] if (self.current_entries[method] >= len(entries_for_method)): self.current_entries[method] = (-1) if ((not self.entries) or (not entries_for_me...
'Handles requests which are generated by code similar to: instance.modify_attribute(\'blockDeviceMapping\', {\'/dev/sda1\': True}) The querystring contains information similar to: BlockDeviceMapping.1.Ebs.DeleteOnTermination : [\'true\'] BlockDeviceMapping.1.DeviceName : [\'/dev/sda1\'] For now we only support the "Blo...
def _block_device_mapping_handler(self):
mapping_counter = 1 mapping_device_name_fmt = u'BlockDeviceMapping.%s.DeviceName' mapping_del_on_term_fmt = u'BlockDeviceMapping.%s.Ebs.DeleteOnTermination' while True: mapping_device_name = (mapping_device_name_fmt % mapping_counter) if (mapping_device_name not in self.querystring.keys(...
':param instance_ids: A string list with instance ids :return: A list with instance objects'
def get_multi_instances_by_id(self, instance_ids):
result = [] for reservation in self.all_reservations(): for instance in reservation.instances: if (instance.id in instance_ids): result.append(instance) if (instance_ids and (len(instance_ids) > len(result))): raise InvalidInstanceIdError(instance_ids) return ...
'Go through all of the reservations and filter to only return those associated with the given instance_ids.'
def get_reservations_by_instance_ids(self, instance_ids, filters=None):
reservations = [] for reservation in self.all_reservations(make_copy=True): reservation_instance_ids = [instance.id for instance in reservation.instances] matching_reservation = any(((instance_id in reservation_instance_ids) for instance_id in instance_ids)) if matching_reservation: ...
'Not exposed as part of the ELB API - used for CloudFormation.'
def delete(self, region_name):
self.ec2_backend.delete_security_group(group_id=self.id)
'API Version 2014-10-01 defines the following filters for DescribeSubnets: * availabilityZone * available-ip-address-count * cidrBlock * defaultForAz * state * subnet-id * tag:key=value * tag-key * tag-value * vpc-id Taken from: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSubnets.html'
def get_filter_value(self, filter_name):
if (filter_name in (u'cidr', u'cidrBlock', u'cidr-block')): return self.cidr_block elif (filter_name in (u'vpc-id', u'vpcId')): return self.vpc_id elif (filter_name == u'subnet-id'): return self.id elif (filter_name in (u'availabilityZone', u'availability-zone')): return ...
'API Version 2015-10-01 defines the following filters for DescribeDhcpOptions: * dhcp-options-id * key * value * tag:key=value * tag-key * tag-value Taken from: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeDhcpOptions.html'
def get_filter_value(self, filter_name):
if (filter_name == u'dhcp-options-id'): return self.id elif (filter_name == u'key'): return list(self._options.keys()) elif (filter_name == u'value'): values = [item for item in list(self._options.values()) if item] return itertools.chain(*values) filter_value = super(DHC...
'create an ec2 reservation if one doesn\'t already exist and call start_instance. Update instance attributes to the newly created instance attributes'
def start(self):
if (self.instance is None): reservation = self.ec2_backend.add_instances(image_id=self.ami_id, count=1, user_data=u'', security_group_names=[], security_group_ids=self.security_group_ids, instance_type=self.instance_type, key_name=self.ssh_keyname, ebs_optimized=self.ebs_optimized, subnet_id=self.subnet_id,...
'Method calls resource with action_name and returns data of response.'
def action_data(self, action_name, **kwargs):
opts = {u'Action': action_name} opts.update(kwargs) res = self.get(u'/?{0}'.format(urlencode(opts)), headers={u'Host': u'{0}.us-east-1.amazonaws.com'.format(self.application.service)}) return res.data.decode(u'utf-8')
'Method calls resource with action_name and returns object obtained via deserialization of output.'
def action_json(self, action_name, **kwargs):
return json.loads(self.action_data(action_name, **kwargs))
'Not exposed as part of the Route 53 API - used for CloudFormation. args are ignored'
def delete(self, *args, **kwargs):
hosted_zone = route53_backend.get_hosted_zone_by_name(self.hosted_zone_name) if (not hosted_zone): hosted_zone = route53_backend.get_hosted_zone(self.hosted_zone_id) hosted_zone.delete_rrset_by_name(self.name)
'We perform no encryption, we just encode the value as base64 and then decode it in decrypt().'
def encrypt(self):
value = self.parameters.get(u'Plaintext') if isinstance(value, six.text_type): value = value.encode(u'utf-8') return json.dumps({u'CiphertextBlob': base64.b64encode(value).decode(u'utf-8')})
'Enable MFA Device for user.'
def enable_mfa_device(self, user_name, serial_number, authentication_code_1, authentication_code_2):
user = self.get_user(user_name) if (serial_number in user.mfa_devices): raise IAMConflictException(u'EntityAlreadyExists', u'Device {0} already exists'.format(serial_number)) user.enable_mfa_device(serial_number, authentication_code_1, authentication_code_2)
'Deactivate and detach MFA Device from user if device exists.'
def deactivate_mfa_device(self, user_name, serial_number):
user = self.get_user(user_name) if (serial_number not in user.mfa_devices): raise IAMNotFoundException(u'Device {0} not found'.format(serial_number)) user.deactivate_mfa_device(serial_number)
'Not exposed as part of the ELB API - used for CloudFormation.'
def delete(self, region):
elbv2_backends[region].delete_load_balancer(self.arn)
'Not exposed as part of the ELB API - used for CloudFormation.'
def delete(self, region):
elb_backends[region].delete_load_balancer(self.name)
'The MD5 of all attributes is calculated by first generating a utf-8 string from each attribute and MD5-ing the concatenation of them all. Each attribute is encoded with some bytes that describe the length of each part and the type of attribute. Not yet implemented: List types (https://github.com/aws/aws-sdk-java/blob/...
@property def attribute_md5(self):
def utf8(str): if isinstance(str, six.string_types): return str.encode(u'utf-8') return str md5 = hashlib.md5() for name in sorted(self.message_attributes.keys()): attr = self.message_attributes[name] data_type = attr[u'data_type'] encoded = utf8(u'') ...
'When a message is received we will set the first receive timestamp, tap the ``approximate_receive_count`` and the ``visible_at`` time.'
def mark_received(self, visibility_timeout=None):
if visibility_timeout: visibility_timeout = int(visibility_timeout) else: visibility_timeout = 0 if (not self.approximate_first_receive_timestamp): self.approximate_first_receive_timestamp = int(unix_time_millis()) self.approximate_receive_count += 1 if visibility_timeout: ...
'Attempt to retrieve visible messages from a queue. If a message was read by client and not deleted it is considered to be "inflight" and cannot be read. We make attempts to obtain ``count`` messages but we may return less if messages are in-flight or there are simple not enough messages in the queue. :param string que...
def receive_messages(self, queue_name, count, wait_seconds_timeout, visibility_timeout):
queue = self.get_queue(queue_name) result = [] polling_end = (unix_time() + wait_seconds_timeout) while True: if (result or (wait_seconds_timeout and (unix_time() > polling_end))): break if (len(queue.messages) == 0): if (wait_seconds_timeout == 0): ...
':raises ValueError: If specified visibility timeout exceeds MAXIMUM_VISIBILTY_TIMEOUT :raises TypeError: If visibility timeout was not specified'
def _get_validated_visibility_timeout(self):
visibility_timeout = int(self.querystring.get(u'VisibilityTimeout')[0]) if (visibility_timeout > MAXIMUM_VISIBILTY_TIMEOUT): raise ValueError return visibility_timeout
'The querystring comes like this \'SendMessageBatchRequestEntry.1.DelaySeconds\': [\'0\'], \'SendMessageBatchRequestEntry.1.MessageBody\': [\'test message 1\'], \'SendMessageBatchRequestEntry.1.Id\': [\'6d0f122d-4b13-da2c-378f-e74244d8ad11\'] \'SendMessageBatchRequestEntry.2.Id\': [\'ff8cbf59-70a2-c1cb-44c7-b7469f1ba39...
def send_message_batch(self):
queue_name = self._get_queue_name() messages = [] for index in range(1, 11): message_key = u'SendMessageBatchRequestEntry.{0}.MessageBody'.format(index) message_body = self.querystring.get(message_key) if (not message_body): break message_user_id_key = u'SendMessa...
'The querystring comes like this \'DeleteMessageBatchRequestEntry.1.Id\': [\'message_1\'], \'DeleteMessageBatchRequestEntry.1.ReceiptHandle\': [\'asdfsfs...\'], \'DeleteMessageBatchRequestEntry.2.Id\': [\'message_2\'], \'DeleteMessageBatchRequestEntry.2.ReceiptHandle\': [\'zxcvfda...\'],'
def delete_message_batch(self):
queue_name = self._get_queue_name() message_ids = [] for index in range(1, 11): receipt_key = u'DeleteMessageBatchRequestEntry.{0}.ReceiptHandle'.format(index) receipt_handle = self.querystring.get(receipt_key) if (not receipt_handle): break self.sqs_backend.delet...
'maxSize and pagination not implemented'
def list_clusters(self):
return [cluster.arn for cluster in self.clusters.values()]
'Filtering not implemented'
def list_task_definitions(self):
task_arns = [] for task_definition_list in self.task_definitions.values(): task_arns.extend([task_definition.arn for task_definition in task_definition_list]) return task_arns
':param container_instance: The container instance trying to be placed onto :param task_resource_requirements: The calculated resource requirements of the task in the form of a dict :return: A boolean stating whether the given container instance has enough resources to have the task placed on it as well as a descriptio...
@staticmethod def _can_be_placed(container_instance, task_resource_requirements):
remaining_cpu = 0 remaining_memory = 0 reserved_ports = [] for resource in container_instance.remaining_resources: if (resource.get(u'name') == u'CPU'): remaining_cpu = resource.get(u'integerValue') elif (resource.get(u'name') == u'MEMORY'): remaining_memory = res...
'maxResults and nextToken not implemented'
def describe_repositories(self, registry_id=None, repository_names=None):
repositories = [] for repository in self.repositories.values(): if registry_id: if (repository.registry_id != registry_id): continue if repository_names: if (repository.name not in repository_names): continue repositories.append(rep...
'maxResults and filtering not implemented'
def list_images(self, repository_name, registry_id=None):
images = [] for repository in self.repositories.values(): if repository_name: if (repository.name != repository_name): continue if registry_id: if (repository.registry_id != registry_id): continue for image in repository.images: ...
'Mock response for localhost metadata http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html'
def metadata_response(self, request, full_url, headers):
parsed_url = urlparse(full_url) tomorrow = (datetime.datetime.utcnow() + datetime.timedelta(days=1)) credentials = dict(AccessKeyId=u'test-key', SecretAccessKey=u'test-secret-key', Token=u'test-session-token', Expiration=tomorrow.strftime(u'%Y-%m-%dT%H:%M:%SZ')) path = parsed_url.path meta_data_pref...
'Compares this type against comparison filters'
def compare(self, range_comparison, range_objs):
range_values = [obj.value for obj in range_objs] comparison_func = get_comparison_func(range_comparison) return comparison_func(self.value, *range_values)
'Parses request headers and extracts part od the X-Amz-Target that corresponds to a method of DynamoHandler ie: X-Amz-Target: DynamoDB_20111205.ListTables -> ListTables'
def get_endpoint_name(self, headers):
match = (headers.get(u'x-amz-target') or headers.get(u'X-Amz-Target')) if match: return match.split(u'.')[1]
'`parent_func` is a function that\'s called every time the child process dies. `child_func` is a function that should be run by the forked child that will auto-restart with the RESTART_EXIT_STATUS.'
@classmethod def start(cls, parent_func, child_func=None):
signal.signal(signal.SIGTERM, cls._handle_sigterm) cls.need_stop = False while True: try: if hasattr(cls, 'child_pid'): delattr(cls, 'child_pid') pid = os.fork() if (pid > 0): cls.child_pid = pid while (not cls.need_...
'Do the UNIX double-fork magic, see Stevens\' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16'
def daemonize(self):
try: pid = os.fork() if (pid > 0): sys.exit(0) except OSError as e: msg = ('fork #1 failed: %d (%s)' % (e.errno, e.strerror)) log.error(msg) sys.stderr.write((msg + '\n')) sys.exit(1) log.debug('Fork 1 ok') os.chdir('/') o...
'Restart the daemon'
def restart(self):
self.stop() self.start()
'You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart().'
def run(self):
raise NotImplementedError
'You should override this method when you subclass Daemon. It will be called to provide information about the status of the process'
@classmethod def info(cls):
raise NotImplementedError
'Get the status of the daemon. Exits with 0 if running, 1 if not.'
def status(self):
pid = self.pid() if (pid < 0): message = ('%s is not running' % self.__class__.__name__) exit_code = 1 else: try: os.kill(pid, 0) except OSError as e: if (e.errno != errno.EPERM): message = ('%s pidfile contains pid ...
'Enable SIGTERM and SIGINT handlers'
def register_signal_handlers(self):
try: signal.signal(signal.SIGTERM, self._handle_sigterm) signal.signal(signal.SIGINT, self._handle_sigterm) except ValueError: log.exception('Unable to register signal handlers.')
'Instantiate JMXFetch parameters, clean potential previous run leftovers.'
def configure(self, checks_list=None, clean_status_file=True):
if clean_status_file: JMXFiles.clean_status_file() (self.jmx_checks, self.invalid_checks, self.java_bin_path, self.java_options, self.tools_jar_path, self.custom_jar_paths) = self.get_configuration(self.confd_path, checks_list=checks_list)
'Should JMXFetch run ?'
def should_run(self):
return ((self.jmx_checks is not None) and (self.jmx_checks != []))
'Run JMXFetch redirect_std_streams: if left to False, the stdout and stderr of JMXFetch are streamed directly to the environment\'s stdout and stderr and cannot be retrieved via python\'s sys.stdout and sys.stderr. Set to True to redirect these streams to python\'s sys.stdout and sys.stderr.'
def run(self, command=None, checks_list=None, reporter=None, redirect_std_streams=False):
if (checks_list or (self.jmx_checks is None)): self.configure(checks_list) try: command = (command or JMX_COLLECT_COMMAND) if (len(self.invalid_checks) > 0): try: JMXFiles.write_status_file(self.invalid_checks) except Exception: log...
'Return a tuple (jmx_checks, invalid_checks, java_bin_path, java_options, tools_jar_path) jmx_checks: list of yaml files that are jmx checks (they have the is_jmx flag enabled or they are in JMX_CHECKS) and that have at least one instance configured invalid_checks: dictionary whose keys are check names that are JMX che...
@classmethod def get_configuration(cls, confd_path, checks_list=None):
jmx_checks = [] java_bin_path = None java_options = None tools_jar_path = None custom_jar_paths = [] invalid_checks = {} jmx_confd_checks = get_jmx_checks(confd_path, auto_conf=False) for check in jmx_confd_checks: check_config = check['check_config'] check_name = check['...
'Small helper function to load fixtures configs'
def get_config(self, name, parse_args=False):
return get_config(cfg_path=os.path.join(self.CONFIG_FOLDER, name), parse_args=parse_args)