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

Revision 1330, 20.9 kB (checked in by jalet, 20 years ago)

pkprinters command line tool added.

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