1 | # PyKota |
---|
2 | # -*- coding: ISO-8859-15 -*- |
---|
3 | # |
---|
4 | # PyKota : Print Quotas for CUPS and LPRng |
---|
5 | # |
---|
6 | # (c) 2003, 2004, 2005, 2006 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
20 | # |
---|
21 | # $Id$ |
---|
22 | # |
---|
23 | # |
---|
24 | |
---|
25 | from mx import DateTime |
---|
26 | |
---|
27 | class PyKotaStorageError(Exception): |
---|
28 | """An exception for database related stuff.""" |
---|
29 | def __init__(self, message = ""): |
---|
30 | self.message = message |
---|
31 | Exception.__init__(self, message) |
---|
32 | def __repr__(self): |
---|
33 | return self.message |
---|
34 | __str__ = __repr__ |
---|
35 | |
---|
36 | class StorageObject : |
---|
37 | """Object present in the database.""" |
---|
38 | def __init__(self, parent) : |
---|
39 | "Initialize minimal data.""" |
---|
40 | self.parent = parent |
---|
41 | self.ident = None |
---|
42 | self.Description = None |
---|
43 | self.isDirty = False |
---|
44 | self.Exists = False |
---|
45 | |
---|
46 | def setDescription(self, description=None) : |
---|
47 | """Sets the object's description.""" |
---|
48 | if description is not None : |
---|
49 | self.Description = str(description) |
---|
50 | self.isDirty = True |
---|
51 | |
---|
52 | def save(self) : |
---|
53 | """Saves the object to the database.""" |
---|
54 | if self.isDirty : |
---|
55 | getattr(self.parent, "save%s" % self.__class__.__name__[7:])(self) |
---|
56 | self.isDirty = False |
---|
57 | |
---|
58 | class StorageUser(StorageObject) : |
---|
59 | """User class.""" |
---|
60 | def __init__(self, parent, name) : |
---|
61 | StorageObject.__init__(self, parent) |
---|
62 | self.Name = name |
---|
63 | self.LimitBy = None |
---|
64 | self.AccountBalance = None |
---|
65 | self.LifeTimePaid = None |
---|
66 | self.Email = None |
---|
67 | self.OverCharge = 1.0 |
---|
68 | self.Payments = [] # TODO : maybe handle this smartly for SQL, for now just don't retrieve them |
---|
69 | self.PaymentsBacklog = [] |
---|
70 | |
---|
71 | def consumeAccountBalance(self, amount) : |
---|
72 | """Consumes an amount of money from the user's account balance.""" |
---|
73 | self.parent.decreaseUserAccountBalance(self, amount) |
---|
74 | self.AccountBalance = float(self.AccountBalance or 0.0) - amount |
---|
75 | |
---|
76 | def setAccountBalance(self, balance, lifetimepaid, comment="") : |
---|
77 | """Sets the user's account balance in case he pays more money.""" |
---|
78 | diff = float(lifetimepaid or 0.0) - float(self.LifeTimePaid or 0.0) |
---|
79 | self.AccountBalance = balance |
---|
80 | self.LifeTimePaid = lifetimepaid |
---|
81 | if diff : |
---|
82 | self.PaymentsBacklog.append((diff, comment)) |
---|
83 | self.isDirty = True |
---|
84 | |
---|
85 | def save(self) : |
---|
86 | """Saves an user and flush its payments backlog.""" |
---|
87 | for (value, comment) in self.PaymentsBacklog : |
---|
88 | self.parent.writeNewPayment(self, value, comment) |
---|
89 | self.PaymentsBacklog = [] |
---|
90 | StorageObject.save(self) |
---|
91 | |
---|
92 | def setLimitBy(self, limitby) : |
---|
93 | """Sets the user's limiting factor.""" |
---|
94 | try : |
---|
95 | limitby = limitby.lower() |
---|
96 | except AttributeError : |
---|
97 | limitby = "quota" |
---|
98 | if limitby in ["quota", "balance", \ |
---|
99 | "noquota", "noprint", "nochange"] : |
---|
100 | self.LimitBy = limitby |
---|
101 | self.isDirty = True |
---|
102 | |
---|
103 | def setOverChargeFactor(self, factor) : |
---|
104 | """Sets the user's overcharging coefficient.""" |
---|
105 | self.OverCharge = factor |
---|
106 | self.isDirty = True |
---|
107 | |
---|
108 | def delete(self) : |
---|
109 | """Deletes an user from the database.""" |
---|
110 | self.parent.deleteUser(self) |
---|
111 | self.parent.flushEntry("USERS", self.Name) |
---|
112 | if self.parent.usecache : |
---|
113 | for (k, v) in self.parent.caches["USERPQUOTAS"].items() : |
---|
114 | if v.User.Name == self.Name : |
---|
115 | self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (v.User.Name, v.Printer.Name)) |
---|
116 | self.Exists = False |
---|
117 | self.isDirty = False |
---|
118 | |
---|
119 | class StorageGroup(StorageObject) : |
---|
120 | """User class.""" |
---|
121 | def __init__(self, parent, name) : |
---|
122 | StorageObject.__init__(self, parent) |
---|
123 | self.Name = name |
---|
124 | self.LimitBy = None |
---|
125 | self.AccountBalance = None |
---|
126 | self.LifeTimePaid = None |
---|
127 | |
---|
128 | def setLimitBy(self, limitby) : |
---|
129 | """Sets the user's limiting factor.""" |
---|
130 | try : |
---|
131 | limitby = limitby.lower() |
---|
132 | except AttributeError : |
---|
133 | limitby = "quota" |
---|
134 | if limitby in ["quota", "balance", "noquota"] : |
---|
135 | self.LimitBy = limitby |
---|
136 | self.isDirty = True |
---|
137 | |
---|
138 | def addUserToGroup(self, user) : |
---|
139 | """Adds an user to an users group.""" |
---|
140 | self.parent.addUserToGroup(user, self) |
---|
141 | |
---|
142 | def delUserFromGroup(self, user) : |
---|
143 | """Removes an user from an users group.""" |
---|
144 | self.parent.delUserFromGroup(user, self) |
---|
145 | |
---|
146 | def delete(self) : |
---|
147 | """Deletes a group from the database.""" |
---|
148 | self.parent.deleteGroup(self) |
---|
149 | self.parent.flushEntry("GROUPS", self.Name) |
---|
150 | if self.parent.usecache : |
---|
151 | for (k, v) in self.parent.caches["GROUPPQUOTAS"].items() : |
---|
152 | if v.Group.Name == self.Name : |
---|
153 | self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (v.Group.Name, v.Printer.Name)) |
---|
154 | self.Exists = False |
---|
155 | self.isDirty = False |
---|
156 | |
---|
157 | class StoragePrinter(StorageObject) : |
---|
158 | """Printer class.""" |
---|
159 | def __init__(self, parent, name) : |
---|
160 | StorageObject.__init__(self, parent) |
---|
161 | self.Name = name |
---|
162 | self.PricePerPage = None |
---|
163 | self.PricePerJob = None |
---|
164 | self.MaxJobSize = None |
---|
165 | self.PassThrough = None |
---|
166 | self.Coefficients = None |
---|
167 | |
---|
168 | def __getattr__(self, name) : |
---|
169 | """Delays data retrieval until it's really needed.""" |
---|
170 | if name == "LastJob" : |
---|
171 | self.LastJob = self.parent.getPrinterLastJob(self) |
---|
172 | return self.LastJob |
---|
173 | else : |
---|
174 | raise AttributeError, name |
---|
175 | |
---|
176 | def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None, jobmd5sum=None, jobpages=None, jobbilling=None, precomputedsize=None, precomputedprice=None) : |
---|
177 | """Adds a job to the printer's history.""" |
---|
178 | self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, clienthost, jobsizebytes, jobmd5sum, jobpages, jobbilling, precomputedsize, precomputedprice) |
---|
179 | # TODO : update LastJob object ? Probably not needed. |
---|
180 | |
---|
181 | def addPrinterToGroup(self, printer) : |
---|
182 | """Adds a printer to a printer group.""" |
---|
183 | if (printer not in self.parent.getParentPrinters(self)) and (printer.ident != self.ident) : |
---|
184 | self.parent.writePrinterToGroup(self, printer) |
---|
185 | # TODO : reset cached value for printer parents, or add new parent to cached value |
---|
186 | |
---|
187 | def delPrinterFromGroup(self, printer) : |
---|
188 | """Deletes a printer from a printer group.""" |
---|
189 | self.parent.removePrinterFromGroup(self, printer) |
---|
190 | # TODO : reset cached value for printer parents, or add new parent to cached value |
---|
191 | |
---|
192 | def setPrices(self, priceperpage = None, priceperjob = None) : |
---|
193 | """Sets the printer's prices.""" |
---|
194 | if priceperpage is None : |
---|
195 | priceperpage = self.PricePerPage or 0.0 |
---|
196 | else : |
---|
197 | self.PricePerPage = float(priceperpage) |
---|
198 | if priceperjob is None : |
---|
199 | priceperjob = self.PricePerJob or 0.0 |
---|
200 | else : |
---|
201 | self.PricePerJob = float(priceperjob) |
---|
202 | self.isDirty = True |
---|
203 | |
---|
204 | def setPassThrough(self, passthrough) : |
---|
205 | """Sets the printer's passthrough mode.""" |
---|
206 | self.PassThrough = passthrough |
---|
207 | self.isDirty = True |
---|
208 | |
---|
209 | def setMaxJobSize(self, maxjobsize) : |
---|
210 | """Sets the printer's maximal job size.""" |
---|
211 | self.MaxJobSize = maxjobsize |
---|
212 | self.isDirty = True |
---|
213 | |
---|
214 | def delete(self) : |
---|
215 | """Deletes a printer from the database.""" |
---|
216 | self.parent.deletePrinter(self) |
---|
217 | self.parent.flushEntry("PRINTERS", self.Name) |
---|
218 | if self.parent.usecache : |
---|
219 | for (k, v) in self.parent.caches["USERPQUOTAS"].items() : |
---|
220 | if v.Printer.Name == self.Name : |
---|
221 | self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (v.User.Name, v.Printer.Name)) |
---|
222 | for (k, v) in self.parent.caches["GROUPPQUOTAS"].items() : |
---|
223 | if v.Printer.Name == self.Name : |
---|
224 | self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (v.Group.Name, v.Printer.Name)) |
---|
225 | self.Exists = False |
---|
226 | self.isDirty = False |
---|
227 | |
---|
228 | class StorageUserPQuota(StorageObject) : |
---|
229 | """User Print Quota class.""" |
---|
230 | def __init__(self, parent, user, printer) : |
---|
231 | StorageObject.__init__(self, parent) |
---|
232 | self.User = user |
---|
233 | self.Printer = printer |
---|
234 | self.PageCounter = None |
---|
235 | self.LifePageCounter = None |
---|
236 | self.SoftLimit = None |
---|
237 | self.HardLimit = None |
---|
238 | self.DateLimit = None |
---|
239 | self.WarnCount = None |
---|
240 | self.MaxJobSize = None |
---|
241 | |
---|
242 | def __getattr__(self, name) : |
---|
243 | """Delays data retrieval until it's really needed.""" |
---|
244 | if name == "ParentPrintersUserPQuota" : |
---|
245 | self.ParentPrintersUserPQuota = (self.User.Exists and self.Printer.Exists and self.parent.getParentPrintersUserPQuota(self)) or [] |
---|
246 | return self.ParentPrintersUserPQuota |
---|
247 | else : |
---|
248 | raise AttributeError, name |
---|
249 | |
---|
250 | def setDateLimit(self, datelimit) : |
---|
251 | """Sets the date limit for this quota.""" |
---|
252 | datelimit = DateTime.ISO.ParseDateTime(str(datelimit)) |
---|
253 | date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second) |
---|
254 | self.parent.writeUserPQuotaDateLimit(self, date) |
---|
255 | self.DateLimit = date |
---|
256 | |
---|
257 | def setLimits(self, softlimit, hardlimit) : |
---|
258 | """Sets the soft and hard limit for this quota.""" |
---|
259 | self.SoftLimit = softlimit |
---|
260 | self.HardLimit = hardlimit |
---|
261 | self.DateLimit = None |
---|
262 | self.WarnCount = 0 |
---|
263 | self.isDirty = True |
---|
264 | |
---|
265 | def setUsage(self, used) : |
---|
266 | """Sets the PageCounter and LifePageCounter to used, or if used is + or - prefixed, changes the values of {Life,}PageCounter by that amount.""" |
---|
267 | vused = int(used) |
---|
268 | if used.startswith("+") or used.startswith("-") : |
---|
269 | self.PageCounter += vused |
---|
270 | self.LifePageCounter += vused |
---|
271 | else : |
---|
272 | self.PageCounter = self.LifePageCounter = vused |
---|
273 | self.DateLimit = None |
---|
274 | self.WarnCount = 0 |
---|
275 | self.isDirty = 1 |
---|
276 | |
---|
277 | def incDenyBannerCounter(self) : |
---|
278 | """Increment the deny banner counter for this user quota.""" |
---|
279 | self.parent.increaseUserPQuotaWarnCount(self) |
---|
280 | self.WarnCount = (self.WarnCount or 0) + 1 |
---|
281 | |
---|
282 | def resetDenyBannerCounter(self) : |
---|
283 | """Resets the deny banner counter for this user quota.""" |
---|
284 | self.parent.writeUserPQuotaWarnCount(self, 0) |
---|
285 | self.WarnCount = 0 |
---|
286 | |
---|
287 | def reset(self) : |
---|
288 | """Resets page counter to 0.""" |
---|
289 | self.PageCounter = 0 |
---|
290 | self.DateLimit = None |
---|
291 | self.isDirty = True |
---|
292 | |
---|
293 | def hardreset(self) : |
---|
294 | """Resets actual and life time page counters to 0.""" |
---|
295 | self.PageCounter = self.LifePageCounter = 0 |
---|
296 | self.DateLimit = None |
---|
297 | self.isDirty = True |
---|
298 | |
---|
299 | def computeJobPrice(self, jobsize) : |
---|
300 | """Computes the job price as the sum of all parent printers' prices + current printer's ones.""" |
---|
301 | totalprice = 0.0 |
---|
302 | if jobsize : |
---|
303 | if self.User.OverCharge != 0.0 : # optimization, but TODO : beware of rounding errors |
---|
304 | for upq in [ self ] + self.ParentPrintersUserPQuota : |
---|
305 | price = (float(upq.Printer.PricePerPage or 0.0) * jobsize) + float(upq.Printer.PricePerJob or 0.0) |
---|
306 | totalprice += price |
---|
307 | if self.User.OverCharge != 1.0 : # TODO : beware of rounding errors |
---|
308 | overcharged = totalprice * self.User.OverCharge |
---|
309 | self.parent.tool.logdebug("Overcharging %s by a factor of %s ===> User %s will be charged for %s units." % (totalprice, self.User.OverCharge, self.User.Name, overcharged)) |
---|
310 | return overcharged |
---|
311 | else : |
---|
312 | return totalprice |
---|
313 | |
---|
314 | def increasePagesUsage(self, jobsize) : |
---|
315 | """Increase the value of used pages and money.""" |
---|
316 | jobprice = self.computeJobPrice(jobsize) |
---|
317 | if jobsize : |
---|
318 | if jobprice : |
---|
319 | self.User.consumeAccountBalance(jobprice) |
---|
320 | for upq in [ self ] + self.ParentPrintersUserPQuota : |
---|
321 | self.parent.increaseUserPQuotaPagesCounters(upq, jobsize) |
---|
322 | upq.PageCounter = int(upq.PageCounter or 0) + jobsize |
---|
323 | upq.LifePageCounter = int(upq.LifePageCounter or 0) + jobsize |
---|
324 | return jobprice |
---|
325 | |
---|
326 | def delete(self) : |
---|
327 | """Deletes an user print quota entry from the database.""" |
---|
328 | self.parent.deleteUserPQuota(self) |
---|
329 | if self.parent.usecache : |
---|
330 | self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (self.User.Name, self.Printer.Name)) |
---|
331 | self.Exists = False |
---|
332 | self.isDirty = False |
---|
333 | |
---|
334 | class StorageGroupPQuota(StorageObject) : |
---|
335 | """Group Print Quota class.""" |
---|
336 | def __init__(self, parent, group, printer) : |
---|
337 | StorageObject.__init__(self, parent) |
---|
338 | self.Group = group |
---|
339 | self.Printer = printer |
---|
340 | self.PageCounter = None |
---|
341 | self.LifePageCounter = None |
---|
342 | self.SoftLimit = None |
---|
343 | self.HardLimit = None |
---|
344 | self.DateLimit = None |
---|
345 | self.MaxJobSize = None |
---|
346 | |
---|
347 | def __getattr__(self, name) : |
---|
348 | """Delays data retrieval until it's really needed.""" |
---|
349 | if name == "ParentPrintersGroupPQuota" : |
---|
350 | self.ParentPrintersGroupPQuota = (self.Group.Exists and self.Printer.Exists and self.parent.getParentPrintersGroupPQuota(self)) or [] |
---|
351 | return self.ParentPrintersGroupPQuota |
---|
352 | else : |
---|
353 | raise AttributeError, name |
---|
354 | |
---|
355 | def reset(self) : |
---|
356 | """Resets page counter to 0.""" |
---|
357 | for user in self.parent.getGroupMembers(self.Group) : |
---|
358 | uq = self.parent.getUserPQuota(user, self.Printer) |
---|
359 | uq.reset() |
---|
360 | uq.save() |
---|
361 | self.PageCounter = 0 |
---|
362 | self.DateLimit = None |
---|
363 | self.isDirty = True |
---|
364 | |
---|
365 | def hardreset(self) : |
---|
366 | """Resets actual and life time page counters to 0.""" |
---|
367 | for user in self.parent.getGroupMembers(self.Group) : |
---|
368 | uq = self.parent.getUserPQuota(user, self.Printer) |
---|
369 | uq.hardreset() |
---|
370 | uq.save() |
---|
371 | self.PageCounter = self.LifePageCounter = 0 |
---|
372 | self.DateLimit = None |
---|
373 | self.isDirty = True |
---|
374 | |
---|
375 | def setDateLimit(self, datelimit) : |
---|
376 | """Sets the date limit for this quota.""" |
---|
377 | datelimit = DateTime.ISO.ParseDateTime(str(datelimit)) |
---|
378 | date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, \ |
---|
379 | datelimit.month, \ |
---|
380 | datelimit.day, \ |
---|
381 | datelimit.hour, \ |
---|
382 | datelimit.minute, \ |
---|
383 | datelimit.second) |
---|
384 | self.parent.writeGroupPQuotaDateLimit(self, date) |
---|
385 | self.DateLimit = date |
---|
386 | |
---|
387 | def setLimits(self, softlimit, hardlimit) : |
---|
388 | """Sets the soft and hard limit for this quota.""" |
---|
389 | self.SoftLimit = softlimit |
---|
390 | self.HardLimit = hardlimit |
---|
391 | self.DateLimit = None |
---|
392 | self.isDirty = True |
---|
393 | |
---|
394 | def delete(self) : |
---|
395 | """Deletes a group print quota entry from the database.""" |
---|
396 | self.parent.deleteGroupPQuota(self) |
---|
397 | if self.parent.usecache : |
---|
398 | self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (self.Group.Name, self.Printer.Name)) |
---|
399 | self.Exists = False |
---|
400 | self.isDirty = False |
---|
401 | |
---|
402 | class StorageJob(StorageObject) : |
---|
403 | """Printer's Job class.""" |
---|
404 | def __init__(self, parent) : |
---|
405 | StorageObject.__init__(self, parent) |
---|
406 | self.UserName = None |
---|
407 | self.PrinterName = None |
---|
408 | self.JobId = None |
---|
409 | self.PrinterPageCounter = None |
---|
410 | self.JobSizeBytes = None |
---|
411 | self.JobSize = None |
---|
412 | self.JobAction = None |
---|
413 | self.JobDate = None |
---|
414 | self.JobPrice = None |
---|
415 | self.JobFileName = None |
---|
416 | self.JobTitle = None |
---|
417 | self.JobCopies = None |
---|
418 | self.JobOptions = None |
---|
419 | self.JobHostName = None |
---|
420 | self.JobMD5Sum = None |
---|
421 | self.JobPages = None |
---|
422 | self.JobBillingCode = None |
---|
423 | self.PrecomputedJobSize = None |
---|
424 | self.PrecomputedJobPrice = None |
---|
425 | |
---|
426 | def __getattr__(self, name) : |
---|
427 | """Delays data retrieval until it's really needed.""" |
---|
428 | if name == "User" : |
---|
429 | self.User = self.parent.getUser(self.UserName) |
---|
430 | return self.User |
---|
431 | elif name == "Printer" : |
---|
432 | self.Printer = self.parent.getPrinter(self.PrinterName) |
---|
433 | return self.Printer |
---|
434 | else : |
---|
435 | raise AttributeError, name |
---|
436 | |
---|
437 | class StorageLastJob(StorageJob) : |
---|
438 | """Printer's Last Job class.""" |
---|
439 | def __init__(self, parent, printer) : |
---|
440 | StorageJob.__init__(self, parent) |
---|
441 | self.PrinterName = printer.Name # not needed |
---|
442 | self.Printer = printer |
---|
443 | |
---|
444 | class StorageBillingCode(StorageObject) : |
---|
445 | """Billing code class.""" |
---|
446 | def __init__(self, parent, name) : |
---|
447 | StorageObject.__init__(self, parent) |
---|
448 | self.BillingCode = name |
---|
449 | self.PageCounter = None |
---|
450 | self.Balance = None |
---|
451 | |
---|
452 | def delete(self) : |
---|
453 | """Deletes the billing code from the database.""" |
---|
454 | self.parent.deleteBillingCode(self) |
---|
455 | self.parent.flushEntry("BILLINGCODES", self.BillingCode) |
---|
456 | self.isDirty = False |
---|
457 | self.Exists = False |
---|
458 | |
---|
459 | def reset(self, balance=0.0, pagecounter=0) : |
---|
460 | """Resets the pagecounter and balance for this billing code.""" |
---|
461 | self.Balance = balance |
---|
462 | self.PageCounter = pagecounter |
---|
463 | self.isDirty = True |
---|
464 | |
---|
465 | def consume(self, pages, price) : |
---|
466 | """Consumes some pages and credits for this billing code.""" |
---|
467 | if pages : |
---|
468 | self.parent.consumeBillingCode(self, pages, price) |
---|
469 | self.PageCounter += pages |
---|
470 | self.Balance -= price |
---|
471 | |
---|
472 | class BaseStorage : |
---|
473 | def __init__(self, pykotatool) : |
---|
474 | """Opens the storage connection.""" |
---|
475 | self.closed = 1 |
---|
476 | self.tool = pykotatool |
---|
477 | self.usecache = pykotatool.config.getCaching() |
---|
478 | self.disablehistory = pykotatool.config.getDisableHistory() |
---|
479 | self.privacy = pykotatool.config.getPrivacy() |
---|
480 | if self.privacy : |
---|
481 | pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.") |
---|
482 | if self.usecache : |
---|
483 | self.tool.logdebug("Caching enabled.") |
---|
484 | self.caches = { "USERS" : {}, \ |
---|
485 | "GROUPS" : {}, \ |
---|
486 | "PRINTERS" : {}, \ |
---|
487 | "USERPQUOTAS" : {}, \ |
---|
488 | "GROUPPQUOTAS" : {}, \ |
---|
489 | "JOBS" : {}, \ |
---|
490 | "LASTJOBS" : {}, \ |
---|
491 | "BILLINGCODES" : {} } |
---|
492 | |
---|
493 | def close(self) : |
---|
494 | """Must be overriden in children classes.""" |
---|
495 | raise RuntimeError, "BaseStorage.close() must be overriden !" |
---|
496 | |
---|
497 | def __del__(self) : |
---|
498 | """Ensures that the database connection is closed.""" |
---|
499 | self.close() |
---|
500 | |
---|
501 | def getFromCache(self, cachetype, key) : |
---|
502 | """Tries to extract something from the cache.""" |
---|
503 | if self.usecache : |
---|
504 | entry = self.caches[cachetype].get(key) |
---|
505 | if entry is not None : |
---|
506 | self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key)) |
---|
507 | else : |
---|
508 | self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key)) |
---|
509 | return entry |
---|
510 | |
---|
511 | def cacheEntry(self, cachetype, key, value) : |
---|
512 | """Puts an entry in the cache.""" |
---|
513 | if self.usecache and getattr(value, "Exists", 0) : |
---|
514 | self.caches[cachetype][key] = value |
---|
515 | self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key)) |
---|
516 | |
---|
517 | def flushEntry(self, cachetype, key) : |
---|
518 | """Removes an entry from the cache.""" |
---|
519 | if self.usecache : |
---|
520 | try : |
---|
521 | del self.caches[cachetype][key] |
---|
522 | except KeyError : |
---|
523 | pass |
---|
524 | else : |
---|
525 | self.tool.logdebug("Cache flush (%s->%s)" % (cachetype, key)) |
---|
526 | |
---|
527 | def getUser(self, username) : |
---|
528 | """Returns the user from cache.""" |
---|
529 | user = self.getFromCache("USERS", username) |
---|
530 | if user is None : |
---|
531 | user = self.getUserFromBackend(username) |
---|
532 | self.cacheEntry("USERS", username, user) |
---|
533 | return user |
---|
534 | |
---|
535 | def getGroup(self, groupname) : |
---|
536 | """Returns the group from cache.""" |
---|
537 | group = self.getFromCache("GROUPS", groupname) |
---|
538 | if group is None : |
---|
539 | group = self.getGroupFromBackend(groupname) |
---|
540 | self.cacheEntry("GROUPS", groupname, group) |
---|
541 | return group |
---|
542 | |
---|
543 | def getPrinter(self, printername) : |
---|
544 | """Returns the printer from cache.""" |
---|
545 | printer = self.getFromCache("PRINTERS", printername) |
---|
546 | if printer is None : |
---|
547 | printer = self.getPrinterFromBackend(printername) |
---|
548 | self.cacheEntry("PRINTERS", printername, printer) |
---|
549 | return printer |
---|
550 | |
---|
551 | def getUserPQuota(self, user, printer) : |
---|
552 | """Returns the user quota information from cache.""" |
---|
553 | useratprinter = "%s@%s" % (user.Name, printer.Name) |
---|
554 | upquota = self.getFromCache("USERPQUOTAS", useratprinter) |
---|
555 | if upquota is None : |
---|
556 | upquota = self.getUserPQuotaFromBackend(user, printer) |
---|
557 | self.cacheEntry("USERPQUOTAS", useratprinter, upquota) |
---|
558 | return upquota |
---|
559 | |
---|
560 | def getGroupPQuota(self, group, printer) : |
---|
561 | """Returns the group quota information from cache.""" |
---|
562 | groupatprinter = "%s@%s" % (group.Name, printer.Name) |
---|
563 | gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter) |
---|
564 | if gpquota is None : |
---|
565 | gpquota = self.getGroupPQuotaFromBackend(group, printer) |
---|
566 | self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota) |
---|
567 | return gpquota |
---|
568 | |
---|
569 | def getPrinterLastJob(self, printer) : |
---|
570 | """Extracts last job information for a given printer from cache.""" |
---|
571 | lastjob = self.getFromCache("LASTJOBS", printer.Name) |
---|
572 | if lastjob is None : |
---|
573 | lastjob = self.getPrinterLastJobFromBackend(printer) |
---|
574 | self.cacheEntry("LASTJOBS", printer.Name, lastjob) |
---|
575 | return lastjob |
---|
576 | |
---|
577 | def getBillingCode(self, label) : |
---|
578 | """Returns the user from cache.""" |
---|
579 | code = self.getFromCache("BILLINGCODES", label) |
---|
580 | if code is None : |
---|
581 | code = self.getBillingCodeFromBackend(label) |
---|
582 | self.cacheEntry("BILLINGCODES", label, code) |
---|
583 | return code |
---|
584 | |
---|
585 | def getParentPrinters(self, printer) : |
---|
586 | """Extracts parent printers information for a given printer from cache.""" |
---|
587 | if self.usecache : |
---|
588 | if not hasattr(printer, "Parents") : |
---|
589 | self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name) |
---|
590 | printer.Parents = self.getParentPrintersFromBackend(printer) |
---|
591 | self.tool.logdebug("Cache store (%s->Parents)" % printer.Name) |
---|
592 | else : |
---|
593 | self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name) |
---|
594 | else : |
---|
595 | printer.Parents = self.getParentPrintersFromBackend(printer) |
---|
596 | for parent in printer.Parents[:] : |
---|
597 | printer.Parents.extend(self.getParentPrinters(parent)) |
---|
598 | uniquedic = {} |
---|
599 | for parent in printer.Parents : |
---|
600 | uniquedic[parent.Name] = parent |
---|
601 | printer.Parents = uniquedic.values() |
---|
602 | return printer.Parents |
---|
603 | |
---|
604 | def getGroupMembers(self, group) : |
---|
605 | """Returns the group's members list from in-group cache.""" |
---|
606 | if self.usecache : |
---|
607 | if not hasattr(group, "Members") : |
---|
608 | self.tool.logdebug("Cache miss (%s->Members)" % group.Name) |
---|
609 | group.Members = self.getGroupMembersFromBackend(group) |
---|
610 | self.tool.logdebug("Cache store (%s->Members)" % group.Name) |
---|
611 | else : |
---|
612 | self.tool.logdebug("Cache hit (%s->Members)" % group.Name) |
---|
613 | else : |
---|
614 | group.Members = self.getGroupMembersFromBackend(group) |
---|
615 | return group.Members |
---|
616 | |
---|
617 | def getUserGroups(self, user) : |
---|
618 | """Returns the user's groups list from in-user cache.""" |
---|
619 | if self.usecache : |
---|
620 | if not hasattr(user, "Groups") : |
---|
621 | self.tool.logdebug("Cache miss (%s->Groups)" % user.Name) |
---|
622 | user.Groups = self.getUserGroupsFromBackend(user) |
---|
623 | self.tool.logdebug("Cache store (%s->Groups)" % user.Name) |
---|
624 | else : |
---|
625 | self.tool.logdebug("Cache hit (%s->Groups)" % user.Name) |
---|
626 | else : |
---|
627 | user.Groups = self.getUserGroupsFromBackend(user) |
---|
628 | return user.Groups |
---|
629 | |
---|
630 | def getParentPrintersUserPQuota(self, userpquota) : |
---|
631 | """Returns all user print quota on the printer and all its parents recursively.""" |
---|
632 | upquotas = [ ] |
---|
633 | for printer in self.getParentPrinters(userpquota.Printer) : |
---|
634 | upq = self.getUserPQuota(userpquota.User, printer) |
---|
635 | if upq.Exists : |
---|
636 | upquotas.append(upq) |
---|
637 | return upquotas |
---|
638 | |
---|
639 | def getParentPrintersGroupPQuota(self, grouppquota) : |
---|
640 | """Returns all group print quota on the printer and all its parents recursively.""" |
---|
641 | gpquotas = [ ] |
---|
642 | for printer in self.getParentPrinters(grouppquota.Printer) : |
---|
643 | gpq = self.getGroupPQuota(grouppquota.Group, printer) |
---|
644 | if gpq.Exists : |
---|
645 | gpquotas.append(gpq) |
---|
646 | return gpquotas |
---|
647 | |
---|
648 | def databaseToUserCharset(self, text) : |
---|
649 | """Converts from database format (UTF-8) to user's charset.""" |
---|
650 | return self.tool.UTF8ToUserCharset(text) |
---|
651 | |
---|
652 | def userCharsetToDatabase(self, text) : |
---|
653 | """Converts from user's charset to database format (UTF-8).""" |
---|
654 | return self.tool.userCharsetToUTF8(text) |
---|
655 | |
---|
656 | def cleanDates(self, startdate, enddate) : |
---|
657 | """Clean the dates to create a correct filter.""" |
---|
658 | if startdate : |
---|
659 | startdate = startdate.strip().lower() |
---|
660 | if enddate : |
---|
661 | enddate = enddate.strip().lower() |
---|
662 | if (not startdate) and (not enddate) : |
---|
663 | return (None, None) |
---|
664 | |
---|
665 | now = DateTime.now() |
---|
666 | nameddates = ('yesterday', 'today', 'now', 'tomorrow') |
---|
667 | datedict = { "start" : startdate, "end" : enddate } |
---|
668 | for limit in datedict.keys() : |
---|
669 | dateval = datedict[limit] |
---|
670 | if dateval : |
---|
671 | for name in nameddates : |
---|
672 | if dateval.startswith(name) : |
---|
673 | try : |
---|
674 | offset = int(dateval[len(name):]) |
---|
675 | except : |
---|
676 | offset = 0 |
---|
677 | dateval = dateval[:len(name)] |
---|
678 | if limit == "start" : |
---|
679 | if dateval == "yesterday" : |
---|
680 | dateval = (now - 1 + offset).Format("%Y%m%d000000") |
---|
681 | elif dateval == "today" : |
---|
682 | dateval = (now + offset).Format("%Y%m%d000000") |
---|
683 | elif dateval == "now" : |
---|
684 | dateval = (now + offset).Format("%Y%m%d%H%M%S") |
---|
685 | else : # tomorrow |
---|
686 | dateval = (now + 1 + offset).Format("%Y%m%d000000") |
---|
687 | else : |
---|
688 | if dateval == "yesterday" : |
---|
689 | dateval = (now - 1 + offset).Format("%Y%m%d235959") |
---|
690 | elif dateval == "today" : |
---|
691 | dateval = (now + offset).Format("%Y%m%d235959") |
---|
692 | elif dateval == "now" : |
---|
693 | dateval = (now + offset).Format("%Y%m%d%H%M%S") |
---|
694 | else : # tomorrow |
---|
695 | dateval = (now + 1 + offset).Format("%Y%m%d235959") |
---|
696 | break |
---|
697 | |
---|
698 | if not dateval.isdigit() : |
---|
699 | dateval = None |
---|
700 | else : |
---|
701 | lgdateval = len(dateval) |
---|
702 | if lgdateval == 4 : |
---|
703 | if limit == "start" : |
---|
704 | dateval = "%s0101 00:00:00" % dateval |
---|
705 | else : |
---|
706 | dateval = "%s1231 23:59:59" % dateval |
---|
707 | elif lgdateval == 6 : |
---|
708 | if limit == "start" : |
---|
709 | dateval = "%s01 00:00:00" % dateval |
---|
710 | else : |
---|
711 | mxdate = DateTime.ISO.ParseDateTime("%s01 00:00:00" % dateval) |
---|
712 | dateval = "%s%02i 23:59:59" % (dateval, mxdate.days_in_month) |
---|
713 | elif lgdateval == 8 : |
---|
714 | if limit == "start" : |
---|
715 | dateval = "%s 00:00:00" % dateval |
---|
716 | else : |
---|
717 | dateval = "%s 23:59:59" % dateval |
---|
718 | elif lgdateval == 10 : |
---|
719 | if limit == "start" : |
---|
720 | dateval = "%s %s:00:00" % (dateval[:8], dateval[8:]) |
---|
721 | else : |
---|
722 | dateval = "%s %s:59:59" % (dateval[:8], dateval[8:]) |
---|
723 | elif lgdateval == 12 : |
---|
724 | if limit == "start" : |
---|
725 | dateval = "%s %s:%s:00" % (dateval[:8], dateval[8:10], dateval[10:]) |
---|
726 | else : |
---|
727 | dateval = "%s %s:%s:59" % (dateval[:8], dateval[8:10], dateval[10:]) |
---|
728 | elif lgdateval == 14 : |
---|
729 | dateval = "%s %s:%s:%s" % (dateval[:8], dateval[8:10], dateval[10:12], dateval[12:]) |
---|
730 | else : |
---|
731 | dateval = None |
---|
732 | try : |
---|
733 | DateTime.ISO.ParseDateTime(dateval) |
---|
734 | except : |
---|
735 | dateval = None |
---|
736 | datedict[limit] = dateval |
---|
737 | (start, end) = (datedict["start"], datedict["end"]) |
---|
738 | if start and end and (start > end) : |
---|
739 | (start, end) = (end, start) |
---|
740 | return (start, end) |
---|
741 | |
---|
742 | def openConnection(pykotatool) : |
---|
743 | """Returns a connection handle to the appropriate database.""" |
---|
744 | backendinfo = pykotatool.config.getStorageBackend() |
---|
745 | backend = backendinfo["storagebackend"] |
---|
746 | try : |
---|
747 | exec "from pykota.storages import %s as storagebackend" % backend.lower() |
---|
748 | except ImportError : |
---|
749 | raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend |
---|
750 | else : |
---|
751 | host = backendinfo["storageserver"] |
---|
752 | database = backendinfo["storagename"] |
---|
753 | admin = backendinfo["storageadmin"] or backendinfo["storageuser"] |
---|
754 | adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"] |
---|
755 | return storagebackend.Storage(pykotatool, host, database, admin, adminpw) |
---|