Skip to content

API Overview

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

API Overview

Understanding ExaBGP's STDIN/STDOUT API


Table of Contents


What is the ExaBGP API?

The ExaBGP API is a simple STDIN/STDOUT interface that allows your programs to control BGP route announcements and receive BGP updates.

Key characteristics:

  • Language-agnostic: Works with Python, Bash, Ruby, Go, Rust, Node.js, or any language
  • Simple: No libraries needed - just read/write text or JSON
  • Bidirectional: Your program sends commands, receives BGP messages
  • Process-based: ExaBGP spawns your program as a subprocess

Think of it as:

Your Program ↔ STDIN/STDOUT ↔ ExaBGP ↔ BGP Protocol ↔ Router

Why This API Design?

Philosophy

"The best API is no API"

ExaBGP uses UNIX pipes (STDIN/STDOUT) instead of complex libraries.

Advantages:

  • ✅ No dependencies: Works with any language that can read/write streams
  • ✅ Simple: print() to send commands, readline() to receive
  • ✅ Debugging-friendly: Can test manually with echo/cat
  • ✅ Language-agnostic: Not tied to Python or any specific ecosystem
  • ✅ Process isolation: Your program crashes don't affect ExaBGP
  • ✅ Easy integration: Wrap existing tools without modification

Compared to alternatives:

  • Library-based (e.g., GoBGP's gRPC): Requires language-specific client
  • REST API: Adds HTTP overhead, state management complexity
  • File-based: Requires polling, slower updates

STDIN/STDOUT is:

  • Fast (no network/HTTP overhead)
  • Simple (just streams)
  • Universal (every language supports it)

How It Works

Configuration

ExaBGP configuration defines which programs to run:

neighbor 192.168.1.1 {
    router-id 192.168.1.2;
    local-address 192.168.1.2;
    local-as 65001;
    peer-as 65000;

    # API configuration
    api {
        processes [ my-program ];
    }
}

process my-program {
    run /etc/exabgp/api/my-program.py;
    encoder text;  # or 'json'
}

Process Startup

When ExaBGP starts:

  1. ExaBGP spawns /etc/exabgp/api/my-program.py as subprocess
  2. ExaBGP connects to program's STDIN/STDOUT
  3. Program can now:
    • Write to STDOUT → Commands to ExaBGP
    • Read from STDIN → BGP messages from ExaBGP

Communication

┌─────────────────────┐
│  Your Program       │
│                     │
│  print("announce    │  STDOUT ──────┐
│    route ...")      │               │
│                     │               ▼
│  for line in stdin: │  STDIN  ◀──────┬─────────┐
│    process(line)    │                │ ExaBGP  │
└─────────────────────┘                │         │
                                       │ BGP     │
                                       │ Speaker │
                                       └────┬────┘
                                            │
                                            │ BGP Protocol
                                            ▼
                                       ┌─────────┐
                                       │ Router  │
                                       └─────────┘

Targeting Specific Neighbors

When ExaBGP is configured with multiple BGP neighbors, you can use neighbor selectors to target specific peers with your API commands.

Basic Syntax

neighbor <ip> [selector-options] <command>

A command without a selector applies to every neighbor whose api block names the program. Use the neighbor keyword to target specific peer(s) instead.

Quick Examples

# Target single neighbor
print("neighbor 127.0.0.1 announce route 10.0.0.0/24 next-hop self")

# Target all neighbors
print("neighbor * announce route 10.0.0.0/24 next-hop self")

# Target multiple neighbors
print("neighbor 10.0.0.1 , neighbor 10.0.0.2 announce route 10.0.0.0/24 next-hop self")

# Filter by peer ASN
print("neighbor 127.0.0.1 peer-as 65000 announce route 10.0.0.0/24 next-hop self")

Available Selectors

You can use these selectors to differentiate between multiple peers:

  • neighbor <ip> - Required: Target neighbor by IP address
  • local-ip <ip> - Filter by local IP address (when multiple local IPs)
  • local-as <asn> - Filter by local ASN (for multi-AS setups)
  • peer-as <asn> - Filter by peer ASN
  • router-id <id> - Filter by router ID
  • family-allowed <families> - Filter by address family capabilities (e.g., ipv4-unicast/ipv6-unicast for multi-session, or in-open for single-session)

Common Use Cases

Multi-Provider Setup:

# Announce different routes to different providers
sys.stdout.write("neighbor 10.0.1.1 announce route 100.10.0.0/24 next-hop self as-path [65001 65001]\n")  # Provider A (de-preference)
sys.stdout.flush()

sys.stdout.write("neighbor 10.0.2.1 announce route 100.10.0.0/24 next-hop self\n")  # Provider B (preferred)
sys.stdout.flush()

Geographic Load Balancing:

# US datacenter announces to US peers with high preference
sys.stdout.write("neighbor 192.168.1.1 announce route 100.10.0.100/32 next-hop self local-preference 200\n")
sys.stdout.flush()

# EU datacenter announces to EU peers with high preference
sys.stdout.write("neighbor 192.168.2.1 announce route 100.10.0.100/32 next-hop self local-preference 200\n")
sys.stdout.flush()

ASN-Based Filtering:

# Announce to 192.168.1.1 only if it is in AS 65000
sys.stdout.write("neighbor 192.168.1.1 peer-as 65000 announce route 10.0.0.0/8 next-hop self\n")
sys.stdout.flush()

Address Family Filtering:

# Announce to 192.168.1.1 only if it is a multi-session neighbor configured for IPv4 and IPv6 unicast
sys.stdout.write("neighbor 192.168.1.1 family-allowed ipv4-unicast/ipv6-unicast announce route 10.0.0.0/24 next-hop self\n")
sys.stdout.flush()

The selectors are compared with the name ExaBGP gives each neighbor, which lists the families only for a multi-session neighbor; any other neighbor is named family-allowed in-open. neighbor * selects every neighbor, and ExaBGP ignores the selectors written after the *, so neighbor * peer-as 65000 reaches neighbors in every AS.

Configuration Example

# Multiple neighbors sharing one API process
neighbor 192.168.1.1 {
    router-id 192.168.1.2;
    local-address 192.168.1.2;
    local-as 65001;
    peer-as 65000;

    api {
        processes [ my-program ];
    }
}

neighbor 192.168.2.1 {
    router-id 192.168.1.2;
    local-address 192.168.1.2;
    local-as 65001;
    peer-as 65002;

    api {
        processes [ my-program ];
    }
}

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

With this configuration, my-program can selectively announce routes to either neighbor using neighbor selectors.

Important Notes

  • 💡 Default behavior: Commands without neighbor selector apply to every neighbor whose api block names the program
  • 💡 Selective targeting: Use neighbor keyword to target specific peer(s) instead of all neighbors
  • 💡 Wildcard: neighbor * explicitly targets the same neighbors as the default, and ignores any selector written after it
  • 💡 Multiple IPs: Separate the neighbors with a comma between spaces (neighbor 10.0.0.1 , neighbor 10.0.0.2) to target multiple specific neighbors
  • 💡 AND Logic: When combining selectors, all must match (e.g., neighbor 127.0.0.1 peer-as 65000 requires both IP and ASN to match)
  • 💡 No Match = Error: If no neighbor matches your selectors, ExaBGP answers error and logs no neighbor matching the command

For detailed examples and more selector options, see:


Text vs JSON Encoders

ExaBGP supports two encoding formats: Text and JSON.

⚠️ Important: Commands are ALWAYS text format

  • Commands you send to ExaBGP (STDOUT): Always text format (announce route ..., withdraw route ...)
  • Messages from ExaBGP (STDIN): Can be text or JSON based on encoder setting
  • The encoder setting controls ONLY what format ExaBGP uses when sending messages to your program
  • You CANNOT send JSON commands to ExaBGP - all commands must be text

Text Encoder

Use case: Sending commands + receiving simple text messages

Configuration:

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

Format: Human-readable text commands (bidirectional)

Example commands (your program → ExaBGP via STDOUT):

# Commands are ALWAYS text format, regardless of encoder setting
print("announce route 100.10.0.0/24 next-hop 192.0.2.1")
print("withdraw route 100.10.0.0/24")
print("announce flow route { match { destination 100.10.0.0/24; } then { discard; } }")

Pros:

  • ✅ Human-readable (both directions)
  • ✅ Easy to test manually
  • ✅ Simple for both sending and receiving

Cons:

  • ❌ Received messages harder to parse programmatically
  • ❌ Limited structured data from ExaBGP

JSON Encoder

Use case: Receiving BGP updates in structured format (routes, session state)

Configuration: The top-level process block starts the helper and selects its encoder. The neighbor's api block attaches that helper and selects the events it receives.

process my-program {
    run /etc/exabgp/api/receive.py;
    encoder json;
}

neighbor 192.168.1.1 {
    router-id 192.168.1.2;
    local-address 192.168.1.2;
    local-as 65001;
    peer-as 65000;

    api {
        processes [ my-program ];
        neighbor-changes;  # Receive session state changes
        receive {
            parsed;  # Receive parsed BGP messages
            update;  # Receive route updates
        }
    }
}

Format: JSON lines (one JSON object per line)

Example message:

{
  "exabgp": "6.0.0",
  "time": 1790846010.7200584,
  "host": "router1",
  "pid": 3075298,
  "ppid": 1,
  "counter": 5,
  "type": "update",
  "neighbor": {
    "address": {
      "local": "192.168.1.2",
      "peer": "192.168.1.1"
    },
    "asn": {
      "local": 65001,
      "peer": 65000
    },
    "router-id": "192.168.1.2",
    "direction": "receive",
    "message": {
      "update": {
        "attribute": {
          "origin": "igp",
          "as-path": {"0": {"element": "as-sequence", "value": [65000]}},
          "med": 100
        },
        "announce": {
          "ipv4 unicast": {
            "192.168.1.1": [
              { "nlri": "100.10.0.0/24" }
            ]
          }
        }
      }
    }
  }
}

ExaBGP writes each message on a single line; it is spread over several here to be read. The announced routes are grouped by family, then by next hop. A message received after the session is established also carries a negotiated object, described in the JSON API Reference.

Pros:

  • ✅ Structured data
  • ✅ Easy to parse (every language has JSON support)
  • ✅ Complete information

Cons:

  • ❌ Verbose
  • ❌ Harder to read manually

Which Encoder Should You Use?

Remember: The encoder setting ONLY affects messages FROM ExaBGP TO your program. Commands from your program to ExaBGP are always text.

Use encoder text when:

  • Only sending commands (announce/withdraw)
  • Want simple, human-readable messages from ExaBGP
  • Testing manually
  • Don't need structured parsing of received messages

Use encoder json when:

  • Receiving BGP updates from router
  • Need structured data parsing
  • Building complex integrations
  • Want easy programmatic parsing of ExaBGP messages

Can use both (common pattern):

# Process 1: Send commands (text)
process announce {
    run /etc/exabgp/api/announce.py;
    encoder text;
}

# Process 2: Receive updates (JSON)
process receive {
    run /etc/exabgp/api/receive.py;
    encoder json;
}

neighbor 192.168.1.1 {
    router-id 192.168.1.2;
    local-address 192.168.1.2;
    local-as 65001;
    peer-as 65000;

    api announce-api {
        processes [ announce ];
    }

    api receive-api {
        processes [ receive ];
        receive {
            parsed;
            update;
        }
    }
}

The separate named api blocks subscribe only the receive helper to incoming updates; the announce helper is attached without those subscriptions.


API Versioning (6.0.0+)

ExaBGP 6.0.0 introduces API versioning with support for v4 (legacy) and v6 (default) API formats.

API Versions

Version Description Used by
v6 JSON-only, peer * announce ... command format programs written for 6.0
v4 Legacy, text or JSON, announce ... command format programs written for 4.x and 5.x

6.0 detects the version of each program from its first command which tells, unless exabgp.api.version is set to 4 or 6, which holds every program to it. See How a program talks to ExaBGP.

Checking/Setting API Version

Use the system api version command to query or change the API version at runtime:

# Query current API version
print("system api version", flush=True)
# Response (JSON): {"api_version": "auto", "helper_api_version": "6"}
# the setting, and the version this program was detected as

# hold every program started afterwards to v4, to v6, or detect again
print("system api version 4", flush=True)
print("system api version 6", flush=True)
print("system api version auto", flush=True)

Command Format Differences

Action v4 Format v6 Format
Announce to all announce route ... peer * announce route ...
Announce to specific neighbor 1.2.3.4 announce ... peer 1.2.3.4 announce route ...
Withdraw withdraw route ... peer * withdraw route ...
Shutdown shutdown daemon shutdown
Enable ACK enable-ack session ack enable
Disable ACK disable-ack session ack disable
Show neighbors show neighbor peer show
Show RIB show adj-rib in rib show in

JSON Output Differences

Some BGP-LS JSON fields changed between 5.x and 6.0:

5.x 6.0 Context
ip-reachability-tlv holds the address ip-reachability-tlv holds the address and its length BGP-LS prefix
sr-adj sr-adjs BGP-LS adjacency SID (now array)
remote-te-router-id remote-router-ids BGP-LS remote router ID (now array)

sr_capability_flags had already become sr-capability-flags in 5.0.

Backward Compatibility

  • Bridge mode - Use exabgp migrate api --exec to run legacy scripts unchanged
  • Nothing to set - a program written for 5.x is detected and receives the v4 formats; system api version 4 holds every program to v4

Example: v6 Command Format

#!/usr/bin/env python3
"""ExaBGP 6.0.0 v6 API format example"""
import sys

# v6 format: target comes first
sys.stdout.write("peer * announce route 10.0.0.0/24 next-hop self\n")
sys.stdout.flush()

# Target specific peer
sys.stdout.write("peer 192.168.1.1 announce route 10.0.1.0/24 next-hop self\n")
sys.stdout.flush()

# Withdraw from all peers
sys.stdout.write("peer * withdraw route 10.0.0.0/24\n")
sys.stdout.flush()

API Architecture

Components

┌──────────────────────────────────────────────────────┐
│                   Your Program(s)                    │
│                                                      │
│  ┌──────────────┐  ┌──────────────┐  ┌────────────┐ │
│  │  announce.py │  │  receive.py  │  │ health.py  │ │
│  │  (text)      │  │  (json)      │  │ (text)     │ │
│  └──────┬───────┘  └──────┬───────┘  └──────┬─────┘ │
│         │ STDOUT          │ STDIN           │ STDOUT│
└─────────┼─────────────────┼─────────────────┼───────┘
          │                 │                 │
          ▼                 ▼                 ▼
┌──────────────────────────────────────────────────────┐
│                      ExaBGP                          │
│                                                      │
│  ┌─────────────┐   ┌──────────────┐   ┌──────────┐ │
│  │  Process    │   │   BGP State  │   │  Route   │ │
│  │  Manager    │   │   Machine    │   │  Manager │ │
│  └─────────────┘   └──────────────┘   └──────────┘ │
└──────────────────────────┬───────────────────────────┘
                           │ BGP Protocol
                           ▼
                     ┌──────────┐
                     │  Router  │
                     └──────────┘

Process Manager

  • Spawns your programs as subprocesses
  • Monitors process health (restarts if crashed)
  • Routes commands from STDOUT to BGP engine
  • Sends BGP messages to process STDIN

Command Flow

1. Your program: print("announce route 100.10.0.0/24 next-hop self")
2. Process writes to STDOUT
3. ExaBGP reads from process STDOUT
4. ExaBGP parses command
5. ExaBGP generates BGP UPDATE message
6. ExaBGP sends UPDATE to router via TCP 179
7. Router installs route in RIB/FIB

Update Flow

1. Router sends BGP UPDATE to ExaBGP
2. ExaBGP receives UPDATE
3. ExaBGP parses BGP message
4. ExaBGP converts to JSON (if encoder json)
5. ExaBGP writes JSON to process STDIN
6. Your program reads from STDIN
7. Your program processes the update

Basic Examples

The programs below read ExaBGP's answer after each command they write, as Reading the answers explains. ExaBGP 6.0 writes these commands with a peer * selector, see How a program talks to ExaBGP.

Example 1: Simple Route Announcement (Python)

#!/usr/bin/env python3
"""
announce.py - Announce static routes
"""
import sys
import time


def send(command):
    """Write one command, then read lines until ExaBGP answers it."""
    sys.stdout.write(command + '\n')
    sys.stdout.flush()  # CRITICAL: Must 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


# Wait for ExaBGP to be ready
time.sleep(2)

# Announce routes
routes = [
    "100.10.0.0/24",
    "100.20.0.0/24",
]

for route in routes:
    if not send(f"announce route {route} next-hop self"):
        sys.stderr.write(f"ExaBGP refused {route}\n")

# Keep process alive
while True:
    time.sleep(60)

Configuration:

process announce {
    run /etc/exabgp/api/announce.py;
    encoder text;
}

Example 2: Health Check

Announcing a route only while a service is healthy is what the health checker shipped with ExaBGP does, so no program needs to be written:

process healthcheck {
    run exabgp healthcheck --cmd "nc -z 100.10.0.100 80" --ip 100.10.0.100/32 --withdraw-on-down --no-ip-setup;
    encoder text;
}

The Healthcheck page describes every option of the checker, which here announces 100.10.0.100/32 once port 80 has answered three checks in a row and withdraws it after three failures.


Example 3: Receive BGP Updates (Python)

#!/usr/bin/env python3
"""
receive.py - Process incoming BGP updates
"""
import sys
import json

for line in sys.stdin:
    line = line.strip()
    if line in ('done', 'error') or line.startswith('error:'):
        continue  # the answer to a command, not a message

    try:
        msg = json.loads(line)

        # Route announcement
        if msg['type'] == 'update':
            if 'update' in msg['neighbor']['message']:
                update = msg['neighbor']['message']['update']

                # New routes announced: family -> next hop -> list of routes
                if 'announce' in update:
                    if 'ipv4 unicast' in update['announce']:
                        next_hops = update['announce']['ipv4 unicast']
                        for nexthop, routes in next_hops.items():
                            for route in routes:
                                if 'nlri' not in route:
                                    continue  # an End-of-RIB marker
                                print(f"[RECEIVED] {route['nlri']} via {nexthop}", file=sys.stderr)

                # Routes withdrawn: family -> list of routes
                if 'withdraw' in update:
                    if 'ipv4 unicast' in update['withdraw']:
                        for route in update['withdraw']['ipv4 unicast']:
                            print(f"[WITHDRAWN] {route['nlri']}", file=sys.stderr)

        # Session state change
        elif msg['type'] == 'state':
            state = msg['neighbor']['state']
            print(f"[STATE] BGP session: {state}", file=sys.stderr)

    except Exception as e:
        print(f"[ERROR] {e}", file=sys.stderr)

Configuration:

process receive {
    run /etc/exabgp/api/receive.py;
    encoder json;
}

neighbor 192.168.1.1 {
    router-id 192.168.1.2;
    local-address 192.168.1.2;
    local-as 65001;
    peer-as 65000;

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

Example 4: Bash Script

#!/bin/bash
# announce.sh - Announce routes from bash

send() {
    echo "$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
}

# Wait for ExaBGP
sleep 2

# Announce routes
send "announce route 100.10.0.0/24 next-hop self"
send "announce route 100.20.0.0/24 next-hop self"

# Keep running
while true; do
    sleep 60
done

Example 5: Go Program

package main

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

var answers = bufio.NewScanner(os.Stdin)

// send writes one command, then reads lines until ExaBGP answers it.
func send(command string) bool {
    fmt.Println(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 main() {
    // Wait for ExaBGP
    time.Sleep(2 * time.Second)

    // Announce routes
    routes := []string{
        "100.10.0.0/24",
        "100.20.0.0/24",
    }

    for _, route := range routes {
        if !send("announce route " + route + " next-hop self") {
            fmt.Fprintf(os.Stderr, "ExaBGP refused %s\n", route)
        }
    }

    // Keep alive
    for {
        time.Sleep(60 * time.Second)
    }
}

Process Lifecycle

1. Startup

  1. ExaBGP starts
  2. Reads configuration file
  3. Spawns process(es) defined in process blocks
  4. Connects to process STDIN/STDOUT
  5. Waits for BGP session to establish

Your program should:

  • Sleep 2-5 seconds to wait for BGP session
  • Send initial announcements
  • Enter main loop

2. Running

Your program:

  • Continuously runs (infinite loop or event-driven)
  • Writes commands to STDOUT when needed
  • Reads messages from STDIN if receiving updates
  • Flushes STDOUT after each write

ExaBGP:

  • Monitors process (checks if still running)
  • Routes commands to BGP engine
  • Sends BGP updates to process

3. Shutdown

Graceful shutdown (SIGTERM):

  1. ExaBGP receives SIGTERM
  2. ExaBGP sends SIGTERM to all processes
  3. Processes should exit cleanly
  4. ExaBGP closes BGP sessions (sends NOTIFICATION)
  5. ExaBGP exits

Process crash:

  1. Process exits/crashes
  2. ExaBGP detects (broken pipe or process exit)
  3. ExaBGP can restart process (if respawn enabled)

Configuration for auto-restart:

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

ExaBGP automatically respawns crashed processes.


Communication Flow

Sending Commands (STDOUT → ExaBGP)

# WRONG - Not flushed, nothing happens
print("announce route 100.10.0.0/24 next-hop self")

# CORRECT - Flushed, ExaBGP receives it
sys.stdout.write("announce route 100.10.0.0/24 next-hop self\n")
sys.stdout.flush()

# ALSO CORRECT - Print and flush
print("announce route 100.10.0.0/24 next-hop self")
sys.stdout.flush()

# ALSO CORRECT - Unbuffered mode
print("announce route 100.10.0.0/24 next-hop self", flush=True)

Critical: Always flush STDOUT, or use unbuffered mode:

python3 -u /etc/exabgp/api/announce.py

Receiving Messages (STDIN ← ExaBGP)

# Read lines forever
while True:
    line = sys.stdin.readline()
    if not line:
        break  # EOF
    process(line)

Message types (JSON):

  • type: "state" - BGP session state changes
  • type: "update" - Route announcements/withdrawals
  • type: "notification" - BGP errors
  • type: "keepalive" - Keepalive messages

Command Acknowledgment (ACK Feature)

ExaBGP answers each command a program writes with one line on the program's standard input: done when it accepted the command, or error when it did not. An error may 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 4.x, 5.x and 6.0, whatever the encoder of the process.

A program has to read these answers. In 5.x and 4.x, ExaBGP blocks once the 64 KiB pipe to the program is full, and stops doing anything else, its BGP sessions included, until the program reads. In 6.0 the unread answers accumulate in ExaBGP's memory without limit. Reading them also tells the program whether each command worked.

A program which has no use for the answers can turn them off by writing one of these commands:

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, and errors are silenced too
session ack enable enable-ack Sends answers again, starting with done for this command

Setting exabgp.api.ack=false turns the answers off for every program, and it is the only way to do so in 4.x. A shell export needs the underscore form, export exabgp_api_ack=false, while the dotted form only works as env exabgp.api.ack=false exabgp ....

Reading the answers shows how a program reads them, with templates in Python, shell and Go.


Error Handling

Command Errors (When ACK is Disabled)

ExaBGP logs errors but continues:

# Invalid command (when ACK is disabled)
print("announce route 100.10.0.0/24")  # Missing next-hop

ExaBGP writes the reason for the refusal to its log.

Your program won't know unless you monitor logs.


Command Errors (When ACK is Enabled - Default)

ExaBGP sends error response:

# Invalid command (with ACK enabled - the default), using send() from Example 1
if not send("announce route 100.10.0.0/24"):  # Missing next-hop
    sys.stderr.write("[ERROR] Command rejected by ExaBGP\n")

Your program knows immediately that the command failed.


Process Crashes

If your program crashes:

  1. ExaBGP detects (broken pipe)
  2. ExaBGP logs error
  3. ExaBGP restarts process automatically

Best practice:

try:
    main_loop()
except Exception as e:
    sys.stderr.write(f"[ERROR] {e}\n")
    sys.exit(1)

BGP Session Failures

If BGP session drops:

  • ExaBGP continues running
  • Your process continues running
  • Commands are queued until session re-establishes

Receive updates about session state:

if msg['type'] == 'state':
    if msg['neighbor']['state'] == 'down':
        # Session dropped - stop announcing?
        pass

Best Practices

1. Always Flush STDOUT

sys.stdout.flush()  # After every write

Or run the program unbuffered, from the process block:

run /usr/bin/python3 -u /etc/exabgp/api/announce.py;

2. Wait for BGP Session

time.sleep(2)  # Give ExaBGP time to establish session

3. Keep Process Alive

while True:
    time.sleep(60)  # Don't exit immediately

4. Use Structured Logging

import sys
import time

def log(message):
    sys.stderr.write(f"[{time.time()}] {message}\n")

log("Service UP - announced route")

ExaBGP does not read a program's STDERR: it goes wherever ExaBGP's own standard error goes, the terminal or the service manager's journal.

5. Handle Errors Gracefully

try:
    result = check_service()
except Exception as e:
    log(f"Health check error: {e}")
    # Assume down on error
    result = False

6. Use State Tracking

announced = False

if should_announce and not announced:
    announce()
    announced = True
elif not should_announce and announced:
    withdraw()
    announced = False

Avoids redundant announcements.

7. Validate Commands

import ipaddress

def announce_route(prefix, nexthop="self"):
    try:
        ipaddress.ip_network(prefix)
    except ValueError:
        log(f"Invalid prefix: {prefix}")
        return False
    return send(f"announce route {prefix} next-hop {nexthop}")

Next Steps

Detailed References

Examples

Configuration


Ready to dive deeper? Continue to Text API Reference →


Clone this wiki locally