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

Revision 1203, 17.7 kB (checked in by jalet, 20 years ago)

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