root / pykota / trunk / pykota / storages / pgstorage.py @ 1137

Revision 1137, 22.6 kB (checked in by jalet, 21 years ago)

More work on caching

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2#
3# PyKota : Print Quotas for CUPS and LPRng
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
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
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19#
20# $Id$
21#
22# $Log$
23# Revision 1.17  2003/10/06 13:12:28  jalet
24# More work on caching
25#
26# Revision 1.16  2003/10/03 18:01:49  jalet
27# Nothing interesting...
28#
29# Revision 1.15  2003/10/03 12:27:03  jalet
30# Several optimizations, especially with LDAP backend
31#
32# Revision 1.14  2003/10/03 08:57:55  jalet
33# Caching mechanism now caches all that's cacheable.
34#
35# Revision 1.13  2003/10/02 20:23:18  jalet
36# Storage caching mechanism added.
37#
38# Revision 1.12  2003/08/17 14:20:25  jalet
39# Bug fix by Oleg Biteryakov
40#
41# Revision 1.11  2003/07/29 20:55:17  jalet
42# 1.14 is out !
43#
44# Revision 1.10  2003/07/16 21:53:08  jalet
45# Really big modifications wrt new configuration file's location and content.
46#
47# Revision 1.9  2003/07/14 17:20:15  jalet
48# Bug in postgresql storage when modifying the prices for a printer
49#
50# Revision 1.8  2003/07/14 14:18:17  jalet
51# Wrong documentation strings
52#
53# Revision 1.7  2003/07/09 20:17:07  jalet
54# Email field added to PostgreSQL schema
55#
56# Revision 1.6  2003/07/07 11:49:24  jalet
57# Lots of small fixes with the help of PyChecker
58#
59# Revision 1.5  2003/07/07 08:33:19  jalet
60# Bug fix due to a typo in LDAP code
61#
62# Revision 1.4  2003/06/30 13:54:21  jalet
63# Sorts by user / group name
64#
65# Revision 1.3  2003/06/25 14:10:01  jalet
66# Hey, it may work (edpykota --reset excepted) !
67#
68# Revision 1.2  2003/06/12 21:09:57  jalet
69# wrongly placed code.
70#
71# Revision 1.1  2003/06/10 16:37:54  jalet
72# Deletion of the second user which is not needed anymore.
73# Added a debug configuration field in /etc/pykota.conf
74# All queries can now be sent to the logger in debug mode, this will
75# greatly help improve performance when time for this will come.
76#
77#
78#
79#
80
81from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
82
83try :
84    import pg
85except ImportError :   
86    import sys
87    # TODO : to translate or not to translate ?
88    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
89
90class Storage(BaseStorage) :
91    def __init__(self, pykotatool, host, dbname, user, passwd) :
92        """Opens the PostgreSQL database connection."""
93        BaseStorage.__init__(self, pykotatool)
94        try :
95            (host, port) = host.split(":")
96            port = int(port)
97        except ValueError :   
98            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
99       
100        try :
101            self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
102        except pg.error, msg :
103            raise PyKotaStorageError, msg
104        else :   
105            self.closed = 0
106            self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
107           
108    def close(self) :   
109        """Closes the database connection."""
110        if not self.closed :
111            self.database.close()
112            self.closed = 1
113            self.tool.logdebug("Database closed.")
114       
115    def beginTransaction(self) :   
116        """Starts a transaction."""
117        self.database.query("BEGIN;")
118        self.tool.logdebug("Transaction begins...")
119       
120    def commitTransaction(self) :   
121        """Commits a transaction."""
122        self.database.query("COMMIT;")
123        self.tool.logdebug("Transaction committed.")
124       
125    def rollbackTransaction(self) :     
126        """Rollbacks a transaction."""
127        self.database.query("ROLLBACK;")
128        self.tool.logdebug("Transaction aborted.")
129       
130    def doSearch(self, query) :
131        """Does a search query."""
132        query = query.strip()   
133        if not query.endswith(';') :   
134            query += ';'
135        try :
136            self.tool.logdebug("QUERY : %s" % query)
137            result = self.database.query(query)
138        except pg.error, msg :   
139            raise PyKotaStorageError, msg
140        else :   
141            if (result is not None) and (result.ntuples() > 0) : 
142                return result.dictresult()
143           
144    def doModify(self, query) :
145        """Does a (possibly multiple) modify query."""
146        query = query.strip()   
147        if not query.endswith(';') :   
148            query += ';'
149        try :
150            self.tool.logdebug("QUERY : %s" % query)
151            result = self.database.query(query)
152        except pg.error, msg :   
153            raise PyKotaStorageError, msg
154        else :   
155            return result
156           
157    def doQuote(self, field) :
158        """Quotes a field for use as a string in SQL queries."""
159        if type(field) == type(0.0) : 
160            typ = "decimal"
161        elif type(field) == type(0) :   
162            typ = "int"
163        else :   
164            typ = "text"
165        return pg._quote(field, typ)
166       
167    def getUserFromBackend(self, username) :   
168        """Extracts user information given its name."""
169        user = StorageUser(self, username)
170        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
171        if result :
172            fields = result[0]
173            user.ident = fields.get("id")
174            user.LimitBy = fields.get("limitby")
175            user.AccountBalance = fields.get("balance")
176            user.LifeTimePaid = fields.get("lifetimepaid")
177            user.Email = fields.get("email")
178            user.Exists = 1
179        return user
180       
181    def getGroupFromBackend(self, groupname) :   
182        """Extracts group information given its name."""
183        group = StorageGroup(self, groupname)
184        result = self.doSearch("SELECT * FROM groups WHERE groupname=%s LIMIT 1" % self.doQuote(groupname))
185        if result :
186            fields = result[0]
187            group.ident = fields.get("id")
188            group.LimitBy = fields.get("limitby")
189            result = self.doSearch("SELECT SUM(balance) AS balance, SUM(lifetimepaid) AS lifetimepaid FROM users WHERE id IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(group.ident))
190            if result :
191                fields = result[0]
192                group.AccountBalance = fields.get("balance")
193                group.LifeTimePaid = fields.get("lifetimepaid")
194            group.Exists = 1
195        return group
196       
197    def getPrinterFromBackend(self, printername) :       
198        """Extracts printer information given its name."""
199        printer = StoragePrinter(self, printername)
200        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
201        if result :
202            fields = result[0]
203            printer.ident = fields.get("id")
204            printer.PricePerJob = fields.get("priceperjob")
205            printer.PricePerPage = fields.get("priceperpage")
206            printer.LastJob = self.getPrinterLastJob(printer)
207            printer.Exists = 1
208        return printer   
209       
210    def getUserPQuotaFromBackend(self, user, printer) :       
211        """Extracts a user print quota."""
212        userpquota = StorageUserPQuota(self, user, printer)
213        if user.Exists :
214            result = self.doSearch("SELECT id, lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
215            if result :
216                fields = result[0]
217                userpquota.ident = fields.get("id")
218                userpquota.PageCounter = fields.get("pagecounter")
219                userpquota.LifePageCounter = fields.get("lifepagecounter")
220                userpquota.SoftLimit = fields.get("softlimit")
221                userpquota.HardLimit = fields.get("hardlimit")
222                userpquota.DateLimit = fields.get("datelimit")
223                userpquota.Exists = 1
224        return userpquota
225       
226    def getGroupPQuotaFromBackend(self, group, printer) :       
227        """Extracts a group print quota."""
228        grouppquota = StorageGroupPQuota(self, group, printer)
229        if group.Exists :
230            result = self.doSearch("SELECT id, softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
231            if result :
232                fields = result[0]
233                grouppquota.ident = fields.get("id")
234                grouppquota.SoftLimit = fields.get("softlimit")
235                grouppquota.HardLimit = fields.get("hardlimit")
236                grouppquota.DateLimit = fields.get("datelimit")
237                result = self.doSearch("SELECT SUM(lifepagecounter) AS lifepagecounter, SUM(pagecounter) AS pagecounter FROM userpquota WHERE printerid=%s AND userid IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % (self.doQuote(printer.ident), self.doQuote(group.ident)))
238                if result :
239                    fields = result[0]
240                    grouppquota.PageCounter = fields.get("pagecounter")
241                    grouppquota.LifePageCounter = fields.get("lifepagecounter")
242                grouppquota.Exists = 1
243        return grouppquota
244       
245    def getPrinterLastJobFromBackend(self, printer) :       
246        """Extracts a printer's last job information."""
247        lastjob = StorageLastJob(self, printer)
248        result = self.doSearch("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize, jobdate FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printer.ident))
249        if result :
250            fields = result[0]
251            lastjob.ident = fields.get("id")
252            lastjob.JobId = fields.get("jobid")
253            lastjob.User = self.getUser(fields.get("username"))
254            lastjob.PrinterPageCounter = fields.get("pagecounter")
255            lastjob.JobSize = fields.get("jobsize")
256            lastjob.JobAction = fields.get("action")
257            lastjob.JobDate = fields.get("jobdate")
258            lastjob.Exists = 1
259        return lastjob
260           
261    def getGroupMembersFromBackend(self, group) :       
262        """Returns the group's members list."""
263        groupmembers = []
264        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
265        if result :
266            for record in result :
267                user = StorageUser(self, record.get("username"))
268                user.ident = record.get("userid")
269                user.LimitBy = record.get("limitby")
270                user.AccountBalance = record.get("balance")
271                user.LifeTimePaid = record.get("lifetimepaid")
272                user.Email = record.get("email")
273                user.Exists = 1
274                groupmembers.append(user)
275                self.cacheEntry("USERS", user.Name, user)
276        return groupmembers       
277       
278    def getUserGroupsFromBackend(self, user) :       
279        """Returns the user's groups list."""
280        groups = []
281        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
282        if result :
283            for record in result :
284                groups.append(self.getGroup(record.get("groupname")))
285        return groups       
286       
287    def getMatchingPrinters(self, printerpattern) :
288        """Returns the list of all printers for which name matches a certain pattern."""
289        printers = []
290        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
291        # but we don't because other storages semantics may be different, so every
292        # storage should use fnmatch to match patterns and be storage agnostic
293        result = self.doSearch("SELECT * FROM printers")
294        if result :
295            for record in result :
296                if self.tool.matchString(record["printername"], [ printerpattern ]) :
297                    printer = StoragePrinter(self, record["printername"])
298                    printer.ident = record.get("id")
299                    printer.PricePerJob = record.get("priceperjob")
300                    printer.PricePerPage = record.get("priceperpage")
301                    printer.LastJob = self.getPrinterLastJob(printer)
302                    printer.Exists = 1
303                    printers.append(printer)
304                    self.cacheEntry("PRINTERS", printer.Name, printer)
305        return printers       
306       
307    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
308        """Returns the list of users who uses a given printer, along with their quotas."""
309        usersandquotas = []
310        result = self.doSearch("SELECT users.id as uid,username,balance,lifetimepaid,limitby,email,userpquota.id,lifepagecounter,pagecounter,softlimit,hardlimit,datelimit FROM users JOIN userpquota ON users.id=userpquota.userid AND printerid=%s ORDER BY username ASC" % self.doQuote(printer.ident))
311        if result :
312            for record in result :
313                if self.tool.matchString(record.get("username"), names) :
314                    user = StorageUser(self, record.get("username"))
315                    user.ident = record.get("uid")
316                    user.LimitBy = record.get("limitby")
317                    user.AccountBalance = record.get("balance")
318                    user.LifeTimePaid = record.get("lifetimepaid")
319                    user.Email = record.get("email") 
320                    user.Exists = 1
321                    userpquota = StorageUserPQuota(self, user, printer)
322                    userpquota.ident = record.get("id")
323                    userpquota.PageCounter = record.get("pagecounter")
324                    userpquota.LifePageCounter = record.get("lifepagecounter")
325                    userpquota.SoftLimit = record.get("softlimit")
326                    userpquota.HardLimit = record.get("hardlimit")
327                    userpquota.DateLimit = record.get("datelimit")
328                    userpquota.Exists = 1
329                    usersandquotas.append((user, userpquota))
330                    self.cacheEntry("USERS", user.Name, user)
331                    self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
332        return usersandquotas
333               
334    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
335        """Returns the list of groups which uses a given printer, along with their quotas."""
336        groupsandquotas = []
337        result = self.doSearch("SELECT groupname FROM groups JOIN grouppquota ON groups.id=grouppquota.groupid AND printerid=%s ORDER BY groupname ASC" % self.doQuote(printer.ident))
338        if result :
339            for record in result :
340                if self.tool.matchString(record.get("groupname"), names) :
341                    group = self.getGroup(record.get("groupname"))
342                    grouppquota = self.getGroupPQuota(group, printer)
343                    groupsandquotas.append((group, grouppquota))
344        return groupsandquotas
345       
346    def addPrinter(self, printername) :       
347        """Adds a printer to the quota storage, returns it."""
348        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
349        return self.getPrinter(printername)
350       
351    def addUser(self, user) :       
352        """Adds a user to the quota storage, returns its id."""
353        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email) VALUES (%s, %s, %s, %s, %s)" % (self.doQuote(user.Name), self.doQuote(user.LimitBy), self.doQuote(user.AccountBalance), self.doQuote(user.LifeTimePaid), self.doQuote(user.Email)))
354        return self.getUser(user.Name)
355       
356    def addGroup(self, group) :       
357        """Adds a group to the quota storage, returns its id."""
358        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % (self.doQuote(group.Name), self.doQuote(group.LimitBy)))
359        return self.getGroup(group.Name)
360
361    def addUserToGroup(self, user, group) :   
362        """Adds an user to a group."""
363        result = self.doSearch("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
364        try :
365            mexists = int(result[0].get("mexists"))
366        except (IndexError, TypeError) :   
367            mexists = 0
368        if not mexists :   
369            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
370           
371    def addUserPQuota(self, user, printer) :
372        """Initializes a user print quota on a printer."""
373        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
374        return self.getUserPQuota(user, printer)
375       
376    def addGroupPQuota(self, group, printer) :
377        """Initializes a group print quota on a printer."""
378        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
379        return self.getGroupPQuota(group, printer)
380       
381    def writePrinterPrices(self, printer) :   
382        """Write the printer's prices back into the storage."""
383        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
384       
385    def writeUserLimitBy(self, user, limitby) :   
386        """Sets the user's limiting factor."""
387        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
388       
389    def writeGroupLimitBy(self, group, limitby) :   
390        """Sets the group's limiting factor."""
391        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
392       
393    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
394        """Sets the date limit permanently for a user print quota."""
395        self.doModify("UPDATE userpquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
396           
397    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
398        """Sets the date limit permanently for a group print quota."""
399        self.doModify("UPDATE grouppquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
400       
401    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
402       """Sets the new page counters permanently for a user print quota."""
403       self.doModify("UPDATE userpquota SET pagecounter=%s,lifepagecounter=%s WHERE id=%s" % (self.doQuote(newpagecounter), self.doQuote(newlifepagecounter), self.doQuote(userpquota.ident)))
404       
405    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
406       """Sets the new account balance and eventually new lifetime paid."""
407       if newlifetimepaid is not None :
408           self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
409       else :   
410           self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
411           
412    def writeLastJobSize(self, lastjob, jobsize) :       
413        """Sets the last job's size permanently."""
414        self.doModify("UPDATE jobhistory SET jobsize=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(lastjob.ident)))
415       
416    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None) :   
417        """Adds a job in a printer's history."""
418        if jobsize is not None :
419            self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, jobsize) VALUES (%s, %s, %s, %s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(jobsize)))
420        else :   
421            self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action) VALUES (%s, %s, %s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action)))
422           
423    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
424        """Sets soft and hard limits for a user quota."""
425        self.doModify("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userpquota.ident)))
426       
427    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
428        """Sets soft and hard limits for a group quota on a specific printer."""
429        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
430
431    def deleteUser(self, user) :   
432        """Completely deletes an user from the Quota Storage."""
433        # TODO : What should we do if we delete the last person who used a given printer ?
434        # TODO : we can't reassign the last job to the previous one, because next user would be
435        # TODO : incorrectly charged (overcharged).
436        for q in [ 
437                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
438                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
439                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
440                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
441                  ] :
442            self.doModify(q)
443       
444    def deleteGroup(self, group) :   
445        """Completely deletes a group from the Quota Storage."""
446        for q in [
447                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
448                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
449                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
450                 ] : 
451            self.doModify(q)
452       
Note: See TracBrowser for help on using the browser.