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

Revision 1249, 18.6 kB (checked in by jalet, 20 years ago)

Printer groups should be cached now, if caching is enabled.

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