reguire gnupg1 on f>=31; sense the system to use gpg1 when installed
[nodemanager.git] / logger.py
index 767a04e..064e98e 100644 (file)
--- a/logger.py
+++ b/logger.py
@@ -1,7 +1,11 @@
+"""
+A very simple logger that tries to be concurrency-safe.
+"""
 
-"""A very simple logger that tries to be concurrency-safe."""
+# pylint: disable=c0111
 
-import os, sys
+import sys
+import os
 import time
 import traceback
 import subprocess
@@ -20,24 +24,26 @@ LOG_LEVEL = LOG_NODE
 
 def set_level(level):
     global LOG_LEVEL
-    try:
-        assert level in [LOG_NONE, LOG_NODE, LOG_VERBOSE]
+    if level in (LOG_NONE, LOG_NODE, LOG_VERBOSE):
         LOG_LEVEL = level
-    except:
-        logger.log("Failed to set LOG_LEVEL to %s" % level)
+    else:
+        log("Failed to set LOG_LEVEL to %s" % level)
 
 def verbose(msg):
     log('(v) ' + msg, LOG_VERBOSE)
 
 def log(msg, level=LOG_NODE):
-    """Write <msg> to the log file if level >= current log level (default LOG_NODE)."""
+    """
+    Write <msg> to the log file if level >= current log level (default LOG_NODE).
+    """
     if level > LOG_LEVEL:
         return
     try:
-        fd = os.open(LOG_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0600)
+        fd = os.open(LOG_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
         if not msg.endswith('\n'):
             msg += '\n'
-        os.write(fd, '%s: %s' % (time.asctime(time.gmtime()), msg))
+        to_write = '%s: %s' % (time.asctime(time.gmtime()), msg)
+        os.write(fd, to_write.encode())
         os.close(fd)
     except OSError:
         sys.stderr.write(msg)
@@ -69,24 +75,24 @@ def log_trace(msg="", name=None):
 # for some reason the various modules are still triggered even when the
 # data from PLC cannot be reached
 # we show this message instead of the exception stack instead in this case
-def log_missing_data(msg,key):
-    log("%s: could not find the %s key in data (PLC connection down?) - IGNORED"%(msg,key))
+def log_missing_data(msg, key):
+    log("%s: could not find the %s key in data (PLC connection down?) - IGNORED"%(msg, key))
 
-def log_data_in_file(data, file, message="",level=LOG_NODE):
+def log_data_in_file(data, file, message="", level=LOG_NODE):
     if level > LOG_LEVEL:
         return
     import pprint, time
     try:
-        f=open(file,'w')
-        now=time.strftime("Last update: %Y.%m.%d at %H:%M:%S %Z", time.localtime())
-        f.write(now+'\n')
-        if message: f.write('Message:'+message+'\n')
-        pp=pprint.PrettyPrinter(stream=f,indent=2)
-        pp.pprint(data)
-        f.close()
-        verbose("logger:.log_data_in_file Owerwrote %s"%file)
+        with open(file, 'w') as f:
+            now=time.strftime("Last update: %Y.%m.%d at %H:%M:%S %Z", time.localtime())
+            f.write(now+'\n')
+            if message: f.write('Message:'+message+'\n')
+            pp=pprint.PrettyPrinter(stream=f, indent=2)
+            pp.pprint(data)
+            f.close()
+            verbose("logger:.log_data_in_file Owerwrote %s"%file)
     except:
-        log_exc('logger.log_data_in_file failed - file=%s - message=%r'%(file,message))
+        log_exc('logger.log_data_in_file failed - file=%s - message=%r'%(file, message))
 
 def log_slivers(data):
     log_data_in_file(data, LOG_SLIVERS, "raw GetSlivers")
@@ -102,9 +108,9 @@ class Buffer:
         self.buffer = ''
         self.message = message
 
-    def add(self,c):
+    def add(self, c):
         self.buffer += c
-        if c=='\n':
+        if c == '\n':
             self.flush()
 
     def flush(self):
@@ -124,8 +130,11 @@ def log_call(command, timeout=default_timeout_minutes*60, poll=1):
     trigger=time.time()+timeout
     result = False
     try:
-        child = subprocess.Popen(command, bufsize=1,
-                                 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
+        child = subprocess.Popen(
+            command, bufsize=1,
+            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+            close_fds=True,
+            universal_newlines=True)
         buffer = Buffer()
         while True:
             # see if anything can be read within the poll interval
@@ -144,13 +153,13 @@ def log_call(command, timeout=default_timeout_minutes*60, poll=1):
                     break
                 # child has failed
                 else:
-                    log("log_call:end command (%s) returned with code %d" %(message,returncode))
+                    log("log_call:end command (%s) returned with code %d" %(message, returncode))
                     break
             # no : still within timeout ?
             if time.time() >= trigger:
                 buffer.flush()
                 child.terminate()
-                log("log_call:end terminating command (%s) - exceeded timeout %d s"%(message,timeout))
+                log("log_call:end terminating command (%s) - exceeded timeout %d s"%(message, timeout))
                 break
     except:
         log_exc("failed to run command %s" % message)