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

Revision 1743, 26.6 kB (checked in by jalet, 20 years ago)

Did a pass of PyChecker?

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