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

Revision 3445, 34.8 kB (checked in by jerome, 16 years ago)

Ported code from the 1.26_fixes branch. References #29.

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