Integration of Net-⁠SNMP into an event loop

Vincent Bernat

Net-⁠SNMP comes with its own event loop based on the select() sys­tem call. While you can build your pro­gram around it, you may pre­fer to use an ex­ist­ing event loop, ei­ther a cus­tom one or some­thing like libevent, libev or Twisted.

Own custom event loop#

Let’s start with the eas­i­est case: you have writ­ten your own event loop. This means you make a call to select(), poll(), epoll(), kqueue() or some­thing sim­i­lar. All these func­tions take a set of file de­scrip­tors and wait for any of them to be­come avail­able in a spec­i­fied time frame.

Here is a typ­i­cal use of select() (adapted from Quagga):

readfd = m->readfd;
writefd = m->writefd;
exceptfd = m->exceptfd;
timer_wait = thread_timer_wait (&m->timer);
num = select (FD_SETSIZE,
              &readfd, &writefd, &exceptfd,
              timer_wait);
if (num < 0)
  {
    if (errno == EINTR)
      continue; /* signal received - process it */
    zlog_warn ("select() error: %s",
               safe_strerror (errno));
    return NULL;
  }
if (num == 0)
  {
    /* Timeout handling */
    thread_timer_process (&m->timer);
  }
if (num > 0)
  {
    thread_process_fd (&readfd);
    thread_process_fd (&writefd);
  }

The thread_​process_​fd (fds) func­tion it­er­ates on each file de­scrip­tor fd and ex­e­cutes the ap­pro­pri­ate ac­tion if FD_​ISSET (fds, fd) is true.

In­te­grat­ing Net-⁠SNMP into such an event loop is easy: Net-⁠SNMP pro­vides the snmp_​select_​info() func­tion which al­ters a set of file de­scrip­tors to in­sert its own. Here is the new code:

#if defined HAVE_SNMP
struct timeval snmp_timer_wait;
int snmpblock = 0;
int fdsetsize;
#endif

/* ... */

#if defined HAVE_SNMP
fdsetsize = FD_SETSIZE;
snmpblock = 1;
if (timer_wait)
  {
    snmpblock = 0;
    memcpy(&snmp_timer_wait, timer_wait,
           sizeof(struct timeval));
  }
snmp_select_info(&fdsetsize, &readfd,
                 &snmp_timer_wait, &snmpblock);
if (snmpblock == 0)
  timer_wait = &snmp_timer_wait;
#endif

num = select (FD_SETSIZE,
              &readfd, &writefd, &exceptfd,
              timer_wait);
if (num < 0) { /* ... */ }

#if defined HAVE_SNMP
if (num > 0)
  snmp_read(&readfd);
else if (num == 0)
  {
    snmp_timeout();
    run_alarms();
  }
netsnmp_check_outstanding_agent_requests();
#endif

/* ... */

snmp_​select_​info() may mod­ify the pro­vided set of file de­scrip­tors (and there­fore, its size). It may also mod­ify the pro­vided timer in case it needs to sched­ule an ac­tion be­fore the orig­i­nal timeout.

snmpblock is a tricky vari­able. While select() can be called with a time­out set to NULL, this is not the case for snmp_​select_​info(): you have to pass a valid pointer. snmpblock is set to 0 if the pro­vided time­out must be con­sid­ered or to 1 oth­er­wise. snmp_​select_​info() will set snmpblock to 0 if and only if it al­ters the timeout.

Here are three ex­am­ples of in­te­gra­tion. They are for a sub­agent but the code for a man­ager is the same:

Third-party event loop#

With a third-party event loop, you do not have ac­cess to the select() sys­tem call any­more. There­fore, you can­not al­ter it with snmp_​select_​info(). In­stead, at each it­er­a­tion of the loop, a list of SNMP-re­lated file de­scrip­tors is kept up to date with the help of snmp_​select_​info(): new ones are added and old ones are removed.

libevent#

Let’s as­sume that snmp_​fds is the list of cur­rent SNMP-re­lated events.1 A func­tion levent_​snmp_​update() calls snmp_​select_​info() to up­date this list. Here is a par­tial im­ple­men­ta­tion (er­ror han­dling re­moved and some dec­la­ra­tions omit­ted, look at the com­plete ver­sion from lldpd):

