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

Revision 1582, 26.7 kB (checked in by jalet, 20 years ago)

Added code to handle the description field for printers

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