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

Revision 2057, 32.6 kB (checked in by jalet, 19 years ago)

Added the md5sum to the history

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