merge from:
[monitor.git] / monitor / database / dbpickle.py
1 import os
2 import sys
3 import pickle
4 import inspect
5 import shutil
6 import time
7 from monitor import config
8
9 noserial=False
10 try:
11         from util.PHPSerialize import *
12         from util.PHPUnserialize import *
13 except:
14         #print >>sys.stderr, "PHPSerial db type not allowed."
15         noserial=True
16
17 DEBUG= 0
18 PICKLE_PATH=config.MONITOR_DATA_ROOT
19
20 def lastModified(name, type=None):
21         # TODO: fix for 'debug' mode also.
22         t = SPickle().mtime("production.%s" % name, type)
23         return t
24
25 def cachedRecently(name, length=int(config.cachetime), type=None):
26         """
27                 return true or false based on whether the modified time of the cached
28                 file is within 'length' minutes.
29         """
30         try:
31                 t = lastModified(name, type)
32         except:
33                 # file doesn't exist or we can't access it.
34                 return False
35
36         current_time = time.time()
37         if current_time > t + length*60:
38                 return False
39         else:
40                 return True
41
42 def dbLoad(name, type=None):
43         return SPickle().load(name, type)
44
45 def dbExists(name, type=None):
46         #if self.config.debug:
47         #       name = "debug.%s" % name
48         return SPickle().exists(name, type)
49
50 def dbDump(name, obj=None, type=None):
51         # depth of the dump is 2 now, since we're redirecting to '.dump'
52         return SPickle().dump(name, obj, type, 2)
53
54 def if_cached_else_refresh(cond, refresh, name, function, type=None):
55         s = SPickle()
56         if refresh:
57                 if not config.debug and s.exists("production.%s" % name, type):
58                         s.remove("production.%s" % name, type)
59                 if config.debug and s.exists("debug.%s" % name, type):
60                         s.remove("debug.%s" % name, type)
61
62         return if_cached_else(cond, name, function, type)
63
64 def if_cached_else(cond, name, function, type=None):
65         s = SPickle()
66         if (cond and s.exists("production.%s" % name, type)) or \
67            (cond and config.debug and s.exists("debug.%s" % name, type)):
68                 o = s.load(name, type)
69         else:
70                 o = function()
71                 if cond:
72                         s.dump(name, o, type)   # cache the object using 'name'
73                         o = s.load(name, type)
74                 # TODO: what if 'o' hasn't been converted...
75         return o
76
77 class SPickle:
78         def __init__(self, path=PICKLE_PATH):
79                 self.path = path
80
81         def if_cached_else(self, cond, name, function, type=None):
82                 if cond and self.exists("production.%s" % name, type):
83                         o = self.load(name, type)
84                 else:
85                         o = function()
86                         if cond:
87                                 self.dump(name, o, type)        # cache the object using 'name'
88                 return o
89
90         def __file(self, name, type=None):
91                 if type == None:
92                         return "%s/%s.pkl" % (self.path, name)
93                 else:
94                         if noserial:
95                                 raise Exception("No PHPSerializer module available")
96
97                         return "%s/%s.phpserial" % (self.path, name)
98
99         def mtime(self, name, type=None):
100                 f = os.stat(self.__file(name, type))
101                 return f[-2]
102                 
103         def exists(self, name, type=None):
104                 return os.path.exists(self.__file(name, type))
105
106         def remove(self, name, type=None):
107                 return os.remove(self.__file(name, type))
108
109         def load(self, name, type=None):
110                 """ 
111                 In debug mode, we should fail if neither file exists.
112                         if the debug file exists, reset name
113                         elif the original file exists, make a copy, reset name
114                         else neither exist, raise an error
115                 Otherwise, it's normal mode, if the file doesn't exist, raise error
116                 Load the file
117                 """
118                 print "loading %s" % name
119
120                 if config.debug:
121                         if self.exists("debug.%s" % name, type):
122                                 name = "debug.%s" % name
123                         elif self.exists("production.%s" % name, type):
124                                 debugname = "debug.%s" % name
125                                 if not self.exists(debugname, type):
126                                         name = "production.%s" % name
127                                         shutil.copyfile(self.__file(name, type), self.__file(debugname, type))
128                                 name = debugname
129                         else:   # neither exist
130                                 raise Exception, "No such pickle based on %s" % self.__file("debug.%s" % name, type)
131                 else:
132                         if   self.exists("production.%s" % name, type):
133                                 name = "production.%s" % name
134                         elif self.exists(name, type):
135                                 name = name
136                         else:
137                                 raise Exception, "No such file %s" % name
138                                 
139
140                 #import traceback
141                 #print traceback.print_stack()
142                 #print "loading %s" % self.__file(name, type)
143                 #sys.stderr.write("-----------------------------\n")
144                 f = open(self.__file(name, type), 'r')
145                 if type == None:
146                         o = pickle.load(f)
147                 else:
148                         if noserial:
149                                 raise Exception("No PHPSerializer module available")
150                         s = PHPUnserialize()
151                         o = s.unserialize(f.read())
152                 f.close()
153                 return o
154                         
155         
156         # use the environment to extract the data associated with the local
157         # variable 'name'
158         def dump(self, name, obj=None, type=None, depth=1):
159                 if obj == None:
160                         o = inspect.getouterframes(inspect.currentframe())
161                         up1 = o[depth][0] # get the frame one prior to (up from) this frame
162                         argvals = inspect.getargvalues(up1)
163                         # TODO: check that 'name' is a local variable; otherwise this would fail.
164                         obj = argvals[3][name] # extract the local variable name 'name'
165                 if not os.path.isdir("%s/" % self.path):
166                         os.mkdir("%s" % self.path)
167                 if config.debug:
168                         name = "debug.%s" % name
169                 else:
170                         name = "production.%s" % name
171                 f = open(self.__file(name, type), 'w')
172                 if type == None:
173                         pickle.dump(obj, f)
174                 else:
175                         if noserial:
176                                 raise Exception("No PHPSerializer module available")
177                         s = PHPSerialize()
178                         f.write(s.serialize(obj))
179                 f.close()
180                 return