root / tea4cups / trunk / tea4cups @ 602

Revision 602, 39.7 kB (checked in by jerome, 19 years ago)

Doesn't set TEASTATUS when a prehook cancels the job

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Rev
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3
4# Tea4CUPS : Tee for CUPS
5#
6# (c) 2005 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23#
24
25import sys
26import os
27import popen2
28import errno
29import md5
30import cStringIO
31import shlex
32import tempfile
33import ConfigParser
34import select
35import signal
36import time
37from struct import unpack
38
39version = "2.00"
40
41class TeeError(Exception):
42    """Base exception for Tea4CUPS related stuff."""
43    def __init__(self, message = ""):
44        self.message = message
45        Exception.__init__(self, message)
46    def __repr__(self):
47        return self.message
48    __str__ = __repr__
49   
50class ConfigError(TeeError) :   
51    """Configuration related exceptions."""
52    pass 
53   
54class IPPError(TeeError) :   
55    """IPP related exceptions."""
56    pass 
57   
58class Popen4ForCUPS(popen2.Popen4) :
59    """Our own class to execute real backends.
60   
61       Their first argument is different from their path so using
62       native popen2.Popen3 would not be feasible.
63    """
64    def __init__(self, cmd, bufsize=-1, arg0=None) :
65        self.arg0 = arg0
66        popen2.Popen4.__init__(self, cmd, bufsize)
67       
68    def _run_child(self, cmd):
69        try :
70            MAXFD = os.sysconf("SC_OPEN_MAX")
71        except (AttributeError, ValueError) :   
72            MAXFD = 256
73        for i in range(3, MAXFD) : 
74            try:
75                os.close(i)
76            except OSError:
77                pass
78        try:
79            os.execvpe(cmd[0], [self.arg0 or cmd[0]] + cmd[1:], os.environ)
80        finally:
81            os._exit(1)
82   
83# Some IPP constants   
84OPERATION_ATTRIBUTES_TAG = 0x01
85JOB_ATTRIBUTES_TAG = 0x02
86END_OF_ATTRIBUTES_TAG = 0x03
87PRINTER_ATTRIBUTES_TAG = 0x04
88UNSUPPORTED_ATTRIBUTES_TAG = 0x05
89
90class IPPMessage :
91    """A class for IPP message files."""
92    def __init__(self, data) :
93        """Initializes an IPP Message object."""
94        self.data = data
95        self._attributes = {}
96        self.curname = None
97        self.tags = [ None ] * 256      # by default all tags reserved
98       
99        # Delimiter tags
100        self.tags[0x01] = "operation-attributes-tag"
101        self.tags[0x02] = "job-attributes-tag"
102        self.tags[0x03] = "end-of-attributes-tag"
103        self.tags[0x04] = "printer-attributes-tag"
104        self.tags[0x05] = "unsupported-attributes-tag"
105       
106        # out of band values
107        self.tags[0x10] = "unsupported"
108        self.tags[0x11] = "reserved-for-future-default"
109        self.tags[0x12] = "unknown"
110        self.tags[0x13] = "no-value"
111       
112        # integer values
113        self.tags[0x20] = "generic-integer"
114        self.tags[0x21] = "integer"
115        self.tags[0x22] = "boolean"
116        self.tags[0x23] = "enum"
117       
118        # octetString
119        self.tags[0x30] = "octetString-with-an-unspecified-format"
120        self.tags[0x31] = "dateTime"
121        self.tags[0x32] = "resolution"
122        self.tags[0x33] = "rangeOfInteger"
123        self.tags[0x34] = "reserved-for-collection"
124        self.tags[0x35] = "textWithLanguage"
125        self.tags[0x36] = "nameWithLanguage"
126       
127        # character strings
128        self.tags[0x20] = "generic-character-string"
129        self.tags[0x41] = "textWithoutLanguage"
130        self.tags[0x42] = "nameWithoutLanguage"
131        # self.tags[0x43] = "reserved"
132        self.tags[0x44] = "keyword"
133        self.tags[0x45] = "uri"
134        self.tags[0x46] = "uriScheme"
135        self.tags[0x47] = "charset"
136        self.tags[0x48] = "naturalLanguage"
137        self.tags[0x49] = "mimeMediaType"
138       
139        # now parses the IPP message
140        self.parse()
141       
142    def __getattr__(self, attrname) :   
143        """Allows self.attributes to return the attributes names."""
144        if attrname == "attributes" :
145            keys = self._attributes.keys()
146            keys.sort()
147            return keys
148        raise AttributeError, attrname
149           
150    def __getitem__(self, ippattrname) :   
151        """Fakes a dictionnary d['key'] notation."""
152        value = self._attributes.get(ippattrname)
153        if value is not None :
154            if len(value) == 1 :
155                value = value[0]
156        return value       
157    get = __getitem__   
158       
159    def parseTag(self) :   
160        """Extracts information from an IPP tag."""
161        pos = self.position
162        valuetag = self.tags[ord(self.data[pos])]
163        # print valuetag.get("name")
164        pos += 1
165        posend = pos2 = pos + 2
166        namelength = unpack(">H", self.data[pos:pos2])[0]
167        if not namelength :
168            name = self.curname
169        else :   
170            posend += namelength
171            self.curname = name = self.data[pos2:posend]
172        pos2 = posend + 2
173        valuelength = unpack(">H", self.data[posend:pos2])[0]
174        posend = pos2 + valuelength
175        value = self.data[pos2:posend]
176        oldval = self._attributes.setdefault(name, [])
177        oldval.append(value)
178        return posend - self.position
179       
180    def operation_attributes_tag(self) : 
181        """Indicates that the parser enters into an operation-attributes-tag group."""
182        return self.parseTag()
183       
184    def job_attributes_tag(self) : 
185        """Indicates that the parser enters into an operation-attributes-tag group."""
186        return self.parseTag()
187       
188    def printer_attributes_tag(self) : 
189        """Indicates that the parser enters into an operation-attributes-tag group."""
190        return self.parseTag()
191       
192    def parse(self) :
193        """Parses an IPP Message.
194       
195           NB : Only a subset of RFC2910 is implemented.
196           We are only interested in textual informations for now anyway.
197        """
198        self.version = "%s.%s" % (ord(self.data[0]), ord(self.data[1]))
199        self.operation_id = "0x%04x" % unpack(">H", self.data[2:4])[0]
200        self.request_id = "0x%08x" % unpack(">I", self.data[4:8])[0]
201        self.position = 8
202        try :
203            tag = ord(self.data[self.position])
204            while tag != END_OF_ATTRIBUTES_TAG :
205                self.position += 1
206                name = self.tags[tag]
207                if name is not None :
208                    func = getattr(self, name.replace("-", "_"), None)
209                    if func is not None :
210                        self.position += func()
211                        if ord(self.data[self.position]) > UNSUPPORTED_ATTRIBUTES_TAG :
212                            self.position -= 1
213                            continue
214                tag = ord(self.data[self.position])
215        except IndexError :
216            raise IPPError, "Unexpected end of IPP message."
217           
218class FakeConfig :   
219    """Fakes a configuration file parser."""
220    def get(self, section, option, raw=0) :
221        """Fakes the retrieval of a global option."""
222        raise ConfigError, "Invalid configuration file : no option %s in section [%s]" % (option, section)
223       
224class CupsBackend :
225    """Base class for tools with no database access."""
226    def __init__(self) :
227        """Initializes the CUPS backend wrapper."""
228        self.gotSigTerm = 0
229        self.isCancelled = 0    # did a prehook cancel the print job ?
230        signal.signal(signal.SIGTERM, signal.SIG_IGN)
231        signal.signal(signal.SIGPIPE, signal.SIG_IGN)
232        self.MyName = "Tea4CUPS"
233        self.myname = "tea4cups"
234        self.pid = os.getpid()
235        confdir = os.environ.get("CUPS_SERVERROOT", ".") 
236        self.conffile = os.path.join(confdir, "%s.conf" % self.myname)
237        if os.path.isfile(self.conffile) :
238            self.config = ConfigParser.ConfigParser()
239            self.config.read([self.conffile])
240            self.debug = self.isTrue(self.getGlobalOption("debug", ignore=1))
241        else :   
242            self.config = FakeConfig()
243            self.debug = 1      # no config, so force debug mode !
244           
245    def logInfo(self, message, level="info") :       
246        """Logs a message to CUPS' error_log file."""
247        sys.stderr.write("%s: %s v%s (PID %i) : %s\n" % (level.upper(), self.MyName, version, os.getpid(), message))
248        sys.stderr.flush()
249       
250    def logDebug(self, message) :   
251        """Logs something to debug output if debug is enabled."""
252        if self.debug :
253            self.logInfo(message, level="debug")
254       
255    def isTrue(self, option) :       
256        """Returns 1 if option is set to true, else 0."""
257        if (option is not None) and (option.upper().strip() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
258            return 1
259        else :   
260            return 0
261                       
262    def getGlobalOption(self, option, ignore=0) :   
263        """Returns an option from the global section, or raises a ConfigError if ignore is not set, else returns None."""
264        try :
265            return self.config.get("global", option, raw=1)
266        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
267            if not ignore :
268                raise ConfigError, "Option %s not found in section global of %s" % (option, self.conffile)
269               
270    def getPrintQueueOption(self, printqueuename, option, ignore=0) :   
271        """Returns an option from the printer section, or the global section, or raises a ConfigError."""
272        globaloption = self.getGlobalOption(option, ignore=1)
273        try :
274            return self.config.get(printqueuename, option, raw=1)
275        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
276            if globaloption is not None :
277                return globaloption
278            elif not ignore :
279                raise ConfigError, "Option %s not found in section [%s] of %s" % (option, printqueuename, self.conffile)
280               
281    def enumBranches(self, printqueuename, branchtype="tee") :
282        """Returns the list of branchtypes branches for a particular section's."""
283        branchbasename = "%s_" % branchtype.lower()
284        try :
285            globalbranches = [ (k, v) for (k, v) in self.config.items("global") if k.startswith(branchbasename) ]
286        except ConfigParser.NoSectionError, msg :   
287            raise ConfigError, "Invalid configuration file : %s" % msg
288        try :
289            sectionbranches = [ (k, v) for (k, v) in self.config.items(printqueuename) if k.startswith(branchbasename) ]
290        except ConfigParser.NoSectionError, msg :   
291            self.logInfo("No section for print queue %s : %s" % (printqueuename, msg))
292            sectionbranches = []
293        branches = {}
294        for (k, v) in globalbranches :
295            value = v.strip()
296            if value :
297                branches[k] = value
298        for (k, v) in sectionbranches :   
299            value = v.strip()
300            if value :
301                branches[k] = value # overwrite any global option or set a new value
302            else :   
303                del branches[k] # empty value disables a global option
304        return branches
305       
306    def discoverOtherBackends(self) :   
307        """Discovers the other CUPS backends.
308       
309           Executes each existing backend in turn in device enumeration mode.
310           Returns the list of available backends.
311        """
312        # Unfortunately this method can't output any debug information
313        # to stdout or stderr, else CUPS considers that the device is
314        # not available.
315        available = []
316        (directory, myname) = os.path.split(sys.argv[0])
317        if not directory :
318            directory = "./"
319        tmpdir = tempfile.gettempdir()
320        lockfilename = os.path.join(tmpdir, "%s..LCK" % myname)
321        if os.path.exists(lockfilename) :
322            lockfile = open(lockfilename, "r")
323            pid = int(lockfile.read())
324            lockfile.close()
325            try :
326                # see if the pid contained in the lock file is still running
327                os.kill(pid, 0)
328            except OSError, e :   
329                if e.errno != errno.EPERM :
330                    # process doesn't exist anymore
331                    os.remove(lockfilename)
332           
333        if not os.path.exists(lockfilename) :
334            lockfile = open(lockfilename, "w")
335            lockfile.write("%i" % self.pid)
336            lockfile.close()
337            allbackends = [ os.path.join(directory, b) \
338                                for b in os.listdir(directory) 
339                                    if os.access(os.path.join(directory, b), os.X_OK) \
340                                        and (b != myname)] 
341            for backend in allbackends :                           
342                answer = os.popen(backend, "r")
343                try :
344                    devices = [line.strip() for line in answer.readlines()]
345                except :   
346                    devices = []
347                status = answer.close()
348                if status is None :
349                    for d in devices :
350                        # each line is of the form :
351                        # 'xxxx xxxx "xxxx xxx" "xxxx xxx"'
352                        # so we have to decompose it carefully
353                        fdevice = cStringIO.StringIO(d)
354                        tokenizer = shlex.shlex(fdevice)
355                        tokenizer.wordchars = tokenizer.wordchars + \
356                                                        r".:,?!~/\_$*-+={}[]()#"
357                        arguments = []
358                        while 1 :
359                            token = tokenizer.get_token()
360                            if token :
361                                arguments.append(token)
362                            else :
363                                break
364                        fdevice.close()
365                        try :
366                            (devicetype, device, name, fullname) = arguments
367                        except ValueError :   
368                            pass    # ignore this 'bizarre' device
369                        else :   
370                            if name.startswith('"') and name.endswith('"') :
371                                name = name[1:-1]
372                            if fullname.startswith('"') and fullname.endswith('"') :
373                                fullname = fullname[1:-1]
374                            available.append('%s %s:%s "%s+%s" "%s managed %s"' \
375                                                 % (devicetype, self.myname, device, self.MyName, name, self.MyName, fullname))
376            os.remove(lockfilename)
377        available.append('direct %s:// "%s+Nothing" "%s managed Virtual Printer"' \
378                             % (self.myname, self.MyName, self.MyName))
379        return available
380                       
381    def initBackend(self) :   
382        """Initializes the backend's attributes."""
383        # check that the DEVICE_URI environment variable's value is
384        # prefixed with self.myname otherwise don't touch it.
385        # If this is the case, we have to remove the prefix from
386        # the environment before launching the real backend
387        muststartwith = "%s:" % self.myname
388        device_uri = os.environ.get("DEVICE_URI", "")
389        if device_uri.startswith(muststartwith) :
390            fulldevice_uri = device_uri[:]
391            device_uri = fulldevice_uri[len(muststartwith):]
392            for i in range(2) :
393                if device_uri.startswith("/") : 
394                    device_uri = device_uri[1:]
395        try :
396            (backend, destination) = device_uri.split(":", 1) 
397        except ValueError :   
398            if not device_uri :
399                self.logDebug("Not attached to an existing print queue.")
400                backend = ""
401            else :   
402                raise TeeError, "Invalid DEVICE_URI : %s\n" % device_uri
403       
404        self.JobId = sys.argv[1].strip()
405        self.UserName = sys.argv[2].strip()
406        self.Title = sys.argv[3].strip()
407        self.Copies = int(sys.argv[4].strip())
408        self.Options = sys.argv[5].strip()
409        if len(sys.argv) == 7 :
410            self.InputFile = sys.argv[6] # read job's datas from file
411        else :   
412            self.InputFile = None        # read job's datas from stdin
413           
414        self.RealBackend = backend
415        self.DeviceURI = device_uri
416        self.PrinterName = os.environ.get("PRINTER", "")
417        self.Directory = self.getPrintQueueOption(self.PrinterName, "directory")
418        self.DataFile = os.path.join(self.Directory, "%s-%s-%s-%s" % (self.myname, self.PrinterName, self.UserName, self.JobId))
419        self.ClientHost = self.extractJobOriginatingHostName()
420           
421    def getCupsConfigDirectives(self, directives=[]) :
422        """Retrieves some CUPS directives from its configuration file.
423       
424           Returns a mapping with lowercased directives as keys and
425           their setting as values.
426        """
427        dirvalues = {} 
428        cupsroot = os.environ.get("CUPS_SERVERROOT", "/etc/cups")
429        cupsdconf = os.path.join(cupsroot, "cupsd.conf")
430        try :
431            conffile = open(cupsdconf, "r")
432        except IOError :   
433            raise TeeError, "Unable to open %s" % cupsdconf
434        else :   
435            for line in conffile.readlines() :
436                linecopy = line.strip().lower()
437                for di in [d.lower() for d in directives] :
438                    if linecopy.startswith("%s " % di) :
439                        try :
440                            val = line.split()[1]
441                        except :   
442                            pass # ignore errors, we take the last value in any case.
443                        else :   
444                            dirvalues[di] = val
445            conffile.close()           
446        return dirvalues       
447           
448    def extractJobOriginatingHostName(self) :       
449        """Extracts the client's hostname or IP address from the CUPS message file for current job."""
450        cupsdconf = self.getCupsConfigDirectives(["RequestRoot"])
451        requestroot = cupsdconf.get("requestroot", "/var/spool/cups")
452        if (len(self.JobId) < 5) and self.JobId.isdigit() :
453            ippmessagefile = "c%05i" % int(self.JobId)
454        else :   
455            ippmessagefile = "c%s" % self.JobId
456        ippmessagefile = os.path.join(requestroot, ippmessagefile)
457        ippmessage = {}
458        try :
459            ippdatafile = open(ippmessagefile)
460        except :   
461            self.logInfo("Unable to open IPP message file %s" % ippmessagefile, "warn")
462        else :   
463            self.logDebug("Parsing of IPP message file %s begins." % ippmessagefile)
464            try :
465                ippmessage = IPPMessage(ippdatafile.read())
466            except IPPError, msg :   
467                self.logInfo("Error while parsing %s : %s" % (ippmessagefile, msg), "warn")
468            else :   
469                self.logDebug("Parsing of IPP message file %s ends." % ippmessagefile)
470            ippdatafile.close()
471        return ippmessage.get("job-originating-host-name")   
472               
473    def exportAttributes(self) :   
474        """Exports our backend's attributes to the environment."""
475        os.environ["DEVICE_URI"] = self.DeviceURI       # WARNING !
476        os.environ["TEAPRINTERNAME"] = self.PrinterName
477        os.environ["TEADIRECTORY"] = self.Directory
478        os.environ["TEADATAFILE"] = self.DataFile
479        os.environ["TEAJOBSIZE"] = str(self.JobSize)
480        os.environ["TEAMD5SUM"] = self.JobMD5Sum
481        os.environ["TEACLIENTHOST"] = self.ClientHost or ""
482        os.environ["TEAJOBID"] = self.JobId
483        os.environ["TEAUSERNAME"] = self.UserName
484        os.environ["TEATITLE"] = self.Title
485        os.environ["TEACOPIES"] = str(self.Copies)
486        os.environ["TEAOPTIONS"] = self.Options
487        os.environ["TEAINPUTFILE"] = self.InputFile or ""
488       
489    def saveDatasAndCheckSum(self) :
490        """Saves the input datas into a static file."""
491        self.logDebug("Duplicating data stream into %s" % self.DataFile)
492        mustclose = 0
493        if self.InputFile is not None :
494            infile = open(self.InputFile, "rb")
495            mustclose = 1
496        else :   
497            infile = sys.stdin
498        CHUNK = 64*1024         # read 64 Kb at a time
499        dummy = 0
500        sizeread = 0
501        checksum = md5.new()
502        outfile = open(self.DataFile, "wb")   
503        while 1 :
504            data = infile.read(CHUNK) 
505            if not data :
506                break
507            sizeread += len(data)   
508            outfile.write(data)
509            checksum.update(data)   
510            if not (dummy % 32) : # Only display every 2 Mb
511                self.logDebug("%s bytes saved..." % sizeread)
512            dummy += 1   
513        outfile.close()
514        if mustclose :   
515            infile.close()
516        self.JobSize = sizeread   
517        self.JobMD5Sum = checksum.hexdigest()
518        self.logDebug("Job %s is %s bytes long." % (self.JobId, self.JobSize))
519        self.logDebug("Job %s MD5 sum is %s" % (self.JobId, self.JobMD5Sum))
520
521    def cleanUp(self) :
522        """Cleans up the place."""
523        if not self.isTrue(self.getPrintQueueOption(self.PrinterName, "keepfiles", ignore=1)) :
524            os.remove(self.DataFile)
525           
526    def sigtermHandler(self, signum, frame) :
527        """Sets an attribute whenever SIGTERM is received."""
528        self.gotSigTerm = 1
529        self.logInfo("SIGTERM received for Job %s." % self.JobId)
530       
531    def runBranches(self) :         
532        """Launches each hook or tee defined for the current print queue."""
533        exitcode = 0
534        signal.signal(signal.SIGTERM, self.sigtermHandler)
535        serialize = self.isTrue(self.getPrintQueueOption(self.PrinterName, "serialize", ignore=1))
536        for branchtype in ["prehook", "tee", "posthook"] :
537            branches = self.enumBranches(self.PrinterName, branchtype)
538            status = self.runCommands(branchtype, branches, serialize)
539            if status :
540                exitcode = status
541            if (branchtype == "prehook") and self.isCancelled :
542                break # We don't want to execute tees or posthooks in this case
543        signal.signal(signal.SIGTERM, signal.SIG_IGN)
544        if not exitcode :
545            self.logInfo("OK")
546        else :   
547            self.logInfo("An error occured, please check CUPS' error_log file.")
548        return exitcode
549       
550    def runCommands(self, btype, branches, serialize) :   
551        """Runs the commands for a particular branch type."""
552        exitcode = 0 
553        btype = btype.lower()
554        btypetitle = btype.title()
555        branchlist = branches.keys()   
556        branchlist.sort()
557        if serialize :
558            self.logDebug("Begin serialized %ss" % btypetitle)
559            if (btype == "tee") and self.RealBackend :
560                self.logDebug("Launching original backend %s for printer %s" % (self.RealBackend, self.PrinterName))
561                exitcode = self.runOriginalBackend()
562            for branch in branchlist :
563                command = branches[branch]
564                if self.gotSigTerm :
565                    break
566                self.logDebug("Launching %s : %s" % (branch, command))
567                retcode = os.system(command)
568                self.logDebug("Exit code for %s %s on printer %s is %s" % (btype, branch, self.PrinterName, retcode))
569                if os.WIFEXITED(retcode) :
570                    retcode = os.WEXITSTATUS(retcode)
571                if retcode :   
572                    if (btype == "prehook") and (retcode == 255) : # -1
573                        self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch))
574                        self.isCancelled = 1
575                    else :   
576                        self.logInfo("%s %s on printer %s didn't exit successfully." % (btypetitle, branch, self.PrinterName), "error")
577                        exitcode = 1
578            self.logDebug("End serialized %ss" % btypetitle)
579        else :       
580            self.logDebug("Begin forked %ss" % btypetitle)
581            pids = {}
582            if (btype == "tee") and self.RealBackend :
583                branches["Original backend"] = None     # Fakes a tee to launch one more child
584                branchlist = ["Original backend"] + branchlist
585            for branch in branchlist :
586                command = branches[branch]
587                if self.gotSigTerm :
588                    break
589                pid = os.fork()
590                if pid :
591                    pids[branch] = pid
592                else :   
593                    if branch == "Original backend" :
594                        self.logDebug("Launching original backend %s for printer %s" % (self.RealBackend, self.PrinterName))
595                        sys.exit(self.runOriginalBackend())
596                    else :
597                        self.logDebug("Launching %s : %s" % (branch, command))
598                        retcode = os.system(command)
599                        if os.WIFEXITED(retcode) :
600                            retcode = os.WEXITSTATUS(retcode)
601                        else :   
602                            retcode = -1
603                        sys.exit(retcode)
604            for (branch, pid) in pids.items() :
605                (childpid, retcode) = os.waitpid(pid, 0)
606                self.logDebug("Exit code for %s %s (PID %s) on printer %s is %s" % (btype, branch, childpid, self.PrinterName, retcode))
607                if os.WIFEXITED(retcode) :
608                    retcode = os.WEXITSTATUS(retcode)
609                if retcode :   
610                    if (btype == "prehook") and (retcode == 255) : # -1
611                        self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch))
612                        self.isCancelled = 1
613                    else :   
614                        self.logInfo("%s %s (PID %s) on printer %s didn't exit successfully." % (btypetitle, branch, childpid, self.PrinterName), "error")
615                        exitcode = 1
616                if branch == "Original backend" :   
617                    os.environ["TEASTATUS"] = str(retcode)
618            self.logDebug("End forked %ss" % btypetitle)
619        return exitcode
620       
621    def unregisterFileNo(self, pollobj, fileno) :               
622        """Removes a file handle from the polling object."""
623        try :
624            pollobj.unregister(fileno)
625        except KeyError :   
626            self.logInfo("File number %s unregistered twice from polling object, ignored." % fileno, "warn")
627        except :   
628            self.logDebug("Error while unregistering file number %s from polling object." % fileno)
629        else :   
630            self.logDebug("File number %s unregistered from polling object." % fileno)
631           
632    def formatFileEvent(self, fd, mask) :       
633        """Formats file debug info."""
634        maskval = []
635        if mask & select.POLLIN :
636            maskval.append("POLLIN")
637        if mask & select.POLLOUT :
638            maskval.append("POLLOUT")
639        if mask & select.POLLPRI :
640            maskval.append("POLLPRI")
641        if mask & select.POLLERR :
642            maskval.append("POLLERR")
643        if mask & select.POLLHUP :
644            maskval.append("POLLHUP")
645        if mask & select.POLLNVAL :
646            maskval.append("POLLNVAL")
647        return "%s (%s)" % (fd, " | ".join(maskval))
648       
649    def runOriginalBackend(self) :   
650        """Launches the original backend."""
651        originalbackend = os.path.join(os.path.split(sys.argv[0])[0], self.RealBackend)
652        arguments = sys.argv
653        self.logDebug("Starting original backend %s with args %s" % (originalbackend, " ".join(['"%s"' % a for a in ([os.environ["DEVICE_URI"]] + arguments[1:])])))
654        subprocess = Popen4ForCUPS([originalbackend] + arguments[1:], bufsize=0, arg0=os.environ["DEVICE_URI"])
655       
656        # Save file descriptors, we will need them later.
657        stderrfno = sys.stderr.fileno()
658        fromcfno = subprocess.fromchild.fileno()
659        tocfno = subprocess.tochild.fileno()
660       
661        # We will have to be careful when dealing with I/O
662        # So we use a poll object to know when to read or write
663        pollster = select.poll()
664        pollster.register(fromcfno, select.POLLIN | select.POLLPRI)
665        pollster.register(stderrfno, select.POLLOUT)
666        pollster.register(tocfno, select.POLLOUT)
667       
668        # Initialize our buffers
669        indata = ""
670        outdata = ""
671        endinput = endoutput = 0
672        inputclosed = outputclosed = 0
673        totaltochild = totalfromcups = 0
674        totalfromchild = totaltocups = 0
675       
676        if self.InputFile is None :
677           # this is not a real file, we read the job's data
678            # from our temporary file which is a copy of stdin
679            inf = open(self.DataFile, "rb")
680            infno = inf.fileno()
681            pollster.register(infno, select.POLLIN | select.POLLPRI)
682        else :   
683            # job's data is in a file, no need to pass the data
684            # to the original backend
685            self.logDebug("Job's data is in %s" % self.InputFile)
686            infno = None
687            endinput = 1
688       
689        self.logDebug("Entering streams polling loop...")
690        MEGABYTE = 1024*1024
691        killed = 0
692        status = -1
693        while (status == -1) and (not killed) and not (inputclosed and outputclosed) :
694            # First check if original backend is still alive
695            status = subprocess.poll()
696           
697            # Now if we got SIGTERM, we have
698            # to kill -TERM the original backend
699            if self.gotSigTerm and not killed :
700                try :
701                    os.kill(subprocess.pid, signal.SIGTERM)
702                except OSError, msg : # ignore but logs if process was already killed.
703                    self.logDebug("Error while sending signal to pid %s : %s" % (subprocess.pid, msg))
704                else :   
705                    self.logInfo(_("SIGTERM was sent to original backend %s (PID %s)") % (originalbackend, subprocess.pid))
706                    killed = 1
707           
708            # In any case, deal with any remaining I/O
709            try :
710                availablefds = pollster.poll(5000)
711            except select.error, msg :   
712                self.logDebug("Interrupted poll : %s" % msg)
713                availablefds = []
714            if not availablefds :
715                self.logDebug("Nothing to do, sleeping a bit...")
716                time.sleep(0.01) # give some time to the system
717            else :
718                for (fd, mask) in availablefds :
719                    try :
720                        if mask & select.POLLOUT :
721                            # We can write
722                            if fd == tocfno :
723                                if indata :
724                                    try :
725                                        nbwritten = os.write(fd, indata)   
726                                    except (OSError, IOError), msg :   
727                                        self.logDebug("Error while writing to original backend's stdin %s : %s" % (fd, msg))
728                                    else :   
729                                        if len(indata) != nbwritten :
730                                            self.logDebug("Short write to original backend's input !")
731                                        totaltochild += nbwritten   
732                                        self.logDebug("%s bytes sent to original backend so far..." % totaltochild)
733                                        indata = indata[nbwritten:]
734                                else :       
735                                    self.logDebug("No data to send to original backend yet, sleeping a bit...")
736                                    time.sleep(0.01)
737                                   
738                                if endinput :   
739                                    self.unregisterFileNo(pollster, tocfno)       
740                                    self.logDebug("Closing original backend's stdin.")
741                                    os.close(tocfno)
742                                    inputclosed = 1
743                            elif fd == stderrfno :
744                                if outdata :
745                                    try :
746                                        nbwritten = os.write(fd, outdata)
747                                    except (OSError, IOError), msg :   
748                                        self.logDebug("Error while writing to CUPS back channel (stderr) %s : %s" % (fd, msg))
749                                    else :
750                                        if len(outdata) != nbwritten :
751                                            self.logDebug("Short write to stderr (CUPS) !")
752                                        totaltocups += nbwritten   
753                                        self.logDebug("%s bytes sent back to CUPS so far..." % totaltocups)
754                                        outdata = outdata[nbwritten:]
755                                else :       
756                                    # self.logDebug("No data to send back to CUPS yet, sleeping a bit...") # Uncommenting this fills your logs
757                                    time.sleep(0.01) # Give some time to the system, stderr is ALWAYS writeable it seems.
758                                   
759                                if endoutput :   
760                                    self.unregisterFileNo(pollster, stderrfno)       
761                                    outputclosed = 1
762                            else :   
763                                self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask))
764                                time.sleep(0.01)
765                               
766                        if mask & (select.POLLIN | select.POLLPRI) :     
767                            # We have something to read
768                            try :
769                                data = os.read(fd, MEGABYTE)
770                            except (IOError, OSError), msg :   
771                                self.logDebug("Error while reading file %s : %s" % (fd, msg))
772                            else :
773                                if fd == infno :
774                                    if not data :    # If yes, then no more input data
775                                        self.unregisterFileNo(pollster, infno)
776                                        self.logDebug("Input data ends.")
777                                        endinput = 1 # this happens with real files.
778                                    else :   
779                                        indata += data
780                                        totalfromcups += len(data)
781                                        self.logDebug("%s bytes read from CUPS so far..." % totalfromcups)
782                                elif fd == fromcfno :
783                                    if not data :
784                                        self.logDebug("No back channel data to read from original backend yet, sleeping a bit...")
785                                        time.sleep(0.01)
786                                    else :
787                                        outdata += data
788                                        totalfromchild += len(data)
789                                        self.logDebug("%s bytes read from original backend so far..." % totalfromchild)
790                                else :   
791                                    self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask))
792                                    time.sleep(0.01)
793                                   
794                        if mask & (select.POLLHUP | select.POLLERR) :
795                            # Treat POLLERR as an EOF.
796                            # Some standard I/O stream has no more datas
797                            self.unregisterFileNo(pollster, fd)
798                            if fd == infno :
799                                # Here we are in the case where the input file is stdin.
800                                # which has no more data to be read.
801                                self.logDebug("Input data ends.")
802                                endinput = 1
803                            elif fd == fromcfno :   
804                                # We are no more interested in this file descriptor       
805                                self.logDebug("Closing original backend's stdout+stderr.")
806                                os.close(fromcfno)
807                                endoutput = 1
808                            else :   
809                                self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask))
810                                time.sleep(0.01)
811                               
812                        if mask & select.POLLNVAL :       
813                            self.logDebug("File %s was closed. Unregistering from polling object." % fd)
814                            self.unregisterFileNo(pollster, fd)
815                    except IOError, msg :           
816                        self.logDebug("Got an IOError : %s" % msg) # we got signalled during an I/O
817               
818        # We must close the original backend's input stream
819        if killed and not inputclosed :
820            self.logDebug("Forcing close of original backend's stdin.")
821            os.close(tocfno)
822       
823        self.logDebug("Exiting streams polling loop...")
824       
825        self.logDebug("input data's final length : %s" % len(indata))
826        self.logDebug("back-channel data's final length : %s" % len(outdata))
827       
828        self.logDebug("Total bytes read from CUPS (job's datas) : %s" % totalfromcups)
829        self.logDebug("Total bytes sent to original backend (job's datas) : %s" % totaltochild)
830       
831        self.logDebug("Total bytes read from original backend (back-channel datas) : %s" % totalfromchild)
832        self.logDebug("Total bytes sent back to CUPS (back-channel datas) : %s" % totaltocups)
833       
834        # Check exit code of original CUPS backend.   
835        if status == -1 :
836            # we exited the loop before the original backend exited
837            # now we have to wait for it to finish and get its status
838            self.logDebug("Waiting for original backend to exit...")
839            try :
840                status = subprocess.wait()
841            except OSError : # already dead : TODO : detect when abnormal
842                status = 0
843        if os.WIFEXITED(status) :
844            return os.WEXITSTATUS(status)
845        elif not killed :   
846            self.logInfo("CUPS backend %s died abnormally." % originalbackend, "error")
847            return -1
848        else :   
849            return 1
850       
851if __name__ == "__main__" :   
852    # This is a CUPS backend, we should act and die like a CUPS backend
853    wrapper = CupsBackend()
854    if len(sys.argv) == 1 :
855        print "\n".join(wrapper.discoverOtherBackends())
856        sys.exit(0)               
857    elif len(sys.argv) not in (6, 7) :   
858        sys.stderr.write("ERROR: %s job-id user title copies options [file]\n"\
859                              % sys.argv[0])
860        sys.exit(1)
861    else :   
862        try :
863            wrapper.initBackend()
864            wrapper.saveDatasAndCheckSum()
865            wrapper.exportAttributes()
866            retcode = wrapper.runBranches()
867            wrapper.cleanUp()
868        except SystemExit, e :   
869            retcode = e.code
870        except :   
871            import traceback
872            lines = []
873            for line in traceback.format_exception(*sys.exc_info()) :
874                lines.extend([l for l in line.split("\n") if l])
875            msg = "ERROR: ".join(["%s (PID %s) : %s\n" % (wrapper.MyName, wrapper.pid, l) for l in (["ERROR: Tea4CUPS v%s" % version] + lines)])
876            sys.stderr.write(msg)
877            sys.stderr.flush()
878            retcode = 1
879        sys.exit(retcode)
Note: See TracBrowser for help on using the browser.