root / pykota / trunk / bin / lprngpykota @ 1609

Revision 1609, 9.9 kB (checked in by jalet, 20 years ago)

Sanitizing

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