root / pykota / trunk / bin / lprngpykota @ 1713

Revision 1713, 12.2 kB (checked in by jalet, 20 years ago)

Added fix for incorrect job's size when hardware accounting fails

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