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

Revision 2147, 25.1 kB (checked in by jerome, 19 years ago)

Removed all references to $Log$

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
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.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23#
24
25class PyKotaStorageError(Exception):
26    """An exception for Quota Storage related stuff."""
27    def __init__(self, message = ""):
28        self.message = message
29        Exception.__init__(self, message)
30    def __repr__(self):
31        return self.message
32    __str__ = __repr__
33       
34class StorageObject :
35    """Object present in the Quota Storage."""
36    def __init__(self, parent) :
37        "Initialize minimal data."""
38        self.parent = parent
39        self.ident = None
40        self.Exists = 0
41       
42class StorageUser(StorageObject) :       
43    """User class."""
44    def __init__(self, parent, name) :
45        StorageObject.__init__(self, parent)
46        self.Name = name
47        self.LimitBy = None
48        self.AccountBalance = None
49        self.LifeTimePaid = None
50        self.Email = None
51        self.OverCharge = 1.0
52        self.Payments = [] # TODO : maybe handle this smartly for SQL, for now just don't retrieve them
53       
54    def consumeAccountBalance(self, amount) :     
55        """Consumes an amount of money from the user's account balance."""
56        self.parent.decreaseUserAccountBalance(self, amount)
57        self.AccountBalance = float(self.AccountBalance or 0.0) - amount
58       
59    def setAccountBalance(self, balance, lifetimepaid) :   
60        """Sets the user's account balance in case he pays more money."""
61        diff = float(lifetimepaid or 0.0) - float(self.LifeTimePaid or 0.0)
62        self.parent.beginTransaction()
63        try :
64            self.parent.writeUserAccountBalance(self, balance, lifetimepaid)
65            self.parent.writeNewPayment(self, diff)
66        except PyKotaStorageError, msg :   
67            self.parent.rollbackTransaction()
68            raise PyKotaStorageError, msg
69        else :   
70            self.parent.commitTransaction()
71            self.AccountBalance = balance
72            self.LifeTimePaid = lifetimepaid
73       
74    def setLimitBy(self, limitby) :   
75        """Sets the user's limiting factor."""
76        try :
77            limitby = limitby.lower()
78        except AttributeError :   
79            limitby = "quota"
80        if limitby in ["quota", "balance", "quota-then-balance", "balance-then-quota"] :
81            self.parent.writeUserLimitBy(self, limitby)
82            self.LimitBy = limitby
83       
84    def setOverChargeFactor(self, factor) :   
85        """Sets the user's overcharging coefficient."""
86        self.parent.writeUserOverCharge(self, factor)
87        self.OverCharge = factor
88       
89    def delete(self) :   
90        """Deletes an user from the Quota Storage."""
91        self.parent.beginTransaction()
92        try :
93            self.parent.deleteUser(self)
94        except PyKotaStorageError, msg :   
95            self.parent.rollbackTransaction()
96            raise PyKotaStorageError, msg
97        else :   
98            self.parent.commitTransaction()
99       
100class StorageGroup(StorageObject) :       
101    """User class."""
102    def __init__(self, parent, name) :
103        StorageObject.__init__(self, parent)
104        self.Name = name
105        self.LimitBy = None
106        self.AccountBalance = None
107        self.LifeTimePaid = None
108       
109    def setLimitBy(self, limitby) :   
110        """Sets the user's limiting factor."""
111        try :
112            limitby = limitby.lower()
113        except AttributeError :   
114            limitby = "quota"
115        if limitby in ["quota", "balance"] :
116            self.parent.writeGroupLimitBy(self, limitby)
117            self.LimitBy = limitby
118       
119    def delete(self) :   
120        """Deletes a group from the Quota Storage."""
121        self.parent.beginTransaction()
122        try :
123            self.parent.deleteGroup(self)
124        except PyKotaStorageError, msg :   
125            self.parent.rollbackTransaction()
126            raise PyKotaStorageError, msg
127        else :   
128            self.parent.commitTransaction()
129       
130class StoragePrinter(StorageObject) :
131    """Printer class."""
132    def __init__(self, parent, name) :
133        StorageObject.__init__(self, parent)
134        self.Name = name
135        self.PricePerPage = None
136        self.PricePerJob = None
137        self.Description = None
138        self.Coefficients = None
139       
140    def __getattr__(self, name) :   
141        """Delays data retrieval until it's really needed."""
142        if name == "LastJob" : 
143            self.LastJob = self.parent.getPrinterLastJob(self)
144            return self.LastJob
145        else :
146            raise AttributeError, name
147           
148    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) :
149        """Adds a job to the printer's history."""
150        self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, clienthost, jobsizebytes, jobmd5sum)
151        # TODO : update LastJob object ? Probably not needed.
152       
153    def addPrinterToGroup(self, printer) :   
154        """Adds a printer to a printer group."""
155        if (printer not in self.parent.getParentPrinters(self)) and (printer.ident != self.ident) :
156            self.parent.writePrinterToGroup(self, printer)
157            # TODO : reset cached value for printer parents, or add new parent to cached value
158           
159    def delPrinterFromGroup(self, printer) :   
160        """Deletes a printer from a printer group."""
161        self.parent.removePrinterFromGroup(self, printer)
162        # TODO : reset cached value for printer parents, or add new parent to cached value
163       
164    def setPrices(self, priceperpage = None, priceperjob = None) :   
165        """Sets the printer's prices."""
166        if priceperpage is None :
167            priceperpage = self.PricePerPage or 0.0
168        else :   
169            self.PricePerPage = float(priceperpage)
170        if priceperjob is None :   
171            priceperjob = self.PricePerJob or 0.0
172        else :   
173            self.PricePerJob = float(priceperjob)
174        self.parent.writePrinterPrices(self)
175       
176    def setDescription(self, description = None) :   
177        """Sets the printer's prices."""
178        if description is None :
179            description = self.Description
180        else :   
181            self.Description = str(description)
182        self.parent.writePrinterDescription(self)
183       
184    def delete(self) :   
185        """Deletes a printer from the Quota Storage."""
186        self.parent.beginTransaction()
187        try :
188            self.parent.deletePrinter(self)
189        except PyKotaStorageError, msg :   
190            self.parent.rollbackTransaction()
191            raise PyKotaStorageError, msg
192        else :   
193            self.parent.commitTransaction()
194       
195class StorageUserPQuota(StorageObject) :
196    """User Print Quota class."""
197    def __init__(self, parent, user, printer) :
198        StorageObject.__init__(self, parent)
199        self.User = user
200        self.Printer = printer
201        self.PageCounter = None
202        self.LifePageCounter = None
203        self.SoftLimit = None
204        self.HardLimit = None
205        self.DateLimit = None
206        self.WarnCount = None
207       
208    def __getattr__(self, name) :   
209        """Delays data retrieval until it's really needed."""
210        if name == "ParentPrintersUserPQuota" : 
211            self.ParentPrintersUserPQuota = (self.User.Exists and self.Printer.Exists and self.parent.getParentPrintersUserPQuota(self)) or []
212            return self.ParentPrintersUserPQuota
213        else :
214            raise AttributeError, name
215       
216    def setDateLimit(self, datelimit) :   
217        """Sets the date limit for this quota."""
218        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
219        self.parent.writeUserPQuotaDateLimit(self, date)
220        self.DateLimit = date
221       
222    def setLimits(self, softlimit, hardlimit) :   
223        """Sets the soft and hard limit for this quota."""
224        self.parent.writeUserPQuotaLimits(self, softlimit, hardlimit)
225        self.SoftLimit = softlimit
226        self.HardLimit = hardlimit
227        self.DateLimit = None
228        self.WarnCount = 0
229       
230    def setUsage(self, used) :
231        """Sets the PageCounter and LifePageCounter to used, or if used is + or - prefixed, changes the values of {Life,}PageCounter by that amount."""
232        vused = int(used)
233        if used.startswith("+") or used.startswith("-") :
234            self.parent.beginTransaction()
235            try :
236                self.parent.increaseUserPQuotaPagesCounters(self, vused)
237                self.parent.writeUserPQuotaDateLimit(self, None)
238                self.parent.writeUserPQuotaWarnCount(self, 0)
239            except PyKotaStorageError, msg :   
240                self.parent.rollbackTransaction()
241                raise PyKotaStorageError, msg
242            else :
243                self.parent.commitTransaction()
244            self.PageCounter += vused
245            self.LifePageCounter += vused
246        else :
247            self.parent.writeUserPQuotaPagesCounters(self, vused, vused)
248            self.PageCounter = self.LifePageCounter = vused
249        self.DateLimit = None
250        self.WarnCount = 0
251
252    def incDenyBannerCounter(self) :
253        """Increment the deny banner counter for this user quota."""
254        self.parent.increaseUserPQuotaWarnCount(self)
255        self.WarnCount = (self.WarnCount or 0) + 1
256       
257    def resetDenyBannerCounter(self) :
258        """Resets the deny banner counter for this user quota."""
259        self.parent.writeUserPQuotaWarnCount(self, 0)
260        self.WarnCount = 0
261       
262    def reset(self) :   
263        """Resets page counter to 0."""
264        self.parent.writeUserPQuotaPagesCounters(self, 0, int(self.LifePageCounter or 0))
265        self.PageCounter = 0
266        self.DateLimit = None
267       
268    def hardreset(self) :   
269        """Resets actual and life time page counters to 0."""
270        self.parent.writeUserPQuotaPagesCounters(self, 0, 0)
271        self.PageCounter = self.LifePageCounter = 0
272        self.DateLimit = None
273       
274    def computeJobPrice(self, jobsize) :   
275        """Computes the job price as the sum of all parent printers' prices + current printer's ones."""
276        totalprice = 0.0   
277        if jobsize :
278            if self.User.OverCharge != 0.0 :    # optimization, but TODO : beware of rounding errors
279                for upq in [ self ] + self.ParentPrintersUserPQuota :
280                    price = (float(upq.Printer.PricePerPage or 0.0) * jobsize) + float(upq.Printer.PricePerJob or 0.0)
281                    totalprice += price
282        if self.User.OverCharge != 1.0 : # TODO : beware of rounding errors
283            overcharged = totalprice * self.User.OverCharge       
284            self.parent.tool.printInfo("Overcharging %s by a factor of %s ===> User %s will be charged for %s units." % (totalprice, self.User.OverCharge, self.User.Name, overcharged))
285            return overcharged
286        else :   
287            return totalprice
288           
289    def increasePagesUsage(self, jobsize) :
290        """Increase the value of used pages and money."""
291        jobprice = self.computeJobPrice(jobsize)
292        if jobsize :
293            self.parent.beginTransaction()
294            try :
295                if jobprice :
296                    self.User.consumeAccountBalance(jobprice)
297                for upq in [ self ] + self.ParentPrintersUserPQuota :
298                    self.parent.increaseUserPQuotaPagesCounters(upq, jobsize)
299                    upq.PageCounter = int(upq.PageCounter or 0) + jobsize
300                    upq.LifePageCounter = int(upq.LifePageCounter or 0) + jobsize
301            except PyKotaStorageError, msg :   
302                self.parent.rollbackTransaction()
303                raise PyKotaStorageError, msg
304            else :   
305                self.parent.commitTransaction()
306        return jobprice
307       
308class StorageGroupPQuota(StorageObject) :
309    """Group Print Quota class."""
310    def __init__(self, parent, group, printer) :
311        StorageObject.__init__(self, parent)
312        self.Group = group
313        self.Printer = printer
314        self.PageCounter = None
315        self.LifePageCounter = None
316        self.SoftLimit = None
317        self.HardLimit = None
318        self.DateLimit = None
319       
320    def __getattr__(self, name) :   
321        """Delays data retrieval until it's really needed."""
322        if name == "ParentPrintersGroupPQuota" : 
323            self.ParentPrintersGroupPQuota = (self.Group.Exists and self.Printer.Exists and self.parent.getParentPrintersGroupPQuota(self)) or []
324            return self.ParentPrintersGroupPQuota
325        else :
326            raise AttributeError, name
327       
328    def reset(self) :   
329        """Resets page counter to 0."""
330        self.parent.beginTransaction()
331        try :
332            for user in self.parent.getGroupMembers(self.Group) :
333                uq = self.parent.getUserPQuota(user, self.Printer)
334                uq.reset()
335            self.parent.writeGroupPQuotaDateLimit(self, None)
336        except PyKotaStorageError, msg :   
337            self.parent.rollbackTransaction()
338            raise PyKotaStorageError, msg
339        else :   
340            self.parent.commitTransaction()
341        self.PageCounter = 0
342        self.DateLimit = None
343       
344    def hardreset(self) :   
345        """Resets actual and life time page counters to 0."""
346        self.parent.beginTransaction()
347        try :
348            for user in self.parent.getGroupMembers(self.Group) :
349                uq = self.parent.getUserPQuota(user, self.Printer)
350                uq.hardreset()
351            self.parent.writeGroupPQuotaDateLimit(self, None)
352        except PyKotaStorageError, msg :   
353            self.parent.rollbackTransaction()
354            raise PyKotaStorageError, msg
355        else :   
356            self.parent.commitTransaction()
357        self.PageCounter = self.LifePageCounter = 0
358        self.DateLimit = None
359       
360    def setDateLimit(self, datelimit) :   
361        """Sets the date limit for this quota."""
362        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
363        self.parent.writeGroupPQuotaDateLimit(self, date)
364        self.DateLimit = date
365       
366    def setLimits(self, softlimit, hardlimit) :   
367        """Sets the soft and hard limit for this quota."""
368        self.parent.writeGroupPQuotaLimits(self, softlimit, hardlimit)
369        self.SoftLimit = softlimit
370        self.HardLimit = hardlimit
371        self.DateLimit = None
372       
373class StorageJob(StorageObject) :
374    """Printer's Job class."""
375    def __init__(self, parent) :
376        StorageObject.__init__(self, parent)
377        self.UserName = None
378        self.PrinterName = None
379        self.JobId = None
380        self.PrinterPageCounter = None
381        self.JobSizeBytes = None
382        self.JobSize = None
383        self.JobAction = None
384        self.JobDate = None
385        self.JobPrice = None
386        self.JobFileName = None
387        self.JobTitle = None
388        self.JobCopies = None
389        self.JobOptions = None
390        self.JobHostName = None
391        self.JobMD5Sum = None
392        self.JobPages = None
393        self.JobBillingCode = None
394       
395    def __getattr__(self, name) :   
396        """Delays data retrieval until it's really needed."""
397        if name == "User" : 
398            self.User = self.parent.getUser(self.UserName)
399            return self.User
400        elif name == "Printer" :   
401            self.Printer = self.parent.getPrinter(self.PrinterName)
402            return self.Printer
403        else :
404            raise AttributeError, name
405       
406class StorageLastJob(StorageJob) :
407    """Printer's Last Job class."""
408    def __init__(self, parent, printer) :
409        StorageJob.__init__(self, parent)
410        self.PrinterName = printer.Name # not needed
411        self.Printer = printer
412       
413class BaseStorage :
414    def __init__(self, pykotatool) :
415        """Opens the storage connection."""
416        self.closed = 1
417        self.tool = pykotatool
418        self.usecache = pykotatool.config.getCaching()
419        self.disablehistory = pykotatool.config.getDisableHistory()
420        self.privacy = pykotatool.config.getPrivacy()
421        if self.privacy :
422            pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.")
423        if self.usecache :
424            self.tool.logdebug("Caching enabled.")
425            self.caches = { "USERS" : {}, "GROUPS" : {}, "PRINTERS" : {}, "USERPQUOTAS" : {}, "GROUPPQUOTAS" : {}, "JOBS" : {}, "LASTJOBS" : {} }
426       
427    def close(self) :   
428        """Must be overriden in children classes."""
429        raise RuntimeError, "BaseStorage.close() must be overriden !"
430       
431    def __del__(self) :       
432        """Ensures that the database connection is closed."""
433        self.close()
434       
435    def getFromCache(self, cachetype, key) :
436        """Tries to extract something from the cache."""
437        if self.usecache :
438            entry = self.caches[cachetype].get(key)
439            if entry is not None :
440                self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key))
441            else :   
442                self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key))
443            return entry   
444           
445    def cacheEntry(self, cachetype, key, value) :       
446        """Puts an entry in the cache."""
447        if self.usecache and getattr(value, "Exists", 0) :
448            self.caches[cachetype][key] = value
449            self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key))
450           
451    def getUser(self, username) :       
452        """Returns the user from cache."""
453        user = self.getFromCache("USERS", username)
454        if user is None :
455            user = self.getUserFromBackend(username)
456            self.cacheEntry("USERS", username, user)
457        return user   
458       
459    def getGroup(self, groupname) :       
460        """Returns the group from cache."""
461        group = self.getFromCache("GROUPS", groupname)
462        if group is None :
463            group = self.getGroupFromBackend(groupname)
464            self.cacheEntry("GROUPS", groupname, group)
465        return group   
466       
467    def getPrinter(self, printername) :       
468        """Returns the printer from cache."""
469        printer = self.getFromCache("PRINTERS", printername)
470        if printer is None :
471            printer = self.getPrinterFromBackend(printername)
472            self.cacheEntry("PRINTERS", printername, printer)
473        return printer   
474       
475    def getUserPQuota(self, user, printer) :       
476        """Returns the user quota information from cache."""
477        useratprinter = "%s@%s" % (user.Name, printer.Name)
478        upquota = self.getFromCache("USERPQUOTAS", useratprinter)
479        if upquota is None :
480            upquota = self.getUserPQuotaFromBackend(user, printer)
481            self.cacheEntry("USERPQUOTAS", useratprinter, upquota)
482        return upquota   
483       
484    def getGroupPQuota(self, group, printer) :       
485        """Returns the group quota information from cache."""
486        groupatprinter = "%s@%s" % (group.Name, printer.Name)
487        gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter)
488        if gpquota is None :
489            gpquota = self.getGroupPQuotaFromBackend(group, printer)
490            self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota)
491        return gpquota   
492       
493    def getPrinterLastJob(self, printer) :       
494        """Extracts last job information for a given printer from cache."""
495        lastjob = self.getFromCache("LASTJOBS", printer.Name)
496        if lastjob is None :
497            lastjob = self.getPrinterLastJobFromBackend(printer)
498            self.cacheEntry("LASTJOBS", printer.Name, lastjob)
499        return lastjob   
500       
501    def getParentPrinters(self, printer) :   
502        """Extracts parent printers information for a given printer from cache."""
503        if self.usecache :
504            if not hasattr(printer, "Parents") :
505                self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name)
506                printer.Parents = self.getParentPrintersFromBackend(printer)
507                self.tool.logdebug("Cache store (%s->Parents)" % printer.Name)
508            else :
509                self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name)
510        else :       
511            printer.Parents = self.getParentPrintersFromBackend(printer)
512        for parent in printer.Parents[:] :   
513            printer.Parents.extend(self.getParentPrinters(parent))
514        uniquedic = {}   
515        for parent in printer.Parents :
516            uniquedic[parent.Name] = parent
517        printer.Parents = uniquedic.values()   
518        return printer.Parents
519       
520    def getGroupMembers(self, group) :       
521        """Returns the group's members list from in-group cache."""
522        if self.usecache :
523            if not hasattr(group, "Members") :
524                self.tool.logdebug("Cache miss (%s->Members)" % group.Name)
525                group.Members = self.getGroupMembersFromBackend(group)
526                self.tool.logdebug("Cache store (%s->Members)" % group.Name)
527            else :
528                self.tool.logdebug("Cache hit (%s->Members)" % group.Name)
529        else :       
530            group.Members = self.getGroupMembersFromBackend(group)
531        return group.Members   
532       
533    def getUserGroups(self, user) :       
534        """Returns the user's groups list from in-user cache."""
535        if self.usecache :
536            if not hasattr(user, "Groups") :
537                self.tool.logdebug("Cache miss (%s->Groups)" % user.Name)
538                user.Groups = self.getUserGroupsFromBackend(user)
539                self.tool.logdebug("Cache store (%s->Groups)" % user.Name)
540            else :
541                self.tool.logdebug("Cache hit (%s->Groups)" % user.Name)
542        else :       
543            user.Groups = self.getUserGroupsFromBackend(user)
544        return user.Groups   
545       
546    def getParentPrintersUserPQuota(self, userpquota) :     
547        """Returns all user print quota on the printer and all its parents recursively."""
548        upquotas = [ ]
549        for printer in self.getParentPrinters(userpquota.Printer) :
550            upq = self.getUserPQuota(userpquota.User, printer)
551            if upq.Exists :
552                upquotas.append(upq)
553        return upquotas       
554       
555    def getParentPrintersGroupPQuota(self, grouppquota) :     
556        """Returns all group print quota on the printer and all its parents recursively."""
557        gpquotas = [ ]
558        for printer in self.getParentPrinters(grouppquota.Printer) :
559            gpq = self.getGroupPQuota(grouppquota.Group, printer)
560            if gpq.Exists :
561                gpquotas.append(gpq)
562        return gpquotas       
563       
564    def databaseToUserCharset(self, text) :
565        """Converts from database format (UTF-8) to user's charset."""
566        if text is not None :
567            try :
568                return unicode(text, "UTF-8").encode(self.tool.getCharset()) 
569            except UnicodeError :   
570                try :
571                    # Incorrect locale settings ?
572                    return unicode(text, "UTF-8").encode("ISO-8859-15") 
573                except UnicodeError :   
574                    pass
575        return text
576       
577    def userCharsetToDatabase(self, text) :
578        """Converts from user's charset to database format (UTF-8)."""
579        if text is not None :
580            try :
581                return unicode(text, self.tool.getCharset()).encode("UTF-8") 
582            except UnicodeError :   
583                try :
584                    # Incorrect locale settings ?
585                    return unicode(text, "ISO-8859-15").encode("UTF-8") 
586                except UnicodeError :   
587                    pass
588        return text
589       
590def openConnection(pykotatool) :
591    """Returns a connection handle to the appropriate Quota Storage Database."""
592    backendinfo = pykotatool.config.getStorageBackend()
593    backend = backendinfo["storagebackend"]
594    try :
595        exec "from pykota.storages import %s as storagebackend" % backend.lower()
596    except ImportError :
597        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
598    else :   
599        host = backendinfo["storageserver"]
600        database = backendinfo["storagename"]
601        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
602        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
603        return storagebackend.Storage(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.