root / pykota / trunk / bin / pykota @ 1391

Revision 1391, 13.8 kB (checked in by jalet, 20 years ago)

Improve tracebacks

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3
4# PyKota accounting filter
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23# $Id$
24#
25# $Log$
26# Revision 1.56  2004/03/05 12:46:08  jalet
27# Improve tracebacks
28#
29# Revision 1.55  2004/03/05 12:31:35  jalet
30# Now should output full traceback when crashing
31#
32# Revision 1.54  2004/03/01 15:06:51  jalet
33# Pre and Post hooks should now work in the pykota filter too.
34# The pykota filter doesn't check the last user's quota anymore
35# when delayed hardware accounting is used : this will be checked
36# anyway the next time the last user will print
37#
38# Revision 1.53  2004/02/25 12:36:34  jalet
39# Avoids a database query even if caching was disabled.
40#
41# Revision 1.52  2004/01/14 15:57:54  jalet
42# Missing return caused problems with LPRng
43#
44# Revision 1.51  2004/01/12 18:20:45  jalet
45# Denied jobs weren't added to the history anymore, this is now fixed.
46#
47# Revision 1.50  2004/01/11 23:22:42  jalet
48# Major code refactoring, it's way cleaner, and now allows automated addition
49# of printers on first print.
50#
51# Revision 1.49  2004/01/08 14:10:32  jalet
52# Copyright year changed.
53#
54# Revision 1.48  2003/12/27 16:49:25  uid67467
55# Should be ok now.
56#
57# Revision 1.47  2003/11/26 19:17:35  jalet
58# Printing on a printer not present in the Quota Storage now results
59# in the job being stopped or cancelled depending on the system.
60#
61# Revision 1.46  2003/11/24 14:25:02  jalet
62# Missing import in pykota filter
63#
64# Revision 1.45  2003/11/19 23:19:37  jalet
65# Code refactoring work.
66# Explicit redirection to /dev/null has to be set in external policy now, just
67# like in external mailto.
68#
69# Revision 1.44  2003/11/08 16:05:31  jalet
70# CUPS backend added for people to experiment.
71#
72# Revision 1.43  2003/11/06 22:33:25  jalet
73# French variable name
74#
75# Revision 1.42  2003/10/08 21:41:38  jalet
76# External policies for printers works !
77# We can now auto-add users on first print, and do other useful things if needed.
78#
79# Revision 1.41  2003/10/07 09:07:27  jalet
80# Character encoding added to please latest version of Python
81#
82# Revision 1.40  2003/09/04 08:38:56  jalet
83# Added an exception catch to ensure clean close of database even in
84# case of TypeError too.
85#
86# Revision 1.39  2003/08/18 16:35:28  jalet
87# New pychecker pass, on the tools this time.
88#
89# Revision 1.38  2003/08/18 16:20:59  jalet
90# Improvement of the printing system detection code.
91#
92# Revision 1.37  2003/07/29 20:55:17  jalet
93# 1.14 is out !
94#
95# Revision 1.36  2003/07/10 06:09:52  jalet
96# Incorrect documentation string
97#
98# Revision 1.35  2003/06/25 14:10:01  jalet
99# Hey, it may work (edpykota --reset excepted) !
100#
101# Revision 1.34  2003/06/13 18:54:17  jalet
102# Bug with remote jobs and LPRng fixed.
103#
104# Revision 1.33  2003/05/28 13:51:38  jalet
105# Better handling of errors
106#
107# Revision 1.32  2003/05/27 23:00:20  jalet
108# Big rewrite of external accounting methods.
109# Should work well now.
110#
111# Revision 1.31  2003/04/30 13:36:39  jalet
112# Stupid accounting method was added.
113#
114# Revision 1.30  2003/04/29 22:03:38  jalet
115# Better error handling.
116#
117# Revision 1.29  2003/04/29 18:37:54  jalet
118# Pluggable accounting methods (actually doesn't support external scripts)
119#
120# Revision 1.28  2003/04/26 08:41:24  jalet
121# Small code reorganisation (UNTESTED) to allow pluggable accounting
122# methods in the future.
123#
124# Revision 1.27  2003/04/25 09:23:47  jalet
125# Debug message passed through !
126#
127# Revision 1.26  2003/04/25 08:23:23  jalet
128# Multiple tries to get the printer's internal page counter, waits for
129# one minute maximum for the printer to warm up, actually.
130#
131# Revision 1.25  2003/04/24 11:53:48  jalet
132# Default policy for unknown users/groups is to DENY printing instead
133# of the previous default to ALLOW printing. This is to solve an accuracy
134# problem. If you set the policy to ALLOW, jobs printed by in nexistant user
135# (from PyKota's POV) will be charged to the next user who prints on the
136# same printer.
137#
138# Revision 1.24  2003/04/23 22:13:56  jalet
139# Preliminary support for LPRng added BUT STILL UNTESTED.
140#
141# Revision 1.23  2003/04/15 11:30:57  jalet
142# More work done on money print charging.
143# Minor bugs corrected.
144# All tools now access to the storage as priviledged users, repykota excepted.
145#
146# Revision 1.22  2003/04/15 11:09:04  jalet
147# Small bug was fixed when a printer was never used and its internal
148# page counter is not accessible.
149#
150# Revision 1.21  2003/04/12 17:20:14  jalet
151# Better formula for HP workaround
152#
153# Revision 1.20  2003/04/12 16:58:28  jalet
154# The workaround for HP printers was not correct, and there's probably no
155# correct way to workaround the problem because we can't save the internal
156# page counter in real time. The last job's size is unconditionnally set to
157# 5 pages in this case.
158#
159# Revision 1.19  2003/04/11 08:56:49  jalet
160# Comment
161#
162# Revision 1.18  2003/04/11 08:50:39  jalet
163# Workaround for the HP "feature" of saving the page counter to NVRAM
164# only every time 10 new pages are printed...
165# Workaround for printers with volatile page counters.
166#
167# Revision 1.17  2003/04/10 21:47:20  jalet
168# Job history added. Upgrade script neutralized for now !
169#
170# Revision 1.16  2003/04/08 20:38:08  jalet
171# The last job Id is saved now for each printer, this will probably
172# allow other accounting methods in the future.
173#
174# Revision 1.15  2003/03/29 13:45:27  jalet
175# GPL paragraphs were incorrectly (from memory) copied into the sources.
176# Two README files were added.
177# Upgrade script for PostgreSQL pre 1.01 schema was added.
178#
179# Revision 1.14  2003/03/07 22:16:57  jalet
180# Algorithmically incorrect : last user quota wasn't updated if current
181# user wasn't allowed to print.
182#
183# Revision 1.13  2003/02/27 23:59:28  jalet
184# Stupid bug wrt exception handlingand value conversion
185#
186# Revision 1.12  2003/02/27 23:48:41  jalet
187# Correctly maps PyKota's log levels to syslog log levels
188#
189# Revision 1.11  2003/02/27 22:55:20  jalet
190# WARN log priority doesn't exist.
191#
192# Revision 1.10  2003/02/27 22:43:21  jalet
193# Missing import
194#
195# Revision 1.9  2003/02/27 22:40:26  jalet
196# Correctly handles cases where the printer is off.
197#
198# Revision 1.8  2003/02/09 12:56:53  jalet
199# Internationalization begins...
200#
201# Revision 1.7  2003/02/07 10:23:48  jalet
202# Avoid a possible future name clash
203#
204# Revision 1.6  2003/02/06 22:54:33  jalet
205# warnpykota should be ok
206#
207# Revision 1.5  2003/02/05 22:45:25  jalet
208# Forgotten import
209#
210# Revision 1.4  2003/02/05 22:42:51  jalet
211# Typo
212#
213# Revision 1.3  2003/02/05 22:38:39  jalet
214# Typo
215#
216# Revision 1.2  2003/02/05 22:16:20  jalet
217# DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools
218#
219# Revision 1.1  2003/02/05 21:28:17  jalet
220# Initial import into CVS
221#
222#
223#
224
225import sys
226import os
227
228from pykota.tool import PyKotaFilterOrBackend, PyKotaToolError
229from pykota.config import PyKotaConfigError
230from pykota.storage import PyKotaStorageError
231from pykota.accounter import PyKotaAccounterError
232from pykota.requester import PyKotaRequesterError
233
234class PyKotaFilter(PyKotaFilterOrBackend) :       
235    """A class for the pykota filter."""
236    def acceptJob(self) :       
237        """Returns the exit code needed by the printing backend to accept the job and print it."""
238        if self.printingsystem == "CUPS" :
239            return 0
240        elif self.printingsystem == "LPRNG" :   
241            return 0
242        else :   
243            # UNKNOWN
244            return -1
245           
246    def removeJob(self) :           
247        """Returns the exit code needed by the printing backend to refuse the job and remove it."""
248        if self.printingsystem == "CUPS" :
249            return 1
250        elif self.printingsystem == "LPRNG" :   
251            return 3
252        else :   
253            # UNKNOWN
254            return -1
255       
256    def doWork(self, policy, printer, user, userpquota) :   
257        """Most of the work is done here."""
258        # Two different values possible for policy here :
259        # ALLOW means : Either printer, user or user print quota doesn't exist,
260        #               but the job should be allowed anyway.
261        # OK means : Both printer, user and user print quota exist, job should
262        #            be allowed if current user is allowed to print on this printer
263        if policy == "OK" :
264            # exports user information with initial values
265            self.exportUserInfo(userpquota)
266           
267            # enters first phase
268            os.putenv("PYKOTAPHASE", "BEFORE")
269           
270            self.logdebug("Does accounting for user %s on printer %s." % (user.Name, printer.Name))
271            action = self.accounter.doAccounting(userpquota)
272           
273            # exports some new environment variables
274            os.putenv("PYKOTAACTION", action)
275           
276            # launches the pre hook
277            self.prehook(userpquota)
278        else :       
279            action = "ALLOW"
280           
281        # pass the job's data to the next filter
282        if action in ["ALLOW", "WARN"] :
283            self.logdebug("Passing input data to next filter.")
284            mustclose = 0   
285            if self.inputfile is not None :   
286                if hasattr(self.inputfile, "read") :
287                    infile = self.inputfile
288                else :   
289                    infile = open(self.inputfile, "rb")
290                mustclose = 1
291            else :   
292                infile = sys.stdin
293            data = infile.read(256*1024)   
294            while data :
295                sys.stdout.write(data)
296                data = infile.read(256*1024)
297            if mustclose :   
298                infile.close()
299            return self.acceptJob()
300        else :
301            self.logdebug("Printing is denied.")
302            return self.removeJob()
303       
304    def mainWork(self) :   
305        # If this is a CUPS filter, we should act and die like a CUPS filter when needed
306        if self.printingsystem == "CUPS" :
307            if len(sys.argv) not in (6, 7) :   
308                sys.stderr.write("ERROR: %s job-id user title copies options [file]\n" % sys.argv[0])
309                return self.removeJob()
310               
311        if self.accounter.isDelayed :       
312            # Here we need to update the last user's print quota       
313            # because hardware accounting is delayed by one print job
314            # in the pykota filter.
315            printer = self.storage.getPrinter(self.printername)       
316            if not printer.Exists :
317                self.logger.log_message(_("Printer %s not registered in the PyKota system") % self.printername, "info")
318            else :   
319                if not printer.LastJob.Exists :
320                    self.logger.log_message(_("Printer %s was never used") % self.printername, "info")
321                else :
322                    self.logdebug("Updating print quota for last user %s on printer %s" % (printer.LastJob.User.Name, printer.Name))
323                    lastuserpquota = self.storage.getUserPQuota(printer.LastJob.User, printer)
324                    self.accounter.counterbefore = printer.LastJob.PrinterPageCounter
325                    self.accounter.counterafter = self.accounter.getPrinterInternalPageCounter() or 0
326                    lastjobsize = self.accounter.getJobSize()
327                    self.logdebug("Last Job size : %i" % lastjobsize)
328                    lastjobprice = printer.LastJob.setSize(lastuserpquota, lastjobsize)
329                    self.logdebug("Updating user %s's quota on printer %s" % (lastuserpquota.User.Name, printer.Name))
330                    lastuserpquota.increasePagesUsage(lastjobsize)
331                   
332                    # exports user information with final values
333                    self.exportUserInfo(lastuserpquota)
334                   
335                    # enters final phase
336                    os.putenv("PYKOTAPHASE", "AFTER")
337                    os.putenv("PYKOTAACTION", printer.LastJob.JobAction)
338                    os.putenv("PYKOTAJOBSIZE", str(lastjobsize))
339                    os.putenv("PYKOTAJOBPRICE", str(lastjobprice))
340                   
341                    # launches the post hook
342                    self.posthook(lastuserpquota)
343                   
344                    # Code below deactivated since this will be checked
345                    # anyway the next time this user prints
346                    # finally check last user's quota
347                    # self.warnUserPQuota(lastuserpquota)
348                   
349        # then deal with current print job as usual           
350        return PyKotaFilterOrBackend.mainWork(self)       
351           
352if __name__ == "__main__" :   
353    retcode = -1
354    try :
355        # Initializes the current tool
356        kotafilter = PyKotaFilter()   
357        retcode = kotafilter.mainWork()
358    except (PyKotaToolError, PyKotaConfigError, PyKotaStorageError, PyKotaAccounterError, PyKotaRequesterError, AttributeError, KeyError, IndexError, ValueError, TypeError, IOError), msg :
359        import traceback
360        sys.stderr.write("ERROR : PyKota filter failed (%s)\n%s" % (msg, "ERROR : ".join(traceback.format_stack())))
361        sys.stderr.flush()
362        try :
363            retcode = kotafilter.removeJob()
364        except :
365            retcode = -1
366
367    try :
368        kotafilter.storage.close()
369    except (TypeError, NameError, AttributeError) :   
370        pass
371       
372    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.