root / pykota / trunk / bin / lprngpykota @ 2059

Revision 2057, 13.9 kB (checked in by jalet, 20 years ago)

Added the md5sum to the history

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