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

Revision 2506, 10.5 kB (checked in by jerome, 19 years ago)

Moved test code into a function.

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