Show
Ignore:
Timestamp:
09/27/08 22:02:37 (16 years ago)
Author:
jerome
Message:

Removed unnecessary spaces at EOL.

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • pykota/trunk/pykota/accounters/snmp.py

    r3411 r3413  
    88# the Free Software Foundation, either version 3 of the License, or 
    99# (at your option) any later version. 
    10 #  
     10# 
    1111# This program is distributed in the hope that it will be useful, 
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of 
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    1414# GNU General Public License for more details. 
    15 #  
     15# 
    1616# You should have received a copy of the GNU General Public License 
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>. 
     
    3636try : 
    3737    from pysnmp.entity.rfc3413.oneliner import cmdgen 
    38 except ImportError :     
     38except ImportError : 
    3939    hasV4 = False 
    4040    try : 
     
    5050from pykota import constants 
    5151 
    52 #                       
     52# 
    5353# Documentation taken from RFC 3805 (Printer MIB v2) and RFC 2790 (Host Resource MIB) 
    5454# 
     
    6767                       4 : 'testing', 
    6868                       5 : 'down', 
    69                      }   
     69                     } 
    7070hrPrinterDetectedErrorStateOID = "1.3.6.1.2.1.25.3.5.1.2.1" # SNMPv2-SMI::mib-2.25.3.5.1.2.1 
    7171printerDetectedErrorStateValues = [ { 128 : 'Low Paper', 
     
    8787                                        1 : 'Not Assigned in RFC3805', 
    8888                                    }, 
    89                                   ]   
    90                                    
     89                                  ] 
     90 
    9191# The default error mask to use when checking error conditions. 
    9292defaultErrorMask = 0x4fcc # [ 'No Paper', 
     
    100100                          #   'Input Tray Empty', 
    101101                          # ] 
    102                            
    103 # WARNING : some printers don't support this one :                   
     102 
     103# WARNING : some printers don't support this one : 
    104104prtConsoleDisplayBufferTextOID = "1.3.6.1.2.1.43.16.5.1.2.1.1" # SNMPv2-SMI::mib-2.43.16.5.1.2.1.1 
    105105class BaseHandler : 
     
    111111        try : 
    112112            self.community = self.parent.arguments.split(":")[1].strip() 
    113         except IndexError :     
     113        except IndexError : 
    114114            self.community = "public" 
    115115        self.port = 161 
    116116        self.initValues() 
    117          
    118     def initValues(self) :     
     117 
     118    def initValues(self) : 
    119119        """Initializes SNMP values.""" 
    120120        self.printerInternalPageCounter = None 
     
    123123        self.printerDetectedErrorState = None 
    124124        self.timebefore = time.time()   # resets timer also in case of error 
    125          
    126     def retrieveSNMPValues(self) :     
     125 
     126    def retrieveSNMPValues(self) : 
    127127        """Retrieves a printer's internal page counter and status via SNMP.""" 
    128128        raise RuntimeError, "You have to overload this method." 
    129          
    130     def extractErrorStates(self, value) :     
     129 
     130    def extractErrorStates(self, value) : 
    131131        """Returns a list of textual error states from a binary value.""" 
    132132        states = [] 
     
    137137                if byte & k : 
    138138                    states.append(v) 
    139         return states             
    140          
    141     def checkIfError(self, errorstates) :     
     139        return states 
     140 
     141    def checkIfError(self, errorstates) : 
    142142        """Checks if any error state is fatal or not.""" 
    143143        if errorstates is None : 
     
    146146            try : 
    147147                errormask = self.parent.filter.config.getPrinterSNMPErrorMask(self.parent.filter.PrinterName) 
    148             except AttributeError : # debug mode     
     148            except AttributeError : # debug mode 
    149149                errormask = defaultErrorMask 
    150150            if errormask is None : 
     
    161161                    return True 
    162162            self.parent.filter.logdebug("No error condition matching mask 0x%04x" % errormask) 
    163             return False     
    164          
     163            return False 
     164 
    165165    def waitPrinting(self) : 
    166166        """Waits for printer status being 'printing'.""" 
     
    169169        if not noprintingmaxdelay : 
    170170            self.parent.filter.logdebug("Will wait indefinitely until printer %s is in 'printing' state." % self.parent.filter.PrinterName) 
    171         else :     
     171        else : 
    172172            self.parent.filter.logdebug("Will wait until printer %s is in 'printing' state or %i seconds have elapsed." % (self.parent.filter.PrinterName, noprintingmaxdelay)) 
    173173        previousValue = self.parent.getLastPageCounter() 
     
    178178            if statusAsString in ('printing', 'warmup') : 
    179179                break 
    180             if self.printerInternalPageCounter is not None :     
     180            if self.printerInternalPageCounter is not None : 
    181181                if firstvalue is None : 
    182182                    # first time we retrieved a page counter, save it 
    183183                    firstvalue = self.printerInternalPageCounter 
    184                 else :      
     184                else : 
    185185                    # second time (or later) 
    186186                    if firstvalue < self.printerInternalPageCounter : 
     
    205205                                # the printer rejected it for some reason. 
    206206                                self.parent.filter.printInfo("Printer %s probably won't print this job !!!" % self.parent.filter.PrinterName, "warn") 
    207                             else :      
     207                            else : 
    208208                                # Here the job has already been entirely printed, and 
    209209                                # the printer has already passed from 'idle' to 'printing' to 'idle' again. 
    210210                                self.parent.filter.printInfo("Printer %s has probably already printed this job !!!" % self.parent.filter.PrinterName, "warn") 
    211211                            break 
    212             self.parent.filter.logdebug(_("Waiting for printer %s to be printing...") % self.parent.filter.PrinterName)     
     212            self.parent.filter.logdebug(_("Waiting for printer %s to be printing...") % self.parent.filter.PrinterName) 
    213213            time.sleep(statusstabilizationdelay) 
    214          
     214 
    215215    def waitIdle(self) : 
    216216        """Waits for printer status being 'idle'.""" 
     
    228228                          (dstatusAsString == 'running'))) : 
    229229                idle_flag = 1       # Standby / Powersave is considered idle 
    230             if idle_flag :     
     230            if idle_flag : 
    231231                if (self.printerInternalPageCounter is not None) \ 
    232232                   and self.skipinitialwait \ 
    233233                   and (os.environ.get("PYKOTAPHASE") == "BEFORE") : 
    234234                    self.parent.filter.logdebug("No need to wait for the printer to be idle, it is the case already.") 
    235                     return  
     235                    return 
    236236                idle_num += 1 
    237237                if idle_num >= statusstabilizationloops : 
    238238                    # printer status is stable, we can exit 
    239239                    break 
    240             else :     
     240            else : 
    241241                idle_num = 0 
    242             self.parent.filter.logdebug(_("Waiting for printer %s's idle status to stabilize...") % self.parent.filter.PrinterName)     
     242            self.parent.filter.logdebug(_("Waiting for printer %s's idle status to stabilize...") % self.parent.filter.PrinterName) 
    243243            time.sleep(statusstabilizationdelay) 
    244              
     244 
    245245    def retrieveInternalPageCounter(self) : 
    246246        """Returns the page counter from the printer via internal SNMP handling.""" 
     
    251251               self.parent.filter.JobSizeBytes : 
    252252                self.waitPrinting() 
    253             self.waitIdle()     
    254         except :     
     253            self.waitIdle() 
     254        except : 
    255255            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") 
    256256            raise 
    257257        return self.printerInternalPageCounter 
    258              
    259 if hasV4 :             
     258 
     259if hasV4 : 
    260260    class Handler(BaseHandler) : 
    261261        """A class for pysnmp v4.x""" 
     
    270270                                                  tuple([int(i) for i in hrDeviceStatusOID.split('.')]), \ 
    271271                                                  tuple([int(i) for i in hrPrinterDetectedErrorStateOID.split('.')])) 
    272             except socket.gaierror, msg :                                       
     272            except socket.gaierror, msg : 
    273273                errorIndication = repr(msg) 
    274             except :                                       
     274            except : 
    275275                errorIndication = "Unknown SNMP/Network error. Check your wires." 
    276             if errorIndication :                                                   
     276            if errorIndication : 
    277277                self.parent.filter.printInfo("SNMP Error : %s" % errorIndication, "error") 
    278278                self.initValues() 
    279             elif errorStatus :     
     279            elif errorStatus : 
    280280                self.parent.filter.printInfo("SNMP Error : %s at %s" % (errorStatus.prettyPrint(), \ 
    281281                                                                        varBinds[int(errorIndex)-1]), \ 
    282282                                             "error") 
    283283                self.initValues() 
    284             else :                                  
     284            else : 
    285285                self.printerInternalPageCounter = max(self.printerInternalPageCounter, int(varBinds[0][1].prettyPrint() or "0")) 
    286286                self.printerStatus = int(varBinds[1][1].prettyPrint()) 
     
    295295    class Handler(BaseHandler) : 
    296296        """A class for pysnmp v3.4.x""" 
    297         def retrieveSNMPValues(self) :     
     297        def retrieveSNMPValues(self) : 
    298298            """Retrieves a printer's internal page counter and status via SNMP.""" 
    299299            ver = alpha.protoVersions[alpha.protoVersionId1] 
     
    310310                                   (self.printerHostname, self.port), \ 
    311311                                   (self.handleAnswer, req)) 
    312             except (SnmpOverUdpError, select.error), msg :     
     312            except (SnmpOverUdpError, select.error), msg : 
    313313                self.parent.filter.printInfo(_("Network error while doing SNMP queries on printer %s : %s") % (self.printerHostname, msg), "warn") 
    314314                self.initValues() 
    315315            tsp.close() 
    316          
     316 
    317317        def handleAnswer(self, wholeMsg, notusedhere, req): 
    318318            """Decodes and handles the SNMP answer.""" 
     
    321321            try : 
    322322                rsp.berDecode(wholeMsg) 
    323             except TypeMismatchError, msg :     
     323            except TypeMismatchError, msg : 
    324324                self.parent.filter.printInfo(_("SNMP message decoding error for printer %s : %s") % (self.printerHostname, msg), "warn") 
    325325                self.initValues() 
     
    333333                        for varBind in rsp.apiAlphaGetPdu().apiAlphaGetVarBindList(): 
    334334                            self.values.append(varBind.apiAlphaGetOidVal()[1].rawAsn1Value) 
    335                         try :     
     335                        try : 
    336336                            # keep maximum value seen for printer's internal page counter 
    337337                            self.printerInternalPageCounter = max(self.printerInternalPageCounter, self.values[0]) 
     
    344344                                    deviceStatusValues.get(self.deviceStatus), \ 
    345345                                    self.printerDetectedErrorState)) 
    346                         except IndexError :     
     346                        except IndexError : 
    347347                            self.parent.filter.logdebug("SNMP answer is incomplete : %s" % str(self.values)) 
    348348                            pass 
    349                         else :     
     349                        else : 
    350350                            return 1 
    351                      
     351 
    352352def main(hostname) : 
    353353    """Tries SNMP accounting for a printer host.""" 
     
    358358            self.PrinterName = "FakePrintQueue" 
    359359            self.JobSizeBytes = 1 
    360              
     360 
    361361        def printInfo(self, msg, level="info") : 
    362362            """Prints informational message.""" 
    363363            sys.stderr.write("%s : %s\n" % (level.upper(), msg)) 
    364364            sys.stderr.flush() 
    365              
    366         def logdebug(self, msg) :     
     365 
     366        def logdebug(self, msg) : 
    367367            """Prints debug message.""" 
    368368            self.printInfo(msg, "debug") 
    369              
    370     class fakeAccounter :         
     369 
     370    class fakeAccounter : 
    371371        """Fakes an accounter for testing purposes.""" 
    372372        def __init__(self) : 
     
    375375            self.filter = fakeFilter() 
    376376            self.protocolHandler = Handler(self, hostname) 
    377              
    378         def getLastPageCounter(self) :     
     377 
     378        def getLastPageCounter(self) : 
    379379            """Fakes the return of a page counter.""" 
    380380            return 0 
    381          
    382     acc = fakeAccounter()             
     381 
     382    acc = fakeAccounter() 
    383383    return acc.protocolHandler.retrieveInternalPageCounter() 
    384          
    385 if __name__ == "__main__" :             
    386     if len(sys.argv) != 2 :     
     384 
     385if __name__ == "__main__" : 
     386    if len(sys.argv) != 2 : 
    387387        sys.stderr.write("Usage :  python  %s  printer_ip_address\n" % sys.argv[0]) 
    388     else :     
     388    else : 
    389389        def _(msg) : 
    390390            return msg 
    391              
     391 
    392392        pagecounter = main(sys.argv[1]) 
    393393        print "Internal page counter's value is : %s" % pagecounter