root / pykota / trunk / bin / pykota @ 1292

Revision 1292, 12.0 kB (checked in by jalet, 20 years ago)

Missing return caused problems with LPRng

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