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

Revision 1358, 22.7 kB (checked in by jalet, 21 years ago)

Don't retrieve data when it's not needed, to avoid database queries

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