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