root / pykota / trunk / bin / lprngpykota @ 1611

Revision 1611, 10.3 kB (checked in by jalet, 20 years ago)

Software accounting seems to be OK with LPRng support now

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