root / pykota / trunk / bin / pykota @ 1360

Revision 1359, 12.1 kB (checked in by jalet, 20 years ago)

Avoids a database query even if caching was disabled.

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