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