root / pykota / trunk / pykota / storage.py @ 3260

Revision 3260, 36.4 kB (checked in by jerome, 16 years ago)

Changed license to GNU GPL v3 or later.
Changed Python source encoding from ISO-8859-15 to UTF-8 (only ASCII
was used anyway).

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