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

Revision 1149, 23.3 kB (checked in by jalet, 21 years ago)

Job history can be disabled.
Some typos in README.
More messages in setup script.

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