Skip to content

Writing API Programs

Thomas Mangin edited this page Oct 6, 2026 · 12 revisions

Writing API Programs

An API program is a program of your own which ExaBGP starts and talks to over a pair of pipes. It writes commands, such as announcing or withdrawing a route, on its standard output, and reads ExaBGP's answer to each command, and any BGP messages it asked for, on its standard input. Any language able to read and write a line of text can be used.

The most common program announces a service address while the service works and withdraws it when it fails. ExaBGP ships with a program which does exactly that, exabgp healthcheck, described on the Healthcheck page. It is worth checking whether it covers your case before writing your own.

Table of Contents


How a program talks to ExaBGP

A program is declared in a process block and attached to the neighbours it may talk to with an api block:

process my-program {
    run /etc/exabgp/my-program.py;
    encoder text;
}

neighbor 198.51.100.1 {
    router-id 198.51.100.2;
    local-address 198.51.100.2;
    local-as 65001;
    peer-as 65000;

    api {
        processes [ my-program ];
    }
}

ExaBGP starts the program when it starts, and restarts it if it exits. Each line the program writes on its standard output is one command. The program has to flush its output after each command, because a pipe is buffered and a command left in the buffer never reaches ExaBGP. ExaBGP does not read the program's standard error, which goes wherever ExaBGP's own standard error goes, the terminal or the service manager's journal, and is the place for the program's own diagnostics.

The commands depend on the version of the API:

ExaBGP Command
6.0 peer * announce route 192.0.2.10/32 next-hop self
5.x and 4.x announce route 192.0.2.10/32 next-hop self

peer * sends the route to every neighbour the program is attached to, and peer 198.51.100.1 to one of them. ExaBGP 6.0 accepts both forms and works out, for each program, which one it uses: the first command whose first word belongs to one form (peer, daemon, session, system or rib for 6.0; announce, withdraw, neighbor and the other 5.x commands for 5.x) holds the program to that form until it is restarted, and a command written in the other form is then answered error. A program written for 5.x therefore runs unchanged, and so does one written for 6.0, side by side. Setting exabgp.api.version to 4 or 6 holds every program to that form instead of detecting it; its default is auto. From 5.x to 6.0.0 describes the other differences. The rest of this page writes 5.x commands, which a 6.0 program prefixes with peer *. The full list of commands is in API Commands.

Reading the answers

ExaBGP answers every command with a line on the program's standard input: done when it accepted the command, error when it did not. An error can be preceded by a line giving the reason: error: <reason> for an API 4 program, {"error": "<reason>"} for an API 6 one. done and error are plain text in every version, whichever encoder the process uses.

A program has to read these answers. ExaBGP writes them into the pipe whether or not the program reads them, and the pipe only holds 64 KiB on Linux. In 5.x and 4.x, ExaBGP stops when the pipe is full: it waits for the program to make room, and while it waits it does nothing else, including keeping its BGP sessions alive. In 6.0 the answers the pipe cannot hold are kept in ExaBGP's memory, which grows for as long as the program runs. At five bytes per done, a program announcing its route every five seconds fills the pipe in about eighteen hours.

Reading the answer also tells the program whether its command worked. Without it, a typing mistake in a command, or a 5.x command sent to 6.0, fails without the program ever knowing.

The same pipe carries everything else ExaBGP sends to the program: the BGP messages, neighbour changes and other events asked for in the api block. A program waiting for its answer has to skip those lines. When it also wants them, it should handle them in the same loop rather than discard them.

When the program has no use for the answers, it can tell ExaBGP to stop sending them, by writing one of these commands first:

6.0 5.x Effect
session ack disable disable-ack Answers this command with a last done, then sends no more answers
session ack silence silence-ack Sends no more answers, starting with this command
session ack enable enable-ack Sends answers again, starting with done for this command

A 6.0 program uses the 6.0 names and a 5.x program the 5.x names, as for every other command. Setting exabgp.api.ack=false in the environment stops the answers for every program instead, and in 4.x it is the only way.

Templates

These templates announce 192.0.2.10/32 while something listens on port 80 of the local machine, withdraw it when nothing does, and read the answer to each command. They write 6.0 commands; for 5.x and 4.x, PREFIX is set to an empty string.

Python

#!/usr/bin/env python3
import socket
import sys
import time

ROUTE = 'route 192.0.2.10/32 next-hop self'
PREFIX = 'peer * '  # ExaBGP 6.0; empty for 4.x and 5.x
CHECK_INTERVAL = 5


