root / tea4cups / trunk / tea4cups @ 626

Revision 626, 40.4 kB (checked in by jerome, 19 years ago)

Improved error handling

  • 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.11_unofficial"
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 a job-attributes-tag group."""
186        return self.parseTag()
187       
188    def printer_attributes_tag(self) : 
189        """Indicates that the parser enters into a printer-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 an 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        signal.signal(signal.SIGTERM, signal.SIG_IGN)
229        signal.signal(signal.SIGPIPE, signal.SIG_IGN)
230        self.MyName = "Tea4CUPS"
231        self.myname = "tea4cups"
232        self.pid = os.getpid()
233       
234    def readConfig(self) :   
235        """Reads the configuration file."""
236        confdir = os.environ.get("CUPS_SERVERROOT", ".") 
237        self.conffile = os.path.join(confdir, "%s.conf" % self.myname)
238        if os.path.isfile(self.conffile) :
239            self.config = ConfigParser.ConfigParser()
240            self.config.read([self.conffile])
241            self.debug = self.isTrue(self.getGlobalOption("debug", ignore=1))
242        else :   
243            self.config = FakeConfig()
244            self.debug = 1      # no config, so force debug mode !
245           
246    def logInfo(self, message, level="info") :       
247        """Logs a message to CUPS' error_log file."""
248        sys.stderr.write("%s: %s v%s (PID %i) : %s\n" % (level.upper(), self.MyName, version, os.getpid(), message))
249        sys.stderr.flush()
250       
251    def logDebug(self, message) :   
252        """Logs something to debug output if debug is enabled."""
253        if self.debug :
254            self.logInfo(message, level="debug")
255       
256    def isTrue(self, option) :       
257        """Returns 1 if option is set to true, else 0."""
258        if (option is not None) and (option.upper().strip() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
259            return 1
260        else :   
261            return 0
262                       
263    def getGlobalOption(self, option, ignore=0) :   
264        """Returns an option from the global section, or raises a ConfigError if ignore is not set, else returns None."""
265        try :
266            return self.config.get("global", option, raw=1)
267        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
268            if not ignore :
269                raise ConfigError, "Option %s not found in section global of %s" % (option, self.conffile)
270               
271    def getPrintQueueOption(self, printqueuename, option, ignore=0) :   
272        """Returns an option from the printer section, or the global section, or raises a ConfigError."""
273        globaloption = self.getGlobalOption(option, ignore=1)
274        try :
275            return self.config.get(printqueuename, option, raw=1)
276        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
277            if globaloption is not None :
278                return globaloption
279            elif not ignore :
280                raise ConfigError, "Option %s not found in section [%s] of %s" % (option, printqueuename, self.conffile)
281               
282    def enumBranches(self, printqueuename, branchtype="tee") :
283        """Returns the list of branchtypes branches for a particular section's."""
284        branchbasename = "%s_" % branchtype.lower()
285        try :
286            globalbranches = [ (k, v) for (k, v) in self.config.items("global") if k.startswith(branchbasename) ]
287        except ConfigParser.NoSectionError, msg :   
288            raise ConfigError, "Invalid configuration file : %s" % msg
289        try :
290            sectionbranches = [ (k, v) for (k, v) in self.config.items(printqueuename) if k.startswith(branchbasename) ]
291        except ConfigParser.NoSectionError, msg :   
292            self.logInfo("No section for print queue %s : %s" % (printqueuename, msg))
293            sectionbranches = []
294        branches = {}
295        for (k, v) in globalbranches :
296            value = v.strip()
297            if value :
298                branches[k] = value
299        for (k, v) in sectionbranches :   
300            value = v.strip()
301            if value :
302                branches[k] = value # overwrite any global option or set a new value
303            else :   
304                del branches[k] # empty value disables a global option
305        return branches
306       
307    def discoverOtherBackends(self) :   
308        """Discovers the other CUPS backends.
309       
310           Executes each existing backend in turn in device enumeration mode.
311           Returns the list of available backends.
312        """
313        # Unfortunately this method can't output any debug information
314        # to stdout or stderr, else CUPS considers that the device is
315        # not available.
316        available = []
317        (directory, myname) = os.path.split(sys.argv[0])
318        if not directory :
319            directory = "./"
320        tmpdir = tempfile.gettempdir()
321        lockfilename = os.path.join(tmpdir, "%s..LCK" % myname)
322        if os.path.exists(lockfilename) :
323            lockfile = open(lockfilename, "r")
324            pid = int(lockfile.read())
325            lockfile.close()
326            try :
327                # see if the pid contained in the lock file is still running
328                os.kill(pid, 0)
329            except OSError, e :   
330                if e.errno != errno.EPERM :
331                    # process doesn't exist anymore
332                    os.remove(lockfilename)
333           
334        if not os.path.exists(lockfilename) :
335            lockfile = open(lockfilename, "w")
336            lockfile.write("%i" % self.pid)
337            lockfile.close()
338            allbackends = [ os.path.join(directory, b) \
339                                for b in os.listdir(directory) 
340                                    if os.access(os.path.join(directory, b), os.X_OK) \
341                                        and (b != myname)] 
342            for backend in allbackends :                           
343                answer = os.popen(backend, "r")
344                try :
345                    devices = [line.strip() for line in answer.readlines()]
346                except :   
347                    devices = []
348                status = answer.close()
349                if status is None :
350                    for d in devices :
351                        # each line is of the form :
352                        # 'xxxx xxxx "xxxx xxx" "xxxx xxx"'
353                        # so we have to decompose it carefully
354                        fdevice = cStringIO.StringIO(d)
355                        tokenizer = shlex.shlex(fdevice)
356                        tokenizer.wordchars = tokenizer.wordchars + \
357                                                        r".:,?!~/\_$*-+={}[]()#"
358                        arguments = []
359                        while 1 :
360                            token = tokenizer.get_token()
361                            if token :
362                                arguments.append(token)
363                            else :
364                                break
365                        fdevice.close()
366                        try :
367                            (devicetype, device, name, fullname) = arguments
368                        except ValueError :   
369                            pass    # ignore this 'bizarre' device
370                        else :   
371                            if name.startswith('"') and name.endswith('"') :
372                                name = name[1:-1]
373                            if fullname.startswith('"') and fullname.endswith('"') :
374                                fullname = fullname[1:-1]
375                            available.append('%s %s:%s "%s+%s" "%s managed %s"' \
376                                                 % (devicetype, self.myname, device, self.MyName, name, self.MyName, fullname))
377            os.remove(lockfilename)
378        available.append('direct %s:// "%s+Nothing" "%s managed Virtual Printer"' \
379                             % (self.myname, self.MyName, self.MyName))
380        return available
381                       
382    def initBackend(self) :   
383        """Initializes the backend's attributes."""
384        # check that the DEVICE_URI environment variable's value is
385        # prefixed with self.myname otherwise don't touch it.
386        # If this is the case, we have to remove the prefix from
387        # the environment before launching the real backend
388        muststartwith = "%s:" % self.myname
389        device_uri = os.environ.get("DEVICE_URI", "")
390        if device_uri.startswith(muststartwith) :
391            fulldevice_uri = device_uri[:]
392            device_uri = fulldevice_uri[len(muststartwith):]
393            for i in range(2) :
394                if device_uri.startswith("/") : 
395                    device_uri = device_uri[1:]
396        try :
397            (backend, destination) = device_uri.split(":", 1) 
398        except ValueError :   
399            if not device_uri :
400                self.logDebug("Not attached to an existing print queue.")
401                backend = ""
402            else :   
403                raise TeeError, "Invalid DEVICE_URI : %s\n" % device_uri
404       
405        self.JobId = sys.argv[1].strip()
406        self.UserName = sys.argv[2].strip()
407        self.Title = sys.argv[3].strip()
408        self.Copies = int(sys.argv[4].strip())
409        self.Options = sys.argv[5].strip()
410        if len(sys.argv) == 7 :
411            self.InputFile = sys.argv[6] # read job's datas from file
412        else :   
413            self.InputFile = None        # read job's datas from stdin
414           
415        self.RealBackend = backend
416        self.DeviceURI = device_uri
417        self.PrinterName = os.environ.get("PRINTER", "")
418        self.Directory = self.getPrintQueueOption(self.PrinterName, "directory")
419        self.DataFile = os.path.join(self.Directory, "%s-%s-%s-%s" % (self.myname, self.PrinterName, self.UserName, self.JobId))
420        (ippfilename, ippmessage) = self.parseIPPMessageFile()
421        self.ControlFile = ippfilename
422        self.ClientHost = ippmessage.get("job-originating-host-name")
423        self.JobBilling = ippmessage.get("job-billing")
424           
425    def getCupsConfigDirectives(self, directives=[]) :
426        """Retrieves some CUPS directives from its configuration file.
427       
428           Returns a mapping with lowercased directives as keys and
429           their setting as values.
430        """
431        dirvalues = {} 
432        cupsroot = os.environ.get("CUPS_SERVERROOT", "/etc/cups")
433        cupsdconf = os.path.join(cupsroot, "cupsd.conf")
434        try :
435            conffile = open(cupsdconf, "r")
436        except IOError :   
437            raise TeeError, "Unable to open %s" % cupsdconf
438        else :   
439            for line in conffile.readlines() :
440                linecopy = line.strip().lower()
441                for di in [d.lower() for d in directives] :
442                    if linecopy.startswith("%s " % di) :
443                        try :
444                            val = line.split()[1]
445                        except :   
446                            pass # ignore errors, we take the last value in any case.
447                        else :   
448                            dirvalues[di] = val
449            conffile.close()           
450        return dirvalues       
451           
452    def parseIPPMessageFile(self) :       
453        """Parses the IPP message file and returns a tuple (filename, parsedvalue)."""
454        cupsdconf = self.getCupsConfigDirectives(["RequestRoot"])
455        requestroot = cupsdconf.get("requestroot", "/var/spool/cups")
456        if (len(self.JobId) < 5) and self.JobId.isdigit() :
457            ippmessagefile = "c%05i" % int(self.JobId)
458        else :   
459            ippmessagefile = "c%s" % self.JobId
460        ippmessagefile = os.path.join(requestroot, ippmessagefile)
461        ippmessage = {}
462        try :
463            ippdatafile = open(ippmessagefile)
464        except :   
465            self.logInfo("Unable to open IPP message file %s" % ippmessagefile, "warn")
466        else :   
467            self.logDebug("Parsing of IPP message file %s begins." % ippmessagefile)
468            try :
469                ippmessage = IPPMessage(ippdatafile.read())
470            except IPPError, msg :   
471                self.logInfo("Error while parsing %s : %s" % (ippmessagefile, msg), "warn")
472            else :   
473                self.logDebug("Parsing of IPP message file %s ends." % ippmessagefile)
474            ippdatafile.close()
475        return (ippmessagefile, ippmessage)
476               
477    def exportAttributes(self) :   
478        """Exports our backend's attributes to the environment."""
479        os.environ["DEVICE_URI"] = self.DeviceURI       # WARNING !
480        os.environ["TEAPRINTERNAME"] = self.PrinterName
481        os.environ["TEADIRECTORY"] = self.Directory
482        os.environ["TEADATAFILE"] = self.DataFile
483        os.environ["TEAJOBSIZE"] = str(self.JobSize)
484        os.environ["TEAMD5SUM"] = self.JobMD5Sum
485        os.environ["TEACLIENTHOST"] = self.ClientHost or ""
486        os.environ["TEAJOBID"] = self.JobId
487        os.environ["TEAUSERNAME"] = self.UserName
488        os.environ["TEATITLE"] = self.Title
489        os.environ["TEACOPIES"] = str(self.Copies)
490        os.environ["TEAOPTIONS"] = self.Options
491        os.environ["TEAINPUTFILE"] = self.InputFile or ""
492        os.environ["TEABILLING"] = self.JobBilling or ""
493        os.environ["TEACONTROLFILE"] = self.ControlFile
494       
495    def saveDatasAndCheckSum(self) :
496        """Saves the input datas into a static file."""
497        self.logDebug("Duplicating data stream into %s" % self.DataFile)
498        mustclose = 0
499        if self.InputFile is not None :
500            infile = open(self.InputFile, "rb")
501            mustclose = 1
502        else :   
503            infile = sys.stdin
504        CHUNK = 64*1024         # read 64 Kb at a time
505        dummy = 0
506        sizeread = 0
507        checksum = md5.new()
508        outfile = open(self.DataFile, "wb")   
509        while 1 :
510            data = infile.read(CHUNK) 
511            if not data :
512                break
513            sizeread += len(data)   
514            outfile.write(data)
515            checksum.update(data)   
516            if not (dummy % 32) : # Only display every 2 Mb
517                self.logDebug("%s bytes saved..." % sizeread)
518            dummy += 1   
519        outfile.close()
520        if mustclose :   
521            infile.close()
522        self.JobSize = sizeread   
523        self.JobMD5Sum = checksum.hexdigest()
524        self.logDebug("Job %s is %s bytes long." % (self.JobId, self.JobSize))
525        self.logDebug("Job %s MD5 sum is %s" % (self.JobId, self.JobMD5Sum))
526
527    def cleanUp(self) :
528        """Cleans up the place."""
529        if not self.isTrue(self.getPrintQueueOption(self.PrinterName, "keepfiles", ignore=1)) :
530            os.remove(self.DataFile)
531           
532    def sigtermHandler(self, signum, frame) :
533        """Sets an attribute whenever SIGTERM is received."""
534        self.gotSigTerm = 1
535        self.logInfo("SIGTERM received for Job %s." % self.JobId)
536       
537    def runBranches(self) :         
538        """Launches each hook or tee defined for the current print queue."""
539        exitcode = 0
540        self.isCancelled = 0    # did a prehook cancel the print job ?
541        self.gotSigTerm = 0
542        signal.signal(signal.SIGTERM, self.sigtermHandler)
543        serialize = self.isTrue(self.getPrintQueueOption(self.PrinterName, "serialize", ignore=1))
544        for branchtype in ["prehook", "tee", "posthook"] :
545            branches = self.enumBranches(self.PrinterName, branchtype)
546            status = self.runCommands(branchtype, branches, serialize)
547            if status :
548                if branchtype != "posthook" :
549                    exitcode = status
550                else :   
551                    # we just ignore error in posthooks
552                    self.logInfo("An error occured during the execution of posthooks.", "warn")
553            if (branchtype == "prehook") and self.isCancelled :
554                break # We don't want to execute tees or posthooks in this case
555        signal.signal(signal.SIGTERM, signal.SIG_IGN)
556        if not exitcode :
557            self.logInfo("OK")
558        else :   
559            self.logInfo("An error occured, please check CUPS' error_log file.")
560        return exitcode
561       
562    def runCommands(self, btype, branches, serialize) :   
563        """Runs the commands for a particular branch type."""
564        exitcode = 0 
565        btype = btype.lower()
566        btypetitle = btype.title()
567        branchlist = branches.keys()   
568        branchlist.sort()
569        if serialize :
570            self.logDebug("Begin serialized %ss" % btypetitle)
571            if (btype == "tee") and self.RealBackend :
572                self.logDebug("Launching original backend %s for printer %s" % (self.RealBackend, self.PrinterName))
573                retcode = self.runOriginalBackend()
574                if os.WIFEXITED(retcode) :
575                    retcode = os.WEXITSTATUS(retcode)
576                os.environ["TEASTATUS"] = str(retcode)
577                exitcode = retcode
578            for branch in branchlist :
579                command = branches[branch]
580                if self.gotSigTerm :
581                    break
582                self.logDebug("Launching %s : %s" % (branch, command))
583                retcode = os.system(command)
584                self.logDebug("Exit code for %s %s on printer %s is %s" % (btype, branch, self.PrinterName, retcode))
585                if os.WIFEXITED(retcode) :
586                    retcode = os.WEXITSTATUS(retcode)
587                if retcode :   
588                    if (btype == "prehook") and (retcode == 255) : # -1
589                        self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch))
590                        self.isCancelled = 1
591                    else :   
592                        self.logInfo("%s %s on printer %s didn't exit successfully." % (btypetitle, branch, self.PrinterName), "error")
593                        exitcode = 1
594            self.logDebug("End serialized %ss" % btypetitle)
595        else :       
596            self.logDebug("Begin forked %ss" % btypetitle)
597            pids = {}
598            if (btype == "tee") and self.RealBackend :
599                branches["Original backend"] = None     # Fakes a tee to launch one more child
600                branchlist = ["Original backend"] + branchlist
601            for branch in branchlist :
602                command = branches[branch]
603                if self.gotSigTerm :
604                    break
605                pid = os.fork()
606                if pid :
607                    pids[branch] = pid
608                else :   
609                    if branch == "Original backend" :
610                        self.logDebug("Launching original backend %s for printer %s" % (self.RealBackend, self.PrinterName))
611                        sys.exit(self.runOriginalBackend())
612                    else :
613                        self.logDebug("Launching %s : %s" % (branch, command))
614                        retcode = os.system(command)
615                        if os.WIFEXITED(retcode) :
616                            retcode = os.WEXITSTATUS(retcode)
617                        else :   
618                            retcode = -1
619                        sys.exit(retcode)
620            for (branch, pid) in pids.items() :
621                (childpid, retcode) = os.waitpid(pid, 0)
622                self.logDebug("Exit code for %s %s (PID %s) on printer %s is %s" % (btype, branch, childpid, self.PrinterName, retcode))
623                if os.WIFEXITED(retcode) :
624                    retcode = os.WEXITSTATUS(retcode)
625                if retcode :   
626                    if (btype == "prehook") and (retcode == 255) : # -1
627                        self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch))
628                        self.isCancelled = 1
629                    else :   
630                        self.logInfo("%s %s (PID %s) on printer %s didn't exit successfully." % (btypetitle, branch, childpid, self.PrinterName), "error")
631                        exitcode = 1
632                if branch == "Original backend" :   
633                    os.environ["TEASTATUS"] = str(retcode)
634            self.logDebug("End forked %ss" % btypetitle)
635        return exitcode
636       
637    def unregisterFileNo(self, pollobj, fileno) :               
638        """Removes a file handle from the polling object."""
639        try :
640            pollobj.unregister(fileno)
641        except KeyError :   
642            self.logInfo("File number %s unregistered twice from polling object, ignored." % fileno, "warn")
643        except :   
644            self.logDebug("Error while unregistering file number %s from polling object." % fileno)
645        else :   
646            self.logDebug("File number %s unregistered from polling object." % fileno)
647           
648    def formatFileEvent(self, fd, mask) :       
649        """Formats file debug info."""
650        maskval = []
651        if mask & select.POLLIN :
652            maskval.append("POLLIN")
653        if mask & select.POLLOUT :
654            maskval.append("POLLOUT")
655        if mask & select.POLLPRI :
656            maskval.append("POLLPRI")
657        if mask & select.POLLERR :
658            maskval.append("POLLERR")
659        if mask & select.POLLHUP :
660            maskval.append("POLLHUP")
661        if mask & select.POLLNVAL :
662            maskval.append("POLLNVAL")
663        return "%s (%s)" % (fd, " | ".join(maskval))
664       
665    def runOriginalBackend(self) :   
666        """Launches the original backend."""
667        originalbackend = os.path.join(os.path.split(sys.argv[0])[0], self.RealBackend)
668        arguments = sys.argv
669        self.logDebug("Starting original backend %s with args %s" % (originalbackend, " ".join(['"%s"' % a for a in ([os.environ["DEVICE_URI"]] + arguments[1:])])))
670        subprocess = Popen4ForCUPS([originalbackend] + arguments[1:], bufsize=0, arg0=os.environ["DEVICE_URI"])
671       
672        # Save file descriptors, we will need them later.
673        stderrfno = sys.stderr.fileno()
674        fromcfno = subprocess.fromchild.fileno()
675        tocfno = subprocess.tochild.fileno()
676       
677        # We will have to be careful when dealing with I/O
678        # So we use a poll object to know when to read or write
679        pollster = select.poll()
680        pollster.register(fromcfno, select.POLLIN | select.POLLPRI)
681        pollster.register(stderrfno, select.POLLOUT)
682        pollster.register(tocfno, select.POLLOUT)
683       
684        # Initialize our buffers
685        indata = ""
686        outdata = ""
687        endinput = endoutput = 0
688        inputclosed = outputclosed = 0
689        totaltochild = totalfromcups = 0
690        totalfromchild = totaltocups = 0
691       
692        if self.InputFile is None :
693           # this is not a real file, we read the job's data
694            # from our temporary file which is a copy of stdin
695            inf = open(self.DataFile, "rb")
696            infno = inf.fileno()
697            pollster.register(infno, select.POLLIN | select.POLLPRI)
698        else :   
699            # job's data is in a file, no need to pass the data
700            # to the original backend
701            self.logDebug("Job's data is in %s" % self.InputFile)
702            infno = None
703            endinput = 1
704       
705        self.logDebug("Entering streams polling loop...")
706        MEGABYTE = 1024*1024
707        killed = 0
708        status = -1
709        while (status == -1) and (not killed) and not (inputclosed and outputclosed) :
710            # First check if original backend is still alive
711            status = subprocess.poll()
712           
713            # Now if we got SIGTERM, we have
714            # to kill -TERM the original backend
715            if self.gotSigTerm and not killed :
716                try :
717                    os.kill(subprocess.pid, signal.SIGTERM)
718                except OSError, msg : # ignore but logs if process was already killed.
719                    self.logDebug("Error while sending signal to pid %s : %s" % (subprocess.pid, msg))
720                else :   
721                    self.logInfo(_("SIGTERM was sent to original backend %s (PID %s)") % (originalbackend, subprocess.pid))
722                    killed = 1
723           
724            # In any case, deal with any remaining I/O
725            try :
726                availablefds = pollster.poll(5000)
727            except select.error, msg :   
728                self.logDebug("Interrupted poll : %s" % msg)
729                availablefds = []
730            if not availablefds :
731                self.logDebug("Nothing to do, sleeping a bit...")
732                time.sleep(0.01) # give some time to the system
733            else :
734                for (fd, mask) in availablefds :
735                    try :
736                        if mask & select.POLLOUT :
737                            # We can write
738                            if fd == tocfno :
739                                if indata :
740                                    try :
741                                        nbwritten = os.write(fd, indata)   
742                                    except (OSError, IOError), msg :   
743                                        self.logDebug("Error while writing to original backend's stdin %s : %s" % (fd, msg))
744                                    else :   
745                                        if len(indata) != nbwritten :
746                                            self.logDebug("Short write to original backend's input !")
747                                        totaltochild += nbwritten   
748                                        self.logDebug("%s bytes sent to original backend so far..." % totaltochild)
749                                        indata = indata[nbwritten:]
750                                else :       
751                                    self.logDebug("No data to send to original backend yet, sleeping a bit...")
752                                    time.sleep(0.01)
753                                   
754                                if endinput :   
755                                    self.unregisterFileNo(pollster, tocfno)       
756                                    self.logDebug("Closing original backend's stdin.")
757                                    os.close(tocfno)
758                                    inputclosed = 1
759                            elif fd == stderrfno :
760                                if outdata :
761                                    try :
762                                        nbwritten = os.write(fd, outdata)
763                                    except (OSError, IOError), msg :   
764                                        self.logDebug("Error while writing to CUPS back channel (stderr) %s : %s" % (fd, msg))
765                                    else :
766                                        if len(outdata) != nbwritten :
767                                            self.logDebug("Short write to stderr (CUPS) !")
768                                        totaltocups += nbwritten   
769                                        self.logDebug("%s bytes sent back to CUPS so far..." % totaltocups)
770                                        outdata = outdata[nbwritten:]
771                                else :       
772                                    # self.logDebug("No data to send back to CUPS yet, sleeping a bit...") # Uncommenting this fills your logs
773                                    time.sleep(0.01) # Give some time to the system, stderr is ALWAYS writeable it seems.
774                                   
775                                if endoutput :   
776                                    self.unregisterFileNo(pollster, stderrfno)       
777                                    outputclosed = 1
778                            else :   
779                                self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask))
780                                time.sleep(0.01)
781                               
782                        if mask & (select.POLLIN | select.POLLPRI) :     
783                            # We have something to read
784                            try :
785                                data = os.read(fd, MEGABYTE)
786                            except (IOError, OSError), msg :   
787                                self.logDebug("Error while reading file %s : %s" % (fd, msg))
788                            else :
789                                if fd == infno :
790                                    if not data :    # If yes, then no more input data
791                                        self.unregisterFileNo(pollster, infno)
792                                        self.logDebug("Input data ends.")
793                                        endinput = 1 # this happens with real files.
794                                    else :   
795                                        indata += data
796                                        totalfromcups += len(data)
797                                        self.logDebug("%s bytes read from CUPS so far..." % totalfromcups)
798                                elif fd == fromcfno :
799                                    if not data :
800                                        self.logDebug("No back channel data to read from original backend yet, sleeping a bit...")
801                                        time.sleep(0.01)
802                                    else :
803                                        outdata += data
804                                        totalfromchild += len(data)
805                                        self.logDebug("%s bytes read from original backend so far..." % totalfromchild)
806                                else :   
807                                    self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask))
808                                    time.sleep(0.01)
809                                   
810                        if mask & (select.POLLHUP | select.POLLERR) :
811                            # Treat POLLERR as an EOF.
812                            # Some standard I/O stream has no more datas
813                            self.unregisterFileNo(pollster, fd)
814                            if fd == infno :
815                                # Here we are in the case where the input file is stdin.
816                                # which has no more data to be read.
817                                self.logDebug("Input data ends.")
818                                endinput = 1
819                            elif fd == fromcfno :   
820                                # We are no more interested in this file descriptor       
821                                self.logDebug("Closing original backend's stdout+stderr.")
822                                os.close(fromcfno)
823                                endoutput = 1
824                            else :   
825                                self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask))
826                                time.sleep(0.01)
827                               
828                        if mask & select.POLLNVAL :       
829                            self.logDebug("File %s was closed. Unregistering from polling object." % fd)
830                            self.unregisterFileNo(pollster, fd)
831                    except IOError, msg :           
832                        self.logDebug("Got an IOError : %s" % msg) # we got signalled during an I/O
833               
834        # We must close the original backend's input stream
835        if killed and not inputclosed :
836            self.logDebug("Forcing close of original backend's stdin.")
837            os.close(tocfno)
838       
839        self.logDebug("Exiting streams polling loop...")
840       
841        self.logDebug("input data's final length : %s" % len(indata))
842        self.logDebug("back-channel data's final length : %s" % len(outdata))
843       
844        self.logDebug("Total bytes read from CUPS (job's datas) : %s" % totalfromcups)
845        self.logDebug("Total bytes sent to original backend (job's datas) : %s" % totaltochild)
846       
847        self.logDebug("Total bytes read from original backend (back-channel datas) : %s" % totalfromchild)
848        self.logDebug("Total bytes sent back to CUPS (back-channel datas) : %s" % totaltocups)
849       
850        # Check exit code of original CUPS backend.   
851        if status == -1 :
852            # we exited the loop before the original backend exited
853            # now we have to wait for it to finish and get its status
854            self.logDebug("Waiting for original backend to exit...")
855            try :
856                status = subprocess.wait()
857            except OSError : # already dead : TODO : detect when abnormal
858                status = 0
859        if os.WIFEXITED(status) :
860            return os.WEXITSTATUS(status)
861        elif not killed :   
862            self.logInfo("CUPS backend %s died abnormally." % originalbackend, "error")
863            return -1
864        else :   
865            return 1
866       
867if __name__ == "__main__" :   
868    # This is a CUPS backend, we should act and die like a CUPS backend
869    wrapper = CupsBackend()
870    if len(sys.argv) == 1 :
871        print "\n".join(wrapper.discoverOtherBackends())
872        sys.exit(0)               
873    elif len(sys.argv) not in (6, 7) :   
874        sys.stderr.write("ERROR: %s job-id user title copies options [file]\n"\
875                              % sys.argv[0])
876        sys.exit(1)
877    else :   
878        try :
879            wrapper.readConfig()
880            wrapper.initBackend()
881            wrapper.saveDatasAndCheckSum()
882            wrapper.exportAttributes()
883            retcode = wrapper.runBranches()
884            wrapper.cleanUp()
885        except SystemExit, e :   
886            retcode = e.code
887        except :   
888            import traceback
889            lines = []
890            for line in traceback.format_exception(*sys.exc_info()) :
891                lines.extend([l for l in line.split("\n") if l])
892            msg = "ERROR: ".join(["%s (PID %s) : %s\n" % (wrapper.MyName, wrapper.pid, l) for l in (["ERROR: Tea4CUPS v%s" % version] + lines)])
893            sys.stderr.write(msg)
894            sys.stderr.flush()
895            retcode = 1
896        sys.exit(retcode)
Note: See TracBrowser for help on using the browser.