Merge branch 'devel' of ssh://git.planet-lab.org/git/nodemanager into devel
[nodemanager.git] / logger.py
1
2 """A very simple logger that tries to be concurrency-safe."""
3
4 import os, sys
5 import time
6 import traceback
7 import subprocess
8 import select
9
10 LOG_FILE    = '/var/log/nodemanager'
11 LOG_SLIVERS = '/var/lib/nodemanager/getslivers.txt'
12 LOG_DATABASE = '/var/lib/nodemanager/database.txt'
13
14 # basically define 3 levels
15 LOG_NONE=0
16 LOG_NODE=1
17 LOG_VERBOSE=2
18 # default is to log a reasonable amount of stuff for when running on operational nodes
19 LOG_LEVEL=1
20
21 def set_level(level):
22     global LOG_LEVEL
23     assert level in [LOG_NONE,LOG_NODE,LOG_VERBOSE]
24     LOG_LEVEL=level
25
26 def verbose(msg):
27     log('(v) '+msg,LOG_VERBOSE)
28
29 def log(msg,level=LOG_NODE):
30     """Write <msg> to the log file if level >= current log level (default LOG_NODE)."""
31     if (level > LOG_LEVEL):
32         return
33     try:
34         fd = os.open(LOG_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0600)
35         if not msg.endswith('\n'): msg += '\n'
36         os.write(fd, '%s: %s' % (time.asctime(time.gmtime()), msg))
37         os.close(fd)
38     except OSError:
39         sys.stderr.write(msg)
40         sys.stderr.flush()
41
42 def log_exc(msg="",name=None):
43     """Log the traceback resulting from an exception."""
44     if name:
45         log("%s: EXCEPTION caught <%s> \n %s" %(name, msg, traceback.format_exc()))
46     else:
47         log("EXCEPTION caught <%s> \n %s" %(msg, traceback.format_exc()))
48
49 ########## snapshot data to a file
50 # for some reason the various modules are still triggered even when the
51 # data from PLC cannot be reached
52 # we show this message instead of the exception stack instead in this case
53 def log_missing_data (msg,key):
54     log("%s: could not find the %s key in data (PLC connection down?) - IGNORED"%(msg,key))
55
56 def log_data_in_file (data, file, message="",level=LOG_NODE):
57     if (level > LOG_LEVEL):
58         return
59     import pprint, time
60     try:
61         f=open(file,'w')
62         now=time.strftime("Last update: %Y.%m.%d at %H:%M:%S %Z", time.localtime())
63         f.write(now+'\n')
64         if message: f.write('Message:'+message+'\n')
65         pp=pprint.PrettyPrinter(stream=f,indent=2)
66         pp.pprint(data)
67         f.close()
68         verbose("logger:.log_data_in_file Owerwrote %s"%file)
69     except:
70         log_exc('logger.log_data_in_file failed - file=%s - message=%r'%(file,message))
71
72 def log_slivers (data):
73     log_data_in_file (data, LOG_SLIVERS, "raw GetSlivers")
74 def log_database (db):
75     log_data_in_file (db, LOG_DATABASE, "raw database")
76
77 #################### child processes
78 # avoid waiting until the process returns;
79 # that makes debugging of hanging children hard
80
81 class Buffer:
82     def __init__ (self,message='log_call: '):
83         self.buffer=''
84         self.message=message
85
86     def add (self,c):
87         self.buffer += c
88         if c=='\n': self.flush()
89
90     def flush (self):
91         if self.buffer:
92             log (self.message + self.buffer)
93             self.buffer=''
94
95 # time out in seconds - avoid hanging subprocesses - default is 5 minutes
96 default_timeout_minutes=5
97
98 # returns a bool that is True when everything goes fine and the retcod is 0
99 def log_call(command,timeout=default_timeout_minutes*60,poll=1):
100     message=" ".join(command)
101     log("log_call: running command %s" % message)
102     verbose("log_call: timeout=%r s" % timeout)
103     verbose("log_call: poll=%r s" % poll)
104     trigger=time.time()+timeout
105     result = False
106     try:
107         child = subprocess.Popen(command, bufsize=1,
108                                  stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
109         buffer = Buffer()
110         while True:
111             # see if anything can be read within the poll interval
112             (r,w,x)=select.select([child.stdout],[],[],poll)
113             if r: buffer.add(child.stdout.read(1))
114             # is process over ?
115             returncode=child.poll()
116             # yes
117             if returncode != None:
118                 buffer.flush()
119                 # child is done and return 0
120                 if returncode == 0:
121                     log("log_call:end command (%s) completed" % message)
122                     result=True
123                     break
124                 # child has failed
125                 else:
126                     log("log_call:end command (%s) returned with code %d" %(message,returncode))
127                     break
128             # no : still within timeout ?
129             if time.time() >= trigger:
130                 buffer.flush()
131                 child.terminate()
132                 log("log_call:end terminating command (%s) - exceeded timeout %d s"%(message,timeout))
133                 break
134     except: log_exc("failed to run command %s" % message)
135     return result