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