Browse Source

Some improvements

- Now can configure server via environment variables.
- Added debug options.
- Empty values in config no more break the system.
Óscar García Amor 3 years ago
parent
commit
d84f35056b
2 changed files with 49 additions and 9 deletions
  1. 10 5
      sysdweb/config.py
  2. 39 4
      sysdweb/main.py

+ 10 - 5
sysdweb/config.py

@@ -7,12 +7,14 @@
 # Distributed under terms of the GNU GPLv3 license.
 
 import configparser
+import logging
 import os
 
 def checkConfig(file=None):
     """
     Parse config and discards errors
     """
+    logger = logging.getLogger('sysdweb.checkConfig')
     if file != None:
         if os.access(file, os.R_OK):
             config_file = [file]
@@ -26,6 +28,7 @@ def checkConfig(file=None):
         config_file = [file for file in config_files if os.access(file, os.R_OK)]
         if config_file == []:
             raise SystemExit('No config file found.')
+    logger.info('Using config file \'{}\'.'.format(config_file[0]))
 
     config = configparser.ConfigParser()
     try:
@@ -36,17 +39,19 @@ def checkConfig(file=None):
 
     # Read all sections to check if are correctly configurated
     for section in config.sections():
-        if config.get(section, 'title', fallback=None) == None:
+        if not config.get(section, 'title', fallback=None):
             config.remove_section(section)
-            print ('Warning: Removed invalid section without title \'{}\' from config.'.format(section))
+            logger.warning('Removed invalid section without title \'{}\' from config.'.format(section))
         else:
-            if config.get(section, 'unit', fallback=None) == None:
+            if not config.get(section, 'unit', fallback=None):
                 config.remove_section(section)
-                print ('Warning: Removed invalid section without unit \'{}\' from config.'.format(section))
+                logger.warning('Removed invalid section without unit \'{}\' from config.'.format(section))
             else:
                 unit = config.get(section, 'unit')
                 if not '.service' in unit:
-                    config.set(section, 'unit', '{}.service'.format(unit))
+                    unit = '{}.service'.format(unit)
+                    config.set(section, 'unit', unit)
+                logger.debug('Configured section \'{}\' for unit \'{}\''.format(section, unit))
 
     # If after check all sections no valid sections remain, exit with error
     if len(config.sections()) < 1:

+ 39 - 4
sysdweb/main.py

@@ -9,12 +9,47 @@
 from sysdweb.server import start
 
 import argparse
+import logging
+import os
 
 def main():
+    # Get config from environment
+    config = os.getenv('SYSDWEB_CONFIG')
+    host   = os.getenv('SYSDWEB_HOST')
+    port   = os.getenv('SYSDWEB_PORT')
+    level  = os.getenv('SYSDWEB_LOGLEVEL')
+
+    # Check loglevel environment variable
+    if level:
+        log_level = getattr(logging, level.upper(), None)
+        if not isinstance(log_level, int):
+            raise ValueError('Invalid log level: {}'.format(level))
+    else:
+        log_level = None
+
+    # Set loglevel equivalents for argument parser
+    log_levels = {
+            1: logging.INFO,
+            2: logging.DEBUG }
+
+    # Create argument parser to get config via arguments
     parser = argparse.ArgumentParser()
-    parser.add_argument('-c', '--config', metavar='value', help='Custom configuration file path')
-    parser.add_argument('-l', '--listen', metavar='value', help='listen address (host or ip), default: 127.0.0.1')
-    parser.add_argument('-p', '--port', metavar='value', help='listen port, default: 10080')
+    parser.add_argument('-c', '--config', metavar='value', default=config, help='custom configuration file path')
+    parser.add_argument('-l', '--listen', metavar='value', default=host, help='listen address (host or ip), default: 127.0.0.1')
+    parser.add_argument('-p', '--port', metavar='value', default=port, help='listen port, default: 10080')
+    parser.add_argument('-v', '--verbose', action='count', default=0, help='be verbose (add more v to increase verbosity)')
     args = parser.parse_args()
 
-    start (args.config, args.listen, args.port)
+    # Maximum loglevel is 3 if user sends more vvv we ignore it
+    args.verbose = 2 if args.verbose >= 2 else args.verbose
+
+    # Set loglevel via argument or environment (untouched warning by default)
+    if args.verbose > 0:
+        log_level = log_levels[args.verbose]
+    if log_level:
+        logging.basicConfig(level=log_level)
+        logger = logging.getLogger('sysdweb')
+        logger.info('Setting loglevel to {}'.format(logging.getLevelName(log_level)))
+
+    # Run main app
+    start(args.config, args.listen, args.port)