root / pykota / trunk / bin / lprngpykota @ 1877

Revision 1877, 13.3 kB (checked in by jalet, 20 years ago)

Fixed typo in code added to debug LPRng problem

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