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

Revision 1711, 26.5 kB (checked in by jalet, 20 years ago)

Small fixes for incomplete entry intialization

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