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

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

Fixed pykotaAccountBalance object location during creation

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