[Twisted-Python] "Injecting" a callWhenRunning when the reactor is already running?

justind2 at ussonet.net justind2 at ussonet.net
Tue Aug 1 13:09:17 EDT 2006


Here is a script I've made and am playing with to try to understand how 
things behave in Twisted. I'm using twistedsnmp but I think my problem 
here is my understanding of how to use the reactor (or lack there of).

I feel like I'm misunderstanding some fundamentals, but I may just be 
hard-headed.

I'm not even sure if this makes sense. I've noticed that unless 
reactor.callWhenRunning(return_def,df) is ran prior to calling 
reactor.run() the return_def will never be ran.

I'm not really sure how to phrase the question, because it may be the 
wrong one.. so here goes...

Is there a way to get the reactor to acknowledge a new "callWhenRunning" 
after the reactor.run()?


I've included my bad code and working code, the difference is in the 
"bad code" I launch a thread that tries every 5 seconds (after 
reactor.run()) to do what the "working code" does only once before.

Any help would be appreciated.


BAD CODE BELOW:

from twisted.internet import reactor
from twisted.internet import task
from twistedsnmp import snmpprotocol, agentproxy
from twisted.internet.defer import TimeoutError
import pprint
import logging
import thread
import time

logging.getLogger().setLevel(logging.INFO)

ips = 
['10.0.16.2','10.0.16.18','10.0.16.34','10.0.16.66','10.0.16.82','10.0.16.98','10.0.16.114','10.0.16.130']

devices = {}

logging.info('Building device dictionary')
for ip in ips:
    devices[ip] = {}
    devices[ip]['oids_to_poll'] = {}
    devices[ip]['oids_to_poll']['sysDescr'] = '.1.3.6.1.2.1.1.0'
    devices[ip]['oids_to_poll']['uptime'] = '.1.3.6.1.2.1.1.3.0'
logging.info('Device dictionary built')

   
def successful_response(result):
    logging.info(str(result))
    return result

def errored_response(err):
    if err.trap(TimeoutError):
        logging.error("timeout error")
        #### dont return the error because it will be handeled if you do
    else:
        logging.error("error" + str(err))
        return err

def return_def(df):
    return df


def process_devices():
    logging.info("proccess_devices thread has been launched")
    while True:
        time.sleep(5)
        for device in devices.keys():
            #### first build the proxy
            try:
                logging.info("building proxy for device:" + str(device))
                port = snmpprotocol.port()
                proxy = agentproxy.AgentProxy(device, 161, 
community='public',snmpVersion='v2',protocol=port.protocol,)
            except:
                logging.exception("exception occured while building proxy")
            else:
                ##### now that the proxy is buil send the request for 
the oids to poll
                if devices.has_key(device):
                    try:
                        oid_descriptions = 
devices[device]['oids_to_poll'].keys()
                    except:
                        pass
                    else:
                        try:
                            oids = []
                            for oid_description in oid_descriptions:
                                
oids.append(devices[device]['oids_to_poll'][oid_description])
                        except:
                            pass
                        else:
                            ##### you have built the list of oids to 
poll now build the deffered and return it
                            logging.info("building defferred for 
device:" + str(device))
                            df = proxy.get(oids, timeout=0.25, retryCount=3)
                            df.addCallback(successful_response)
                            df.addErrback(errored_response)
                            logging.info("launching callWhenRunning for 
device:" + str(device))
                            reactor.callWhenRunning(return_def,df)

thread.start_new(process_devices,())
logging.info("starting reactor")
reactor.run()



WORKING CODE (not necessarily good):

from twisted.internet import reactor
from twisted.internet import task
from twistedsnmp import snmpprotocol, agentproxy
from twisted.internet.defer import TimeoutError
import pprint
import logging
import time

logging.getLogger().setLevel(logging.INFO)

ips = 
['10.0.16.2','10.0.16.18','10.0.16.34','10.0.16.66','10.0.16.82','10.0.16.98','10.0.16.114','10.0.16.130']

devices = {}

logging.info('Building device dictionary')
for ip in ips:
    devices[ip] = {}
    devices[ip]['oids_to_poll'] = {}
    devices[ip]['oids_to_poll']['sysDescr'] = '.1.3.6.1.2.1.1.0'
    devices[ip]['oids_to_poll']['uptime'] = '.1.3.6.1.2.1.1.3.0'
logging.info('Device dictionary built')

   
def successful_response(result):
    logging.info(str(result))
    return result

def errored_response(err):
    if err.trap(TimeoutError):
        logging.error("timeout error")
        #### dont return the error because it will be handeled if you do
    else:
        logging.error("error" + str(err))
        return err

def return_def(df):
    return df


def process_devices():
    logging.info("proccess_devices thread has been launched")
        for device in devices.keys():
            #### first build the proxy
            try:
                logging.info("building proxy for device:" + str(device))
                port = snmpprotocol.port()
                proxy = agentproxy.AgentProxy(device, 161, 
community='public',snmpVersion='v2',protocol=port.protocol,)
            except:
                logging.exception("exception occured while building proxy")
            else:
                ##### now that the proxy is buil send the request for 
the oids to poll
                if devices.has_key(device):
                    try:
                        oid_descriptions = 
devices[device]['oids_to_poll'].keys()
                    except:
                        pass
                    else:
                        try:
                            oids = []
                            for oid_description in oid_descriptions:
                                
oids.append(devices[device]['oids_to_poll'][oid_description])
                        except:
                            pass
                        else:
                            ##### you have built the list of oids to 
poll now build the deffered and return it
                            logging.info("building defferred for 
device:" + str(device))
                            df = proxy.get(oids, timeout=0.25, retryCount=3)
                            df.addCallback(successful_response)
                            df.addErrback(errored_response)
                            logging.info("launching callWhenRunning for 
device:" + str(device))
                            reactor.callWhenRunning(return_def,df)

process_devices()
logging.info("starting reactor")
reactor.run()
















More information about the Twisted-Python mailing list