text
stringlengths
81
112k
Gettext function wrapper to return a message in a specified language by domain To use internationalization (i18n) on your messages, import it as '_' and use as usual. Do not forget to supply the client's language setting. def i18n(msg, event=None, lang='en', domain='backend'): """Gettext function wrapper to return a message in a specified language by domain To use internationalization (i18n) on your messages, import it as '_' and use as usual. Do not forget to supply the client's language setting.""" if event is not None: language = event.client.language else: language = lang domain = Domain(domain) return domain.get(language, msg)
Generates a cryptographically strong (sha512) hash with this nodes salt added. def std_hash(word, salt): """Generates a cryptographically strong (sha512) hash with this nodes salt added.""" try: password = word.encode('utf-8') except UnicodeDecodeError: password = word word_hash = sha512(password) word_hash.update(salt) hex_hash = word_hash.hexdigest() return hex_hash
Return a random generated human-friendly phrase as low-probability unique id def std_human_uid(kind=None): """Return a random generated human-friendly phrase as low-probability unique id""" kind_list = alphabet if kind == 'animal': kind_list = animals elif kind == 'place': kind_list = places name = "{color} {adjective} {kind} of {attribute}".format( color=choice(colors), adjective=choice(adjectives), kind=choice(kind_list), attribute=choice(attributes) ) return name
Return a formatted table of given rows def std_table(rows): """Return a formatted table of given rows""" result = "" if len(rows) > 1: headers = rows[0]._fields lens = [] for i in range(len(rows[0])): lens.append(len(max([x[i] for x in rows] + [headers[i]], key=lambda x: len(str(x))))) formats = [] hformats = [] for i in range(len(rows[0])): if isinstance(rows[0][i], int): formats.append("%%%dd" % lens[i]) else: formats.append("%%-%ds" % lens[i]) hformats.append("%%-%ds" % lens[i]) pattern = " | ".join(formats) hpattern = " | ".join(hformats) separator = "-+-".join(['-' * n for n in lens]) result += hpattern % tuple(headers) + " \n" result += separator + "\n" for line in rows: result += pattern % tuple(t for t in line) + "\n" elif len(rows) == 1: row = rows[0] hwidth = len(max(row._fields, key=lambda x: len(x))) for i in range(len(row)): result += "%*s = %s" % (hwidth, row._fields[i], row[i]) + "\n" return result
Generates a cryptographically sane salt of 'length' (default: 16) alphanumeric characters def std_salt(length=16, lowercase=True): """Generates a cryptographically sane salt of 'length' (default: 16) alphanumeric characters """ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" if lowercase is True: alphabet += "abcdefghijklmnopqrstuvwxyz" chars = [] for i in range(length): chars.append(choice(alphabet)) return "".join(chars)
Add a new translation language to the live gettext translator def _get_translation(self, lang): """Add a new translation language to the live gettext translator""" try: return self._translations[lang] except KeyError: # The fact that `fallback=True` is not the default is a serious design flaw. rv = self._translations[lang] = gettext.translation(self._domain, localedir=localedir, languages=[lang], fallback=True) return rv
Creates an Event Handler This decorator can be applied to methods of classes derived from :class:`circuits.core.components.BaseComponent`. It marks the method as a handler for the events passed as arguments to the ``@handler`` decorator. The events are specified by their name. The decorated method's arguments must match the arguments passed to the :class:`circuits.core.events.Event` on creation. Optionally, the method may have an additional first argument named *event*. If declared, the event object that caused the handler to be invoked is assigned to it. By default, the handler is invoked by the component's root :class:`~.manager.Manager` for events that are propagated on the channel determined by the BaseComponent's *channel* attribute. This may be overridden by specifying a different channel as a keyword parameter of the decorator (``channel=...``). Keyword argument ``priority`` influences the order in which handlers for a specific event are invoked. The higher the priority, the earlier the handler is executed. If you want to override a handler defined in a base class of your component, you must specify ``override=True``, else your method becomes an additional handler for the event. **Return value** Normally, the results returned by the handlers for an event are simply collected in the :class:`circuits.core.events.Event`'s :attr:`value` attribute. As a special case, a handler may return a :class:`types.GeneratorType`. This signals to the dispatcher that the handler isn't ready to deliver a result yet. Rather, it has interrupted it's execution with a ``yield None`` statement, thus preserving its current execution state. The dispatcher saves the returned generator object as a task. All tasks are reexamined (i.e. their :meth:`next()` method is invoked) when the pending events have been executed. This feature avoids an unnecessarily complicated chaining of event handlers. Imagine a handler A that needs the results from firing an event E in order to complete. Then without this feature, the final action of A would be to fire event E, and another handler for an event ``SuccessE`` would be required to complete handler A's operation, now having the result from invoking E available (actually it's even a bit more complicated). Using this "suspend" feature, the handler simply fires event E and then yields ``None`` until e.g. it finds a result in E's :attr:`value` attribute. For the simplest scenario, there even is a utility method :meth:`circuits.core.manager.Manager.callEvent` that combines firing and waiting. def handler(*names, **kwargs): """Creates an Event Handler This decorator can be applied to methods of classes derived from :class:`circuits.core.components.BaseComponent`. It marks the method as a handler for the events passed as arguments to the ``@handler`` decorator. The events are specified by their name. The decorated method's arguments must match the arguments passed to the :class:`circuits.core.events.Event` on creation. Optionally, the method may have an additional first argument named *event*. If declared, the event object that caused the handler to be invoked is assigned to it. By default, the handler is invoked by the component's root :class:`~.manager.Manager` for events that are propagated on the channel determined by the BaseComponent's *channel* attribute. This may be overridden by specifying a different channel as a keyword parameter of the decorator (``channel=...``). Keyword argument ``priority`` influences the order in which handlers for a specific event are invoked. The higher the priority, the earlier the handler is executed. If you want to override a handler defined in a base class of your component, you must specify ``override=True``, else your method becomes an additional handler for the event. **Return value** Normally, the results returned by the handlers for an event are simply collected in the :class:`circuits.core.events.Event`'s :attr:`value` attribute. As a special case, a handler may return a :class:`types.GeneratorType`. This signals to the dispatcher that the handler isn't ready to deliver a result yet. Rather, it has interrupted it's execution with a ``yield None`` statement, thus preserving its current execution state. The dispatcher saves the returned generator object as a task. All tasks are reexamined (i.e. their :meth:`next()` method is invoked) when the pending events have been executed. This feature avoids an unnecessarily complicated chaining of event handlers. Imagine a handler A that needs the results from firing an event E in order to complete. Then without this feature, the final action of A would be to fire event E, and another handler for an event ``SuccessE`` would be required to complete handler A's operation, now having the result from invoking E available (actually it's even a bit more complicated). Using this "suspend" feature, the handler simply fires event E and then yields ``None`` until e.g. it finds a result in E's :attr:`value` attribute. For the simplest scenario, there even is a utility method :meth:`circuits.core.manager.Manager.callEvent` that combines firing and waiting. """ def wrapper(f): if names and isinstance(names[0], bool) and not names[0]: f.handler = False return f if len(names) > 0 and inspect.isclass(names[0]) and \ issubclass(names[0], hfosEvent): f.names = (str(names[0].realname()),) else: f.names = names f.handler = True f.priority = kwargs.get("priority", 0) f.channel = kwargs.get("channel", None) f.override = kwargs.get("override", False) args = inspect.getargspec(f)[0] if args and args[0] == "self": del args[0] f.event = getattr(f, "event", bool(args and args[0] == "event")) return f return wrapper
Log a statement from this component def log(self, *args, **kwargs): """Log a statement from this component""" func = inspect.currentframe().f_back.f_code # Dump the message + the name of this function to the log. if 'exc' in kwargs and kwargs['exc'] is True: exc_type, exc_obj, exc_tb = exc_info() line_no = exc_tb.tb_lineno # print('EXCEPTION DATA:', line_no, exc_type, exc_obj, exc_tb) args += traceback.extract_tb(exc_tb), else: line_no = func.co_firstlineno sourceloc = "[%.10s@%s:%i]" % ( func.co_name, func.co_filename, line_no ) hfoslog(sourceloc=sourceloc, emitter=self.uniquename, *args, **kwargs)
Register a configurable component in the configuration schema store def register(self, *args): """Register a configurable component in the configuration schema store""" super(ConfigurableMeta, self).register(*args) from hfos.database import configschemastore # self.log('ADDING SCHEMA:') # pprint(self.configschema) configschemastore[self.name] = self.configschema
Removes the unique name from the systems unique name list def unregister(self): """Removes the unique name from the systems unique name list""" self.names.remove(self.uniquename) super(ConfigurableMeta, self).unregister()
Read this component's configuration from the database def _read_config(self): """Read this component's configuration from the database""" try: self.config = self.componentmodel.find_one( {'name': self.uniquename}) except ServerSelectionTimeoutError: # pragma: no cover self.log("No database access! Check if mongodb is running " "correctly.", lvl=critical) if self.config: self.log("Configuration read.", lvl=verbose) else: self.log("No configuration found.", lvl=warn)
Write this component's configuration back to the database def _write_config(self): """Write this component's configuration back to the database""" if not self.config: self.log("Unable to write non existing configuration", lvl=error) return self.config.save() self.log("Configuration stored.")
Set this component's initial configuration def _set_config(self, config=None): """Set this component's initial configuration""" if not config: config = {} try: # pprint(self.configschema) self.config = self.componentmodel(config) # self.log("Config schema:", lvl=critical) # pprint(self.config.__dict__) # pprint(self.config._fields) try: name = self.config.name self.log("Name set to: ", name, lvl=verbose) except (AttributeError, KeyError): # pragma: no cover self.log("Has no name.", lvl=verbose) try: self.config.name = self.uniquename except (AttributeError, KeyError) as e: # pragma: no cover self.log("Cannot set component name for configuration: ", e, type(e), self.name, exc=True, lvl=critical) try: uuid = self.config.uuid self.log("UUID set to: ", uuid, lvl=verbose) except (AttributeError, KeyError): self.log("Has no UUID", lvl=verbose) self.config.uuid = str(uuid4()) try: notes = self.config.notes self.log("Notes set to: ", notes, lvl=verbose) except (AttributeError, KeyError): self.log("Has no notes, trying docstring", lvl=verbose) notes = self.__doc__ if notes is None: notes = "No notes." else: notes = notes.lstrip().rstrip() self.log(notes) self.config.notes = notes try: componentclass = self.config.componentclass self.log("Componentclass set to: ", componentclass, lvl=verbose) except (AttributeError, KeyError): self.log("Has no component class", lvl=verbose) self.config.componentclass = self.name except ValidationError as e: self.log("Not setting invalid component configuration: ", e, type(e), exc=True, lvl=error)
Event triggered configuration reload def reload_configuration(self, event): """Event triggered configuration reload""" if event.target == self.uniquename: self.log('Reloading configuration') self._read_config()
Fill out the template information def _augment_info(info): """Fill out the template information""" info['description_header'] = "=" * len(info['description']) info['component_name'] = info['plugin_name'].capitalize() info['year'] = time.localtime().tm_year info['license_longtext'] = '' info['keyword_list'] = u"" for keyword in info['keywords'].split(" "): print(keyword) info['keyword_list'] += u"\'" + str(keyword) + u"\', " print(info['keyword_list']) if len(info['keyword_list']) > 0: # strip last comma info['keyword_list'] = info['keyword_list'][:-2] return info
Build a module from templates and user supplied information def _construct_module(info, target): """Build a module from templates and user supplied information""" for path in paths: real_path = os.path.abspath(os.path.join(target, path.format(**info))) log("Making directory '%s'" % real_path) os.makedirs(real_path) # pprint(info) for item in templates.values(): source = os.path.join('dev/templates', item[0]) filename = os.path.abspath( os.path.join(target, item[1].format(**info))) log("Creating file from template '%s'" % filename, emitter='MANAGE') write_template_file(source, filename, info)
Asks questions to fill out a HFOS plugin template def _ask_questionnaire(): """Asks questions to fill out a HFOS plugin template""" answers = {} print(info_header) pprint(questions.items()) for question, default in questions.items(): response = _ask(question, default, str(type(default)), show_hint=True) if type(default) == unicode and type(response) != str: response = response.decode('utf-8') answers[question] = response return answers
Creates a new template HFOS plugin module def create_module(clear_target, target): """Creates a new template HFOS plugin module""" if os.path.exists(target): if clear_target: shutil.rmtree(target) else: log("Target exists! Use --clear to delete it first.", emitter='MANAGE') sys.exit(2) done = False info = None while not done: info = _ask_questionnaire() pprint(info) done = _ask('Is the above correct', default='y', data_type='bool') augmented_info = _augment_info(info) log("Constructing module %(plugin_name)s" % info) _construct_module(augmented_info, target)
Generates a lookup field for form definitions def lookup_field(key, lookup_type=None, placeholder=None, html_class="div", select_type="strapselect", mapping="uuid"): """Generates a lookup field for form definitions""" if lookup_type is None: lookup_type = key if placeholder is None: placeholder = "Select a " + lookup_type result = { 'key': key, 'htmlClass': html_class, 'type': select_type, 'placeholder': placeholder, 'options': { "type": lookup_type, "asyncCallback": "$ctrl.getFormData", "map": {'valueProperty': mapping, 'nameProperty': 'name'} } } return result
A field set with a title and sub items def fieldset(title, items, options=None): """A field set with a title and sub items""" result = { 'title': title, 'type': 'fieldset', 'items': items } if options is not None: result.update(options) return result
A section consisting of rows and columns def section(rows, columns, items, label=None): """A section consisting of rows and columns""" # TODO: Integrate label sections = [] column_class = "section-column col-sm-%i" % (12 / columns) for vertical in range(columns): column_items = [] for horizontal in range(rows): try: item = items[horizontal][vertical] column_items.append(item) except IndexError: hfoslog('Field in', label, 'omitted, due to missing row/column:', vertical, horizontal, lvl=warn, emitter='FORMS', tb=True, frame=2) column = { 'type': 'section', 'htmlClass': column_class, 'items': column_items } sections.append(column) result = { 'type': 'section', 'htmlClass': 'row', 'items': sections } return result
An array that starts empty def emptyArray(key, add_label=None): """An array that starts empty""" result = { 'key': key, 'startEmpty': True } if add_label is not None: result['add'] = add_label result['style'] = {'add': 'btn-success'} return result
A tabbed container widget def tabset(titles, contents): """A tabbed container widget""" tabs = [] for no, title in enumerate(titles): tab = { 'title': title, } content = contents[no] if isinstance(content, list): tab['items'] = content else: tab['items'] = [content] tabs.append(tab) result = { 'type': 'tabs', 'tabs': tabs } return result
Provides a select box for country selection def country_field(key='country'): """Provides a select box for country selection""" country_list = list(countries) title_map = [] for item in country_list: title_map.append({'value': item.alpha_3, 'name': item.name}) widget = { 'key': key, 'type': 'uiselect', 'titleMap': title_map } return widget
Provides a select box for country selection def area_field(key='area'): """Provides a select box for country selection""" area_list = list(subdivisions) title_map = [] for item in area_list: title_map.append({'value': item.code, 'name': item.name}) widget = { 'key': key, 'type': 'uiselect', 'titleMap': title_map } return widget
Tests internet connectivity in regular intervals and updates the nodestate accordingly def timed_connectivity_check(self, event): """Tests internet connectivity in regular intervals and updates the nodestate accordingly""" self.status = self._can_connect() self.log('Timed connectivity check:', self.status, lvl=verbose) if self.status: if not self.old_status: self.log('Connectivity gained') self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, on=True, force=True)) else: if self.old_status: self.log('Connectivity lost', lvl=warn) self.old_status = False self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, off=True, force=True)) self.old_status = self.status
Tries to connect to the configured host:port and returns True if the connection was established def _can_connect(self): """Tries to connect to the configured host:port and returns True if the connection was established""" self.log('Trying to reach configured connectivity check endpoint', lvl=verbose) try: socket.setdefaulttimeout(self.config.timeout) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((self.config.host, self.config.port)) return True except Exception as ex: self.log(ex, pretty=True, lvl=debug) return False
Handles navigational reference frame updates. These are necessary to assign geo coordinates to alerts and other misc things. :param event with incoming referenceframe message def referenceframe(self, event): """Handles navigational reference frame updates. These are necessary to assign geo coordinates to alerts and other misc things. :param event with incoming referenceframe message """ self.log("Got a reference frame update! ", event, lvl=verbose) self.referenceframe = event.data
ActivityMonitor event handler for incoming events :param event with incoming ActivityMonitor message def activityrequest(self, event): """ActivityMonitor event handler for incoming events :param event with incoming ActivityMonitor message """ # self.log("Event: '%s'" % event.__dict__) try: action = event.action data = event.data self.log("Activityrequest: ", action, data) except Exception as e: self.log("Error: '%s' %s" % (e, type(e)), lvl=error)
Modify field values of objects def modify(ctx, schema, uuid, object_filter, field, value): """Modify field values of objects""" database = ctx.obj['db'] model = database.objectmodels[schema] obj = None if uuid: obj = model.find_one({'uuid': uuid}) elif object_filter: obj = model.find_one(literal_eval(object_filter)) else: log('No object uuid or filter specified.', lvl=error) if obj is None: log('No object found', lvl=error) return log('Object found, modifying', lvl=debug) try: new_value = literal_eval(value) except ValueError: log('Interpreting value as string') new_value = str(value) obj._fields[field] = new_value obj.validate() log('Changed object validated', lvl=debug) obj.save() log('Done')
Show stored objects def view(ctx, schema, uuid, object_filter): """Show stored objects""" database = ctx.obj['db'] if schema is None: log('No schema given. Read the help', lvl=warn) return model = database.objectmodels[schema] if uuid: obj = model.find({'uuid': uuid}) elif object_filter: obj = model.find(literal_eval(object_filter)) else: obj = model.find() for item in obj: pprint(item._fields)
Delete stored objects (CAUTION!) def delete(ctx, schema, uuid, object_filter, yes): """Delete stored objects (CAUTION!)""" database = ctx.obj['db'] if schema is None: log('No schema given. Read the help', lvl=warn) return model = database.objectmodels[schema] if uuid: count = model.count({'uuid': uuid}) obj = model.find({'uuid': uuid}) elif object_filter: count = model.count(literal_eval(object_filter)) obj = model.find(literal_eval(object_filter)) else: count = model.count() obj = model.find() if count == 0: log('No objects to delete found') return if not yes and not _ask("Are you sure you want to delete %i objects" % count, default=False, data_type="bool", show_hint=True): return for item in obj: item.delete() log('Done')
Validates all objects or all objects of a given schema. def validate(ctx, schema, all_schemata): """Validates all objects or all objects of a given schema.""" database = ctx.obj['db'] if schema is None: if all_schemata is False: log('No schema given. Read the help', lvl=warn) return else: schemata = database.objectmodels.keys() else: schemata = [schema] for schema in schemata: try: things = database.objectmodels[schema] with click.progressbar(things.find(), length=things.count(), label='Validating %15s' % schema) as object_bar: for obj in object_bar: obj.validate() except Exception as e: log('Exception while validating:', schema, e, type(e), '\n\nFix this object and rerun validation!', emitter='MANAGE', lvl=error) log('Done')
Find fields in registered data models. def find_field(ctx, search, by_type, obj): """Find fields in registered data models.""" # TODO: Fix this to work recursively on all possible subschemes if search is not None: search = search else: search = _ask("Enter search term") database = ctx.obj['db'] def find(search_schema, search_field, find_result=None, key=""): """Examine a schema to find fields by type or name""" if find_result is None: find_result = [] fields = search_schema['properties'] if not by_type: if search_field in fields: find_result.append(key) # log("Found queried fieldname in ", model) else: for field in fields: try: if "type" in fields[field]: # log(fields[field], field) if fields[field]["type"] == search_field: find_result.append((key, field)) # log("Found field", field, "in", model) except KeyError as e: log("Field access error:", e, type(e), exc=True, lvl=debug) if 'properties' in fields: # log('Sub properties checking:', fields['properties']) find_result.append(find(fields['properties'], search_field, find_result, key=fields['name'])) for field in fields: if 'items' in fields[field]: if 'properties' in fields[field]['items']: # log('Sub items checking:', fields[field]) find_result.append(find(fields[field]['items'], search_field, find_result, key=field)) else: pass # log('Items without proper definition!') return find_result if obj is not None: schema = database.objectmodels[obj]._schema result = find(schema, search, [], key="top") if result: # log(args.object, result) print(obj) pprint(result) else: for model, thing in database.objectmodels.items(): schema = thing._schema result = find(schema, search, [], key="top") if result: print(model) # log(model, result) print(result)
Get distance between pairs of lat-lon points def Distance(lat1, lon1, lat2, lon2): """Get distance between pairs of lat-lon points""" az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2) return az21, dist
Display known details about a given client def client_details(self, *args): """Display known details about a given client""" self.log(_('Client details:', lang='de')) client = self._clients[args[0]] self.log('UUID:', client.uuid, 'IP:', client.ip, 'Name:', client.name, 'User:', self._users[client.useruuid], pretty=True)
Display a list of connected clients def client_list(self, *args): """Display a list of connected clients""" if len(self._clients) == 0: self.log('No clients connected') else: self.log(self._clients, pretty=True)
Display a list of connected users def users_list(self, *args): """Display a list of connected users""" if len(self._users) == 0: self.log('No users connected') else: self.log(self._users, pretty=True)
Display a list of all registered events def sourcess_list(self, *args): """Display a list of all registered events""" from pprint import pprint sources = {} sources.update(self.authorized_events) sources.update(self.anonymous_events) for source in sources: pprint(source)
Display a list of all registered events def events_list(self, *args): """Display a list of all registered events""" def merge(a, b, path=None): "merges b into a" if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge(a[key], b[key], path + [str(key)]) elif a[key] == b[key]: pass # same leaf value else: raise Exception('Conflict at %s' % '.'.join(path + [str(key)])) else: a[key] = b[key] return a events = {} sources = merge(self.authorized_events, self.anonymous_events) for source, source_events in sources.items(): events[source] = [] for item in source_events: events[source].append(item) self.log(events, pretty=True)
Display a table of connected users and clients def who(self, *args): """Display a table of connected users and clients""" if len(self._users) == 0: self.log('No users connected') if len(self._clients) == 0: self.log('No clients connected') return Row = namedtuple("Row", ['User', 'Client', 'IP']) rows = [] for user in self._users.values(): for key, client in self._clients.items(): if client.useruuid == user.uuid: row = Row(user.account.name, key, client.ip) rows.append(row) for key, client in self._clients.items(): if client.useruuid is None: row = Row('ANON', key, client.ip) rows.append(row) self.log("\n" + std_table(rows))
Handles socket disconnections def disconnect(self, sock): """Handles socket disconnections""" self.log("Disconnect ", sock, lvl=debug) try: if sock in self._sockets: self.log("Getting socket", lvl=debug) sockobj = self._sockets[sock] self.log("Getting clientuuid", lvl=debug) clientuuid = sockobj.clientuuid self.log("getting useruuid", lvl=debug) useruuid = self._clients[clientuuid].useruuid self.log("Firing disconnect event", lvl=debug) self.fireEvent(clientdisconnect(clientuuid, self._clients[ clientuuid].useruuid)) self.log("Logging out relevant client", lvl=debug) if useruuid is not None: self.log("Client was logged in", lvl=debug) try: self._logoutclient(useruuid, clientuuid) self.log("Client logged out", useruuid, clientuuid) except Exception as e: self.log("Couldn't clean up logged in user! ", self._users[useruuid], e, type(e), lvl=critical) self.log("Deleting Client (", self._clients.keys, ")", lvl=debug) del self._clients[clientuuid] self.log("Deleting Socket", lvl=debug) del self._sockets[sock] except Exception as e: self.log("Error during disconnect handling: ", e, type(e), lvl=critical)
Log out a client and possibly associated user def _logoutclient(self, useruuid, clientuuid): """Log out a client and possibly associated user""" self.log("Cleaning up client of logged in user.", lvl=debug) try: self._users[useruuid].clients.remove(clientuuid) if len(self._users[useruuid].clients) == 0: self.log("Last client of user disconnected.", lvl=verbose) self.fireEvent(userlogout(useruuid, clientuuid)) del self._users[useruuid] self._clients[clientuuid].useruuid = None except Exception as e: self.log("Error during client logout: ", e, type(e), clientuuid, useruuid, lvl=error, exc=True)
Registers new sockets and their clients and allocates uuids def connect(self, *args): """Registers new sockets and their clients and allocates uuids""" self.log("Connect ", args, lvl=verbose) try: sock = args[0] ip = args[1] if sock not in self._sockets: self.log("New client connected:", ip, lvl=debug) clientuuid = str(uuid4()) self._sockets[sock] = Socket(ip, clientuuid) # Key uuid is temporary, until signin, will then be replaced # with account uuid self._clients[clientuuid] = Client( sock=sock, ip=ip, clientuuid=clientuuid, ) self.log("Client connected:", clientuuid, lvl=debug) else: self.log("Old IP reconnected!", lvl=warn) # self.fireEvent(write(sock, "Another client is # connecting from your IP!")) # self._sockets[sock] = (ip, uuid.uuid4()) except Exception as e: self.log("Error during connect: ", e, type(e), lvl=critical)
Sends a packet to an already known user or one of his clients by UUID def send(self, event): """Sends a packet to an already known user or one of his clients by UUID""" try: jsonpacket = json.dumps(event.packet, cls=ComplexEncoder) if event.sendtype == "user": # TODO: I think, caching a user name <-> uuid table would # make sense instead of looking this up all the time. if event.uuid is None: userobject = objectmodels['user'].find_one({ 'name': event.username }) else: userobject = objectmodels['user'].find_one({ 'uuid': event.uuid }) if userobject is None: self.log("No user by that name known.", lvl=warn) return else: uuid = userobject.uuid self.log("Broadcasting to all of users clients: '%s': '%s" % ( uuid, str(event.packet)[:20]), lvl=network) if uuid not in self._users: self.log("User not connected!", event, lvl=critical) return clients = self._users[uuid].clients for clientuuid in clients: sock = self._clients[clientuuid].sock if not event.raw: self.log("Sending json to client", jsonpacket[:50], lvl=network) self.fireEvent(write(sock, jsonpacket), "wsserver") else: self.log("Sending raw data to client") self.fireEvent(write(sock, event.packet), "wsserver") else: # only to client self.log("Sending to user's client: '%s': '%s'" % ( event.uuid, jsonpacket[:20]), lvl=network) if event.uuid not in self._clients: if not event.fail_quiet: self.log("Unknown client!", event.uuid, lvl=critical) self.log("Clients:", self._clients, lvl=debug) return sock = self._clients[event.uuid].sock if not event.raw: self.fireEvent(write(sock, jsonpacket), "wsserver") else: self.log("Sending raw data to client", lvl=network) self.fireEvent(write(sock, event.packet[:20]), "wsserver") except Exception as e: self.log("Exception during sending: %s (%s)" % (e, type(e)), lvl=critical, exc=True)
Broadcasts an event either to all users or clients, depending on event flag def broadcast(self, event): """Broadcasts an event either to all users or clients, depending on event flag""" try: if event.broadcasttype == "users": if len(self._users) > 0: self.log("Broadcasting to all users:", event.content, lvl=network) for useruuid in self._users.keys(): self.fireEvent( send(useruuid, event.content, sendtype="user")) # else: # self.log("Not broadcasting, no users connected.", # lvl=debug) elif event.broadcasttype == "clients": if len(self._clients) > 0: self.log("Broadcasting to all clients: ", event.content, lvl=network) for client in self._clients.values(): self.fireEvent(write(client.sock, event.content), "wsserver") # else: # self.log("Not broadcasting, no clients # connected.", # lvl=debug) elif event.broadcasttype == "socks": if len(self._sockets) > 0: self.log("Emergency?! Broadcasting to all sockets: ", event.content) for sock in self._sockets: self.fireEvent(write(sock, event.content), "wsserver") # else: # self.log("Not broadcasting, no sockets # connected.", # lvl=debug) except Exception as e: self.log("Error during broadcast: ", e, type(e), lvl=critical)
Checks if the user has in any role that allows to fire the event. def _checkPermissions(self, user, event): """Checks if the user has in any role that allows to fire the event.""" for role in user.account.roles: if role in event.roles: self.log('Access granted', lvl=verbose) return True self.log('Access denied', lvl=verbose) return False
Isolated communication link for authorized events. def _handleAuthorizedEvents(self, component, action, data, user, client): """Isolated communication link for authorized events.""" try: if component == "debugger": self.log(component, action, data, user, client, lvl=info) if not user and component in self.authorized_events.keys(): self.log("Unknown client tried to do an authenticated " "operation: %s", component, action, data, user) return event = self.authorized_events[component][action]['event'](user, action, data, client) self.log('Authorized event roles:', event.roles, lvl=verbose) if not self._checkPermissions(user, event): result = { 'component': 'hfos.ui.clientmanager', 'action': 'Permission', 'data': _('You have no role that allows this action.', lang='de') } self.fireEvent(send(event.client.uuid, result)) return self.log("Firing authorized event: ", component, action, str(data)[:100], lvl=debug) # self.log("", (user, action, data, client), lvl=critical) self.fireEvent(event) except Exception as e: self.log("Critical error during authorized event handling:", component, action, e, type(e), lvl=critical, exc=True)
Handler for anonymous (public) events def _handleAnonymousEvents(self, component, action, data, client): """Handler for anonymous (public) events""" try: event = self.anonymous_events[component][action]['event'] self.log("Firing anonymous event: ", component, action, str(data)[:20], lvl=network) # self.log("", (user, action, data, client), lvl=critical) self.fireEvent(event(action, data, client)) except Exception as e: self.log("Critical error during anonymous event handling:", component, action, e, type(e), lvl=critical, exc=True)
Handler for authentication events def _handleAuthenticationEvents(self, requestdata, requestaction, clientuuid, sock): """Handler for authentication events""" # TODO: Move this stuff over to ./auth.py if requestaction in ("login", "autologin"): try: self.log("Login request", lvl=verbose) if requestaction == "autologin": username = password = None requestedclientuuid = requestdata auto = True self.log("Autologin for", requestedclientuuid, lvl=debug) else: username = requestdata['username'] password = requestdata['password'] if 'clientuuid' in requestdata: requestedclientuuid = requestdata['clientuuid'] else: requestedclientuuid = None auto = False self.log("Auth request by", username, lvl=verbose) self.fireEvent(authenticationrequest( username, password, clientuuid, requestedclientuuid, sock, auto, ), "auth") return except Exception as e: self.log("Login failed: ", e, type(e), lvl=warn, exc=True) elif requestaction == "logout": self.log("User logged out, refreshing client.", lvl=network) try: if clientuuid in self._clients: client = self._clients[clientuuid] user_id = client.useruuid if client.useruuid: self.log("Logout client uuid: ", clientuuid) self._logoutclient(client.useruuid, clientuuid) self.fireEvent(clientdisconnect(clientuuid)) else: self.log("Client is not connected!", lvl=warn) except Exception as e: self.log("Error during client logout: ", e, type(e), lvl=error, exc=True) else: self.log("Unsupported auth action requested:", requestaction, lvl=warn)
Resets the list of flood offenders on event trigger def _reset_flood_offenders(self, *args): """Resets the list of flood offenders on event trigger""" offenders = [] # self.log('Resetting flood offenders') for offender, offence_time in self._flooding.items(): if time() - offence_time < 10: self.log('Removed offender from flood list:', offender) offenders.append(offender) for offender in offenders: del self._flooding[offender]
Checks if any clients have been flooding the node def _check_flood_protection(self, component, action, clientuuid): """Checks if any clients have been flooding the node""" if clientuuid not in self._flood_counter: self._flood_counter[clientuuid] = 0 self._flood_counter[clientuuid] += 1 if self._flood_counter[clientuuid] > 100: packet = { 'component': 'hfos.ui.clientmanager', 'action': 'Flooding', 'data': True } self.fireEvent(send(clientuuid, packet)) self.log('Flooding from', clientuuid) return True
Handles raw client requests and distributes them to the appropriate components def read(self, *args): """Handles raw client requests and distributes them to the appropriate components""" self.log("Beginning new transaction: ", args, lvl=network) try: sock, msg = args[0], args[1] user = password = client = clientuuid = useruuid = requestdata = \ requestaction = None # self.log("", msg) clientuuid = self._sockets[sock].clientuuid except Exception as e: self.log("Receiving error: ", e, type(e), lvl=error) if clientuuid in self._flooding: return try: msg = json.loads(msg) self.log("Message from client received: ", msg, lvl=network) except Exception as e: self.log("JSON Decoding failed! %s (%s of %s)" % (msg, e, type(e))) return try: requestcomponent = msg['component'] requestaction = msg['action'] except (KeyError, AttributeError) as e: self.log("Unpacking error: ", msg, e, type(e), lvl=error) return if self._check_flood_protection(requestcomponent, requestaction, clientuuid): self.log('Flood protection triggered') self._flooding[clientuuid] = time() try: # TODO: Do not unpickle or decode anything from unsafe events requestdata = msg['data'] if isinstance(requestdata, (dict, list)) and 'raw' in requestdata: # self.log(requestdata['raw'], lvl=critical) requestdata['raw'] = b64decode(requestdata['raw']) # self.log(requestdata['raw']) except (KeyError, AttributeError) as e: self.log("No payload.", lvl=network) requestdata = None if requestcomponent == "auth": self._handleAuthenticationEvents(requestdata, requestaction, clientuuid, sock) return try: client = self._clients[clientuuid] except KeyError as e: self.log('Could not get client for request!', e, type(e), lvl=warn) return if requestcomponent in self.anonymous_events and requestaction in \ self.anonymous_events[requestcomponent]: self.log('Executing anonymous event:', requestcomponent, requestaction) try: self._handleAnonymousEvents(requestcomponent, requestaction, requestdata, client) except Exception as e: self.log("Anonymous request failed:", e, type(e), lvl=warn, exc=True) return elif requestcomponent in self.authorized_events: try: useruuid = client.useruuid self.log("Authenticated operation requested by ", useruuid, client.config, lvl=network) except Exception as e: self.log("No useruuid!", e, type(e), lvl=critical) return self.log('Checking if user is logged in', lvl=verbose) try: user = self._users[useruuid] except KeyError: if not (requestaction == 'ping' and requestcomponent == 'hfos.ui.clientmanager'): self.log("User not logged in.", lvl=warn) return self.log('Handling event:', requestcomponent, requestaction, lvl=verbose) try: self._handleAuthorizedEvents(requestcomponent, requestaction, requestdata, user, client) except Exception as e: self.log("User request failed: ", e, type(e), lvl=warn, exc=True) else: self.log('Invalid event received:', requestcomponent, requestaction, lvl=warn)
Links the client to the granted account and profile, then notifies the client def authentication(self, event): """Links the client to the granted account and profile, then notifies the client""" try: self.log("Authorization has been granted by DB check:", event.username, lvl=debug) account, profile, clientconfig = event.userdata useruuid = event.useruuid originatingclientuuid = event.clientuuid clientuuid = clientconfig.uuid if clientuuid != originatingclientuuid: self.log("Mutating client uuid to request id:", clientuuid, lvl=network) # Assign client to user if useruuid in self._users: signedinuser = self._users[useruuid] else: signedinuser = User(account, profile, useruuid) self._users[account.uuid] = signedinuser if clientuuid in signedinuser.clients: self.log("Client configuration already logged in.", lvl=critical) # TODO: What now?? # Probably senseful would be to add the socket to the # client's other socket # The clients would be identical then - that could cause # problems # which could be remedied by duplicating the configuration else: signedinuser.clients.append(clientuuid) self.log("Active client (", clientuuid, ") registered to " "user", useruuid, lvl=debug) # Update socket.. socket = self._sockets[event.sock] socket.clientuuid = clientuuid self._sockets[event.sock] = socket # ..and client lists try: language = clientconfig.language except AttributeError: language = "en" # TODO: Rewrite and simplify this: newclient = Client( sock=event.sock, ip=socket.ip, clientuuid=clientuuid, useruuid=useruuid, name=clientconfig.name, config=clientconfig, language=language ) del (self._clients[originatingclientuuid]) self._clients[clientuuid] = newclient authpacket = {"component": "auth", "action": "login", "data": account.serializablefields()} self.log("Transmitting Authorization to client", authpacket, lvl=network) self.fireEvent( write(event.sock, json.dumps(authpacket)), "wsserver" ) profilepacket = {"component": "profile", "action": "get", "data": profile.serializablefields()} self.log("Transmitting Profile to client", profilepacket, lvl=network) self.fireEvent(write(event.sock, json.dumps(profilepacket)), "wsserver") clientconfigpacket = {"component": "clientconfig", "action": "get", "data": clientconfig.serializablefields()} self.log("Transmitting client configuration to client", clientconfigpacket, lvl=network) self.fireEvent(write(event.sock, json.dumps(clientconfigpacket)), "wsserver") self.fireEvent(userlogin(clientuuid, useruuid, clientconfig, signedinuser)) self.log("User configured: Name", signedinuser.account.name, "Profile", signedinuser.profile.uuid, "Clients", signedinuser.clients, lvl=debug) except Exception as e: self.log("Error (%s, %s) during auth grant: %s" % ( type(e), e, event), lvl=error)
Store client's selection of a new translation def selectlanguage(self, event): """Store client's selection of a new translation""" self.log('Language selection event:', event.client, pretty=True) if event.data not in all_languages(): self.log('Unavailable language selected:', event.data, lvl=warn) language = None else: language = event.data if language is None: language = 'en' event.client.language = language if event.client.config is not None: event.client.config.language = language event.client.config.save()
Compile and return a human readable list of registered translations def getlanguages(self, event): """Compile and return a human readable list of registered translations""" self.log('Client requests all languages.', lvl=verbose) result = { 'component': 'hfos.ui.clientmanager', 'action': 'getlanguages', 'data': language_token_to_name(all_languages()) } self.fireEvent(send(event.client.uuid, result))
Perform a ping to measure client <-> node latency def ping(self, event): """Perform a ping to measure client <-> node latency""" self.log('Client ping received:', event.data, lvl=verbose) response = { 'component': 'hfos.ui.clientmanager', 'action': 'pong', 'data': [event.data, time() * 1000] } self.fire(send(event.client.uuid, response))
Converts between geodetic, modified apex, quasi-dipole and MLT. Parameters ========== lat : array_like Latitude lon : array_like Longitude/MLT source : {'geo', 'apex', 'qd', 'mlt'} Input coordinate system dest : {'geo', 'apex', 'qd', 'mlt'} Output coordinate system height : array_like, optional Altitude in km datetime : :class:`datetime.datetime` Date and time for MLT conversions (required for MLT conversions) precision : float, optional Precision of output (degrees) when converting to geo. A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision (all coordinates being converted to geo are converted to QD first and passed through APXG2Q). ssheight : float, optional Altitude in km to use for converting the subsolar point from geographic to magnetic coordinates. A high altitude is used to ensure the subsolar point is mapped to high latitudes, which prevents the South-Atlantic Anomaly (SAA) from influencing the MLT. Returns ======= lat : ndarray or float Converted latitude (if converting to MLT, output latitude is apex) lat : ndarray or float Converted longitude/MLT def convert(self, lat, lon, source, dest, height=0, datetime=None, precision=1e-10, ssheight=50*6371): """Converts between geodetic, modified apex, quasi-dipole and MLT. Parameters ========== lat : array_like Latitude lon : array_like Longitude/MLT source : {'geo', 'apex', 'qd', 'mlt'} Input coordinate system dest : {'geo', 'apex', 'qd', 'mlt'} Output coordinate system height : array_like, optional Altitude in km datetime : :class:`datetime.datetime` Date and time for MLT conversions (required for MLT conversions) precision : float, optional Precision of output (degrees) when converting to geo. A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision (all coordinates being converted to geo are converted to QD first and passed through APXG2Q). ssheight : float, optional Altitude in km to use for converting the subsolar point from geographic to magnetic coordinates. A high altitude is used to ensure the subsolar point is mapped to high latitudes, which prevents the South-Atlantic Anomaly (SAA) from influencing the MLT. Returns ======= lat : ndarray or float Converted latitude (if converting to MLT, output latitude is apex) lat : ndarray or float Converted longitude/MLT """ if datetime is None and ('mlt' in [source, dest]): raise ValueError('datetime must be given for MLT calculations') lat = helpers.checklat(lat) if source == dest: return lat, lon # from geo elif source == 'geo' and dest == 'apex': lat, lon = self.geo2apex(lat, lon, height) elif source == 'geo' and dest == 'qd': lat, lon = self.geo2qd(lat, lon, height) elif source == 'geo' and dest == 'mlt': lat, lon = self.geo2apex(lat, lon, height) lon = self.mlon2mlt(lon, datetime, ssheight=ssheight) # from apex elif source == 'apex' and dest == 'geo': lat, lon, _ = self.apex2geo(lat, lon, height, precision=precision) elif source == 'apex' and dest == 'qd': lat, lon = self.apex2qd(lat, lon, height=height) elif source == 'apex' and dest == 'mlt': lon = self.mlon2mlt(lon, datetime, ssheight=ssheight) # from qd elif source == 'qd' and dest == 'geo': lat, lon, _ = self.qd2geo(lat, lon, height, precision=precision) elif source == 'qd' and dest == 'apex': lat, lon = self.qd2apex(lat, lon, height=height) elif source == 'qd' and dest == 'mlt': lat, lon = self.qd2apex(lat, lon, height=height) lon = self.mlon2mlt(lon, datetime, ssheight=ssheight) # from mlt (input latitude assumed apex) elif source == 'mlt' and dest == 'geo': lon = self.mlt2mlon(lon, datetime, ssheight=ssheight) lat, lon, _ = self.apex2geo(lat, lon, height, precision=precision) elif source == 'mlt' and dest == 'apex': lon = self.mlt2mlon(lon, datetime, ssheight=ssheight) elif source == 'mlt' and dest == 'qd': lon = self.mlt2mlon(lon, datetime, ssheight=ssheight) lat, lon = self.apex2qd(lat, lon, height=height) # no other transformations are implemented else: estr = 'Unknown coordinate transformation: ' estr += '{} -> {}'.format(source, dest) raise NotImplementedError(estr) return lat, lon
Converts geodetic to modified apex coordinates. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Altitude in km Returns ======= alat : ndarray or float Modified apex latitude alon : ndarray or float Modified apex longitude def geo2apex(self, glat, glon, height): """Converts geodetic to modified apex coordinates. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Altitude in km Returns ======= alat : ndarray or float Modified apex latitude alon : ndarray or float Modified apex longitude """ glat = helpers.checklat(glat, name='glat') alat, alon = self._geo2apex(glat, glon, height) if np.any(np.float64(alat) == -9999): warnings.warn('Apex latitude set to -9999 where undefined ' '(apex height may be < reference height)') # if array is returned, dtype is object, so convert to float return np.float64(alat), np.float64(alon)
Converts modified apex to geodetic coordinates. Parameters ========== alat : array_like Modified apex latitude alon : array_like Modified apex longitude height : array_like Altitude in km precision : float, optional Precision of output (degrees). A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision. Returns ======= glat : ndarray or float Geodetic latitude glon : ndarray or float Geodetic longitude error : ndarray or float The angular difference (degrees) between the input QD coordinates and the qlat/qlon produced by feeding the output glat and glon into geo2qd (APXG2Q) def apex2geo(self, alat, alon, height, precision=1e-10): """Converts modified apex to geodetic coordinates. Parameters ========== alat : array_like Modified apex latitude alon : array_like Modified apex longitude height : array_like Altitude in km precision : float, optional Precision of output (degrees). A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision. Returns ======= glat : ndarray or float Geodetic latitude glon : ndarray or float Geodetic longitude error : ndarray or float The angular difference (degrees) between the input QD coordinates and the qlat/qlon produced by feeding the output glat and glon into geo2qd (APXG2Q) """ alat = helpers.checklat(alat, name='alat') qlat, qlon = self.apex2qd(alat, alon, height=height) glat, glon, error = self.qd2geo(qlat, qlon, height, precision=precision) return glat, glon, error
Converts geodetic to quasi-dipole coordinates. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Altitude in km Returns ======= qlat : ndarray or float Quasi-dipole latitude qlon : ndarray or float Quasi-dipole longitude def geo2qd(self, glat, glon, height): """Converts geodetic to quasi-dipole coordinates. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Altitude in km Returns ======= qlat : ndarray or float Quasi-dipole latitude qlon : ndarray or float Quasi-dipole longitude """ glat = helpers.checklat(glat, name='glat') qlat, qlon = self._geo2qd(glat, glon, height) # if array is returned, dtype is object, so convert to float return np.float64(qlat), np.float64(qlon)
Converts quasi-dipole to geodetic coordinates. Parameters ========== qlat : array_like Quasi-dipole latitude qlon : array_like Quasi-dipole longitude height : array_like Altitude in km precision : float, optional Precision of output (degrees). A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision. Returns ======= glat : ndarray or float Geodetic latitude glon : ndarray or float Geodetic longitude error : ndarray or float The angular difference (degrees) between the input QD coordinates and the qlat/qlon produced by feeding the output glat and glon into geo2qd (APXG2Q) def qd2geo(self, qlat, qlon, height, precision=1e-10): """Converts quasi-dipole to geodetic coordinates. Parameters ========== qlat : array_like Quasi-dipole latitude qlon : array_like Quasi-dipole longitude height : array_like Altitude in km precision : float, optional Precision of output (degrees). A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision. Returns ======= glat : ndarray or float Geodetic latitude glon : ndarray or float Geodetic longitude error : ndarray or float The angular difference (degrees) between the input QD coordinates and the qlat/qlon produced by feeding the output glat and glon into geo2qd (APXG2Q) """ qlat = helpers.checklat(qlat, name='qlat') glat, glon, error = self._qd2geo(qlat, qlon, height, precision) # if array is returned, dtype is object, so convert to float return np.float64(glat), np.float64(glon), np.float64(error)
Convert from apex to quasi-dipole (not-vectorised) Parameters ----------- alat : (float) Apex latitude in degrees alon : (float) Apex longitude in degrees height : (float) Height in km Returns --------- qlat : (float) Quasi-dipole latitude in degrees qlon : (float) Quasi-diplole longitude in degrees def _apex2qd_nonvectorized(self, alat, alon, height): """Convert from apex to quasi-dipole (not-vectorised) Parameters ----------- alat : (float) Apex latitude in degrees alon : (float) Apex longitude in degrees height : (float) Height in km Returns --------- qlat : (float) Quasi-dipole latitude in degrees qlon : (float) Quasi-diplole longitude in degrees """ alat = helpers.checklat(alat, name='alat') # convert modified apex to quasi-dipole: qlon = alon # apex height hA = self.get_apex(alat) if hA < height: if np.isclose(hA, height, rtol=0, atol=1e-5): # allow for values that are close hA = height else: estr = 'height {:.3g} is > apex height '.format(np.max(height)) estr += '{:.3g} for alat {:.3g}'.format(hA, alat) raise ApexHeightError(estr) qlat = np.sign(alat) * np.degrees(np.arccos(np.sqrt((self.RE + height) / (self.RE + hA)))) return qlat, qlon
Converts modified apex to quasi-dipole coordinates. Parameters ========== alat : array_like Modified apex latitude alon : array_like Modified apex longitude height : array_like Altitude in km Returns ======= qlat : ndarray or float Quasi-dipole latitude qlon : ndarray or float Quasi-dipole longitude Raises ====== ApexHeightError if `height` > apex height def apex2qd(self, alat, alon, height): """Converts modified apex to quasi-dipole coordinates. Parameters ========== alat : array_like Modified apex latitude alon : array_like Modified apex longitude height : array_like Altitude in km Returns ======= qlat : ndarray or float Quasi-dipole latitude qlon : ndarray or float Quasi-dipole longitude Raises ====== ApexHeightError if `height` > apex height """ qlat, qlon = self._apex2qd(alat, alon, height) # if array is returned, the dtype is object, so convert to float return np.float64(qlat), np.float64(qlon)
Converts quasi-dipole to modified apex coordinates. Parameters ========== qlat : array_like Quasi-dipole latitude qlon : array_like Quasi-dipole longitude height : array_like Altitude in km Returns ======= alat : ndarray or float Modified apex latitude alon : ndarray or float Modified apex longitude Raises ====== ApexHeightError if apex height < reference height def qd2apex(self, qlat, qlon, height): """Converts quasi-dipole to modified apex coordinates. Parameters ========== qlat : array_like Quasi-dipole latitude qlon : array_like Quasi-dipole longitude height : array_like Altitude in km Returns ======= alat : ndarray or float Modified apex latitude alon : ndarray or float Modified apex longitude Raises ====== ApexHeightError if apex height < reference height """ alat, alon = self._qd2apex(qlat, qlon, height) # if array is returned, the dtype is object, so convert to float return np.float64(alat), np.float64(alon)
Computes the magnetic local time at the specified magnetic longitude and UT. Parameters ========== mlon : array_like Magnetic longitude (apex and quasi-dipole longitude are always equal) datetime : :class:`datetime.datetime` Date and time ssheight : float, optional Altitude in km to use for converting the subsolar point from geographic to magnetic coordinates. A high altitude is used to ensure the subsolar point is mapped to high latitudes, which prevents the South-Atlantic Anomaly (SAA) from influencing the MLT. Returns ======= mlt : ndarray or float Magnetic local time [0, 24) Notes ===== To compute the MLT, we find the apex longitude of the subsolar point at the given time. Then the MLT of the given point will be computed from the separation in magnetic longitude from this point (1 hour = 15 degrees). def mlon2mlt(self, mlon, datetime, ssheight=50*6371): """Computes the magnetic local time at the specified magnetic longitude and UT. Parameters ========== mlon : array_like Magnetic longitude (apex and quasi-dipole longitude are always equal) datetime : :class:`datetime.datetime` Date and time ssheight : float, optional Altitude in km to use for converting the subsolar point from geographic to magnetic coordinates. A high altitude is used to ensure the subsolar point is mapped to high latitudes, which prevents the South-Atlantic Anomaly (SAA) from influencing the MLT. Returns ======= mlt : ndarray or float Magnetic local time [0, 24) Notes ===== To compute the MLT, we find the apex longitude of the subsolar point at the given time. Then the MLT of the given point will be computed from the separation in magnetic longitude from this point (1 hour = 15 degrees). """ ssglat, ssglon = helpers.subsol(datetime) ssalat, ssalon = self.geo2apex(ssglat, ssglon, ssheight) # np.float64 will ensure lists are converted to arrays return (180 + np.float64(mlon) - ssalon)/15 % 24
Computes the magnetic longitude at the specified magnetic local time and UT. Parameters ========== mlt : array_like Magnetic local time datetime : :class:`datetime.datetime` Date and time ssheight : float, optional Altitude in km to use for converting the subsolar point from geographic to magnetic coordinates. A high altitude is used to ensure the subsolar point is mapped to high latitudes, which prevents the South-Atlantic Anomaly (SAA) from influencing the MLT. Returns ======= mlon : ndarray or float Magnetic longitude [0, 360) (apex and quasi-dipole longitude are always equal) Notes ===== To compute the magnetic longitude, we find the apex longitude of the subsolar point at the given time. Then the magnetic longitude of the given point will be computed from the separation in magnetic local time from this point (1 hour = 15 degrees). def mlt2mlon(self, mlt, datetime, ssheight=50*6371): """Computes the magnetic longitude at the specified magnetic local time and UT. Parameters ========== mlt : array_like Magnetic local time datetime : :class:`datetime.datetime` Date and time ssheight : float, optional Altitude in km to use for converting the subsolar point from geographic to magnetic coordinates. A high altitude is used to ensure the subsolar point is mapped to high latitudes, which prevents the South-Atlantic Anomaly (SAA) from influencing the MLT. Returns ======= mlon : ndarray or float Magnetic longitude [0, 360) (apex and quasi-dipole longitude are always equal) Notes ===== To compute the magnetic longitude, we find the apex longitude of the subsolar point at the given time. Then the magnetic longitude of the given point will be computed from the separation in magnetic local time from this point (1 hour = 15 degrees). """ ssglat, ssglon = helpers.subsol(datetime) ssalat, ssalon = self.geo2apex(ssglat, ssglon, ssheight) # np.float64 will ensure lists are converted to arrays return (15*np.float64(mlt) - 180 + ssalon + 360) % 360
Performs mapping of points along the magnetic field to the closest or conjugate hemisphere. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Source altitude in km newheight : array_like Destination altitude in km conjugate : bool, optional Map to `newheight` in the conjugate hemisphere instead of the closest hemisphere precision : float, optional Precision of output (degrees). A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision. Returns ======= newglat : ndarray or float Geodetic latitude of mapped point newglon : ndarray or float Geodetic longitude of mapped point error : ndarray or float The angular difference (degrees) between the input QD coordinates and the qlat/qlon produced by feeding the output glat and glon into geo2qd (APXG2Q) Notes ===== The mapping is done by converting glat/glon/height to modified apex lat/lon, and converting back to geographic using newheight (if conjugate, use negative apex latitude when converting back) def map_to_height(self, glat, glon, height, newheight, conjugate=False, precision=1e-10): """Performs mapping of points along the magnetic field to the closest or conjugate hemisphere. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Source altitude in km newheight : array_like Destination altitude in km conjugate : bool, optional Map to `newheight` in the conjugate hemisphere instead of the closest hemisphere precision : float, optional Precision of output (degrees). A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision. Returns ======= newglat : ndarray or float Geodetic latitude of mapped point newglon : ndarray or float Geodetic longitude of mapped point error : ndarray or float The angular difference (degrees) between the input QD coordinates and the qlat/qlon produced by feeding the output glat and glon into geo2qd (APXG2Q) Notes ===== The mapping is done by converting glat/glon/height to modified apex lat/lon, and converting back to geographic using newheight (if conjugate, use negative apex latitude when converting back) """ alat, alon = self.geo2apex(glat, glon, height) if conjugate: alat = -alat try: newglat, newglon, error = self.apex2geo(alat, alon, newheight, precision=precision) except ApexHeightError: raise ApexHeightError("newheight is > apex height") return newglat, newglon, error
Performs mapping of electric field along the magnetic field. It is assumed that the electric field is perpendicular to B. Parameters ========== alat : (N,) array_like or float Modified apex latitude alon : (N,) array_like or float Modified apex longitude height : (N,) array_like or float Source altitude in km newheight : (N,) array_like or float Destination altitude in km E : (3,) or (3, N) array_like Electric field (at `alat`, `alon`, `height`) in geodetic east, north, and up components Returns ======= E : (3, N) or (3,) ndarray The electric field at `newheight` (geodetic east, north, and up components) def map_E_to_height(self, alat, alon, height, newheight, E): """Performs mapping of electric field along the magnetic field. It is assumed that the electric field is perpendicular to B. Parameters ========== alat : (N,) array_like or float Modified apex latitude alon : (N,) array_like or float Modified apex longitude height : (N,) array_like or float Source altitude in km newheight : (N,) array_like or float Destination altitude in km E : (3,) or (3, N) array_like Electric field (at `alat`, `alon`, `height`) in geodetic east, north, and up components Returns ======= E : (3, N) or (3,) ndarray The electric field at `newheight` (geodetic east, north, and up components) """ return self._map_EV_to_height(alat, alon, height, newheight, E, 'E')
Performs mapping of electric drift velocity along the magnetic field. It is assumed that the electric field is perpendicular to B. Parameters ========== alat : (N,) array_like or float Modified apex latitude alon : (N,) array_like or float Modified apex longitude height : (N,) array_like or float Source altitude in km newheight : (N,) array_like or float Destination altitude in km V : (3,) or (3, N) array_like Electric drift velocity (at `alat`, `alon`, `height`) in geodetic east, north, and up components Returns ======= V : (3, N) or (3,) ndarray The electric drift velocity at `newheight` (geodetic east, north, and up components) def map_V_to_height(self, alat, alon, height, newheight, V): """Performs mapping of electric drift velocity along the magnetic field. It is assumed that the electric field is perpendicular to B. Parameters ========== alat : (N,) array_like or float Modified apex latitude alon : (N,) array_like or float Modified apex longitude height : (N,) array_like or float Source altitude in km newheight : (N,) array_like or float Destination altitude in km V : (3,) or (3, N) array_like Electric drift velocity (at `alat`, `alon`, `height`) in geodetic east, north, and up components Returns ======= V : (3, N) or (3,) ndarray The electric drift velocity at `newheight` (geodetic east, north, and up components) """ return self._map_EV_to_height(alat, alon, height, newheight, V, 'V')
Returns quasi-dipole base vectors f1 and f2 at the specified coordinates. The vectors are described by Richmond [1995] [2]_ and Emmert et al. [2010] [3]_. The vector components are geodetic east and north. Parameters ========== lat : (N,) array_like or float Latitude lon : (N,) array_like or float Longitude height : (N,) array_like or float Altitude in km coords : {'geo', 'apex', 'qd'}, optional Input coordinate system precision : float, optional Precision of output (degrees) when converting to geo. A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision (all coordinates being converted to geo are converted to QD first and passed through APXG2Q). Returns ======= f1 : (2, N) or (2,) ndarray f2 : (2, N) or (2,) ndarray References ========== .. [2] Richmond, A. D. (1995), Ionospheric Electrodynamics Using Magnetic Apex Coordinates, Journal of geomagnetism and geoelectricity, 47(2), 191–212, :doi:`10.5636/jgg.47.191`. .. [3] Emmert, J. T., A. D. Richmond, and D. P. Drob (2010), A computationally compact representation of Magnetic-Apex and Quasi-Dipole coordinates with smooth base vectors, J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`. def basevectors_qd(self, lat, lon, height, coords='geo', precision=1e-10): """Returns quasi-dipole base vectors f1 and f2 at the specified coordinates. The vectors are described by Richmond [1995] [2]_ and Emmert et al. [2010] [3]_. The vector components are geodetic east and north. Parameters ========== lat : (N,) array_like or float Latitude lon : (N,) array_like or float Longitude height : (N,) array_like or float Altitude in km coords : {'geo', 'apex', 'qd'}, optional Input coordinate system precision : float, optional Precision of output (degrees) when converting to geo. A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision (all coordinates being converted to geo are converted to QD first and passed through APXG2Q). Returns ======= f1 : (2, N) or (2,) ndarray f2 : (2, N) or (2,) ndarray References ========== .. [2] Richmond, A. D. (1995), Ionospheric Electrodynamics Using Magnetic Apex Coordinates, Journal of geomagnetism and geoelectricity, 47(2), 191–212, :doi:`10.5636/jgg.47.191`. .. [3] Emmert, J. T., A. D. Richmond, and D. P. Drob (2010), A computationally compact representation of Magnetic-Apex and Quasi-Dipole coordinates with smooth base vectors, J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`. """ glat, glon = self.convert(lat, lon, coords, 'geo', height=height, precision=precision) f1, f2 = self._basevec(glat, glon, height) # if inputs are not scalar, each vector is an array of arrays, # so reshape to a single array if f1.dtype == object: f1 = np.vstack(f1).T f2 = np.vstack(f2).T return f1, f2
Returns base vectors in quasi-dipole and apex coordinates. The vectors are described by Richmond [1995] [4]_ and Emmert et al. [2010] [5]_. The vector components are geodetic east, north, and up (only east and north for `f1` and `f2`). Parameters ========== lat, lon : (N,) array_like or float Latitude lat : (N,) array_like or float Longitude height : (N,) array_like or float Altitude in km coords : {'geo', 'apex', 'qd'}, optional Input coordinate system return_all : bool, optional Will also return f3, g1, g2, and g3, and f1 and f2 have 3 components (the last component is zero). Requires `lat`, `lon`, and `height` to be broadcast to 1D (at least one of the parameters must be 1D and the other two parameters must be 1D or 0D). precision : float, optional Precision of output (degrees) when converting to geo. A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision (all coordinates being converted to geo are converted to QD first and passed through APXG2Q). Returns ======= f1, f2 : (2, N) or (2,) ndarray f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 : (3, N) or (3,) ndarray Note ==== `f3`, `g1`, `g2`, and `g3` are not part of the Fortran code by Emmert et al. [2010] [5]_. They are calculated by this Python library according to the following equations in Richmond [1995] [4]_: * `g1`: Eqn. 6.3 * `g2`: Eqn. 6.4 * `g3`: Eqn. 6.5 * `f3`: Eqn. 6.8 References ========== .. [4] Richmond, A. D. (1995), Ionospheric Electrodynamics Using Magnetic Apex Coordinates, Journal of geomagnetism and geoelectricity, 47(2), 191–212, :doi:`10.5636/jgg.47.191`. .. [5] Emmert, J. T., A. D. Richmond, and D. P. Drob (2010), A computationally compact representation of Magnetic-Apex and Quasi-Dipole coordinates with smooth base vectors, J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`. def basevectors_apex(self, lat, lon, height, coords='geo', precision=1e-10): """Returns base vectors in quasi-dipole and apex coordinates. The vectors are described by Richmond [1995] [4]_ and Emmert et al. [2010] [5]_. The vector components are geodetic east, north, and up (only east and north for `f1` and `f2`). Parameters ========== lat, lon : (N,) array_like or float Latitude lat : (N,) array_like or float Longitude height : (N,) array_like or float Altitude in km coords : {'geo', 'apex', 'qd'}, optional Input coordinate system return_all : bool, optional Will also return f3, g1, g2, and g3, and f1 and f2 have 3 components (the last component is zero). Requires `lat`, `lon`, and `height` to be broadcast to 1D (at least one of the parameters must be 1D and the other two parameters must be 1D or 0D). precision : float, optional Precision of output (degrees) when converting to geo. A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision (all coordinates being converted to geo are converted to QD first and passed through APXG2Q). Returns ======= f1, f2 : (2, N) or (2,) ndarray f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 : (3, N) or (3,) ndarray Note ==== `f3`, `g1`, `g2`, and `g3` are not part of the Fortran code by Emmert et al. [2010] [5]_. They are calculated by this Python library according to the following equations in Richmond [1995] [4]_: * `g1`: Eqn. 6.3 * `g2`: Eqn. 6.4 * `g3`: Eqn. 6.5 * `f3`: Eqn. 6.8 References ========== .. [4] Richmond, A. D. (1995), Ionospheric Electrodynamics Using Magnetic Apex Coordinates, Journal of geomagnetism and geoelectricity, 47(2), 191–212, :doi:`10.5636/jgg.47.191`. .. [5] Emmert, J. T., A. D. Richmond, and D. P. Drob (2010), A computationally compact representation of Magnetic-Apex and Quasi-Dipole coordinates with smooth base vectors, J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`. """ glat, glon = self.convert(lat, lon, coords, 'geo', height=height, precision=precision) returnvals = self._geo2apexall(glat, glon, height) qlat = np.float64(returnvals[0]) alat = np.float64(returnvals[2]) f1, f2 = returnvals[4:6] d1, d2, d3 = returnvals[7:10] e1, e2, e3 = returnvals[11:14] # if inputs are not scalar, each vector is an array of arrays, # so reshape to a single array if f1.dtype == object: f1 = np.vstack(f1).T f2 = np.vstack(f2).T d1 = np.vstack(d1).T d2 = np.vstack(d2).T d3 = np.vstack(d3).T e1 = np.vstack(e1).T e2 = np.vstack(e2).T e3 = np.vstack(e3).T # make sure arrays are 2D f1 = f1.reshape((2, f1.size//2)) f2 = f2.reshape((2, f2.size//2)) d1 = d1.reshape((3, d1.size//3)) d2 = d2.reshape((3, d2.size//3)) d3 = d3.reshape((3, d3.size//3)) e1 = e1.reshape((3, e1.size//3)) e2 = e2.reshape((3, e2.size//3)) e3 = e3.reshape((3, e3.size//3)) # compute f3, g1, g2, g3 F1 = np.vstack((f1, np.zeros_like(f1[0]))) F2 = np.vstack((f2, np.zeros_like(f2[0]))) F = np.cross(F1.T, F2.T).T[-1] cosI = helpers.getcosIm(alat) k = np.array([0, 0, 1], dtype=np.float64).reshape((3, 1)) g1 = ((self.RE + np.float64(height)) / (self.RE + self.refh))**(3/2) \ * d1 / F g2 = -1.0 / (2.0 * F * np.tan(np.radians(qlat))) * \ (k + ((self.RE + np.float64(height)) / (self.RE + self.refh)) * d2 / cosI) g3 = k*F f3 = np.cross(g1.T, g2.T).T if np.any(alat == -9999): warnings.warn(('Base vectors g, d, e, and f3 set to -9999 where ' 'apex latitude is undefined (apex height may be < ' 'reference height)')) f3 = np.where(alat == -9999, -9999, f3) g1 = np.where(alat == -9999, -9999, g1) g2 = np.where(alat == -9999, -9999, g2) g3 = np.where(alat == -9999, -9999, g3) d1 = np.where(alat == -9999, -9999, d1) d2 = np.where(alat == -9999, -9999, d2) d3 = np.where(alat == -9999, -9999, d3) e1 = np.where(alat == -9999, -9999, e1) e2 = np.where(alat == -9999, -9999, e2) e3 = np.where(alat == -9999, -9999, e3) return tuple(np.squeeze(x) for x in [f1, f2, f3, g1, g2, g3, d1, d2, d3, e1, e2, e3])
Calculate apex height Parameters ----------- lat : (float) Latitude in degrees height : (float or NoneType) Height above the surface of the earth in km or NoneType to use reference height (default=None) Returns ---------- apex_height : (float) Height of the field line apex in km def get_apex(self, lat, height=None): """ Calculate apex height Parameters ----------- lat : (float) Latitude in degrees height : (float or NoneType) Height above the surface of the earth in km or NoneType to use reference height (default=None) Returns ---------- apex_height : (float) Height of the field line apex in km """ lat = helpers.checklat(lat, name='alat') if height is None: height = self.refh cos_lat_squared = np.cos(np.radians(lat))**2 apex_height = (self.RE + height) / cos_lat_squared - self.RE return apex_height
Updates the epoch for all subsequent conversions. Parameters ========== year : float Decimal year def set_epoch(self, year): """Updates the epoch for all subsequent conversions. Parameters ========== year : float Decimal year """ fa.loadapxsh(self.datafile, np.float(year)) self.year = year
Basic ordered parser. def basic_parser(patterns, with_name=None): """ Basic ordered parser. """ def parse(line): output = None highest_order = 0 highest_pattern_name = None for pattern in patterns: results = pattern.findall(line) if results and any(results): if pattern.order > highest_order: output = results highest_order = pattern.order if with_name: highest_pattern_name = pattern.name if with_name: return output, highest_pattern_name return output return parse
This parser is able to handle multiple different patterns finding stuff in text-- while removing matches that overlap. def alt_parser(patterns): """ This parser is able to handle multiple different patterns finding stuff in text-- while removing matches that overlap. """ from reparse.util import remove_lower_overlapping get_first = lambda items: [i[0] for i in items] get_second = lambda items: [i[1] for i in items] def parse(line): output = [] for pattern in patterns: results = pattern.scan(line) if results and any(results): output.append((pattern.order, results)) return get_first(reduce(remove_lower_overlapping, get_second(sorted(output)), [])) return parse
This parser_type simply outputs an array of [(tree, regex)] for use in another language. def build_tree_parser(patterns): """ This parser_type simply outputs an array of [(tree, regex)] for use in another language. """ def output(): for pattern in patterns: yield (pattern.build_full_tree(), pattern.regex) return list(output())
A Reparse parser description. Simply provide the functions, patterns, & expressions to build. If you are using YAML for expressions + patterns, you can use ``expressions_yaml_path`` & ``patterns_yaml_path`` for convenience. The default parser_type is the basic ordered parser. def parser(parser_type=basic_parser, functions=None, patterns=None, expressions=None, patterns_yaml_path=None, expressions_yaml_path=None): """ A Reparse parser description. Simply provide the functions, patterns, & expressions to build. If you are using YAML for expressions + patterns, you can use ``expressions_yaml_path`` & ``patterns_yaml_path`` for convenience. The default parser_type is the basic ordered parser. """ from reparse.builders import build_all from reparse.validators import validate def _load_yaml(file_path): import yaml with open(file_path) as f: return yaml.safe_load(f) assert expressions or expressions_yaml_path, "Reparse can't build a parser without expressions" assert patterns or patterns_yaml_path, "Reparse can't build a parser without patterns" assert functions, "Reparse can't build without a functions" if patterns_yaml_path: patterns = _load_yaml(patterns_yaml_path) if expressions_yaml_path: expressions = _load_yaml(expressions_yaml_path) validate(patterns, expressions) return parser_type(build_all(patterns, expressions, functions))
Translate KML file to geojson for import def _translate(self, input_filename, output_filename): """Translate KML file to geojson for import""" command = [ self.translate_binary, '-f', 'GeoJSON', output_filename, input_filename ] result = self._runcommand(command) self.log('Result (Translate): ', result, lvl=debug)
Update a single specified guide def _update_guide(self, guide, update=False, clear=True): """Update a single specified guide""" kml_filename = os.path.join(self.cache_path, guide + '.kml') geojson_filename = os.path.join(self.cache_path, guide + '.geojson') if not os.path.exists(geojson_filename) or update: try: data = request.urlopen(self.guides[guide]).read().decode( 'utf-8') except (request.URLError, request.HTTPError) as e: self.log('Could not get web guide data:', e, type(e), lvl=warn) return with open(kml_filename, 'w') as f: f.write(data) self._translate(kml_filename, geojson_filename) with open(geojson_filename, 'r') as f: json_data = json.loads(f.read()) if len(json_data['features']) == 0: self.log('No features found!', lvl=warn) return layer = objectmodels['layer'].find_one({'name': guide}) if clear and layer is not None: layer.delete() layer = None if layer is None: layer_uuid = std_uuid() layer = objectmodels['layer']({ 'uuid': layer_uuid, 'name': guide, 'type': 'geoobjects' }) layer.save() else: layer_uuid = layer.uuid if clear: for item in objectmodels['geoobject'].find({'layer': layer_uuid}): self.log('Deleting old guide location', lvl=debug) item.delete() locations = [] for item in json_data['features']: self.log('Adding new guide location:', item, lvl=verbose) location = objectmodels['geoobject']({ 'uuid': std_uuid(), 'layer': layer_uuid, 'geojson': item, 'type': 'Skipperguide', 'name': 'Guide for %s' % (item['properties']['Name']) }) locations.append(location) self.log('Bulk inserting guide locations', lvl=debug) objectmodels['geoobject'].bulk_create(locations)
Worker task to send out an email, which is a blocking process unless it is threaded def send_mail_worker(config, mail, event): """Worker task to send out an email, which is a blocking process unless it is threaded""" log = "" try: if config.get('ssl', True): server = SMTP_SSL(config['server'], port=config['port'], timeout=30) else: server = SMTP(config['server'], port=config['port'], timeout=30) if config['tls']: log += 'Starting TLS\n' server.starttls() if config['username'] != '': log += 'Logging in with ' + str(config['username']) + "\n" server.login(config['username'], config['password']) else: log += 'No username, trying anonymous access\n' log += 'Sending Mail\n' response_send = server.send_message(mail) server.quit() except timeout as e: log += 'Could not send email: ' + str(e) + "\n" return False, log, event log += 'Server response:' + str(response_send) return True, log, event
Connect to mail server and send actual email def send_mail(self, event): """Connect to mail server and send actual email""" mime_mail = MIMEText(event.text) mime_mail['Subject'] = event.subject if event.account == 'default': account_name = self.config.default_account else: account_name = event.account account = list(filter(lambda account: account['name'] == account_name, self.config.accounts))[0] mime_mail['From'] = render(account['mail_from'], {'server': account['server'], 'hostname': self.hostname}) mime_mail['To'] = event.to_address self.log('MimeMail:', mime_mail, lvl=verbose) if self.config.mail_send is True: self.log('Sending mail to', event.to_address) self.fireEvent(task(send_mail_worker, account, mime_mail, event), "mail-transmit-workers") else: self.log('Not sending mail, here it is for debugging info:', mime_mail, pretty=True)
Provision a system user def provision_system_user(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provision a system user""" from hfos.provisions.base import provisionList from hfos.database import objectmodels # TODO: Add a root user and make sure owner can access it later. # Setting up details and asking for a password here is not very useful, # since this process is usually run automated. if overwrite is True: hfoslog('Refusing to overwrite system user!', lvl=warn, emitter='PROVISIONS') overwrite = False system_user_count = objectmodels['user'].count({'name': 'System'}) if system_user_count == 0 or clear is False: provisionList(Users, 'user', overwrite, clear, skip_user_check=True) hfoslog('Provisioning: Users: Done.', emitter="PROVISIONS") else: hfoslog('System user already present.', lvl=warn, emitter='PROVISIONS')
Group expressions using the OR character ``|`` >>> from collections import namedtuple >>> expr = namedtuple('expr', 'regex group_lengths run')('(1)', [1], None) >>> grouping = AlternatesGroup([expr, expr], lambda f: None, 'yeah') >>> grouping.regex # doctest: +IGNORE_UNICODE '(?:(1))|(?:(1))' >>> grouping.group_lengths [1, 1] def AlternatesGroup(expressions, final_function, name=""): """ Group expressions using the OR character ``|`` >>> from collections import namedtuple >>> expr = namedtuple('expr', 'regex group_lengths run')('(1)', [1], None) >>> grouping = AlternatesGroup([expr, expr], lambda f: None, 'yeah') >>> grouping.regex # doctest: +IGNORE_UNICODE '(?:(1))|(?:(1))' >>> grouping.group_lengths [1, 1] """ inbetweens = ["|"] * (len(expressions) + 1) inbetweens[0] = "" inbetweens[-1] = "" return Group(expressions, final_function, inbetweens, name)
Group expressions together with ``inbetweens`` and with the output of a ``final_functions``. def Group(expressions, final_function, inbetweens, name=""): """ Group expressions together with ``inbetweens`` and with the output of a ``final_functions``. """ lengths = [] functions = [] regex = "" i = 0 for expression in expressions: regex += inbetweens[i] regex += "(?:" + expression.regex + ")" lengths.append(sum(expression.group_lengths)) functions.append(expression.run) i += 1 regex += inbetweens[i] return Expression(regex, functions, lengths, final_function, name)
Parse string, returning all outputs as parsed by functions def findall(self, string): """ Parse string, returning all outputs as parsed by functions """ output = [] for match in self.pattern.findall(string): if hasattr(match, 'strip'): match = [match] self._list_add(output, self.run(match)) return output
Like findall, but also returning matching start and end string locations def scan(self, string): """ Like findall, but also returning matching start and end string locations """ return list(self._scanner_to_matches(self.pattern.scanner(string), self.run))
Run group functions over matches def run(self, matches): """ Run group functions over matches """ def _run(matches): group_starting_pos = 0 for current_pos, (group_length, group_function) in enumerate(zip(self.group_lengths, self.group_functions)): start_pos = current_pos + group_starting_pos end_pos = current_pos + group_starting_pos + group_length yield group_function(matches[start_pos:end_pos]) group_starting_pos += group_length - 1 return self.final_function(list(_run(matches)))
Specify logfile path def set_logfile(path, instance): """Specify logfile path""" global logfile logfile = os.path.normpath(path) + '/hfos.' + instance + '.log'
Checks if a logged event is to be muted for debugging purposes. Also goes through the solo list - only items in there will be logged! :param what: :return: def is_muted(what): """ Checks if a logged event is to be muted for debugging purposes. Also goes through the solo list - only items in there will be logged! :param what: :return: """ state = False for item in solo: if item not in what: state = True else: state = False break for item in mute: if item in what: state = True break return state
Logs all *what arguments. :param *what: Loggable objects (i.e. they have a string representation) :param lvl: Debug message level :param exc: Switch to better handle exceptions, use if logging in an except clause :param emitter: Optional log source, where this can't be determined automatically :param sourceloc: Give specific source code location hints, used internally def hfoslog(*what, **kwargs): """Logs all *what arguments. :param *what: Loggable objects (i.e. they have a string representation) :param lvl: Debug message level :param exc: Switch to better handle exceptions, use if logging in an except clause :param emitter: Optional log source, where this can't be determined automatically :param sourceloc: Give specific source code location hints, used internally """ # Count all messages (missing numbers give a hint at too high log level) global count global verbosity count += 1 lvl = kwargs.get('lvl', info) if lvl < verbosity['global']: return emitter = kwargs.get('emitter', 'UNKNOWN') traceback = kwargs.get('tb', False) frame_ref = kwargs.get('frame_ref', 0) output = None timestamp = time.time() runtime = timestamp - start callee = None exception = kwargs.get('exc', False) if exception: exc_type, exc_obj, exc_tb = sys.exc_info() # NOQA if verbosity['global'] <= debug or traceback: # Automatically log the current function details. if 'sourceloc' not in kwargs: frame = kwargs.get('frame', frame_ref) # Get the previous frame in the stack, otherwise it would # be this function current_frame = inspect.currentframe() while frame > 0: frame -= 1 current_frame = current_frame.f_back func = current_frame.f_code # Dump the message + the name of this function to the log. if exception: line_no = exc_tb.tb_lineno if lvl <= error: lvl = error else: line_no = func.co_firstlineno callee = "[%.10s@%s:%i]" % ( func.co_name, func.co_filename, line_no ) else: callee = kwargs['sourceloc'] now = time.asctime() msg = "[%s] : %5s : %.5f : %3i : [%5s]" % (now, lvldata[lvl][0], runtime, count, emitter) content = "" if callee: if not uncut and lvl > 10: msg += "%-60s" % callee else: msg += "%s" % callee for thing in what: content += " " if kwargs.get('pretty', False): content += pprint.pformat(thing) else: content += str(thing) msg += content if exception: msg += "\n" + "".join(format_exception(exc_type, exc_obj, exc_tb)) if is_muted(msg): return if not uncut and lvl > 10 and len(msg) > 1000: msg = msg[:1000] if lvl >= verbosity['file']: try: f = open(logfile, "a") f.write(msg + '\n') f.flush() f.close() except IOError: print("Can't open logfile %s for writing!" % logfile) # sys.exit(23) if is_marked(msg): lvl = hilight if lvl >= verbosity['console']: output = str(msg) if six.PY3 and color: output = lvldata[lvl][1] + output + terminator try: print(output) except UnicodeEncodeError as e: print(output.encode("utf-8")) hfoslog("Bad encoding encountered on previous message:", e, lvl=error) except BlockingIOError: hfoslog("Too long log line encountered:", output[:20], lvl=warn) if live: item = [now, lvl, runtime, count, emitter, str(content)] LiveLog.append(item)
Return a list of tagged objects for a schema def get_tagged(self, event): """Return a list of tagged objects for a schema""" self.log("Tagged objects request for", event.data, "from", event.user, lvl=debug) if event.data in self.tags: tagged = self._get_tagged(event.data) response = { 'component': 'hfos.events.schemamanager', 'action': 'get', 'data': tagged } self.fireEvent(send(event.client.uuid, response)) else: self.log("Unavailable schema requested!", lvl=warn)
Provisions the default system vessel def provision_system_vessel(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provisions the default system vessel""" from hfos.provisions.base import provisionList from hfos.database import objectmodels vessel = objectmodels['vessel'].find_one({'name': 'Default System Vessel'}) if vessel is not None: if overwrite is False: hfoslog('Default vessel already existing. Skipping provisions.') return else: vessel.delete() provisionList([SystemVessel], 'vessel', overwrite, clear, skip_user_check) sysconfig = objectmodels['systemconfig'].find_one({'active': True}) hfoslog('Adapting system config for default vessel:', sysconfig) sysconfig.vesseluuid = SystemVessel['uuid'] sysconfig.save() hfoslog('Provisioning: Vessel: Done.', emitter='PROVISIONS')
Threadable function to retrieve map tiles from the internet :param url: URL of tile to get def get_tile(url): """ Threadable function to retrieve map tiles from the internet :param url: URL of tile to get """ log = "" connection = None try: if six.PY3: connection = urlopen(url=url, timeout=2) # NOQA else: connection = urlopen(url=url) except Exception as e: log += "MTST: ERROR Tilegetter error: %s " % str([type(e), e, url]) content = "" # Read and return requested content if connection: try: content = connection.read() except (socket.timeout, socket.error) as e: log += "MTST: ERROR Tilegetter error: %s " % str([type(e), e]) connection.close() else: log += "MTST: ERROR Got no connection." return content, log
Checks and caches a requested tile to disk, then delivers it to client def tilecache(self, event, *args, **kwargs): """Checks and caches a requested tile to disk, then delivers it to client""" request, response = event.args[:2] self.log(request.path, lvl=verbose) try: filename, url = self._split_cache_url(request.path, 'tilecache') except UrlError: return # self.log('CACHE QUERY:', filename, url) # Do we have the tile already? if os.path.isfile(filename): self.log("Tile exists in cache", lvl=verbose) # Don't set cookies for static content response.cookie.clear() try: yield serve_file(request, response, filename) finally: event.stop() else: # We will have to get it first. self.log("Tile not cached yet. Tile data: ", filename, url, lvl=verbose) if url in self._tiles: self.log("Getting a tile for the second time?!", lvl=error) else: self._tiles += url try: tile, log = yield self.call(task(get_tile, url), "tcworkers") if log: self.log("Thread error: ", log, lvl=error) except Exception as e: self.log("[MTS]", e, type(e)) tile = None tile_path = os.path.dirname(filename) if tile: try: os.makedirs(tile_path) except OSError as e: if e.errno != errno.EEXIST: self.log( "Couldn't create path: %s (%s)" % (e, type(e)), lvl=error) self.log("Caching tile.", lvl=verbose) try: with open(filename, "wb") as tile_file: try: tile_file.write(bytes(tile)) except Exception as e: self.log("Writing error: %s" % str([type(e), e]), lvl=error) except Exception as e: self.log("Open error on %s - %s" % (filename, str([type(e), e])), lvl=error) return finally: event.stop() try: self.log("Delivering tile.", lvl=verbose) yield serve_file(request, response, filename) except Exception as e: self.log("Couldn't deliver tile: ", e, lvl=error) event.stop() self.log("Tile stored and delivered.", lvl=verbose) else: self.log("Got no tile, serving default tile: %s" % url) if self.default_tile: try: yield serve_file(request, response, self.default_tile) except Exception as e: self.log('Cannot deliver default tile:', e, type(e), exc=True, lvl=error) finally: event.stop() else: yield
Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD def todegdec(origin): """ Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD """ # if the input is already a float (or can be converted to float) try: return float(origin) except ValueError: pass # DMS format m = dms_re.search(origin) if m: degrees = int(m.group('degrees')) minutes = float(m.group('minutes')) seconds = float(m.group('seconds')) return degrees + minutes / 60 + seconds / 3600 # Degree + Minutes format m = mindec_re.search(origin) if m: degrees = int(m.group('degrees')) minutes = float(m.group('minutes')) return degrees + minutes / 60
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes) def tomindec(origin): """ Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes) """ origin = float(origin) degrees = int(origin) minutes = (origin % 1) * 60 return degrees, minutes
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM' def tomindecstr(origin): """ Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM' """ degrees, minutes = tomindec(origin) return u'%d°%f\'' % (degrees, minutes)
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes, seconds) def todms(origin): """ Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes, seconds) """ degrees, minutes = tomindec(origin) seconds = (minutes % 1) * 60 return degrees, int(minutes), seconds
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD" def todmsstr(origin): """ Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD" """ degrees, minutes, seconds = todms(origin) return u'%d°%d\'%f"' % (degrees, minutes, seconds)