root / pykota / trunk / bin / pykota @ 1196

Revision 1196, 11.3 kB (checked in by jalet, 21 years ago)

Code refactoring work.
Explicit redirection to /dev/null has to be set in external policy now, just
like in external mailto.

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