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

Revision 1147, 37.0 kB (checked in by jalet, 21 years ago)

More work on cache

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