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

Revision 1363, 22.9 kB (checked in by jalet, 20 years ago)

Fix for LDAP problem when job price was 0.

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