def send(command):
    """Write one command, then read lines until ExaBGP answers it."""
    sys.stdout.write(PREFIX + command + '\n')
    sys.stdout.flush()
    while True:
        line = sys.stdin.readline()
        if not line:  # ExaBGP closed the pipe: it is stopping
            sys.exit(0)
        answer = line.strip()
        if answer == 'done':
            return True
        if answer == 'error':
            return False
        # any other line is the reason for an error, or a message
        # this process was configured to receive


def healthy():
    try:
        with socket.create_connection(('127.0.0.1', 80), timeout=2):
            return True
    except OSError:
        return False


announced = False
while True:
    up = healthy()
    if up != announced:
        action = 'announce' if up else 'withdraw'
        if send(f'{action} {ROUTE}'):
            announced = up
        else:
            sys.stderr.write(f'ExaBGP refused: {action} {ROUTE}\n')
    time.sleep(CHECK_INTERVAL)

The program only writes when the state of the service changes, and it only records the new state once ExaBGP has accepted the command, so a refused command is tried again on the next check.

Shell

#!/bin/sh
ROUTE="route 192.0.2.10/32 next-hop self"
PREFIX="peer * "   # ExaBGP 6.0; empty for 4.x and 5.x

send() {
    echo "${PREFIX}$1"
    while read -r answer; do
        case "$answer" in
            done) return 0 ;;
            error) return 1 ;;
        esac
    done
    exit 0   # ExaBGP closed the pipe: it is stopping
}

announced=no
while true; do
    if nc -z 127.0.0.1 80 2>/dev/null; then
        [ "$announced" = no ] && send "announce $ROUTE" && announced=yes
    else
        [ "$announced" = yes ] && send "withdraw $ROUTE" && announced=no
    fi
    sleep 5
done

echo writes its line at once, so the shell needs no explicit flush.

Go

package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"time"
)

const route = "route 192.0.2.10/32 next-hop self"
const prefix = "peer * " // ExaBGP 6.0; empty for 4.x and 5.x

var answers = bufio.NewScanner(os.Stdin)

// send writes one command, then reads lines until ExaBGP answers it.
func send(command string) bool {
	fmt.Println(prefix + command) // os.Stdout is not buffered
	for answers.Scan() {
		switch answers.Text() {
		case "done":
			return true
		case "error":
			return false
		}
	}
	os.Exit(0) // ExaBGP closed the pipe: it is stopping
	return false
}

func healthy() bool {
	conn, err := net.DialTimeout("tcp", "127.0.0.1:80", 2*time.Second)
	if err != nil {
		return false
	}
	conn.Close()
	return true
}

func main() {
	announced := false
	for {
		up := healthy()
		if up != announced {
			action := "withdraw"
			if up {
				action = "announce"
			}
			if send(action + " " + route) {
				announced = up
			} else {
				fmt.Fprintf(os.Stderr, "ExaBGP refused: %s %s\n", action, route)
			}
		}
		time.Sleep(5 * time.Second)
	}
}

Other languages

The same three steps apply in any language: write the command followed by a newline, flush the output, and read lines from the input until one is done or error. In Ruby, STDOUT.sync = true removes the need to flush and STDIN.gets reads a line. In Node.js, process.stdout.write sends the command and the readline module reads the answers from process.stdin.


Receiving messages from ExaBGP

A program can also receive the BGP messages ExaBGP exchanges with its neighbours, and the changes of state of each session. What it receives is chosen in the api block of the neighbour, which also names the process:

neighbor 198.51.100.1 {
    router-id 198.51.100.2;
    local-address 198.51.100.2;
    local-as 65001;
    peer-as 65000;

    api {
        processes [ watcher ];
        neighbor-changes;
        receive {
            parsed;
            update;
        }
    }
}

neighbor-changes reports each session going up or down, receive { update; } the UPDATE messages received from the neighbour, and send { update; } those ExaBGP sends to it. parsed asks for the decoded message; packets would give the raw bytes as well. API Overview lists every message type which can be requested.

The encoder of the process chooses the format. A 6.0 program always receives JSON, whatever its encoder. A 5.x program, on 6.0 as on 5.x and 4.x, receives what its encoder asks for: encoder json gives JSON and encoder text a line of text per message, which is easier to read but harder to parse. JSON is the format to use for a program.

Each message is one JSON object on one line. An UPDATE received from a neighbour looks like this, with the announced routes grouped by family and then by next hop, and the withdrawn routes grouped by family:

