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

Revision 1132, 15.4 kB (checked in by jalet, 21 years ago)

Logs cache store actions too

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