Browse Source

Implemented the configuration class, added the configuration file to jwmud and set logger level and syslog facility according to the configuration values. Added a sample configuration file.

Helmut Pozimski 10 years ago
parent
commit
660b8ec298
4 changed files with 100 additions and 10 deletions
  1. 8 0
      config/jwmud.conf
  2. 26 10
      jwmud
  3. 52 0
      jwmudlib/configuration.py
  4. 14 0
      jwmudlib/jwmu_exceptions.py

+ 8 - 0
config/jwmud.conf

@@ -0,0 +1,8 @@
+# Maximum syslog level to log, jwmud uses debug, info and error
+SYSLOG_LEVEL=info
+
+# Syslog facility to use for logging
+SYSLOG_FACILITY=user
+
+# Script to call for raising the alarm
+ALARM_SCRIPT=/usr/bin/beep

+ 26 - 10
jwmud

@@ -29,6 +29,7 @@ import os
 from jwmudlib import database
 from jwmudlib import jwmu_exceptions
 from jwmudlib import daemon
+from jwmudlib import configuration
 
 parser = argparse.ArgumentParser(prog="jwmud", add_help=True)
 parser.add_argument("-d", "--daemon", action="store_true", dest="daemon",
@@ -43,25 +44,40 @@ parser.add_argument("-c", "--config", dest="config", help="define an alternate"
                                                           "configuration file")
 arguments = parser.parse_args()
 
-# TODO: Implement configuration and insert it here
+if arguments.config is not None:
+    config = configuration.conf(arguments.config)
+else:
+    config = configuration.conf()
 
-logger = logging.getLogger("jwmud")
+try:
+    config.Read()
+except jwmu_exceptions.ConfigurationFileAccessDenied as e:
+    print(e, file=sys.stderr)
+    sys.exit(1)
+except jwmu_exceptions.ConfigurationFileMissing as e:
+    print(e, file=sys.stderr)
+    sys.exit(1)
 
-# TODO: Set log level according to configuration
+logger = logging.getLogger("jwmud")
 
-logger.setLevel(logging.INFO)
+if config.values["syslog_level"] == "debug":
+    logger.setLevel(logging.DEBUG)
+elif config.values["syslog_level"] == "error":
+    logger.setLevel(logging.ERROR)
+else:
+    logger.setLevel(logging.INFO)
 
 formatter = logging.Formatter("%(name)s[" + str(os.getpid()) + "]: %(message)s")
 
-
-# TODO: Set syslog facility according to configuration
-
 if arguments.daemon is True:
-    syslog_handler = logging.handlers.SysLogHandler("/dev/log")
+    if config.values["syslog_facility"] == "daemon":
+        syslog_handler = logging.handlers.SysLogHandler(
+            "/dev/log", facility=logging.handlers.SysLogHandler.LOG_DAEMON)
+    else:
+        syslog_handler = logging.handlers.SysLogHandler("/dev/log")
     syslog_handler.setFormatter(formatter)
     logger.addHandler(syslog_handler)
 else:
     console_handler = logging.StreamHandler()
     console_handler.setFormatter(formatter)
-    logger.addHandler(console_handler)
-
+    logger.addHandler(console_handler)

+ 52 - 0
jwmudlib/configuration.py

@@ -0,0 +1,52 @@
+# This file is part of jwmud, written by Helmut Pozimski in 2014.
+#
+#       jwmud is free software: you can redistribute it and/or modify
+#       it under the terms of the GNU General Public License as published by
+#       the Free Software Foundation, version 2 of the License.
+#
+#       jwmud is distributed in the hope that it will be useful,
+#       but WITHOUT ANY WARRANTY; without even the implied warranty of
+#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#       GNU General Public License for more details.
+#
+#       You should have received a copy of the GNU General Public License
+#       along with jwmud.  If not, see <http://www.gnu.org/licenses/>.
+
+# -*- coding: utf8 -*-
+
+from jwmudlib import jwmu_exceptions
+
+class conf(object):
+    def __init__(self, file_path="/etc/jwmud.conf"):
+        """Constructor, creates the object and prepopulates the dictionary
+        that stores the configuration values.
+
+        """
+        self.values = {
+            "syslog_level": "info",
+            "syslog_facility": "user",
+            "alarm_script": None
+        }
+        self.__file_path = file_path
+
+    def Read(self):
+        """Reads the configuration file and puts the data into the
+        dictionary.
+
+        """
+        try:
+            conf_file = open(self.__file_path, "r")
+        except FileNotFoundError:
+            raise jwmu_exceptions.ConfigurationFileMissing()
+        except PermissionError:
+            raise jwmu_exceptions.ConfigurationFileAccessDenied()
+        else:
+            for line in conf_file:
+                if "#" in line:
+                    continue
+                else:
+                    line_stripped = line.strip()
+                    if line_stripped != "":
+                        tmp_value = line_stripped.split("=")
+                        self.values[tmp_value[0].lower()] = tmp_value[1]
+            conf_file.close()

+ 14 - 0
jwmudlib/jwmu_exceptions.py

@@ -56,3 +56,17 @@ class DayAlreadyInDatabase(Exception):
     def __str__(self):
         return self.__message
 
+class ConfigurationFileMissing(Exception):
+    def __init__(self):
+        self.__message = "The configuration file does not exist."
+
+    def __str__(self):
+        return self.__message
+
+class ConfigurationFileAccessDenied(Exception):
+    def __init__(self):
+        self.__message = "The configuration file could not be opened " \
+                         "for reading."
+
+    def __str__(self):
+        return self.__message