root / pykota / trunk / bin / lprngpykota @ 1848

Revision 1848, 12.6 kB (checked in by jalet, 20 years ago)

Fixes recently introduced bug

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