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

Revision 1274, 19.9 kB (checked in by jalet, 20 years ago)

Printing history added to CGI script.

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