root / pykota / trunk / bin / lprngpykota @ 2139

Revision 2139, 15.7 kB (checked in by jerome, 19 years ago)

Added the Log keyword property

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