root / pykota / trunk / bin / pykota @ 1284

Revision 1281, 11.9 kB (checked in by jalet, 20 years ago)

Denied jobs weren't added to the history anymore, this is now fixed.

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