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

Revision 3357, 5.7 kB (checked in by jerome, 16 years ago)

Less verbose now since some messages are now logged only at debug level.
Added a workaround for API mess.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# -*- coding: UTF-8 -*-
2#
3# PyKota : Print Quotas for CUPS
4#
5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18#
19# $Id$
20#
21#
22
23"""This module handles software page counting for PyKota."""
24
25import os
26import popen2
27
28from pykota.errors import PyKotaAccounterError
29from pykota.accounter import AccounterBase
30
31class Accounter(AccounterBase) :
32    def computeJobSize(self) :   
33        """Feeds an external command with our datas to let it compute the job size, and return its value."""
34        if (not self.isPreAccounter) and \
35            (self.filter.accounter.arguments == self.filter.preaccounter.arguments) :
36            # if precomputing has been done and both accounter and preaccounter are
37            # configured the same, no need to launch a second pass since we already
38            # know the result.
39            self.filter.logdebug("Precomputing pass told us that job is %s pages long." % self.filter.softwareJobSize)
40            return self.filter.softwareJobSize   # Optimize : already computed !
41           
42        if self.arguments :
43            self.filter.logdebug("Using external script %s to compute job's size." % self.arguments)
44            return self.withExternalScript()
45        else :   
46            self.filter.logdebug("Using internal parser to compute job's size.")
47            return self.withInternalParser()
48       
49    def withInternalParser(self) :   
50        """Does software accounting through an external script."""
51        jobsize = 0
52        if self.filter.JobSizeBytes :
53            try :
54                from pkpgpdls import analyzer, pdlparser
55            except ImportError :   
56                self.filter.printInfo("pkpgcounter is now distributed separately, please grab it from http://www.pykota.com/software/pkpgcounter", "error")
57                self.filter.printInfo("Precomputed job size will be forced to 0 pages.", "error")
58            else :     
59                try :
60                    parser = analyzer.PDLAnalyzer(self.filter.DataFile)
61                    jobsize = parser.getJobSize()
62                except pdlparser.PDLParserError, msg :   
63                    # Here we just log the failure, but
64                    # we finally ignore it and return 0 since this
65                    # computation is just an indication of what the
66                    # job's size MAY be.
67                    self.filter.printInfo(_("Unable to precompute the job's size with the generic PDL analyzer : %s") % msg, "warn")
68                else :   
69                    try :
70                        if self.filter.Ticket.FileName is not None :
71                            # when a filename is passed as an argument, the backend
72                            # must generate the correct number of copies.
73                            jobsize *= self.filter.Ticket.Copies
74                    except AttributeError : # When not run from the cupspykota backend
75                        pass
76        return jobsize       
77               
78    def withExternalScript(self) :   
79        """Does software accounting through an external script."""
80        self.filter.logdebug(_("Launching SOFTWARE(%s)...") % self.arguments)
81        pagecounter = None
82        child = os.popen(self.arguments, "r")
83        try :
84            answer = child.read()
85        except (IOError, OSError), msg :   
86            msg = "%s : %s" % (self.arguments, msg) 
87            self.filter.printInfo(_("Unable to compute job size with accounter %s") % msg, "warn")
88        else :   
89            lines = [l.strip() for l in answer.split("\n")]
90            for i in range(len(lines)) : 
91                try :
92                    pagecounter = int(lines[i])
93                except (AttributeError, ValueError) :
94                    self.filter.logdebug(_("Line [%s] skipped in accounter's output. Trying again...") % lines[i])
95                else :   
96                    break
97                   
98        status = child.close()
99        try :
100            if os.WIFEXITED(status) :
101                status = os.WEXITSTATUS(status)
102        except TypeError :       
103            pass # None means no error occured.
104        self.filter.logdebug(_("Software accounter %s exit code is %s") % (self.arguments, str(status)))
105           
106        if pagecounter is None :   
107            message = _("Unable to compute job size with accounter %s") % self.arguments
108            if self.onerror == "CONTINUE" :
109                self.filter.printInfo(message, "error")
110            else :
111                raise PyKotaAccounterError, message
112        self.filter.logdebug("Software accounter %s said job is %s pages long." % (self.arguments, repr(pagecounter)))
113           
114        pagecounter = pagecounter or 0   
115        try :
116            if self.filter.Ticket.FileName is not None :
117                # when a filename is passed as an argument, the backend
118                # must generate the correct number of copies.
119                pagecounter *= self.filter.Ticket.Copies
120        except AttributeError :       
121            pass # when called from pykotme. TODO : clean this mess some day.
122                       
123        return pagecounter
Note: See TracBrowser for help on using the browser.