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

Revision 1144, 16.8 kB (checked in by jalet, 21 years ago)

Character encoding added to please latest version of Python

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