root / pykota / trunk / pykota / storages / ldapstorage.py @ 1269

Revision 1269, 43.7 kB (checked in by jalet, 20 years ago)

Fixed potential accuracy problem if a user printed on several printers at
the very same time.

  • 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.47  2004/01/10 09:44:02  jalet
25# Fixed potential accuracy problem if a user printed on several printers at
26# the very same time.
27#
28# Revision 1.46  2004/01/08 16:33:27  jalet
29# Additionnal check to not create a circular printers group.
30#
31# Revision 1.45  2004/01/08 16:24:49  jalet
32# edpykota now supports adding printers to printer groups.
33#
34# Revision 1.44  2004/01/08 14:10:33  jalet
35# Copyright year changed.
36#
37# Revision 1.43  2004/01/06 14:24:59  jalet
38# Printer groups should be cached now, if caching is enabled.
39#
40# Revision 1.42  2003/12/29 14:12:48  uid67467
41# Tries to workaround possible integrity violations when retrieving printer groups
42#
43# Revision 1.41  2003/12/27 16:49:25  uid67467
44# Should be ok now.
45#
46# Revision 1.40  2003/11/29 22:02:14  jalet
47# Don't try to retrieve the user print quota information if current printer
48# doesn't exist.
49#
50# Revision 1.39  2003/11/26 23:35:32  jalet
51# Added a bit of code to support the setting of the user's email address
52# which was ignored during writes for now.
53#
54# Revision 1.38  2003/11/24 09:54:06  jalet
55# Small fix for LDAP when pykotaOptions attribute wasn't present.
56#
57# Revision 1.37  2003/11/23 19:01:37  jalet
58# Job price added to history
59#
60# Revision 1.36  2003/11/21 14:28:46  jalet
61# More complete job history.
62#
63# Revision 1.35  2003/11/12 13:06:37  jalet
64# Bug fix wrt no user/group name command line argument to edpykota
65#
66# Revision 1.34  2003/10/24 08:37:55  jalet
67# More complete messages in case of LDAP failure.
68# LDAP database connection is now unbound on exit too.
69#
70# Revision 1.33  2003/10/08 07:01:20  jalet
71# Job history can be disabled.
72# Some typos in README.
73# More messages in setup script.
74#
75# Revision 1.32  2003/10/07 14:23:25  jalet
76# More work on cache
77#
78# Revision 1.31  2003/10/07 09:07:30  jalet
79# Character encoding added to please latest version of Python
80#
81# Revision 1.30  2003/10/06 14:42:36  jalet
82# LDAP group access will be slower when cache is disabled, but at least code
83# is consistent with the rest of the caching mechanis, but at least code
84# is consistent with the rest of the caching mechanism
85#
86# Revision 1.29  2003/10/06 13:12:28  jalet
87# More work on caching
88#
89# Revision 1.28  2003/10/03 12:27:02  jalet
90# Several optimizations, especially with LDAP backend
91#
92# Revision 1.27  2003/10/03 08:57:55  jalet
93# Caching mechanism now caches all that's cacheable.
94#
95# Revision 1.26  2003/10/02 20:23:18  jalet
96# Storage caching mechanism added.
97#
98# Revision 1.25  2003/08/20 15:56:24  jalet
99# Better user and group deletion
100#
101# Revision 1.24  2003/07/29 20:55:17  jalet
102# 1.14 is out !
103#
104# Revision 1.23  2003/07/29 19:52:32  jalet
105# Forgot to read the email field from LDAP
106#
107# Revision 1.22  2003/07/29 09:54:03  jalet
108# Added configurable LDAP mail attribute support
109#
110# Revision 1.21  2003/07/28 09:11:12  jalet
111# PyKota now tries to add its attributes intelligently in existing LDAP
112# directories.
113#
114# Revision 1.20  2003/07/25 10:41:30  jalet
115# Better documentation.
116# pykotme now displays the current user's account balance.
117# Some test changed in ldap module.
118#
119# Revision 1.19  2003/07/14 14:18:16  jalet
120# Wrong documentation strings
121#
122# Revision 1.18  2003/07/11 14:23:13  jalet
123# When adding an user only adds one object containing both the user and
124# its account balance instead of two objects.
125#
126# Revision 1.17  2003/07/07 12:51:07  jalet
127# Small fix
128#
129# Revision 1.16  2003/07/07 12:11:13  jalet
130# Small fix
131#
132# Revision 1.15  2003/07/07 11:49:24  jalet
133# Lots of small fixes with the help of PyChecker
134#
135# Revision 1.14  2003/07/07 08:33:18  jalet
136# Bug fix due to a typo in LDAP code
137#
138# Revision 1.13  2003/07/05 07:46:50  jalet
139# The previous bug fix was incomplete.
140#
141# Revision 1.12  2003/06/30 13:54:21  jalet
142# Sorts by user / group name
143#
144# Revision 1.11  2003/06/25 14:10:01  jalet
145# Hey, it may work (edpykota --reset excepted) !
146#
147# Revision 1.10  2003/06/16 21:55:15  jalet
148# More work on LDAP, again. Problem detected.
149#
150# Revision 1.9  2003/06/16 11:59:09  jalet
151# More work on LDAP
152#
153# Revision 1.8  2003/06/15 22:26:52  jalet
154# More work on LDAP
155#
156# Revision 1.7  2003/06/14 22:44:21  jalet
157# More work on LDAP storage backend.
158#
159# Revision 1.6  2003/06/13 19:07:57  jalet
160# Two big bugs fixed, time to release something ;-)
161#
162# Revision 1.5  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.4  2003/06/10 10:45:32  jalet
169# Not implemented methods now raise an exception when called.
170#
171# Revision 1.3  2003/06/06 20:49:15  jalet
172# Very latest schema. UNTESTED.
173#
174# Revision 1.2  2003/06/06 14:21:08  jalet
175# New LDAP schema.
176# Small bug fixes.
177#
178# Revision 1.1  2003/06/05 11:19:13  jalet
179# More good work on LDAP storage.
180#
181#
182#
183
184#
185# My IANA assigned number, for
186# "Conseil Internet & Logiciels Libres, J�me Alet"
187# is 16868. Use this as a base to create the LDAP schema.
188#
189
190import types
191import time
192import md5
193
194from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
195
196try :
197    import ldap
198    from ldap import modlist
199except ImportError :   
200    import sys
201    # TODO : to translate or not to translate ?
202    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
203   
204class Storage(BaseStorage) :
205    def __init__(self, pykotatool, host, dbname, user, passwd) :
206        """Opens the LDAP connection."""
207        # raise PyKotaStorageError, "Sorry, the LDAP backend for PyKota is not yet implemented !"
208        BaseStorage.__init__(self, pykotatool)
209        self.info = pykotatool.config.getLDAPInfo()
210        try :
211            self.database = ldap.initialize(host) 
212            self.database.simple_bind_s(user, passwd)
213            self.basedn = dbname
214        except ldap.SERVER_DOWN :   
215            raise PyKotaStorageError, "LDAP backend for PyKota seems to be down !" # TODO : translate
216        except ldap.LDAPError :   
217            raise PyKotaStorageError, "Unable to connect to LDAP server %s as %s." % (host, user) # TODO : translate
218        else :   
219            self.closed = 0
220            self.tool.logdebug("Database opened (host=%s, dbname=%s, user=%s)" % (host, dbname, user))
221           
222    def close(self) :   
223        """Closes the database connection."""
224        if not self.closed :
225            self.database.unbind_s()
226            self.closed = 1
227            self.tool.logdebug("Database closed.")
228       
229    def genUUID(self) :   
230        """Generates an unique identifier.
231       
232           TODO : this one is not unique accross several print servers, but should be sufficient for testing.
233        """
234        return md5.md5("%s" % time.time()).hexdigest()
235       
236    def normalizeFields(self, fields) :   
237        """Ensure all items are lists."""
238        for (k, v) in fields.items() :
239            if type(v) not in (types.TupleType, types.ListType) :
240                if not v :
241                    del fields[k]
242                else :   
243                    fields[k] = [ v ]
244        return fields       
245       
246    def beginTransaction(self) :   
247        """Starts a transaction."""
248        self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !")
249       
250    def commitTransaction(self) :   
251        """Commits a transaction."""
252        self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !")
253       
254    def rollbackTransaction(self) :     
255        """Rollbacks a transaction."""
256        self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !")
257       
258    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE) :
259        """Does an LDAP search query."""
260        try :
261            base = base or self.basedn
262            self.tool.logdebug("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields))
263            result = self.database.search_s(base or self.basedn, scope, key, fields)
264        except ldap.LDAPError, msg :   
265            raise PyKotaStorageError, (_("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)) + " : %s" % str(msg)
266        else :     
267            self.tool.logdebug("QUERY : Result : %s" % result)
268            return result
269           
270    def doAdd(self, dn, fields) :
271        """Adds an entry in the LDAP directory."""
272        fields = self.normalizeFields(fields)
273        try :
274            self.tool.logdebug("QUERY : ADD(%s, %s)" % (dn, str(fields)))
275            self.database.add_s(dn, modlist.addModlist(fields))
276        except ldap.LDAPError, msg :
277            raise PyKotaStorageError, (_("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))) + " : %s" % str(msg)
278        else :
279            return dn
280           
281    def doDelete(self, dn) :
282        """Deletes an entry from the LDAP directory."""
283        try :
284            self.tool.logdebug("QUERY : Delete(%s)" % dn)
285            self.database.delete_s(dn)
286        except ldap.LDAPError, msg :
287            raise PyKotaStorageError, (_("Problem deleting LDAP entry (%s)") % dn) + " : %s" % str(msg)
288           
289    def doModify(self, dn, fields, ignoreold=1) :
290        """Modifies an entry in the LDAP directory."""
291        try :
292            oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)
293            for (k, v) in fields.items() :
294                if type(v) == type({}) :
295                    try :
296                        oldvalue = v["convert"](oldentry[0][1].get(k, [0])[0])
297                    except ValueError :   
298                        self.tool.logdebug("Error converting %s with %s(%s)" % (oldentry[0][1].get(k), k, v))
299                        oldvalue = 0
300                    if v["operator"] == '+' :
301                        newvalue = oldvalue + v["value"]
302                    else :   
303                        newvalue = oldvalue - v["value"]
304                    fields[k] = str(newvalue)
305            fields = self.normalizeFields(fields)
306            self.tool.logdebug("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry[0][1], fields))
307            self.database.modify_s(dn, modlist.modifyModlist(oldentry[0][1], fields, ignore_oldexistent=ignoreold))
308        except ldap.LDAPError, msg :
309            raise PyKotaStorageError, (_("Problem modifying LDAP entry (%s, %s)") % (dn, fields)) + " : %s" % str(msg)
310        else :
311            return dn
312           
313    def getAllUsersNames(self) :   
314        """Extracts all user names."""
315        usernames = []
316        result = self.doSearch("objectClass=pykotaAccount", ["pykotaUserName"], base=self.info["userbase"])
317        if result :
318            usernames = [record[1]["pykotaUserName"][0] for record in result]
319        return usernames
320       
321    def getAllGroupsNames(self) :   
322        """Extracts all group names."""
323        groupnames = []
324        result = self.doSearch("objectClass=pykotaGroup", ["pykotaGroupName"], base=self.info["groupbase"])
325        if result :
326            groupnames = [record[1]["pykotaGroupName"][0] for record in result]
327        return groupnames
328       
329    def getUserFromBackend(self, username) :   
330        """Extracts user information given its name."""
331        user = StorageUser(self, username)
332        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaLimitBy", self.info["usermail"]], base=self.info["userbase"])
333        if result :
334            fields = result[0][1]
335            user.ident = result[0][0]
336            user.Email = fields.get(self.info["usermail"])
337            if user.Email is not None :
338                user.Email = user.Email[0]
339            user.LimitBy = fields.get("pykotaLimitBy")
340            if user.LimitBy is not None :
341                user.LimitBy = user.LimitBy[0]
342            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid"], base=self.info["balancebase"])
343            if result :
344                fields = result[0][1]
345                user.idbalance = result[0][0]
346                user.AccountBalance = fields.get("pykotaBalance")
347                if user.AccountBalance is not None :
348                    if user.AccountBalance[0].upper() == "NONE" :
349                        user.AccountBalance = None
350                    else :   
351                        user.AccountBalance = float(user.AccountBalance[0])
352                user.AccountBalance = user.AccountBalance or 0.0       
353                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
354                if user.LifeTimePaid is not None :
355                    if user.LifeTimePaid[0].upper() == "NONE" :
356                        user.LifeTimePaid = None
357                    else :   
358                        user.LifeTimePaid = float(user.LifeTimePaid[0])
359                user.LifeTimePaid = user.LifeTimePaid or 0.0       
360            user.Exists = 1
361        return user
362       
363    def getGroupFromBackend(self, groupname) :   
364        """Extracts group information given its name."""
365        group = StorageGroup(self, groupname)
366        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaLimitBy"], base=self.info["groupbase"])
367        if result :
368            fields = result[0][1]
369            group.ident = result[0][0]
370            group.LimitBy = fields.get("pykotaLimitBy")
371            if group.LimitBy is not None :
372                group.LimitBy = group.LimitBy[0]
373            group.AccountBalance = 0.0
374            group.LifeTimePaid = 0.0
375            for member in self.getGroupMembers(group) :
376                if member.Exists :
377                    group.AccountBalance += member.AccountBalance
378                    group.LifeTimePaid += member.LifeTimePaid
379            group.Exists = 1
380        return group
381       
382    def getPrinterFromBackend(self, printername) :       
383        """Extracts printer information given its name."""
384        printer = StoragePrinter(self, printername)
385        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember"], base=self.info["printerbase"])
386        if result :
387            fields = result[0][1]
388            printer.ident = result[0][0]
389            printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
390            printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
391            printer.LastJob = self.getPrinterLastJob(printer)
392            printer.uniqueMember = fields.get("uniqueMember", [])
393            printer.Exists = 1
394        return printer   
395       
396    def getUserPQuotaFromBackend(self, user, printer) :       
397        """Extracts a user print quota."""
398        userpquota = StorageUserPQuota(self, user, printer)
399        if printer.Exists and user.Exists :
400            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
401            if result :
402                fields = result[0][1]
403                userpquota.ident = result[0][0]
404                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
405                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
406                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
407                if userpquota.SoftLimit is not None :
408                    if userpquota.SoftLimit[0].upper() == "NONE" :
409                        userpquota.SoftLimit = None
410                    else :   
411                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
412                userpquota.HardLimit = fields.get("pykotaHardLimit")
413                if userpquota.HardLimit is not None :
414                    if userpquota.HardLimit[0].upper() == "NONE" :
415                        userpquota.HardLimit = None
416                    elif userpquota.HardLimit is not None :   
417                        userpquota.HardLimit = int(userpquota.HardLimit[0])
418                userpquota.DateLimit = fields.get("pykotaDateLimit")
419                if userpquota.DateLimit is not None :
420                    if userpquota.DateLimit[0].upper() == "NONE" : 
421                        userpquota.DateLimit = None
422                    else :   
423                        userpquota.DateLimit = userpquota.DateLimit[0]
424                userpquota.Exists = 1
425        return userpquota
426       
427    def getGroupPQuotaFromBackend(self, group, printer) :       
428        """Extracts a group print quota."""
429        grouppquota = StorageGroupPQuota(self, group, printer)
430        if group.Exists :
431            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["groupquotabase"])
432            if result :
433                fields = result[0][1]
434                grouppquota.ident = result[0][0]
435                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
436                if grouppquota.SoftLimit is not None :
437                    if grouppquota.SoftLimit[0].upper() == "NONE" :
438                        grouppquota.SoftLimit = None
439                    else :   
440                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
441                grouppquota.HardLimit = fields.get("pykotaHardLimit")
442                if grouppquota.HardLimit is not None :
443                    if grouppquota.HardLimit[0].upper() == "NONE" :
444                        grouppquota.HardLimit = None
445                    else :   
446                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
447                grouppquota.DateLimit = fields.get("pykotaDateLimit")
448                if grouppquota.DateLimit is not None :
449                    if grouppquota.DateLimit[0].upper() == "NONE" : 
450                        grouppquota.DateLimit = None
451                    else :   
452                        grouppquota.DateLimit = grouppquota.DateLimit[0]
453                grouppquota.PageCounter = 0
454                grouppquota.LifePageCounter = 0
455                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in self.getGroupMembers(group)])
456                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=self.info["userquotabase"])
457                if result :
458                    for userpquota in result :   
459                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter")[0] or 0)
460                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter")[0] or 0)
461                grouppquota.Exists = 1
462        return grouppquota
463       
464    def getPrinterLastJobFromBackend(self, printer) :       
465        """Extracts a printer's last job information."""
466        lastjob = StorageLastJob(self, printer)
467        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
468        if result :
469            lastjob.lastjobident = result[0][0]
470            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
471            result = self.doSearch("objectClass=pykotaJob", ["pykotaUserName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE)
472            if result :
473                fields = result[0][1]
474                lastjob.ident = result[0][0]
475                lastjob.JobId = fields.get("pykotaJobId")[0]
476                lastjob.User = self.getUser(fields.get("pykotaUserName")[0])
477                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter")[0] or 0)
478                lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
479                lastjob.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
480                lastjob.JobAction = fields.get("pykotaAction")[0]
481                lastjob.JobFileName = fields.get("pykotaFileName", [""])[0]
482                lastjob.JobTitle = fields.get("pykotaTitle", [""])[0]
483                lastjob.JobCopies = int(fields.get("pykotaCopies", [0])[0])
484                lastjob.JobOptions = fields.get("pykotaOptions", [""])[0]
485                date = fields.get("createTimestamp")[0]
486                year = int(date[:4])
487                month = int(date[4:6])
488                day = int(date[6:8])
489                hour = int(date[8:10])
490                minute = int(date[10:12])
491                second = int(date[12:14])
492                lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
493                lastjob.Exists = 1
494        return lastjob
495       
496    def getGroupMembersFromBackend(self, group) :       
497        """Returns the group's members list."""
498        groupmembers = []
499        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"])
500        if result :
501            for username in result[0][1].get(self.info["groupmembers"], []) :
502                groupmembers.append(self.getUser(username))
503        return groupmembers       
504       
505    def getUserGroupsFromBackend(self, user) :       
506        """Returns the user's groups list."""
507        groups = []
508        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"], "pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
509        if result :
510            for (groupid, fields) in result :
511                groupname = (fields.get("pykotaGroupName", [None]) or fields.get(self.info["grouprdn"], [None]))[0]
512                group = self.getFromCache("GROUPS", groupname)
513                if group is None :
514                    group = StorageGroup(self, groupname)
515                    group.ident = groupid
516                    group.LimitBy = fields.get("pykotaLimitBy")
517                    if group.LimitBy is not None :
518                        group.LimitBy = group.LimitBy[0]
519                    group.AccountBalance = 0.0
520                    group.LifeTimePaid = 0.0
521                    for member in self.getGroupMembers(group) :
522                        if member.Exists :
523                            group.AccountBalance += member.AccountBalance
524                            group.LifeTimePaid += member.LifeTimePaid
525                    group.Exists = 1
526                    self.cacheEntry("GROUPS", group.Name, group)
527                groups.append(group)
528        return groups       
529       
530    def getParentPrintersFromBackend(self, printer) :   
531        """Get all the printer groups this printer is a member of."""
532        pgroups = []
533        result = self.doSearch("(&(objectClass=pykotaPrinter)(uniqueMember=%s))" % printer.ident, ["pykotaPrinterName"], base=self.info["printerbase"])
534        if result :
535            for (printerid, fields) in result :
536                if printerid != printer.ident : # In case of integrity violation.
537                    parentprinter = self.getPrinter(fields.get("pykotaPrinterName")[0])
538                    if parentprinter.Exists :
539                        pgroups.append(parentprinter)
540        return pgroups
541       
542    def getMatchingPrinters(self, printerpattern) :
543        """Returns the list of all printers for which name matches a certain pattern."""
544        printers = []
545        # see comment at the same place in pgstorage.py
546        result = self.doSearch("(&(objectClass=pykotaPrinter)(|%s))" % "".join(["(pykotaPrinterName=%s)" % pname for pname in printerpattern.split(",")]), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember"], base=self.info["printerbase"])
547        if result :
548            for (printerid, fields) in result :
549                printername = fields["pykotaPrinterName"][0]
550                printer = StoragePrinter(self, printername)
551                printer.ident = printerid
552                printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
553                printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
554                printer.uniqueMember = fields.get("uniqueMember", [])
555                printer.LastJob = self.getPrinterLastJob(printer)
556                printer.Exists = 1
557                printers.append(printer)
558                self.cacheEntry("PRINTERS", printer.Name, printer)
559        return printers       
560       
561    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
562        """Returns the list of users who uses a given printer, along with their quotas."""
563        usersandquotas = []
564        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaUserName=%s)" % uname for uname in names])), ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
565        if result :
566            for (userquotaid, fields) in result :
567                user = self.getUser(fields.get("pykotaUserName")[0])
568                userpquota = StorageUserPQuota(self, user, printer)
569                userpquota.ident = userquotaid
570                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
571                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
572                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
573                if userpquota.SoftLimit is not None :
574                    if userpquota.SoftLimit[0].upper() == "NONE" :
575                        userpquota.SoftLimit = None
576                    else :   
577                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
578                userpquota.HardLimit = fields.get("pykotaHardLimit")
579                if userpquota.HardLimit is not None :
580                    if userpquota.HardLimit[0].upper() == "NONE" :
581                        userpquota.HardLimit = None
582                    elif userpquota.HardLimit is not None :   
583                        userpquota.HardLimit = int(userpquota.HardLimit[0])
584                userpquota.DateLimit = fields.get("pykotaDateLimit")
585                if userpquota.DateLimit is not None :
586                    if userpquota.DateLimit[0].upper() == "NONE" : 
587                        userpquota.DateLimit = None
588                    else :   
589                        userpquota.DateLimit = userpquota.DateLimit[0]
590                userpquota.Exists = 1
591                usersandquotas.append((user, userpquota))
592                self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
593        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
594        return usersandquotas
595               
596    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
597        """Returns the list of groups which uses a given printer, along with their quotas."""
598        groupsandquotas = []
599        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaGroupName=%s)" % gname for gname in names])), ["pykotaGroupName"], base=self.info["groupquotabase"])
600        if result :
601            for (groupquotaid, fields) in result :
602                group = self.getGroup(fields.get("pykotaGroupName")[0])
603                grouppquota = self.getGroupPQuota(group, printer)
604                groupsandquotas.append((group, grouppquota))
605        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
606        return groupsandquotas
607       
608    def addPrinter(self, printername) :       
609        """Adds a printer to the quota storage, returns it."""
610        fields = { self.info["printerrdn"] : printername,
611                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
612                   "cn" : printername,
613                   "pykotaPrinterName" : printername,
614                   "pykotaPricePerPage" : "0.0",
615                   "pykotaPricePerJob" : "0.0",
616                 } 
617        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
618        self.doAdd(dn, fields)
619        return self.getPrinter(printername)
620       
621    def addUser(self, user) :       
622        """Adds a user to the quota storage, returns it."""
623        newfields = {
624                       "pykotaUserName" : user.Name,
625                       "pykotaLimitBY" : (user.LimitBy or "quota"),
626                       "pykotaBalance" : str(user.AccountBalance or 0.0),
627                       "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0),
628                    }   
629        if user.Email :
630            newfields.update({self.info["usermail"]: user.Email})
631        mustadd = 1
632        if self.info["newuser"].lower() != 'below' :
633            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (self.info["newuser"], self.info["userrdn"], user.Name), None, base=self.info["userbase"])
634            if result :
635                (dn, fields) = result[0]
636                fields["objectClass"].extend(["pykotaAccount", "pykotaAccountBalance"])
637                fields.update(newfields)
638                self.doModify(dn, fields)
639                mustadd = 0
640               
641        if mustadd :
642            fields = { self.info["userrdn"] : user.Name,
643                       "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
644                       "cn" : user.Name,
645                     } 
646            fields.update(newfields)         
647            dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
648            self.doAdd(dn, fields)
649        return self.getUser(user.Name)
650       
651    def addGroup(self, group) :       
652        """Adds a group to the quota storage, returns it."""
653        newfields = { 
654                      "pykotaGroupName" : group.Name,
655                      "pykotaLimitBY" : (group.LimitBy or "quota"),
656                    } 
657        mustadd = 1
658        if self.info["newgroup"].lower() != 'below' :
659            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (self.info["newgroup"], self.info["grouprdn"], group.Name), None, base=self.info["groupbase"])
660            if result :
661                (dn, fields) = result[0]
662                fields["objectClass"].extend(["pykotaGroup"])
663                fields.update(newfields)
664                self.doModify(dn, fields)
665                mustadd = 0
666               
667        if mustadd :
668            fields = { self.info["grouprdn"] : group.Name,
669                       "objectClass" : ["pykotaObject", "pykotaGroup"],
670                       "cn" : group.Name,
671                     } 
672            fields.update(newfields)         
673            dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"])
674            self.doAdd(dn, fields)
675        return self.getGroup(group.Name)
676       
677    def addUserToGroup(self, user, group) :   
678        """Adds an user to a group."""
679        if user.Name not in [u.Name for u in self.getGroupMembers(group)] :
680            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
681            if result :
682                fields = result[0][1]
683                if not fields.has_key(self.info["groupmembers"]) :
684                    fields[self.info["groupmembers"]] = []
685                fields[self.info["groupmembers"]].append(user.Name)
686                self.doModify(group.ident, fields)
687                group.Members.append(user)
688               
689    def addUserPQuota(self, user, printer) :
690        """Initializes a user print quota on a printer."""
691        uuid = self.genUUID()
692        fields = { "cn" : uuid,
693                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
694                   "pykotaUserName" : user.Name,
695                   "pykotaPrinterName" : printer.Name,
696                   "pykotaDateLimit" : "None",
697                   "pykotaPageCounter" : "0",
698                   "pykotaLifePageCounter" : "0",
699                 } 
700        dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
701        self.doAdd(dn, fields)
702        return self.getUserPQuota(user, printer)
703       
704    def addGroupPQuota(self, group, printer) :
705        """Initializes a group print quota on a printer."""
706        uuid = self.genUUID()
707        fields = { "cn" : uuid,
708                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
709                   "pykotaGroupName" : group.Name,
710                   "pykotaPrinterName" : printer.Name,
711                   "pykotaDateLimit" : "None",
712                 } 
713        dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
714        self.doAdd(dn, fields)
715        return self.getGroupPQuota(group, printer)
716       
717    def writePrinterPrices(self, printer) :   
718        """Write the printer's prices back into the storage."""
719        fields = {
720                   "pykotaPricePerPage" : str(printer.PricePerPage),
721                   "pykotaPricePerJob" : str(printer.PricePerJob),
722                 }
723        self.doModify(printer.ident, fields)
724       
725    def writeUserLimitBy(self, user, limitby) :   
726        """Sets the user's limiting factor."""
727        fields = {
728                   "pykotaLimitBy" : limitby,
729                 }
730        self.doModify(user.ident, fields)         
731       
732    def writeGroupLimitBy(self, group, limitby) :   
733        """Sets the group's limiting factor."""
734        fields = {
735                   "pykotaLimitBy" : limitby,
736                 }
737        self.doModify(group.ident, fields)         
738       
739    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
740        """Sets the date limit permanently for a user print quota."""
741        fields = {
742                   "pykotaDateLimit" : datelimit,
743                 }
744        return self.doModify(userpquota.ident, fields)
745           
746    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
747        """Sets the date limit permanently for a group print quota."""
748        fields = {
749                   "pykotaDateLimit" : datelimit,
750                 }
751        return self.doModify(grouppquota.ident, fields)
752       
753    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
754        """Increase page counters for a user print quota."""
755        fields = {
756                   "pykotaPageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
757                   "pykotaLifePageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
758                 }
759        return self.doModify(userpquota.ident, fields)         
760       
761    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
762        """Sets the new page counters permanently for a user print quota."""
763        fields = {
764                   "pykotaPageCounter" : str(newpagecounter),
765                   "pykotaLifePageCounter" : str(newlifepagecounter),
766                 } 
767        return self.doModify(userpquota.ident, fields)         
768       
769    def decreaseUserAccountBalance(self, user, amount) :   
770        """Decreases user's account balance from an amount."""
771        fields = {
772                   "pykotaBalance" : { "operator" : "-", "value" : amount, "convert" : float },
773                 }
774        return self.doModify(user.idbalance, fields)         
775       
776    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
777        """Sets the new account balance and eventually new lifetime paid."""
778        fields = {
779                   "pykotaBalance" : str(newbalance),
780                 }
781        if newlifetimepaid is not None :
782            fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) })
783        return self.doModify(user.idbalance, fields)         
784           
785    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
786        """Sets the last job's size permanently."""
787        fields = {
788                   "pykotaJobSize" : str(jobsize),
789                   "pykotaJobPrice" : str(jobprice),
790                 }
791        self.doModify(lastjob.ident, fields)         
792       
793    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None) :
794        """Adds a job in a printer's history."""
795        if (not self.disablehistory) or (not printer.LastJob.Exists) :
796            uuid = self.genUUID()
797            dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
798        else :   
799            uuid = printer.LastJob.ident[3:].split(",")[0]
800            dn = printer.LastJob.ident
801        fields = {
802                   "objectClass" : ["pykotaObject", "pykotaJob"],
803                   "cn" : uuid,
804                   "pykotaUserName" : user.Name,
805                   "pykotaPrinterName" : printer.Name,
806                   "pykotaJobId" : jobid,
807                   "pykotaPrinterPageCounter" : str(pagecounter),
808                   "pykotaAction" : action,
809                   "pykotaFileName" : str(filename), 
810                   "pykotaTitle" : str(title), 
811                   "pykotaCopies" : str(copies), 
812                   "pykotaOptions" : str(options), 
813                 }
814        if (not self.disablehistory) or (not printer.LastJob.Exists) :
815            if jobsize is not None :         
816                fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
817            self.doAdd(dn, fields)
818        else :   
819            # here we explicitly want to reset jobsize to 'None' if needed
820            fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
821            self.doModify(dn, fields)
822           
823        if printer.LastJob.Exists :
824            fields = {
825                       "pykotaLastJobIdent" : uuid,
826                     }
827            self.doModify(printer.LastJob.lastjobident, fields)         
828        else :   
829            lastjuuid = self.genUUID()
830            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
831            fields = {
832                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
833                       "cn" : lastjuuid,
834                       "pykotaPrinterName" : printer.Name,
835                       "pykotaLastJobIdent" : uuid,
836                     } 
837            self.doAdd(lastjdn, fields)         
838           
839    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
840        """Sets soft and hard limits for a user quota."""
841        fields = { 
842                   "pykotaSoftLimit" : str(softlimit),
843                   "pykotaHardLimit" : str(hardlimit),
844                 }
845        self.doModify(userpquota.ident, fields)
846       
847    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
848        """Sets soft and hard limits for a group quota on a specific printer."""
849        fields = { 
850                   "pykotaSoftLimit" : str(softlimit),
851                   "pykotaHardLimit" : str(hardlimit),
852                 }
853        self.doModify(grouppquota.ident, fields)
854           
855    def writePrinterToGroup(self, pgroup, printer) :
856        """Puts a printer into a printer group."""
857        if printer.ident not in pgroup.uniqueMember :
858            pgroup.uniqueMember.append(printer.ident)
859            fields = {
860                       "uniqueMember" : pgroup.uniqueMember
861                     } 
862            self.doModify(pgroup.ident, fields)         
863       
864    def deleteUser(self, user) :   
865        """Completely deletes an user from the Quota Storage."""
866        # TODO : What should we do if we delete the last person who used a given printer ?
867        # TODO : we can't reassign the last job to the previous one, because next user would be
868        # TODO : incorrectly charged (overcharged).
869        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaUserName=%s))" % user.Name, base=self.info["lastjobbase"])
870        for (ident, fields) in result :
871            self.doDelete(ident)
872        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
873        for (ident, fields) in result :
874            self.doDelete(ident)
875        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["userquotabase"])
876        for (ident, fields) in result :
877            self.doDelete(ident)
878        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
879        if result :
880            fields = result[0][1]
881            for k in fields.keys() :
882                if k.startswith("pykota") :
883                    del fields[k]
884                elif k.lower() == "objectclass" :   
885                    todelete = []
886                    for i in range(len(fields[k])) :
887                        if fields[k][i].startswith("pykota") : 
888                            todelete.append(i)
889                    todelete.sort()       
890                    todelete.reverse()
891                    for i in todelete :
892                        del fields[k][i]
893            if fields.get("objectClass") or fields.get("objectclass") :
894                self.doModify(user.ident, fields, ignoreold=0)       
895            else :   
896                self.doDelete(user.ident)
897        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"])
898        for (ident, fields) in result :
899            self.doDelete(ident)
900       
901    def deleteGroup(self, group) :   
902        """Completely deletes a group from the Quota Storage."""
903        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=self.info["groupquotabase"])
904        for (ident, fields) in result :
905            self.doDelete(ident)
906        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
907        if result :
908            fields = result[0][1]
909            for k in fields.keys() :
910                if k.startswith("pykota") :
911                    del fields[k]
912                elif k.lower() == "objectclass" :   
913                    todelete = []
914                    for i in range(len(fields[k])) :
915                        if fields[k][i].startswith("pykota") : 
916                            todelete.append(i)
917                    todelete.sort()       
918                    todelete.reverse()
919                    for i in todelete :
920                        del fields[k][i]
921            if fields.get("objectClass") or fields.get("objectclass") :
922                self.doModify(group.ident, fields, ignoreold=0)       
923            else :   
924                self.doDelete(group.ident)
925           
Note: See TracBrowser for help on using the browser.