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
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 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.33  2004/01/08 14:10:32  jalet
25# Copyright year changed.
26#
27# Revision 1.32  2004/01/06 16:02:57  jalet
28# This time printer groups caching works.
29#
30# Revision 1.31  2004/01/06 15:51:24  jalet
31# Fixed caching of printer groups
32#
33# Revision 1.30  2004/01/06 14:24:59  jalet
34# Printer groups should be cached now, if caching is enabled.
35#
36# Revision 1.29  2003/12/27 16:49:25  uid67467
37# Should be ok now.
38#
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#
42# Revision 1.27  2003/11/23 19:01:36  jalet
43# Job price added to history
44#
45# Revision 1.26  2003/11/21 14:28:45  jalet
46# More complete job history.
47#
48# Revision 1.25  2003/10/08 21:12:27  jalet
49# Do not cache anymore entries which don't exist.
50#
51# Revision 1.24  2003/10/07 22:06:05  jalet
52# Preliminary code to disable job history
53#
54# Revision 1.23  2003/10/07 09:07:28  jalet
55# Character encoding added to please latest version of Python
56#
57# Revision 1.22  2003/10/06 13:12:27  jalet
58# More work on caching
59#
60# Revision 1.21  2003/10/03 09:02:20  jalet
61# Logs cache store actions too
62#
63# Revision 1.20  2003/10/02 20:23:18  jalet
64# Storage caching mechanism added.
65#
66# Revision 1.19  2003/07/16 21:53:07  jalet
67# Really big modifications wrt new configuration file's location and content.
68#
69# Revision 1.18  2003/07/07 08:33:18  jalet
70# Bug fix due to a typo in LDAP code
71#
72# Revision 1.17  2003/07/05 07:46:50  jalet
73# The previous bug fix was incomplete.
74#
75# Revision 1.16  2003/06/25 19:52:31  jalet
76# Should be ready for testing :-)
77#
78# Revision 1.15  2003/06/25 14:10:58  jalet
79# Exception raising for now.
80#
81# Revision 1.14  2003/06/25 14:10:01  jalet
82# Hey, it may work (edpykota --reset excepted) !
83#
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#
90# Revision 1.12  2003/04/23 22:13:57  jalet
91# Preliminary support for LPRng added BUT STILL UNTESTED.
92#
93# Revision 1.11  2003/04/10 21:47:20  jalet
94# Job history added. Upgrade script neutralized for now !
95#
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#
101# Revision 1.9  2003/02/17 22:55:01  jalet
102# More options can now be set per printer or globally :
103#
104#       admin
105#       adminmail
106#       gracedelay
107#       requester
108#
109# the printer option has priority when both are defined.
110#
111# Revision 1.8  2003/02/17 22:05:50  jalet
112# Storage backend now supports admin and user passwords (untested)
113#
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#
117# Revision 1.6  2003/02/09 13:05:43  jalet
118# Internationalization continues...
119#
120# Revision 1.5  2003/02/08 22:39:46  jalet
121# --reset command line option added
122#
123# Revision 1.4  2003/02/08 09:59:59  jalet
124# Added preliminary base class for all storages
125#
126# Revision 1.3  2003/02/05 22:10:29  jalet
127# Typos
128#
129# Revision 1.2  2003/02/05 22:02:22  jalet
130# __import__ statement didn't work as expected
131#
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__
146       
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
163        self.Email = None
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."""
173        self.parent.writeUserAccountBalance(self, balance, lifetimepaid)
174        self.AccountBalance = balance
175        self.LifeTimePaid = lifetimepaid
176       
177    def setLimitBy(self, limitby) :   
178        """Sets the user's limiting factor."""
179        try :
180            limitby = limitby.lower()
181        except AttributeError :   
182            limitby = "quota"
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."""
209        try :
210            limitby = limitby.lower()
211        except AttributeError :   
212            limitby = "quota"
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       
237    def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None) :
238        """Adds a job to the printer's history."""
239        self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options)
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
265        self.ParentPrintersUserPQuota = (user.Exists and printer.Exists and parent.getParentPrintersUserPQuota(self)) or []
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."""
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()
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
338        self.JobPrice = None
339        self.JobFileName = None
340        self.JobTitle = None
341        self.JobCopies = None
342        self.JobOptions = None
343       
344    def setSize(self, jobsize) :
345        """Sets the last job's size."""
346        jobprice = (float(self.Printer.PricePerPage or 0.0) * jobsize) + float(self.Printer.PricePerJob or 0.0)
347        self.parent.writeLastJobSize(self, jobsize, jobprice)
348        self.JobSize = jobsize
349        self.JobPrice = jobprice
350   
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()
358        self.disablehistory = pykotatool.config.getDisableHistory()
359        if self.usecache :
360            self.tool.logdebug("Caching enabled.")
361            self.caches = { "USERS" : {}, "GROUPS" : {}, "PRINTERS" : {}, "USERPQUOTAS" : {}, "GROUPPQUOTAS" : {}, "JOBS" : {}, "LASTJOBS" : {} }
362       
363    def close(self) :   
364        """Must be overriden in children classes."""
365        raise RuntimeError, "BaseStorage.close() must be overriden !"
366       
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."""
383        if self.usecache and getattr(value, "Exists", 0) :
384            self.caches[cachetype][key] = value
385            self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key))
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       
437    def getParentPrinters(self, printer) :   
438        """Extracts parent printers information for a given printer from cache."""
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
449       
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       
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       
483def openConnection(pykotatool) :
484    """Returns a connection handle to the appropriate Quota Storage Database."""
485    backendinfo = pykotatool.config.getStorageBackend()
486    backend = backendinfo["storagebackend"]
487    try :
488        exec "from pykota.storages import %s as storagebackend" % backend.lower()
489    except ImportError :
490        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
491    else :   
492        host = backendinfo["storageserver"]
493        database = backendinfo["storagename"]
494        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
495        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
496        return storagebackend.Storage(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.