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

Revision 1151, 17.1 kB (checked in by jalet, 21 years ago)

Do not cache anymore entries which don't exist.

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