code stringlengths 1 18.2k |
|---|
data.', lvl=warn) return print('Writing migration: ', os.path.join(path, filename)) pprint(migration) with open(os.path.join(path, filename), 'w') as f: f.write(migration) for schema_entrypoint in iter_entry_points(group='hfos.schemata', name=None): try: hfoslog("Schemata found: ", schema_entrypoint.name, lvl=debug, em... |
in sorted(os.listdir(path)): if not file.endswith('.json'): continue fullpath = os.path.join(path, file) hfoslog('Importing migration', fullpath) with open(fullpath, 'r') as f: migration = DeepDiff.from_json(f.read()) migrations.append(migration) hfoslog('Successfully imported') if len(migrations) == 0: raise ImportErr... |
(ImportError, DistributionNotFound) as e: hfoslog("Problematic schema: ", e, type(e), schema_entrypoint.name, exc=True, lvl=warn, emitter='SCHEMATA') hfoslog("Found schemata: ", sorted(entrypoints.keys()), lvl=debug, emitter='SCHEMATA') pprint(entrypoints) def make_single_migration(old, new): pass |
def userlogin(self, event): """Provides the newly authenticated user with a backlog and general channel status information""" try: user_uuid = event.useruuid user = objectmodels['user'].find_one({'uuid': user_uuid}) if user_uuid not in self.lastlogs: self.log('Setting up lastlog for a new user.', lvl=debug) lastlog = o... |
during chat setup of user:', e, type(e), exc=True) |
def join(self, event): """Chat event handler for incoming events :param event: say-event with incoming chat message """ try: channel_uuid = event.data user_uuid = event.user.uuid if channel_uuid in self.chat_channels: self.log('User joins a known channel', lvl=debug) if user_uuid in self.chat_channels[channel_uuid].use... |
except Exception as e: self.log('Join error:', e, type(e), exc=True, lvl=error) |
def say(self, event): """Chat event handler for incoming events :param event: say-event with incoming chat message """ try: userid = event.user.uuid recipient = self._get_recipient(event) content = self._get_content(event) message = objectmodels['chatmessage']({ 'timestamp': time(), 'recipient': recipient, 'sender': us... |
self.log('User in channel', lvl=debug) self.update_lastlog(useruuid, recipient) self.log('Sending message', lvl=debug) self.fireEvent(send(useruuid, chat_packet, sendtype='user')) except Exception as e: self.log("Error: '%s' %s" % (e, type(e)), exc=True, lvl=error) |
def install_docs(instance, clear_target): """Builds and installs the complete HFOS documentation.""" _check_root() def make_docs(): """Trigger a Sphinx make command to build the documentation.""" log("Generating HTML documentation") try: build = Popen( [ 'make', 'html' ], cwd='docs/' ) build.wait() except Exception as ... |
and don't remove # wanted stuff! target = os.path.join('/var/lib/hfos', instance, 'frontend/docs') source = 'docs/build/html' log("Updating documentation directory:", target) if not os.path.exists(os.path.join(os.path.curdir, source)): log( "Documentation not existing yet. Run python setup.py " "build_sphinx first.", l... |
def var(ctx, clear_target, clear_all): """Install variable data to /var/[lib,cache]/hfos""" install_var(str(ctx.obj['instance']), clear_target, clear_all) |
def install_var(instance, clear_target, clear_all): """Install required folders in /var""" _check_root() log("Checking frontend library and cache directories", emitter='MANAGE') uid = pwd.getpwnam("hfos").pw_uid gid = grp.getgrnam("hfos").gr_gid join = os.path.join # If these need changes, make sure they are watertight... |
join('/var/cache/hfos', instance, 'rastertiles'), join('/var/cache/hfos', instance, 'rastercache') ) logfile = "/var/log/hfos-" + instance + ".log" for item in target_paths: if os.path.exists(item): log("Path already exists: " + item) if clear_all or (clear_target and 'cache' in item): log("Cleaning up: " + item, lvl=w... |
uid, gid) log("Done: Install Var") |
def provisions(ctx, provision, clear_existing, overwrite, list_provisions): """Install default provisioning data""" install_provisions(ctx, provision, clear_existing, overwrite, list_provisions) |
def install_provisions(ctx, provision, clear_provisions=False, overwrite=False, list_provisions=False): """Install default provisioning data""" log("Installing HFOS default provisions") # from hfos.logger import verbosity, events # verbosity['console'] = verbosity['global'] = events from hfos import database database.i... |
= item.get('dependencies', []) if isinstance(dependencies, str): dependencies = [dependencies] if key not in g: g.add_node(key) for link in dependencies: g.add_edge(key, link) if not networkx.is_directed_acyclic_graph(g): log('Cycles in provosioning dependency graph detected!', lvl=error) log('Involved provisions:', li... |
method(data, model, overwrite=overwrite, clear=clear_provisions) if provision is not None: if provision in provision_store: log("Provisioning ", provision, pretty=True) provision_item(provision_store[provision]) else: log("Unknown provision: ", provision, "\nValid provisions are", list(provision_store.keys()), lvl=erro... |
def install_modules(wip): """Install the plugin modules""" def install_module(hfos_module): """Install a single module via setuptools""" try: setup = Popen( [ sys.executable, 'setup.py', 'develop' ], cwd='modules/' + hfos_module + "/" ) setup.wait() except Exception as e: log("Problem during module installation: ", hfo... |
# To get the module dependencies: # packages = {} # for provision_entrypoint in iter_entry_points(group='hfos.provisions', # name=None): # log("Found packages: ", provision_entrypoint.dist.project_name, lvl=warn) # # _package_name = provision_entrypoint.dist.project_name # _package = pkg_resources.working_set.by_key[_p... |
and they're not available on pypi, # which would handle real dependency management for us: 'navdata', # Now all the rest: 'alert', 'automat', 'busrepeater', 'calendar', 'countables', 'dash', # 'dev', 'enrol', 'mail', 'maps', 'nmea', 'nodestate', 'project', 'webguides', 'wiki' ] modules_wip = [ 'calc', 'camera', 'chat',... |
if wip: installables.extend(modules_wip) success = [] failed = [] for installable in installables: log('Installing module ', installable) if install_module(installable): success.append(installable) else: failed.append(installable) log('Installed modules: ', success) if len(failed) > 0: log('Failed modules: ', failed) l... |
def service(ctx): """Install systemd service configuration""" install_service(ctx.obj['instance'], ctx.obj['dbhost'], ctx.obj['dbname'], ctx.obj['port']) |
def install_service(instance, dbhost, dbname, port): """Install systemd service configuration""" _check_root() log("Installing systemd service") launcher = os.path.realpath(__file__).replace('manage', 'launcher') executable = sys.executable + " " + launcher executable += " --instance " + instance executable += " --dbna... |
" --logfileverbosity 30 -q" definitions = { 'instance': instance, 'executable': executable } service_name = 'hfos-' + instance + '.service' write_template_file(os.path.join('dev/templates', service_template), os.path.join('/etc/systemd/system/', service_name), definitions) Popen([ 'systemctl', 'enable', service_name ])... |
def nginx(ctx, hostname): """Install nginx configuration""" install_nginx(ctx.obj['dbhost'], ctx.obj['dbname'], ctx.obj['port'], hostname) |
def install_nginx(instance, dbhost, dbname, port, hostname=None): """Install nginx configuration""" _check_root() log("Installing nginx configuration") if hostname is None: try: configuration = _get_system_configuration(dbhost, dbname) hostname = configuration.hostname except Exception as e: log('Exception:', e, type(e... |
definitions = { 'instance': instance, 'server_public_name': hostname, 'ssl_certificate': cert_file, 'ssl_key': key_file, 'host_url': 'http://127.0.0.1:%i/' % port } if distribution == 'DEBIAN': configuration_file = '/etc/nginx/sites-available/hfos.%s.conf' % instance configuration_link = '/etc/nginx/sites-enabled/hfos.... |
if configuration_link is not None: log('Enabling nginx HFOS site (symlink)') if not os.path.exists(configuration_link): os.symlink(configuration_file, configuration_link) log('Restarting nginx service') Popen([ 'systemctl', 'restart', 'nginx.service' ]) log("Done: Install nginx configuration") |
def install_cert(selfsigned): """Install a local SSL certificate""" _check_root() if selfsigned: log('Generating self signed (insecure) certificate/key ' 'combination') try: os.mkdir('/etc/ssl/certs/hfos') except FileExistsError: pass except PermissionError: log("Need root (e.g. via sudo) to generate ssl certificate") ... |
serial = old_cert.get_serial_number() + 1 except (crypto.Error, OSError) as e: log('Could not read old certificate to increment ' 'serial:', type(e), e, exc=True, lvl=warn) serial = 1 else: serial = 1 # create a self-signed certificate certificate = crypto.X509() certificate.get_subject().C = "DE" certificate.get_subje... |
* 24 * 60 * 60) certificate.set_issuer(certificate.get_subject()) certificate.set_pubkey(k) certificate.sign(k, b'sha512') open(key_file, "wt").write(str( crypto.dump_privatekey(crypto.FILETYPE_PEM, k), encoding="ASCII")) open(cert_file, "wt").write(str( crypto.dump_certificate(crypto.FILETYPE_PEM, certificate), encodi... |
used server side and ' 'there is no way to enter a separate key.', lvl=error) |
def frontend(ctx, dev, rebuild, no_install, build_type): """Build and install frontend""" install_frontend(instance=ctx.obj['instance'], forcerebuild=rebuild, development=dev, install=not no_install, build_type=build_type) |
def install_all(ctx, clear_all): """Default-Install everything installable \b This includes * System user (hfos.hfos) * Self signed certificate * Variable data locations (/var/lib/hfos and /var/cache/hfos) * All the official modules in this repository * Default module provisioning data * Documentation * systemd service... |
ctx.obj['port'] install_system_user() install_cert(selfsigned=True) install_var(instance, clear_target=clear_all, clear_all=clear_all) install_modules(wip=False) install_provisions(provision=None, clear_provisions=clear_all) install_docs(instance, clear_target=clear_all) install_service(instance, dbhost, dbname, port) ... |
def uninstall(): """Uninstall data and resource locations""" _check_root() response = _ask("This will delete all data of your HFOS installations! Type" "YES to continue:", default="N", show_hint=False) if response == 'YES': shutil.rmtree('/var/lib/hfos') shutil.rmtree('/var/cache/hfos') |
def update(ctx, no_restart, no_rebuild): """Update a HFOS node""" # 0. (NOT YET! MAKE A BACKUP OF EVERYTHING) # 1. update repository # 2. update frontend repository # 3. (Not yet: update venv) # 4. rebuild frontend # 5. restart service instance = ctx.obj['instance'] log('Pulling github updates') run_process('.', ['git'... |
development=True) if not no_restart: log('Restaring service') if instance != 'hfos': instance = 'hfos-' + instance run_process('.', ['sudo', 'systemctl', 'restart', instance]) log('Done') |
def raw_data(self, event): """Handles incoming raw sensor data :param event: Raw sentences incoming data """ self.log('Received raw data from bus', lvl=events) if not parse: return nmea_time = event.data[0] try: parsed_data = parse(event.data[1]) except Exception as e: self.log('Unparseable sentence:', event.data[1], e... |
"navdata") |
def clear_all(): """DANGER! *This command is a maintenance tool and clears the complete database.* """ sure = input("Are you sure to drop the complete database content? (Type " "in upppercase YES)") if not (sure == 'YES'): db_log('Not deleting the database.') sys.exit(5) client = pymongo.MongoClient(host=dbhost, port=d... |
def _build_model_factories(store): """Generate factories to construct objects from schemata""" result = {} for schemaname in store: schema = None try: schema = store[schemaname]['schema'] except KeyError: schemata_log("No schema found for ", schemaname, lvl=critical, exc=True) try: result[schemaname] = warmongo.model_f... |
def _build_collections(store): """Generate database collections with indices from the schemastore""" result = {} client = pymongo.MongoClient(host=dbhost, port=dbport) db = client[dbname] for schemaname in store: schema = None indices = None try: schema = store[schemaname]['schema'] indices = store[schemaname].get('ind... |
if indices is not None: col = db[schemaname] db_log('Adding indices to', schemaname, lvl=debug) i = 0 keys = list(indices.keys()) while i < len(indices): index_name = keys[i] index = indices[index_name] index_type = index.get('type', None) index_unique = index.get('unique', False) index_sparse = index.get('sparse', Tru... |
unique=index_unique, sparse=index_sparse) db_log('Enabling index of type', index_type, 'on', index_name, lvl=debug) try: do_index() i += 1 except pymongo.errors.OperationFailure: db_log(col.list_indexes().__dict__, pretty=True, lvl=verbose) if not index_reindex: db_log('Index was not created!', lvl=warn) i += 1 else: t... |
def initialize(address='127.0.0.1:27017', database_name='hfos', instance_name="default", reload=False): """Initializes the database connectivity, schemata and finally object models""" global schemastore global l10n_schemastore global objectmodels global collections global dbhost global dbport global dbname global insta... |
'@', dbhost, ':', dbport) try: client = pymongo.MongoClient(host=dbhost, port=dbport) db = client[dbname] db_log("Database: ", db.command('buildinfo'), lvl=debug) except Exception as e: db_log("No database available! Check if you have mongodb > 3.0 " "installed and running as well as listening on port 27017 " "of local... |
_build_collections(schemastore) instance = instance_name initialized = True |
def profile(schemaname='sensordata', profiletype='pjs'): """Profiles object model handling with a very simple benchmarking test""" db_log("Profiling ", schemaname) schema = schemastore[schemaname]['schema'] db_log("Schema: ", schema, lvl=debug) testclass = None if profiletype == 'warmongo': db_log("Running Warmongo ben... |
pjs.ObjectBuilder(schema) ns = builder.build_classes() pprint(ns) testclass = ns[schemaname] db_log("ns: ", ns, lvl=warn) if testclass is not None: db_log("Instantiating elements...") for i in range(100): testclass() else: db_log("No Profiletype available!") db_log("Profiling done") |
def backup(schema, uuid, export_filter, export_format, filename, pretty, export_all, omit): """Exports all collections to (JSON-) files.""" export_format = export_format.upper() if pretty: indent = 4 else: indent = 0 f = None if filename: try: f = open(filename, 'w') except (IOError, PermissionError) as e: backup_log('... |
if export_format == 'JSON': data = json.dumps(what, indent=indent) else: data = "" else: data = what if not filename: print(data) else: f.write(data) if schema is None: if export_all is False: backup_log('No schema given.', lvl=warn) return else: schemata = objectmodels.keys() else: schemata = [schema] all_items = {} f... |
else: obj = model.find() items = [] for item in obj: fields = item.serializablefields() for field in omit: try: fields.pop(field) except KeyError: pass items.append(fields) all_items[schema_item] = items # if pretty is True: # output('\n// Objectmodel: ' + schema_item + '\n\n') # output(schema_item + ' = [\n') output(a... |
def _check_collections(self): """Checks node local collection storage sizes""" self.collection_sizes = {} self.collection_total = 0 for col in self.db.collection_names(include_system_collections=False): self.collection_sizes[col] = self.db.command('collstats', col).get( 'storageSize', 0) self.collection_total += self.c... |
def _check_free_space(self): """Checks used filesystem storage sizes""" def get_folder_size(path): """Aggregates used size of a specified path, recursively""" total_size = 0 for item in walk(path): for file in item[2]: try: total_size = total_size + getsize(join(item[0], file)) except (OSError, PermissionError) as e: s... |
self.log('Location unavailable:', name, e, type(e), lvl=error, exc=True) continue free_space = stats.f_frsize * stats.f_bavail used_space = get_folder_size( checkpoint['location'] ) / 1024.0 / 1024 self.log('Location %s uses %.2f MB' % (name, used_space)) if free_space < checkpoint['minimum']: self.log('Short of free s... |
def send_mail_worker(config, mail, event): """Worker task to send out an email, which blocks the process unless it is threaded""" log = "" try: if config.mail_ssl: server = SMTP_SSL(config.mail_server, port=config.mail_server_port, timeout=30) else: server = SMTP(config.mail_server, port=config.mail_server_port, timeou... |
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 to enrollee, mailserver timeout: ' + str(e) + "\n" return False, log, event log += 'Server response:' + str(response_send) return True, log, event |
def reload_configuration(self, event): """Reload the current configuration and set up everything depending on it""" super(EnrolManager, self).reload_configuration(event) self.log('Reloaded configuration.') self._setup() |
def change(self, event): """An admin user requests a change to an enrolment""" uuid = event.data['uuid'] status = event.data['status'] if status not in ['Open', 'Pending', 'Accepted', 'Denied', 'Resend']: self.log('Erroneous status for enrollment requested!', lvl=warn) return self.log('Changing status of an enrollment'... |
self._send_invitation(enrollment, event) reply = {True: 'Resent'} else: enrollment.status = status enrollment.save() reply = {True: enrollment.serializablefields()} if status == 'Accepted' and enrollment.method == 'Enrolled': self._create_user(enrollment.name, enrollment.password, enrollment.email, 'Invited', event.cli... |
def changepassword(self, event): """An enrolled user wants to change their password""" old = event.data['old'] new = event.data['new'] uuid = event.user.uuid # TODO: Write email to notify user of password change user = objectmodels['user'].find_one({'uuid': uuid}) if std_hash(old, self.salt) == user.passhash: user.pass... |
= { 'component': 'hfos.enrol.enrolmanager', 'action': 'changepassword', 'data': False } self.fireEvent(send(event.client.uuid, packet)) self.log('User tried to change password without supplying old one', lvl=warn) |
def invite(self, event): """A new user has been invited to enrol by an admin user""" self.log('Inviting new user to enrol') name = event.data['name'] email = event.data['email'] method = event.data['method'] self._invite(name, method, email, event.client.uuid, event) |
def enrol(self, event): """A user tries to self-enrol with the enrolment form""" if self.config.allow_registration is False: self.log('Someone tried to register although enrolment is closed.') return self.log('Client trying to register a new account:', event, pretty=True) # self.log(event.data, pretty=True) uuid = even... |
return mail = event.data.get('mail', None) if mail is None: self._fail(event, _('You have to supply all required fields.', event)) return elif not validate_email(mail): self._fail(event, _('The supplied email address seems invalid', event)) return if objectmodels['user'].count({'mail': mail}) > 0: self._fail(event, _('... |
event)) return username = event.data.get('username', None) if username is None or len(username) < 1: self._fail(event, _('Your username is not long enough.', event)) return elif (objectmodels['user'].count({'name': username}) > 0) or \ (objectmodels['enrollment'].count({'name': username}) > 0): self._fail(event, _('The... |
def accept(self, event): """A challenge/response for an enrolment has been accepted""" self.log('Invitation accepted:', event.__dict__, lvl=debug) try: uuid = event.data enrollment = objectmodels['enrollment'].find_one({ 'uuid': uuid }) if enrollment is not None: self.log('Enrollment found', lvl=debug) if enrollment.st... |
\ 'and can now log in to the system and start to use it. <br/>' \ 'Please change your password immediately after logging in' password = std_human_uid().replace(" ", '') self._create_user(enrollment.name, password, enrollment.email, enrollment.method, uuid) self._send_acceptance(enrollment, password, event) elif enrollm... |
acceptance mail makes sense # self._send_acceptance(enrollment, "", event) else: enrollment.status = 'Pending' data = 'Someone has to confirm your enrollment ' \ 'first. Thank you, for your patience.' # TODO: Alert admin users enrollment.save() # Reaffirm acceptance to end user, when clicking on the link multiple times... |
use it.' elif enrollment.status == 'Pending': data = 'Someone has to confirm your enrollment ' \ 'first. Thank you, for your patience.' else: self.log('Enrollment has been closed already!', lvl=warn) self._fail(event) return packet = { 'component': 'hfos.enrol.enrolmanager', 'action': 'accept', 'data': {True: data} } s... |
def status(self, event): """An anonymous client wants to know if we're open for enrollment""" self.log('Registration status requested') response = { 'component': 'hfos.enrol.enrolmanager', 'action': 'status', 'data': self.config.allow_registration } self.fire(send(event.client.uuid, response)) |
def request_reset(self, event): """An anonymous client requests a password reset""" self.log('Password reset request received:', event.__dict__, lvl=hilight) user_object = objectmodels['user'] email = event.data.get('email', None) email_user = None if email is not None and user_object.count({'mail': email}) > 0: email_... |
def captcha_transmit(self, captcha, uuid): """Delayed transmission of a requested captcha""" self.log('Transmitting captcha') response = { 'component': 'hfos.enrol.enrolmanager', 'action': 'captcha', 'data': b64encode(captcha['image'].getvalue()).decode('utf-8') } self.fire(send(uuid, response)) |
def _invite(self, name, method, email, uuid, event, password=""): """Actually invite a given user""" props = { 'uuid': std_uuid(), 'status': 'Open', 'name': name, 'method': method, 'email': email, 'password': password, 'timestamp': std_now() } enrollment = objectmodels['enrollment'](props) enrollment.save() self.log('E... |
def _create_user(self, username, password, mail, method, uuid): """Create a new user and all initial data""" try: if method == 'Invited': config_role = self.config.group_accept_invited else: config_role = self.config.group_accept_enrolled roles = [] if ',' in config_role: for item in config_role.split(','): roles.appen... |
newuser.needs_password_change = True newuser.save() except Exception as e: self.log("Problem creating new user: ", type(e), e, lvl=error) return try: newprofile = objectmodels['profile']({ 'uuid': std_uuid(), 'owner': newuser.uuid }) self.log("New profile uuid: ", newprofile.uuid, lvl=verbose) newprofile.save() packet ... |
def _send_invitation(self, enrollment, event): """Send an invitation mail to an open enrolment""" self.log('Sending enrollment status mail to user') self._send_mail(self.config.invitation_subject, self.config.invitation_mail, enrollment, event) |
def _send_acceptance(self, enrollment, password, event): """Send an acceptance mail to an open enrolment""" self.log('Sending acceptance status mail to user') if password is not "": password_hint = '\n\nPS: Your new password is ' + password + ' - please change it after your first login!' acceptance_text = self.config.a... |
def _send_mail(self, subject, template, enrollment, event): """Connect to mail server and send actual email""" context = { 'name': enrollment.name, 'invitation_url': self.invitation_url, 'node_name': self.node_name, 'node_url': self.node_url, 'uuid': enrollment.uuid } mail = render(template, context) self.log('Mail:', ... |
event), "enrolworkers") else: self.log('Not sending mail, here it is for debugging info:', mail, pretty=True) |
def say(self, event): """Chat event handler for incoming events :param event: say-event with incoming chat message """ try: userid = event.user.uuid recipient = self._get_recipient(event) content = self._get_content(event) if self.config.name in content: self.log('I think, someone mentioned me:', content) except Except... |
def add_auth_hook(self, event): """Register event hook on reception of add_auth_hook-event""" self.log('Adding authentication hook for', event.authenticator_name) self.auth_hooks[event.authenticator_name] = event.event |
def _fail(self, event, message='Invalid credentials'): """Sends a failure message to the requesting client""" notification = { 'component': 'auth', 'action': 'fail', 'data': message } ip = event.sock.getpeername()[0] self.failing_clients[ip] = event Timer(3, Event.create('notify_fail', event.clientuuid, notification, i... |
def _login(self, event, user_account, user_profile, client_config): """Send login notification to client""" user_account.lastlogin = std_now() user_account.save() user_account.passhash = "" self.fireEvent( authentication(user_account.name, ( user_account, user_profile, client_config), event.clientuuid, user_account.uui... |
def authenticationrequest(self, event): """Handles authentication requests from clients :param event: AuthenticationRequest with user's credentials """ if event.sock.getpeername()[0] in self.failing_clients: self.log('Client failed a login and has to wait', lvl=debug) return if event.auto: self._handle_autologin(event)... |
def _handle_autologin(self, event): """Automatic logins for client configurations that allow it""" self.log("Verifying automatic login request") # TODO: Check for a common secret # noinspection PyBroadException try: client_config = objectmodels['client'].find_one({ 'uuid': event.requestedclientuuid }) except Exception:... |
self.log("Autologin for", user_account.name, lvl=debug) except Exception as e: self.log("No user object due to error: ", e, type(e), lvl=error) self._fail(event) return if user_account.active is False: self.log("Account deactivated.") self._fail(event, 'Account deactivated.') return user_profile = self._get_profile(use... |
def _handle_login(self, event): """Manual password based login""" # TODO: Refactor to simplify self.log("Auth request for ", event.username, 'client:', event.clientuuid) # TODO: Define the requirements for secure passwords etc. # They're also required in the Enrol module..! if (len(event.username) < 1) or (len(event.pa... |
= objectmodels['user'].find_one({ 'name': event.username }) # self.log("Account: %s" % user_account._fields, lvl=debug) if user_account is None: raise AuthenticationError except Exception as e: self.log("No userobject due to error: ", e, type(e), lvl=error) self._fail(event) return self.log("User found.", lvl=debug) if... |
requested_client_uuid = event.requestedclientuuid if requested_client_uuid is not None: client_config = objectmodels['client'].find_one({ 'uuid': requested_client_uuid }) if client_config: self.log("Checking client configuration permissions", lvl=debug) # TODO: Shareable client configurations? if client_config.owner !=... |
requested # -> Create a new client configuration uuid = event.clientuuid if event.clientuuid is not None else str(uuid4()) client_config = objectmodels['client']({'uuid': uuid}) client_config.name = std_human_uid(kind='place') client_config.description = "New client configuration from " + user_account.name client_confi... |
def _get_profile(self, user_account): """Retrieves a user's profile""" try: # TODO: Load active profile, not just any user_profile = objectmodels['profile'].find_one( {'owner': str(user_account.uuid)}) self.log("Profile: ", user_profile, user_account.uuid, lvl=debug) except Exception as e: self.log("No profile due to e... |
= objectmodels['profile'](default) user_profile.save() return user_profile |
def _parse(self, bus, data): """ Called when a sensor sends a new raw data to this serial connector. The data is sanitized and sent to the registered protocol listeners as time/raw/bus sentence tuple. """ sen_time = time.time() try: # Split up multiple sentences if isinstance(data, bytes): data = data.decode('ascii') d... |
s = set() for el in it: if el not in s: s.add(el) yield el else: # TODO: Make sure, this is not identical but new data self.log("Duplicate sentence received: ", el, lvl=debug) sentences = list(unique(sentences)) return sentences except Exception as e: self.log("Error during data unpacking: ", e, type(e), lvl=error, exc... |
def serial_packet(self, event): """Handles incoming raw sensor data :param data: raw incoming data """ self.log('Incoming serial packet:', event.__dict__, lvl=verbose) if self.scanning: pass else: # self.log("Incoming data: ", '%.50s ...' % event.data, lvl=debug) sanitized_data = self._parse(event.bus, event.data) self... |
def main(): """Entry point for the script""" desc = 'Converts between geodetic, modified apex, quasi-dipole and MLT' parser = argparse.ArgumentParser(description=desc, prog='apexpy') parser.add_argument('source', metavar='SOURCE', choices=['geo', 'apex', 'qd', 'mlt'], help='Convert from {geo, apex, qd, mlt}') parser.ad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.