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

Revision 1285, 20.4 kB (checked in by jalet, 20 years ago)

New formula to compute a job's price

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