print('Sorry, this script requires a python3 runtime environment.', file=sys.stderr) # Argparse parser = argparse.ArgumentParser(description=project_name, epilog='For further details see: ' + project_url) parser.add_argument('--config_dir', help='set directory where config.ini is located', default=sys.path[0]) parse_args = parser.parse_args() # Intro colorama_init() print(Fore.GREEN + Style.BRIGHT) print(project_name) print('Source:', project_url) print(Style.RESET_ALL) # Systemd Service Notifications - https://github.com/bb4242/sdnotify sd_notifier = sdnotify.SystemdNotifier() # Logging function def print_line(text, error = False, warning=False, sd_notify=False, console=True): timestamp = strftime('%Y-%m-%d %H:%M:%S', localtime()) if console: if error: print(Fore.RED + Style.BRIGHT + '[{}] '.format(timestamp) + Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL, file=sys.stderr) elif warning: print(Fore.YELLOW + '[{}] '.format(timestamp) + Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL) else: print(Fore.GREEN + '[{}] '.format(timestamp) + Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL) timestamp_sd = strftime('%b %d %H:%M:%S', localtime()) if sd_notify: sd_notifier.notify('STATUS={} - {}.'.format(timestamp_sd, unidecode(text)))
from influxdb import InfluxDBClient import sdnotify import sys import logging from dynaconf import LazySettings, Validator from dynaconf.utils.boxing import DynaBox settings = LazySettings( SETTINGS_FILE_FOR_DYNACONF="default.toml,user.toml", ENVVAR_PREFIX_FOR_DYNACONF="PIHOLE", ) settings.validators.register(Validator("INSTANCES", must_exist=True)) settings.validators.validate() n = sdnotify.SystemdNotifier() logging.basicConfig(level=logging.INFO, format="%(levelname)s: [%(name)s] %(message)s") logger = logging.getLogger(__name__) class Pihole: """Container object for a single Pi-hole instance.""" def __init__(self, name, url): self.name = name self.url = url self.timeout = settings.as_int("REQUEST_TIMEOUT") self.logger = logging.getLogger(__name__ + name) self.logger.debug("Initialized for %s", name, url)
def start(self): """ Starts this node. This will start a node controller and then spawn new worker processes as needed. """ if not self._config: raise Exception("No node configuration set") # get controller config/options # controller_config = self._config.get('controller', {}) controller_options = controller_config.get('options', {}) # set controller process title # try: import setproctitle except ImportError: self.log.warn( "Warning, could not set process title (setproctitle not installed)" ) else: setproctitle.setproctitle( controller_options.get('title', 'crossbar-controller')) # local node management router # self._router_factory = RouterFactory(None) self._router_session_factory = RouterSessionFactory( self._router_factory) rlm_config = {'name': self._realm} rlm = RouterRealm(None, rlm_config) router = self._router_factory.start_realm(rlm) # setup global static roles # self._add_global_roles() # always add a realm service session # cfg = ComponentConfig(self._realm) rlm.session = (self.ROUTER_SERVICE)(cfg, router) self._router_session_factory.add(rlm.session, authrole=u'trusted') self.log.debug('Router service session attached [{router_service}]', router_service=qual(self.ROUTER_SERVICE)) # add the node controller singleton component # self._controller = self.NODE_CONTROLLER(self) self._router_session_factory.add(self._controller, authrole=u'trusted') self.log.debug('Node controller attached [{node_controller}]', node_controller=qual(self.NODE_CONTROLLER)) # add extra node controller components # self._add_extra_controller_components(controller_options) # setup Node shutdown triggers # self._set_shutdown_triggers(controller_options) panic = False try: # startup the node personality .. yield self._startup() # .. and notify systemd that we are fully up and running try: import sdnotify sdnotify.SystemdNotifier().notify("READY=1") except: # do nothing on non-systemd platforms pass except ApplicationError as e: panic = True self.log.error("{msg}", msg=e.error_message()) except Exception: panic = True self.log.failure() self.log.error('fatal: could not startup node') if panic: try: self._reactor.stop() except twisted.internet.error.ReactorNotRunning: pass