root / pykota / trunk / bin / lprngpykota @ 2060

Revision 2060, 14.1 kB (checked in by jalet, 19 years ago)

Now always precomputes the job's size with the internal PDL parser, and not
only when 'enforcement: strict' was set in pykota.conf

  • 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# LPRngPyKota accounting filter
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003, 2004, 2005 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.15  2005/02/14 22:53:44  jalet
27# Now always precomputes the job's size with the internal PDL parser, and not
28# only when 'enforcement: strict' was set in pykota.conf
29#
30# Revision 1.14  2005/02/13 22:48:37  jalet
31# Added the md5sum to the history
32#
33# Revision 1.13  2005/01/17 08:44:23  jalet
34# Modified copyright years
35#
36# Revision 1.12  2004/10/25 17:05:36  jalet
37# Another fix for LPRng support debug messages : I'm sure I'm completely stupid now.
38#
39# Revision 1.11  2004/10/25 15:14:59  jalet
40# Fixed typo in code added to debug LPRng problem
41#
42# Revision 1.10  2004/10/24 09:06:46  jalet
43# Added debug messages for LPRng support possible problem ???
44#
45# Revision 1.9  2004/10/19 21:37:57  jalet
46# Fixes recently introduced bug
47#
48# Revision 1.8  2004/10/13 20:51:27  jalet
49# Made debugging levels be the same in cupspykota and lprngpykota.
50# Now outputs more information in informational messages : user, printer, jobid
51#
52# Revision 1.7  2004/09/13 16:02:44  jalet
53# Added fix for incorrect job's size when hardware accounting fails
54#
55# Revision 1.6  2004/09/02 14:40:13  jalet
56# Another bunch of LPRng fixes
57#
58# Revision 1.5  2004/07/23 11:19:48  jalet
59# 1.19beta is out !
60#
61# Revision 1.4  2004/07/22 22:41:48  jalet
62# Hardware accounting for LPRng should be OK now. UNTESTED.
63#
64# Revision 1.3  2004/07/21 09:35:48  jalet
65# Software accounting seems to be OK with LPRng support now
66#
67# Revision 1.2  2004/07/20 22:47:38  jalet
68# Sanitizing
69#
70# Revision 1.1  2004/07/17 20:37:27  jalet
71# Missing file... Am I really stupid ?
72#
73#
74#
75
76import sys
77import os
78
79from pykota.tool import PyKotaFilterOrBackend, PyKotaToolError, crashed
80from pykota.config import PyKotaConfigError
81from pykota.storage import PyKotaStorageError
82from pykota.accounter import PyKotaAccounterError
83   
84# Exit codes
85JSUCC = 0       # filter succeeded
86JFAIL = 1       # filter failed, print server should retry later
87JABORT = 2      # filter failed, print server should suspend the queue
88JREMOVE = 3     # job will be removed from print queue
89JHOLD = 6       # job will be prevented from printing until lpc release
90
91# Environment variables
92# PRINTER = printer name
93# PRINTCAP_ENTRY = complete printcap entry for this printer
94# HF = job hold file contents
95# SPOOL_DIR = spool directory
96
97# HF contains df_name which is DataFile_Name created in SPOOL_DIR
98
99class PyKotaFilter(PyKotaFilterOrBackend) :       
100    """A class for the pykota filter for LPRng."""
101    def acceptJob(self) :       
102        """Returns the appropriate exit code to tell LPRng all is OK."""
103        return JSUCC
104           
105    def removeJob(self) :           
106        """Returns the appropriate exit code to tell LPRng job has to be removed."""   
107        return JREMOVE
108       
109    def getJobOriginatingHostname(self, printername, username, jobid) :
110        """Retrieves the job-originating-hostname if possible."""
111        try :
112            return [line[11:] for line in os.environ.get("HF", "").split() if line.startswith("remotehost=")][0]
113        except IndexError :   
114            try :
115                return [line[1:] for line in os.environ.get("CONTROL", "").split() if line.startswith("H")][0]
116            except IndexError :   
117                return None
118               
119    def firstPass(self, policy, printer, user, userpquota) :           
120        """First pass done here."""
121        # first we have to check if previous job was correctly accounted for
122        self.logdebug("First pass begins : POLICY_%s => %s => %s" % (policy, getattr(printer, "Name", None), getattr(user, "Name", None)))
123        if printer.LastJob.Exists and not printer.LastJob.JobSize :
124            # here we know that previous job wasn't accounted for correctly
125            # we are sure (?) that it was hardware accounting which was used
126            # and that the second pass didn't work or wasn't even launched
127            # we know have to act just as if we were in second pass
128            # for previous user on this printer, then we will continue
129            # with normal processing of current user.
130            self.secondPass(policy, printer, None, None)
131       
132        # export user info with initial values
133        self.exportUserInfo(userpquota)
134       
135        # tries to extract job-originating-hostname
136        clienthost = self.getJobOriginatingHostname(printer.Name, user.Name, self.jobid)
137        self.logdebug("Client Hostname : %s" % (clienthost or "Unknown"))   
138        os.environ["PYKOTAJOBORIGINATINGHOSTNAME"] = str(clienthost or "")
139       
140        # indicates first pass
141        os.environ["PYKOTAPHASE"] = "BEFORE"
142       
143        # precomputes the job's price
144        self.softwareJobPrice = userpquota.computeJobPrice(self.softwareJobSize)
145        os.environ["PYKOTAPRECOMPUTEDJOBPRICE"] = str(self.softwareJobPrice)
146        self.logdebug("Precomputed job's size is %s pages, price is %s units" % (self.softwareJobSize, self.softwareJobPrice))
147       
148        # if no data to pass to real backend, probably a filter
149        # higher in the chain failed because of a misconfiguration.
150        # we deny the job in this case (nothing to print anyway)
151        if not self.jobSizeBytes :
152            self.printMoreInfo(user, printer, _("Job contains no data. Printing is denied."), "warn")
153            action = "DENY"
154        else :   
155            # checks the user's quota
156            action = self.warnUserPQuota(userpquota)
157       
158        # exports some new environment variables
159        os.environ["PYKOTAACTION"] = action
160       
161        # launches the pre hook
162        self.prehook(userpquota)
163       
164        self.printMoreInfo(user, printer, _("Job accounting begins."))
165        self.accounter.beginJob(printer)
166       
167        jobsize = None
168        if self.accounter.isSoftware :
169            self.accounter.endJob(printer)
170            jobsize = self.accounter.getJobSize(printer)
171            self.printMoreInfo(user, printer, _("Job accounting ends."))
172           
173        if action == "DENY" :   
174            jobsize = 0
175            self.printMoreInfo(user, printer, _("Job size forced to 0 because printing is denied."))
176           
177        if (self.accounter.isSoftware) or (action == "DENY") :   
178            # update the quota for the current user on this printer
179            self.printMoreInfo(user, printer, _("Job size : %i") % jobsize)
180            self.printInfo(_("Updating user %s's quota on printer %s") % (user.Name, printer.Name))
181            jobprice = userpquota.increasePagesUsage(jobsize)
182           
183            printer.addJobToHistory(self.jobid, user, self.accounter.getLastPageCounter(), \
184                                    action, jobsize, jobprice, self.preserveinputfile, \
185                                    self.title, self.copies, self.options, clienthost, \
186                                    self.jobSizeBytes, self.checksum)
187            self.printMoreInfo(user, printer, _("Job added to history."))
188           
189            # exports some new environment variables
190            os.environ["PYKOTAPHASE"] = "AFTER"
191            os.environ["PYKOTAJOBSIZE"] = str(jobsize)
192            os.environ["PYKOTAJOBPRICE"] = str(jobprice)
193           
194            # then re-export user information with new value
195            self.exportUserInfo(userpquota)
196           
197            # Launches the post hook
198            self.posthook(userpquota)
199           
200            # here accounting was completed, either software, or hardware but over quota
201        else :
202            printer.addJobToHistory(self.jobid, user, self.accounter.getLastPageCounter(), \
203                                    action, filename=self.preserveinputfile, title=self.title, \
204                                    copies=self.copies, options=self.options, clienthost=clienthost, \
205                                    jobsizebytes=self.jobSizeBytes, self.checksum)
206            self.logdebug("Job added to history during first pass : Job's size and price are still unknown.")
207           
208        self.logdebug("First pass ends : ACTION_%s => %s => %s" % (action, getattr(printer, "Name", None), getattr(user, "Name", None)))
209        if action == "DENY" :
210            return self.removeJob()
211        else :   
212            return self.acceptJob()
213       
214    def secondPass(self, policy, printer, user, userpquota) :   
215        """Second pass done here."""
216        # Last job for current printer has the same JobId than
217        # the current job, so we know we are in the second pass
218        self.logdebug("Second pass begins : POLICY_%s => %s => %s" % (policy, getattr(printer, "Name", None), getattr(user, "Name", None)))
219        if self.accounter.isSoftware :
220            # Software accounting method was used, and we are
221            # in second pass, so all work is already done,
222            # now we just have to exit successfully
223            self.printInfo(_("Software accounting already done in first pass. Ignoring."))
224        elif printer.LastJob.JobAction == "DENY" :
225            # Hardware accounting method was used, but job
226            # was rejected during first pass, so nothing to do
227            self.printInfo(_("Hardware accounting already done in first pass. Ignoring."))
228        else :   
229            # here if user and userpquota are both None
230            # then it's a special second pass for a job
231            # which should have had one but didn't, so
232            # we need to get the last user, not the current one.
233            if (user is None) and (userpquota is None) :
234                user = printer.LastJob.User
235                userpquota = self.storage.getUserPQuota(user, printer)
236               
237            # exports user info for last user   
238            self.exportUserInfo(userpquota)
239           
240            # indicate phase change
241            os.environ["PYKOTAPHASE"] = "AFTER"
242           
243            # fakes beginning of job with old page counter
244            self.accounter.LastPageCounter = int(printer.LastJob.PrinterPageCounter or 0)
245            self.accounter.fakeBeginJob()
246            self.logdebug("Fakes beginning of job with LastPageCounter: %s" % self.accounter.getLastPageCounter())
247           
248            # stops accounting.
249            self.accounter.endJob(printer)
250            self.logdebug("Job accounting ends.")
251               
252            # retrieve the job size   
253            jobsize = self.accounter.getJobSize(printer)
254            if self.softwareJobSize and (jobsize != self.softwareJobSize) :
255                self.printInfo(_("Beware : computed job size (%s) != precomputed job size (%s)") % (jobsize, self.softwareJobSize), "error")
256           
257            self.printMoreInfo(user, printer, _("Job size : %i") % jobsize)
258            self.printInfo(_("Updating user %s's quota on printer %s") % (user.Name, printer.Name))
259            jobprice = userpquota.increasePagesUsage(jobsize)
260           
261            self.storage.writeLastJobSize(printer.LastJob, jobsize, jobprice)
262            self.printMoreInfo(user, printer, _("Job size and price now set in history."))
263           
264            # exports some new environment variables
265            os.environ["PYKOTAPHASE"] = "AFTER"
266            os.environ["PYKOTAJOBSIZE"] = str(jobsize)
267            os.environ["PYKOTAJOBPRICE"] = str(jobprice)
268           
269            # then re-export user information with new value
270            self.exportUserInfo(userpquota)
271           
272            # Launches the post hook
273            self.posthook(userpquota)
274           
275            # here hardware accounting was completed.
276        self.logdebug("Second pass ends : POLICY_%s => %s => %s" % (policy, getattr(printer, "Name", None), getattr(user, "Name", None)))
277        return self.acceptJob()
278       
279    def doWork(self, policy, printer, user, userpquota) :   
280        """Most of the work is done here."""
281        # Two different values possible for policy here :
282        # ALLOW means : Either printer, user or user print quota doesn't exist,
283        #               but the job should be allowed anyway.
284        # OK means : Both printer, user and user print quota exist, job should
285        #            be allowed if current user is allowed to print on this printer
286        if policy == "ALLOW" :
287            # nothing to do, just accept the job
288            return self.acceptJob()
289        else :   
290            if printer.LastJob.Exists and (printer.LastJob.JobId == self.jobid) :
291                # here we know we are in second pass.
292                return self.secondPass(policy, printer, user, userpquota)
293            else :   
294                # Last job for current printer has a different JobId than
295                # the current job, so we know we are in the first pass.
296                return self.firstPass(policy, printer, user, userpquota)
297           
298if __name__ == "__main__" :   
299    retcode = JSUCC
300    try :
301        try :
302            # Initializes the backend
303            kotabackend = PyKotaFilter()   
304        except SystemExit :   
305            retcode = JABORT
306        except :   
307            crashed("lprngpykota filter initialization failed")
308            retcode = JABORT
309        else :   
310            retcode = kotabackend.mainWork()
311            kotabackend.storage.close()
312            kotabackend.closeJobDataStream()   
313    except :
314        try :
315            kotabackend.crashed("lprngpykota filter failed")
316        except :   
317            crashed("lprngpykota filter failed")
318        retcode = JABORT
319       
320    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.