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