text
stringlengths
81
112k
Turn a URL into an Avro-safe name. If the URL has no fragment, return this plain URL. Extract either the last part of the URL fragment past the slash, otherwise the whole fragment. def avro_name(url): # type: (AnyStr) -> AnyStr """ Turn a URL into an Avro-safe name. If the URL has no fragment, return this plain URL. Extract either the last part of the URL fragment past the slash, otherwise the whole fragment. """ frg = urllib.parse.urldefrag(url)[1] if frg != '': if '/' in frg: return frg[frg.rindex('/') + 1:] return frg return url
Convert our schema to be more avro like. def make_valid_avro(items, # type: Avro alltypes, # type: Dict[Text, Dict[Text, Any]] found, # type: Set[Text] union=False # type: bool ): # type: (...) -> Union[Avro, Dict, Text] """Convert our schema to be more avro like.""" # Possibly could be integrated into our fork of avro/schema.py? if isinstance(items, MutableMapping): items = copy.copy(items) if items.get("name") and items.get("inVocab", True): items["name"] = avro_name(items["name"]) if "type" in items and items["type"] in ( "https://w3id.org/cwl/salad#record", "https://w3id.org/cwl/salad#enum", "record", "enum"): if (hasattr(items, "get") and items.get("abstract")) or ("abstract" in items): return items if items["name"] in found: return cast(Text, items["name"]) found.add(items["name"]) for field in ("type", "items", "values", "fields"): if field in items: items[field] = make_valid_avro( items[field], alltypes, found, union=True) if "symbols" in items: items["symbols"] = [avro_name(sym) for sym in items["symbols"]] return items if isinstance(items, MutableSequence): ret = [] for i in items: ret.append(make_valid_avro(i, alltypes, found, union=union)) # type: ignore return ret if union and isinstance(items, string_types): if items in alltypes and avro_name(items) not in found: return cast(Dict, make_valid_avro(alltypes[items], alltypes, found, union=union)) items = avro_name(items) return items
Make a deep copy of list and dict objects. Intentionally do not copy attributes. This is to discard CommentedMap and CommentedSeq metadata which is very expensive with regular copy.deepcopy. def deepcopy_strip(item): # type: (Any) -> Any """ Make a deep copy of list and dict objects. Intentionally do not copy attributes. This is to discard CommentedMap and CommentedSeq metadata which is very expensive with regular copy.deepcopy. """ if isinstance(item, MutableMapping): return {k: deepcopy_strip(v) for k, v in iteritems(item)} if isinstance(item, MutableSequence): return [deepcopy_strip(k) for k in item] return item
Apply 'extend' and 'specialize' to fully materialize derived record types. def extend_and_specialize(items, loader): # type: (List[Dict[Text, Any]], Loader) -> List[Dict[Text, Any]] """ Apply 'extend' and 'specialize' to fully materialize derived record types. """ items = deepcopy_strip(items) types = {i["name"]: i for i in items} # type: Dict[Text, Any] results = [] for stype in items: if "extends" in stype: specs = {} # type: Dict[Text, Text] if "specialize" in stype: for spec in aslist(stype["specialize"]): specs[spec["specializeFrom"]] = spec["specializeTo"] exfields = [] # type: List[Text] exsym = [] # type: List[Text] for ex in aslist(stype["extends"]): if ex not in types: raise Exception( "Extends {} in {} refers to invalid base type.".format( stype["extends"], stype["name"])) basetype = copy.copy(types[ex]) if stype["type"] == "record": if specs: basetype["fields"] = replace_type( basetype.get("fields", []), specs, loader, set()) for field in basetype.get("fields", []): if "inherited_from" not in field: field["inherited_from"] = ex exfields.extend(basetype.get("fields", [])) elif stype["type"] == "enum": exsym.extend(basetype.get("symbols", [])) if stype["type"] == "record": stype = copy.copy(stype) exfields.extend(stype.get("fields", [])) stype["fields"] = exfields fieldnames = set() # type: Set[Text] for field in stype["fields"]: if field["name"] in fieldnames: raise validate.ValidationException( "Field name {} appears twice in {}".format( field["name"], stype["name"])) else: fieldnames.add(field["name"]) elif stype["type"] == "enum": stype = copy.copy(stype) exsym.extend(stype.get("symbols", [])) stype["symbol"] = exsym types[stype["name"]] = stype results.append(stype) ex_types = {} for result in results: ex_types[result["name"]] = result extended_by = {} # type: Dict[Text, Text] for result in results: if "extends" in result: for ex in aslist(result["extends"]): if ex_types[ex].get("abstract"): add_dictlist(extended_by, ex, ex_types[result["name"]]) add_dictlist(extended_by, avro_name(ex), ex_types[ex]) for result in results: if result.get("abstract") and result["name"] not in extended_by: raise validate.ValidationException( "{} is abstract but missing a concrete subtype".format( result["name"])) for result in results: if "fields" in result: result["fields"] = replace_type( result["fields"], extended_by, loader, set()) return results
All in one convenience function. Call make_avro() and make_avro_schema_from_avro() separately if you need the intermediate result for diagnostic output. def make_avro_schema(i, # type: List[Any] loader # type: Loader ): # type: (...) -> Names """ All in one convenience function. Call make_avro() and make_avro_schema_from_avro() separately if you need the intermediate result for diagnostic output. """ names = Names() avro = make_avro(i, loader) make_avsc_object(convert_to_dict(avro), names) return names
Returns the last segment of the provided fragment or path. def shortname(inputid): # type: (Text) -> Text """Returns the last segment of the provided fragment or path.""" parsed_id = urllib.parse.urlparse(inputid) if parsed_id.fragment: return parsed_id.fragment.split(u"/")[-1] return parsed_id.path.split(u"/")[-1]
Write a Grapviz inheritance graph for the supplied document. def print_inheritance(doc, stream): # type: (List[Dict[Text, Any]], IO) -> None """Write a Grapviz inheritance graph for the supplied document.""" stream.write("digraph {\n") for entry in doc: if entry["type"] == "record": label = name = shortname(entry["name"]) fields = entry.get("fields", []) if fields: label += "\\n* %s\\l" % ( "\\l* ".join(shortname(field["name"]) for field in fields)) shape = "ellipse" if entry.get("abstract") else "box" stream.write("\"%s\" [shape=%s label=\"%s\"];\n" % (name, shape, label)) if "extends" in entry: for target in aslist(entry["extends"]): stream.write("\"%s\" -> \"%s\";\n" % (shortname(target), name)) stream.write("}\n")
Write a GraphViz graph of the relationships between the fields. def print_fieldrefs(doc, loader, stream): # type: (List[Dict[Text, Any]], Loader, IO) -> None """Write a GraphViz graph of the relationships between the fields.""" obj = extend_and_specialize(doc, loader) primitives = set(("http://www.w3.org/2001/XMLSchema#string", "http://www.w3.org/2001/XMLSchema#boolean", "http://www.w3.org/2001/XMLSchema#int", "http://www.w3.org/2001/XMLSchema#long", "https://w3id.org/cwl/salad#null", "https://w3id.org/cwl/salad#enum", "https://w3id.org/cwl/salad#array", "https://w3id.org/cwl/salad#record", "https://w3id.org/cwl/salad#Any")) stream.write("digraph {\n") for entry in obj: if entry.get("abstract"): continue if entry["type"] == "record": label = shortname(entry["name"]) for field in entry.get("fields", []): found = set() # type: Set[Text] field_name = shortname(field["name"]) replace_type(field["type"], {}, loader, found, find_embeds=False) for each_type in found: if each_type not in primitives: stream.write( "\"%s\" -> \"%s\" [label=\"%s\"];\n" % (label, shortname(each_type), field_name)) stream.write("}\n")
Retrieve the non-reserved properties from a dictionary of properties @args reserved_props: The set of reserved properties to exclude def get_other_props(all_props, reserved_props): # type: (Dict, Tuple) -> Optional[Dict] """ Retrieve the non-reserved properties from a dictionary of properties @args reserved_props: The set of reserved properties to exclude """ if hasattr(all_props, 'items') and callable(all_props.items): return dict([(k,v) for (k,v) in list(all_props.items()) if k not in reserved_props]) return None
Build Avro Schema from data parsed out of JSON string. @arg names: A Name object (tracks seen names and default space) def make_avsc_object(json_data, names=None): # type: (Union[Dict[Text, Text], List[Any], Text], Optional[Names]) -> Schema """ Build Avro Schema from data parsed out of JSON string. @arg names: A Name object (tracks seen names and default space) """ if names is None: names = Names() assert isinstance(names, Names) # JSON object (non-union) if hasattr(json_data, 'get') and callable(json_data.get): # type: ignore assert isinstance(json_data, Dict) atype = cast(Text, json_data.get('type')) other_props = get_other_props(json_data, SCHEMA_RESERVED_PROPS) if atype in PRIMITIVE_TYPES: return PrimitiveSchema(atype, other_props) if atype in NAMED_TYPES: name = cast(Text, json_data.get('name')) namespace = cast(Text, json_data.get('namespace', names.default_namespace)) if atype == 'enum': symbols = cast(List[Text], json_data.get('symbols')) doc = json_data.get('doc') return EnumSchema(name, namespace, symbols, names, doc, other_props) if atype in ['record', 'error']: fields = cast(List, json_data.get('fields')) doc = json_data.get('doc') return RecordSchema(name, namespace, fields, names, atype, doc, other_props) raise SchemaParseException('Unknown Named Type: %s' % atype) if atype in VALID_TYPES: if atype == 'array': items = cast(List, json_data.get('items')) return ArraySchema(items, names, other_props) if atype is None: raise SchemaParseException('No "type" property: %s' % json_data) raise SchemaParseException('Undefined type: %s' % atype) # JSON array (union) if isinstance(json_data, list): return UnionSchema(json_data, names) # JSON string (primitive) if json_data in PRIMITIVE_TYPES: return PrimitiveSchema(cast(Text, json_data)) # not for us! fail_msg = "Could not make an Avro Schema object from %s." % json_data raise SchemaParseException(fail_msg)
Back out a namespace from full name. def get_space(self): # type: () -> Optional[Text] """Back out a namespace from full name.""" if self._full is None: return None if self._full.find('.') > 0: return self._full.rsplit(".", 1)[0] else: return ""
Add a new schema object to the name set. @arg name_attr: name value read in schema @arg space_attr: namespace value read in schema. @return: the Name that was just added. def add_name(self, name_attr, space_attr, new_schema): # type: (Text, Optional[Text], NamedSchema) -> Name """ Add a new schema object to the name set. @arg name_attr: name value read in schema @arg space_attr: namespace value read in schema. @return: the Name that was just added. """ to_add = Name(name_attr, space_attr, self.default_namespace) if to_add.fullname in VALID_TYPES: fail_msg = '%s is a reserved type name.' % to_add.fullname raise SchemaParseException(fail_msg) elif to_add.fullname in self.names: fail_msg = 'The name "%s" is already in use.' % to_add.fullname raise SchemaParseException(fail_msg) self.names[to_add.fullname] = new_schema return to_add
We're going to need to make message parameters too. def make_field_objects(field_data, names): # type: (List[Dict[Text, Text]], Names) -> List[Field] """We're going to need to make message parameters too.""" field_objects = [] field_names = [] # type: List[Text] for field in field_data: if hasattr(field, 'get') and callable(field.get): atype = cast(Text, field.get('type')) name = cast(Text, field.get('name')) # null values can have a default value of None has_default = False default = None if 'default' in field: has_default = True default = field.get('default') order = field.get('order') doc = field.get('doc') other_props = get_other_props(field, FIELD_RESERVED_PROPS) new_field = Field(atype, name, has_default, default, order, names, doc, other_props) # make sure field name has not been used yet if new_field.name in field_names: fail_msg = 'Field name %s already in use.' % new_field.name raise SchemaParseException(fail_msg) field_names.append(new_field.name) else: raise SchemaParseException('Not a valid field: %s' % field) field_objects.append(new_field) return field_objects
function to get links def search_function(root1, q, s, f, l, o='g'): """ function to get links """ global links links = search(q, o, s, f, l) root1.destroy() root1.quit()
to create loading progress bar def task(ft): """ to create loading progress bar """ ft.pack(expand = True, fill = BOTH, side = TOP) pb_hD = ttk.Progressbar(ft, orient = 'horizontal', mode = 'indeterminate') pb_hD.pack(expand = True, fill = BOTH, side = TOP) pb_hD.start(50) ft.mainloop()
function to fetch links and download them def download_content_gui(**args): """ function to fetch links and download them """ global row if not args ['directory']: args ['directory'] = args ['query'].replace(' ', '-') root1 = Frame(root) t1 = threading.Thread(target = search_function, args = (root1, args['query'], args['website'], args['file_type'], args['limit'],args['option'])) t1.start() task(root1) t1.join() #new frame for progress bar row = Frame(root) row.pack() if args['parallel']: download_parallel_gui(row, links, args['directory'], args['min_file_size'], args['max_file_size'], args['no_redirects']) else: download_series_gui(row, links, args['directory'], args['min_file_size'], args['max_file_size'], args['no_redirects'])
main function def main(): """ main function """ s = ttk.Style() s.theme_use('clam') ents = makeform(root) root.mainloop()
event for download button def click_download(self, event): """ event for download button """ args ['parallel'] = self.p.get() args ['file_type'] = self.optionmenu.get() args ['no_redirects'] = self.t.get() args ['query'] = self.entry_query.get() args ['min_file_size'] = int( self.entry_min.get()) args ['max_file_size'] = int( self.entry_max.get()) args ['limit'] = int( self.entry_limit.get()) args ['website']= self.entry_website.get() args ['option']= self.engine.get() print(args) self.check_threat() download_content_gui( **args )
function that gets called whenever entry is clicked def on_entry_click(self, event): """ function that gets called whenever entry is clicked """ if event.widget.config('fg') [4] == 'grey': event.widget.delete(0, "end" ) # delete all the text in the entry event.widget.insert(0, '') #Insert blank for user input event.widget.config(fg = 'black')
function that gets called whenever anywhere except entry is clicked def on_focusout(self, event, a): """ function that gets called whenever anywhere except entry is clicked """ if event.widget.get() == '': event.widget.insert(0, default_text[a]) event.widget.config(fg = 'grey')
function to check input filetype against threat extensions list def check_threat(self): """ function to check input filetype against threat extensions list """ is_high_threat = False for val in THREAT_EXTENSIONS.values(): if type(val) == list: for el in val: if self.optionmenu.get() == el: is_high_threat = True break else: if self.optionmenu.get() == val: is_high_threat = True break if is_high_threat == True: is_high_threat = not askokcancel('FILE TYPE', 'WARNING: Downloading this \ file type may expose you to a heightened security risk.\nPress\ "OK" to proceed or "CANCEL" to exit') return not is_high_threat
dialogue box for choosing directory def ask_dir(self): """ dialogue box for choosing directory """ args ['directory'] = askdirectory(**self.dir_opt) self.dir_text.set(args ['directory'])
function to fetch links equal to limit every Google search result page has a start index. every page contains 10 search results. def get_google_links(limit, params, headers): """ function to fetch links equal to limit every Google search result page has a start index. every page contains 10 search results. """ links = [] for start_index in range(0, limit, 10): params['start'] = start_index resp = s.get("https://www.google.com/search", params = params, headers = headers) page_links = scrape_links(resp.content, engine = 'g') links.extend(page_links) return links[:limit]
function to fetch links equal to limit duckduckgo pagination is not static, so there is a limit on maximum number of links that can be scraped def get_duckduckgo_links(limit, params, headers): """ function to fetch links equal to limit duckduckgo pagination is not static, so there is a limit on maximum number of links that can be scraped """ resp = s.get('https://duckduckgo.com/html', params = params, headers = headers) links = scrape_links(resp.content, engine = 'd') return links[:limit]
function to scrape file links from html response def scrape_links(html, engine): """ function to scrape file links from html response """ soup = BeautifulSoup(html, 'lxml') links = [] if engine == 'd': results = soup.findAll('a', {'class': 'result__a'}) for result in results: link = result.get('href')[15:] link = link.replace('/blob/', '/raw/') links.append(link) elif engine == 'g': results = soup.findAll('h3', {'class': 'r'}) for result in results: link = result.a['href'][7:].split('&')[0] link = link.replace('/blob/', '/raw/') links.append(link) return links
function to get return code of a url Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/ def get_url_nofollow(url): """ function to get return code of a url Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/ """ try: response = urlopen(url) code = response.getcode() return code except HTTPError as e: return e.code except: return 0
function to validate urls based on http(s) prefix and return code def validate_links(links): """ function to validate urls based on http(s) prefix and return code """ valid_links = [] for link in links: if link[:7] in "http://" or link[:8] in "https://": valid_links.append(link) if not valid_links: print("No files found.") sys.exit(0) # checking valid urls for return code urls = {} for link in valid_links: if 'github.com' and '/blob/' in link: link = link.replace('/blob/', '/raw/') urls[link] = {'code': get_url_nofollow(link)} # printing valid urls with return code 200 available_urls = [] for url in urls: print("code: %d\turl: %s" % (urls[url]['code'], url)) if urls[url]['code'] != 0: available_urls.append(url) return available_urls
main function to search for links and return valid ones def search(query, engine='g', site="", file_type = 'pdf', limit = 10): """ main function to search for links and return valid ones """ if site == "": search_query = "filetype:{0} {1}".format(file_type, query) else: search_query = "site:{0} filetype:{1} {2}".format(site,file_type, query) headers = { 'User Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) \ Gecko/20100101 Firefox/53.0' } if engine == "g": params = { 'q': search_query, 'start': 0, } links = get_google_links(limit, params, headers) elif engine == "d": params = { 'q': search_query, } links = get_duckduckgo_links(limit,params,headers) else: print("Wrong search engine selected!") sys.exit() valid_links = validate_links(links) return valid_links
function to check input filetype against threat extensions list def check_threats(**args): """ function to check input filetype against threat extensions list """ is_high_threat = False for val in THREAT_EXTENSIONS.values(): if type(val) == list: for el in val: if args['file_type'] == el: is_high_threat = True break else: if args['file_type'] == val: is_high_threat = True break return is_high_threat
function to check if input query is not None and set missing arguments to default value def validate_args(**args): """ function to check if input query is not None and set missing arguments to default value """ if not args['query']: print("\nMissing required query argument.") sys.exit() for key in DEFAULTS: if key not in args: args[key] = DEFAULTS[key] return args
main function to fetch links and download them def download_content(**args): """ main function to fetch links and download them """ args = validate_args(**args) if not args['directory']: args['directory'] = args['query'].replace(' ', '-') print("Downloading {0} {1} files on topic {2} from {3} and saving to directory: {4}" .format(args['limit'], args['file_type'], args['query'], args['website'], args['directory'])) links = search(args['query'], args['engine'], args['website'], args['file_type'], args['limit']) if args['parallel']: download_parallel(links, args['directory'], args['min_file_size'], args['max_file_size'], args['no_redirects']) else: download_series(links, args['directory'], args['min_file_size'], args['max_file_size'], args['no_redirects'])
function to show valid file extensions def show_filetypes(extensions): """ function to show valid file extensions """ for item in extensions.items(): val = item[1] if type(item[1]) == list: val = ", ".join(str(x) for x in item[1]) print("{0:4}: {1}".format(val, item[0]))
Determine if a python datum is an instance of a schema. def validate_ex(expected_schema, # type: Schema datum, # type: Any identifiers=None, # type: List[Text] strict=False, # type: bool foreign_properties=None, # type: Set[Text] raise_ex=True, # type: bool strict_foreign_properties=False, # type: bool logger=_logger, # type: logging.Logger skip_foreign_properties=False # type: bool ): # type: (...) -> bool """Determine if a python datum is an instance of a schema.""" if not identifiers: identifiers = [] if not foreign_properties: foreign_properties = set() schema_type = expected_schema.type if schema_type == 'null': if datum is None: return True else: if raise_ex: raise ValidationException(u"the value is not null") else: return False elif schema_type == 'boolean': if isinstance(datum, bool): return True else: if raise_ex: raise ValidationException(u"the value is not boolean") else: return False elif schema_type == 'string': if isinstance(datum, six.string_types): return True elif isinstance(datum, bytes): datum = datum.decode(u"utf-8") return True else: if raise_ex: raise ValidationException(u"the value is not string") else: return False elif schema_type == 'int': if (isinstance(datum, six.integer_types) and INT_MIN_VALUE <= datum <= INT_MAX_VALUE): return True else: if raise_ex: raise ValidationException(u"`%s` is not int" % vpformat(datum)) else: return False elif schema_type == 'long': if ((isinstance(datum, six.integer_types)) and LONG_MIN_VALUE <= datum <= LONG_MAX_VALUE): return True else: if raise_ex: raise ValidationException( u"the value `%s` is not long" % vpformat(datum)) else: return False elif schema_type in ['float', 'double']: if (isinstance(datum, six.integer_types) or isinstance(datum, float)): return True else: if raise_ex: raise ValidationException( u"the value `%s` is not float or double" % vpformat(datum)) else: return False elif isinstance(expected_schema, avro.schema.EnumSchema): if expected_schema.name == "Any": if datum is not None: return True else: if raise_ex: raise ValidationException(u"'Any' type must be non-null") else: return False if not isinstance(datum, six.string_types): if raise_ex: raise ValidationException( u"value is a %s but expected a string" % (type(datum).__name__)) else: return False if expected_schema.name == "Expression": if "$(" in datum or "${" in datum: return True if raise_ex: raise ValidationException(u"value `%s` does not contain an expression in the form $() or ${}" % datum) else: return False if datum in expected_schema.symbols: return True else: if raise_ex: raise ValidationException(u"the value %s is not a valid %s, expected %s%s" % (vpformat(datum), expected_schema.name, "one of " if len( expected_schema.symbols) > 1 else "", "'" + "', '".join(expected_schema.symbols) + "'")) else: return False elif isinstance(expected_schema, avro.schema.ArraySchema): if isinstance(datum, MutableSequence): for i, d in enumerate(datum): try: sl = SourceLine(datum, i, ValidationException) if not validate_ex(expected_schema.items, d, identifiers, strict=strict, foreign_properties=foreign_properties, raise_ex=raise_ex, strict_foreign_properties=strict_foreign_properties, logger=logger, skip_foreign_properties=skip_foreign_properties): return False except ValidationException as v: if raise_ex: raise sl.makeError( six.text_type("item is invalid because\n%s" % (indent(str(v))))) else: return False return True else: if raise_ex: raise ValidationException(u"the value %s is not a list, expected list of %s" % ( vpformat(datum), friendly(expected_schema.items))) else: return False elif isinstance(expected_schema, avro.schema.UnionSchema): for s in expected_schema.schemas: if validate_ex(s, datum, identifiers, strict=strict, raise_ex=False, strict_foreign_properties=strict_foreign_properties, logger=logger, skip_foreign_properties=skip_foreign_properties): return True if not raise_ex: return False errors = [] # type: List[Text] checked = [] for s in expected_schema.schemas: if isinstance(datum, MutableSequence) and not isinstance(s, avro.schema.ArraySchema): continue elif isinstance(datum, MutableMapping) and not isinstance(s, avro.schema.RecordSchema): continue elif (isinstance( # type: ignore datum, (bool, six.integer_types, float, six.string_types)) and isinstance(s, (avro.schema.ArraySchema, avro.schema.RecordSchema))): continue elif datum is not None and s.type == "null": continue checked.append(s) try: validate_ex(s, datum, identifiers, strict=strict, foreign_properties=foreign_properties, raise_ex=True, strict_foreign_properties=strict_foreign_properties, logger=logger, skip_foreign_properties=skip_foreign_properties) except ClassValidationException as e: raise except ValidationException as e: errors.append(six.text_type(e)) if bool(errors): raise ValidationException(bullets(["tried %s but\n%s" % (friendly( checked[i]), indent(errors[i])) for i in range(0, len(errors))], "- ")) else: raise ValidationException("value is a %s, expected %s" % ( type(datum).__name__, friendly(expected_schema))) elif isinstance(expected_schema, avro.schema.RecordSchema): if not isinstance(datum, MutableMapping): if raise_ex: raise ValidationException(u"is not a dict") else: return False classmatch = None for f in expected_schema.fields: if f.name in ("class",): d = datum.get(f.name) if not d: if raise_ex: raise ValidationException( u"Missing '%s' field" % (f.name)) else: return False if expected_schema.name != d: if raise_ex: raise ValidationException( u"Expected class '%s' but this is '%s'" % (expected_schema.name, d)) else: return False classmatch = d break errors = [] for f in expected_schema.fields: if f.name in ("class",): continue if f.name in datum: fieldval = datum[f.name] else: try: fieldval = f.default except KeyError: fieldval = None try: sl = SourceLine(datum, f.name, six.text_type) if not validate_ex(f.type, fieldval, identifiers, strict=strict, foreign_properties=foreign_properties, raise_ex=raise_ex, strict_foreign_properties=strict_foreign_properties, logger=logger, skip_foreign_properties=skip_foreign_properties): return False except ValidationException as v: if f.name not in datum: errors.append(u"missing required field `%s`" % f.name) else: errors.append(sl.makeError(u"the `%s` field is not valid because\n%s" % ( f.name, indent(str(v))))) for d in datum: found = False for f in expected_schema.fields: if d == f.name: found = True if not found: sl = SourceLine(datum, d, six.text_type) if d not in identifiers and d not in foreign_properties and d[0] not in ("@", "$"): if (d not in identifiers and strict) and ( d not in foreign_properties and strict_foreign_properties and not skip_foreign_properties) and not raise_ex: return False split = urllib.parse.urlsplit(d) if split.scheme: if not skip_foreign_properties: err = sl.makeError(u"unrecognized extension field `%s`%s.%s" % (d, " and strict_foreign_properties checking is enabled" if strict_foreign_properties else "", "\nForeign properties from $schemas:\n %s" % "\n ".join(sorted(foreign_properties)) if len(foreign_properties) > 0 else "")) if strict_foreign_properties: errors.append(err) elif len(foreign_properties) > 0: logger.warning(strip_dup_lineno(err)) else: err = sl.makeError(u"invalid field `%s`, expected one of: %s" % ( d, ", ".join("'%s'" % fn.name for fn in expected_schema.fields))) if strict: errors.append(err) else: logger.warning(err) if bool(errors): if raise_ex: if classmatch: raise ClassValidationException(bullets(errors, "* ")) else: raise ValidationException(bullets(errors, "* ")) else: return False else: return True if raise_ex: raise ValidationException(u"Unrecognized schema_type %s" % schema_type) else: return False
Force use of unicode. def json_dump(obj, # type: Any fp, # type: IO[str] **kwargs # type: Any ): # type: (...) -> None """ Force use of unicode. """ if six.PY2: kwargs['encoding'] = 'utf-8' json.dump(convert_to_dict(obj), fp, **kwargs)
Force use of unicode. def json_dumps(obj, # type: Any **kwargs # type: Any ): # type: (...) -> str """ Force use of unicode. """ if six.PY2: kwargs['encoding'] = 'utf-8' return json.dumps(convert_to_dict(obj), **kwargs)
Generate classes with loaders for the given Schema Salad description. def codegen(lang, # type: str i, # type: List[Dict[Text, Any]] schema_metadata, # type: Dict[Text, Any] loader # type: Loader ): # type: (...) -> None """Generate classes with loaders for the given Schema Salad description.""" j = schema.extend_and_specialize(i, loader) gen = None # type: Optional[CodeGenBase] if lang == "python": gen = PythonCodeGen(sys.stdout) elif lang == "java": gen = JavaCodeGen(schema_metadata.get("$base", schema_metadata.get("id"))) else: raise Exception("Unsupported code generation language '%s'" % lang) assert gen is not None gen.prologue() document_roots = [] for rec in j: if rec["type"] in ("enum", "record"): gen.type_loader(rec) gen.add_vocab(shortname(rec["name"]), rec["name"]) for rec in j: if rec["type"] == "enum": for symbol in rec["symbols"]: gen.add_vocab(shortname(symbol), symbol) if rec["type"] == "record": if rec.get("documentRoot"): document_roots.append(rec["name"]) field_names = [] for field in rec.get("fields", []): field_names.append(shortname(field["name"])) idfield = "" for field in rec.get("fields", []): if field.get("jsonldPredicate") == "@id": idfield = field.get("name") gen.begin_class(rec["name"], aslist(rec.get("extends", [])), rec.get("doc", ""), rec.get("abstract", False), field_names, idfield) gen.add_vocab(shortname(rec["name"]), rec["name"]) for field in rec.get("fields", []): if field.get("jsonldPredicate") == "@id": fieldpred = field["name"] optional = bool("https://w3id.org/cwl/salad#null" in field["type"]) uri_loader = gen.uri_loader(gen.type_loader(field["type"]), True, False, None) gen.declare_id_field(fieldpred, uri_loader, field.get("doc"), optional) break for field in rec.get("fields", []): optional = bool("https://w3id.org/cwl/salad#null" in field["type"]) type_loader = gen.type_loader(field["type"]) jld = field.get("jsonldPredicate") fieldpred = field["name"] if isinstance(jld, MutableMapping): ref_scope = jld.get("refScope") if jld.get("typeDSL"): type_loader = gen.typedsl_loader(type_loader, ref_scope) elif jld.get("_type") == "@id": type_loader = gen.uri_loader(type_loader, jld.get("identity", False), False, ref_scope) elif jld.get("_type") == "@vocab": type_loader = gen.uri_loader(type_loader, False, True, ref_scope) map_subject = jld.get("mapSubject") if map_subject: type_loader = gen.idmap_loader( field["name"], type_loader, map_subject, jld.get("mapPredicate")) if "_id" in jld and jld["_id"][0] != "@": fieldpred = jld["_id"] if jld == "@id": continue gen.declare_field(fieldpred, type_loader, field.get("doc"), optional) gen.end_class(rec["name"], field_names) root_type = list(document_roots) root_type.append({ "type": "array", "items": document_roots }) gen.epilogue(gen.type_loader(root_type))
Return a list of subset of VM that match the pattern name @param name (str): the vm name of the virtual machine @param name (Obj): the vm object that represent the virtual machine (can be Pro or Smart) @return (list): the subset containing the serach result. def find(self, name): """ Return a list of subset of VM that match the pattern name @param name (str): the vm name of the virtual machine @param name (Obj): the vm object that represent the virtual machine (can be Pro or Smart) @return (list): the subset containing the serach result. """ if name.__class__ is 'base.Server.Pro' or name.__class__ is 'base.Server.Smart': # print('DEBUG: matched VM object %s' % name.__class__) pattern = name.vm_name else: # print('DEBUG: matched Str Object %s' % name.__class__) pattern = name # 14/06/2013: since this method is called within a thread and I wont to pass the return objects with queue or # call back, I will allocate a list inside the Interface class object itself, which contain all of the vm found # 02/11/2015: this must be changed ASAP! it's a mess this way... what was I thinking?? self.last_search_result = [vm for vm in self if pattern in vm.vm_name] return self.last_search_result
Reinitialize a VM. :param admin_password: Administrator password. :param debug: Flag to enable debug output. :param ConfigureIPv6: Flag to enable IPv6 on the VM. :param OSTemplateID: TemplateID to reinitialize the VM with. :return: True in case of success, otherwise False :type admin_password: str :type debug: bool :type ConfigureIPv6: bool :type OSTemplateID: int def reinitialize(self, admin_password=None, debug=False, ConfigureIPv6=False, OSTemplateID=None): """ Reinitialize a VM. :param admin_password: Administrator password. :param debug: Flag to enable debug output. :param ConfigureIPv6: Flag to enable IPv6 on the VM. :param OSTemplateID: TemplateID to reinitialize the VM with. :return: True in case of success, otherwise False :type admin_password: str :type debug: bool :type ConfigureIPv6: bool :type OSTemplateID: int """ data = dict( AdministratorPassword=admin_password, ServerId=self.sid, ConfigureIPv6=ConfigureIPv6 ) if OSTemplateID is not None: data.update(OSTemplateID=OSTemplateID) assert data['AdministratorPassword'] is not None, 'Error reinitializing VM: no admin password specified.' assert data['ServerId'] is not None, 'Error reinitializing VM: no Server Id specified.' json_scheme = self.interface.gen_def_json_scheme('SetEnqueueReinitializeServer', method_fields=data) json_obj = self.interface.call_method_post('SetEnqueueReinitializeServer', json_scheme=json_scheme, debug=debug) return True if json_obj['Success'] is 'True' else False
Set the authentication data in the object, and if load is True (default is True) it also retrieve the ip list and the vm list in order to build the internal objects list. @param (str) username: username of the cloud @param (str) password: password of the cloud @param (bool) load: define if pre cache the objects. @return: None def login(self, username, password, load=True): """ Set the authentication data in the object, and if load is True (default is True) it also retrieve the ip list and the vm list in order to build the internal objects list. @param (str) username: username of the cloud @param (str) password: password of the cloud @param (bool) load: define if pre cache the objects. @return: None """ self.auth = Auth(username, password) if load is True: self.get_ip() self.get_servers()
Poweroff a VM. If possible to pass the VM object or simply the ID of the VM that we want to turn on. Args: server: VM Object that represent the VM to power off, server_id: Int or Str representing the ID of the VM to power off. Returns: return True if json_obj['Success'] is 'True' else False def poweroff_server(self, server=None, server_id=None): """ Poweroff a VM. If possible to pass the VM object or simply the ID of the VM that we want to turn on. Args: server: VM Object that represent the VM to power off, server_id: Int or Str representing the ID of the VM to power off. Returns: return True if json_obj['Success'] is 'True' else False """ sid = server_id if server_id is not None else server.sid if sid is None: raise Exception('No Server Specified.') json_scheme = self.gen_def_json_scheme('SetEnqueueServerPowerOff', dict(ServerId=sid)) json_obj = self.call_method_post('SetEnqueueServerPowerOff', json_scheme=json_scheme) return True if json_obj['Success'] is 'True' else False
Initialize the internal list containing each template available for each hypervisor. :return: [bool] True in case of success, otherwise False def get_hypervisors(self): """ Initialize the internal list containing each template available for each hypervisor. :return: [bool] True in case of success, otherwise False """ json_scheme = self.gen_def_json_scheme('GetHypervisors') json_obj = self.call_method_post(method='GetHypervisors', json_scheme=json_scheme) self.json_templates = json_obj d = dict(json_obj) for elem in d['Value']: hv = self.hypervisors[elem['HypervisorType']] for inner_elem in elem['Templates']: o = Template(hv) o.template_id = inner_elem['Id'] o.descr = inner_elem['Description'] o.id_code = inner_elem['IdentificationCode'] o.name = inner_elem['Name'] o.enabled = inner_elem['Enabled'] if hv != 'SMART': for rb in inner_elem['ResourceBounds']: resource_type = rb['ResourceType'] if resource_type == 1: o.resource_bounds.max_cpu = rb['Max'] if resource_type == 2: o.resource_bounds.max_memory = rb['Max'] if resource_type == 3: o.resource_bounds.hdd0 = rb['Max'] if resource_type == 7: o.resource_bounds.hdd1 = rb['Max'] if resource_type == 8: o.resource_bounds.hdd2 = rb['Max'] if resource_type == 9: o.resource_bounds.hdd3 = rb['Max'] self.templates.append(o) return True if json_obj['Success'] is 'True' else False
Create the list of Server object inside the Datacenter objects. Build an internal list of VM Objects (pro or smart) as iterator. :return: bool def get_servers(self): """ Create the list of Server object inside the Datacenter objects. Build an internal list of VM Objects (pro or smart) as iterator. :return: bool """ json_scheme = self.gen_def_json_scheme('GetServers') json_obj = self.call_method_post(method='GetServers', json_scheme=json_scheme) self.json_servers = json_obj # if this method is called I assume that i must re-read the data # so i reinitialize the vmlist self.vmlist = VMList() # getting all instanced IP in case the list is empty if len(self.iplist) <= 0: self.get_ip() for elem in dict(json_obj)["Value"]: if elem['HypervisorType'] is 4: s = Smart(interface=self, sid=elem['ServerId']) else: s = Pro(interface=self, sid=elem['ServerId']) s.vm_name = elem['Name'] s.cpu_qty = elem['CPUQuantity'] s.ram_qty = elem['RAMQuantity'] s.status = elem['ServerStatus'] s.datacenter_id = elem['DatacenterId'] s.wcf_baseurl = self.wcf_baseurl s.auth = self.auth s.hd_qty = elem['HDQuantity'] s.hd_total_size = elem['HDTotalSize'] if elem['HypervisorType'] is 4: ssd = self.get_server_detail(elem['ServerId']) try: s.ip_addr = str(ssd['EasyCloudIPAddress']['Value']) except TypeError: s.ip_addr = 'Not retrieved.' else: s.ip_addr = [] for ip in self.iplist: if ip.serverid == s.sid: s.ip_addr.append(ip) self.vmlist.append(s) return True if json_obj['Success'] is True else False
Return a list of templates that could have one or more elements. Args: name: name of the template to find. hv: the ID of the hypervisor to search the template in Returns: A list of templates object. If hv is None will return all the templates matching the name if every hypervisor type. Otherwise if name is None will return all templates of an hypervisor. Raises: ValidationError: if name and hv are None def find_template(self, name=None, hv=None): """ Return a list of templates that could have one or more elements. Args: name: name of the template to find. hv: the ID of the hypervisor to search the template in Returns: A list of templates object. If hv is None will return all the templates matching the name if every hypervisor type. Otherwise if name is None will return all templates of an hypervisor. Raises: ValidationError: if name and hv are None """ if len(self.templates) <= 0: self.get_hypervisors() if name is not None and hv is not None: template_list = filter( lambda x: name in x.descr and x.hypervisor == self.hypervisors[hv], self.templates ) elif name is not None and hv is None: template_list = filter( lambda x: name in x.descr, self.templates ) elif name is None and hv is not None: template_list = filter( lambda x: x.hypervisor == self.hypervisors[hv], self.templates ) else: raise Exception('Error, no pattern defined') if sys.version_info.major < (3): return template_list else: return(list(template_list))
Return an ip object representing a new bought IP @param debug [Boolean] if true, request and response will be printed @return (Ip): Ip object def purchase_ip(self, debug=False): """ Return an ip object representing a new bought IP @param debug [Boolean] if true, request and response will be printed @return (Ip): Ip object """ json_scheme = self.gen_def_json_scheme('SetPurchaseIpAddress') json_obj = self.call_method_post(method='SetPurchaseIpAddress', json_scheme=json_scheme, debug=debug) try: ip = Ip() ip.ip_addr = json_obj['Value']['Value'] ip.resid = json_obj['Value']['ResourceId'] return ip except: raise Exception('Unknown error retrieving IP.')
Purchase a new VLAN. :param debug: Log the json response if True :param vlan_name: String representing the name of the vlan (virtual switch) :return: a Vlan Object representing the vlan created def purchase_vlan(self, vlan_name, debug=False): """ Purchase a new VLAN. :param debug: Log the json response if True :param vlan_name: String representing the name of the vlan (virtual switch) :return: a Vlan Object representing the vlan created """ vlan_name = {'VLanName': vlan_name} json_scheme = self.gen_def_json_scheme('SetPurchaseVLan', vlan_name) json_obj = self.call_method_post(method="SetPurchaseVLan", json_scheme=json_scheme) if debug is True: self.logger.debug(json_obj) if json_obj['Success'] is False: raise Exception("Cannot purchase new vlan.") vlan = Vlan() vlan.name = json_obj['Value']['Name'] vlan.resource_id = json_obj['Value']['ResourceId'] vlan.vlan_code = json_obj['Value']['VlanCode'] return vlan
Remove a VLAN :param vlan_resource_id: :return: def remove_vlan(self, vlan_resource_id): """ Remove a VLAN :param vlan_resource_id: :return: """ vlan_id = {'VLanResourceId': vlan_resource_id} json_scheme = self.gen_def_json_scheme('SetRemoveVLan', vlan_id) json_obj = self.call_method_post(method='SetRemoveVLan', json_scheme=json_scheme) return True if json_obj['Success'] is True else False
Delete an Ip from the boughs ip list @param (str) ip_id: a string representing the resource id of the IP @return: True if json method had success else False def remove_ip(self, ip_id): """ Delete an Ip from the boughs ip list @param (str) ip_id: a string representing the resource id of the IP @return: True if json method had success else False """ ip_id = ' "IpAddressResourceId": %s' % ip_id json_scheme = self.gen_def_json_scheme('SetRemoveIpAddress', ip_id) json_obj = self.call_method_post(method='SetRemoveIpAddress', json_scheme=json_scheme) pprint(json_obj) return True if json_obj['Success'] is True else False
Retrieve the smart package id given is English name @param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large". @return: The package id that depends on the Data center and the size choosen. def get_package_id(self, name): """ Retrieve the smart package id given is English name @param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large". @return: The package id that depends on the Data center and the size choosen. """ json_scheme = self.gen_def_json_scheme('GetPreConfiguredPackages', dict(HypervisorType=4)) json_obj = self.call_method_post(method='GetPreConfiguredPackages ', json_scheme=json_scheme) for package in json_obj['Value']: packageId = package['PackageID'] for description in package['Descriptions']: languageID = description['LanguageID'] packageName = description['Text'] if languageID == 2 and packageName.lower() == name.lower(): return packageId
Retrieve a complete list of bought ip address related only to PRO Servers. It create an internal object (Iplist) representing all of the ips object iterated form the WS. @param: None @return: None def get_ip(self): """ Retrieve a complete list of bought ip address related only to PRO Servers. It create an internal object (Iplist) representing all of the ips object iterated form the WS. @param: None @return: None """ json_scheme = self.gen_def_json_scheme('GetPurchasedIpAddresses') json_obj = self.call_method_post(method='GetPurchasedIpAddresses ', json_scheme=json_scheme) self.iplist = IpList() for ip in json_obj['Value']: r = Ip() r.ip_addr = ip['Value'] r.resid = ip['ResourceId'] r.serverid = ip['ServerId'] if 'None' not in str(ip['ServerId']) else None self.iplist.append(r)
Generate the scheme for the json request. :param req: String representing the name of the method to call :param method_fields: A dictionary containing the method-specified fields :rtype : json object representing the method call def gen_def_json_scheme(self, req, method_fields=None): """ Generate the scheme for the json request. :param req: String representing the name of the method to call :param method_fields: A dictionary containing the method-specified fields :rtype : json object representing the method call """ json_dict = dict( ApplicationId=req, RequestId=req, SessionId=req, Password=self.auth.password, Username=self.auth.username ) if method_fields is not None: json_dict.update(method_fields) self.logger.debug(json.dumps(json_dict)) return json.dumps(json_dict)
:return: (dict) Response object content def _commit(self): """ :return: (dict) Response object content """ assert self.uri is not None, Exception("BadArgument: uri property cannot be None") url = '{}/{}'.format(self.uri, self.__class__.__name__) serialized_json = jsonpickle.encode(self, unpicklable=False, ) headers = {'Content-Type': 'application/json', 'Content-Length': str(len(serialized_json))} response = Http.post(url=url, data=serialized_json, headers=headers) if response.status_code != 200: from ArubaCloud.base.Errors import MalformedJsonRequest raise MalformedJsonRequest("Request: {}, Status Code: {}".format(serialized_json, response.status_code)) content = jsonpickle.decode(response.content.decode("utf-8")) if content['ResultCode'] == 17: from ArubaCloud.base.Errors import OperationAlreadyEnqueued raise OperationAlreadyEnqueued("{} already enqueued".format(self.__class__.__name__)) if content['Success'] is False: from ArubaCloud.base.Errors import RequestFailed raise RequestFailed("Request: {}, Response: {}".format(serialized_json, response.content)) return content
Retrieve the current configured SharedStorages entries :return: [list] List containing the current SharedStorages entries def get(self): """ Retrieve the current configured SharedStorages entries :return: [list] List containing the current SharedStorages entries """ request = self._call(GetSharedStorages) response = request.commit() return response['Value']
:type quantity: int :type iqn: list[str] :type name: str :type protocol: SharedStorageProtocols :param quantity: Amount of GB :param iqn: List of IQN represented in string format :param name: Name of the resource :param protocol: Protocol to use :return: def purchase_iscsi(self, quantity, iqn, name, protocol=SharedStorageProtocolType.ISCSI): """ :type quantity: int :type iqn: list[str] :type name: str :type protocol: SharedStorageProtocols :param quantity: Amount of GB :param iqn: List of IQN represented in string format :param name: Name of the resource :param protocol: Protocol to use :return: """ iqns = [] for _iqn in iqn: iqns.append(SharedStorageIQN(Value=_iqn)) request = self._call(SetEnqueuePurchaseSharedStorage, Quantity=quantity, SharedStorageName=name, SharedStorageIQNs=iqns, SharedStorageProtocolType=protocol) response = request.commit() return response['Value']
Wrapper around Requests for GET requests Returns: Response: A Requests Response object def _get(self, *args, **kwargs): """Wrapper around Requests for GET requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.get(*args, **kwargs) return req
Wrapper around Requests for GET XML requests Returns: Response: A Requests Response object def _get_xml(self, *args, **kwargs): """Wrapper around Requests for GET XML requests Returns: Response: A Requests Response object """ req = self.session_xml.get(*args, **kwargs) return req
Wrapper around Requests for POST requests Returns: Response: A Requests Response object def _post(self, *args, **kwargs): """Wrapper around Requests for POST requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.post(*args, **kwargs) return req
Wrapper around Requests for POST requests Returns: Response: A Requests Response object def _post_xml(self, *args, **kwargs): """Wrapper around Requests for POST requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session_xml.post(*args, **kwargs) return req
Wrapper around Requests for PUT requests Returns: Response: A Requests Response object def _put(self, *args, **kwargs): """Wrapper around Requests for PUT requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.put(*args, **kwargs) return req
Wrapper around Requests for DELETE requests Returns: Response: A Requests Response object def _delete(self, *args, **kwargs): """Wrapper around Requests for DELETE requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.delete(*args, **kwargs) return req
Test that application can authenticate to Crowd. Attempts to authenticate the application user against the Crowd server. In order for user authentication to work, an application must be able to authenticate. Returns: bool: True if the application authentication succeeded. def auth_ping(self): """Test that application can authenticate to Crowd. Attempts to authenticate the application user against the Crowd server. In order for user authentication to work, an application must be able to authenticate. Returns: bool: True if the application authentication succeeded. """ url = self.rest_url + "/non-existent/location" response = self._get(url) if response.status_code == 401: return False elif response.status_code == 404: return True else: # An error encountered - problem with the Crowd server? return False
Authenticate a user account against the Crowd server. Attempts to authenticate the user against the Crowd server. Args: username: The account username. password: The account password. Returns: dict: A dict mapping of user attributes if the application authentication was successful. See the Crowd documentation for the authoritative list of attributes. None: If authentication failed. def auth_user(self, username, password): """Authenticate a user account against the Crowd server. Attempts to authenticate the user against the Crowd server. Args: username: The account username. password: The account password. Returns: dict: A dict mapping of user attributes if the application authentication was successful. See the Crowd documentation for the authoritative list of attributes. None: If authentication failed. """ response = self._post(self.rest_url + "/authentication", data=json.dumps({"value": password}), params={"username": username}) # If authentication failed for any reason return None if not response.ok: return None # ...otherwise return a dictionary of user attributes return response.json()
Create a session for a user. Attempts to create a user session on the Crowd server. Args: username: The account username. password: The account password. remote: The remote address of the user. This can be used to create multiple concurrent sessions for a user. The host you run this program on may need to be configured in Crowd as a trusted proxy for this to work. proxy: Value of X-Forwarded-For server header. Returns: dict: A dict mapping of user attributes if the application authentication was successful. See the Crowd documentation for the authoritative list of attributes. None: If authentication failed. def get_session(self, username, password, remote="127.0.0.1", proxy=None): """Create a session for a user. Attempts to create a user session on the Crowd server. Args: username: The account username. password: The account password. remote: The remote address of the user. This can be used to create multiple concurrent sessions for a user. The host you run this program on may need to be configured in Crowd as a trusted proxy for this to work. proxy: Value of X-Forwarded-For server header. Returns: dict: A dict mapping of user attributes if the application authentication was successful. See the Crowd documentation for the authoritative list of attributes. None: If authentication failed. """ params = { "username": username, "password": password, "validation-factors": { "validationFactors": [ {"name": "remote_address", "value": remote, }, ] } } if proxy: params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, }) response = self._post(self.rest_url + "/session", data=json.dumps(params), params={"expand": "user"}) # If authentication failed for any reason return None if not response.ok: return None # Otherwise return the user object return response.json()
Validate a session token. Validate a previously acquired session token against the Crowd server. This may be a token provided by a user from a http cookie or by some other means. Args: token: The session token. remote: The remote address of the user. proxy: Value of X-Forwarded-For server header Returns: dict: A dict mapping of user attributes if the application authentication was successful. See the Crowd documentation for the authoritative list of attributes. None: If authentication failed. def validate_session(self, token, remote="127.0.0.1", proxy=None): """Validate a session token. Validate a previously acquired session token against the Crowd server. This may be a token provided by a user from a http cookie or by some other means. Args: token: The session token. remote: The remote address of the user. proxy: Value of X-Forwarded-For server header Returns: dict: A dict mapping of user attributes if the application authentication was successful. See the Crowd documentation for the authoritative list of attributes. None: If authentication failed. """ params = { "validationFactors": [ {"name": "remote_address", "value": remote, }, ] } if proxy: params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, }) url = self.rest_url + "/session/%s" % token response = self._post(url, data=json.dumps(params), params={"expand": "user"}) # For consistency between methods use None rather than False # If token validation failed for any reason return None if not response.ok: return None # Otherwise return the user object return response.json()
Terminates the session token, effectively logging out the user from all crowd-enabled services. Args: token: The session token. Returns: True: If session terminated None: If session termination failed def terminate_session(self, token): """Terminates the session token, effectively logging out the user from all crowd-enabled services. Args: token: The session token. Returns: True: If session terminated None: If session termination failed """ url = self.rest_url + "/session/%s" % token response = self._delete(url) # For consistency between methods use None rather than False # If token validation failed for any reason return None if not response.ok: return None # Otherwise return True return True
Add a user to the directory Args: username: The account username raise_on_error: optional (default: False) **kwargs: key-value pairs: password: mandatory email: mandatory first_name: optional last_name: optional display_name: optional active: optional (default True) Returns: True: Succeeded False: If unsuccessful def add_user(self, username, raise_on_error=False, **kwargs): """Add a user to the directory Args: username: The account username raise_on_error: optional (default: False) **kwargs: key-value pairs: password: mandatory email: mandatory first_name: optional last_name: optional display_name: optional active: optional (default True) Returns: True: Succeeded False: If unsuccessful """ # Check that mandatory elements have been provided if 'password' not in kwargs: raise ValueError("missing password") if 'email' not in kwargs: raise ValueError("missing email") # Populate data with default and mandatory values. # A KeyError means a mandatory value was not provided, # so raise a ValueError indicating bad args. try: data = { "name": username, "first-name": username, "last-name": username, "display-name": username, "email": kwargs["email"], "password": {"value": kwargs["password"]}, "active": True } except KeyError: return ValueError # Remove special case 'password' del(kwargs["password"]) # Put values from kwargs into data for k, v in kwargs.items(): new_k = k.replace("_", "-") if new_k not in data: raise ValueError("invalid argument %s" % k) data[new_k] = v response = self._post(self.rest_url + "/user", data=json.dumps(data)) if response.status_code == 201: return True if raise_on_error: raise RuntimeError(response.json()['message']) return False
Retrieve information about a user Returns: dict: User information None: If no user or failure occurred def get_user(self, username): """Retrieve information about a user Returns: dict: User information None: If no user or failure occurred """ response = self._get(self.rest_url + "/user", params={"username": username, "expand": "attributes"}) if not response.ok: return None return response.json()
Set the active state of a user Args: username: The account username active_state: True or False Returns: True: If successful None: If no user or failure occurred def set_active(self, username, active_state): """Set the active state of a user Args: username: The account username active_state: True or False Returns: True: If successful None: If no user or failure occurred """ if active_state not in (True, False): raise ValueError("active_state must be True or False") user = self.get_user(username) if user is None: return None if user['active'] is active_state: # Already in desired state return True user['active'] = active_state response = self._put(self.rest_url + "/user", params={"username": username}, data=json.dumps(user)) if response.status_code == 204: return True return None
Set an attribute on a user :param username: The username on which to set the attribute :param attribute: The name of the attribute to set :param value: The value of the attribute to set :return: True on success, False on failure. def set_user_attribute(self, username, attribute, value, raise_on_error=False): """Set an attribute on a user :param username: The username on which to set the attribute :param attribute: The name of the attribute to set :param value: The value of the attribute to set :return: True on success, False on failure. """ data = { 'attributes': [ { 'name': attribute, 'values': [ value ] }, ] } response = self._post(self.rest_url + "/user/attribute", params={"username": username,}, data=json.dumps(data)) if response.status_code == 204: return True if raise_on_error: raise RuntimeError(response.json()['message']) return False
Add a user to a group :param username: The username to assign to the group :param groupname: The group name into which to assign the user :return: True on success, False on failure. def add_user_to_group(self, username, groupname, raise_on_error=False): """Add a user to a group :param username: The username to assign to the group :param groupname: The group name into which to assign the user :return: True on success, False on failure. """ data = { 'name': groupname, } response = self._post(self.rest_url + "/user/group/direct", params={"username": username,}, data=json.dumps(data)) if response.status_code == 201: return True if raise_on_error: raise RuntimeError(response.json()['message']) return False
Remove a user from a group Attempts to remove a user from a group Args username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: True: Succeeded False: If unsuccessful def remove_user_from_group(self, username, groupname, raise_on_error=False): """Remove a user from a group Attempts to remove a user from a group Args username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: True: Succeeded False: If unsuccessful """ response = self._delete(self.rest_url + "/group/user/direct",params={"username": username, "groupname": groupname}) if response.status_code == 204: return True if raise_on_error: raise RuntimeError(response.json()['message']) return False
Change new password for a user Args: username: The account username. newpassword: The account new password. raise_on_error: optional (default: False) Returns: True: Succeeded False: If unsuccessful def change_password(self, username, newpassword, raise_on_error=False): """Change new password for a user Args: username: The account username. newpassword: The account new password. raise_on_error: optional (default: False) Returns: True: Succeeded False: If unsuccessful """ response = self._put(self.rest_url + "/user/password", data=json.dumps({"value": newpassword}), params={"username": username}) if response.ok: return True if raise_on_error: raise RuntimeError(response.json()['message']) return False
Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful def send_password_reset_link(self, username): """Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful """ response = self._post(self.rest_url + "/user/mail/password", params={"username": username}) if response.ok: return True return False
Retrieve a list of all group names that have <username> as a direct or indirect member. Args: username: The account username. Returns: list: A list of strings of group names. def get_nested_groups(self, username): """Retrieve a list of all group names that have <username> as a direct or indirect member. Args: username: The account username. Returns: list: A list of strings of group names. """ response = self._get(self.rest_url + "/user/group/nested", params={"username": username}) if not response.ok: return None return [g['name'] for g in response.json()['groups']]
Retrieves a list of all users that directly or indirectly belong to the given groupname. Args: groupname: The group name. Returns: list: A list of strings of user names. def get_nested_group_users(self, groupname): """Retrieves a list of all users that directly or indirectly belong to the given groupname. Args: groupname: The group name. Returns: list: A list of strings of user names. """ response = self._get(self.rest_url + "/group/user/nested", params={"groupname": groupname, "start-index": 0, "max-results": 99999}) if not response.ok: return None return [u['name'] for u in response.json()['users']]
Determines if the user exists. Args: username: The user name. Returns: bool: True if the user exists in the Crowd application. def user_exists(self, username): """Determines if the user exists. Args: username: The user name. Returns: bool: True if the user exists in the Crowd application. """ response = self._get(self.rest_url + "/user", params={"username": username}) if not response.ok: return None return True
Fetches all group memberships. Returns: dict: key: group name value: (array of users, array of groups) def get_memberships(self): """Fetches all group memberships. Returns: dict: key: group name value: (array of users, array of groups) """ response = self._get_xml(self.rest_url + "/group/membership") if not response.ok: return None xmltree = etree.fromstring(response.content) memberships = {} for mg in xmltree.findall('membership'): # coerce values to unicode in a python 2 and 3 compatible way group = u'{}'.format(mg.get('group')) users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')] groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')] memberships[group] = {u'users': users, u'groups': groups} return memberships
Performs a user search using the Crowd search API. https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource Args: entity_type: 'user' or 'group' property_name: eg. 'email', 'name' search_string: the string to search for. start_index: starting index of the results (default: 0) max_results: maximum number of results returned (default: 99999) Returns: json results: Returns search results. def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999): """Performs a user search using the Crowd search API. https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource Args: entity_type: 'user' or 'group' property_name: eg. 'email', 'name' search_string: the string to search for. start_index: starting index of the results (default: 0) max_results: maximum number of results returned (default: 99999) Returns: json results: Returns search results. """ params = { "entity-type": entity_type, "expand": entity_type, "property-search-restriction": { "property": {"name": property_name, "type": "STRING"}, "match-mode": "CONTAINS", "value": search_string, } } params = { 'entity-type': entity_type, 'expand': entity_type, 'start-index': start_index, 'max-results': max_results } # Construct XML payload of the form: # <property-search-restriction> # <property> # <name>email</name> # <type>STRING</type> # </property> # <match-mode>EXACTLY_MATCHES</match-mode> # <value>bob@example.net</value> # </property-search-restriction> root = etree.Element('property-search-restriction') property_ = etree.Element('property') prop_name = etree.Element('name') prop_name.text = property_name property_.append(prop_name) prop_type = etree.Element('type') prop_type.text = 'STRING' property_.append(prop_type) root.append(property_) match_mode = etree.Element('match-mode') match_mode.text = 'CONTAINS' root.append(match_mode) value = etree.Element('value') value.text = search_string root.append(value) # Construct the XML payload expected by search API payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8') # We're sending XML but would like a JSON response session = self._build_session(content_type='xml') session.headers.update({'Accept': 'application/json'}) response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout) if not response.ok: return None return response.json()
The versions associated with Blender def versions(self) -> List(BlenderVersion): """ The versions associated with Blender """ return [BlenderVersion(tag) for tag in self.git_repo.tags] + [BlenderVersion(BLENDER_VERSION_MASTER)]
Copy libraries from the bin directory and place them as appropriate def run(self): """ Copy libraries from the bin directory and place them as appropriate """ self.announce("Moving library files", level=3) # We have already built the libraries in the previous build_ext step self.skip_build = True bin_dir = self.distribution.bin_dir libs = [os.path.join(bin_dir, _lib) for _lib in os.listdir(bin_dir) if os.path.isfile(os.path.join(bin_dir, _lib)) and os.path.splitext(_lib)[1] in [".dll", ".so"] and not (_lib.startswith("python") or _lib.startswith("bpy"))] for lib in libs: shutil.move(lib, os.path.join(self.build_dir, os.path.basename(lib))) # Mark the libs for installation, adding them to # distribution.data_files seems to ensure that setuptools' record # writer appends them to installed-files.txt in the package's egg-info # # Also tried adding the libraries to the distribution.libraries list, # but that never seemed to add them to the installed-files.txt in the # egg-info, and the online recommendation seems to be adding libraries # into eager_resources in the call to setup(), which I think puts them # in data_files anyways. # # What is the best way? self.distribution.data_files = [os.path.join(self.install_dir, os.path.basename(lib)) for lib in libs] # Must be forced to run after adding the libs to data_files self.distribution.run_command("install_data") super().run()
Copy the required directory to the build directory and super().run() def run(self): """ Copy the required directory to the build directory and super().run() """ self.announce("Moving scripts files", level=3) self.skip_build = True bin_dir = self.distribution.bin_dir scripts_dirs = [os.path.join(bin_dir, _dir) for _dir in os.listdir(bin_dir) if os.path.isdir(os.path.join(bin_dir, _dir))] for scripts_dir in scripts_dirs: dst_dir = os.path.join(self.build_dir, os.path.basename(scripts_dir)) # Mostly in case of weird things happening during build if os.path.exists(dst_dir): if os.path.isdir(dst_dir): shutil.rmtree(dst_dir) elif os.path.isfile(dst_dir): os.remove(dst_dir) shutil.move(scripts_dir, os.path.join(self.build_dir, os.path.basename(scripts_dir))) # Mark the scripts for installation, adding them to # distribution.scripts seems to ensure that the setuptools' record # writer appends them to installed-files.txt in the package's egg-info self.distribution.scripts = scripts_dirs super().run()
Perform build_cmake before doing the 'normal' stuff def run(self): """ Perform build_cmake before doing the 'normal' stuff """ for extension in self.extensions: if extension.name == "bpy": self.build_cmake(extension) super().run()
The steps required to build the extension def build_cmake(self, extension: Extension): """ The steps required to build the extension """ # We import the setup_requires modules here because if we import them # at the top this script will always fail as they won't be present from git import Repo as GitRepo from svn.remote import RemoteClient as SvnRepo self.announce("Preparing the build environment", level=3) blender_dir = os.path.join(BLENDERPY_DIR, "blender") build_dir = pathlib.Path(self.build_temp) extension_path = pathlib.Path(self.get_ext_fullpath(extension.name)) os.makedirs(blender_dir, exist_ok=True) os.makedirs(str(build_dir), exist_ok=True) os.makedirs(str(extension_path.parent.absolute()), exist_ok=True) # Now that the necessary directories are created, ensure that OS # specific steps are performed; a good example is checking on linux # that the required build libraries are in place. os_build_args = [] # Have to find the correct release tag to checkout here, as potentially # master may not be the correct one for this Python version. We use svn # to find whether or not master, or a specific tag supports the # current python version if sys.platform == "win32": # Windows only steps import winreg vs_versions = [] for version in [12, 14, 15]: try: winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, f"VisualStudio.DTE.{version}.0") except: pass else: vs_versions.append(version) if not vs_versions: raise Exception("Windows users must have Visual Studio 2013 " "or later installed") if max(vs_versions) == 15: os_build_args += ["-G", f"Visual Studio 15 2017" f"{' Win64' if BITS == 64 else ''}"] elif max(vs_versions) == 14: os_build_args += ["-G", f"Visual Studio 14 2015" f"{' Win64' if BITS == 64 else ''}"] elif max(vs_versions) == 12: os_build_args += ["-G", f"Visual Studio 12 2013" f"{' Win64' if BITS == 64 else ''}"] # TODO: Clean up here svn_lib_options += [f"win{64 if BITS == 64 else 'dows'}_vc{version}" for version in vs_versions] blender_svn_repo = SvnRepo(svn_url) os.makedirs(svn_dir, exist_ok=True) self.announce(f"Checking out svn libs from {svn_url}", level=3) try: blender_svn_repo.checkout(svn_dir) except Exception as e: self.warn("Windows users must have the svn executable " "available from the command line") self.warn("Please install Tortoise SVN with \"command line " "client tools\" as described here") self.warn("https://stackoverflow.com/questions/1625406/using-" "tortoisesvn-via-the-command-line") raise e elif sys.platform == "linux": # Linux only steps # TODO: Test linux environment, issue #1 pass elif sys.platform == "darwin": # MacOS only steps # TODO: Test MacOS environment, issue #2 pass # Perform relatively common build steps # TODO: if blender desired version, then see if we can install that # Otherwise fail, if no desired version, find the latest version that # supports our python and install that git_repo = GitRepo(GIT_BASE_URL) svn_repo = SvnRepo(SVN_BASE_URL) if BLENDER_DESIRED_VERSION: match = BLENDER_VERSION_REGEX.match(BLENDER_DESIRED_VERSION) if match: # We have a blender version that conforms to the naming scheme # now to see if it actually exists in git and svn if match.group(0) in git_repo.tags: # The version was tagged in the git repository # now, format the version to match the svn versioning # scheme... svn_version_tag = (f"blender-{match.group(1)}" f"{match.group(2) if not match.group(2).startswith("-rc")}-release") svn_tag_repo = SvnRepo(os.path.join(SVN_BASE_URL, SVN_TAGS)) if svn_version_tag in svn_tag_repo.list(): # The version was released in svn and we found it # Now, is it compatible with our OS and python version? else: raise Exception(f"{BLENDER_DESIRED_VERSION} was found " f"in the git repository but not the " f"svn repository.") else: raise Exception(f"The provided version " f"{BLENDER_DESIRED_VERSION} does not " f"exist; please check " f"https://git.blender.org/gitweb/" f"gitweb.cgi/blender.git/tags for a list " f"of valid Blender releases") else: # The blender version did not conform to the naming scheme # fail and notify the user how to list the version raise Exception(f"The provided version " f"{BLENDER_DESIRED_VERSION} did not match " f"Blender's naming scheme. Please list your " f"desired version as 'v' followed by a digit, " f"followed by a period, followed by two " f"digits and either 'a', 'b', 'c' or '-rc' " f"(versions using '-rc' can optionally add " f"a number which specifies which release " f"candidate they want to install) such that " f"the version looks like the following: " f"v2.74-rc2") else: if sys.version_info >= (3, 6): # we can get from svn and git master branch else: # we must find a compatible version self.announce(f"Cloning Blender source from {BLENDER_GIT_REPO_URL}", level=3) try: blender_git_repo = GitRepo(blender_dir) except: GitRepo.clone_from(BLENDER_GIT_REPO_URL, blender_dir) blender_git_repo = GitRepo(blender_dir) finally: blender_git_repo.heads.master.checkout() blender_git_repo.remotes.origin.pull() self.announce(f"Updating Blender git submodules", level=3) blender_git_repo.git.submodule('update', '--init', '--recursive') for submodule in blender_git_repo.submodules: submodule_repo = submodule.module() submodule_repo.heads.master.checkout() submodule_repo.remotes.origin.pull() self.announce("Configuring cmake project", level=3) self.spawn(['cmake', '-H'+blender_dir, '-B'+self.build_temp, '-DWITH_PLAYER=OFF', '-DWITH_PYTHON_INSTALL=OFF', '-DWITH_PYTHON_MODULE=ON', f"-DPYTHON_VERSION=" f"{sys.version_info[0]}.{sys.version_info[1]}"] + os_build_args) self.announce("Building binaries", level=3) self.spawn(["cmake", "--build", self.build_temp, "--target", "INSTALL", "--config", "Release"]) # Build finished, now copy the files into the copy directory # The copy directory is the parent directory of the extension (.pyd) self.announce("Moving Blender python module", level=3) bin_dir = os.path.join(str(build_dir), 'bin', 'Release') self.distribution.bin_dir = bin_dir bpy_path = [os.path.join(bin_dir, _bpy) for _bpy in os.listdir(bin_dir) if os.path.isfile(os.path.join(bin_dir, _bpy)) and os.path.splitext(_bpy)[0].startswith('bpy') and os.path.splitext(_bpy)[1] in [".pyd", ".so"]][0] shutil.move(str(bpy_path), str(extension_path))
:type addresses: list[str] :param addresses: (list[str]) List of addresses to retrieve their reverse dns Retrieve the current configured ReverseDns entries :return: (list) List containing the current ReverseDns Addresses def get(self, addresses): """ :type addresses: list[str] :param addresses: (list[str]) List of addresses to retrieve their reverse dns Retrieve the current configured ReverseDns entries :return: (list) List containing the current ReverseDns Addresses """ request = self._call(GetReverseDns.GetReverseDns, IPs=addresses) response = request.commit() return response['Value']
Assign one or more PTR record to a single IP Address :type address: str :type host_name: list[str] :param address: (str) The IP address to configure :param host_name: (list[str]) The list of strings representing PTR records :return: (bool) True in case of success, False in case of failure def set(self, address, host_name): """ Assign one or more PTR record to a single IP Address :type address: str :type host_name: list[str] :param address: (str) The IP address to configure :param host_name: (list[str]) The list of strings representing PTR records :return: (bool) True in case of success, False in case of failure """ request = self._call(SetEnqueueSetReverseDns.SetEnqueueSetReverseDns, IP=address, Hosts=host_name) response = request.commit() return response['Success']
Remove all PTR records from the given address :type addresses: List[str] :param addresses: (List[str]) The IP Address to reset :return: (bool) True in case of success, False in case of failure def reset(self, addresses): """ Remove all PTR records from the given address :type addresses: List[str] :param addresses: (List[str]) The IP Address to reset :return: (bool) True in case of success, False in case of failure """ request = self._call(SetEnqueueResetReverseDns.SetEnqueueResetReverseDns, IPs=addresses) response = request.commit() return response['Success']
:type healthCheckNotification: bool :type instance: list[Instance] :type ipAddressResourceId: list[int] :type loadBalancerClassOfServiceID: int :type name: str :type notificationContacts: NotificationContacts or list[NotificationContact] :type rules: Rules :param healthCheckNotification: Enable or disable notifications :param instance: List of balanced IP Addresses (VM or server) :param ipAddressResourceId: ID of the IP Address resource of the Load Balancer :param loadBalancerClassOfServiceID: default 1 :param name: Name of the Load Balancer :param notificationContacts: Nullable if notificationContacts is false :param rules: List of NewLoadBalancerRule object containing the list of rules to be configured with the service def create(self, healthCheckNotification, instance, ipAddressResourceId, name, notificationContacts, rules, loadBalancerClassOfServiceID=1, *args, **kwargs): """ :type healthCheckNotification: bool :type instance: list[Instance] :type ipAddressResourceId: list[int] :type loadBalancerClassOfServiceID: int :type name: str :type notificationContacts: NotificationContacts or list[NotificationContact] :type rules: Rules :param healthCheckNotification: Enable or disable notifications :param instance: List of balanced IP Addresses (VM or server) :param ipAddressResourceId: ID of the IP Address resource of the Load Balancer :param loadBalancerClassOfServiceID: default 1 :param name: Name of the Load Balancer :param notificationContacts: Nullable if notificationContacts is false :param rules: List of NewLoadBalancerRule object containing the list of rules to be configured with the service """ response = self._call(method=SetEnqueueLoadBalancerCreation, healthCheckNotification=healthCheckNotification, instance=instance, ipAddressResourceId=ipAddressResourceId, name=name, notificationContacts=notificationContacts, rules=rules, loadBalancerClassOfServiceID=loadBalancerClassOfServiceID, *args, **kwargs)
Get the load balancer notifications for a specific rule within a specifying window time frame :type startDate: datetime :type endDate: datetime :type loadBalancerID: int :type loadBalancerRuleID: int :param startDate: From Date :param endDate: To Date :param loadBalancerID: ID of the Laod Balancer :param loadBalancerRuleID: ID of the Load Balancer Rule def get_notifications(self, startDate, endDate, loadBalancerID, loadBalancerRuleID): """ Get the load balancer notifications for a specific rule within a specifying window time frame :type startDate: datetime :type endDate: datetime :type loadBalancerID: int :type loadBalancerRuleID: int :param startDate: From Date :param endDate: To Date :param loadBalancerID: ID of the Laod Balancer :param loadBalancerRuleID: ID of the Load Balancer Rule """ return self._call(GetLoadBalancerNotifications, startDate=startDate, endDate=endDate, loadBalancerID=loadBalancerID, loadBalancerRuleID=loadBalancerRuleID)
Check if the given authcfg_id (or the default) exists, and if it's valid OAuth2, return the configuration or None def get_oauth_authcfg(authcfg_id=AUTHCFG_ID): """Check if the given authcfg_id (or the default) exists, and if it's valid OAuth2, return the configuration or None""" # Handle empty strings if not authcfg_id: authcfg_id = AUTHCFG_ID configs = auth_manager().availableAuthMethodConfigs() if authcfg_id in configs \ and configs[authcfg_id].isValid() \ and configs[authcfg_id].method() == 'OAuth2': return configs[authcfg_id] return None
Setup oauth configuration to access the BCS API, return authcfg_id on success, None on failure def setup_oauth(username, password, basemaps_token_uri, authcfg_id=AUTHCFG_ID, authcfg_name=AUTHCFG_NAME): """Setup oauth configuration to access the BCS API, return authcfg_id on success, None on failure """ cfgjson = { "accessMethod" : 0, "apiKey" : "", "clientId" : "", "clientSecret" : "", "configType" : 1, "grantFlow" : 2, "password" : password, "persistToken" : False, "redirectPort" : '7070', "redirectUrl" : "", "refreshTokenUrl" : "", "requestTimeout" : '30', "requestUrl" : "", "scope" : "", "state" : "", "tokenUrl" : basemaps_token_uri, "username" : username, "version" : 1 } if authcfg_id not in auth_manager().availableAuthMethodConfigs(): authConfig = QgsAuthMethodConfig('OAuth2') authConfig.setId(authcfg_id) authConfig.setName(authcfg_name) authConfig.setConfig('oauth2config', json.dumps(cfgjson)) if auth_manager().storeAuthenticationConfig(authConfig): return authcfg_id else: authConfig = QgsAuthMethodConfig() auth_manager().loadAuthenticationConfig(authcfg_id, authConfig, True) authConfig.setName(authcfg_name) authConfig.setConfig('oauth2config', json.dumps(cfgjson)) if auth_manager().updateAuthenticationConfig(authConfig): return authcfg_id return None
Create a new SearchQuery instance and execute a search against ES. Args: search: elasticsearch.search.Search object, that internally contains the connection and query; this is the query that is executed. All we are doing is logging the input and parsing the output. search_terms: raw end user search terms input - what they typed into the search box. user: Django User object, the person making the query - used for logging purposes. Can be null. reference: string, can be anything you like, used for identification, grouping purposes. save: bool, if True then save the new object immediately, can be overridden to False to prevent logging absolutely everything. Defaults to True query_type: string, used to determine whether to run a search query or a count query (returns hit count, but no results). def execute_search( search, search_terms="", user=None, reference="", save=True, query_type=SearchQuery.QUERY_TYPE_SEARCH, ): """ Create a new SearchQuery instance and execute a search against ES. Args: search: elasticsearch.search.Search object, that internally contains the connection and query; this is the query that is executed. All we are doing is logging the input and parsing the output. search_terms: raw end user search terms input - what they typed into the search box. user: Django User object, the person making the query - used for logging purposes. Can be null. reference: string, can be anything you like, used for identification, grouping purposes. save: bool, if True then save the new object immediately, can be overridden to False to prevent logging absolutely everything. Defaults to True query_type: string, used to determine whether to run a search query or a count query (returns hit count, but no results). """ start = time.time() if query_type == SearchQuery.QUERY_TYPE_SEARCH: response = search.execute() hits = [h.meta.to_dict() for h in response.hits] total_hits = response.hits.total elif query_type == SearchQuery.QUERY_TYPE_COUNT: response = total_hits = search.count() hits = [] else: raise ValueError(f"Invalid SearchQuery.query_type value: '{query_type}'") duration = time.time() - start search_query = SearchQuery( user=user, search_terms=search_terms, index=", ".join(search._index or ["_all"])[:100], # field length restriction query=search.to_dict(), query_type=query_type, hits=hits, total_hits=total_hits, reference=reference or "", executed_at=tz_now(), duration=duration, ) search_query.response = response return search_query.save() if save else search_query
Return True if an object is part of the search index queryset. Sometimes it's useful to know if an object _should_ be indexed. If an object is saved, how do you know if you should push that change to the search index? The simplest (albeit not most efficient) way is to check if it appears in the underlying search queryset. NB this method doesn't evaluate the entire dataset, it chains an additional queryset filter expression on the end. That's why it's important that the `get_search_queryset` method returns a queryset. Args: instance_id: the id of model object that we are looking for. Kwargs: index: string, the name of the index in which to check. Defaults to '_all'. def in_search_queryset(self, instance_id, index="_all"): """ Return True if an object is part of the search index queryset. Sometimes it's useful to know if an object _should_ be indexed. If an object is saved, how do you know if you should push that change to the search index? The simplest (albeit not most efficient) way is to check if it appears in the underlying search queryset. NB this method doesn't evaluate the entire dataset, it chains an additional queryset filter expression on the end. That's why it's important that the `get_search_queryset` method returns a queryset. Args: instance_id: the id of model object that we are looking for. Kwargs: index: string, the name of the index in which to check. Defaults to '_all'. """ return self.get_search_queryset(index=index).filter(pk=instance_id).exists()
Return queryset of objects from SearchQuery.results, **in order**. EXPERIMENTAL: this will only work with results from a single index, with a single doc_type - as we are returning a single QuerySet. This method takes the hits JSON and converts that into a queryset of all the relevant objects. The key part of this is the ordering - the order in which search results are returned is based on relevance, something that only ES can calculate, and that cannot be replicated in the database. It does this by adding custom SQL which annotates each record with the score from the search 'hit'. This is brittle, caveat emptor. The RawSQL clause is in the form: SELECT CASE {{model}}.id WHEN {{id}} THEN {{score}} END The "WHEN x THEN y" is repeated for every hit. The resulting SQL, in full is like this: SELECT "freelancer_freelancerprofile"."id", (SELECT CASE freelancer_freelancerprofile.id WHEN 25 THEN 1.0 WHEN 26 THEN 1.0 [...] ELSE 0 END) AS "search_score" FROM "freelancer_freelancerprofile" WHERE "freelancer_freelancerprofile"."id" IN (25, 26, [...]) ORDER BY "search_score" DESC It should be very fast, as there is no table lookup, but there is an assumption at the heart of this, which is that the search query doesn't contain the entire database - i.e. that it has been paged. (ES itself caps the results at 10,000.) def from_search_query(self, search_query): """ Return queryset of objects from SearchQuery.results, **in order**. EXPERIMENTAL: this will only work with results from a single index, with a single doc_type - as we are returning a single QuerySet. This method takes the hits JSON and converts that into a queryset of all the relevant objects. The key part of this is the ordering - the order in which search results are returned is based on relevance, something that only ES can calculate, and that cannot be replicated in the database. It does this by adding custom SQL which annotates each record with the score from the search 'hit'. This is brittle, caveat emptor. The RawSQL clause is in the form: SELECT CASE {{model}}.id WHEN {{id}} THEN {{score}} END The "WHEN x THEN y" is repeated for every hit. The resulting SQL, in full is like this: SELECT "freelancer_freelancerprofile"."id", (SELECT CASE freelancer_freelancerprofile.id WHEN 25 THEN 1.0 WHEN 26 THEN 1.0 [...] ELSE 0 END) AS "search_score" FROM "freelancer_freelancerprofile" WHERE "freelancer_freelancerprofile"."id" IN (25, 26, [...]) ORDER BY "search_score" DESC It should be very fast, as there is no table lookup, but there is an assumption at the heart of this, which is that the search query doesn't contain the entire database - i.e. that it has been paged. (ES itself caps the results at 10,000.) """ hits = search_query.hits score_sql = self._raw_sql([(h["id"], h["score"] or 0) for h in hits]) rank_sql = self._raw_sql([(hits[i]["id"], i) for i in range(len(hits))]) return ( self.get_queryset() .filter(pk__in=[h["id"] for h in hits]) # add the query relevance score .annotate(search_score=RawSQL(score_sql, ())) # add the ordering number (0-based) .annotate(search_rank=RawSQL(rank_sql, ())) .order_by("search_rank") )
Prepare SQL statement consisting of a sequence of WHEN .. THEN statements. def _raw_sql(self, values): """Prepare SQL statement consisting of a sequence of WHEN .. THEN statements.""" if isinstance(self.model._meta.pk, CharField): when_clauses = " ".join( [self._when("'{}'".format(x), y) for (x, y) in values] ) else: when_clauses = " ".join([self._when(x, y) for (x, y) in values]) table_name = self.model._meta.db_table primary_key = self.model._meta.pk.column return 'SELECT CASE {}."{}" {} ELSE 0 END'.format( table_name, primary_key, when_clauses )
Key used for storing search docs in local cache. def search_document_cache_key(self): """Key used for storing search docs in local cache.""" return "elasticsearch_django:{}.{}.{}".format( self._meta.app_label, self._meta.model_name, self.pk )
Return True if the field can be serialized into a JSON doc. def _is_field_serializable(self, field_name): """Return True if the field can be serialized into a JSON doc.""" return ( self._meta.get_field(field_name).get_internal_type() in self.SIMPLE_UPDATE_FIELD_TYPES )
Clean the list of update_fields based on the index being updated.\ If any field in the update_fields list is not in the set of properties defined by the index mapping for this model, then we ignore it. If a field _is_ in the mapping, but the underlying model field is a related object, and thereby not directly serializable, then this method will raise a ValueError. def clean_update_fields(self, index, update_fields): """ Clean the list of update_fields based on the index being updated.\ If any field in the update_fields list is not in the set of properties defined by the index mapping for this model, then we ignore it. If a field _is_ in the mapping, but the underlying model field is a related object, and thereby not directly serializable, then this method will raise a ValueError. """ search_fields = get_model_index_properties(self, index) clean_fields = [f for f in update_fields if f in search_fields] ignore = [f for f in update_fields if f not in search_fields] if ignore: logger.debug( "Ignoring fields from partial update: %s", [f for f in update_fields if f not in search_fields], ) for f in clean_fields: if not self._is_field_serializable(f): raise ValueError( "'%s' cannot be automatically serialized into a search document property. Please override as_search_document_update.", f, ) return clean_fields
Return a partial update document based on which fields have been updated. If an object is saved with the `update_fields` argument passed through, then it is assumed that this is a 'partial update'. In this scenario we need a {property: value} dictionary containing just the fields we want to update. This method handles two possible update strategies - 'full' or 'partial'. The default 'full' strategy simply returns the value of `as_search_document` - thereby replacing the entire document each time. The 'partial' strategy is more intelligent - it will determine whether the fields passed are in the search document mapping, and return a partial update document that contains only those that are. In addition, if any field that _is_ included cannot be automatically serialized (e.g. a RelatedField object), then this method will raise a ValueError. In this scenario, you should override this method in your subclass. >>> def as_search_document_update(self, index, update_fields): ... if 'user' in update_fields: ... update_fields.remove('user') ... doc = super().as_search_document_update(index, update_fields) ... doc['user'] = self.user.get_full_name() ... return doc ... return super().as_search_document_update(index, update_fields) You may also wish to subclass this method to perform field-specific logic - in this example if only the timestamp is being saved, then ignore the update if the timestamp is later than a certain time. >>> def as_search_document_update(self, index, update_fields): ... if update_fields == ['timestamp']: ... if self.timestamp > today(): ... return {} ... return super().as_search_document_update(index, update_fields) def as_search_document_update(self, *, index, update_fields): """ Return a partial update document based on which fields have been updated. If an object is saved with the `update_fields` argument passed through, then it is assumed that this is a 'partial update'. In this scenario we need a {property: value} dictionary containing just the fields we want to update. This method handles two possible update strategies - 'full' or 'partial'. The default 'full' strategy simply returns the value of `as_search_document` - thereby replacing the entire document each time. The 'partial' strategy is more intelligent - it will determine whether the fields passed are in the search document mapping, and return a partial update document that contains only those that are. In addition, if any field that _is_ included cannot be automatically serialized (e.g. a RelatedField object), then this method will raise a ValueError. In this scenario, you should override this method in your subclass. >>> def as_search_document_update(self, index, update_fields): ... if 'user' in update_fields: ... update_fields.remove('user') ... doc = super().as_search_document_update(index, update_fields) ... doc['user'] = self.user.get_full_name() ... return doc ... return super().as_search_document_update(index, update_fields) You may also wish to subclass this method to perform field-specific logic - in this example if only the timestamp is being saved, then ignore the update if the timestamp is later than a certain time. >>> def as_search_document_update(self, index, update_fields): ... if update_fields == ['timestamp']: ... if self.timestamp > today(): ... return {} ... return super().as_search_document_update(index, update_fields) """ if UPDATE_STRATEGY == UPDATE_STRATEGY_FULL: return self.as_search_document(index=index) if UPDATE_STRATEGY == UPDATE_STRATEGY_PARTIAL: # in partial mode we update the intersection of update_fields and # properties found in the mapping file. return { k: getattr(self, k) for k in self.clean_update_fields( index=index, update_fields=update_fields ) }
Return an object as represented in a bulk api operation. Bulk API operations have a very specific format. This function will call the standard `as_search_document` method on the object and then wrap that up in the correct format for the action specified. https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html Args: index: string, the name of the index in which the action is to be taken. Bulk operations are only every carried out on a single index at a time. action: string ['index' | 'update' | 'delete'] - this decides how the final document is formatted. Returns a dictionary. def as_search_action(self, *, index, action): """ Return an object as represented in a bulk api operation. Bulk API operations have a very specific format. This function will call the standard `as_search_document` method on the object and then wrap that up in the correct format for the action specified. https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html Args: index: string, the name of the index in which the action is to be taken. Bulk operations are only every carried out on a single index at a time. action: string ['index' | 'update' | 'delete'] - this decides how the final document is formatted. Returns a dictionary. """ if action not in ("index", "update", "delete"): raise ValueError("Action must be 'index', 'update' or 'delete'.") document = { "_index": index, "_type": self.search_doc_type, "_op_type": action, "_id": self.pk, } if action == "index": document["_source"] = self.as_search_document(index=index) elif action == "update": document["doc"] = self.as_search_document(index=index) return document
Fetch the object's document from a search index by id. def fetch_search_document(self, *, index): """Fetch the object's document from a search index by id.""" assert self.pk, "Object must have a primary key before being indexed." client = get_client() return client.get(index=index, doc_type=self.search_doc_type, id=self.pk)
Create or replace search document in named index. Checks the local cache to see if the document has changed, and if not aborts the update, else pushes to ES, and then resets the local cache. Cache timeout is set as "cache_expiry" in the settings, and defaults to 60s. def index_search_document(self, *, index): """ Create or replace search document in named index. Checks the local cache to see if the document has changed, and if not aborts the update, else pushes to ES, and then resets the local cache. Cache timeout is set as "cache_expiry" in the settings, and defaults to 60s. """ cache_key = self.search_document_cache_key new_doc = self.as_search_document(index=index) cached_doc = cache.get(cache_key) if new_doc == cached_doc: logger.debug("Search document for %r is unchanged, ignoring update.", self) return [] cache.set(cache_key, new_doc, timeout=get_setting("cache_expiry", 60)) get_client().index( index=index, doc_type=self.search_doc_type, body=new_doc, id=self.pk )