HALF ECHO LEARN / REFERENCE COLLECTION
v262.2test/test-network/systemd-networkd-tests.py
Git blob: aaf8830b28df24259c9ca79d57929ab5449e46af
Lines 1–1000 of 11,559
#!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1-or-later
# systemd-networkd tests
# These tests can be executed in the systemd mkosi image when booted in QEMU. After booting the QEMU VM,
# simply run this file which can be found in the VM at
# /usr/lib/systemd/tests/testdata/test-network/systemd-networkd-tests.py.
#
# To run an individual test, specify it as a command line argument in the form
# of <class>.<test_function>. E.g. the NetworkdMTUTests class has a test
# function called test_ipv6_mtu(). To run just that test use:
#
# run0 ./systemd-networkd-tests.py NetworkdMTUTests.test_ipv6_mtu
#
# Similarly, other individual tests can be run, e.g.:
#
# run0 ./systemd-networkd-tests.py NetworkdNetworkTests.test_ipv6_neigh_retrans_time
#
# To run the test with the executables (systemd-networkd, networkctl, systemd-udevd and so on)
# in your build directory, --build-dir=/path/to/build/ option can be used:
#
# run0 ./systemd-networkd-tests.py --build-dir=/path/to/build NetworkdNetworkTests.test_address_static
#
# Note, unlike the long getopt option handling, the path must be specified after '=', rather than space.
# Otherwise the path is recognized as a test case, and the test run will fail.
import argparse
import datetime
import enum
import errno
import ipaddress
import itertools
import json
import os
import pathlib
import random
import re
import shutil
import signal
import socket
import struct
import subprocess
import sys
import tempfile
import time
import unittest
import psutil
network_unit_dir = '/run/systemd/network'
networkd_conf_dropin_dir = '/run/systemd/networkd.conf.d'
networkd_ci_temp_dir = '/run/networkd-ci'
udev_rules_dir = '/run/udev/rules.d'
credstore_dir = '/run/credstore'
dnsmasq_pid_file = '/run/networkd-ci/test-dnsmasq.pid'
dnsmasq_log_file = '/run/networkd-ci/test-dnsmasq.log'
dnsmasq_lease_file = '/run/networkd-ci/test-dnsmasq.lease'
isc_dhcpd_pid_file = '/run/networkd-ci/test-isc-dhcpd.pid'
isc_dhcpd_lease_file = '/run/networkd-ci/test-isc-dhcpd.lease'
radvd_pid_file = '/run/networkd-ci/test-radvd.pid'
systemd_lib_paths = ['/usr/lib/systemd', '/lib/systemd']
which_paths = ':'.join(systemd_lib_paths + os.getenv('PATH', os.defpath).lstrip(':').split(':'))
networkd_bin = shutil.which('systemd-networkd', path=which_paths)
resolved_bin = shutil.which('systemd-resolved', path=which_paths)
timesyncd_bin = shutil.which('systemd-timesyncd', path=which_paths)
wait_online_bin = shutil.which('systemd-networkd-wait-online', path=which_paths)
networkctl_bin = shutil.which('networkctl', path=which_paths)
resolvectl_bin = shutil.which('resolvectl', path=which_paths)
timedatectl_bin = shutil.which('timedatectl', path=which_paths)
udevadm_bin = shutil.which('udevadm', path=which_paths)
test_ndisc_send = None
test_modem_manager_mock = None
build_dir = None
source_dir = None
use_valgrind = False
valgrind_cmd = ''
enable_debug = True
env = {}
wait_online_env = {}
asan_options = os.getenv('ASAN_OPTIONS')
lsan_options = os.getenv('LSAN_OPTIONS')
ubsan_options = os.getenv('UBSAN_OPTIONS')
with_coverage = os.getenv('COVERAGE_BUILD_DIR') is not None
show_journal = True # When true, show journal on stopping networkd.
active_units = []
protected_links = {
'erspan0',
'gre0',
'gretap0',
'ifb0',
'ifb1',
'ip6_vti0',
'ip6gre0',
'ip6tnl0',
'ip_vti0',
'lo',
'sit0',
'tunl0',
}
saved_routes = None
saved_ipv4_rules = None
saved_ipv6_rules = None
saved_timezone = None
def rm_f(path):
if os.path.exists(path):
os.remove(path)
def rm_rf(path):
shutil.rmtree(path, ignore_errors=True)
def cp(src, dst):
shutil.copy(src, dst)
def cp_r(src, dst):
shutil.copytree(src, dst, copy_function=shutil.copy, dirs_exist_ok=True)
def mkdir_p(path):
os.makedirs(path, exist_ok=True)
def touch(path):
pathlib.Path(path).touch()
# pylint: disable=R1710
def check_output(*command, **kwargs):
# This checks the result and returns stdout (and stderr) on success.
command = command[0].split() + list(command[1:])
ret = subprocess.run(
command,
check=False,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
**kwargs,
)
if ret.returncode == 0:
return ret.stdout.rstrip()
# When returncode != 0, print stdout and stderr, then trigger CalledProcessError.
print(ret.stdout)
ret.check_returncode()
def call(*command, **kwargs):
# This returns returncode. stdout and stderr are merged and shown in console
command = command[0].split() + list(command[1:])
return subprocess.run(
command,
check=False,
text=True,
stderr=subprocess.STDOUT,
**kwargs,
).returncode
def call_check(*command, **kwargs):
# Same as call() above, but it triggers CalledProcessError if rc != 0
command = command[0].split() + list(command[1:])
return subprocess.run(
command,
check=False,
text=True,
stderr=subprocess.STDOUT,
**kwargs,
).check_returncode()
def call_quiet(*command, **kwargs):
command = command[0].split() + list(command[1:])
return subprocess.run(
command,
check=False,
text=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
**kwargs,
).returncode
def run(*command, **kwargs):
# This returns CompletedProcess instance.
command = command[0].split() + list(command[1:])
return subprocess.run(
command,
check=False,
text=True,
capture_output=True,
**kwargs,
)
def check_json(string):
try:
json.loads(string)
except json.JSONDecodeError:
print(f"String is not a valid JSON: '{string}'")
raise
def is_module_available(*module_names):
for module_name in module_names:
lsmod_output = check_output('lsmod')
module_re = re.compile(rf'^{re.escape(module_name)}\b', re.MULTILINE)
if not module_re.search(lsmod_output) and call_quiet('modprobe', module_name) != 0:
return False
return True
def expectedFailureIfModuleIsNotAvailable(*module_names):
def f(func):
return func if is_module_available(*module_names) else unittest.expectedFailure(func)
return f
# pylint: disable=C0415
def compare_kernel_version(min_kernel_version):
try:
import platform
from packaging import version
except ImportError:
print('Failed to import either platform or packaging module, assuming the comparison failed')
return False
# Get only the actual kernel version without any build/distro/arch stuff
# e.g. '5.18.5-200.fc36.x86_64' -> '5.18.5'
kver = platform.release().split('-')[0]
# Get also rid of '+'
kver = kver.split('+')[0]
return version.parse(kver) >= version.parse(min_kernel_version)
def networkd_has_sysctl_monitor_bpf():
"""Check whether systemd-networkd was built with ENABLE_SYSCTL_BPF support."""
if not networkd_bin:
return False
try:
output = subprocess.run(
[networkd_bin, '--version'],
capture_output=True,
text=True,
check=False,
).stdout
except (OSError, subprocess.SubprocessError):
return False
return '+BTF' in output.split()
def copy_network_unit(*units, copy_dropins=True):
"""
Copy networkd unit files into the testbed.
Any networkd unit file type can be specified, as well as drop-in files.
By default, all drop-ins for a specified unit file are copied in;
to avoid that specify dropins=False.
When a drop-in file is specified, its unit file is also copied in automatically.
"""
has_link = False
mkdir_p(network_unit_dir)
for unit in units:
if copy_dropins and os.path.exists(os.path.join(networkd_ci_temp_dir, unit + '.d')):
cp_r(
os.path.join(networkd_ci_temp_dir, unit + '.d'),
os.path.join(network_unit_dir, unit + '.d'),
)
if unit.endswith('.conf'):
dropin = unit
unit = os.path.dirname(dropin).rstrip('.d')
dropindir = os.path.join(network_unit_dir, unit + '.d')
mkdir_p(dropindir)
cp(os.path.join(networkd_ci_temp_dir, dropin), dropindir)
cp(os.path.join(networkd_ci_temp_dir, unit), network_unit_dir)
if unit.endswith('.link'):
has_link = True
if has_link:
udevadm_reload()
def copy_credential(src, target):
mkdir_p(credstore_dir)
cp(os.path.join(networkd_ci_temp_dir, src), os.path.join(credstore_dir, target))
def remove_network_unit(*units):
"""
Remove previously copied unit files from the testbed.
Drop-ins will be removed automatically.
"""
has_link = False
for unit in units:
rm_f(os.path.join(network_unit_dir, unit))
rm_rf(os.path.join(network_unit_dir, unit + '.d'))
if unit.endswith('.link') or unit.endswith('.link.d'):
has_link = True
if has_link:
udevadm_reload()
def touch_network_unit(*units):
for unit in units:
touch(os.path.join(network_unit_dir, unit))
def clear_network_units():
has_link = False
if os.path.exists(network_unit_dir):
units = os.listdir(network_unit_dir)
for unit in units:
if unit.endswith('.link') or unit.endswith('.link.d'):
has_link = True
rm_rf(network_unit_dir)
if has_link:
udevadm_reload()
def copy_networkd_conf_dropin(*dropins):
"""Copy networkd.conf dropin files into the testbed."""
mkdir_p(networkd_conf_dropin_dir)
for dropin in dropins:
cp(os.path.join(networkd_ci_temp_dir, dropin), networkd_conf_dropin_dir)
def remove_networkd_conf_dropin(*dropins):
"""Remove previously copied networkd.conf dropin files from the testbed."""
for dropin in dropins:
rm_f(os.path.join(networkd_conf_dropin_dir, dropin))
def clear_networkd_conf_dropins():
rm_rf(networkd_conf_dropin_dir)
def setup_systemd_udev_rules():
if not build_dir and not source_dir:
return
mkdir_p(udev_rules_dir)
for path in [build_dir, source_dir]:
if not path:
continue
path = os.path.join(path, 'rules.d')
print(f'Copying udev rules from {path} to {udev_rules_dir}')
for rule in os.listdir(path):
if not rule.endswith('.rules'):
continue
cp(os.path.join(path, rule), udev_rules_dir)
def clear_networkd_state_files():
rm_rf('/var/lib/systemd/network/')
def copy_udev_rule(*rules):
"""Copy udev rules"""
mkdir_p(udev_rules_dir)
for rule in rules:
cp(os.path.join(networkd_ci_temp_dir, rule), udev_rules_dir)
def remove_udev_rule(*rules):
"""Remove previously copied udev rules"""
for rule in rules:
rm_f(os.path.join(udev_rules_dir, rule))
def clear_udev_rules():
rm_rf(udev_rules_dir)
def save_active_units():
for u in [
'systemd-networkd.socket',
'systemd-networkd-resolve-hook.socket',
'systemd-networkd-varlink.socket',
'systemd-networkd-varlink-metrics.socket',
'systemd-networkd.service',
'systemd-resolved-monitor.socket',
'systemd-resolved-varlink.socket',
'systemd-resolved.service',
'systemd-timesyncd.service',
'firewalld.service',
'nftables.service',
]:
if call(f'systemctl is-active --quiet {u}') == 0:
call(f'systemctl stop {u}')
active_units.append(u)
def restore_active_units():
has_network_socket = False
has_resolve_socket = False
if 'systemd-networkd.socket' in active_units:
call('systemctl stop systemd-networkd.socket')
has_network_socket = True
if 'systemd-networkd-resolve-hook.socket' in active_units:
call('systemctl stop systemd-networkd-resolve-hook.socket')
has_network_socket = True
if 'systemd-networkd-varlink.socket' in active_units:
call('systemctl stop systemd-networkd-varlink.socket')
has_network_socket = True
if 'systemd-networkd-varlink-metrics.socket' in active_units:
call('systemctl stop systemd-networkd-varlink-metrics.socket')
has_network_socket = True
if 'systemd-resolved-monitor.socket' in active_units:
call('systemctl stop systemd-resolved-monitor.socket')
has_resolve_socket = True
if 'systemd-resolved-varlink.socket' in active_units:
call('systemctl stop systemd-resolved-varlink.socket')
has_resolve_socket = True
if has_network_socket:
call('systemctl stop systemd-networkd.service')
if has_resolve_socket:
call('systemctl stop systemd-resolved.service')
for u in active_units:
call(f'systemctl restart {u}')
def create_unit_dropin(unit, contents):
mkdir_p(f'/run/systemd/system/{unit}.d')
with open(f'/run/systemd/system/{unit}.d/00-override.conf', mode='w', encoding='utf-8') as f:
f.write('\n'.join(contents))
def create_service_dropin(service, command, additional_settings=None):
drop_in = ['[Service]']
if command:
drop_in += [
'ExecStart=',
f'ExecStart={valgrind_cmd}{command}',
]
if enable_debug:
drop_in += ['Environment=SYSTEMD_LOG_LEVEL=debug']
if asan_options:
drop_in += [f'Environment=ASAN_OPTIONS="{asan_options}"']
if lsan_options:
drop_in += [f'Environment=LSAN_OPTIONS="{lsan_options}"']
if ubsan_options:
drop_in += [f'Environment=UBSAN_OPTIONS="{ubsan_options}"']
if asan_options or lsan_options or ubsan_options:
drop_in += [
'SystemCallFilter=',
'TimeoutStopFailureMode=abort',
]
if use_valgrind or asan_options or lsan_options or ubsan_options:
drop_in += ['MemoryDenyWriteExecute=no']
if use_valgrind:
drop_in += [
'Environment=SYSTEMD_MEMPOOL=0',
'PrivateTmp=yes',
]
if with_coverage:
drop_in += [
'ProtectSystem=no',
'ProtectHome=no',
]
if additional_settings:
drop_in += additional_settings
create_unit_dropin(f'{service}.service', drop_in)
def setup_system_units():
if build_dir or source_dir:
mkdir_p('/run/systemd/system/')
for unit in [
'systemd-networkd.service',
'systemd-networkd.socket',
'systemd-networkd-persistent-storage.service',
'systemd-networkd-resolve-hook.socket',
'systemd-networkd-varlink.socket',
'systemd-networkd-varlink-metrics.socket',
'systemd-resolved.service',
'systemd-timesyncd.service',
'systemd-udevd.service',
]:
for path in [build_dir, source_dir]:
if not path:
continue
fullpath = os.path.join(os.path.join(path, 'units'), unit)
if os.path.exists(fullpath):
print(f'Copying unit file from {fullpath} to /run/systemd/system/')
cp(fullpath, '/run/systemd/system/')
break
create_service_dropin(
'systemd-networkd',
networkd_bin,
[
'[Service]',
'Restart=no',
'Environment=SYSTEMD_NETWORK_TEST_MODE=yes',
'[Unit]',
'StartLimitIntervalSec=0',
],
)
create_service_dropin('systemd-resolved', resolved_bin)
create_service_dropin('systemd-timesyncd', timesyncd_bin)
# TODO: also run udevd with sanitizers, valgrind, or coverage
create_unit_dropin(
'systemd-networkd.socket',
[
'[Unit]',
'StartLimitIntervalSec=0',
],
)
create_unit_dropin(
'systemd-networkd-persistent-storage.service',
[
'[Unit]',
'StartLimitIntervalSec=0',
'[Service]',
'ExecStart=',
f'ExecStart={networkctl_bin} persistent-storage yes',
'ExecStop=',
f'ExecStop={networkctl_bin} persistent-storage no',
'Environment=SYSTEMD_LOG_LEVEL=debug' if enable_debug else '',
],
)
create_unit_dropin(
'systemd-networkd-resolve-hook.socket',
[
'[Unit]',
'StartLimitIntervalSec=0',
],
)
create_unit_dropin(
'systemd-networkd-varlink.socket',
[
'[Unit]',
'StartLimitIntervalSec=0',
],
)
create_unit_dropin(
'systemd-networkd-varlink-metrics.socket',
[
'[Unit]',
'StartLimitIntervalSec=0',
],
)
create_unit_dropin(
'systemd-udevd.service',
[
'[Service]',
'ExecStart=',
f'ExecStart=@{udevadm_bin} systemd-udevd',
],
)
check_output('systemctl daemon-reload')
print(check_output('systemctl cat systemd-networkd.service'))
print(check_output('systemctl cat systemd-networkd-persistent-storage.service'))
print(check_output('systemctl cat systemd-resolved.service'))
print(check_output('systemctl cat systemd-timesyncd.service'))
print(check_output('systemctl cat systemd-udevd.service'))
check_output('systemctl restart systemd-resolved.service')
check_output('systemctl restart systemd-timesyncd.service')
check_output('systemctl restart systemd-udevd.service')
def clear_system_units():
def rm_unit(name):
rm_f(f'/run/systemd/system/{name}')
rm_rf(f'/run/systemd/system/{name}.d')
rm_unit('systemd-networkd.service')
rm_unit('systemd-networkd.socket')
rm_unit('systemd-networkd-persistent-storage.service')
rm_unit('systemd-networkd-resolve-hook.socket')
rm_unit('systemd-networkd-varlink.socket')
rm_unit('systemd-networkd-varlink-metrics.socket')
rm_unit('systemd-resolved.service')
rm_unit('systemd-timesyncd.service')
rm_unit('systemd-udevd.service')
check_output('systemctl daemon-reload')
check_output('systemctl restart systemd-udevd.service')
def link_exists(*links):
for link in links:
if call_quiet(f'ip link show {link}') != 0:
return False
return True
def link_resolve(link):
return check_output(f'ip link show {link}').split(':')[1].strip().split('@')[0]
def remove_link(*links, protect=False):
for link in links:
if protect and link in protected_links:
continue
if link_exists(link):
call(f'ip link del dev {link}')
def save_existing_links():
links = os.listdir('/sys/class/net')
for link in links:
if link_exists(link):
protected_links.add(link)
print('### The following links will be protected:')
print(', '.join(sorted(list(protected_links))))
def unmanage_existing_links():
mkdir_p(network_unit_dir)
with open(os.path.join(network_unit_dir, '00-unmanaged.network'), mode='w', encoding='utf-8') as f:
f.write('[Match]\n')
for link in protected_links:
f.write(f'Name={link}\n')
f.write('\n[Link]\nUnmanaged=yes\n')
def flush_links():
links = os.listdir('/sys/class/net')
remove_link(*links, protect=True)
def flush_nexthops():
# Currently, the 'ip nexthop' command does not have 'save' and 'restore'.
# Hence, we cannot restore nexthops in a simple way.
# Let's assume there is no nexthop used in the system
call_quiet('ip nexthop flush')
def save_routes():
# pylint: disable=global-statement
global saved_routes
saved_routes = check_output('ip route show table all')
print('### The following routes will be protected:')
print(saved_routes)
def flush_routes():
have = False
output = check_output('ip route show table all')
for line in output.splitlines():
if line in saved_routes:
continue
if 'proto kernel' in line:
continue
if ' dev ' in line and ' dev lo ' not in line:
continue
if not have:
have = True
print('### Removing routes that did not exist when the test started.')
print(f'# {line}')
call(f'ip route del {line}')
def save_routing_policy_rules():
# pylint: disable=global-statement
global saved_ipv4_rules, saved_ipv6_rules
def save(ipv):
output = check_output(f'ip -{ipv} rule show')
print(f'### The following IPv{ipv} routing policy rules will be protected:')
print(output)
return output
saved_ipv4_rules = save(4)
saved_ipv6_rules = save(6)
def flush_routing_policy_rules():
def flush(ipv, saved_rules):
have = False
output = check_output(f'ip -{ipv} rule show')
for line in output.splitlines():
if line in saved_rules:
continue
if not have:
have = True
print(f'### Removing IPv{ipv} routing policy rules that did not exist when the test started.') # fmt: skip
print(f'# {line}')
words = line.replace('lookup [l3mdev-table]', 'l3mdev').replace('[detached]', '').split()
priority = words[0].rstrip(':')
call(f'ip -{ipv} rule del priority {priority} ' + ' '.join(words[1:]))
flush(4, saved_ipv4_rules)
flush(6, saved_ipv6_rules)
def flush_fou_ports():
ret = run('ip fou show')
if ret.returncode != 0:
return # fou may not be supported
for line in ret.stdout.splitlines():
port = line.split()[1]
call(f'ip fou del port {port}')
def flush_l2tp_tunnels():
tids = []
ret = run('ip l2tp show tunnel')
if ret.returncode != 0:
return # l2tp may not be supported
for line in ret.stdout.splitlines():
words = line.split()
if words[0] == 'Tunnel':
tid = words[1].rstrip(',')
call(f'ip l2tp del tunnel tunnel_id {tid}')
tids.append(tid)
# Removing L2TP tunnel is asynchronous and slightly takes a time.
for tid in tids:
for _ in range(50):
r = run(f'ip l2tp show tunnel tunnel_id {tid}')
if r.returncode != 0 or len(r.stdout.rstrip()) == 0:
break
time.sleep(0.2)
else:
print(f'Cannot remove L2TP tunnel {tid}, ignoring.')
def save_timezone():
# pylint: disable=global-statement
global saved_timezone
r = run(*timedatectl_cmd, 'show', '--value', '--property', 'Timezone', env=env)
if r.returncode == 0:
saved_timezone = r.stdout.rstrip()
print(f'### Saved timezone: {saved_timezone}')
def restore_timezone():
if saved_timezone:
call(*timedatectl_cmd, 'set-timezone', f'{saved_timezone}', env=env)
def read_link_attr(*args):
with open(os.path.join('/sys/class/net', *args), encoding='utf-8') as f:
return f.readline().strip()
def read_manager_state_file():
with open('/run/systemd/netif/state', encoding='utf-8') as f:
return f.read()
def read_link_state_file(link):
ifindex = read_link_attr(link, 'ifindex')
path = os.path.join('/run/systemd/netif/links', ifindex)
with open(path, encoding='utf-8') as f:
return f.read()
def read_ip_sysctl_attr(link, attribute, ipv):
with open(os.path.join('/proc/sys/net', ipv, 'conf', link, attribute), encoding='utf-8') as f:
return f.readline().strip()
def read_ip_neigh_sysctl_attr(link, attribute, ipv):
with open(os.path.join('/proc/sys/net', ipv, 'neigh', link, attribute), encoding='utf-8') as f:
return f.readline().strip()
def read_ipv6_sysctl_attr(link, attribute):
return read_ip_sysctl_attr(link, attribute, 'ipv6')
def read_ipv6_neigh_sysctl_attr(link, attribute):
return read_ip_neigh_sysctl_attr(link, attribute, 'ipv6')
def read_ipv4_sysctl_attr(link, attribute):
return read_ip_sysctl_attr(link, attribute, 'ipv4')
def read_mpls_sysctl_attr(link, attribute):
return read_ip_sysctl_attr(link, attribute, 'mpls')
def stop_by_pid_file(pid_file):
if not os.path.exists(pid_file):
return
with open(pid_file, encoding='utf-8') as f:
pid = f.read().rstrip(' \t\r\n\0')
os.kill(int(pid), signal.SIGTERM)
for _ in range(25):
try:
os.kill(int(pid), 0)
print(f'PID {pid} is still alive, waiting...')
time.sleep(0.2)
except OSError as e:
if e.errno == errno.ESRCH:
break
print(f'Unexpected exception when waiting for {pid} to die: {e.errno}')
rm_f(pid_file)
def pack(c, width=1):
# big-endian unsigned char/short/integer
fmt = {1: '>B', 2: '>H', 4: '>I'}
return struct.pack(fmt[width], len(c)) + c
def pyton(n, width=2):
fmt = {1: '>B', 2: '>H', 4: '>I'}
return struct.pack(fmt[width], n)
class SvcParam(enum.Enum):
ALPN = 1
DOHPATH = 7
def dnr_v4_instance_data(adn, addrs=None, prio=1, alpns=('dot',), dohpath=None):
ipv4 = ipaddress.IPv4Address
data = pyton(prio)
adn = adn.rstrip('.') + '.'
data += pack(b''.join(pack(label.encode('ascii')) for label in adn.split('.')))
if not addrs: # adn-only mode
return pack(data, 2)
data += pack(b''.join(ipv4(addr).packed for addr in addrs))
data += pyton(SvcParam.ALPN.value) + pack(b''.join(pack(alpn.encode('ascii')) for alpn in alpns), 2)
if dohpath is not None:
data += pyton(SvcParam.DOHPATH.value) + pack(dohpath.encode('utf-8'), 2)
return pack(data, 2)
def dnr_v6_instance_data(adn, addrs=None, prio=1, alpns=('dot',), dohpath=None):
ipv6 = ipaddress.IPv6Address
data = pyton(prio)
adn = adn.rstrip('.') + '.'
data += pack(b''.join(pack(label.encode('ascii')) for label in adn.split('.')), 2)
if not addrs: # adn-only mode
return data
data += pack(b''.join(ipv6(addr).packed for addr in addrs), 2)
data += pyton(SvcParam.ALPN.value) + pack(b''.join(pack(alpn.encode('ascii')) for alpn in alpns), 2)
if dohpath is not None:
data += pyton(SvcParam.DOHPATH.value) + pack(dohpath.encode('utf-8'), 2)
return data
def start_dnsmasq(
*additional_options,
namespace=None,
interface='veth-peer',
ra_mode=None,
ipv4_range='192.168.5.10,192.168.5.200',
ipv4_router='192.168.5.1',
ipv6_range='2600::10,2600::20',
):
if ra_mode:
ra_mode = f',{ra_mode}'
else:
ra_mode = ''
if namespace:
ns_command = ('ip', 'netns', 'exec', namespace)
else:
ns_command = ()
command = (
ns_command
+ (
'dnsmasq',
f'--log-facility={dnsmasq_log_file}',
'--log-queries=extra',
'--log-dhcp',
f'--pid-file={dnsmasq_pid_file}',
'--conf-file=/dev/null',
'--bind-interfaces',
f'--interface={interface}',
f'--dhcp-leasefile={dnsmasq_lease_file}',
'--enable-ra',
f'--dhcp-range={ipv6_range}{ra_mode},2m',
f'--dhcp-range={ipv4_range},2m',
'--dhcp-option=option:mtu,1492',
f'--dhcp-option=option:router,{ipv4_router}',
'--port=0',
'--no-resolv',
)
+ additional_options
)
check_output(*command)
def stop_dnsmasq():
stop_by_pid_file(dnsmasq_pid_file)
rm_f(dnsmasq_lease_file)
rm_f(dnsmasq_log_file)
def read_dnsmasq_log_file():
with open(dnsmasq_log_file, encoding='utf-8') as f:
return f.read()
def start_isc_dhcpd(conf_file, ipv, interface='veth-peer'):
conf_file_path = os.path.join(networkd_ci_temp_dir, conf_file)
isc_dhcpd_command = f'dhcpd {ipv} -cf {conf_file_path} -lf {isc_dhcpd_lease_file} -pf {isc_dhcpd_pid_file} {interface}' # fmt: skip
touch(isc_dhcpd_lease_file)
check_output(isc_dhcpd_command)
def stop_isc_dhcpd():
stop_by_pid_file(isc_dhcpd_pid_file)
rm_f(isc_dhcpd_lease_file)
def get_dbus_link_path(link):
out = subprocess.check_output(
[
'busctl',
'call',
'org.freedesktop.network1',
'/org/freedesktop/network1',
'org.freedesktop.network1.Manager',
'GetLinkByName',
's',
link,
]
)
assert out.startswith(b'io ')
out = out.strip()
assert out.endswith(b'"')
out = out.decode()
return out[:-1].split('"')[1]
def get_dhcp_server_property(link, prop):
link_path = get_dbus_link_path(link)
out = subprocess.check_output(
[
'busctl',
'get-property',
'org.freedesktop.network1',
link_path,
'org.freedesktop.network1.DHCPServer',
prop,
]
)
return out.strip().decode()
def get_dhcp_client_state(link, family):
link_path = get_dbus_link_path(link)
out = subprocess.check_output(
[
'busctl',
'get-property',
'org.freedesktop.network1',