root / pykota / trunk / bin / lprngpykota @ 2096

Revision 2066, 15.6 kB (checked in by jalet, 20 years ago)

Fixed the maxdenybanners directive.
Introduced the denyduplicates directive.
Fixed some database related glitches.

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