root / pykota / trunk / bin / lprngpykota @ 2028

Revision 2028, 13.6 kB (checked in by jalet, 19 years ago)

Modified copyright years

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