root / pykota / trunk / pykota / accounters / software.py @ 3256

Revision 3256, 6.2 kB (checked in by jerome, 16 years ago)

No need to reopen the file another time, it's already done in
pkpgcounter.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota - Print Quotas for CUPS and LPRng
5#
6# (c) 2003, 2004, 2005, 2006, 2007 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25import os
26import popen2
27from pykota.accounter import AccounterBase, PyKotaAccounterError
28
29class Accounter(AccounterBase) :
30    def computeJobSize(self) :   
31        """Feeds an external command with our datas to let it compute the job size, and return its value."""
32        if (not self.isPreAccounter) and \
33            (self.filter.accounter.arguments == self.filter.preaccounter.arguments) :
34            # if precomputing has been done and both accounter and preaccounter are
35            # configured the same, no need to launch a second pass since we already
36            # know the result.
37            self.filter.logdebug("Precomputing pass told us that job is %s pages long." % self.filter.softwareJobSize)
38            return self.filter.softwareJobSize   # Optimize : already computed !
39           
40        if self.arguments :
41            self.filter.logdebug("Using external script %s to compute job's size." % self.arguments)
42            return self.withExternalScript()
43        else :   
44            self.filter.logdebug("Using internal parser to compute job's size.")
45            return self.withInternalParser()
46       
47    def withInternalParser(self) :   
48        """Does software accounting through an external script."""
49        jobsize = 0
50        if self.filter.JobSizeBytes :
51            try :
52                from pkpgpdls import analyzer, pdlparser
53            except ImportError :   
54                self.filter.printInfo("pkpgcounter is now distributed separately, please grab it from http://www.pykota.com/software/pkpgcounter", "error")
55                self.filter.printInfo("Precomputed job size will be forced to 0 pages.", "error")
56            else :     
57                try :
58                    parser = analyzer.PDLAnalyzer(self.filter.DataFile)
59                    jobsize = parser.getJobSize()
60                except pdlparser.PDLParserError, msg :   
61                    # Here we just log the failure, but
62                    # we finally ignore it and return 0 since this
63                    # computation is just an indication of what the
64                    # job's size MAY be.
65                    self.filter.printInfo(_("Unable to precompute the job's size with the generic PDL analyzer : %s") % msg, "warn")
66                else :   
67                    try :
68                        if self.filter.Ticket.FileName is not None :
69                            # when a filename is passed as an argument, the backend
70                            # must generate the correct number of copies.
71                            jobsize *= self.filter.Ticket.Copies
72                    except AttributeError : # When not run from the cupspykota backend
73                        pass
74        return jobsize       
75               
76    def withExternalScript(self) :   
77        """Does software accounting through an external script."""
78        self.filter.printInfo(_("Launching SOFTWARE(%s)...") % self.arguments)
79        MEGABYTE = 1024*1024
80        infile = open(self.filter.DataFile, "rb")
81        child = popen2.Popen4(self.arguments)
82        try :
83            data = infile.read(MEGABYTE)   
84            while data :
85                child.tochild.write(data)
86                data = infile.read(MEGABYTE)
87            child.tochild.flush()
88            child.tochild.close()   
89        except (IOError, OSError), msg :   
90            msg = "%s : %s" % (self.arguments, msg) 
91            self.filter.printInfo(_("Unable to compute job size with accounter %s") % msg)
92        infile.close()
93        pagecounter = None
94        try :
95            answer = child.fromchild.read()
96        except (IOError, OSError), msg :   
97            msg = "%s : %s" % (self.arguments, msg) 
98            self.filter.printInfo(_("Unable to compute job size with accounter %s") % msg)
99        else :   
100            lines = [l.strip() for l in answer.split("\n")]
101            for i in range(len(lines)) : 
102                try :
103                    pagecounter = int(lines[i])
104                except (AttributeError, ValueError) :
105                    self.filter.printInfo(_("Line [%s] skipped in accounter's output. Trying again...") % lines[i])
106                else :   
107                    break
108        child.fromchild.close()
109       
110        try :
111            status = child.wait()
112        except OSError, msg :   
113            self.filter.printInfo(_("Problem while waiting for software accounter pid %s to exit : %s") % (child.pid, msg))
114        else :   
115            if os.WIFEXITED(status) :
116                status = os.WEXITSTATUS(status)
117            self.filter.printInfo(_("Software accounter %s exit code is %s") % (self.arguments, str(status)))
118           
119        if pagecounter is None :   
120            message = _("Unable to compute job size with accounter %s") % self.arguments
121            if self.onerror == "CONTINUE" :
122                self.filter.printInfo(message, "error")
123            else :
124                raise PyKotaAccounterError, message
125        self.filter.logdebug("Software accounter %s said job is %s pages long." % (self.arguments, repr(pagecounter)))
126           
127        pagecounter = pagecounter or 0   
128        if self.filter.Ticket.FileName is not None :
129            # when a filename is passed as an argument, the backend
130            # must generate the correct number of copies.
131            pagecounter *= self.filter.Ticket.Copies
132                       
133        return pagecounter
Note: See TracBrowser for help on using the browser.