root / pykota / trunk / bin / cupspykota @ 1458

Revision 1458, 21.3 kB (checked in by jalet, 20 years ago)

Fix for file handles unregistered twice from the polling object

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[1177]1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3
4# CUPSPyKota accounting backend
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
[1257]8# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
[1177]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$
[1458]26# Revision 1.39  2004/05/07 14:44:53  jalet
27# Fix for file handles unregistered twice from the polling object
28#
[1433]29# Revision 1.38  2004/04/09 22:24:46  jalet
30# Began work on correct handling of child processes when jobs are cancelled by
31# the user. Especially important when an external requester is running for a
32# long time.
33#
[1411]34# Revision 1.37  2004/03/18 19:11:25  jalet
35# Fix for raw jobs in cupspykota
36#
[1410]37# Revision 1.36  2004/03/18 14:03:18  jalet
38# Added fsync() calls
39#
[1405]40# Revision 1.35  2004/03/16 12:05:01  jalet
41# Small fix for new waitprinter.sh : when job was denied, would wait forever
42# for printer being in printing mode.
43#
[1400]44# Revision 1.34  2004/03/15 10:47:56  jalet
45# This time the traceback formatting should be correct !
46#
[1391]47# Revision 1.33  2004/03/05 12:46:07  jalet
48# Improve tracebacks
49#
[1390]50# Revision 1.32  2004/03/05 12:31:35  jalet
51# Now should output full traceback when crashing
52#
[1375]53# Revision 1.31  2004/03/01 14:35:56  jalet
54# PYKOTAPHASE wasn't set soon enough at the start of the job
55#
[1374]56# Revision 1.30  2004/03/01 14:34:15  jalet
57# PYKOTAPHASE wasn't set at the right time at the end of data transmission
58# to underlying layer (real backend)
59#
[1372]60# Revision 1.29  2004/03/01 11:23:25  jalet
61# Pre and Post hooks to external commands are available in the cupspykota
62# backend. Forthe pykota filter they will be implemented real soon now.
63#
[1365]64# Revision 1.28  2004/02/26 14:18:07  jalet
65# Should fix the remaining bugs wrt printers groups and users groups.
66#
[1335]67# Revision 1.27  2004/02/04 23:41:27  jalet
68# Should fix the incorrect "backend died abnormally" problem.
69#
[1321]70# Revision 1.26  2004/01/30 16:35:03  jalet
71# Fixes stupid software accounting bug in CUPS backend
72#
[1302]73# Revision 1.25  2004/01/16 17:51:46  jalet
74# Fuck Fuck Fuck !!!
75#
[1291]76# Revision 1.24  2004/01/14 15:52:01  jalet
77# Small fix for job cancelling code.
78#
[1289]79# Revision 1.23  2004/01/13 10:48:28  jalet
80# Small streams polling loop modification.
81#
[1285]82# Revision 1.22  2004/01/12 22:43:40  jalet
83# New formula to compute a job's price
84#
[1280]85# Revision 1.21  2004/01/12 18:17:36  jalet
86# Denied jobs weren't stored into the history anymore, this is now fixed.
87#
[1271]88# Revision 1.20  2004/01/11 23:22:42  jalet
89# Major code refactoring, it's way cleaner, and now allows automated addition
90# of printers on first print.
91#
[1257]92# Revision 1.19  2004/01/08 14:10:32  jalet
93# Copyright year changed.
94#
[1256]95# Revision 1.18  2004/01/07 16:16:32  jalet
96# Better debugging information
97#
[1240]98# Revision 1.17  2003/12/27 16:49:25  uid67467
99# Should be ok now.
100#
101# Revision 1.17  2003/12/06 08:54:29  jalet
102# Code simplifications.
103# Added many debugging messages.
104#
[1222]105# Revision 1.16  2003/11/26 20:43:29  jalet
106# Inadvertantly introduced a bug, which is fixed.
107#
[1221]108# Revision 1.15  2003/11/26 19:17:35  jalet
109# Printing on a printer not present in the Quota Storage now results
110# in the job being stopped or cancelled depending on the system.
111#
[1210]112# Revision 1.14  2003/11/25 13:25:45  jalet
113# Boolean problem with old Python, replaced with 0
114#
[1203]115# Revision 1.13  2003/11/23 19:01:35  jalet
116# Job price added to history
117#
[1200]118# Revision 1.12  2003/11/21 14:28:43  jalet
119# More complete job history.
120#
[1196]121# Revision 1.11  2003/11/19 23:19:35  jalet
122# Code refactoring work.
123# Explicit redirection to /dev/null has to be set in external policy now, just
124# like in external mailto.
125#
[1191]126# Revision 1.10  2003/11/18 17:54:24  jalet
127# SIGTERMs are now transmitted to original backends.
128#
[1190]129# Revision 1.9  2003/11/18 14:11:07  jalet
130# Small fix for bizarre urls
131#
[1186]132# Revision 1.8  2003/11/15 14:26:44  jalet
133# General improvements to the documentation.
134# Email address changed in sample configuration file, because
135# I receive low quota messages almost every day...
136#
[1185]137# Revision 1.7  2003/11/14 22:05:12  jalet
138# New CUPS backend fully functionnal.
139# Old CUPS configuration method is now officially deprecated.
140#
[1184]141# Revision 1.6  2003/11/14 20:13:11  jalet
142# We exit the loop too soon.
143#
[1183]144# Revision 1.5  2003/11/14 18:31:27  jalet
145# Not perfect, but seems to work with the poll() loop.
146#
[1182]147# Revision 1.4  2003/11/14 17:04:15  jalet
148# More (untested) work on the CUPS backend.
149#
[1180]150# Revision 1.3  2003/11/12 23:27:44  jalet
151# More work on new backend. This commit may be unstable.
152#
[1178]153# Revision 1.2  2003/11/12 09:33:34  jalet
154# New CUPS backend supports device enumeration
155#
[1177]156# Revision 1.1  2003/11/08 16:05:31  jalet
157# CUPS backend added for people to experiment.
158#
159#
160#
161
162import sys
163import os
[1182]164import popen2
[1178]165import cStringIO
166import shlex
[1182]167import select
168import signal
[1291]169import time
[1177]170
[1196]171from pykota.tool import PyKotaFilterOrBackend, PyKotaToolError
[1177]172from pykota.config import PyKotaConfigError
173from pykota.storage import PyKotaStorageError
[1196]174from pykota.accounter import PyKotaAccounterError
175from pykota.requester import PyKotaRequesterError
[1271]176   
[1182]177class PyKotaPopen3(popen2.Popen3) :
178    """Our own class to execute real backends.
179   
180       Their first argument is different from their path so using
181       native popen2.Popen3 would not be feasible.
182    """
[1210]183    def __init__(self, cmd, capturestderr=0, bufsize=-1, arg0=None) :
[1182]184        self.arg0 = arg0
185        popen2.Popen3.__init__(self, cmd, capturestderr, bufsize)
186       
187    def _run_child(self, cmd):
[1183]188        for i in range(3, 256): # TODO : MAXFD in original popen2 module
[1182]189            try:
190                os.close(i)
191            except OSError:
192                pass
193        try:
194            os.execvpe(cmd[0], [self.arg0 or cmd[0]] + cmd[1:], os.environ)
195        finally:
196            os._exit(1)
197   
[1271]198class PyKotaBackend(PyKotaFilterOrBackend) :       
199    """A class for the pykota backend."""
200    def acceptJob(self) :       
201        """Returns the appropriate exit code to tell CUPS all is OK."""
202        return 0
203           
204    def removeJob(self) :           
205        """Returns the appropriate exit code to let CUPS think all is OK.
[1177]206       
[1271]207           Returning 0 (success) prevents CUPS from stopping the print queue.
208        """   
209        return 0
[1222]210       
[1271]211    def doWork(self, policy, printer, user, userpquota) :   
212        """Most of the work is done here."""
213        # Two different values possible for policy here :
214        # ALLOW means : Either printer, user or user print quota doesn't exist,
215        #               but the job should be allowed anyway.
216        # OK means : Both printer, user and user print quota exist, job should
217        #            be allowed if current user is allowed to print on this printer
218        if policy == "OK" :
[1372]219            # exports user information with initial values
220            self.exportUserInfo(userpquota)
221           
[1375]222            # enters first phase
223            os.putenv("PYKOTAPHASE", "BEFORE")
224           
[1372]225            # checks the user's quota
[1271]226            action = self.warnUserPQuota(userpquota)
[1372]227           
228            # exports some new environment variables
229            os.putenv("PYKOTAACTION", action)
230           
231            # launches the pre hook
232            self.prehook(userpquota)
233           
[1271]234            self.logdebug("Job accounting begins.")
235            self.accounter.beginJob(userpquota)
[1280]236        else :   
237            action = "ALLOW"
[1405]238            os.putenv("PYKOTAACTION", action)
[1271]239           
240        # pass the job's data to the real backend   
[1280]241        if action in ["ALLOW", "WARN"] :
[1291]242            if self.gotSigTerm :
[1280]243                retcode = self.removeJob()
244            else :   
245                retcode = self.handleData()       
246        else :       
[1271]247            retcode = self.removeJob()
248       
249        if policy == "OK" :       
[1374]250            # indicate phase change
251            os.putenv("PYKOTAPHASE", "AFTER")
252           
[1271]253            # stops accounting.
254            self.accounter.endJob(userpquota)
255            self.logdebug("Job accounting ends.")
256               
257            # retrieve the job size   
[1321]258            if action == "DENY" :
259                jobsize = 0
260                self.logdebug("Job size forced to 0 because printing is denied.")
261            else :   
262                jobsize = self.accounter.getJobSize()
[1271]263            self.logdebug("Job size : %i" % jobsize)
264           
265            # update the quota for the current user on this printer
[1285]266            self.logdebug("Updating user %s's quota on printer %s" % (user.Name, printer.Name))
267            jobprice = userpquota.increasePagesUsage(jobsize)
[1271]268           
269            # adds the current job to history   
270            printer.addJobToHistory(self.jobid, user, self.accounter.getLastPageCounter(), action, jobsize, jobprice, self.preserveinputfile, self.title, self.copies, self.options)
271            self.logdebug("Job added to history.")
272           
[1372]273            # exports some new environment variables
274            os.putenv("PYKOTAJOBSIZE", str(jobsize))
275            os.putenv("PYKOTAJOBPRICE", str(jobprice))
276           
277            # then re-export user information with new values
278            self.exportUserInfo(userpquota)
279           
280            # Launches the post hook
281            self.posthook(userpquota)
282           
[1271]283        return retcode   
284                   
[1458]285    def unregisterFileNo(self, pollobj, fileno) :               
286        """Removes a file handle from the polling object."""
287        try :
288            pollobj.unregister(fileno)
289        except KeyError :   
290            self.logger.log_message(_("File number %s unregistered twice from polling object, ignored.") % fileno, "warn")
291        else :   
292            self.logdebug("File number %s unregistered from polling object." % fileno)
293           
[1271]294    def handleData(self) :                   
295        """Pass the job's data to the real backend."""
[1222]296        # Now it becomes tricky...
[1271]297        # We must pass the unmodified job to the original backend
[1222]298        # First ensure that we have a file object as input
299        mustclose = 0   
[1271]300        if self.inputfile is not None :   
301            if hasattr(self.inputfile, "read") :
302                infile = self.inputfile
[1182]303            else :   
[1271]304                infile = open(self.inputfile, "rb")
[1222]305            mustclose = 1
306        else :   
307            infile = sys.stdin
[1185]308           
[1222]309        # Find the real backend pathname   
[1271]310        realbackend = os.path.join(os.path.split(sys.argv[0])[0], self.originalbackend)
[1222]311       
312        # And launch it
[1271]313        self.logdebug("Starting real backend %s with args %s" % (realbackend, " ".join(['"%s"' % a for a in ([os.environ["DEVICE_URI"]] + sys.argv[1:])])))
[1222]314        subprocess = PyKotaPopen3([realbackend] + sys.argv[1:], capturestderr=1, bufsize=0, arg0=os.environ["DEVICE_URI"])
315       
316        # Save file descriptors, we will need them later.
317        stdoutfno = sys.stdout.fileno()
318        stderrfno = sys.stderr.fileno()
319        fromcfno = subprocess.fromchild.fileno()
320        tocfno = subprocess.tochild.fileno()
321        cerrfno = subprocess.childerr.fileno()
322       
323        # We will have to be careful when dealing with I/O
324        # So we use a poll object to know when to read or write
325        pollster = select.poll()
326        pollster.register(fromcfno, select.POLLIN | select.POLLPRI)
327        pollster.register(cerrfno, select.POLLIN | select.POLLPRI)
328        pollster.register(stdoutfno, select.POLLOUT)
329        pollster.register(stderrfno, select.POLLOUT)
330        pollster.register(tocfno, select.POLLOUT)
331       
332        # Initialize our buffers
333        indata = ""
334        outdata = ""
335        errdata = ""
[1289]336        endinput = endoutput = enderr = 0
[1302]337        inputclosed = outputclosed = errclosed = 0
[1411]338       
339        if self.preserveinputfile is None :
340            # this is not a real file, we read the job's data
341            # from stdin
342            infno = infile.fileno()
343            pollster.register(infno, select.POLLIN | select.POLLPRI)
344        else :   
345            # job's data is in a file, no need to pass the data
346            # to the real backend
347            self.logdebug("Job's data is in %s" % self.preserveinputfile)
348            infno = None
349            endinput = 1
350       
[1291]351        killed = 0
[1271]352        self.logdebug("Entering streams polling loop...")
[1289]353        status = -1
[1222]354        while status == -1 :
355            # First check if original backend is still alive
356            status = subprocess.poll()
[1185]357           
[1222]358            # Now if we got SIGTERM, we have
359            # to kill -TERM the original backend
[1291]360            if self.gotSigTerm and not killed :
[1222]361                try :
362                    os.kill(subprocess.pid, signal.SIGTERM)
[1291]363                    self.logger.log_message(_("SIGTERM was sent to real backend %s (pid: %s)") % (realbackend, subprocess.pid), "info")
364                    killed = 1
[1222]365                except : # ignore if process was already killed.
366                    pass
[1191]367           
[1222]368            # In any case, deal with any remaining I/O
[1289]369            availablefds = pollster.poll(5000)
[1222]370            for (fd, mask) in availablefds :
[1271]371                # self.logdebug("file: %i    mask: %04x" % (fd, mask))
[1222]372                if mask & select.POLLOUT :
373                    # We can write
374                    if fd == tocfno :
375                        if indata :
376                            os.write(fd, indata)   
[1411]377                            try :
378                                os.fsync(fd)
379                            except OSError :
380                                pass
[1222]381                            indata = ""
[1289]382                        if endinput :   
[1458]383                            self.unregisterFileNo(pollster, tocfno)       
[1291]384                            self.logdebug("Closing real backend's stdin.")
[1289]385                            os.close(tocfno)
386                            inputclosed = 1
[1222]387                    elif fd == stdoutfno :
388                        if outdata :
389                            os.write(fd, outdata)
[1411]390                            try :
391                                os.fsync(fd)
392                            except OSError :   
393                                pass
[1222]394                            outdata = ""
[1289]395                        if endoutput :   
[1458]396                            self.unregisterFileNo(pollster, stdoutfno)       
[1289]397                            outputclosed = 1
[1222]398                    elif fd == stderrfno :
399                        if errdata :
400                            os.write(fd, errdata)
[1411]401                            try :
402                                os.fsync(fd)
403                            except OSError :   
404                                pass
[1222]405                            errdata = ""
[1289]406                        if enderr :   
[1458]407                            self.unregisterFileNo(pollster, stderrfno)       
[1289]408                            errclosed = 1
[1222]409                if (mask & select.POLLIN) or (mask & select.POLLPRI) :     
410                    # We have something to read
411                    data = os.read(fd, 256 * 1024)
412                    if fd == infno :
413                        indata += data
414                        if not data :    # If yes, then no more input data
[1458]415                            self.unregisterFileNo(pollster, infno)
[1289]416                            self.logdebug("Input data ends.")
[1222]417                            endinput = 1 # this happens with real files.
418                    elif fd == fromcfno :
419                        outdata += data
420                    elif fd == cerrfno :   
421                        errdata += data
422                if (mask & select.POLLHUP) or (mask & select.POLLERR) :
423                    # I've never seen POLLERR myself, but this probably
424                    # can't hurt to treat an error condition just like
425                    # an EOF.
426                    #
427                    # Some standard I/O stream has no more datas
[1458]428                    self.unregisterFileNo(pollster, fd)
[1222]429                    if fd == infno :
430                        # Here we are in the case where the input file is stdin.
431                        # which has no more data to be read.
[1289]432                        self.logdebug("Input data ends.")
[1222]433                        endinput = 1
434                    elif fd == fromcfno :   
435                        # This should never happen, since
436                        # CUPS backends don't send anything on their
[1289]437                        # standard output.
[1240]438                        # We are no more interested in this file descriptor       
[1291]439                        self.logdebug("Closing real backend's stdout.")
[1240]440                        os.close(fromcfno)
[1289]441                        endoutput = 1
[1222]442                    elif fd == cerrfno :   
443                        # Original CUPS backend has finished
[1289]444                        # to write informations on its standard error.
445                        # We are no more interested in this file descriptor        .
[1291]446                        self.logdebug("Closing real backend's stderr.")
[1240]447                        os.close(cerrfno)
[1289]448                        enderr = 1
[1291]449            if killed or (inputclosed and outputclosed and errclosed) :
450                break
[1191]451               
[1291]452        # We must close the real backend's input stream
453        if killed and not inputclosed :
454            self.logdebug("Forcing close of real backend's stdin.")
455            os.close(tocfno)
456       
[1222]457        # Input file was a real file, we have to close it.   
458        if mustclose :
459            infile.close()
[1185]460           
[1271]461        self.logdebug("Exiting streams polling loop...")
[1240]462           
[1222]463        # Check exit code of original CUPS backend.   
[1335]464        if status == -1 :
465            # we exited the loop before the real backend exited
466            # now we have to wait for it to finish and get its status
467            status = subprocess.wait()
[1222]468        if os.WIFEXITED(status) :
469            retcode = os.WEXITSTATUS(status)
[1291]470        elif not killed :   
[1271]471            self.logger.log_message(_("CUPS backend %s died abnormally.") % realbackend, "error")
[1222]472            retcode = -1
[1291]473        else :   
474            retcode = self.removeJob()
[1271]475        return retcode   
[1222]476   
[1177]477if __name__ == "__main__" :   
478    # This is a CUPS backend, we should act and die like a CUPS backend
479    if len(sys.argv) == 1 :
[1178]480        # we will execute each existing backend in device enumeration mode
481        # and generate their PyKota accounting counterpart
482        (directory, myname) = os.path.split(sys.argv[0])
483        for backend in [os.path.join(directory, b) for b in os.listdir(directory) if os.path.isfile(os.path.join(directory, b)) and (b != myname)] :
484            answer = os.popen(backend, "r")
485            try :
486                devices = [line.strip() for line in answer.readlines()]
487            except :   
488                devices = []
489            status = answer.close()
490            if status is None :
491                for d in devices :
[1180]492                    # each line is of the form : 'xxxx xxxx "xxxx xxx" "xxxx xxx"'
493                    # so we have to decompose it carefully
[1178]494                    fdevice = cStringIO.StringIO("%s" % d)
495                    tokenizer = shlex.shlex(fdevice)
496                    tokenizer.wordchars = tokenizer.wordchars + r".:,?!~/\_$*-+={}[]()#"
497                    arguments = []
498                    while 1 :
499                        token = tokenizer.get_token()
500                        if token :
501                            arguments.append(token)
502                        else :
503                            break
504                    fdevice.close()
[1180]505                    try :
506                        (devicetype, device, name, fullname) = arguments
507                    except ValueError :   
508                        pass    # ignore this 'bizarre' device
509                    else :   
510                        if name.startswith('"') and name.endswith('"') :
511                            name = name[1:-1]
512                        if fullname.startswith('"') and fullname.endswith('"') :
513                            fullname = fullname[1:-1]
[1191]514                        print '%s cupspykota:%s "PyKota+%s" "PyKota managed %s"' % (devicetype, device, name, fullname)
[1177]515        retcode = 0
516    elif len(sys.argv) not in (6, 7) :   
517        sys.stderr.write("ERROR: %s job-id user title copies options [file]\n" % sys.argv[0])
518        retcode = 1
519    else :   
520        try :
521            # Initializes the backend
[1271]522            kotabackend = PyKotaBackend()   
523            retcode = kotabackend.mainWork()
[1196]524        except (PyKotaToolError, PyKotaConfigError, PyKotaStorageError, PyKotaAccounterError, PyKotaRequesterError, AttributeError, KeyError, IndexError, ValueError, TypeError, IOError), msg :
[1390]525            import traceback
[1400]526            mm = [((f.endswith('\n') and f) or (f + '\n')) for f in traceback.format_exception(*sys.exc_info())]
527            sys.stderr.write("ERROR : cupspykota backend failed (%s)\n%s" % (msg, "ERROR : ".join(mm)))
[1177]528            sys.stderr.flush()
529            retcode = 1
530       
531        try :
532            kotabackend.storage.close()
533        except (TypeError, NameError, AttributeError) :   
534            pass
535       
536    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.