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

Revision 1250, 18.7 kB (checked in by jalet, 20 years ago)

Fixed caching of printer groups

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