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

Revision 1170, 37.9 kB (checked in by jalet, 21 years ago)

More complete messages in case of LDAP failure.
LDAP database connection is now unbound on exit too.

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