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

Revision 1257, 19.1 kB (checked in by jalet, 20 years ago)

Copyright year changed.

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