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

Revision 1240, 18.1 kB (checked in by uid67467, 20 years ago)

Should be ok now.

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