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

Revision 1258, 19.5 kB (checked in by jalet, 20 years ago)

edpykota now supports adding printers to printer groups.

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