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

Revision 1200, 17.3 kB (checked in by jalet, 20 years ago)

More complete job history.

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