def get_active_ruleset(self, p_session_context, p_username, p_reference_date): active_ruleset = None max_priority = None user = self._persistence.user_map(p_session_context).get(p_username) if user is not None: for ruleset in user.rulesets: context_name = ruleset.context or self._default_context_rule_handler_name context_rule_handler = self._context_rule_handlers.get( context_name) if context_rule_handler is None: raise configuration.ConfigurationException( "invalid rule set context '%s'" % ruleset.context) active = context_rule_handler.is_active( p_reference_date=p_reference_date, p_details=ruleset.context_details) if active: if max_priority is None or ruleset.priority > max_priority: max_priority = ruleset.priority active_ruleset = ruleset return active_ruleset
def get_active_ruleset_config(self, p_username, p_reference_date): active_ruleset_config = None max_priority = None ruleset_configs = self._rule_set_configs.get(p_username) if ruleset_configs is not None: for c_config in ruleset_configs: active = False context_name = c_config.context or self._default_context_rule_handler_name context_rule_handler = self._context_rule_handlers.get(context_name) if context_rule_handler is None: raise configuration.ConfigurationException("invalid rule set context '%s'" % c_config.context) active = context_rule_handler.is_active(p_reference_date=p_reference_date, p_details=c_config.context_details) if active: if max_priority is None or c_config.priority > max_priority: max_priority = c_config.priority active_ruleset_config = c_config return active_ruleset_config
def get_string_as_duration(p_string): if p_string is None: return None if p_string.strip() in (EMPTY_DURATION, ''): return None match = REGEX_DURATION.match(p_string) if match is None: fmt = _("Use Hh MMm SSs") raise configuration.ConfigurationException(fmt.format(string=p_string)) result = 0 if match.group(2) is not None: result = result + 3600 * int(match.group(2)) if match.group(4) is not None: result = result + 60 * int(match.group(4)) if match.group(6) is not None: result = result + int(match.group(6)) return result
def get_string_as_time(p_string): if p_string is None: return None if p_string.strip() in (EMPTY_TIME, ''): return None match = REGEX_TIME.match(p_string) if match is None: fmt = _("Use HH[:MM[:SS]]") raise configuration.ConfigurationException(fmt.format(string=p_string)) hour = int(match.group(1)) if match.group(3) is not None: minute = int(match.group(3)) else: minute = 0 if match.group(5) is not None: second = int(match.group(5)) else: second = 0 return datetime.time(hour=hour, minute=minute, second=second)
def is_active(self, p_reference_date, p_details): state_name = p_details key = "{date}|{state}".format(date=datetime.datetime.strftime( p_reference_date, "%d%m%Y"), state=state_name) cached_result = self._cache.get(key) if cached_result is not None: return cached_result self.check_data() vacation_entries = self._vacation_data.get(p_details) if vacation_entries is None: fmt = "unknown federal state name {name}" raise configuration.ConfigurationException( fmt.format(name=state_name)) for entry in vacation_entries: if entry.start_date <= p_reference_date <= entry.end_date: self._cache[key] = True return True self._cache[key] = False return False
def post_process(self): self.min_time_of_day = RuleSetSectionHandler.read_time_of_day( p_time_of_day=self.min_time_of_day) self.max_time_of_day = RuleSetSectionHandler.read_time_of_day( p_time_of_day=self.max_time_of_day) if (self.min_time_of_day is not None and self.max_time_of_day is not None and self.min_time_of_day >= self.max_time_of_day): msg = "Maximum time of day '{max_time_of_day}' must be later than minimum time of day '{min_time_of_day}'" \ " for user '{user}' and context '{context}'" raise configuration.ConfigurationException( msg.format(min_time_of_day=tools.get_time_as_string( self.min_time_of_day), max_time_of_day=tools.get_time_as_string( self.max_time_of_day), user=self.username, context=self.label)) self.max_time_per_day = tools.get_string_as_duration( p_string=self.max_time_per_day) self.max_activity_duration = tools.get_string_as_duration( p_string=self.max_activity_duration) self.min_break = tools.get_string_as_duration(p_string=self.min_break)
def get_test_data_path(self, p_rel_path='.'): if self._test_data_base_dir is None: msg = "No base path specified for test case '{testcase}'" raise configuration.ConfigurationException( msg.format(testcase=self.__class__.__name__)) return join(self._test_data_base_dir, p_rel_path)
def load_configuration(self): if self._config_filename is None: msg = "No filename specified for test case '{testcase}'" raise configuration.ConfigurationException( msg.format(testcase=self.__class__.__name__)) self._config.read_config_file(self._config_filename, p_ignore_invalid_sections=True)
def check_playsound(self): try: import playsound self._playsound = playsound except: fmt = "init_engine_google(): cannot load module 'playsound'" self._logger.error(fmt) raise configuration.ConfigurationException(fmt)
def init_engine(self): popup_command_info = POPUP_ENGINES.get(self._config.popup_engine) if popup_command_info is None: fmt = "init_engine(): invalid popup engine '{engine}'; valid engines: {engines}" msg = fmt.format(engine=self._config.popup_engine, engines="'" + "', '".join(POPUP_ENGINES.keys()) + "'") self._logger.error(msg) raise configuration.ConfigurationException(msg)
def regex_process_name_pattern(self): if self._regex_process_name_pattern is None: try: self._regex_process_name_pattern = re.compile(self.process_name_pattern) except Exception as e: raise configuration.ConfigurationException("Invalid process REGEX pattern '%s' (Exception: %s)" % ( self.process_name_pattern, str(e))) return self._regex_process_name_pattern
def init_engine_google(self): try: import python_google_speak.speech_generator self._google_speak = python_google_speak.speech_generator except: fmt = "init_engine_google(): cannot load module 'python_google_speak'" self._logger.error(fmt) raise configuration.ConfigurationException(fmt) self.check_playsound()
def start(self): try: fmt = "Starting Prometheus server on port {port}..." self._logger.info(fmt.format(port=self._config.port)) prometheus_client.start_http_server(self._config.port) except OSError as e: fmt = "Exception {msg} while starting Prometheus server on port {port}" raise configuration.ConfigurationException( fmt.format(msg=str(e), port=self._config.port))
def check_audio_player(self): try: # if self._config.audio_player == AUDIO_PLAYER_PLAYSOUND: # self._audio_player = playsound_audio_player.PlaysoundAudioPlayer() if self._config.audio_player == AUDIO_PLAYER_PYGLET: self._audio_player = pyglet_audio_player.PygletAudioPlayer() elif self._config.audio_player == AUDIO_PLAYER_MPG123: self._audio_player = mpg123_audio_player.Mpg123AudioPlayer( self._config.mpg123_binary, self._config.play_command_pattern) else: msg = f"Invalid audio player '{self._config.audio_player}'" raise configuration.ConfigurationException(msg) except Exception as e: msg = f"Cannot load audio player '{self._config.audio_player}': {str(e)}" self._logger.error(msg) raise configuration.ConfigurationException(msg)
def is_active(self, p_reference_date, p_details): if p_details is None: raise configuration.ConfigurationException( "Weekday context without context details") p_details = p_details.lower() if p_details in WEEKPLAN_PREDEFINED_DETAILS: weekday_string = WEEKPLAN_PREDEFINED_DETAILS[p_details] elif len(p_details) == 7: weekday_string = p_details else: fmt = "invalid context details '{details}' for context {name}" raise configuration.ConfigurationException( fmt.format(details=p_details, name=self.context_name)) time_tuple = p_reference_date.timetuple() return weekday_string[ time_tuple.tm_wday] in VALID_ACTIVE_DAY_CHARACTERS
def __init__(self): super().__init__() self._player = None try: import playsound self._play_command = playsound.playsound except: fmt = "Cannot load module 'playsound'" self._logger.error(fmt) raise configuration.ConfigurationException(fmt) self._logger.info("audio player 'playsound' loaded")
def init_engine(self): if self._config.speech_engine == SPEECH_ENGINE_EXTERNAL: pass elif self._config.speech_engine == SPEECH_ENGINE_PYTTSX3: self.init_engine_pyttsx3() elif self._config.speech_engine == SPEECH_ENGINE_GOOGLE: self.init_engine_google() else: fmt = "init_engine(): invalid speech engine '%s'" % self._config.speech_engine self._logger.error(fmt) raise configuration.ConfigurationException(fmt)
def __init__(self, p_mpg123_binary, p_play_command_pattern=DEFAULT_PLAY_COMMAND_PATTERN): super().__init__() self._mpg123_binary = p_mpg123_binary self._play_command_pattern = p_play_command_pattern if not os.path.exists(p_mpg123_binary): fmt = "Cannot find mpg123 binary at path '{path}'" raise configuration.ConfigurationException( fmt.format(path=p_mpg123_binary)) fmt = "using audio player '{path}'" self._logger.info(fmt.format(path=p_mpg123_binary))
def __init__(self, p_default_port=None, p_config=None): if p_config is None: p_config = PingerConfigModel() self._config = p_config self._default_port = p_default_port self._logger = log_handling.get_logger(self.__class__.__name__) try: self.ping_result_regex = re.compile(self._config.ping_result_regex) except Exception: fmt = "Invalid regular expression '{regex}' in [{section}]ping_result_regex" raise configuration.ConfigurationException( fmt.format(regex=self._config.ping_result_regex, section=SECTION_NAME))
def read_from_configuration(self, p_login_mapping_section_handler:LoginMappingSectionHandler): for section in p_login_mapping_section_handler._login_mapping_sections.values(): for mapping_entry in section.mapping_entries: single_entries = mapping_entry.split(",") for entry in single_entries: match = MAPPING_ENTRY_PATTERN.match(entry) if match is None: msg = "Invalid logging mapping '{entry}' for host group {group}" raise configuration.ConfigurationException(msg.format(entry=entry, group=section.server_group)) login_uid_mapping_entry = LoginUidMappingEntry(match.group(1), int(match.group(2))) self.add_entry(p_server_group=section.server_group, p_login_uid_mapping_entry=login_uid_mapping_entry)
def check_schema(self): if self._admin_engine is None and self._config.database_admin is not None: raise configuration.ConfigurationException( "check_schema () called without [StatusCollector].database_admin " "and [StatusCollector].database_admin_password set") if DATABASE_DRIVER_POSTGRESQL in self._config.database_driver: self.create_postgresql() elif DATABASE_DRIVER_MYSQL in self._config.database_driver: self.create_mysql() elif DATABASE_DRIVER_SQLITE in self._config.database_driver: self.create_sqlite() else: raise ("Unknown database driver %s" % self._config.database_driver)
def _notify(self, p_text, p_locale=None): if self._config.speech_engine == SPEECH_ENGINE_EXTERNAL: self.speak_external_command(p_text=p_text, p_locale=p_locale) elif self._config.speech_engine == SPEECH_ENGINE_PYTTSX3: self.speak_pyttsx(p_text=p_text, p_locale=p_locale) elif self._config.speech_engine == SPEECH_ENGINE_GOOGLE: self.speak_google(p_text=p_text, p_locale=p_locale) else: fmt = "_notify(): invalid speech engine '%s'" % self._config.speech_engine self._logger.error(fmt) raise configuration.ConfigurationException(fmt) self._recent_texts[p_text] = datetime.datetime.now()
def __init__(self, p_config, p_persistence): super().__init__(p_config=p_config) self._persistence = p_persistence #self._session_context = persistence.SessionContext(p_persistence=self._persistence, p_register=True) try: self.ping_result_regex = re.compile(self._config.ping_result_regex) except Exception: fmt = "Invalid regular expression '{regex}' in [{section}]ping_result_regex" raise configuration.ConfigurationException( fmt.format(regex=self._config.ping_result_regex, section=SECTION_NAME)) self._logger = log_handling.get_logger(self.__class__.__name__) self._process_infos = {} self._device_infos = {}
def __init__(self, p_config, p_client_device_configs): super()._init__(p_config=p_config) self._client_device_configs = p_client_device_configs try: self.ping_result_regex = re.compile(self._config.ping_result_regex) except Exception: fmt = "Invalid regular expression '{regex}' in [{section}]ping_result_regex" raise configuration.ConfigurationException( fmt.format(regex=self._config.ping_result_regex, section=SECTION_NAME)) self._logger = log_handling.get_logger(self.__class__.__name__) self._process_infos = {} self._device_infos = {} self._process_info_candidates = {}
def read_time_of_day(p_time_of_day): if p_time_of_day is None: return None result = REGEX_TIME_OF_DAY.match(p_time_of_day) if result is None: raise configuration.ConfigurationException("Invalid time of day format: '%s'. Use HH[:MM]" % p_time_of_day) hours = int(result.group(1)) if result.group(3) is None: minutes = 0 else: minutes = int(result.group(3)) return datetime.time(hour=hours, minute=minutes)
def check_schema(self, p_create_tables=True): msg = "Checking whether to create database {name}..." self._logger.info(msg.format(name=self._config.database_name)) if DATABASE_DRIVER_POSTGRESQL in self._config.database_driver: self.create_postgresql(p_create_tables=p_create_tables) elif DATABASE_DRIVER_MYSQL in self._config.database_driver: self.create_mysql(p_create_tables=p_create_tables) elif DATABASE_DRIVER_SQLITE in self._config.database_driver: self.create_sqlite(p_create_tables=p_create_tables) else: fmt = "Unknown database driver '{driver}'. Known drivers: {drivers}" raise configuration.ConfigurationException( fmt.format(driver=self._config.database_driver, drivers="'" + "', '".join(DATABASE_DRIVERS) + "'"))
def __init__(self): super().__init__() self._player_thread = None try: import pyglet self._pyglet = pyglet run_method = self._pyglet.app.run self._pyglet.clock.schedule(lambda dt: 1) self._player_thread = threading.Thread(target=run_method) self._player_thread.start() except Exception: fmt = "Cannot load module 'pyglet'" self._logger.error(fmt) raise configuration.ConfigurationException(fmt) self._logger.info("audio player 'pyglet' loaded")
def _notify(self, p_text, p_locale=None): popup_command_info = POPUP_ENGINES.get(self._config.popup_engine) if popup_command_info is not None: if self._config.engine_binary is not None: popup_binary = self._config.engine_binary else: popup_binary = popup_command_info[0] if popup_command_info[2] is not None: p_text = popup_command_info[2](p_text) self.popup_command(p_text=p_text, p_locale=p_locale, p_command_line=popup_command_info[1], p_binary=popup_binary) else: fmt = "_notify(): invalid popup engine '%s'" % self._config.popup_engine self._logger.error(fmt) raise configuration.ConfigurationException(fmt) self._recent_texts[p_text] = datetime.datetime.now()
def is_active(self, p_reference_date, p_details): state_name = p_details key = "{date}|{state}".format(date=datetime.datetime.strftime( p_reference_date, "%d%m%Y"), state=state_name) cached_result = self._cache.get(key) if cached_result is not None: return cached_result try: self.check_data() except Exception as e: msg = "Exception '{msg}' while retrieving calender information. Assuming that {date} is not a vacation day." self._logger.error( msg.format(msg=str(e), date=datetime.datetime.strftime( p_reference_date, "%d.%m.%Y"))) self._cache[key] = False return False vacation_entries = self._vacation_data.get(p_details) if vacation_entries is None: fmt = "unknown federal state name {name}" raise configuration.ConfigurationException( fmt.format(name=state_name)) for entry in vacation_entries: if entry.start_date <= p_reference_date <= entry.end_date: self._cache[key] = True return True self._cache[key] = False return False
def __init__(self, p_config, p_exclude_user_list=None): super().__init__(p_config=p_config, p_exclude_user_list=p_exclude_user_list) self._users = None msg = "Using admin user '{username}'" self._logger.info(msg.format(username=self._config.admin_username)) if self._config.user_list is not None: try: self._users = { name_uid.split(":")[0].strip(): int(name_uid.split(":")[1]) for name_uid in self._config.user_list.split(",") } except Exception as e: msg = "Invalid user:uid list '{list}' in [UnixUserHandler].user_list" raise configuration.ConfigurationException( msg.format(list=self._config.user_list)) msg = "Using predefined users {users}" self._logger.info(msg.format(users=",".join(self._users.keys())))