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.24 2003/10/07 22:06:05 jalet |
---|
25 | # Preliminary code to disable job history |
---|
26 | # |
---|
27 | # Revision 1.23 2003/10/07 09:07:28 jalet |
---|
28 | # Character encoding added to please latest version of Python |
---|
29 | # |
---|
30 | # Revision 1.22 2003/10/06 13:12:27 jalet |
---|
31 | # More work on caching |
---|
32 | # |
---|
33 | # Revision 1.21 2003/10/03 09:02:20 jalet |
---|
34 | # Logs cache store actions too |
---|
35 | # |
---|
36 | # Revision 1.20 2003/10/02 20:23:18 jalet |
---|
37 | # Storage caching mechanism added. |
---|
38 | # |
---|
39 | # Revision 1.19 2003/07/16 21:53:07 jalet |
---|
40 | # Really big modifications wrt new configuration file's location and content. |
---|
41 | # |
---|
42 | # Revision 1.18 2003/07/07 08:33:18 jalet |
---|
43 | # Bug fix due to a typo in LDAP code |
---|
44 | # |
---|
45 | # Revision 1.17 2003/07/05 07:46:50 jalet |
---|
46 | # The previous bug fix was incomplete. |
---|
47 | # |
---|
48 | # Revision 1.16 2003/06/25 19:52:31 jalet |
---|
49 | # Should be ready for testing :-) |
---|
50 | # |
---|
51 | # Revision 1.15 2003/06/25 14:10:58 jalet |
---|
52 | # Exception raising for now. |
---|
53 | # |
---|
54 | # Revision 1.14 2003/06/25 14:10:01 jalet |
---|
55 | # Hey, it may work (edpykota --reset excepted) ! |
---|
56 | # |
---|
57 | # Revision 1.13 2003/06/10 16:37:54 jalet |
---|
58 | # Deletion of the second user which is not needed anymore. |
---|
59 | # Added a debug configuration field in /etc/pykota.conf |
---|
60 | # All queries can now be sent to the logger in debug mode, this will |
---|
61 | # greatly help improve performance when time for this will come. |
---|
62 | # |
---|
63 | # Revision 1.12 2003/04/23 22:13:57 jalet |
---|
64 | # Preliminary support for LPRng added BUT STILL UNTESTED. |
---|
65 | # |
---|
66 | # Revision 1.11 2003/04/10 21:47:20 jalet |
---|
67 | # Job history added. Upgrade script neutralized for now ! |
---|
68 | # |
---|
69 | # Revision 1.10 2003/03/29 13:45:27 jalet |
---|
70 | # GPL paragraphs were incorrectly (from memory) copied into the sources. |
---|
71 | # Two README files were added. |
---|
72 | # Upgrade script for PostgreSQL pre 1.01 schema was added. |
---|
73 | # |
---|
74 | # Revision 1.9 2003/02/17 22:55:01 jalet |
---|
75 | # More options can now be set per printer or globally : |
---|
76 | # |
---|
77 | # admin |
---|
78 | # adminmail |
---|
79 | # gracedelay |
---|
80 | # requester |
---|
81 | # |
---|
82 | # the printer option has priority when both are defined. |
---|
83 | # |
---|
84 | # Revision 1.8 2003/02/17 22:05:50 jalet |
---|
85 | # Storage backend now supports admin and user passwords (untested) |
---|
86 | # |
---|
87 | # Revision 1.7 2003/02/10 12:07:31 jalet |
---|
88 | # Now repykota should output the recorded total page number for each printer too. |
---|
89 | # |
---|
90 | # Revision 1.6 2003/02/09 13:05:43 jalet |
---|
91 | # Internationalization continues... |
---|
92 | # |
---|
93 | # Revision 1.5 2003/02/08 22:39:46 jalet |
---|
94 | # --reset command line option added |
---|
95 | # |
---|
96 | # Revision 1.4 2003/02/08 09:59:59 jalet |
---|
97 | # Added preliminary base class for all storages |
---|
98 | # |
---|
99 | # Revision 1.3 2003/02/05 22:10:29 jalet |
---|
100 | # Typos |
---|
101 | # |
---|
102 | # Revision 1.2 2003/02/05 22:02:22 jalet |
---|
103 | # __import__ statement didn't work as expected |
---|
104 | # |
---|
105 | # Revision 1.1 2003/02/05 21:28:17 jalet |
---|
106 | # Initial import into CVS |
---|
107 | # |
---|
108 | # |
---|
109 | # |
---|
110 | |
---|
111 | class PyKotaStorageError(Exception): |
---|
112 | """An exception for Quota Storage related stuff.""" |
---|
113 | def __init__(self, message = ""): |
---|
114 | self.message = message |
---|
115 | Exception.__init__(self, message) |
---|
116 | def __repr__(self): |
---|
117 | return self.message |
---|
118 | __str__ = __repr__ |
---|
119 | |
---|
120 | class StorageObject : |
---|
121 | """Object present in the Quota Storage.""" |
---|
122 | def __init__(self, parent) : |
---|
123 | "Initialize minimal data.""" |
---|
124 | self.parent = parent |
---|
125 | self.ident = None |
---|
126 | self.Exists = 0 |
---|
127 | |
---|
128 | class StorageUser(StorageObject) : |
---|
129 | """User class.""" |
---|
130 | def __init__(self, parent, name) : |
---|
131 | StorageObject.__init__(self, parent) |
---|
132 | self.Name = name |
---|
133 | self.LimitBy = None |
---|
134 | self.AccountBalance = None |
---|
135 | self.LifeTimePaid = None |
---|
136 | self.Email = None |
---|
137 | |
---|
138 | def consumeAccountBalance(self, amount) : |
---|
139 | """Consumes an amount of money from the user's account balance.""" |
---|
140 | newbalance = float(self.AccountBalance or 0.0) - amount |
---|
141 | self.parent.writeUserAccountBalance(self, newbalance) |
---|
142 | self.AccountBalance = newbalance |
---|
143 | |
---|
144 | def setAccountBalance(self, balance, lifetimepaid) : |
---|
145 | """Sets the user's account balance in case he pays more money.""" |
---|
146 | self.parent.writeUserAccountBalance(self, balance, lifetimepaid) |
---|
147 | self.AccountBalance = balance |
---|
148 | self.LifeTimePaid = lifetimepaid |
---|
149 | |
---|
150 | def setLimitBy(self, limitby) : |
---|
151 | """Sets the user's limiting factor.""" |
---|
152 | try : |
---|
153 | limitby = limitby.lower() |
---|
154 | except AttributeError : |
---|
155 | limitby = "quota" |
---|
156 | if limitby in ["quota", "balance"] : |
---|
157 | self.parent.writeUserLimitBy(self, limitby) |
---|
158 | self.LimitBy = limitby |
---|
159 | |
---|
160 | def delete(self) : |
---|
161 | """Deletes an user from the Quota Storage.""" |
---|
162 | self.parent.beginTransaction() |
---|
163 | try : |
---|
164 | self.parent.deleteUser(self) |
---|
165 | except PyKotaStorageError, msg : |
---|
166 | self.parent.rollbackTransaction() |
---|
167 | raise PyKotaStorageError, msg |
---|
168 | else : |
---|
169 | self.parent.commitTransaction() |
---|
170 | |
---|
171 | class StorageGroup(StorageObject) : |
---|
172 | """User class.""" |
---|
173 | def __init__(self, parent, name) : |
---|
174 | StorageObject.__init__(self, parent) |
---|
175 | self.Name = name |
---|
176 | self.LimitBy = None |
---|
177 | self.AccountBalance = None |
---|
178 | self.LifeTimePaid = None |
---|
179 | |
---|
180 | def setLimitBy(self, limitby) : |
---|
181 | """Sets the user's limiting factor.""" |
---|
182 | try : |
---|
183 | limitby = limitby.lower() |
---|
184 | except AttributeError : |
---|
185 | limitby = "quota" |
---|
186 | if limitby in ["quota", "balance"] : |
---|
187 | self.parent.writeGroupLimitBy(self, limitby) |
---|
188 | self.LimitBy = limitby |
---|
189 | |
---|
190 | def delete(self) : |
---|
191 | """Deletes a group from the Quota Storage.""" |
---|
192 | self.parent.beginTransaction() |
---|
193 | try : |
---|
194 | self.parent.deleteGroup(self) |
---|
195 | except PyKotaStorageError, msg : |
---|
196 | self.parent.rollbackTransaction() |
---|
197 | raise PyKotaStorageError, msg |
---|
198 | else : |
---|
199 | self.parent.commitTransaction() |
---|
200 | |
---|
201 | class StoragePrinter(StorageObject) : |
---|
202 | """Printer class.""" |
---|
203 | def __init__(self, parent, name) : |
---|
204 | StorageObject.__init__(self, parent) |
---|
205 | self.Name = name |
---|
206 | self.PricePerPage = None |
---|
207 | self.PricePerJob = None |
---|
208 | self.LastJob = None |
---|
209 | |
---|
210 | def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None) : |
---|
211 | """Adds a job to the printer's history.""" |
---|
212 | self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize) |
---|
213 | # TODO : update LastJob object ? Probably not needed. |
---|
214 | |
---|
215 | def setPrices(self, priceperpage = None, priceperjob = None) : |
---|
216 | """Sets the printer's prices.""" |
---|
217 | if priceperpage is None : |
---|
218 | priceperpage = self.PricePerPage |
---|
219 | else : |
---|
220 | self.PricePerPage = float(priceperpage) |
---|
221 | if priceperjob is None : |
---|
222 | priceperjob = self.PricePerJob |
---|
223 | else : |
---|
224 | self.PricePerJob = float(priceperjob) |
---|
225 | self.parent.writePrinterPrices(self) |
---|
226 | |
---|
227 | class StorageUserPQuota(StorageObject) : |
---|
228 | """User Print Quota class.""" |
---|
229 | def __init__(self, parent, user, printer) : |
---|
230 | StorageObject.__init__(self, parent) |
---|
231 | self.User = user |
---|
232 | self.Printer = printer |
---|
233 | self.PageCounter = None |
---|
234 | self.LifePageCounter = None |
---|
235 | self.SoftLimit = None |
---|
236 | self.HardLimit = None |
---|
237 | self.DateLimit = None |
---|
238 | |
---|
239 | def setDateLimit(self, datelimit) : |
---|
240 | """Sets the date limit for this quota.""" |
---|
241 | date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second) |
---|
242 | self.parent.writeUserPQuotaDateLimit(self, date) |
---|
243 | self.DateLimit = date |
---|
244 | |
---|
245 | def setLimits(self, softlimit, hardlimit) : |
---|
246 | """Sets the soft and hard limit for this quota.""" |
---|
247 | self.parent.writeUserPQuotaLimits(self, softlimit, hardlimit) |
---|
248 | self.SoftLimit = softlimit |
---|
249 | self.HardLimit = hardlimit |
---|
250 | |
---|
251 | def reset(self) : |
---|
252 | """Resets page counter to 0.""" |
---|
253 | self.parent.writeUserPQuotaPagesCounters(self, 0, int(self.LifePageCounter or 0)) |
---|
254 | self.PageCounter = 0 |
---|
255 | |
---|
256 | def increasePagesUsage(self, nbpages) : |
---|
257 | """Increase the value of used pages and money.""" |
---|
258 | if nbpages : |
---|
259 | jobprice = (float(self.Printer.PricePerPage or 0.0) * nbpages) + float(self.Printer.PricePerJob or 0.0) |
---|
260 | newpagecounter = int(self.PageCounter or 0) + nbpages |
---|
261 | newlifepagecounter = int(self.LifePageCounter or 0) + nbpages |
---|
262 | self.parent.beginTransaction() |
---|
263 | try : |
---|
264 | if jobprice : # optimization : don't access the database if unneeded. |
---|
265 | self.User.consumeAccountBalance(jobprice) |
---|
266 | self.parent.writeUserPQuotaPagesCounters(self, newpagecounter, newlifepagecounter) |
---|
267 | except PyKotaStorageError, msg : |
---|
268 | self.parent.rollbackTransaction() |
---|
269 | raise PyKotaStorageError, msg |
---|
270 | else : |
---|
271 | self.parent.commitTransaction() |
---|
272 | self.PageCounter = newpagecounter |
---|
273 | self.LifePageCounter = newlifepagecounter |
---|
274 | |
---|
275 | class StorageGroupPQuota(StorageObject) : |
---|
276 | """Group Print Quota class.""" |
---|
277 | def __init__(self, parent, group, printer) : |
---|
278 | StorageObject.__init__(self, parent) |
---|
279 | self.Group = group |
---|
280 | self.Printer = printer |
---|
281 | self.PageCounter = None |
---|
282 | self.LifePageCounter = None |
---|
283 | self.SoftLimit = None |
---|
284 | self.HardLimit = None |
---|
285 | self.DateLimit = None |
---|
286 | |
---|
287 | def setDateLimit(self, datelimit) : |
---|
288 | """Sets the date limit for this quota.""" |
---|
289 | date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second) |
---|
290 | self.parent.writeGroupPQuotaDateLimit(self, date) |
---|
291 | self.DateLimit = date |
---|
292 | |
---|
293 | def setLimits(self, softlimit, hardlimit) : |
---|
294 | """Sets the soft and hard limit for this quota.""" |
---|
295 | self.parent.writeGroupPQuotaLimits(self, softlimit, hardlimit) |
---|
296 | self.SoftLimit = softlimit |
---|
297 | self.HardLimit = hardlimit |
---|
298 | |
---|
299 | class StorageLastJob(StorageObject) : |
---|
300 | """Printer's Last Job class.""" |
---|
301 | def __init__(self, parent, printer) : |
---|
302 | StorageObject.__init__(self, parent) |
---|
303 | self.Printer = printer |
---|
304 | self.JobId = None |
---|
305 | self.User = None |
---|
306 | self.PrinterPageCounter = None |
---|
307 | self.JobSize = None |
---|
308 | self.JobAction = None |
---|
309 | self.JobDate = None |
---|
310 | |
---|
311 | def setSize(self, jobsize) : |
---|
312 | """Sets the last job's size.""" |
---|
313 | self.parent.writeLastJobSize(self, jobsize) |
---|
314 | self.JobSize = jobsize |
---|
315 | |
---|
316 | class BaseStorage : |
---|
317 | def __init__(self, pykotatool) : |
---|
318 | """Opens the LDAP connection.""" |
---|
319 | # raise PyKotaStorageError, "Sorry, the LDAP backend for PyKota is not yet implemented !" |
---|
320 | self.closed = 1 |
---|
321 | self.tool = pykotatool |
---|
322 | self.usecache = pykotatool.config.getCaching() |
---|
323 | self.disablehistory = pykotatool.config.getDisableHistory() |
---|
324 | if self.usecache : |
---|
325 | self.tool.logdebug("Caching enabled.") |
---|
326 | self.caches = { "USERS" : {}, "GROUPS" : {}, "PRINTERS" : {}, "USERPQUOTAS" : {}, "GROUPPQUOTAS" : {}, "JOBS" : {}, "LASTJOBS" : {} } |
---|
327 | |
---|
328 | def __del__(self) : |
---|
329 | """Ensures that the database connection is closed.""" |
---|
330 | self.close() |
---|
331 | |
---|
332 | def getFromCache(self, cachetype, key) : |
---|
333 | """Tries to extract something from the cache.""" |
---|
334 | if self.usecache : |
---|
335 | entry = self.caches[cachetype].get(key) |
---|
336 | if entry is not None : |
---|
337 | self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key)) |
---|
338 | else : |
---|
339 | self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key)) |
---|
340 | return entry |
---|
341 | |
---|
342 | def cacheEntry(self, cachetype, key, value) : |
---|
343 | """Puts an entry in the cache.""" |
---|
344 | if self.usecache : |
---|
345 | self.caches[cachetype][key] = value |
---|
346 | self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key)) |
---|
347 | |
---|
348 | def getUser(self, username) : |
---|
349 | """Returns the user from cache.""" |
---|
350 | user = self.getFromCache("USERS", username) |
---|
351 | if user is None : |
---|
352 | user = self.getUserFromBackend(username) |
---|
353 | self.cacheEntry("USERS", username, user) |
---|
354 | return user |
---|
355 | |
---|
356 | def getGroup(self, groupname) : |
---|
357 | """Returns the group from cache.""" |
---|
358 | group = self.getFromCache("GROUPS", groupname) |
---|
359 | if group is None : |
---|
360 | group = self.getGroupFromBackend(groupname) |
---|
361 | self.cacheEntry("GROUPS", groupname, group) |
---|
362 | return group |
---|
363 | |
---|
364 | def getPrinter(self, printername) : |
---|
365 | """Returns the printer from cache.""" |
---|
366 | printer = self.getFromCache("PRINTERS", printername) |
---|
367 | if printer is None : |
---|
368 | printer = self.getPrinterFromBackend(printername) |
---|
369 | self.cacheEntry("PRINTERS", printername, printer) |
---|
370 | return printer |
---|
371 | |
---|
372 | def getUserPQuota(self, user, printer) : |
---|
373 | """Returns the user quota information from cache.""" |
---|
374 | useratprinter = "%s@%s" % (user.Name, printer.Name) |
---|
375 | upquota = self.getFromCache("USERPQUOTAS", useratprinter) |
---|
376 | if upquota is None : |
---|
377 | upquota = self.getUserPQuotaFromBackend(user, printer) |
---|
378 | self.cacheEntry("USERPQUOTAS", useratprinter, upquota) |
---|
379 | return upquota |
---|
380 | |
---|
381 | def getGroupPQuota(self, group, printer) : |
---|
382 | """Returns the group quota information from cache.""" |
---|
383 | groupatprinter = "%s@%s" % (group.Name, printer.Name) |
---|
384 | gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter) |
---|
385 | if gpquota is None : |
---|
386 | gpquota = self.getGroupPQuotaFromBackend(group, printer) |
---|
387 | self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota) |
---|
388 | return gpquota |
---|
389 | |
---|
390 | def getPrinterLastJob(self, printer) : |
---|
391 | """Extracts last job information for a given printer from cache.""" |
---|
392 | lastjob = self.getFromCache("LASTJOBS", printer.Name) |
---|
393 | if lastjob is None : |
---|
394 | lastjob = self.getPrinterLastJobFromBackend(printer) |
---|
395 | self.cacheEntry("LASTJOBS", printer.Name, lastjob) |
---|
396 | return lastjob |
---|
397 | |
---|
398 | def getGroupMembers(self, group) : |
---|
399 | """Returns the group's members list from in-group cache.""" |
---|
400 | if self.usecache : |
---|
401 | if not hasattr(group, "Members") : |
---|
402 | self.tool.logdebug("Cache miss (%s->Members)" % group.Name) |
---|
403 | group.Members = self.getGroupMembersFromBackend(group) |
---|
404 | self.tool.logdebug("Cache store (%s->Members)" % group.Name) |
---|
405 | else : |
---|
406 | self.tool.logdebug("Cache hit (%s->Members)" % group.Name) |
---|
407 | else : |
---|
408 | group.Members = self.getGroupMembersFromBackend(group) |
---|
409 | return group.Members |
---|
410 | |
---|
411 | def getUserGroups(self, user) : |
---|
412 | """Returns the user's groups list from in-user cache.""" |
---|
413 | if self.usecache : |
---|
414 | if not hasattr(user, "Groups") : |
---|
415 | self.tool.logdebug("Cache miss (%s->Groups)" % user.Name) |
---|
416 | user.Groups = self.getUserGroupsFromBackend(user) |
---|
417 | self.tool.logdebug("Cache store (%s->Groups)" % user.Name) |
---|
418 | else : |
---|
419 | self.tool.logdebug("Cache hit (%s->Groups)" % user.Name) |
---|
420 | else : |
---|
421 | user.Groups = self.getUserGroupsFromBackend(user) |
---|
422 | return user.Groups |
---|
423 | |
---|
424 | def openConnection(pykotatool) : |
---|
425 | """Returns a connection handle to the appropriate Quota Storage Database.""" |
---|
426 | backendinfo = pykotatool.config.getStorageBackend() |
---|
427 | backend = backendinfo["storagebackend"] |
---|
428 | try : |
---|
429 | if not backend.isalpha() : |
---|
430 | # don't trust user input |
---|
431 | raise ImportError |
---|
432 | # |
---|
433 | # TODO : descending compatibility |
---|
434 | # |
---|
435 | if backend == "postgresql" : |
---|
436 | backend = "pgstorage" # TODO : delete, this is for descending compatibility only |
---|
437 | exec "from pykota.storages import %s as storagebackend" % backend.lower() |
---|
438 | except ImportError : |
---|
439 | raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend |
---|
440 | else : |
---|
441 | host = backendinfo["storageserver"] |
---|
442 | database = backendinfo["storagename"] |
---|
443 | admin = backendinfo["storageadmin"] or backendinfo["storageuser"] |
---|
444 | adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"] |
---|
445 | return getattr(storagebackend, "Storage")(pykotatool, host, database, admin, adminpw) |
---|