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

Revision 1522, 26.2 kB (checked in by jalet, 20 years ago)

Payments history is now stored in database

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