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

Revision 1755, 26.9 kB (checked in by jalet, 20 years ago)

Added the --hardreset command line option to edpykota

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