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

Revision 1364, 23.4 kB (checked in by jalet, 20 years ago)

Fixed nested printer groups accounting.

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