sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def insert_group(node, target): """Insert node into in target tree, in appropriate group. Uses group and lang from target function. This assumes the node and target share a structure of a first child that determines the grouping, and a second child that will be accumulated in the group. """ group = target.sort lang = target.lang collator = Collator.createInstance(Locale(lang) if lang else Locale()) for child in target.tree: order = collator.compare(group(child) or '', group(node) or '') if order == 0: for nodechild in node[1:]: child.append(nodechild) break elif order > 0: child.addprevious(node) break else: target.tree.append(node)
Insert node into in target tree, in appropriate group. Uses group and lang from target function. This assumes the node and target share a structure of a first child that determines the grouping, and a second child that will be accumulated in the group.
entailment
def create_group(value): """Create the group wrapper node.""" node = etree.Element('div', attrib={'class': 'group-by'}) span = etree.Element('span', attrib={'class': 'group-label'}) span.text = value node.append(span) return node
Create the group wrapper node.
entailment
def _extract_sel_info(sel): """Recurse down parsed tree, return pseudo class info""" from cssselect2.parser import (CombinedSelector, CompoundSelector, PseudoClassSelector, FunctionalPseudoClassSelector) steps = [] extras = [] if isinstance(sel, CombinedSelector): lstep, lextras = _extract_sel_info(sel.left) rstep, rextras = _extract_sel_info(sel.right) steps = lstep + rstep extras = lextras + rextras elif isinstance(sel, CompoundSelector): for ssel in sel.simple_selectors: s, e = _extract_sel_info(ssel) steps.extend(s) extras.extend(e) elif isinstance(sel, FunctionalPseudoClassSelector): if sel.name == 'pass': steps.append(serialize(sel.arguments).strip('"\'')) elif isinstance(sel, PseudoClassSelector): if sel.name == 'deferred': extras.append('deferred') return (steps, extras)
Recurse down parsed tree, return pseudo class info
entailment
def extract_selector_info(sel): """Return selector special pseudo class info (steps and other).""" # walk the parsed_tree, looking for pseudoClass selectors, check names # add in steps and/or deferred extras steps, extras = _extract_sel_info(sel.parsed_tree) steps = sorted(set(steps)) extras = sorted(set(extras)) if len(steps) == 0: steps = ['default'] return (steps, extras)
Return selector special pseudo class info (steps and other).
entailment
def _to_roman(num): """Convert integer to roman numerals.""" roman_numeral_map = ( ('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1) ) if not (0 < num < 5000): log(WARN, 'Number out of range for roman (must be 1..4999)') return str(num) result = '' for numeral, integer in roman_numeral_map: while num >= integer: result += numeral num -= integer return result
Convert integer to roman numerals.
entailment
def copy_w_id_suffix(elem, suffix="_copy"): """Make a deep copy of the provided tree, altering ids.""" mycopy = deepcopy(elem) for id_elem in mycopy.xpath('//*[@id]'): id_elem.set('id', id_elem.get('id') + suffix) return mycopy
Make a deep copy of the provided tree, altering ids.
entailment
def generate_id(self): """Generate a fresh id""" if self.use_repeatable_ids: self.repeatable_id_counter += 1 return 'autobaked-{}'.format(self.repeatable_id_counter) else: return str(uuid4())
Generate a fresh id
entailment
def clear_state(self): """Clear the recipe state.""" self.state = {} self.state['steps'] = [] self.state['current_step'] = None self.state['scope'] = [] self.state['counters'] = {} self.state['strings'] = {} for step in self.matchers: self.state[step] = {} self.state[step]['pending'] = {} self.state[step]['actions'] = [] self.state[step]['counters'] = {} self.state[step]['strings'] = {} # FIXME rather than boolean should ref HTML tree self.state[step]['recipe'] = False
Clear the recipe state.
entailment
def update_css(self, css_in=None, clear_css=False): """Add additional CSS rules, optionally replacing all.""" if clear_css: self.matchers = {} # CSS is changing, so clear processing state self.clear_state() if css_in is None: return try: with open(css_in, 'rb') as f: # is it a path/filename? css = f.read() except (IOError, TypeError): try: css = css_in.read() # Perhaps a file obj? except AttributeError: css = css_in # Treat it as a string # Namespaces defined in the CSS if clear_css: self.css_namespaces = {} rules, _ = tinycss2.parse_stylesheet_bytes(css, skip_whitespace=True) for rule in rules: # Check for any @namespace declarations if rule.type == 'at-rule': if rule.lower_at_keyword == 'namespace': # The 1 supported format is: # # default (unsupported): [<WhitespaceToken>, # <StringToken "http://www.w3.org/1999/xhtml">] # prefixed: [<WhitespaceToken>, # <IdentToken html>, # <WhitespaceToken>, # <StringToken "http://www.w3.org/1999/xhtml">] if len(rule.prelude) == 4 and \ [tok.type for tok in rule.prelude] == \ ['whitespace', 'ident', 'whitespace', 'string']: # Prefixed namespace ns_prefix = rule.prelude[1].value ns_url = rule.prelude[3].value self.css_namespaces[ns_prefix] = ns_url else: # etree.XPath does not support the default namespace # and XPath is used to implement `sort-by:` # http://www.goodmami.org/2015/11/04/ # ... python-xpath-and-default-namespaces.html log(WARN, u'Unknown @namespace format at {}:{}' .format(rule.source_line, rule.source_column) .encode('utf-8')) elif rule.type == 'qualified-rule': selectors = parse(rule.prelude, namespaces=self.css_namespaces, extensions=extensions) decls = [d for d in parse_declaration_list(rule.content, skip_whitespace=True) if d.type == 'declaration'] # Could also be a comment for sel in selectors: try: csel = CompiledSelector(sel) except cssselect2.SelectorError as error: log(WARN, u'Invalid selector: {} {}'.format( serialize(rule.prelude), to_str(error.args)).encode('utf-8')) else: steps, extras = extract_selector_info(sel) label = csel.pseudo_element if len(extras) > 0: if label is not None: extras.insert(0, label) label = '_'.join(extras) for step in steps: if step not in self.matchers: self.matchers[step] = cssselect2.Matcher() self.record_coverage_zero(rule, sel.source_line_offset) self.matchers[step].add_selector( csel, ((rule.source_line + sel.source_line_offset, serialize(rule.prelude).replace('\n', ' ')), decls, label)) elif rule.type == 'comment': pass elif rule.type == 'error': log(ERROR, u'Parse Error {}: {}'.format( rule.kind, rule.message).encode('utf-8')) # Phil does not know how to nicely exit with staus != 0 raise ValueError(u'Parse Error {}: {}'.format( rule.kind, rule.message).encode('utf-8')) else: raise ValueError(u'BUG: Unknown ruletype={}'.format(rule.type)) steps = sorted(self.matchers.keys()) if len(steps) > 1: if 'default' in steps: steps.remove('default') try: steps.sort(key=int) steps.insert(0, '0') self.matchers['0'] = self.matchers.pop('default') except ValueError: steps.insert(0, 'default') else: try: steps.sort(key=int) except ValueError: pass # already sorted alpha self.clear_state() self.state['steps'] = steps log(DEBUG, 'Passes: {}'.format(to_str(steps)))
Add additional CSS rules, optionally replacing all.
entailment
def bake(self, element, last_step=None): """Apply recipes to HTML tree. Will build recipes if needed.""" if last_step is not None: try: self.state['steps'] = [s for s in self.state['steps'] if int(s) < int(last_step)] except ValueError: self.state['steps'] = [s for s in self.state['steps'] if s < last_step] for step in self.state['steps']: self.state['current_step'] = step self.state['scope'].insert(0, step) # Need to wrap each loop, since tree may have changed wrapped_html_tree = ElementWrapper.from_html_root(element) if not self.state[step]['recipe']: recipe = self.build_recipe(wrapped_html_tree, step) else: recipe = self.state[step] log(DEBUG, u'Recipe {} length: {}'.format( step, len(recipe['actions'])).encode('utf-8')) target = None old_content = {} node_counts = {} for action, value in recipe['actions']: if action == 'target': target = value old_content = {} elif action == 'tag': target.tree.tag = value elif action == 'clear': old_content['text'] = target.tree.text target.tree.text = None old_content['children'] = [] for child in target.tree: old_content['children'].append(child) target.tree.remove(child) elif action == 'content': if value is not None: append_string(target, value.text) for child in value: target.tree.append(child) elif old_content: append_string(target, old_content['text']) for child in old_content['children']: target.tree.append(child) elif action == 'attrib': attname, vals = value strval = u''.join([u'{}'.format(s) for s in vals]) target.tree.set(attname, strval) elif action == 'string': strval = u''.join([u'{}'.format(s) for s in value]) if target.location == 'before': prepend_string(target, strval) else: append_string(target, strval) elif action == 'move': grouped_insert(target, value) elif action == 'copy': mycopy = copy_w_id_suffix(value) mycopy.tail = None grouped_insert(target, mycopy) elif action == 'nodeset': node_counts[value] = node_counts.setdefault(value, 0) + 1 suffix = u'_copy_{}'.format(node_counts[value]) mycopy = copy_w_id_suffix(value, suffix) mycopy.tail = None grouped_insert(target, mycopy) else: log(WARN, u'Missing action {}'.format( action).encode('utf-8')) # Do numbering # Do label/link updates # Add an empty string to each element just to make sure the element # is closed. This is useful for browsers that parse the output # as HTML5 rather than as XHTML5. # # One use-case would be users that inject the content into an # existing HTML (not XHTML) document. walkAll = element.iter() for elt in walkAll: if elt.tag not in SELF_CLOSING_TAGS: if len(elt) == 0 and not elt.text: elt.text = ''
Apply recipes to HTML tree. Will build recipes if needed.
entailment
def record_coverage_zero(self, rule, offset): """Add entry to coverage saying this selector was parsed""" self.coverage_lines.append('DA:{},0'.format(rule.source_line + offset))
Add entry to coverage saying this selector was parsed
entailment
def record_coverage(self, rule): """Add entry to coverage saying this selector was matched""" log(DEBUG, u'Rule ({}): {}'.format(*rule).encode('utf-8')) self.coverage_lines.append('DA:{},1'.format(rule[0]))
Add entry to coverage saying this selector was matched
entailment
def build_recipe(self, element, step, depth=0): """Construct a set of steps to collate (and number) an HTML doc. Returns a state object that contains the steps to apply to the HTML tree. CSS rules match during a recusive descent HTML tree walk. Each declaration has a method that then runs, given the current element, the decaration value. State is maintained on the collator instance. Since matching occurs when entering a node, declaration methods are ran either before or after recursing into its children, depending on the presence of a pseudo-element and its value. """ element_id = element.etree_element.get('id') self.state['lang'] = element.lang matching_rules = {} # specificity, order, pseudo, payload = match # selector_rule, declaration_list, label = payload for _, _, pseudo, payload in self.matchers[step].match(element): rule, decs, label = payload matching_rules.setdefault(label, []).append((rule, decs)) # Do non-pseudo if None in matching_rules: for rule, declarations in matching_rules.get(None): self.record_coverage(rule) self.push_target_elem(element) for decl in declarations: method = self.find_method(decl) method(element, decl, None) # Store all variables (strings and counters) before children if element_id: temp_counters = {} temp_strings = {} for s_step in self.state['scope']: temp_counters[s_step] = { 'counters': deepcopy(self.state[s_step]['counters'])} temp_strings[s_step] = { 'strings': deepcopy(self.state[s_step]['strings'])} self.state['counters'][element_id] = temp_counters self.state['strings'][element_id] = temp_strings # Do before if 'before' in matching_rules: for rule, declarations in matching_rules.get('before'): self.record_coverage(rule) # pseudo element, create wrapper self.push_pending_elem(element, 'before') for decl in declarations: method = self.find_method(decl) method(element, decl, 'before') # deal w/ pending_elements, per rule self.pop_pending_if_empty(element) # Recurse for el in element.iter_children(): _state = self.build_recipe(el, step, depth=depth+1) # noqa # Do after if 'after' in matching_rules: for rule, declarations in matching_rules.get('after'): self.record_coverage(rule) # pseudo element, create wrapper self.push_pending_elem(element, 'after') for decl in declarations: method = self.find_method(decl) method(element, decl, 'after') # deal w/ pending_elements, per rule self.pop_pending_if_empty(element) # Do outside if 'outside' in matching_rules: for rule, declarations in matching_rules.get('outside'): self.record_coverage(rule) self.push_pending_elem(element, 'outside') for decl in declarations: method = self.find_method(decl) method(element, decl, 'outside') # Do inside if 'inside' in matching_rules: for rule, declarations in matching_rules.get('inside'): self.record_coverage(rule) self.push_pending_elem(element, 'inside') for decl in declarations: method = self.find_method(decl) method(element, decl, 'inside') # Do deferred if ('deferred' in matching_rules or 'after_deferred' in matching_rules or # NOQA 'before_deferred' in matching_rules or 'outside_deferred' in matching_rules or 'inside_deferred' in matching_rules): # store strings and counters, in case a deferred rule changes one if element_id: temp_counters = {} temp_strings = {} for s_step in self.state['scope']: temp_counters[s_step] = { 'counters': deepcopy(self.state[s_step]['counters'])} temp_strings[s_step] = { 'strings': deepcopy(self.state[s_step]['strings'])} # Do straight up deferred if 'deferred' in matching_rules: for rule, declarations in matching_rules.get('deferred'): self.record_coverage(rule) self.push_target_elem(element) for decl in declarations: method = self.find_method(decl) method(element, decl, None) # Do before_deferred if 'before_deferred' in matching_rules: for rule, declarations in \ matching_rules.get('before_deferred'): self.record_coverage(rule) # pseudo element, create wrapper self.push_pending_elem(element, 'before') for decl in declarations: method = self.find_method(decl) method(element, decl, 'before') # deal w/ pending_elements, per rule self.pop_pending_if_empty(element) # Do after_deferred if 'after_deferred' in matching_rules: for rule, declarations in matching_rules.get('after_deferred'): self.record_coverage(rule) # pseudo element, create wrapper self.push_pending_elem(element, 'after') for decl in declarations: method = self.find_method(decl) method(element, decl, 'after') # deal w/ pending_elements, per rule self.pop_pending_if_empty(element) # Do outside_deferred if 'outside_deferred' in matching_rules: for rule, declarations in \ matching_rules.get('outside_deferred'): self.record_coverage(rule) self.push_pending_elem(element, 'outside') for decl in declarations: method = self.find_method(decl) method(element, decl, 'outside') # Do inside_deferred if 'inside_deferred' in matching_rules: for rule, declarations in \ matching_rules.get('inside_deferred'): self.record_coverage(rule) self.push_pending_elem(element, 'inside') for decl in declarations: method = self.find_method(decl) method(element, decl, 'inside') # Did a deferred rule change a stored variable? if element_id: for s_step in self.state['scope']: for counter, val in self.state[s_step]['counters'].items(): if (counter not in temp_counters or temp_counters[counter] != val): self.state['counters'][element_id][s_step]['counters'][counter] = val # NOQA for string, val in self.state[s_step]['strings'].items(): if (string not in temp_strings or temp_strings[string] != val): self.state['strings'][element_id][s_step]['strings'][string] = val # NOQA if depth == 0: self.state[step]['recipe'] = True # FIXME should ref HTML tree return self.state[step]
Construct a set of steps to collate (and number) an HTML doc. Returns a state object that contains the steps to apply to the HTML tree. CSS rules match during a recusive descent HTML tree walk. Each declaration has a method that then runs, given the current element, the decaration value. State is maintained on the collator instance. Since matching occurs when entering a node, declaration methods are ran either before or after recursing into its children, depending on the presence of a pseudo-element and its value.
entailment
def push_target_elem(self, element, pseudo=None): """Place target element onto action stack.""" actions = self.state[self.state['current_step']]['actions'] if len(actions) > 0 and actions[-1][0] == 'target': actions.pop() actions.append(('target', Target(element.etree_element, pseudo, element.parent.etree_element )))
Place target element onto action stack.
entailment
def push_pending_elem(self, element, pseudo): """Create and place pending target element onto stack.""" self.push_target_elem(element, pseudo) elem = etree.Element('div') actions = self.state[self.state['current_step']]['actions'] actions.append(('move', elem)) actions.append(('target', Target(elem)))
Create and place pending target element onto stack.
entailment
def pop_pending_if_empty(self, element): """Remove empty wrapper element.""" actions = self.state[self.state['current_step']]['actions'] elem = self.current_target().tree if actions[-1][0] == ('target') and actions[-1][1].tree == elem: actions.pop() actions.pop() actions.pop()
Remove empty wrapper element.
entailment
def current_target(self): """Return current target.""" actions = self.state[self.state['current_step']]['actions'] for action, value in reversed(actions): if action == 'target': return value
Return current target.
entailment
def find_method(self, decl): """Find class method to call for declaration based on name.""" name = decl.name method = None try: method = getattr(self, u'do_{}'.format( (name).replace('-', '_'))) except AttributeError: if name.startswith('data-'): method = getattr(self, 'do_data_any') elif name.startswith('attr-'): method = getattr(self, 'do_attr_any') else: log(WARN, u'Missing method {}'.format( (name).replace('-', '_')).encode('utf-8')) if method: self.record_coverage_line(decl.source_line) return method else: return lambda x, y, z: None
Find class method to call for declaration based on name.
entailment
def lookup(self, vtype, vname, target_id=None): """Return value of vname from the variable store vtype. Valid vtypes are `strings` 'counters', and `pending`. If the value is not found in the current steps store, earlier steps will be checked. If not found, '', 0, or (None, None) is returned. """ nullvals = {'strings': '', 'counters': 0, 'pending': (None, None)} nullval = nullvals[vtype] vstyle = None if vtype == 'counters': if len(vname) > 1: vname, vstyle = vname else: vname = vname[0] if target_id is not None: try: state = self.state[vtype][target_id] steps = self.state[vtype][target_id].keys() except KeyError: log(WARN, u'Bad ID target lookup {}'.format( target_id).encode('utf-8')) return nullval else: state = self.state steps = self.state['scope'] for step in steps: if vname in state[step][vtype]: if vtype == 'pending': return(state[step][vtype][vname], step) else: val = state[step][vtype][vname] if vstyle is not None: return self.counter_style(val, vstyle) return val else: return nullval
Return value of vname from the variable store vtype. Valid vtypes are `strings` 'counters', and `pending`. If the value is not found in the current steps store, earlier steps will be checked. If not found, '', 0, or (None, None) is returned.
entailment
def counter_style(self, val, style): """Return counter value in given style.""" if style == 'decimal-leading-zero': if val < 10: valstr = "0{}".format(val) else: valstr = str(val) elif style == 'lower-roman': valstr = _to_roman(val).lower() elif style == 'upper-roman': valstr = _to_roman(val) elif style == 'lower-latin' or style == 'lower-alpha': if 1 <= val <= 26: valstr = chr(val + 96) else: log(WARN, 'Counter out of range for latin (must be 1...26)') valstr = str(val) elif style == 'upper-latin' or style == 'upper-alpha': if 1 <= val <= 26: valstr = chr(val + 64) else: log(WARN, 'Counter out of range for latin (must be 1...26)') valstr = str(val) elif style == 'decimal': valstr = str(val) else: log(WARN, u"ERROR: Counter numbering not supported for" u" list type {}. Using decimal.".format( style).encode('utf-8')) valstr = str(val) return valstr
Return counter value in given style.
entailment
def eval_string_value(self, element, value): """Evaluate parsed string. Returns a list of current and delayed values. """ strval = '' vals = [] for term in value: if type(term) is ast.WhitespaceToken: pass elif type(term) is ast.StringToken: strval += term.value elif type(term) is ast.IdentToken: log(DEBUG, u"IdentToken as string: {}".format( term.value).encode('utf-8')) strval += term.value elif type(term) is ast.LiteralToken: log(DEBUG, u"LiteralToken as string: {}".format( term.value).encode('utf-8')) strval += term.value elif type(term) is ast.FunctionBlock: if term.name == 'string': str_args = split(term.arguments, ',') str_name = self.eval_string_value(element, str_args[0])[0] val = self.lookup('strings', str_name) if val == '': if len(str_args) > 1: val = self.eval_string_value(element, str_args[1])[0] else: log(WARN, u"{} blank string" .format(str_name).encode('utf-8')) strval += val elif term.name == u'attr': att_args = split(term.arguments, ',') att_name = self.eval_string_value(element, att_args[0])[0] att_def = '' if len(att_args) > 1: att_def = self.eval_string_value(element, att_args[1])[0] if '|' in att_name: ns, att = att_name.split('|') try: ns = self.css_namespaces[ns] except KeyError: log(WARN, u"Undefined namespace prefix {}" .format(ns).encode('utf-8')) continue att_name = etree.QName(ns, att) strval += element.etree_element.get(att_name, att_def) elif term.name == u'uuid': strval += self.generate_id() elif term.name == u'content': strval += etree.tostring(element.etree_element, encoding='unicode', method='text', with_tail=False) elif term.name.startswith('target-'): if strval: vals.append(strval) strval = '' target_args = split(term.arguments, ',') vref = self.eval_string_value(element, target_args[0])[0] vname = self.eval_string_value(element, target_args[1])[0] vtype = term.name[7:]+'s' vals.append(TargetVal(self, vref[1:], vname, vtype)) elif term.name == u'first-letter': tmpstr = self.eval_string_value(element, term.arguments) if tmpstr: if isinstance(tmpstr[0], basestring): strval += tmpstr[0][0] else: log(WARN, u"Bad string value:" u" nested target-* not allowed. " u"{}".format( serialize(value)).encode( 'utf-8')) # FIXME can we do delayed first-letter elif term.name == 'counter': counterargs = [serialize(t).strip(" \'") for t in split(term.arguments, ',')] count = self.lookup('counters', counterargs) strval += str(count) elif term.name == u'pending': log(WARN, u"Bad string value: pending() not allowed. " u"{}".format(serialize(value)).encode( 'utf-8')) else: log(WARN, u"Bad string value: unknown function: {}. " u"{}".format(term.name, serialize(value)).encode( 'utf-8')) if strval: vals.append(strval) return vals
Evaluate parsed string. Returns a list of current and delayed values.
entailment
def do_string_set(self, element, decl, pseudo): """Implement string-set declaration.""" args = serialize(decl.value) step = self.state[self.state['current_step']] strval = '' strname = None for term in decl.value: if type(term) is ast.WhitespaceToken: continue elif type(term) is ast.StringToken: if strname is not None: strval += term.value else: log(WARN, u"Bad string-set: {}".format( args).encode('utf-8')) elif type(term) is ast.IdentToken: if strname is not None: log(WARN, u"Bad string-set: {}".format( args).encode('utf-8')) else: strname = term.value elif type(term) is ast.LiteralToken: if strname is None: log(WARN, u"Bad string-set: {}".format( args).encode('utf-8')) else: step['strings'][strname] = strval strval = '' strname = None elif type(term) is ast.FunctionBlock: if term.name == 'string': str_args = split(term.arguments, ',') str_name = self.eval_string_value(element, str_args[0])[0] val = self.lookup('strings', str_name) if val == '': if len(str_args) > 1: val = self.eval_string_value(element, str_args[1])[0] else: log(WARN, u"{} blank string" .format(str_name).encode('utf-8')) if strname is not None: strval += val else: log(WARN, u"Bad string-set: {}".format( args).encode('utf-8')) elif term.name == 'counter': counterargs = [serialize(t).strip(" \'") for t in split(term.arguments, ',')] count = self.lookup('counters', counterargs) strval += str(count) elif term.name == u'attr': if strname is not None: att_args = split(term.arguments, ',') att_name = self.eval_string_value(element, att_args[0])[0] att_def = '' if len(att_args) > 1: att_def = self.eval_string_value(element, att_args[1])[0] if '|' in att_name: ns, att = att_name.split('|') try: ns = self.css_namespaces[ns] except KeyError: log(WARN, u"Undefined namespace prefix {}" .format(ns).encode('utf-8')) continue att_name = etree.QName(ns, att) strval += element.etree_element.get(att_name, att_def) else: log(WARN, u"Bad string-set: {}".format( args).encode('utf-8')) elif term.name == u'content': if strname is not None: strval += etree.tostring(element.etree_element, encoding='unicode', method='text', with_tail=False) else: log(WARN, u"Bad string-set: {}".format( args).encode('utf-8')) elif term.name == u'first-letter': tmpstr = self.eval_string_value(element, term.arguments) if tmpstr: if isinstance(tmpstr[0], basestring): strval += tmpstr[0][0] else: log(WARN, u"Bad string value:" u" nested target-* not allowed. " u"{}".format(serialize( args)).encode('utf-8')) elif term.name == u'pending': log(WARN, u"Bad string-set:pending() not allowed. {}" .format(args).encode('utf-8')) if strname is not None: step['strings'][strname] = strval
Implement string-set declaration.
entailment
def do_counter_reset(self, element, decl, pseudo): """Clear specified counters.""" step = self.state[self.state['current_step']] counter_name = '' for term in decl.value: if type(term) is ast.WhitespaceToken: continue elif type(term) is ast.IdentToken: if counter_name: step['counters'][counter_name] = 0 counter_name = term.value elif type(term) is ast.LiteralToken: if counter_name: step['counters'][counter_name] = 0 counter_name = '' elif type(term) is ast.NumberToken: if counter_name: step['counters'][counter_name] = int(term.value) counter_name = '' else: log(WARN, u"Unrecognized counter-reset term {}" .format(type(term)).encode('utf-8')) if counter_name: step['counters'][counter_name] = 0
Clear specified counters.
entailment
def do_node_set(self, element, decl, pseudo): """Implement node-set declaration.""" target = serialize(decl.value).strip() step = self.state[self.state['current_step']] elem = self.current_target().tree _, valstep = self.lookup('pending', target) if not valstep: step['pending'][target] = [('nodeset', elem)] else: self.state[valstep]['pending'][target] = [('nodeset', elem)]
Implement node-set declaration.
entailment
def do_move_to(self, element, decl, pseudo): """Implement move-to declaration.""" target = serialize(decl.value).strip() step = self.state[self.state['current_step']] elem = self.current_target().tree # Find if the current node already has a move, and remove it. actions = step['actions'] for pos, action in enumerate(reversed(actions)): if action[0] == 'move' and action[1] == elem: target_index = - pos - 1 actions[target_index:] = actions[target_index+1:] break _, valstep = self.lookup('pending', target) if not valstep: step['pending'][target] = [('move', elem)] else: self.state[valstep]['pending'][target].append(('move', elem))
Implement move-to declaration.
entailment
def do_container(self, element, decl, pseudo): """Implement setting tag for new wrapper element.""" value = serialize(decl.value).strip() if '|' in value: namespace, tag = value.split('|', 1) try: namespace = self.css_namespaces[namespace] except KeyError: log(WARN, u'undefined namespace prefix: {}'.format( namespace).encode('utf-8')) value = tag else: value = etree.QName(namespace, tag) step = self.state[self.state['current_step']] actions = step['actions'] actions.append(('tag', value))
Implement setting tag for new wrapper element.
entailment
def do_class(self, element, decl, pseudo): """Implement class declaration - pre-match.""" step = self.state[self.state['current_step']] actions = step['actions'] strval = self.eval_string_value(element, decl.value) actions.append(('attrib', ('class', strval)))
Implement class declaration - pre-match.
entailment
def do_attr_any(self, element, decl, pseudo): """Implement generic attribute setting.""" step = self.state[self.state['current_step']] actions = step['actions'] strval = self.eval_string_value(element, decl.value) actions.append(('attrib', (decl.name[5:], strval)))
Implement generic attribute setting.
entailment
def do_content(self, element, decl, pseudo): """Implement content declaration.""" # FIXME Need?: link(id) step = self.state[self.state['current_step']] actions = step['actions'] wastebin = [] elem = self.current_target().tree if elem == element.etree_element or pseudo == 'inside': actions.append(('clear', elem)) if pseudo: current_actions = len(actions) # decl.value is parsed representation: loop over it # if a string, to pending elem - either text, or tail of last child # if a string(x) retrieve value from state and attach as tail # if a pending(x), do the target/extend dance # content() attr(x), link(x,y) etc. for term in decl.value: if type(term) is ast.WhitespaceToken: continue elif type(term) is ast.StringToken: actions.append(('string', term.value)) elif type(term) is ast.LiteralToken: actions.append(('string', term.value)) elif type(term) is ast.FunctionBlock: if term.name == 'string': str_args = split(term.arguments, ',') str_name = self.eval_string_value(element, str_args[0])[0] val = self.lookup('strings', str_name) if val == '': if len(str_args) > 1: val = self.eval_string_value(element, str_args[1])[0] else: log(WARN, u"{} blank string" .format(str_name).encode('utf-8')) if val != '': actions.append(('string', val)) elif term.name == 'counter': counterargs = [serialize(t).strip(" \'") for t in split(term.arguments, ',')] count = self.lookup('counters', counterargs) actions.append(('string', (count,))) elif term.name.startswith('target-'): target_args = split(term.arguments, ',') vref = self.eval_string_value(element, target_args[0])[0] vname = self.eval_string_value(element, target_args[1])[0] vtype = term.name[7:]+'s' actions.append(('string', [TargetVal(self, vref[1:], vname, vtype)])) elif term.name == u'attr': att_args = split(term.arguments, ',') att_name = self.eval_string_value(element, att_args[0])[0] att_def = '' if len(att_args) > 1: att_def = self.eval_string_value(element, att_args[1])[0] if '|' in att_name: ns, att = att_name.split('|') try: ns = self.css_namespaces[ns] except KeyError: log(WARN, u"Undefined namespace prefix {}" .format(ns).encode('utf-8')) continue att_name = etree.QName(ns, att) att_val = element.etree_element.get(att_name, att_def) actions.append(('string', att_val)) elif term.name == u'uuid': actions.append(('string', self.generate_id())) elif term.name == u'first-letter': tmpstr = self.eval_string_value(element, term.arguments) if tmpstr: actions.append(('string', tmpstr[0])) elif term.name == u'content': if pseudo in ('before', 'after'): mycopy = copy_w_id_suffix(element.etree_element) actions.append(('content', mycopy)) elif pseudo == 'outside': actions.append(('move', element.etree_element)) else: actions.append(('content', None)) elif term.name == 'pending': target = serialize(term.arguments) val, val_step = self.lookup('pending', target) if val is None: log(INFO, u"{} empty bucket".format( target).encode('utf-8')) continue actions.extend(val) del self.state[val_step]['pending'][target] elif term.name == 'nodes': target = serialize(term.arguments) val, val_step = self.lookup('pending', target) if val is None: log(INFO, u"{} empty bucket".format( target).encode('utf-8')) continue for action in val: if action[0] == 'move': actions.append(('nodeset', action[1])) else: actions.append(action) elif term.name == u'clear': target = serialize(term.arguments) val, val_step = self.lookup('pending', target) if val is None: log(INFO, u"{} empty bucket".format( target).encode('utf-8')) continue wastebin.extend(val) del self.state[val_step]['pending'][target] else: log(WARN, u"Unknown function {}".format( term.name).encode('utf-8')) else: log(WARN, u"Unknown term {}".format( term).encode('utf-8')) if pseudo: if len(actions) == current_actions: wastebin.append(('move', elem)) if len(wastebin) > 0: trashbucket = etree.Element('div', attrib={'class': 'delete-me'}) if actions[-1][0] == 'target': actions.pop() actions.append(('target', Target(trashbucket))) actions.extend(wastebin) wastebin = []
Implement content declaration.
entailment
def do_group_by(self, element, decl, pseudo): """Implement group-by declaration - pre-match.""" sort_css = groupby_css = flags = '' if ',' in decl.value: if decl.value.count(',') == 2: sort_css, groupby_css, flags = \ map(serialize, split(decl.value, ',')) else: sort_css, groupby_css = map(serialize, split(decl.value, ',')) else: sort_css = serialize(decl.value) if groupby_css.strip() == 'nocase': flags = groupby_css groupby_css = '' sort = css_to_func(sort_css, flags, self.css_namespaces, self.state['lang']) groupby = css_to_func(groupby_css, flags, self.css_namespaces, self.state['lang']) step = self.state[self.state['current_step']] target = self.current_target() target.sort = sort target.lang = self.state['lang'] target.isgroup = True target.groupby = groupby # Find current target, set its sort/grouping as well for pos, action in \ enumerate(reversed(step['actions'])): if action[0] == 'target' and \ action[1].tree == element.etree_element: action[1].sort = sort action[1].isgroup = True action[1].groupby = groupby break
Implement group-by declaration - pre-match.
entailment
def do_sort_by(self, element, decl, pseudo): """Implement sort-by declaration - pre-match.""" if ',' in decl.value: css, flags = split(decl.value, ',') else: css = decl.value flags = None sort = css_to_func(serialize(css), serialize(flags or ''), self.css_namespaces, self.state['lang']) step = self.state[self.state['current_step']] target = self.current_target() target.sort = sort target.lang = self.state['lang'] target.isgroup = False target.groupby = None # Find current target, set its sort as well for pos, action in \ enumerate(reversed(step['actions'])): if action[0] == 'target' and \ action[1].tree == element.etree_element: action[1].sort = sort action[1].isgroup = False action[1].groupby = None break
Implement sort-by declaration - pre-match.
entailment
def do_pass(self, element, decl, pseudo): """No longer valid way to set processing pass.""" log(WARN, u"Old-style pass as declaration not allowed.{}" .format(decl.value).encpde('utf-8'))
No longer valid way to set processing pass.
entailment
def connection_cache(func: callable): """Connection cache for SSH sessions. This is to prevent opening a new, expensive connection on every command run.""" cache = dict() lock = RLock() @wraps(func) def func_wrapper(host: str, username: str, *args, **kwargs): key = "{h}-{u}".format(h=host, u=username) if key in cache: # connection exists, check if it is still valid before # returning it. conn = cache[key] if conn and conn.is_active() and conn.is_authenticated(): return conn else: # try to close a bad connection and remove it from # the cache. if conn: try_close(conn) del cache[key] # key is not in the cache, so try to recreate it # it may have been removed just above. if key not in cache: conn = func(host, username, *args, **kwargs) if conn is not None: cache[key] = conn return conn # not sure how to reach this point, but just in case. return None def get_cache() -> dict: return cache def purge(key: str=None): with lock: if key is None: conns = [(k, v) for k, v in cache.items()] elif key in cache: conns = ((key, cache[key]), ) else: conns = list() for k, v in conns: try_close(v) del cache[k] func_wrapper.get_cache = get_cache func_wrapper.purge = purge return func_wrapper
Connection cache for SSH sessions. This is to prevent opening a new, expensive connection on every command run.
entailment
def _get_connection(host, username: str, key_path: str) \ -> paramiko.Transport or None: """Return an authenticated SSH connection. :param host: host or IP of the machine :type host: str :param username: SSH username :type username: str :param key_path: path to the SSH private key for SSH auth :type key_path: str :return: SSH connection :rtype: paramiko.Transport or None """ if not username: username = shakedown.cli.ssh_user if not key_path: key_path = shakedown.cli.ssh_key_file key = validate_key(key_path) transport = get_transport(host, username, key) if transport: transport = start_transport(transport, username, key) if transport.is_authenticated(): return transport else: print("error: unable to authenticate {}@{} with key {}".format(username, host, key_path)) else: print("error: unable to connect to {}".format(host)) return None
Return an authenticated SSH connection. :param host: host or IP of the machine :type host: str :param username: SSH username :type username: str :param key_path: path to the SSH private key for SSH auth :type key_path: str :return: SSH connection :rtype: paramiko.Transport or None
entailment
def run_command( host, command, username=None, key_path=None, noisy=True ): """ Run a command via SSH, proxied through the mesos master :param host: host or IP of the machine to execute the command on :type host: str :param command: the command to execute :type command: str :param username: SSH username :type username: str :param key_path: path to the SSH private key to use for SSH authentication :type key_path: str :return: True if successful, False otherwise :rtype: bool :return: Output of command :rtype: string """ with HostSession(host, username, key_path, noisy) as s: if noisy: print("\n{}{} $ {}\n".format(shakedown.fchr('>>'), host, command)) s.run(command) ec, output = s.get_result() return ec == 0, output
Run a command via SSH, proxied through the mesos master :param host: host or IP of the machine to execute the command on :type host: str :param command: the command to execute :type command: str :param username: SSH username :type username: str :param key_path: path to the SSH private key to use for SSH authentication :type key_path: str :return: True if successful, False otherwise :rtype: bool :return: Output of command :rtype: string
entailment
def run_command_on_master( command, username=None, key_path=None, noisy=True ): """ Run a command on the Mesos master """ return run_command(shakedown.master_ip(), command, username, key_path, noisy)
Run a command on the Mesos master
entailment
def run_command_on_leader( command, username=None, key_path=None, noisy=True ): """ Run a command on the Mesos leader. Important for Multi-Master. """ return run_command(shakedown.master_leader_ip(), command, username, key_path, noisy)
Run a command on the Mesos leader. Important for Multi-Master.
entailment
def run_command_on_marathon_leader( command, username=None, key_path=None, noisy=True ): """ Run a command on the Marathon leader """ return run_command(shakedown.marathon_leader_ip(), command, username, key_path, noisy)
Run a command on the Marathon leader
entailment
def run_command_on_agent( host, command, username=None, key_path=None, noisy=True ): """ Run a command on a Mesos agent, proxied through the master """ return run_command(host, command, username, key_path, noisy)
Run a command on a Mesos agent, proxied through the master
entailment
def run_dcos_command(command, raise_on_error=False, print_output=True): """ Run `dcos {command}` via DC/OS CLI :param command: the command to execute :type command: str :param raise_on_error: whether to raise a DCOSException if the return code is nonzero :type raise_on_error: bool :param print_output: whether to print the resulting stdout/stderr from running the command :type print_output: bool :return: (stdout, stderr, return_code) :rtype: tuple """ call = shlex.split(command) call.insert(0, 'dcos') print("\n{}{}\n".format(shakedown.fchr('>>'), ' '.join(call))) proc = subprocess.Popen(call, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = proc.communicate() return_code = proc.wait() stdout = output.decode('utf-8') stderr = error.decode('utf-8') if print_output: print(stdout, stderr, return_code) if return_code != 0 and raise_on_error: raise DCOSException( 'Got error code {} when running command "dcos {}":\nstdout: "{}"\nstderr: "{}"'.format( return_code, command, stdout, stderr)) return stdout, stderr, return_code
Run `dcos {command}` via DC/OS CLI :param command: the command to execute :type command: str :param raise_on_error: whether to raise a DCOSException if the return code is nonzero :type raise_on_error: bool :param print_output: whether to print the resulting stdout/stderr from running the command :type print_output: bool :return: (stdout, stderr, return_code) :rtype: tuple
entailment
def _wait_for_recv(self): """After executing a command, wait for results. Because `recv_ready()` can return False, but still have a valid, open connection, it is not enough to ensure output from a command execution is properly captured. :return: None """ while True: time.sleep(0.2) if self.session.recv_ready() or self.session.closed: return
After executing a command, wait for results. Because `recv_ready()` can return False, but still have a valid, open connection, it is not enough to ensure output from a command execution is properly captured. :return: None
entailment
def attach_cluster(url): """Attach to an already set-up cluster :return: True if successful, else False """ with shakedown.stdchannel_redirected(sys.stderr, os.devnull): clusters = [c.dict() for c in dcos.cluster.get_clusters()] for c in clusters: if url == c['url']: try: dcos.cluster.set_attached(dcos.cluster.get_cluster(c['name']).get_cluster_path()) return True except: return False return False
Attach to an already set-up cluster :return: True if successful, else False
entailment
def dcos_version(): """Return the version of the running cluster. :return: DC/OS cluster version as a string """ url = _gen_url('dcos-metadata/dcos-version.json') response = dcos.http.request('get', url) if response.status_code == 200: return response.json()['version'] else: return None
Return the version of the running cluster. :return: DC/OS cluster version as a string
entailment
def authenticate(username, password): """Authenticate with a DC/OS cluster and return an ACS token. return: ACS token """ url = _gen_url('acs/api/v1/auth/login') creds = { 'uid': username, 'password': password } response = dcos.http.request('post', url, json=creds) if response.status_code == 200: return response.json()['token'] else: return None
Authenticate with a DC/OS cluster and return an ACS token. return: ACS token
entailment
def authenticate_oauth(oauth_token): """Authenticate by checking for a valid OAuth token. return: ACS token """ url = _gen_url('acs/api/v1/auth/login') creds = { 'token': oauth_token } response = dcos.http.request('post', url, json=creds) if response.status_code == 200: return response.json()['token'] else: return None
Authenticate by checking for a valid OAuth token. return: ACS token
entailment
def _gen_url(url_path): """Return an absolute URL by combining DC/OS URL and url_path. :param url_path: path to append to DC/OS URL :type url_path: str :return: absolute URL :rtype: str """ from six.moves import urllib return urllib.parse.urljoin(dcos_url(), url_path)
Return an absolute URL by combining DC/OS URL and url_path. :param url_path: path to append to DC/OS URL :type url_path: str :return: absolute URL :rtype: str
entailment
def partition_master(incoming=True, outgoing=True): """ Partition master's port alone. To keep DC/OS cluster running. :param incoming: Partition incoming traffic to master process. Default True. :param outgoing: Partition outgoing traffic from master process. Default True. """ echo('Partitioning master. Incoming:{} | Outgoing:{}'.format(incoming, outgoing)) network.save_iptables(shakedown.master_ip()) network.flush_all_rules(shakedown.master_ip()) network.allow_all_traffic(shakedown.master_ip()) if incoming and outgoing: network.run_iptables(shakedown.master_ip(), DISABLE_MASTER_INCOMING) network.run_iptables(shakedown.master_ip(), DISABLE_MASTER_OUTGOING) elif incoming: network.run_iptables(shakedown.master_ip(), DISABLE_MASTER_INCOMING) elif outgoing: network.run_iptables(shakedown.master_ip(), DISABLE_MASTER_OUTGOING) else: pass
Partition master's port alone. To keep DC/OS cluster running. :param incoming: Partition incoming traffic to master process. Default True. :param outgoing: Partition outgoing traffic from master process. Default True.
entailment
def get_all_masters(): """ Returns the json object that represents each of the masters. """ masters = [] for master in __master_zk_nodes_keys(): master_zk_str = get_zk_node_data(master)['str'] masters.append(json.loads(master_zk_str)) return masters
Returns the json object that represents each of the masters.
entailment
def get_public_agents_public_ip(): """Provides a list public IPs for public agents in the cluster""" public_ip_list = [] agents = get_public_agents() for agent in agents: status, public_ip = shakedown.run_command_on_agent(agent, "/opt/mesosphere/bin/detect_ip_public") public_ip_list.append(public_ip) return public_ip_list
Provides a list public IPs for public agents in the cluster
entailment
def get_public_agents(): """Provides a list of hostnames / private IPs that are public agents in the cluster""" agent_list = [] agents = __get_all_agents() for agent in agents: for reservation in agent["reserved_resources"]: if "slave_public" in reservation: agent_list.append(agent["hostname"]) return agent_list
Provides a list of hostnames / private IPs that are public agents in the cluster
entailment
def get_private_agents(): """Provides a list of hostnames / IPs that are private agents in the cluster""" agent_list = [] agents = __get_all_agents() for agent in agents: if(len(agent["reserved_resources"]) == 0): agent_list.append(agent["hostname"]) else: private = True for reservation in agent["reserved_resources"]: if("slave_public" in reservation): private = False if(private): agent_list.append(agent["hostname"]) return agent_list
Provides a list of hostnames / IPs that are private agents in the cluster
entailment
def get_agents(): """Provides a list of hostnames / IPs of all agents in the cluster""" agent_list = [] agents = __get_all_agents() for agent in agents: agent_list.append(agent["hostname"]) return agent_list
Provides a list of hostnames / IPs of all agents in the cluster
entailment
def partition_agent(host): """ Partition a node from all network traffic except for SSH and loopback :param hostname: host or IP of the machine to partition from the cluster """ network.save_iptables(host) network.flush_all_rules(host) network.allow_all_traffic(host) network.run_iptables(host, ALLOW_SSH) network.run_iptables(host, ALLOW_PING) network.run_iptables(host, DISALLOW_MESOS) network.run_iptables(host, DISALLOW_INPUT)
Partition a node from all network traffic except for SSH and loopback :param hostname: host or IP of the machine to partition from the cluster
entailment
def kill_process_on_host( hostname, pattern ): """ Kill the process matching pattern at ip :param hostname: the hostname or ip address of the host on which the process will be killed :param pattern: a regular expression matching the name of the process to kill """ status, stdout = run_command_on_agent(hostname, "ps aux | grep -v grep | grep '{}'".format(pattern)) pids = [p.strip().split()[1] for p in stdout.splitlines()] for pid in pids: status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid)) if status: print("Killed pid: {}".format(pid)) else: print("Unable to killed pid: {}".format(pid))
Kill the process matching pattern at ip :param hostname: the hostname or ip address of the host on which the process will be killed :param pattern: a regular expression matching the name of the process to kill
entailment
def kill_process_from_pid_file_on_host(hostname, pid_file='app.pid'): """ Retrieves the PID of a process from a pid file on host and kills it. :param hostname: the hostname or ip address of the host on which the process will be killed :param pid_file: pid file to use holding the pid number to kill """ status, pid = run_command_on_agent(hostname, 'cat {}'.format(pid_file)) status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid)) if status: print("Killed pid: {}".format(pid)) run_command_on_agent(hostname, 'rm {}'.format(pid_file)) else: print("Unable to killed pid: {}".format(pid))
Retrieves the PID of a process from a pid file on host and kills it. :param hostname: the hostname or ip address of the host on which the process will be killed :param pid_file: pid file to use holding the pid number to kill
entailment
def wait_for( predicate, timeout_seconds=120, sleep_seconds=1, ignore_exceptions=True, inverse_predicate=False, noisy=False, required_consecutive_success_count=1): """ waits or spins for a predicate, returning the result. Predicate is a function that returns a truthy or falsy value. An exception in the function will be returned. A timeout will throw a TimeoutExpired Exception. """ count = 0 start_time = time_module.time() timeout = Deadline.create_deadline(timeout_seconds) while True: try: result = predicate() except Exception as e: if ignore_exceptions: if noisy: logger.exception("Ignoring error during wait.") else: count = 0 raise # preserve original stack else: if (not inverse_predicate and result) or (inverse_predicate and not result): count = count + 1 if count >= required_consecutive_success_count: return result if timeout.is_expired(): funname = __stringify_predicate(predicate) raise TimeoutExpired(timeout_seconds, funname) if noisy: header = '{}[{}/{}]'.format( shakedown.cli.helpers.fchr('>>'), pretty_duration(time_module.time() - start_time), pretty_duration(timeout_seconds) ) if required_consecutive_success_count > 1: header = '{} [{} of {} times]'.format( header, count, required_consecutive_success_count) print('{} spinning...'.format(header)) time_module.sleep(sleep_seconds)
waits or spins for a predicate, returning the result. Predicate is a function that returns a truthy or falsy value. An exception in the function will be returned. A timeout will throw a TimeoutExpired Exception.
entailment
def __stringify_predicate(predicate): """ Reflection of function name and parameters of the predicate being used. """ funname = getsource(predicate).strip().split(' ')[2].rstrip(',') params = 'None' # if args dig in the stack if '()' not in funname: stack = getouterframes(currentframe()) for frame in range(0, len(stack)): if funname in str(stack[frame]): _, _, _, params = getargvalues(stack[frame][0]) return "function: {} params: {}".format(funname, params)
Reflection of function name and parameters of the predicate being used.
entailment
def time_wait( predicate, timeout_seconds=120, sleep_seconds=1, ignore_exceptions=True, inverse_predicate=False, noisy=True, required_consecutive_success_count=1): """ waits or spins for a predicate and returns the time of the wait. An exception in the function will be returned. A timeout will throw a TimeoutExpired Exception. """ start = time_module.time() wait_for(predicate, timeout_seconds, sleep_seconds, ignore_exceptions, inverse_predicate, noisy, required_consecutive_success_count) return elapse_time(start)
waits or spins for a predicate and returns the time of the wait. An exception in the function will be returned. A timeout will throw a TimeoutExpired Exception.
entailment
def wait_while_exceptions( predicate, timeout_seconds=120, sleep_seconds=1, noisy=False): """ waits for a predicate, ignoring exceptions, returning the result. Predicate is a function. Exceptions will trigger the sleep and retry; any non-exception result will be returned. A timeout will throw a TimeoutExpired Exception. """ start_time = time_module.time() timeout = Deadline.create_deadline(timeout_seconds) while True: try: result = predicate() return result except Exception as e: if noisy: logger.exception("Ignoring error during wait.") if timeout.is_expired(): funname = __stringify_predicate(predicate) raise TimeoutExpired(timeout_seconds, funname) if noisy: header = '{}[{}/{}]'.format( shakedown.cli.helpers.fchr('>>'), pretty_duration(time_module.time() - start_time), pretty_duration(timeout_seconds) ) print('{} spinning...'.format(header)) time_module.sleep(sleep_seconds)
waits for a predicate, ignoring exceptions, returning the result. Predicate is a function. Exceptions will trigger the sleep and retry; any non-exception result will be returned. A timeout will throw a TimeoutExpired Exception.
entailment
def elapse_time(start, end=None, precision=3): """ Simple time calculation utility. Given a start time, it will provide an elapse time. """ if end is None: end = time_module.time() return round(end-start, precision)
Simple time calculation utility. Given a start time, it will provide an elapse time.
entailment
def pretty_duration(seconds): """ Returns a user-friendly representation of the provided duration in seconds. For example: 62.8 => "1m2.8s", or 129837.8 => "2d12h4m57.8s" """ if seconds is None: return '' ret = '' if seconds >= 86400: ret += '{:.0f}d'.format(int(seconds / 86400)) seconds = seconds % 86400 if seconds >= 3600: ret += '{:.0f}h'.format(int(seconds / 3600)) seconds = seconds % 3600 if seconds >= 60: ret += '{:.0f}m'.format(int(seconds / 60)) seconds = seconds % 60 if seconds > 0: ret += '{:.1f}s'.format(seconds) return ret
Returns a user-friendly representation of the provided duration in seconds. For example: 62.8 => "1m2.8s", or 129837.8 => "2d12h4m57.8s"
entailment
def read_config(args): """ Read configuration options from ~/.shakedown (if exists) :param args: a dict of arguments :type args: dict :return: a dict of arguments :rtype: dict """ configfile = os.path.expanduser('~/.shakedown') if os.path.isfile(configfile): with open(configfile, 'r') as f: config = toml.loads(f.read()) for key in config: param = key.replace('-', '_') if not param in args or args[param] in [False, None]: args[param] = config[key] return args
Read configuration options from ~/.shakedown (if exists) :param args: a dict of arguments :type args: dict :return: a dict of arguments :rtype: dict
entailment
def set_config_defaults(args): """ Set configuration defaults :param args: a dict of arguments :type args: dict :return: a dict of arguments :rtype: dict """ defaults = { 'fail': 'fast', 'stdout': 'fail' } for key in defaults: if not args[key]: args[key] = defaults[key] return args
Set configuration defaults :param args: a dict of arguments :type args: dict :return: a dict of arguments :rtype: dict
entailment
def banner(): """ Display a product banner :return: a delightful Mesosphere logo rendered in unicode :rtype: str """ banner_dict = { 'a0': click.style(chr(9601), fg='magenta'), 'a1': click.style(chr(9601), fg='magenta', bold=True), 'b0': click.style(chr(9616), fg='magenta'), 'c0': click.style(chr(9626), fg='magenta'), 'c1': click.style(chr(9626), fg='magenta', bold=True), 'd0': click.style(chr(9622), fg='magenta'), 'd1': click.style(chr(9622), fg='magenta', bold=True), 'e0': click.style(chr(9623), fg='magenta'), 'e1': click.style(chr(9623), fg='magenta', bold=True), 'f0': click.style(chr(9630), fg='magenta'), 'f1': click.style(chr(9630), fg='magenta', bold=True), 'g1': click.style(chr(9612), fg='magenta', bold=True), 'h0': click.style(chr(9624), fg='magenta'), 'h1': click.style(chr(9624), fg='magenta', bold=True), 'i0': click.style(chr(9629), fg='magenta'), 'i1': click.style(chr(9629), fg='magenta', bold=True), 'j0': click.style(fchr('>>'), fg='magenta'), 'k0': click.style(chr(9473), fg='magenta'), 'l0': click.style('_', fg='magenta'), 'l1': click.style('_', fg='magenta', bold=True), 'v0': click.style('mesosphere', fg='magenta'), 'x1': click.style('shakedown', fg='magenta', bold=True), 'y0': click.style('v' + shakedown.VERSION, fg='magenta'), 'z0': chr(32) } banner_map = [ " %(z0)s%(z0)s%(l0)s%(l0)s%(l1)s%(l0)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s%(l1)s", " %(z0)s%(b0)s%(z0)s%(c0)s%(z0)s%(d0)s%(z0)s%(z0)s%(z0)s%(z0)s%(e1)s%(z0)s%(f1)s%(z0)s%(g1)s", " %(z0)s%(b0)s%(z0)s%(z0)s%(c0)s%(z0)s%(h0)s%(e0)s%(d1)s%(i1)s%(z0)s%(f1)s%(z0)s%(z0)s%(g1)s%(z0)s%(j0)s%(v0)s %(x1)s %(y0)s", " %(z0)s%(b0)s%(z0)s%(z0)s%(f0)s%(c0)s%(i0)s%(z0)s%(z0)s%(h1)s%(f1)s%(c1)s%(z0)s%(z0)s%(g1)s%(z0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(k0)s%(z0)s%(k0)s%(k0)s%(z0)s%(z0)s%(k0)s", " %(z0)s%(i0)s%(f0)s%(h0)s%(z0)s%(z0)s%(c0)s%(z0)s%(z0)s%(f0)s%(z0)s%(z0)s%(i1)s%(c1)s%(h1)s", " %(z0)s%(z0)s%(z0)s%(z0)s%(z0)s%(z0)s%(z0)s%(c0)s%(f0)s", ] if 'TERM' in os.environ and os.environ['TERM'] in ('velocity', 'xterm', 'xterm-256color', 'xterm-color'): return echo("\n".join(banner_map) % banner_dict) else: return echo(fchr('>>') + 'mesosphere shakedown v' + shakedown.VERSION, b=True)
Display a product banner :return: a delightful Mesosphere logo rendered in unicode :rtype: str
entailment
def decorate(text, style): """ Console decoration style definitions :param text: the text string to decorate :type text: str :param style: the style used to decorate the string :type style: str :return: a decorated string :rtype: str """ return { 'step-maj': click.style("\n" + '> ' + text, fg='yellow', bold=True), 'step-min': click.style(' - ' + text + ' ', bold=True), 'item-maj': click.style(' - ' + text + ' '), 'item-min': click.style(' - ' + text + ' '), 'quote-head-fail': click.style("\n" + chr(9485) + (chr(9480)*2) + ' ' + text, fg='red'), 'quote-head-pass': click.style("\n" + chr(9485) + (chr(9480)*2) + ' ' + text, fg='green'), 'quote-head-skip': click.style("\n" + chr(9485) + (chr(9480)*2) + ' ' + text, fg='yellow'), 'quote-fail': re.sub('^', click.style(chr(9482) + ' ', fg='red'), text, flags=re.M), 'quote-pass': re.sub('^', click.style(chr(9482) + ' ', fg='green'), text, flags=re.M), 'quote-skip': re.sub('^', click.style(chr(9482) + ' ', fg='yellow'), text, flags=re.M), 'fail': click.style(text + ' ', fg='red'), 'pass': click.style(text + ' ', fg='green'), 'skip': click.style(text + ' ', fg='yellow') }.get(style, '')
Console decoration style definitions :param text: the text string to decorate :type text: str :param style: the style used to decorate the string :type style: str :return: a decorated string :rtype: str
entailment
def echo(text, **kwargs): """ Print results to the console :param text: the text string to print :type text: str :return: a string :rtype: str """ if shakedown.cli.quiet: return if not 'n' in kwargs: kwargs['n'] = True if 'd' in kwargs: text = decorate(text, kwargs['d']) if 'TERM' in os.environ and os.environ['TERM'] == 'velocity': if text: print(text, end="", flush=True) if kwargs.get('n'): print() else: click.echo(text, nl=kwargs.get('n'))
Print results to the console :param text: the text string to print :type text: str :return: a string :rtype: str
entailment
def add_user(uid, password, desc=None): """ Adds user to the DCOS Enterprise. If not description is provided the uid will be used for the description. :param uid: user id :type uid: str :param password: password :type password: str :param desc: description of user :type desc: str """ try: desc = uid if desc is None else desc user_object = {"description": desc, "password": password} acl_url = urljoin(_acl_url(), 'users/{}'.format(uid)) r = http.put(acl_url, json=user_object) assert r.status_code == 201 except DCOSHTTPException as e: # already exists if e.response.status_code != 409: raise
Adds user to the DCOS Enterprise. If not description is provided the uid will be used for the description. :param uid: user id :type uid: str :param password: password :type password: str :param desc: description of user :type desc: str
entailment
def get_user(uid): """ Returns a user from the DCOS Enterprise. It returns None if none exists. :param uid: user id :type uid: str :return: User :rtype: dict """ try: acl_url = urljoin(_acl_url(), 'users/{}'.format(uid)) r = http.get(acl_url) return r.json() # assert r.status_code == 201 except DCOSHTTPException as e: if e.response.status_code == 400: return None else: raise
Returns a user from the DCOS Enterprise. It returns None if none exists. :param uid: user id :type uid: str :return: User :rtype: dict
entailment
def remove_user(uid): """ Removes a user from the DCOS Enterprise. :param uid: user id :type uid: str """ try: acl_url = urljoin(_acl_url(), 'users/{}'.format(uid)) r = http.delete(acl_url) assert r.status_code == 204 except DCOSHTTPException as e: # doesn't exist if e.response.status_code != 400: raise
Removes a user from the DCOS Enterprise. :param uid: user id :type uid: str
entailment
def ensure_resource(rid): """ Creates or confirms that a resource is added into the DCOS Enterprise System. Example: dcos:service:marathon:marathon:services:/example-secure :param rid: resource ID :type rid: str """ try: acl_url = urljoin(_acl_url(), 'acls/{}'.format(rid)) r = http.put(acl_url, json={'description': 'jope'}) assert r.status_code == 201 except DCOSHTTPException as e: if e.response.status_code != 409: raise
Creates or confirms that a resource is added into the DCOS Enterprise System. Example: dcos:service:marathon:marathon:services:/example-secure :param rid: resource ID :type rid: str
entailment
def set_user_permission(rid, uid, action='full'): """ Sets users permission on a given resource. The resource will be created if it doesn't exist. Actions are: read, write, update, delete, full. :param uid: user id :type uid: str :param rid: resource ID :type rid: str :param action: read, write, update, delete or full :type action: str """ rid = rid.replace('/', '%252F') # Create ACL if it does not yet exist. ensure_resource(rid) # Set the permission triplet. try: acl_url = urljoin(_acl_url(), 'acls/{}/users/{}/{}'.format(rid, uid, action)) r = http.put(acl_url) assert r.status_code == 204 except DCOSHTTPException as e: if e.response.status_code != 409: raise
Sets users permission on a given resource. The resource will be created if it doesn't exist. Actions are: read, write, update, delete, full. :param uid: user id :type uid: str :param rid: resource ID :type rid: str :param action: read, write, update, delete or full :type action: str
entailment
def remove_user_permission(rid, uid, action='full'): """ Removes user permission on a given resource. :param uid: user id :type uid: str :param rid: resource ID :type rid: str :param action: read, write, update, delete or full :type action: str """ rid = rid.replace('/', '%252F') try: acl_url = urljoin(_acl_url(), 'acls/{}/users/{}/{}'.format(rid, uid, action)) r = http.delete(acl_url) assert r.status_code == 204 except DCOSHTTPException as e: if e.response.status_code != 400: raise
Removes user permission on a given resource. :param uid: user id :type uid: str :param rid: resource ID :type rid: str :param action: read, write, update, delete or full :type action: str
entailment
def no_user(): """ Provides a context with no logged in user. """ o_token = dcos_acs_token() dcos.config.set_val('core.dcos_acs_token', '') yield dcos.config.set_val('core.dcos_acs_token', o_token)
Provides a context with no logged in user.
entailment
def new_dcos_user(user_id, password): """ Provides a context with a newly created user. """ o_token = dcos_acs_token() shakedown.add_user(user_id, password, user_id) token = shakedown.authenticate(user_id, password) dcos.config.set_val('core.dcos_acs_token', token) yield dcos.config.set_val('core.dcos_acs_token', o_token) shakedown.remove_user(user_id)
Provides a context with a newly created user.
entailment
def dcos_user(user_id, password): """ Provides a context with user otherthan super """ o_token = dcos_acs_token() token = shakedown.authenticate(user_id, password) dcos.config.set_val('core.dcos_acs_token', token) yield dcos.config.set_val('core.dcos_acs_token', o_token)
Provides a context with user otherthan super
entailment
def add_group(id, description=None): """ Adds group to the DCOS Enterprise. If not description is provided the id will be used for the description. :param id: group id :type id: str :param desc: description of user :type desc: str """ if not description: description = id data = { 'description': description } acl_url = urljoin(_acl_url(), 'groups/{}'.format(id)) try: r = http.put(acl_url, json=data) assert r.status_code == 201 except DCOSHTTPException as e: if e.response.status_code != 409: raise
Adds group to the DCOS Enterprise. If not description is provided the id will be used for the description. :param id: group id :type id: str :param desc: description of user :type desc: str
entailment
def get_group(id): """ Returns a group from the DCOS Enterprise. It returns None if none exists. :param id: group id :type id: str :return: Group :rtype: dict """ acl_url = urljoin(_acl_url(), 'groups/{}'.format(id)) try: r = http.get(acl_url) return r.json() except DCOSHTTPException as e: if e.response.status_code != 400: raise
Returns a group from the DCOS Enterprise. It returns None if none exists. :param id: group id :type id: str :return: Group :rtype: dict
entailment
def remove_group(id): """ Removes a group from the DCOS Enterprise. The group is removed regardless of associated users. :param id: group id :type id: str """ acl_url = urljoin(_acl_url(), 'groups/{}'.format(id)) try: r = http.delete(acl_url) print(r.status_code) except DCOSHTTPException as e: if e.response.status_code != 400: raise
Removes a group from the DCOS Enterprise. The group is removed regardless of associated users. :param id: group id :type id: str
entailment
def add_user_to_group(uid, gid, exist_ok=True): """ Adds a user to a group within DCOS Enterprise. The group and user must exist. :param uid: user id :type uid: str :param gid: group id :type gid: str :param exist_ok: True if it is ok for the relationship to pre-exist. :type exist_ok: bool """ acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid)) try: r = http.put(acl_url) assert r.status_code == 204 except DCOSHTTPException as e: if e.response.status_code == 409 and exist_ok: pass else: raise
Adds a user to a group within DCOS Enterprise. The group and user must exist. :param uid: user id :type uid: str :param gid: group id :type gid: str :param exist_ok: True if it is ok for the relationship to pre-exist. :type exist_ok: bool
entailment
def remove_user_from_group(uid, gid): """ Removes a user from a group within DCOS Enterprise. :param uid: user id :type uid: str :param gid: group id :type gid: str """ acl_url = urljoin(_acl_url(), 'groups/{}/users/{}'.format(gid, uid)) try: r = http.delete(acl_url) assert r.status_code == 204 except dcos.errors.DCOSBadRequest: pass
Removes a user from a group within DCOS Enterprise. :param uid: user id :type uid: str :param gid: group id :type gid: str
entailment
def easybake(css_in, html_in=sys.stdin, html_out=sys.stdout, last_step=None, coverage_file=None, use_repeatable_ids=False): """Process the given HTML file stream with the css stream.""" html_doc = etree.parse(html_in) oven = Oven(css_in, use_repeatable_ids) oven.bake(html_doc, last_step) # serialize out HTML print(etree.tostring(html_doc, method="xml").decode('utf-8'), file=html_out) # generate CSS coverage_file file if coverage_file: print('SF:{}'.format(css_in.name), file=coverage_file) print(oven.get_coverage_report(), file=coverage_file) print('end_of_record', file=coverage_file)
Process the given HTML file stream with the css stream.
entailment
def main(argv=None): """Commandline script wrapping Baker.""" parser = argparse.ArgumentParser(description="Process raw HTML to baked" " (embedded numbering and" " collation)") parser.add_argument('-v', '--version', action="version", version=__version__, help='Report the library version') parser.add_argument("css_rules", type=argparse.FileType('rb'), help="CSS3 ruleset stylesheet recipe") parser.add_argument("html_in", nargs="?", type=argparse.FileType('r'), help="raw HTML file to bake (default stdin)", default=sys.stdin) parser.add_argument("html_out", nargs="?", type=argparse.FileType('w'), help="baked HTML file output (default stdout)", default=sys.stdout) parser.add_argument('-s', '--stop-at', action='store', metavar='<pass>', help='Stop baking just before given pass name') parser.add_argument('-d', '--debug', action='store_true', help='Send debugging info to stderr') parser.add_argument('-q', '--quiet', action='store_true', help="Quiet all on stderr except errors") parser.add_argument('-c', '--coverage-file', metavar='coverage.lcov', type=FileTypeExt('w'), help="output coverage file (lcov format). If " "filename starts with '+', append coverage info.") parser.add_argument('--use-repeatable-ids', action='store_true', help="use repeatable id attributes instead of uuids " "which is useful for diffing") args = parser.parse_args(argv) formatter = logging.Formatter('%(name)s %(levelname)s %(message)s') handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatter) logger.addHandler(handler) use_quiet_log = (args.quiet and logging.ERROR) use_debug_log = (args.debug and logging.DEBUG) # Debug option takes higher priority than quiet warnings option logger.setLevel(use_debug_log or use_quiet_log or logging.WARNING) try: easybake(args.css_rules, args.html_in, args.html_out, args.stop_at, args.coverage_file, args.use_repeatable_ids) finally: if args.css_rules: args.css_rules.close() if args.html_in: args.html_in.close() if args.html_out: args.html_out.close() if args.coverage_file: args.coverage_file.close()
Commandline script wrapping Baker.
entailment
def mom_version(name='marathon-user'): """Returns the version of marathon on marathon. """ if service_available_predicate(name): with marathon_on_marathon(name): return marathon_version() else: # We can either skip the corresponding test by returning False # or raise an exception. print('WARN: {} MoM not found. Version is None'.format(name)) return None
Returns the version of marathon on marathon.
entailment
def mom_version_less_than(version, name='marathon-user'): """ Returns True if MoM with the given {name} exists and has a version less than {version}. Note that if MoM does not exist False is returned. :param version: required version :type: string :param name: MoM name, default is 'marathon-user' :type: string :return: True if version < MoM version :rtype: bool """ if service_available_predicate(name): return mom_version() < LooseVersion(version) else: # We can either skip the corresponding test by returning False # or raise an exception. print('WARN: {} MoM not found. mom_version_less_than({}) is False'.format(name, version)) return False
Returns True if MoM with the given {name} exists and has a version less than {version}. Note that if MoM does not exist False is returned. :param version: required version :type: string :param name: MoM name, default is 'marathon-user' :type: string :return: True if version < MoM version :rtype: bool
entailment
def marathon_on_marathon(name='marathon-user'): """ Context manager for altering the marathon client for MoM :param name: service name of MoM to use :type name: str """ toml_config_o = config.get_config() dcos_url = config.get_config_val('core.dcos_url', toml_config_o) service_name = 'service/{}/'.format(name) marathon_url = urllib.parse.urljoin(dcos_url, service_name) config.set_val('marathon.url', marathon_url) try: yield finally: # return config to previous state config.save(toml_config_o)
Context manager for altering the marathon client for MoM :param name: service name of MoM to use :type name: str
entailment
def get_transport(host, username, key): """ Create a transport object :param host: the hostname to connect to :type host: str :param username: SSH username :type username: str :param key: key object used for authentication :type key: paramiko.RSAKey :return: a transport object :rtype: paramiko.Transport """ if host == shakedown.master_ip(): transport = paramiko.Transport(host) else: transport_master = paramiko.Transport(shakedown.master_ip()) transport_master = start_transport(transport_master, username, key) if not transport_master.is_authenticated(): print("error: unable to authenticate {}@{} with key {}".format(username, shakedown.master_ip(), key)) return False try: channel = transport_master.open_channel('direct-tcpip', (host, 22), ('127.0.0.1', 0)) except paramiko.SSHException: print("error: unable to connect to {}".format(host)) return False transport = paramiko.Transport(channel) return transport
Create a transport object :param host: the hostname to connect to :type host: str :param username: SSH username :type username: str :param key: key object used for authentication :type key: paramiko.RSAKey :return: a transport object :rtype: paramiko.Transport
entailment
def start_transport(transport, username, key): """ Begin a transport client and authenticate it :param transport: the transport object to start :type transport: paramiko.Transport :param username: SSH username :type username: str :param key: key object used for authentication :type key: paramiko.RSAKey :return: the transport object passed :rtype: paramiko.Transport """ transport.start_client() agent = paramiko.agent.Agent() keys = itertools.chain((key,) if key else (), agent.get_keys()) for test_key in keys: try: transport.auth_publickey(username, test_key) break except paramiko.AuthenticationException as e: pass else: raise ValueError('No valid key supplied') return transport
Begin a transport client and authenticate it :param transport: the transport object to start :type transport: paramiko.Transport :param username: SSH username :type username: str :param key: key object used for authentication :type key: paramiko.RSAKey :return: the transport object passed :rtype: paramiko.Transport
entailment
def validate_key(key_path): """ Validate a key :param key_path: path to a key to use for authentication :type key_path: str :return: key object used for authentication :rtype: paramiko.RSAKey """ key_path = os.path.expanduser(key_path) if not os.path.isfile(key_path): return False return paramiko.RSAKey.from_private_key_file(key_path)
Validate a key :param key_path: path to a key to use for authentication :type key_path: str :return: key object used for authentication :rtype: paramiko.RSAKey
entailment
def get_service( service_name, inactive=False, completed=False ): """ Get a dictionary describing a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a dict describing a service :rtype: dict, or None """ services = mesos.get_master().frameworks(inactive=inactive, completed=completed) for service in services: if service['name'] == service_name: return service return None
Get a dictionary describing a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a dict describing a service :rtype: dict, or None
entailment
def get_service_framework_id( service_name, inactive=False, completed=False ): """ Get the framework ID for a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a framework id :rtype: str, or None """ service = get_service(service_name, inactive, completed) if service is not None and service['id']: return service['id'] return None
Get the framework ID for a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a framework id :rtype: str, or None
entailment
def get_service_tasks( service_name, inactive=False, completed=False ): """ Get a list of tasks associated with a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a list of task objects :rtye: [dict], or None """ service = get_service(service_name, inactive, completed) if service is not None and service['tasks']: return service['tasks'] return []
Get a list of tasks associated with a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a list of task objects :rtye: [dict], or None
entailment
def get_service_task_ids( service_name, task_predicate=None, inactive=False, completed=False ): """ Get a list of task IDs associated with a service :param service_name: the service name :type service_name: str :param task_predicate: filter function which accepts a task object and returns a boolean :type task_predicate: function, or None :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a list of task ids :rtye: [str], or None """ tasks = get_service_tasks(service_name, inactive, completed) if task_predicate: return [t['id'] for t in tasks if task_predicate(t)] else: return [t['id'] for t in tasks]
Get a list of task IDs associated with a service :param service_name: the service name :type service_name: str :param task_predicate: filter function which accepts a task object and returns a boolean :type task_predicate: function, or None :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a list of task ids :rtye: [str], or None
entailment
def get_service_task( service_name, task_name, inactive=False, completed=False ): """ Get a dictionary describing a service task, or None :param service_name: the service name :type service_name: str :param task_name: the task name :type task_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a dictionary describing the service :rtye: dict, or None """ service = get_service_tasks(service_name, inactive, completed) if service is not None: for task in service: if task['name'] == task_name: return task return None
Get a dictionary describing a service task, or None :param service_name: the service name :type service_name: str :param task_name: the task name :type task_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a dictionary describing the service :rtye: dict, or None
entailment
def get_marathon_task( task_name, inactive=False, completed=False ): """ Get a dictionary describing a named marathon task """ return get_service_task('marathon', task_name, inactive, completed)
Get a dictionary describing a named marathon task
entailment
def get_mesos_task(task_name): """ Get a mesos task with a specific task name """ tasks = get_mesos_tasks() if tasks is not None: for task in tasks: if task['name'] == task_name: return task return None
Get a mesos task with a specific task name
entailment
def get_service_ips( service_name, task_name=None, inactive=False, completed=False ): """ Get a set of the IPs associated with a service :param service_name: the service name :type service_name: str :param task_name: the task name :type task_name: str :param inactive: wehther to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a list of IP addresses :rtype: [str] """ service_tasks = get_service_tasks(service_name, inactive, completed) ips = set([]) for task in service_tasks: if task_name is None or task['name'] == task_name: for status in task['statuses']: # Only the TASK_RUNNING status will have correct IP information. if status["state"] != "TASK_RUNNING": continue for ip in status['container_status']['network_infos'][0]['ip_addresses']: ips.add(ip['ip_address']) return ips
Get a set of the IPs associated with a service :param service_name: the service name :type service_name: str :param task_name: the task name :type task_name: str :param inactive: wehther to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a list of IP addresses :rtype: [str]
entailment
def service_healthy(service_name, app_id=None): """ Check whether a named service is healthy :param service_name: the service name :type service_name: str :param app_id: app_id to filter :type app_id: str :return: True if healthy, False otherwise :rtype: bool """ marathon_client = marathon.create_client() apps = marathon_client.get_apps_for_framework(service_name) if apps: for app in apps: if (app_id is not None) and (app['id'] != "/{}".format(str(app_id))): continue if (app['tasksHealthy']) \ and (app['tasksRunning']) \ and (not app['tasksStaged']) \ and (not app['tasksUnhealthy']): return True return False
Check whether a named service is healthy :param service_name: the service name :type service_name: str :param app_id: app_id to filter :type app_id: str :return: True if healthy, False otherwise :rtype: bool
entailment
def delete_persistent_data(role, zk_node): """ Deletes any persistent data associated with the specified role, and zk node. :param role: the mesos role to delete, or None to omit this :type role: str :param zk_node: the zookeeper node to be deleted, or None to skip this deletion :type zk_node: str """ if role: destroy_volumes(role) unreserve_resources(role) if zk_node: delete_zk_node(zk_node)
Deletes any persistent data associated with the specified role, and zk node. :param role: the mesos role to delete, or None to omit this :type role: str :param zk_node: the zookeeper node to be deleted, or None to skip this deletion :type zk_node: str
entailment
def destroy_volumes(role): """ Destroys all volumes on all the slaves in the cluster for the role. """ state = dcos_agents_state() if not state or 'slaves' not in state.keys(): return False all_success = True for agent in state['slaves']: if not destroy_volume(agent, role): all_success = False return all_success
Destroys all volumes on all the slaves in the cluster for the role.
entailment
def destroy_volume(agent, role): """ Deletes the volumes on the specific agent for the role """ volumes = [] agent_id = agent['id'] reserved_resources_full = agent.get('reserved_resources_full', None) if not reserved_resources_full: # doesn't exist return True reserved_resources = reserved_resources_full.get(role, None) if not reserved_resources: # doesn't exist return True for reserved_resource in reserved_resources: name = reserved_resource.get('name', None) disk = reserved_resource.get('disk', None) if name == 'disk' and disk is not None and 'persistence' in disk: volumes.append(reserved_resource) req_url = urljoin(master_url(), 'destroy-volumes') data = { 'slaveId': agent_id, 'volumes': json.dumps(volumes) } success = False try: response = http.post(req_url, data=data) success = 200 <= response.status_code < 300 if response.status_code == 409: # thoughts on what to do here? throw exception # i would rather not print print('''###\nIs a framework using these resources still installed?\n###''') except DCOSHTTPException as e: print("HTTP {}: Unabled to delete volume based on: {}".format( e.response.status_code, e.response.text)) return success
Deletes the volumes on the specific agent for the role
entailment