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

Revision 1333, 21.3 kB (checked in by jalet, 20 years ago)

Removing a printer from a printers group should work now.

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