6071940a540e376e10016dcae4b6980eb74bbd1b
1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17 #
18 #$Id: back_anydbm.py,v 1.21 2002-01-02 02:31:38 richard Exp $
19 '''
20 This module defines a backend that saves the hyperdatabase in a database
21 chosen by anydbm. It is guaranteed to always be available in python
22 versions >2.1.1 (the dumbdbm fallback in 2.1.1 and earlier has several
23 serious bugs, and is not available)
24 '''
26 import whichdb, anydbm, os, marshal
27 from roundup import hyperdb, date, password
29 DEBUG=os.environ.get('HYPERDBDEBUG', '')
31 #
32 # Now the database
33 #
34 class Database(hyperdb.Database):
35 """A database for storing records containing flexible data types.
37 Transaction stuff TODO:
38 . check the timestamp of the class file and nuke the cache if it's
39 modified. Do some sort of conflict checking on the dirty stuff.
40 . perhaps detect write collisions (related to above)?
42 """
43 def __init__(self, storagelocator, journaltag=None):
44 """Open a hyperdatabase given a specifier to some storage.
46 The meaning of 'storagelocator' depends on the particular
47 implementation of the hyperdatabase. It could be a file name,
48 a directory path, a socket descriptor for a connection to a
49 database over the network, etc.
51 The 'journaltag' is a token that will be attached to the journal
52 entries for any edits done on the database. If 'journaltag' is
53 None, the database is opened in read-only mode: the Class.create(),
54 Class.set(), and Class.retire() methods are disabled.
55 """
56 self.dir, self.journaltag = storagelocator, journaltag
57 self.classes = {}
58 self.cache = {} # cache of nodes loaded or created
59 self.dirtynodes = {} # keep track of the dirty nodes by class
60 self.newnodes = {} # keep track of the new nodes by class
61 self.transactions = []
63 def __repr__(self):
64 return '<back_anydbm instance at %x>'%id(self)
66 #
67 # Classes
68 #
69 def __getattr__(self, classname):
70 """A convenient way of calling self.getclass(classname)."""
71 if self.classes.has_key(classname):
72 if DEBUG:
73 print '__getattr__', (self, classname)
74 return self.classes[classname]
75 raise AttributeError, classname
77 def addclass(self, cl):
78 if DEBUG:
79 print 'addclass', (self, cl)
80 cn = cl.classname
81 if self.classes.has_key(cn):
82 raise ValueError, cn
83 self.classes[cn] = cl
85 def getclasses(self):
86 """Return a list of the names of all existing classes."""
87 if DEBUG:
88 print 'getclasses', (self,)
89 l = self.classes.keys()
90 l.sort()
91 return l
93 def getclass(self, classname):
94 """Get the Class object representing a particular class.
96 If 'classname' is not a valid class name, a KeyError is raised.
97 """
98 if DEBUG:
99 print 'getclass', (self, classname)
100 return self.classes[classname]
102 #
103 # Class DBs
104 #
105 def clear(self):
106 '''Delete all database contents
107 '''
108 if DEBUG:
109 print 'clear', (self,)
110 for cn in self.classes.keys():
111 for type in 'nodes', 'journals':
112 path = os.path.join(self.dir, 'journals.%s'%cn)
113 if os.path.exists(path):
114 os.remove(path)
115 elif os.path.exists(path+'.db'): # dbm appends .db
116 os.remove(path+'.db')
118 def getclassdb(self, classname, mode='r'):
119 ''' grab a connection to the class db that will be used for
120 multiple actions
121 '''
122 if DEBUG:
123 print 'getclassdb', (self, classname, mode)
124 return self._opendb('nodes.%s'%classname, mode)
126 def _opendb(self, name, mode):
127 '''Low-level database opener that gets around anydbm/dbm
128 eccentricities.
129 '''
130 if DEBUG:
131 print '_opendb', (self, name, mode)
132 # determine which DB wrote the class file
133 db_type = ''
134 path = os.path.join(os.getcwd(), self.dir, name)
135 if os.path.exists(path):
136 db_type = whichdb.whichdb(path)
137 if not db_type:
138 raise hyperdb.DatabaseError, "Couldn't identify database type"
139 elif os.path.exists(path+'.db'):
140 # if the path ends in '.db', it's a dbm database, whether
141 # anydbm says it's dbhash or not!
142 db_type = 'dbm'
144 # new database? let anydbm pick the best dbm
145 if not db_type:
146 if DEBUG:
147 print "_opendb anydbm.open(%r, 'n')"%path
148 return anydbm.open(path, 'n')
150 # open the database with the correct module
151 try:
152 dbm = __import__(db_type)
153 except ImportError:
154 raise hyperdb.DatabaseError, \
155 "Couldn't open database - the required module '%s'"\
156 "is not available"%db_type
157 if DEBUG:
158 print "_opendb %r.open(%r, %r)"%(db_type, path, mode)
159 return dbm.open(path, mode)
161 #
162 # Nodes
163 #
164 def addnode(self, classname, nodeid, node):
165 ''' add the specified node to its class's db
166 '''
167 if DEBUG:
168 print 'addnode', (self, classname, nodeid, node)
169 self.newnodes.setdefault(classname, {})[nodeid] = 1
170 self.cache.setdefault(classname, {})[nodeid] = node
171 self.savenode(classname, nodeid, node)
173 def setnode(self, classname, nodeid, node):
174 ''' change the specified node
175 '''
176 if DEBUG:
177 print 'setnode', (self, classname, nodeid, node)
178 self.dirtynodes.setdefault(classname, {})[nodeid] = 1
179 # can't set without having already loaded the node
180 self.cache[classname][nodeid] = node
181 self.savenode(classname, nodeid, node)
183 def savenode(self, classname, nodeid, node):
184 ''' perform the saving of data specified by the set/addnode
185 '''
186 if DEBUG:
187 print 'savenode', (self, classname, nodeid, node)
188 self.transactions.append((self._doSaveNode, (classname, nodeid, node)))
190 def getnode(self, classname, nodeid, db=None, cache=1):
191 ''' get a node from the database
192 '''
193 if DEBUG:
194 print 'getnode', (self, classname, nodeid, cldb)
195 if cache:
196 # try the cache
197 cache = self.cache.setdefault(classname, {})
198 if cache.has_key(nodeid):
199 return cache[nodeid]
201 # get from the database and save in the cache
202 if db is None:
203 db = self.getclassdb(classname)
204 if not db.has_key(nodeid):
205 raise IndexError, "no such %s %s"%(classname, nodeid)
206 res = marshal.loads(db[nodeid])
207 if cache:
208 cache[nodeid] = res
209 return res
211 def hasnode(self, classname, nodeid, db=None):
212 ''' determine if the database has a given node
213 '''
214 if DEBUG:
215 print 'hasnode', (self, classname, nodeid, cldb)
216 # try the cache
217 cache = self.cache.setdefault(classname, {})
218 if cache.has_key(nodeid):
219 return 1
221 # not in the cache - check the database
222 if db is None:
223 db = self.getclassdb(classname)
224 res = db.has_key(nodeid)
225 return res
227 def countnodes(self, classname, db=None):
228 if DEBUG:
229 print 'countnodes', (self, classname, cldb)
230 # include the new nodes not saved to the DB yet
231 count = len(self.newnodes.get(classname, {}))
233 # and count those in the DB
234 if db is None:
235 db = self.getclassdb(classname)
236 count = count + len(db.keys())
237 return count
239 def getnodeids(self, classname, db=None):
240 if DEBUG:
241 print 'getnodeids', (self, classname, db)
242 # start off with the new nodes
243 res = self.newnodes.get(classname, {}).keys()
245 if db is None:
246 db = self.getclassdb(classname)
247 res = res + db.keys()
248 return res
251 #
252 # Files - special node properties
253 #
254 def filename(self, classname, nodeid, property=None):
255 '''Determine what the filename for the given node and optionally property is.
256 '''
257 # TODO: split into multiple files directories
258 if property:
259 return os.path.join(self.dir, 'files', '%s%s.%s'%(classname,
260 nodeid, property))
261 else:
262 # roundupdb.FileClass never specified the property name, so don't include it
263 return os.path.join(self.dir, 'files', '%s%s'%(classname,
264 nodeid))
266 def storefile(self, classname, nodeid, property, content):
267 '''Store the content of the file in the database. The property may be None, in
268 which case the filename does not indicate which property is being saved.
269 '''
270 name = self.filename(classname, nodeid, property)
271 open(name + '.tmp', 'wb').write(content)
272 self.transactions.append((self._doStoreFile, (name, )))
274 def getfile(self, classname, nodeid, property):
275 '''Store the content of the file in the database.
276 '''
277 filename = self.filename(classname, nodeid, property)
278 try:
279 return open(filename, 'rb').read()
280 except:
281 return open(filename+'.tmp', 'rb').read()
284 #
285 # Journal
286 #
287 def addjournal(self, classname, nodeid, action, params):
288 ''' Journal the Action
289 'action' may be:
291 'create' or 'set' -- 'params' is a dictionary of property values
292 'link' or 'unlink' -- 'params' is (classname, nodeid, propname)
293 'retire' -- 'params' is None
294 '''
295 if DEBUG:
296 print 'addjournal', (self, classname, nodeid, action, params)
297 self.transactions.append((self._doSaveJournal, (classname, nodeid,
298 action, params)))
300 def getjournal(self, classname, nodeid):
301 ''' get the journal for id
302 '''
303 if DEBUG:
304 print 'getjournal', (self, classname, nodeid)
305 # attempt to open the journal - in some rare cases, the journal may
306 # not exist
307 try:
308 db = self._opendb('journals.%s'%classname, 'r')
309 except anydbm.error, error:
310 if str(error) == "need 'c' or 'n' flag to open new db": return []
311 elif error.args[0] != 2: raise
312 return []
313 journal = marshal.loads(db[nodeid])
314 res = []
315 for entry in journal:
316 (nodeid, date_stamp, self.journaltag, action, params) = entry
317 date_obj = date.Date(date_stamp)
318 res.append((nodeid, date_obj, self.journaltag, action, params))
319 return res
322 #
323 # Basic transaction support
324 #
325 def commit(self):
326 ''' Commit the current transactions.
327 '''
328 if DEBUG:
329 print 'commit', (self,)
330 # TODO: lock the DB
332 # keep a handle to all the database files opened
333 self.databases = {}
335 # now, do all the transactions
336 for method, args in self.transactions:
337 method(*args)
339 # now close all the database files
340 for db in self.databases.values():
341 db.close()
342 del self.databases
343 # TODO: unlock the DB
345 # all transactions committed, back to normal
346 self.cache = {}
347 self.dirtynodes = {}
348 self.newnodes = {}
349 self.transactions = []
351 def _doSaveNode(self, classname, nodeid, node):
352 if DEBUG:
353 print '_doSaveNode', (self, classname, nodeid, node)
355 # get the database handle
356 db_name = 'nodes.%s'%classname
357 if self.databases.has_key(db_name):
358 db = self.databases[db_name]
359 else:
360 db = self.databases[db_name] = self.getclassdb(classname, 'c')
362 # now save the marshalled data
363 db[nodeid] = marshal.dumps(node)
365 def _doSaveJournal(self, classname, nodeid, action, params):
366 if DEBUG:
367 print '_doSaveJournal', (self, classname, nodeid, action, params)
368 entry = (nodeid, date.Date().get_tuple(), self.journaltag, action,
369 params)
371 # get the database handle
372 db_name = 'journals.%s'%classname
373 if self.databases.has_key(db_name):
374 db = self.databases[db_name]
375 else:
376 db = self.databases[db_name] = self._opendb(db_name, 'c')
378 # now insert the journal entry
379 if db.has_key(nodeid):
380 s = db[nodeid]
381 l = marshal.loads(db[nodeid])
382 l.append(entry)
383 else:
384 l = [entry]
385 db[nodeid] = marshal.dumps(l)
387 def _doStoreFile(self, name, **databases):
388 # the file is currently ".tmp" - move it to its real name to commit
389 os.rename(name+".tmp", name)
391 def rollback(self):
392 ''' Reverse all actions from the current transaction.
393 '''
394 if DEBUG:
395 print 'rollback', (self, )
396 for method, args in self.transactions:
397 # delete temporary files
398 if method == self._doStoreFile:
399 os.remove(args[0]+".tmp")
400 self.cache = {}
401 self.dirtynodes = {}
402 self.newnodes = {}
403 self.transactions = []
405 #
406 #$Log: not supported by cvs2svn $
407 #Revision 1.20 2001/12/18 15:30:34 rochecompaan
408 #Fixed bugs:
409 # . Fixed file creation and retrieval in same transaction in anydbm
410 # backend
411 # . Cgi interface now renders new issue after issue creation
412 # . Could not set issue status to resolved through cgi interface
413 # . Mail gateway was changing status back to 'chatting' if status was
414 # omitted as an argument
415 #
416 #Revision 1.19 2001/12/17 03:52:48 richard
417 #Implemented file store rollback. As a bonus, the hyperdb is now capable of
418 #storing more than one file per node - if a property name is supplied,
419 #the file is called designator.property.
420 #I decided not to migrate the existing files stored over to the new naming
421 #scheme - the FileClass just doesn't specify the property name.
422 #
423 #Revision 1.18 2001/12/16 10:53:38 richard
424 #take a copy of the node dict so that the subsequent set
425 #operation doesn't modify the oldvalues structure
426 #
427 #Revision 1.17 2001/12/14 23:42:57 richard
428 #yuck, a gdbm instance tests false :(
429 #I've left the debugging code in - it should be removed one day if we're ever
430 #_really_ anal about performace :)
431 #
432 #Revision 1.16 2001/12/12 03:23:14 richard
433 #Cor blimey this anydbm/whichdb stuff is yecchy. Turns out that whichdb
434 #incorrectly identifies a dbm file as a dbhash file on my system. This has
435 #been submitted to the python bug tracker as issue #491888:
436 #https://sourceforge.net/tracker/index.php?func=detail&aid=491888&group_id=5470&atid=105470
437 #
438 #Revision 1.15 2001/12/12 02:30:51 richard
439 #I fixed the problems with people whose anydbm was using the dbm module at the
440 #backend. It turns out the dbm module modifies the file name to append ".db"
441 #and my check to determine if we're opening an existing or new db just
442 #tested os.path.exists() on the filename. Well, no longer! We now perform a
443 #much better check _and_ cope with the anydbm implementation module changing
444 #too!
445 #I also fixed the backends __init__ so only ImportError is squashed.
446 #
447 #Revision 1.14 2001/12/10 22:20:01 richard
448 #Enabled transaction support in the bsddb backend. It uses the anydbm code
449 #where possible, only replacing methods where the db is opened (it uses the
450 #btree opener specifically.)
451 #Also cleaned up some change note generation.
452 #Made the backends package work with pydoc too.
453 #
454 #Revision 1.13 2001/12/02 05:06:16 richard
455 #. We now use weakrefs in the Classes to keep the database reference, so
456 # the close() method on the database is no longer needed.
457 # I bumped the minimum python requirement up to 2.1 accordingly.
458 #. #487480 ] roundup-server
459 #. #487476 ] INSTALL.txt
460 #
461 #I also cleaned up the change message / post-edit stuff in the cgi client.
462 #There's now a clearly marked "TODO: append the change note" where I believe
463 #the change note should be added there. The "changes" list will obviously
464 #have to be modified to be a dict of the changes, or somesuch.
465 #
466 #More testing needed.
467 #
468 #Revision 1.12 2001/12/01 07:17:50 richard
469 #. We now have basic transaction support! Information is only written to
470 # the database when the commit() method is called. Only the anydbm
471 # backend is modified in this way - neither of the bsddb backends have been.
472 # The mail, admin and cgi interfaces all use commit (except the admin tool
473 # doesn't have a commit command, so interactive users can't commit...)
474 #. Fixed login/registration forwarding the user to the right page (or not,
475 # on a failure)
476 #
477 #Revision 1.11 2001/11/21 02:34:18 richard
478 #Added a target version field to the extended issue schema
479 #
480 #Revision 1.10 2001/10/09 23:58:10 richard
481 #Moved the data stringification up into the hyperdb.Class class' get, set
482 #and create methods. This means that the data is also stringified for the
483 #journal call, and removes duplication of code from the backends. The
484 #backend code now only sees strings.
485 #
486 #Revision 1.9 2001/10/09 07:25:59 richard
487 #Added the Password property type. See "pydoc roundup.password" for
488 #implementation details. Have updated some of the documentation too.
489 #
490 #Revision 1.8 2001/09/29 13:27:00 richard
491 #CGI interfaces now spit up a top-level index of all the instances they can
492 #serve.
493 #
494 #Revision 1.7 2001/08/12 06:32:36 richard
495 #using isinstance(blah, Foo) now instead of isFooType
496 #
497 #Revision 1.6 2001/08/07 00:24:42 richard
498 #stupid typo
499 #
500 #Revision 1.5 2001/08/07 00:15:51 richard
501 #Added the copyright/license notice to (nearly) all files at request of
502 #Bizar Software.
503 #
504 #Revision 1.4 2001/07/30 01:41:36 richard
505 #Makes schema changes mucho easier.
506 #
507 #Revision 1.3 2001/07/25 01:23:07 richard
508 #Added the Roundup spec to the new documentation directory.
509 #
510 #Revision 1.2 2001/07/23 08:20:44 richard
511 #Moved over to using marshal in the bsddb and anydbm backends.
512 #roundup-admin now has a "freshen" command that'll load/save all nodes (not
513 # retired - mod hyperdb.Class.list() so it lists retired nodes)
514 #
515 #