root / pykota / trunk / pykota / storage.py @ 1130

Revision 1130, 15.3 kB (checked in by jalet, 21 years ago)

Storage caching mechanism added.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2#
3# PyKota : Print Quotas for CUPS and LPRng
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19#
20# $Id$
21#
22# $Log$
23# Revision 1.20  2003/10/02 20:23:18  jalet
24# Storage caching mechanism added.
25#
26# Revision 1.19  2003/07/16 21:53:07  jalet
27# Really big modifications wrt new configuration file's location and content.
28#
29# Revision 1.18  2003/07/07 08:33:18  jalet
30# Bug fix due to a typo in LDAP code
31#
32# Revision 1.17  2003/07/05 07:46:50  jalet
33# The previous bug fix was incomplete.
34#
35# Revision 1.16  2003/06/25 19:52:31  jalet
36# Should be ready for testing :-)
37#
38# Revision 1.15  2003/06/25 14:10:58  jalet
39# Exception raising for now.
40#
41# Revision 1.14  2003/06/25 14:10:01  jalet
42# Hey, it may work (edpykota --reset excepted) !
43#
44# Revision 1.13  2003/06/10 16:37:54  jalet
45# Deletion of the second user which is not needed anymore.
46# Added a debug configuration field in /etc/pykota.conf
47# All queries can now be sent to the logger in debug mode, this will
48# greatly help improve performance when time for this will come.
49#
50# Revision 1.12  2003/04/23 22:13:57  jalet
51# Preliminary support for LPRng added BUT STILL UNTESTED.
52#
53# Revision 1.11  2003/04/10 21:47:20  jalet
54# Job history added. Upgrade script neutralized for now !
55#
56# Revision 1.10  2003/03/29 13:45:27  jalet
57# GPL paragraphs were incorrectly (from memory) copied into the sources.
58# Two README files were added.
59# Upgrade script for PostgreSQL pre 1.01 schema was added.
60#
61# Revision 1.9  2003/02/17 22:55:01  jalet
62# More options can now be set per printer or globally :
63#
64#       admin
65#       adminmail
66#       gracedelay
67#       requester
68#
69# the printer option has priority when both are defined.
70#
71# Revision 1.8  2003/02/17 22:05:50  jalet
72# Storage backend now supports admin and user passwords (untested)
73#
74# Revision 1.7  2003/02/10 12:07:31  jalet
75# Now repykota should output the recorded total page number for each printer too.
76#
77# Revision 1.6  2003/02/09 13:05:43  jalet
78# Internationalization continues...
79#
80# Revision 1.5  2003/02/08 22:39:46  jalet
81# --reset command line option added
82#
83# Revision 1.4  2003/02/08 09:59:59  jalet
84# Added preliminary base class for all storages
85#
86# Revision 1.3  2003/02/05 22:10:29  jalet
87# Typos
88#
89# Revision 1.2  2003/02/05 22:02:22  jalet
90# __import__ statement didn't work as expected
91#
92# Revision 1.1  2003/02/05 21:28:17  jalet
93# Initial import into CVS
94#
95#
96#
97
98class PyKotaStorageError(Exception):
99    """An exception for Quota Storage related stuff."""
100    def __init__(self, message = ""):
101        self.message = message
102        Exception.__init__(self, message)
103    def __repr__(self):
104        return self.message
105    __str__ = __repr__
106       
107class StorageObject :
108    """Object present in the Quota Storage."""
109    def __init__(self, parent) :
110        "Initialize minimal data."""
111        self.parent = parent
112        self.ident = None
113        self.Exists = 0
114       
115class StorageUser(StorageObject) :       
116    """User class."""
117    def __init__(self, parent, name) :
118        StorageObject.__init__(self, parent)
119        self.Name = name
120        self.LimitBy = None
121        self.AccountBalance = None
122        self.LifeTimePaid = None
123        self.Email = None
124       
125    def consumeAccountBalance(self, amount) :     
126        """Consumes an amount of money from the user's account balance."""
127        newbalance = float(self.AccountBalance or 0.0) - amount
128        self.parent.writeUserAccountBalance(self, newbalance)
129        self.AccountBalance = newbalance
130       
131    def setAccountBalance(self, balance, lifetimepaid) :   
132        """Sets the user's account balance in case he pays more money."""
133        self.parent.writeUserAccountBalance(self, balance, lifetimepaid)
134        self.AccountBalance = balance
135        self.LifeTimePaid = lifetimepaid
136       
137    def setLimitBy(self, limitby) :   
138        """Sets the user's limiting factor."""
139        try :
140            limitby = limitby.lower()
141        except AttributeError :   
142            limitby = "quota"
143        if limitby in ["quota", "balance"] :
144            self.parent.writeUserLimitBy(self, limitby)
145            self.LimitBy = limitby
146       
147    def delete(self) :   
148        """Deletes an user from the Quota Storage."""
149        self.parent.beginTransaction()
150        try :
151            self.parent.deleteUser(self)
152        except PyKotaStorageError, msg :   
153            self.parent.rollbackTransaction()
154            raise PyKotaStorageError, msg
155        else :   
156            self.parent.commitTransaction()
157       
158class StorageGroup(StorageObject) :       
159    """User class."""
160    def __init__(self, parent, name) :
161        StorageObject.__init__(self, parent)
162        self.Name = name
163        self.LimitBy = None
164        self.AccountBalance = None
165        self.LifeTimePaid = None
166       
167    def setLimitBy(self, limitby) :   
168        """Sets the user's limiting factor."""
169        try :
170            limitby = limitby.lower()
171        except AttributeError :   
172            limitby = "quota"
173        if limitby in ["quota", "balance"] :
174            self.parent.writeGroupLimitBy(self, limitby)
175            self.LimitBy = limitby
176       
177    def delete(self) :   
178        """Deletes a group from the Quota Storage."""
179        self.parent.beginTransaction()
180        try :
181            self.parent.deleteGroup(self)
182        except PyKotaStorageError, msg :   
183            self.parent.rollbackTransaction()
184            raise PyKotaStorageError, msg
185        else :   
186            self.parent.commitTransaction()
187       
188class StoragePrinter(StorageObject) :
189    """Printer class."""
190    def __init__(self, parent, name) :
191        StorageObject.__init__(self, parent)
192        self.Name = name
193        self.PricePerPage = None
194        self.PricePerJob = None
195        self.LastJob = None
196       
197    def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None) :   
198        """Adds a job to the printer's history."""
199        self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize)
200        # TODO : update LastJob object ? Probably not needed.
201       
202    def setPrices(self, priceperpage = None, priceperjob = None) :   
203        """Sets the printer's prices."""
204        if priceperpage is None :
205            priceperpage = self.PricePerPage
206        else :   
207            self.PricePerPage = float(priceperpage)
208        if priceperjob is None :   
209            priceperjob = self.PricePerJob
210        else :   
211            self.PricePerJob = float(priceperjob)
212        self.parent.writePrinterPrices(self)
213       
214class StorageUserPQuota(StorageObject) :
215    """User Print Quota class."""
216    def __init__(self, parent, user, printer) :
217        StorageObject.__init__(self, parent)
218        self.User = user
219        self.Printer = printer
220        self.PageCounter = None
221        self.LifePageCounter = None
222        self.SoftLimit = None
223        self.HardLimit = None
224        self.DateLimit = None
225       
226    def setDateLimit(self, datelimit) :   
227        """Sets the date limit for this quota."""
228        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
229        self.parent.writeUserPQuotaDateLimit(self, date)
230        self.DateLimit = date
231       
232    def setLimits(self, softlimit, hardlimit) :   
233        """Sets the soft and hard limit for this quota."""
234        self.parent.writeUserPQuotaLimits(self, softlimit, hardlimit)
235        self.SoftLimit = softlimit
236        self.HardLimit = hardlimit
237       
238    def reset(self) :   
239        """Resets page counter to 0."""
240        self.parent.writeUserPQuotaPagesCounters(self, 0, int(self.LifePageCounter or 0))
241        self.PageCounter = 0
242       
243    def increasePagesUsage(self, nbpages) :
244        """Increase the value of used pages and money."""
245        if nbpages :
246            jobprice = (float(self.Printer.PricePerPage or 0.0) * nbpages) + float(self.Printer.PricePerJob or 0.0)
247            newpagecounter = int(self.PageCounter or 0) + nbpages
248            newlifepagecounter = int(self.LifePageCounter or 0) + nbpages
249            self.parent.beginTransaction()
250            try :
251                if jobprice : # optimization : don't access the database if unneeded.
252                    self.User.consumeAccountBalance(jobprice)
253                self.parent.writeUserPQuotaPagesCounters(self, newpagecounter, newlifepagecounter)
254            except PyKotaStorageError, msg :   
255                self.parent.rollbackTransaction()
256                raise PyKotaStorageError, msg
257            else :   
258                self.parent.commitTransaction()
259                self.PageCounter = newpagecounter
260                self.LifePageCounter = newlifepagecounter
261       
262class StorageGroupPQuota(StorageObject) :
263    """Group Print Quota class."""
264    def __init__(self, parent, group, printer) :
265        StorageObject.__init__(self, parent)
266        self.Group = group
267        self.Printer = printer
268        self.PageCounter = None
269        self.LifePageCounter = None
270        self.SoftLimit = None
271        self.HardLimit = None
272        self.DateLimit = None
273       
274    def setDateLimit(self, datelimit) :   
275        """Sets the date limit for this quota."""
276        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
277        self.parent.writeGroupPQuotaDateLimit(self, date)
278        self.DateLimit = date
279       
280    def setLimits(self, softlimit, hardlimit) :   
281        """Sets the soft and hard limit for this quota."""
282        self.parent.writeGroupPQuotaLimits(self, softlimit, hardlimit)
283        self.SoftLimit = softlimit
284        self.HardLimit = hardlimit
285       
286class StorageLastJob(StorageObject) :
287    """Printer's Last Job class."""
288    def __init__(self, parent, printer) :
289        StorageObject.__init__(self, parent)
290        self.Printer = printer
291        self.JobId = None
292        self.User = None
293        self.PrinterPageCounter = None
294        self.JobSize = None
295        self.JobAction = None
296        self.JobDate = None
297       
298    def setSize(self, jobsize) :
299        """Sets the last job's size."""
300        self.parent.writeLastJobSize(self, jobsize)
301        self.JobSize = jobsize
302   
303class BaseStorage :
304    def __init__(self, pykotatool) :
305        """Opens the LDAP connection."""
306        # raise PyKotaStorageError, "Sorry, the LDAP backend for PyKota is not yet implemented !"
307        self.closed = 1
308        self.tool = pykotatool
309        self.usecache = pykotatool.config.getCaching()
310        if self.usecache :
311            self.tool.logdebug("Caching enabled.")
312            self.caches = { "USERS" : {}, "GROUPS" : {}, "PRINTERS" : {}, "USERPQUOTAS" : {}, "GROUPPQUOTAS" : {}, "JOBS" : {}, "LASTJOBS" : {} }
313       
314    def __del__(self) :       
315        """Ensures that the database connection is closed."""
316        self.close()
317       
318    def getFromCache(self, cachetype, key) :
319        """Tries to extract something from the cache."""
320        if self.usecache :
321            entry = self.caches[cachetype].get(key)
322            if entry is not None :
323                self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key))
324            else :   
325                self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key))
326            return entry   
327           
328    def cacheEntry(self, cachetype, key, value) :       
329        """Puts an entry in the cache."""
330        if self.usecache :
331            self.caches[cachetype][key] = value
332           
333    def getUser(self, username) :       
334        """Returns the user from cache."""
335        user = self.getFromCache("USERS", username)
336        if user is None :
337            user = self.getUserFromBackend(username)
338            self.cacheEntry("USERS", username, user)
339        return user   
340       
341    def getGroup(self, groupname) :       
342        """Returns the group from cache."""
343        group = self.getFromCache("GROUPS", groupname)
344        if group is None :
345            group = self.getGroupFromBackend(groupname)
346            self.cacheEntry("GROUPS", groupname, group)
347        return group   
348       
349    def getPrinter(self, printername) :       
350        """Returns the printer from cache."""
351        printer = self.getFromCache("PRINTERS", printername)
352        if printer is None :
353            printer = self.getPrinterFromBackend(printername)
354            self.cacheEntry("PRINTERS", printername, printer)
355        return printer   
356       
357    def getUserPQuota(self, user, printer) :       
358        """Returns the user quota information from cache."""
359        useratprinter = "%s@%s" % (user.Name, printer.Name)
360        upquota = self.getFromCache("USERPQUOTAS", useratprinter)
361        if upquota is None :
362            upquota = self.getUserPQuotaFromBackend(user, printer)
363            self.cacheEntry("USERPQUOTAS", useratprinter, upquota)
364        return upquota   
365       
366    def getGroupPQuota(self, group, printer) :       
367        """Returns the group quota information from cache."""
368        groupatprinter = "%s@%s" % (group.Name, printer.Name)
369        gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter)
370        if gpquota is None :
371            gpquota = self.getGroupPQuotaFromBackend(group, printer)
372            self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota)
373        return gpquota   
374       
375    def getPrinterLastJob(self, printer) :       
376        """Extracts last job information for a given printer from cache."""
377        lastjob = self.getFromCache("LASTJOBS", printer.Name)
378        if lastjob is None :
379            lastjob = self.getPrinterLastJobFromBackend(printer)
380            self.cacheEntry("LASTJOBS", printer.Name, lastjob)
381        return lastjob   
382       
383def openConnection(pykotatool) :
384    """Returns a connection handle to the appropriate Quota Storage Database."""
385    backendinfo = pykotatool.config.getStorageBackend()
386    backend = backendinfo["storagebackend"]
387    try :
388        if not backend.isalpha() :
389            # don't trust user input
390            raise ImportError
391        #   
392        # TODO : descending compatibility
393        #
394        if backend == "postgresql" :
395            backend = "pgstorage"       # TODO : delete, this is for descending compatibility only
396        exec "from pykota.storages import %s as storagebackend" % backend.lower()   
397    except ImportError :
398        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
399    else :   
400        host = backendinfo["storageserver"]
401        database = backendinfo["storagename"]
402        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
403        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
404        return getattr(storagebackend, "Storage")(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.