root / pykota / trunk / pykota / accounters / snmp.py @ 2319

Revision 2319, 10.1 kB (checked in by jerome, 19 years ago)

Now catches errors due to interrupted select.select() calls

  • Property svn:eol-style set to native
  • Property svn:keywords set to Auth Date Rev Id
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota - Print Quotas for CUPS and LPRng
5#
6# (c) 2003, 2004, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25ITERATIONDELAY = 1.5   # 1.5 Second
26STABILIZATIONDELAY = 3 # We must read three times the same value to consider it to be stable
27
28import sys
29import os
30import time
31import select
32
33try :
34    from pysnmp.asn1.encoding.ber.error import TypeMismatchError
35    from pysnmp.mapping.udp.error import SnmpOverUdpError
36    from pysnmp.mapping.udp.role import Manager
37    from pysnmp.proto.api import alpha
38except ImportError :
39    class Handler :
40        def __init__(self, parent, printerhostname) :
41            """Just there to raise an exception."""
42            raise RuntimeError, "The pysnmp module is not available. Download it from http://pysnmp.sf.net/"
43else :   
44    pageCounterOID = ".1.3.6.1.2.1.43.10.2.1.4.1.1"  # SNMPv2-SMI::mib-2.43.10.2.1.4.1.1
45    hrPrinterStatusOID = ".1.3.6.1.2.1.25.3.5.1.1.1" # SNMPv2-SMI::mib-2.25.3.5.1.1.1
46    printerStatusValues = { 1 : 'other',
47                            2 : 'unknown',
48                            3 : 'idle',
49                            4 : 'printing',
50                            5 : 'warmup',
51                          }
52    hrDeviceStatusOID = ".1.3.6.1.2.1.25.3.2.1.5.1" # SNMPv2-SMI::mib-2.25.3.2.1.5.1
53    deviceStatusValues = { 1 : 'unknown',
54                           2 : 'running',
55                           3 : 'warning',
56                           4 : 'testing',
57                           5 : 'down',
58                         } 
59    hrPrinterDetectedErrorStateOID = ".1.3.6.1.2.1.25.3.5.1.2.1" # SNMPv2-SMI::mib-2.25.3.5.1.2.1
60    prtConsoleDisplayBufferTextOID = ".1.3.6.1.2.1.43.16.5.1.2.1.1" # SNMPv2-SMI::mib-2.43.16.5.1.2.1.1
61                         
62    #                     
63    # Documentation taken from RFC 3805 (Printer MIB v2) and RFC 2790 (Host Resource MIB)
64    #
65    class Handler :
66        """A class for SNMP print accounting."""
67        def __init__(self, parent, printerhostname) :
68            self.parent = parent
69            self.printerHostname = printerhostname
70            self.printerInternalPageCounter = None
71            self.printerStatus = None
72            self.deviceStatus = None
73           
74        def retrieveSNMPValues(self) :   
75            """Retrieves a printer's internal page counter and status via SNMP."""
76            ver = alpha.protoVersions[alpha.protoVersionId1]
77            req = ver.Message()
78            req.apiAlphaSetCommunity('public')
79            req.apiAlphaSetPdu(ver.GetRequestPdu())
80            req.apiAlphaGetPdu().apiAlphaSetVarBindList((pageCounterOID, ver.Null()), \
81                                                        (hrPrinterStatusOID, ver.Null()), \
82                                                        (hrDeviceStatusOID, ver.Null()))
83            tsp = Manager()
84            try :
85                tsp.sendAndReceive(req.berEncode(), (self.printerHostname, 161), (self.handleAnswer, req))
86            except (SnmpOverUdpError, select.error), msg :   
87                self.parent.filter.printInfo(_("Network error while doing SNMP queries on printer %s : %s") % (self.printerHostname, msg), "warn")
88            tsp.close()
89   
90        def handleAnswer(self, wholeMsg, notusedhere, req):
91            """Decodes and handles the SNMP answer."""
92            self.parent.filter.logdebug("SNMP message : '%s'" % repr(wholeMsg))
93            ver = alpha.protoVersions[alpha.protoVersionId1]
94            rsp = ver.Message()
95            try :
96                rsp.berDecode(wholeMsg)
97            except TypeMismatchError, msg :   
98                self.parent.filter.printInfo(_("SNMP message decoding error for printer %s : %s") % (self.printerHostname, msg), "warn")
99            else :
100                if req.apiAlphaMatch(rsp):
101                    errorStatus = rsp.apiAlphaGetPdu().apiAlphaGetErrorStatus()
102                    if errorStatus:
103                        self.parent.filter.printInfo(_("Problem encountered while doing SNMP queries on printer %s : %s") % (self.printerHostname, errorStatus), "warn")
104                    else:
105                        self.values = []
106                        for varBind in rsp.apiAlphaGetPdu().apiAlphaGetVarBindList():
107                            self.values.append(varBind.apiAlphaGetOidVal()[1].rawAsn1Value)
108                        try :   
109                            # keep maximum value seen for printer's internal page counter
110                            self.printerInternalPageCounter = max(self.printerInternalPageCounter, self.values[0])
111                            self.printerStatus = self.values[1]
112                            self.deviceStatus = self.values[2]
113                            self.parent.filter.logdebug("SNMP answer is decoded : PageCounter : %s  PrinterStatus : %s  DeviceStatus : %s" % tuple(self.values))
114                        except IndexError :   
115                            self.parent.filter.logdebug("SNMP answer is incomplete : %s" % str(self.values))
116                            pass
117                        else :   
118                            return 1
119                       
120        def waitPrinting(self) :
121            """Waits for printer status being 'printing'."""
122            firstvalue = None
123            while 1:
124                self.retrieveSNMPValues()
125                statusAsString = printerStatusValues.get(self.printerStatus)
126                if statusAsString in ('printing', 'warmup') :
127                    break
128                if self.printerInternalPageCounter is not None :   
129                    if firstvalue is None :
130                        # first time we retrieved a page counter, save it
131                        firstvalue = self.printerInternalPageCounter
132                    else :     
133                        # second time (or later)
134                        if firstvalue < self.printerInternalPageCounter :
135                            # Here we have a printer which lies :
136                            # it says it is not printing or warming up
137                            # BUT the page counter increases !!!
138                            # So we can probably quit being sure it is printing.
139                            self.parent.filter.printInfo("Printer %s is lying to us !!!" % self.parent.filter.printername, "warn")
140                            break
141                self.parent.filter.logdebug(_("Waiting for printer %s to be printing...") % self.parent.filter.printername)   
142                time.sleep(ITERATIONDELAY)
143           
144        def waitIdle(self) :
145            """Waits for printer status being 'idle'."""
146            idle_num = idle_flag = 0
147            while 1 :
148                self.retrieveSNMPValues()
149                pstatusAsString = printerStatusValues.get(self.printerStatus)
150                dstatusAsString = deviceStatusValues.get(self.deviceStatus)
151                idle_flag = 0
152                if (pstatusAsString == 'idle') or \
153                   ((pstatusAsString == 'other') and \
154                    (dstatusAsString == 'running')) :
155                    idle_flag = 1       # Standby / Powersave is considered idle
156                if idle_flag :   
157                    idle_num += 1
158                    if idle_num >= STABILIZATIONDELAY :
159                        # printer status is stable, we can exit
160                        break
161                else :   
162                    idle_num = 0
163                self.parent.filter.logdebug(_("Waiting for printer %s's idle status to stabilize...") % self.parent.filter.printername)   
164                time.sleep(ITERATIONDELAY)
165               
166        def retrieveInternalPageCounter(self) :
167            """Returns the page counter from the printer via internal SNMP handling."""
168            try :
169                if (os.environ.get("PYKOTASTATUS") != "CANCELLED") and \
170                   (os.environ.get("PYKOTAACTION") != "DENY") and \
171                   (os.environ.get("PYKOTAPHASE") == "AFTER") and \
172                   self.parent.filter.jobSizeBytes :
173                    self.waitPrinting()
174                self.waitIdle()   
175            except :   
176                if self.printerInternalPageCounter is None :
177                    raise
178                else :   
179                    self.parent.filter.printInfo(_("SNMP querying stage interrupted. Using latest value seen for internal page counter (%s) on printer %s.") % (self.printerInternalPageCounter, self.parent.filter.printername), "warn")
180            return self.printerInternalPageCounter
181           
182if __name__ == "__main__" :           
183    if len(sys.argv) != 2 :   
184        sys.stderr.write("Usage :  python  %s  printer_ip_address\n" % sys.argv[0])
185    else :   
186        def _(msg) :
187            return msg
188           
189        class fakeFilter :
190            def __init__(self) :
191                self.printername = "FakePrintQueue"
192                self.jobSizeBytes = 1
193               
194            def printInfo(self, msg, level="info") :
195                sys.stderr.write("%s : %s\n" % (level.upper(), msg))
196                sys.stderr.flush()
197               
198            def logdebug(self, msg) :   
199                self.printInfo(msg, "debug")
200               
201        class fakeAccounter :       
202            def __init__(self) :
203                self.filter = fakeFilter()
204                self.protocolHandler = Handler(self, sys.argv[1])
205           
206        acc = fakeAccounter()           
207        print "Internal page counter's value is : %s" % acc.protocolHandler.retrieveInternalPageCounter()
Note: See TracBrowser for help on using the browser.