static void
levent_snmp_update()
{
    int maxfd = 0;
    int block = 1;

    FD_ZERO(&fdset);
    snmp_select_info(&maxfd, &fdset, &timeout, &block);

    /* We need to untrack any event whose FD is not in `fdset`
       anymore */
    for (snmpfd = TAILQ_FIRST(snmp_fds);
         snmpfd;
         snmpfd = snmpfd_next) {
        snmpfd_next = TAILQ_NEXT(snmpfd, next);
        if (event_get_fd(snmpfd->ev) >= maxfd ||
            (!FD_ISSET(event_get_fd(snmpfd->ev), &fdset))) {
            event_free(snmpfd->ev);
            TAILQ_REMOVE(snmp_fds, snmpfd, next);
            free(snmpfd);
        } else
            FD_CLR(event_get_fd(snmpfd->ev), &fdset);
    }

    /* Invariant: FD in `fdset` are not in list of FD */
    for (int fd = 0; fd < maxfd; fd++)
        if (FD_ISSET(fd, &fdset)) {
            snmpfd->ev = event_new(base, fd,
                EV_READ | EV_PERSIST,
                levent_snmp_read,
                NULL);
            event_add(snmpfd->ev, NULL);
            TAILQ_INSERT_TAIL(snmp_fds, snmpfd, next);
        }

    /* If needed, handle timeout */
    evtimer_add(snmp_timeout, block?NULL:&timeout);
}

Then, re­place the main loop (usu­ally, a call to event_​base_​dispatch()) with this:

do {
    if (event_base_got_break(base) ||
        event_base_got_exit(base))
        break;
    netsnmp_check_outstanding_agent_requests();
    levent_snmp_update();
} while (event_base_loop(base, EVLOOP_ONCE) == 0);

Here is how the two call­backs are defined:

static void
levent_snmp_read(evutil_socket_t fd, short what, void *arg)
{
    FD_ZERO(&fdset);
    FD_SET(fd, &fdset);
    snmp_read(&fdset);
    levent_snmp_update();
}

static void
levent_snmp_timeout(evutil_socket_t fd, short what, void *arg)
{
    snmp_timeout();
    run_alarms();
    levent_snmp_update();
}

Twisted reactor#

As a sec­ond ex­am­ple, here is how to in­te­grate Net-⁠SNMP into the Twisted re­ac­tor. Twisted is an event-driven net­work pro­gram­ming frame­work writ­ten in Python. It does not come with sup­port for SNMP.2 Be­cause of the lan­guage mis­match, the in­te­gra­tion of Net-⁠SNMP in Twisted needs to be done us­ing a C ex­ten­sion or the ctypes module.3

The Twisted event loop is called a re­ac­tor. Like for libevent, events need to be reg­is­tered. It is pos­si­ble to reg­is­ter file-de­scrip­tor-like ob­jects us­ing a class im­ple­ment­ing a hand­ful of meth­ods. Here is the im­ple­men­ta­tion of such a class (adapted from PyNet-⁠SNMP, a sub­pro­ject of Zenoss us­ing the ctypes module):

class SnmpReader:
    "Respond to input events"
    implements(IReadDescriptor)

    def __init__(self, fd):
        self.fd = fd

    def doRead(self):
        netsnmp.snmp_read(self.fd)

    def fileno(self):
        return self.fd

Like for libevent, we have a func­tion to up­date the list of SNMP-re­lated events (stored as a map­ping be­tween file de­scrip­tors and SnmpReader in­stances):

class Timer(object):
    callLater = None
timer = Timer()
fdMap = {}

def updateReactor():
    "Add/remove event handlers for SNMP file descriptors and timers"

    fds, t = netsnmp.snmp_select_info()
    for fd in fds:
        if fd not in fdMap:
            reader = SnmpReader(fd)
            fdMap[fd] = reader
            reactor.addReader(reader)
    current = Set(fdMap.keys())
    need = Set(fds)
    doomed = current - need
    for d in doomed:
        reactor.removeReader(fdMap[d])
        del fdMap[d]
    if timer.callLater:
        timer.callLater.cancel()
        timer.callLater = None
    if t is not None:
        timer.callLater = reactor.callLater(t, checkTimeouts)

