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

Revision 1249, 41.3 kB (checked in by jalet, 20 years ago)

Printer groups should be cached now, if caching is enabled.

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