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

Revision 1523, 26.3 kB (checked in by jalet, 20 years ago)

Now catches some exceptions earlier.
storage.py and ldapstorage.py : removed old comments

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