root / pykota / trunk / bin / lprngpykota @ 1629

Revision 1629, 11.8 kB (checked in by jalet, 20 years ago)

1.19beta is out !

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