{ "exabgp": "6.0.0", "type": "update", "neighbor": { "address": { "local": "198.51.100.2", "peer": "198.51.100.1" }, "asn": { "local": 65001, "peer": 65000 }, "direction": "receive", "message": { "update": { "attribute": { "origin": "igp", "local-preference": 100 }, "announce": { "ipv4 unicast": { "192.0.2.1": [ { "nlri": "10.0.0.0/24" } ] } } } } } }
{ "exabgp": "6.0.0", "type": "update", "neighbor": { "address": { "local": "198.51.100.2", "peer": "198.51.100.1" }, "direction": "receive", "message": { "update": { "withdraw": { "ipv4 unicast": [ { "nlri": "10.0.0.0/24" } ] } } } } }

A session changing state is reported with the type state, and neighbor.state set to connected, up or down. The complete format of every message is in JSON API Reference.

This program logs the routes its neighbours announce and withdraw, for the unicast families. The answers to its own commands arrive on the same input, so it skips them, and a program which also writes commands would act on them there instead:

#!/usr/bin/env python3
import json
import sys


def log(text):
    sys.stderr.write(text + '\n')
    sys.stderr.flush()


def on_update(peer, update):
    # announce: family -> next hop -> list of routes
    for family, next_hops in update.get('announce', {}).items():
        for next_hop, routes in next_hops.items():
            for route in routes:
                if 'nlri' not in route:
                    continue  # an End-of-RIB marker, which has no route
                log(f'{peer} announced {route["nlri"]} via {next_hop} ({family})')
    # withdraw: family -> list of routes
    for family, routes in update.get('withdraw', {}).items():
        for route in routes:
            log(f'{peer} withdrew {route["nlri"]} ({family})')


for line in sys.stdin:
    line = line.strip()
    if line in ('done', 'error') or line.startswith('error:'):
        continue  # the answer to a command this program wrote
    try:
        message = json.loads(line)
    except ValueError:
        log(f'not JSON: {line}')
        continue
    neighbor = message.get('neighbor', {})
    peer = neighbor.get('address', {}).get('peer')
    if message.get('type') == 'state':
        log(f'{peer} is {neighbor.get("state")}')
    elif message.get('type') == 'update':
        on_update(peer, neighbor['message']['update'])

A program which both writes commands and receives messages can wait for its answer inside the same loop which handles the messages, or be split into two processes, one for each direction, which keeps each of them simple.

When the program stops

When ExaBGP stops, it closes the program's input, and a program reading its input sees the end of the file and should exit, as the templates do. ExaBGP also sends a last message before closing, shutdown with the text encoder, or a JSON object of type notification containing "notification": "shutdown".

When the program exits while ExaBGP keeps running, ExaBGP starts it again, unless the process block says respawn false;. In 6.0, the routes of a program using the 6.0 commands (API 6) are withdrawn when it exits, while a program using the commands of 4.x and 5.x (API 4) keeps them, as those releases did. on-exit keep; or on-exit withdraw; in the process block decides instead, whatever the API. 5.x and 4.x leave them announced, so a program for those versions which has to take its routes away should withdraw them itself on SIGTERM before it exits.

Testing a program

A program can be run by hand, without ExaBGP, by playing ExaBGP's part in the terminal: it prints its commands, and typing done after each one answers it. A program which stops after printing its first command is waiting for that answer.

$ ./my-program.py
peer * announce route 192.0.2.10/32 next-hop self
done

A receiving program can be fed the JSON from this page, or real messages produced by exabgp decode:

exabgp encode "route 10.0.0.0/24 next-hop 192.0.2.1" | exabgp decode | ./watcher.py

Under ExaBGP, running with exabgp.log.level=DEBUG and exabgp.log.processes=true logs every command a program writes and every answer it receives, which shows at once whether a command was refused.

Common mistakes

  • The output is not flushed, so ExaBGP never sees the command. Python needs sys.stdout.flush() or print(..., flush=True).
  • The answers are never read. In 5.x ExaBGP stops once the pipe is full, and in 6.0 its memory grows; see Reading the answers.
  • The program waits for an answer while the answers are switched off with exabgp.api.ack=false or session ack disable, and blocks forever.
  • A program mixes the two command forms. Its first command decides which one it uses, and a command in the other form is answered error.
  • The process is declared but not named in any neighbour's api block, so its commands reach no neighbour.

See Also

Clone this wiki locally