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

Revision 1502, 25.3 kB (checked in by jalet, 20 years ago)

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