[2205] | 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 |
---|
[2302] | 19 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
[2205] | 20 | # |
---|
| 21 | # $Id$ |
---|
| 22 | # |
---|
| 23 | # |
---|
| 24 | |
---|
[2277] | 25 | ITERATIONDELAY = 1.5 # 1.5 Second |
---|
[2205] | 26 | STABILIZATIONDELAY = 3 # We must read three times the same value to consider it to be stable |
---|
| 27 | |
---|
| 28 | import sys |
---|
| 29 | import os |
---|
| 30 | import time |
---|
[2319] | 31 | import select |
---|
[2205] | 32 | |
---|
| 33 | try : |
---|
| 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 |
---|
| 38 | except 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/" |
---|
| 43 | else : |
---|
| 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 |
---|
[2425] | 70 | try : |
---|
| 71 | self.community = self.parent.arguments.split(":")[1].strip() |
---|
| 72 | except IndexError : |
---|
| 73 | self.community = "public" |
---|
[2423] | 74 | self.port = 161 |
---|
[2205] | 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() |
---|
[2423] | 83 | req.apiAlphaSetCommunity(self.community) |
---|
[2205] | 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 : |
---|
[2423] | 90 | tsp.sendAndReceive(req.berEncode(), \ |
---|
| 91 | (self.printerHostname, self.port), \ |
---|
| 92 | (self.handleAnswer, req)) |
---|
[2319] | 93 | except (SnmpOverUdpError, select.error), msg : |
---|
[2205] | 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]) |
---|
[2305] | 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)) |
---|
[2205] | 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. |
---|
[2409] | 146 | self.parent.filter.printInfo("Printer %s is lying to us !!!" % self.parent.filter.PrinterName, "warn") |
---|
[2205] | 147 | break |
---|
[2409] | 148 | self.parent.filter.logdebug(_("Waiting for printer %s to be printing...") % self.parent.filter.PrinterName) |
---|
[2205] | 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 |
---|
[2277] | 165 | if idle_num >= STABILIZATIONDELAY : |
---|
[2205] | 166 | # printer status is stable, we can exit |
---|
| 167 | break |
---|
| 168 | else : |
---|
| 169 | idle_num = 0 |
---|
[2409] | 170 | self.parent.filter.logdebug(_("Waiting for printer %s's idle status to stabilize...") % self.parent.filter.PrinterName) |
---|
[2205] | 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 \ |
---|
[2409] | 179 | self.parent.filter.JobSizeBytes : |
---|
[2205] | 180 | self.waitPrinting() |
---|
| 181 | self.waitIdle() |
---|
| 182 | except : |
---|
| 183 | if self.printerInternalPageCounter is None : |
---|
| 184 | raise |
---|
| 185 | else : |
---|
[2409] | 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") |
---|
[2205] | 187 | return self.printerInternalPageCounter |
---|
| 188 | |
---|
| 189 | if __name__ == "__main__" : |
---|
| 190 | if len(sys.argv) != 2 : |
---|
| 191 | sys.stderr.write("Usage : python %s printer_ip_address\n" % sys.argv[0]) |
---|
| 192 | else : |
---|
| 193 | def _(msg) : |
---|
| 194 | return msg |
---|
| 195 | |
---|
| 196 | class fakeFilter : |
---|
| 197 | def __init__(self) : |
---|
[2409] | 198 | self.PrinterName = "FakePrintQueue" |
---|
| 199 | self.JobSizeBytes = 1 |
---|
[2205] | 200 | |
---|
| 201 | def printInfo(self, msg, level="info") : |
---|
| 202 | sys.stderr.write("%s : %s\n" % (level.upper(), msg)) |
---|
| 203 | sys.stderr.flush() |
---|
| 204 | |
---|
| 205 | def logdebug(self, msg) : |
---|
| 206 | self.printInfo(msg, "debug") |
---|
| 207 | |
---|
| 208 | class fakeAccounter : |
---|
| 209 | def __init__(self) : |
---|
| 210 | self.filter = fakeFilter() |
---|
| 211 | self.protocolHandler = Handler(self, sys.argv[1]) |
---|
| 212 | |
---|
| 213 | acc = fakeAccounter() |
---|
| 214 | print "Internal page counter's value is : %s" % acc.protocolHandler.retrieveInternalPageCounter() |
---|