root / pykota / trunk / bin / lprngpykota @ 1624

Revision 1624, 12.1 kB (checked in by jalet, 20 years ago)

Hardware accounting for LPRng should be OK now. UNTESTED.

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