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

Revision 1257, 41.4 kB (checked in by jalet, 20 years ago)

Copyright year changed.

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