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

Revision 1359, 22.8 kB (checked in by jalet, 20 years ago)

Avoids a database query even if caching was disabled.

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