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

Revision 1520, 25.6 kB (checked in by jalet, 20 years ago)

Now stores the job's size in bytes in the database.
Preliminary work on payments storage : database schemas are OK now,
but no code to store payments yet.
Removed schema picture, not relevant anymore.

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