root / pykota / branches / 1.26_fixes / pykota / storage.py @ 3444

Revision 3444, 35.2 kB (checked in by jerome, 15 years ago)

Doesn't break when there's an error retrieving the login name (when run
through sudo). Fixes #29.

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