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

Revision 1137, 16.7 kB (checked in by jalet, 21 years ago)

More work on caching

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