Files
mikrotik-olsr/container/start.py
T
feedc0de 22cf76deaf
Check source / check (push) Successful in 16s
Build OLSR container / image (push) Failing after 8m35s
Build NPK and multiarch container releases with native next-hop groundwork
2026-11-19 08:44:02 +01:00

123 lines
4.7 KiB
Python

"""OLSR/BIRD supervisor for stock RouterOS containers; configuration via env."""
import ipaddress
import json
import os
from pathlib import Path
import re
import signal
import subprocess
import sys
import time
def links(env):
"""Stable link IDs are mapped to RouterOS interfaces by import filters."""
data = json.loads(env['OLSR_LINKS']) if env.get('OLSR_LINKS') else [
{'interface': env.get('OLSR_INTERFACE', 'veth-olsr'),
'address': env['OLSR_NODE_IP'], 'id': 1}]
if not isinstance(data, list) or not data:
raise ValueError('OLSR_LINKS must be a nonempty JSON list')
seen_names, seen_ids, seen_addresses = set(), set(), set()
for link in data:
name = link['interface']
if not re.fullmatch(r'[A-Za-z0-9_.:-]{1,15}', name):
raise ValueError('Invalid OLSR interface name')
address = str(ipaddress.IPv4Address(link['address']))
ident = link['id']
if type(ident) is not int or not 1 <= ident <= 65535:
raise ValueError('Link ID must be an integer from 1 to 65535')
if name in seen_names or ident in seen_ids or address in seen_addresses:
raise ValueError('Link interfaces, IDs and addresses must be unique')
seen_names.add(name)
seen_ids.add(ident)
seen_addresses.add(address)
link['address'] = address
return data
def configuration(env):
mesh_links = links(env)
node = str(ipaddress.IPv4Address(env['OLSR_NODE_IP']))
local = str(ipaddress.IPv4Address(env['BGP_LOCAL_IP']))
peer = str(ipaddress.IPv4Address(env['BGP_PEER_IP']))
if len({local, peer, node}) != 3 or any(link['address'] in (local, peer) for link in mesh_links):
raise ValueError('Container and RouterOS addresses must be distinct')
debug = int(env.get('OLSR_DEBUG', '0'))
if debug not in (0, 1):
raise ValueError('OLSR_DEBUG must be 0 or 1')
config = f'''DebugLevel {debug}
IpVersion 4
AllowNoInt no
MainIp {node}
RtTable 201
RtTableDefault 202
RtTableTunnel 203
RtProto 100
UseHysteresis no
LinkQualityLevel 2
LinkQualityAlgorithm "etx_ff"
LinkQualityFishEye 0
'''
for link in mesh_links:
config += (f'Interface "{link["interface"]}" {{ Mode "mesh" '
f'IPv4Src {link["address"]} IPv4Broadcast 255.255.255.255 }}\n')
# HNA requires a verified return path through RouterOS before enabling it.
if env.get('OLSR_HNA'):
raise ValueError('HNA is not yet supported by this experimental container')
bird = Path(__file__).with_name('bird.conf.template').read_text()
bird = bird.replace('@MAINIP@', node).replace('@LOCALIP@', local).replace('@PEERIP@', peer)
link_filter = '\n'.join(
f' if ifname = "{link["interface"]}" then bgp_community.add((64514, {link["id"]}));'
for link in mesh_links)
# Reject routes whose kernel interface is not one of our mesh links.
allowed = ' || '.join(f'ifname = "{link["interface"]}"' for link in mesh_links)
bird = bird.replace('@LINK_FILTER@', f' if !({allowed}) then reject;\n' + link_filter)
return config, bird
def main():
config, bird = configuration(os.environ)
Path('/run/olsrd.conf').write_text(config)
Path('/run/bird.conf').write_text(bird)
subprocess.run(['bird', '-p', '-c', '/run/bird.conf'], check=True)
if '--check' in sys.argv:
return
# olsrd enables the kernel forwarding sysctl itself. A fail-closed FORWARD
# policy prevents transit regardless of that sysctl. No NAT or policy route
# into OLSR's private table: RouterOS owns packet forwarding.
subprocess.run(['iptables', '-P', 'FORWARD', 'DROP'], check=True)
stopping = False
def stop(*_):
nonlocal stopping
stopping = True
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
children = []
failed = False
try:
children.append(subprocess.Popen(['olsrd', '-f', '/run/olsrd.conf', '-nofork']))
children.append(subprocess.Popen(['bird', '-f', '-c', '/run/bird.conf', '-s', '/run/bird.ctl']))
while not stopping:
if any(child.poll() is not None for child in children):
failed = True
break
time.sleep(0.2)
finally:
# BIRD first: withdraw routes even if olsrd exits unexpectedly.
for child in reversed(children):
if child.poll() is None:
child.terminate()
try:
child.wait(timeout=3)
except subprocess.TimeoutExpired:
child.kill()
child.wait()
if failed:
raise SystemExit('Routing daemon exited; stopped both daemons')
if __name__ == '__main__':
main()