diff --git a/.gitignore b/.gitignore index 147ed61..33ea36d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,6 @@ # ---> Python -# Byte-compiled / optimized / DLL files +# Byte-compiled __pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so # Distribution / packaging .Python @@ -18,6 +13,7 @@ eggs/ .eggs/ lib/ lib64/ +lib64 include/ parts/ sdist/ @@ -35,93 +31,9 @@ MANIFEST *.manifest *.spec -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - # Sphinx documentation docs/_build/ -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -#poetry.lock - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -#pdm.lock -# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it -# in version control. -# https://pdm.fming.dev/#use-with-ide -.pdm.toml - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - # Environments .env .venv @@ -130,35 +42,4 @@ venv/ ENV/ env.bak/ venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ - +pyvenv.cfg \ No newline at end of file diff --git a/src/pyappengine/appengine.py b/src/pyappengine/appengine.py index f844322..408ebef 100644 --- a/src/pyappengine/appengine.py +++ b/src/pyappengine/appengine.py @@ -1,7 +1,7 @@ #!/usr/bin/python3 import os -import configparser +from configparser import ConfigParser import logging from systemd import journal import inspect @@ -9,16 +9,10 @@ from importlib import import_module from commands import Commands from threading import Lock -ourpath = os.path.dirname(os.path.abspath(__file__)) - - -def dir_writeable(path): - return os.access(path, os.W_OK) - - class CommandsLoader: - def __init__(self, config, log): + def __init__(self, config: ConfigParser, log: logging.Handler, modpath: str): self.config = config + self.modpath = modpath Commands.defmod = self.config['general'].get('default') self.log = log self.lock = Lock() @@ -28,7 +22,7 @@ class CommandsLoader: def _load_commands(self): cmds = {} - with os.scandir(os.path.join(ourpath, "commands")) as it: + with os.scandir(self.modpath) as it: for entry in it: if entry.name.startswith('cmds_') and entry.name.endswith('.py') and entry.is_file(): obj = self._load_module(entry.name[:-3]) @@ -71,7 +65,7 @@ class CommandsLoader: if p in self.cmods.keys(): setattr(v, p, self.cmods[p]) else: - log.error( + self.log.error( 'Dependency "{}" of module "{}" could not be satisfied'.format(p, k)) def start(self): @@ -85,48 +79,48 @@ class CommandsLoader: v.join() -if __name__ == "__main__": - import argparse - parser = argparse.ArgumentParser() - parser.add_argument( - "-c", "--config", help="Configuration file", default='/etc/sms-server.conf') - parser.add_argument("-l", "--log-file", help="log to a file instead of the console", - default='') - parser.add_argument("-g", "--debug", action='store_true', required=False, - help="Debug messages logged") - args = parser.parse_args() +class AppEngine: + def __init__(self, app_name: str, conf_file : str="", mod_dir: str="", log_file: str="", debug: bool=False) -> None: + self.app_name = app_name + self.conf = ConfigParser() + if conf_file != '': + self.parse_config(conf_file) + self.def_log(log_file) - if os.path.exists(args.config): - conf = configparser.ConfigParser() - conf.read(args.config) - else: - raise Exception('Configuration file not found') - - log = logging.getLogger(os.path.basename(__name__)) - if args.log_file != '': - fname = args.log_file - is_writeable = False - - if not os.path.isabs(fname): - fname = os.path.join(os.getcwd(), fname) - - if dir_writeable(os.path.dirname(fname)): - is_writeable = True - - if is_writeable: - log.addHandler(logging.FileHandler(fname)) + if debug: + self.log.setLevel(logging.DEBUG) else: - log.addHandler(journal.JournalHandler()) - log.error('No write permissions: "{}"'.format(fname)) + self.log.setLevel(logging.WARNING) - else: - log.addHandler(journal.JournalHandler()) + def parse_config(self, cf: str): + if os.path.exists(cf) and os.path.isfile(cf): + self.conf.read(cf) + else: + raise Exception('Configuration file not found') - if args.debug: - log.setLevel(logging.DEBUG) - else: - log.setLevel(logging.WARNING) + def def_log(self, log_file): + self.log = logging.getLogger(self.app_name) + if log_file != '': + fname = log_file + is_writeable = False - cl = CommandsLoader(conf, log) - cl.start() - cl.join() + if not os.path.isabs(fname): + fname = os.path.join(os.getcwd(), fname) + + if os.access(os.path.dirname(fname), os.W_OK): + is_writeable = True + + if is_writeable: + self.log.addHandler(logging.FileHandler(fname)) + else: + self.log.addHandler(journal.JournalHandler()) + self.log.error('No write permissions: "{}"'.format(fname)) + + else: + self.log.addHandler(journal.JournalHandler()) + + + def exec(self, modpath: str=""): + cl = CommandsLoader(self.conf, self.log, modpath) + cl.start() + cl.join()