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

Revision 2146, 33.0 kB (checked in by jerome, 19 years ago)

It seems that $Log$ is not implemented or doesn't work for some reason

  • 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.70  2005/02/16 00:29:33  jalet
25# Fixed the maxdenybanners directive.
26# Introduced the denyduplicates directive.
27# Fixed some database related glitches.
28#
29# Revision 1.69  2005/02/13 22:48:37  jalet
30# Added the md5sum to the history
31#
32# Revision 1.68  2005/02/13 22:02:29  jalet
33# Big database structure changes. Upgrade script is now included as well as
34# the new LDAP schema.
35# Introduction of the -o | --overcharge command line option to edpykota.
36# The output of repykota is more complete, but doesn't fit in 80 columns anymore.
37# Introduction of the new 'maxdenybanners' directive.
38#
39# Revision 1.67  2005/01/18 19:47:50  jalet
40# Big bug fix wrt the datelimit attribute
41#
42# Revision 1.66  2004/12/02 21:24:50  jalet
43# Integrated the patch by Wilson Roberto Afonso and Matt Hyclak to allow
44# edpykota to accept the -U | --used value command line option.
45#
46# Revision 1.65  2004/10/25 14:12:25  jalet
47# For URGENT legal reasons (Italy), a new "privacy" directive was added to pykota.conf
48# to hide print jobs' title, filename, and options.
49#
50# Revision 1.64  2004/10/08 20:19:18  jalet
51# Added ugly workaround for strange locale problem
52#
53# Revision 1.63  2004/10/07 21:14:28  jalet
54# Hopefully final fix for data encoding to and from the database
55#
56# Revision 1.62  2004/09/28 17:45:31  jalet
57# Added the --hardreset command line option to edpykota
58#
59# Revision 1.61  2004/09/24 21:19:48  jalet
60# Did a pass of PyChecker
61#
62# Revision 1.60  2004/09/24 20:21:50  jalet
63# Fixed pykotaAccountBalance object location during creation
64#
65# Revision 1.59  2004/09/10 21:32:52  jalet
66# Small fixes for incomplete entry intialization
67#
68# Revision 1.58  2004/09/02 10:09:30  jalet
69# Fixed bug in LDAP user deletion code which didn't correctly delete the user's
70# pykotaLastJob entries.
71#
72# Revision 1.57  2004/07/22 22:41:48  jalet
73# Hardware accounting for LPRng should be OK now. UNTESTED.
74#
75# Revision 1.56  2004/07/01 17:45:49  jalet
76# Added code to handle the description field for printers
77#
78# Revision 1.55  2004/06/05 22:18:04  jalet
79# Now catches some exceptions earlier.
80# storage.py and ldapstorage.py : removed old comments
81#
82# Revision 1.54  2004/06/05 22:03:49  jalet
83# Payments history is now stored in database
84#
85# Revision 1.53  2004/06/03 23:14:10  jalet
86# Now stores the job's size in bytes in the database.
87# Preliminary work on payments storage : database schemas are OK now,
88# but no code to store payments yet.
89# Removed schema picture, not relevant anymore.
90#
91# Revision 1.52  2004/05/26 14:49:57  jalet
92# First try at saving the job-originating-hostname in the database
93#
94# Revision 1.51  2004/03/24 15:15:24  jalet
95# Began integration of Henrik Janhagen's work on quota-then-balance
96# and balance-then-quota
97#
98# Revision 1.50  2004/03/09 08:05:27  jalet
99# Small fix : only keeps existing quota entries when searching parents
100#
101# Revision 1.49  2004/03/01 15:06:51  jalet
102# Pre and Post hooks should now work in the pykota filter too.
103# The pykota filter doesn't check the last user's quota anymore
104# when delayed hardware accounting is used : this will be checked
105# anyway the next time the last user will print
106#
107# Revision 1.48  2004/02/27 13:50:12  jalet
108# Hopefully the final fix for groups (users and printers)
109#
110# Revision 1.47  2004/02/27 09:30:33  jalet
111# datelimit wasn't reset when modifying soft and hard limits with the LDAP backend
112#
113# Revision 1.46  2004/02/26 14:18:07  jalet
114# Should fix the remaining bugs wrt printers groups and users groups.
115#
116# Revision 1.45  2004/02/26 10:40:40  jalet
117# Fixed nested printer groups accounting.
118#
119# Revision 1.44  2004/02/25 19:09:24  jalet
120# Fix for LDAP problem when job price was 0.
121#
122# Revision 1.43  2004/02/25 12:36:34  jalet
123# Avoids a database query even if caching was disabled.
124#
125# Revision 1.42  2004/02/23 22:53:21  jalet
126# Don't retrieve data when it's not needed, to avoid database queries
127#
128# Revision 1.41  2004/02/04 17:12:33  jalet
129# Removing a printer from a printers group should work now.
130#
131# Revision 1.40  2004/02/04 13:24:41  jalet
132# pkprinters can now remove printers from printers groups.
133#
134# Revision 1.39  2004/02/04 11:16:59  jalet
135# pkprinters command line tool added.
136#
137# Revision 1.38  2004/01/12 22:43:40  jalet
138# New formula to compute a job's price
139#
140# Revision 1.37  2004/01/12 14:35:01  jalet
141# Printing history added to CGI script.
142#
143# Revision 1.36  2004/01/10 09:44:02  jalet
144# Fixed potential accuracy problem if a user printed on several printers at
145# the very same time.
146#
147# Revision 1.35  2004/01/08 16:33:27  jalet
148# Additionnal check to not create a circular printers group.
149#
150# Revision 1.34  2004/01/08 16:24:49  jalet
151# edpykota now supports adding printers to printer groups.
152#
153# Revision 1.33  2004/01/08 14:10:32  jalet
154# Copyright year changed.
155#
156# Revision 1.32  2004/01/06 16:02:57  jalet
157# This time printer groups caching works.
158#
159# Revision 1.31  2004/01/06 15:51:24  jalet
160# Fixed caching of printer groups
161#
162# Revision 1.30  2004/01/06 14:24:59  jalet
163# Printer groups should be cached now, if caching is enabled.
164#
165# Revision 1.29  2003/12/27 16:49:25  uid67467
166# Should be ok now.
167#
168# Revision 1.28  2003/11/25 23:46:40  jalet
169# Don't try to verify if module name is valid, Python does this better than us.
170#
171# Revision 1.27  2003/11/23 19:01:36  jalet
172# Job price added to history
173#
174# Revision 1.26  2003/11/21 14:28:45  jalet
175# More complete job history.
176#
177# Revision 1.25  2003/10/08 21:12:27  jalet
178# Do not cache anymore entries which don't exist.
179#
180# Revision 1.24  2003/10/07 22:06:05  jalet
181# Preliminary code to disable job history
182#
183# Revision 1.23  2003/10/07 09:07:28  jalet
184# Character encoding added to please latest version of Python
185#
186# Revision 1.22  2003/10/06 13:12:27  jalet
187# More work on caching
188#
189# Revision 1.21  2003/10/03 09:02:20  jalet
190# Logs cache store actions too
191#
192# Revision 1.20  2003/10/02 20:23:18  jalet
193# Storage caching mechanism added.
194#
195# Revision 1.19  2003/07/16 21:53:07  jalet
196# Really big modifications wrt new configuration file's location and content.
197#
198# Revision 1.18  2003/07/07 08:33:18  jalet
199# Bug fix due to a typo in LDAP code
200#
201# Revision 1.17  2003/07/05 07:46:50  jalet
202# The previous bug fix was incomplete.
203#
204# Revision 1.16  2003/06/25 19:52:31  jalet
205# Should be ready for testing :-)
206#
207# Revision 1.15  2003/06/25 14:10:58  jalet
208# Exception raising for now.
209#
210# Revision 1.14  2003/06/25 14:10:01  jalet
211# Hey, it may work (edpykota --reset excepted) !
212#
213# Revision 1.13  2003/06/10 16:37:54  jalet
214# Deletion of the second user which is not needed anymore.
215# Added a debug configuration field in /etc/pykota.conf
216# All queries can now be sent to the logger in debug mode, this will
217# greatly help improve performance when time for this will come.
218#
219# Revision 1.12  2003/04/23 22:13:57  jalet
220# Preliminary support for LPRng added BUT STILL UNTESTED.
221#
222# Revision 1.11  2003/04/10 21:47:20  jalet
223# Job history added. Upgrade script neutralized for now !
224#
225# Revision 1.10  2003/03/29 13:45:27  jalet
226# GPL paragraphs were incorrectly (from memory) copied into the sources.
227# Two README files were added.
228# Upgrade script for PostgreSQL pre 1.01 schema was added.
229#
230# Revision 1.9  2003/02/17 22:55:01  jalet
231# More options can now be set per printer or globally :
232#
233#       admin
234#       adminmail
235#       gracedelay
236#       requester
237#
238# the printer option has priority when both are defined.
239#
240# Revision 1.8  2003/02/17 22:05:50  jalet
241# Storage backend now supports admin and user passwords (untested)
242#
243# Revision 1.7  2003/02/10 12:07:31  jalet
244# Now repykota should output the recorded total page number for each printer too.
245#
246# Revision 1.6  2003/02/09 13:05:43  jalet
247# Internationalization continues...
248#
249# Revision 1.5  2003/02/08 22:39:46  jalet
250# --reset command line option added
251#
252# Revision 1.4  2003/02/08 09:59:59  jalet
253# Added preliminary base class for all storages
254#
255# Revision 1.3  2003/02/05 22:10:29  jalet
256# Typos
257#
258# Revision 1.2  2003/02/05 22:02:22  jalet
259# __import__ statement didn't work as expected
260#
261# Revision 1.1  2003/02/05 21:28:17  jalet
262# Initial import into CVS
263#
264#
265#
266
267class PyKotaStorageError(Exception):
268    """An exception for Quota Storage related stuff."""
269    def __init__(self, message = ""):
270        self.message = message
271        Exception.__init__(self, message)
272    def __repr__(self):
273        return self.message
274    __str__ = __repr__
275       
276class StorageObject :
277    """Object present in the Quota Storage."""
278    def __init__(self, parent) :
279        "Initialize minimal data."""
280        self.parent = parent
281        self.ident = None
282        self.Exists = 0
283       
284class StorageUser(StorageObject) :       
285    """User class."""
286    def __init__(self, parent, name) :
287        StorageObject.__init__(self, parent)
288        self.Name = name
289        self.LimitBy = None
290        self.AccountBalance = None
291        self.LifeTimePaid = None
292        self.Email = None
293        self.OverCharge = 1.0
294        self.Payments = [] # TODO : maybe handle this smartly for SQL, for now just don't retrieve them
295       
296    def consumeAccountBalance(self, amount) :     
297        """Consumes an amount of money from the user's account balance."""
298        self.parent.decreaseUserAccountBalance(self, amount)
299        self.AccountBalance = float(self.AccountBalance or 0.0) - amount
300       
301    def setAccountBalance(self, balance, lifetimepaid) :   
302        """Sets the user's account balance in case he pays more money."""
303        diff = float(lifetimepaid or 0.0) - float(self.LifeTimePaid or 0.0)
304        self.parent.beginTransaction()
305        try :
306            self.parent.writeUserAccountBalance(self, balance, lifetimepaid)
307            self.parent.writeNewPayment(self, diff)
308        except PyKotaStorageError, msg :   
309            self.parent.rollbackTransaction()
310            raise PyKotaStorageError, msg
311        else :   
312            self.parent.commitTransaction()
313            self.AccountBalance = balance
314            self.LifeTimePaid = lifetimepaid
315       
316    def setLimitBy(self, limitby) :   
317        """Sets the user's limiting factor."""
318        try :
319            limitby = limitby.lower()
320        except AttributeError :   
321            limitby = "quota"
322        if limitby in ["quota", "balance", "quota-then-balance", "balance-then-quota"] :
323            self.parent.writeUserLimitBy(self, limitby)
324            self.LimitBy = limitby
325       
326    def setOverChargeFactor(self, factor) :   
327        """Sets the user's overcharging coefficient."""
328        self.parent.writeUserOverCharge(self, factor)
329        self.OverCharge = factor
330       
331    def delete(self) :   
332        """Deletes an user from the Quota Storage."""
333        self.parent.beginTransaction()
334        try :
335            self.parent.deleteUser(self)
336        except PyKotaStorageError, msg :   
337            self.parent.rollbackTransaction()
338            raise PyKotaStorageError, msg
339        else :   
340            self.parent.commitTransaction()
341       
342class StorageGroup(StorageObject) :       
343    """User class."""
344    def __init__(self, parent, name) :
345        StorageObject.__init__(self, parent)
346        self.Name = name
347        self.LimitBy = None
348        self.AccountBalance = None
349        self.LifeTimePaid = None
350       
351    def setLimitBy(self, limitby) :   
352        """Sets the user's limiting factor."""
353        try :
354            limitby = limitby.lower()
355        except AttributeError :   
356            limitby = "quota"
357        if limitby in ["quota", "balance"] :
358            self.parent.writeGroupLimitBy(self, limitby)
359            self.LimitBy = limitby
360       
361    def delete(self) :   
362        """Deletes a group from the Quota Storage."""
363        self.parent.beginTransaction()
364        try :
365            self.parent.deleteGroup(self)
366        except PyKotaStorageError, msg :   
367            self.parent.rollbackTransaction()
368            raise PyKotaStorageError, msg
369        else :   
370            self.parent.commitTransaction()
371       
372class StoragePrinter(StorageObject) :
373    """Printer class."""
374    def __init__(self, parent, name) :
375        StorageObject.__init__(self, parent)
376        self.Name = name
377        self.PricePerPage = None
378        self.PricePerJob = None
379        self.Description = None
380        self.Coefficients = None
381       
382    def __getattr__(self, name) :   
383        """Delays data retrieval until it's really needed."""
384        if name == "LastJob" : 
385            self.LastJob = self.parent.getPrinterLastJob(self)
386            return self.LastJob
387        else :
388            raise AttributeError, name
389           
390    def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None, jobmd5sum=None) :
391        """Adds a job to the printer's history."""
392        self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, clienthost, jobsizebytes, jobmd5sum)
393        # TODO : update LastJob object ? Probably not needed.
394       
395    def addPrinterToGroup(self, printer) :   
396        """Adds a printer to a printer group."""
397        if (printer not in self.parent.getParentPrinters(self)) and (printer.ident != self.ident) :
398            self.parent.writePrinterToGroup(self, printer)
399            # TODO : reset cached value for printer parents, or add new parent to cached value
400           
401    def delPrinterFromGroup(self, printer) :   
402        """Deletes a printer from a printer group."""
403        self.parent.removePrinterFromGroup(self, printer)
404        # TODO : reset cached value for printer parents, or add new parent to cached value
405       
406    def setPrices(self, priceperpage = None, priceperjob = None) :   
407        """Sets the printer's prices."""
408        if priceperpage is None :
409            priceperpage = self.PricePerPage or 0.0
410        else :   
411            self.PricePerPage = float(priceperpage)
412        if priceperjob is None :   
413            priceperjob = self.PricePerJob or 0.0
414        else :   
415            self.PricePerJob = float(priceperjob)
416        self.parent.writePrinterPrices(self)
417       
418    def setDescription(self, description = None) :   
419        """Sets the printer's prices."""
420        if description is None :
421            description = self.Description
422        else :   
423            self.Description = str(description)
424        self.parent.writePrinterDescription(self)
425       
426    def delete(self) :   
427        """Deletes a printer from the Quota Storage."""
428        self.parent.beginTransaction()
429        try :
430            self.parent.deletePrinter(self)
431        except PyKotaStorageError, msg :   
432            self.parent.rollbackTransaction()
433            raise PyKotaStorageError, msg
434        else :   
435            self.parent.commitTransaction()
436       
437class StorageUserPQuota(StorageObject) :
438    """User Print Quota class."""
439    def __init__(self, parent, user, printer) :
440        StorageObject.__init__(self, parent)
441        self.User = user
442        self.Printer = printer
443        self.PageCounter = None
444        self.LifePageCounter = None
445        self.SoftLimit = None
446        self.HardLimit = None
447        self.DateLimit = None
448        self.WarnCount = None
449       
450    def __getattr__(self, name) :   
451        """Delays data retrieval until it's really needed."""
452        if name == "ParentPrintersUserPQuota" : 
453            self.ParentPrintersUserPQuota = (self.User.Exists and self.Printer.Exists and self.parent.getParentPrintersUserPQuota(self)) or []
454            return self.ParentPrintersUserPQuota
455        else :
456            raise AttributeError, name
457       
458    def setDateLimit(self, datelimit) :   
459        """Sets the date limit for this quota."""
460        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
461        self.parent.writeUserPQuotaDateLimit(self, date)
462        self.DateLimit = date
463       
464    def setLimits(self, softlimit, hardlimit) :   
465        """Sets the soft and hard limit for this quota."""
466        self.parent.writeUserPQuotaLimits(self, softlimit, hardlimit)
467        self.SoftLimit = softlimit
468        self.HardLimit = hardlimit
469        self.DateLimit = None
470        self.WarnCount = 0
471       
472    def setUsage(self, used) :
473        """Sets the PageCounter and LifePageCounter to used, or if used is + or - prefixed, changes the values of {Life,}PageCounter by that amount."""
474        vused = int(used)
475        if used.startswith("+") or used.startswith("-") :
476            self.parent.beginTransaction()
477            try :
478                self.parent.increaseUserPQuotaPagesCounters(self, vused)
479                self.parent.writeUserPQuotaDateLimit(self, None)
480                self.parent.writeUserPQuotaWarnCount(self, 0)
481            except PyKotaStorageError, msg :   
482                self.parent.rollbackTransaction()
483                raise PyKotaStorageError, msg
484            else :
485                self.parent.commitTransaction()
486            self.PageCounter += vused
487            self.LifePageCounter += vused
488        else :
489            self.parent.writeUserPQuotaPagesCounters(self, vused, vused)
490            self.PageCounter = self.LifePageCounter = vused
491        self.DateLimit = None
492        self.WarnCount = 0
493
494    def incDenyBannerCounter(self) :
495        """Increment the deny banner counter for this user quota."""
496        self.parent.increaseUserPQuotaWarnCount(self)
497        self.WarnCount = (self.WarnCount or 0) + 1
498       
499    def resetDenyBannerCounter(self) :
500        """Resets the deny banner counter for this user quota."""
501        self.parent.writeUserPQuotaWarnCount(self, 0)
502        self.WarnCount = 0
503       
504    def reset(self) :   
505        """Resets page counter to 0."""
506        self.parent.writeUserPQuotaPagesCounters(self, 0, int(self.LifePageCounter or 0))
507        self.PageCounter = 0
508        self.DateLimit = None
509       
510    def hardreset(self) :   
511        """Resets actual and life time page counters to 0."""
512        self.parent.writeUserPQuotaPagesCounters(self, 0, 0)
513        self.PageCounter = self.LifePageCounter = 0
514        self.DateLimit = None
515       
516    def computeJobPrice(self, jobsize) :   
517        """Computes the job price as the sum of all parent printers' prices + current printer's ones."""
518        totalprice = 0.0   
519        if jobsize :
520            if self.User.OverCharge != 0.0 :    # optimization, but TODO : beware of rounding errors
521                for upq in [ self ] + self.ParentPrintersUserPQuota :
522                    price = (float(upq.Printer.PricePerPage or 0.0) * jobsize) + float(upq.Printer.PricePerJob or 0.0)
523                    totalprice += price
524        if self.User.OverCharge != 1.0 : # TODO : beware of rounding errors
525            overcharged = totalprice * self.User.OverCharge       
526            self.parent.tool.printInfo("Overcharging %s by a factor of %s ===> User %s will be charged for %s units." % (totalprice, self.User.OverCharge, self.User.Name, overcharged))
527            return overcharged
528        else :   
529            return totalprice
530           
531    def increasePagesUsage(self, jobsize) :
532        """Increase the value of used pages and money."""
533        jobprice = self.computeJobPrice(jobsize)
534        if jobsize :
535            self.parent.beginTransaction()
536            try :
537                if jobprice :
538                    self.User.consumeAccountBalance(jobprice)
539                for upq in [ self ] + self.ParentPrintersUserPQuota :
540                    self.parent.increaseUserPQuotaPagesCounters(upq, jobsize)
541                    upq.PageCounter = int(upq.PageCounter or 0) + jobsize
542                    upq.LifePageCounter = int(upq.LifePageCounter or 0) + jobsize
543            except PyKotaStorageError, msg :   
544                self.parent.rollbackTransaction()
545                raise PyKotaStorageError, msg
546            else :   
547                self.parent.commitTransaction()
548        return jobprice
549       
550class StorageGroupPQuota(StorageObject) :
551    """Group Print Quota class."""
552    def __init__(self, parent, group, printer) :
553        StorageObject.__init__(self, parent)
554        self.Group = group
555        self.Printer = printer
556        self.PageCounter = None
557        self.LifePageCounter = None
558        self.SoftLimit = None
559        self.HardLimit = None
560        self.DateLimit = None
561       
562    def __getattr__(self, name) :   
563        """Delays data retrieval until it's really needed."""
564        if name == "ParentPrintersGroupPQuota" : 
565            self.ParentPrintersGroupPQuota = (self.Group.Exists and self.Printer.Exists and self.parent.getParentPrintersGroupPQuota(self)) or []
566            return self.ParentPrintersGroupPQuota
567        else :
568            raise AttributeError, name
569       
570    def reset(self) :   
571        """Resets page counter to 0."""
572        self.parent.beginTransaction()
573        try :
574            for user in self.parent.getGroupMembers(self.Group) :
575                uq = self.parent.getUserPQuota(user, self.Printer)
576                uq.reset()
577            self.parent.writeGroupPQuotaDateLimit(self, None)
578        except PyKotaStorageError, msg :   
579            self.parent.rollbackTransaction()
580            raise PyKotaStorageError, msg
581        else :   
582            self.parent.commitTransaction()
583        self.PageCounter = 0
584        self.DateLimit = None
585       
586    def hardreset(self) :   
587        """Resets actual and life time page counters to 0."""
588        self.parent.beginTransaction()
589        try :
590            for user in self.parent.getGroupMembers(self.Group) :
591                uq = self.parent.getUserPQuota(user, self.Printer)
592                uq.hardreset()
593            self.parent.writeGroupPQuotaDateLimit(self, None)
594        except PyKotaStorageError, msg :   
595            self.parent.rollbackTransaction()
596            raise PyKotaStorageError, msg
597        else :   
598            self.parent.commitTransaction()
599        self.PageCounter = self.LifePageCounter = 0
600        self.DateLimit = None
601       
602    def setDateLimit(self, datelimit) :   
603        """Sets the date limit for this quota."""
604        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
605        self.parent.writeGroupPQuotaDateLimit(self, date)
606        self.DateLimit = date
607       
608    def setLimits(self, softlimit, hardlimit) :   
609        """Sets the soft and hard limit for this quota."""
610        self.parent.writeGroupPQuotaLimits(self, softlimit, hardlimit)
611        self.SoftLimit = softlimit
612        self.HardLimit = hardlimit
613        self.DateLimit = None
614       
615class StorageJob(StorageObject) :
616    """Printer's Job class."""
617    def __init__(self, parent) :
618        StorageObject.__init__(self, parent)
619        self.UserName = None
620        self.PrinterName = None
621        self.JobId = None
622        self.PrinterPageCounter = None
623        self.JobSizeBytes = None
624        self.JobSize = None
625        self.JobAction = None
626        self.JobDate = None
627        self.JobPrice = None
628        self.JobFileName = None
629        self.JobTitle = None
630        self.JobCopies = None
631        self.JobOptions = None
632        self.JobHostName = None
633        self.JobMD5Sum = None
634        self.JobPages = None
635        self.JobBillingCode = None
636       
637    def __getattr__(self, name) :   
638        """Delays data retrieval until it's really needed."""
639        if name == "User" : 
640            self.User = self.parent.getUser(self.UserName)
641            return self.User
642        elif name == "Printer" :   
643            self.Printer = self.parent.getPrinter(self.PrinterName)
644            return self.Printer
645        else :
646            raise AttributeError, name
647       
648class StorageLastJob(StorageJob) :
649    """Printer's Last Job class."""
650    def __init__(self, parent, printer) :
651        StorageJob.__init__(self, parent)
652        self.PrinterName = printer.Name # not needed
653        self.Printer = printer
654       
655class BaseStorage :
656    def __init__(self, pykotatool) :
657        """Opens the storage connection."""
658        self.closed = 1
659        self.tool = pykotatool
660        self.usecache = pykotatool.config.getCaching()
661        self.disablehistory = pykotatool.config.getDisableHistory()
662        self.privacy = pykotatool.config.getPrivacy()
663        if self.privacy :
664            pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.")
665        if self.usecache :
666            self.tool.logdebug("Caching enabled.")
667            self.caches = { "USERS" : {}, "GROUPS" : {}, "PRINTERS" : {}, "USERPQUOTAS" : {}, "GROUPPQUOTAS" : {}, "JOBS" : {}, "LASTJOBS" : {} }
668       
669    def close(self) :   
670        """Must be overriden in children classes."""
671        raise RuntimeError, "BaseStorage.close() must be overriden !"
672       
673    def __del__(self) :       
674        """Ensures that the database connection is closed."""
675        self.close()
676       
677    def getFromCache(self, cachetype, key) :
678        """Tries to extract something from the cache."""
679        if self.usecache :
680            entry = self.caches[cachetype].get(key)
681            if entry is not None :
682                self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key))
683            else :   
684                self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key))
685            return entry   
686           
687    def cacheEntry(self, cachetype, key, value) :       
688        """Puts an entry in the cache."""
689        if self.usecache and getattr(value, "Exists", 0) :
690            self.caches[cachetype][key] = value
691            self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key))
692           
693    def getUser(self, username) :       
694        """Returns the user from cache."""
695        user = self.getFromCache("USERS", username)
696        if user is None :
697            user = self.getUserFromBackend(username)
698            self.cacheEntry("USERS", username, user)
699        return user   
700       
701    def getGroup(self, groupname) :       
702        """Returns the group from cache."""
703        group = self.getFromCache("GROUPS", groupname)
704        if group is None :
705            group = self.getGroupFromBackend(groupname)
706            self.cacheEntry("GROUPS", groupname, group)
707        return group   
708       
709    def getPrinter(self, printername) :       
710        """Returns the printer from cache."""
711        printer = self.getFromCache("PRINTERS", printername)
712        if printer is None :
713            printer = self.getPrinterFromBackend(printername)
714            self.cacheEntry("PRINTERS", printername, printer)
715        return printer   
716       
717    def getUserPQuota(self, user, printer) :       
718        """Returns the user quota information from cache."""
719        useratprinter = "%s@%s" % (user.Name, printer.Name)
720        upquota = self.getFromCache("USERPQUOTAS", useratprinter)
721        if upquota is None :
722            upquota = self.getUserPQuotaFromBackend(user, printer)
723            self.cacheEntry("USERPQUOTAS", useratprinter, upquota)
724        return upquota   
725       
726    def getGroupPQuota(self, group, printer) :       
727        """Returns the group quota information from cache."""
728        groupatprinter = "%s@%s" % (group.Name, printer.Name)
729        gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter)
730        if gpquota is None :
731            gpquota = self.getGroupPQuotaFromBackend(group, printer)
732            self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota)
733        return gpquota   
734       
735    def getPrinterLastJob(self, printer) :       
736        """Extracts last job information for a given printer from cache."""
737        lastjob = self.getFromCache("LASTJOBS", printer.Name)
738        if lastjob is None :
739            lastjob = self.getPrinterLastJobFromBackend(printer)
740            self.cacheEntry("LASTJOBS", printer.Name, lastjob)
741        return lastjob   
742       
743    def getParentPrinters(self, printer) :   
744        """Extracts parent printers information for a given printer from cache."""
745        if self.usecache :
746            if not hasattr(printer, "Parents") :
747                self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name)
748                printer.Parents = self.getParentPrintersFromBackend(printer)
749                self.tool.logdebug("Cache store (%s->Parents)" % printer.Name)
750            else :
751                self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name)
752        else :       
753            printer.Parents = self.getParentPrintersFromBackend(printer)
754        for parent in printer.Parents[:] :   
755            printer.Parents.extend(self.getParentPrinters(parent))
756        uniquedic = {}   
757        for parent in printer.Parents :
758            uniquedic[parent.Name] = parent
759        printer.Parents = uniquedic.values()   
760        return printer.Parents
761       
762    def getGroupMembers(self, group) :       
763        """Returns the group's members list from in-group cache."""
764        if self.usecache :
765            if not hasattr(group, "Members") :
766                self.tool.logdebug("Cache miss (%s->Members)" % group.Name)
767                group.Members = self.getGroupMembersFromBackend(group)
768                self.tool.logdebug("Cache store (%s->Members)" % group.Name)
769            else :
770                self.tool.logdebug("Cache hit (%s->Members)" % group.Name)
771        else :       
772            group.Members = self.getGroupMembersFromBackend(group)
773        return group.Members   
774       
775    def getUserGroups(self, user) :       
776        """Returns the user's groups list from in-user cache."""
777        if self.usecache :
778            if not hasattr(user, "Groups") :
779                self.tool.logdebug("Cache miss (%s->Groups)" % user.Name)
780                user.Groups = self.getUserGroupsFromBackend(user)
781                self.tool.logdebug("Cache store (%s->Groups)" % user.Name)
782            else :
783                self.tool.logdebug("Cache hit (%s->Groups)" % user.Name)
784        else :       
785            user.Groups = self.getUserGroupsFromBackend(user)
786        return user.Groups   
787       
788    def getParentPrintersUserPQuota(self, userpquota) :     
789        """Returns all user print quota on the printer and all its parents recursively."""
790        upquotas = [ ]
791        for printer in self.getParentPrinters(userpquota.Printer) :
792            upq = self.getUserPQuota(userpquota.User, printer)
793            if upq.Exists :
794                upquotas.append(upq)
795        return upquotas       
796       
797    def getParentPrintersGroupPQuota(self, grouppquota) :     
798        """Returns all group print quota on the printer and all its parents recursively."""
799        gpquotas = [ ]
800        for printer in self.getParentPrinters(grouppquota.Printer) :
801            gpq = self.getGroupPQuota(grouppquota.Group, printer)
802            if gpq.Exists :
803                gpquotas.append(gpq)
804        return gpquotas       
805       
806    def databaseToUserCharset(self, text) :
807        """Converts from database format (UTF-8) to user's charset."""
808        if text is not None :
809            try :
810                return unicode(text, "UTF-8").encode(self.tool.getCharset()) 
811            except UnicodeError :   
812                try :
813                    # Incorrect locale settings ?
814                    return unicode(text, "UTF-8").encode("ISO-8859-15") 
815                except UnicodeError :   
816                    pass
817        return text
818       
819    def userCharsetToDatabase(self, text) :
820        """Converts from user's charset to database format (UTF-8)."""
821        if text is not None :
822            try :
823                return unicode(text, self.tool.getCharset()).encode("UTF-8") 
824            except UnicodeError :   
825                try :
826                    # Incorrect locale settings ?
827                    return unicode(text, "ISO-8859-15").encode("UTF-8") 
828                except UnicodeError :   
829                    pass
830        return text
831       
832def openConnection(pykotatool) :
833    """Returns a connection handle to the appropriate Quota Storage Database."""
834    backendinfo = pykotatool.config.getStorageBackend()
835    backend = backendinfo["storagebackend"]
836    try :
837        exec "from pykota.storages import %s as storagebackend" % backend.lower()
838    except ImportError :
839        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
840    else :   
841        host = backendinfo["storageserver"]
842        database = backendinfo["storagename"]
843        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
844        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
845        return storagebackend.Storage(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.