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

Revision 2423, 10.2 kB (checked in by jerome, 19 years ago)

Prepare for parametrized internal hardware accounters

  • 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.community = "public"
71            self.port = 161
72            self.printerInternalPageCounter = None
73            self.printerStatus = None
74            self.deviceStatus = None
75           
76        def retrieveSNMPValues(self) :   
77            """Retrieves a printer's internal page counter and status via SNMP."""
78            ver = alpha.protoVersions[alpha.protoVersionId1]
79            req = ver.Message()
80            req.apiAlphaSetCommunity(self.community)
81            req.apiAlphaSetPdu(ver.GetRequestPdu())
82            req.apiAlphaGetPdu().apiAlphaSetVarBindList((pageCounterOID, ver.Null()), \
83                                                        (hrPrinterStatusOID, ver.Null()), \
84                                                        (hrDeviceStatusOID, ver.Null()))
85            tsp = Manager()
86            try :
87                tsp.sendAndReceive(req.berEncode(), \
88                                   (self.printerHostname, self.port), \
89                                   (self.handleAnswer, req))
90            except (SnmpOverUdpError, select.error), msg :   
91                self.parent.filter.printInfo(_("Network error while doing SNMP queries on printer %s : %s") % (self.printerHostname, msg), "warn")
92            tsp.close()
93   
94        def handleAnswer(self, wholeMsg, notusedhere, req):
95            """Decodes and handles the SNMP answer."""
96            self.parent.filter.logdebug("SNMP message : '%s'" % repr(wholeMsg))
97            ver = alpha.protoVersions[alpha.protoVersionId1]
98            rsp = ver.Message()
99            try :
100                rsp.berDecode(wholeMsg)
101            except TypeMismatchError, msg :   
102                self.parent.filter.printInfo(_("SNMP message decoding error for printer %s : %s") % (self.printerHostname, msg), "warn")
103            else :
104                if req.apiAlphaMatch(rsp):
105                    errorStatus = rsp.apiAlphaGetPdu().apiAlphaGetErrorStatus()
106                    if errorStatus:
107                        self.parent.filter.printInfo(_("Problem encountered while doing SNMP queries on printer %s : %s") % (self.printerHostname, errorStatus), "warn")
108                    else:
109                        self.values = []
110                        for varBind in rsp.apiAlphaGetPdu().apiAlphaGetVarBindList():
111                            self.values.append(varBind.apiAlphaGetOidVal()[1].rawAsn1Value)
112                        try :   
113                            # keep maximum value seen for printer's internal page counter
114                            self.printerInternalPageCounter = max(self.printerInternalPageCounter, self.values[0])
115                            self.printerStatus = self.values[1]
116                            self.deviceStatus = self.values[2]
117                            self.parent.filter.logdebug("SNMP answer is decoded : PageCounter : %s  PrinterStatus : %s  DeviceStatus : %s" % tuple(self.values))
118                        except IndexError :   
119                            self.parent.filter.logdebug("SNMP answer is incomplete : %s" % str(self.values))
120                            pass
121                        else :   
122                            return 1
123                       
124        def waitPrinting(self) :
125            """Waits for printer status being 'printing'."""
126            firstvalue = None
127            while 1:
128                self.retrieveSNMPValues()
129                statusAsString = printerStatusValues.get(self.printerStatus)
130                if statusAsString in ('printing', 'warmup') :
131                    break
132                if self.printerInternalPageCounter is not None :   
133                    if firstvalue is None :
134                        # first time we retrieved a page counter, save it
135                        firstvalue = self.printerInternalPageCounter
136                    else :     
137                        # second time (or later)
138                        if firstvalue < self.printerInternalPageCounter :
139                            # Here we have a printer which lies :
140                            # it says it is not printing or warming up
141                            # BUT the page counter increases !!!
142                            # So we can probably quit being sure it is printing.
143                            self.parent.filter.printInfo("Printer %s is lying to us !!!" % self.parent.filter.PrinterName, "warn")
144                            break
145                self.parent.filter.logdebug(_("Waiting for printer %s to be printing...") % self.parent.filter.PrinterName)   
146                time.sleep(ITERATIONDELAY)
147           
148        def waitIdle(self) :
149            """Waits for printer status being 'idle'."""
150            idle_num = idle_flag = 0
151            while 1 :
152                self.retrieveSNMPValues()
153                pstatusAsString = printerStatusValues.get(self.printerStatus)
154                dstatusAsString = deviceStatusValues.get(self.deviceStatus)
155                idle_flag = 0
156                if (pstatusAsString == 'idle') or \
157                   ((pstatusAsString == 'other') and \
158                    (dstatusAsString == 'running')) :
159                    idle_flag = 1       # Standby / Powersave is considered idle
160                if idle_flag :   
161                    idle_num += 1
162                    if idle_num >= STABILIZATIONDELAY :
163                        # printer status is stable, we can exit
164                        break
165                else :   
166                    idle_num = 0
167                self.parent.filter.logdebug(_("Waiting for printer %s's idle status to stabilize...") % self.parent.filter.PrinterName)   
168                time.sleep(ITERATIONDELAY)
169               
170        def retrieveInternalPageCounter(self) :
171            """Returns the page counter from the printer via internal SNMP handling."""
172            try :
173                if (os.environ.get("PYKOTASTATUS") != "CANCELLED") and \
174                   (os.environ.get("PYKOTAACTION") != "DENY") and \
175                   (os.environ.get("PYKOTAPHASE") == "AFTER") and \
176                   self.parent.filter.JobSizeBytes :
177                    self.waitPrinting()
178                self.waitIdle()   
179            except :   
180                if self.printerInternalPageCounter is None :
181                    raise
182                else :   
183                    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")
184            return self.printerInternalPageCounter
185           
186if __name__ == "__main__" :           
187    if len(sys.argv) != 2 :   
188        sys.stderr.write("Usage :  python  %s  printer_ip_address\n" % sys.argv[0])
189    else :   
190        def _(msg) :
191            return msg
192           
193        class fakeFilter :
194            def __init__(self) :
195                self.PrinterName = "FakePrintQueue"
196                self.JobSizeBytes = 1
197               
198            def printInfo(self, msg, level="info") :
199                sys.stderr.write("%s : %s\n" % (level.upper(), msg))
200                sys.stderr.flush()
201               
202            def logdebug(self, msg) :   
203                self.printInfo(msg, "debug")
204               
205        class fakeAccounter :       
206            def __init__(self) :
207                self.filter = fakeFilter()
208                self.protocolHandler = Handler(self, sys.argv[1])
209           
210        acc = fakeAccounter()           
211        print "Internal page counter's value is : %s" % acc.protocolHandler.retrieveInternalPageCounter()
Note: See TracBrowser for help on using the browser.