Con­trary to libevent, we can­not al­ter the main loop to call updateReactor() at each it­er­a­tion. There­fore, it must be called af­ter each SNMP-re­lated function.

For an­other ex­am­ple, have a look at my equiv­a­lent im­ple­men­ta­tion as a C ex­tension.

Miscellaneous#

Lack of asynchronicity#

In­te­grat­ing Net-⁠SNMP into an event-based pro­gram is not risk-free. I have writ­ten a fairly com­pre­hen­sive ar­ti­cle on the lack of asyn­chronic­ity in the Net-⁠SNMP AgentX pro­to­col im­ple­men­ta­tion. I urge you to read it if you want to in­te­grate an SNMP sub­agent into an ex­ist­ing program.

On the man­ager side, you will get sim­i­lar draw­backs when us­ing SNMPv3. To re­trieve or ma­nip­u­late man­age­ment in­for­ma­tion us­ing SNMPv3, it is nec­es­sary to know the iden­ti­fier of the re­mote SNMP pro­to­col en­gine. This iden­ti­fier can be con­fig­ured di­rectly on each man­ager but it is usu­ally dis­cov­ered by query­ing SNMP-FRAMEWORK-MIB::‌snmpEngineID, as de­scribed in RFC 5343.

Un­for­tu­nately, this dis­cov­ery is done syn­chronously by Net-⁠SNMP. There is a bug re­port for this is­sue but it seems dif­fi­cult to fix. I have not been able to come up with a proper patch but I have de­scribed a work­around around snmp_​sess_​async_send().

There is no such prob­lem with SNMPv2.

Limitation of file descriptor sets#

snmp_​select_​info() and snmp_​read() use the fd_​set type to han­dle a set of file de­scrip­tors. This type should be ma­nip­u­lated with FD_​CLR(), FD_​ISSET(), FD_​SET() and FD_​ZERO(). They may be de­fined as func­tions but they usu­ally are macros. More­over, no file de­scrip­tor greater than FD_​SETSIZE (which is usu­ally set to 1024) can be han­dled with the fd_​set type. This means that if you have a file de­scrip­tor greater than 1024, you will not be able to use snmp_​select_​info() with it.

Start­ing from Net-⁠SNMP 5.5, you can use snmp_​select_​info2() and snmp_​read2() in­stead of snmp_​select_​info() and snmp_​read(). They use the netsnmp_​large_​fd_​set type.

If you want to keep com­pat­i­bil­ity with Net-⁠SNMP 5.4, here is an­other twist. The fd_​set type is usu­ally a fixed-size ar­ray of long in­te­gers. FD_​CLR(), FD_​ISSET() and FD_​SET() are size-in­de­pen­dent. The size only mat­ters for FD_​ZERO() which is not used by ei­ther snmp_​select_​info() or snmp_​read(). You can there­fore al­lo­cate a larger fd_​set. A com­mon way is to com­pile your pro­gram with -D__​FD_​SETSIZE=​4096. You can still use FD_​ZERO() your­self. How­ever, this is not por­ta­ble (GNU C li­brary only). An­other way is to al­lo­cate your own ar­ray of long in­te­gers and cast it to fd_​set. You will have to re­de­fine FD_ZERO():

typedef struct {
   long int fds_bits[4096/sizeof(long int)];
} my_fdset;

#undef FD_ZERO
#define FD_ZERO(fdset) memset((fdset), 0, sizeof(my_fdset))

{
   /* ... */
   my_fdset fdset;
   FD_ZERO(&fdset);
   /* ... */
   rc = snmp_select_info(&n, (fd_set *)&fdset, &timeout, &block);
   /* ... */
}

Threads#

Net-⁠SNMP pro­vides two APIs:

  • the tra­di­tional ses­sion API which is not thread-safe and
  • the sin­gle ses­sion API.

In the above ex­am­ples, I have used the tra­di­tional ses­sion API. If you are us­ing threads, you need to en­sure that all SNMP op­er­a­tions are done in a sin­gle thread. Oth­er­wise, you need to adapt the ex­am­ples to use the sin­gle ses­sion API. snmp_​select_​info() is part of the tra­di­tional ses­sion API. You should re­place it with snmp_​sess_​select_​info() and keep a list of SNMP sessions.

This API is not avail­able for the agent side of Net-⁠SNMP.