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

Revision 1692, 26.4 kB (checked in by jalet, 20 years ago)

Fixed bug in LDAP user deletion code which didn't correctly delete the user's
pykotaLastJob entries.

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