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