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

Revision 1269, 19.7 kB (checked in by jalet, 20 years ago)

Fixed potential accuracy problem if a user printed on several printers at
the very same time.

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