root / pykota / trunk / bin / lprngpykota @ 1872

Revision 1872, 13.2 kB (checked in by jalet, 20 years ago)

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