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

Revision 1087, 22.1 kB (checked in by jalet, 21 years ago)

Really big modifications wrt new configuration file's location and content.

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