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