HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

test/test-network/systemd-networkd-tests.py

468,283 bytesGit mode 100755Download original fileLGPL-2.1-or-later

Git blob: aaf8830b28df24259c9ca79d57929ab5449e46af

Lines 1001–2000 of 11,559

            link_path,
            f'org.freedesktop.network1.DHCPv{family}Client',
            'State',
        ]
    )
    assert out.startswith(b's "')
    out = out.strip()
    assert out.endswith(b'"')
    return out[3:-1].decode()
 
 
def get_dhcp4_client_state(link):
    return get_dhcp_client_state(link, '4')
 
 
def get_dhcp6_client_state(link):
    return get_dhcp_client_state(link, '6')
 
 
def get_link_description(link):
    link_path = get_dbus_link_path(link)
 
    out = subprocess.check_output(
        [
            'busctl',
            'call',
            'org.freedesktop.network1',
            link_path,
            'org.freedesktop.network1.Link',
            'Describe',
        ]
    )
    assert out.startswith(b's "')
    out = out.strip()
    assert out.endswith(b'"')
    json_raw = out[2:].decode()
    check_json(json_raw)
    description = json.loads(json_raw)  # Convert from escaped sequences to json
    check_json(description)
    return json.loads(description)  # Now parse the json
 
 
def start_radvd(*additional_options, config_file):
    config_file_path = os.path.join(networkd_ci_temp_dir, 'radvd', config_file)
    command = (
        'radvd',
        f'--pidfile={radvd_pid_file}',
        f'--config={config_file_path}',
        '--logmethod=stderr',
    ) + additional_options
    check_output(*command)
 
 
def stop_radvd():
    stop_by_pid_file(radvd_pid_file)
 
 
def start_modem_manager_mock(*additional_options):
    dbus_policy_src = os.path.join(networkd_ci_temp_dir, 'mock-modem-manager.conf')
    cp(dbus_policy_src, '/etc/dbus-1/system.d/mock-modem-manager.conf')
    check_output('systemctl reload dbus.service')
 
    command = ' '.join([test_modem_manager_mock] + list(additional_options))
    with open('/run/systemd/system/test-modem-manager-mock.service', mode='w', encoding='utf-8') as f:
        f.write(
            '[Unit]\n'
            'Description=Mock ModemManager for networkd testing\n'
            '[Service]\n'
            'Type=notify\n'
            'BusName=org.freedesktop.ModemManager1\n'
            f'ExecStart={command}\n'
        )
    check_output('systemctl daemon-reload')
    check_output('systemctl start test-modem-manager-mock.service')
 
 
def stop_modem_manager_mock():
    call('systemctl stop test-modem-manager-mock.service')
    rm_f('/run/systemd/system/test-modem-manager-mock.service')
    call('systemctl daemon-reload')
    rm_f('/etc/dbus-1/system.d/mock-modem-manager.conf')
 
 
def radvd_check_config(config_file):
    if not shutil.which('radvd'):
        print('radvd is not installed, assuming the config check failed')
        return False
 
    # Note: can't use networkd_ci_temp_dir here, as this command may run before that dir is
    #       set up (one instance is @unittest.skipX())
    config_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'conf/radvd', config_file)
    return call(f'radvd --config={config_file_path} --configtest') == 0
 
 
def networkd_invocation_id():
    return check_output('systemctl show --value -p InvocationID systemd-networkd.service')
 
 
def networkd_pid():
    return int(check_output('systemctl show --value -p MainPID systemd-networkd.service'))
 
 
def read_networkd_log(invocation_id=None, since=None):
    if not invocation_id:
        invocation_id = networkd_invocation_id()
    command = [
        'journalctl',
        '--no-hostname',
        '--output=short-monotonic',
        f'_SYSTEMD_INVOCATION_ID={invocation_id}',
    ]
    if since:
        command.append(f'--since={since}')
    check_output('journalctl --sync')
    return check_output(*command)
 
 
def networkd_is_failed():
    return call_quiet('systemctl is-failed -q systemd-networkd.service') != 1
 
 
def stop_networkd(show_logs=True, check_failed=True):
    global show_journal
    show_logs = show_logs and show_journal
    if show_logs:
        invocation_id = networkd_invocation_id()
 
    if check_failed:
        check_output('systemctl stop systemd-networkd.socket')
        check_output('systemctl stop systemd-networkd-resolve-hook.socket')
        check_output('systemctl stop systemd-networkd-varlink.socket')
        check_output('systemctl stop systemd-networkd-varlink-metrics.socket')
        check_output('systemctl stop systemd-networkd.service')
    else:
        call('systemctl stop systemd-networkd.socket')
        call('systemctl stop systemd-networkd-resolve-hook.socket')
        call('systemctl stop systemd-networkd-varlink.socket')
        call('systemctl stop systemd-networkd-varlink-metrics.socket')
        call('systemctl stop systemd-networkd.service')
 
    if show_logs:
        print(read_networkd_log(invocation_id))
 
    # Check if networkd exits cleanly.
    if check_failed:
        assert not networkd_is_failed()
 
 
def start_networkd():
    check_output('systemctl start systemd-networkd')
    invocation_id = networkd_invocation_id()
    pid = networkd_pid()
    print(f'Started systemd-networkd.service: PID={pid}, Invocation ID={invocation_id}')
 
 
def restart_networkd(show_logs=True):
    global show_journal
    show_logs = show_logs and show_journal
    if show_logs:
        invocation_id = networkd_invocation_id()
    check_output('systemctl restart systemd-networkd.service')
    if show_logs:
        print(read_networkd_log(invocation_id))
 
    invocation_id = networkd_invocation_id()
    pid = networkd_pid()
    print(f'Restarted systemd-networkd.service: PID={pid}, Invocation ID={invocation_id}')
 
 
def networkctl(*args):
    # Do not call networkctl if networkd is in failed state.
    # Otherwise, networkd may be restarted and we may get wrong results.
    assert not networkd_is_failed()
    return check_output(*(networkctl_cmd + list(args)), env=env)
 
 
def networkctl_status(*args):
    return networkctl('-n', '0', 'status', *args)
 
 
def networkctl_json(*args):
    return networkctl('--json=short', 'status', *args)
 
 
def networkctl_reconfigure(*links):
    networkctl('reconfigure', *links)
 
 
def networkctl_reload():
    networkctl('reload')
 
 
def networkctl_dhcp_lease(*args):
    return networkctl('dhcp-lease', *args)
 
 
def resolvectl(*args):
    return check_output(*(resolvectl_cmd + list(args)), env=env)
 
 
def timedatectl(*args):
    return check_output(*(timedatectl_cmd + list(args)), env=env)
 
 
def udevadm(*args):
    return check_output(*(udevadm_cmd + list(args)))
 
 
def udevadm_reload():
    udevadm('control', '--reload')
 
 
def udevadm_trigger(*args, action='add'):
    udevadm('trigger', '--settle', f'--action={action}', *args)
 
 
def setup_common():
    # Protect existing links
    unmanage_existing_links()
 
    # We usually show something in each test. So, let's break line to make the title of a test and output
    # from the test mixed. Then, flush stream buffer and journals.
    print()
    sys.stdout.flush()
    check_output('journalctl --sync')
 
 
def tear_down_common():
    # 1. stop DHCP/RA servers
    stop_dnsmasq()
    stop_isc_dhcpd()
    stop_radvd()
 
    # 2. remove modules
    call_quiet('rmmod netdevsim')
    call_quiet('rmmod sch_teql')
 
    # 3. remove network namespace
    call_quiet('ip netns del ns99')
    call_quiet('ip netns del ns-bridge')
    call_quiet('ip netns del ns-relay')
    call_quiet('ip netns del ns-server')
 
    # 4. remove links
    flush_l2tp_tunnels()
    flush_links()
 
    # 5. stop networkd
    stop_networkd(check_failed=False)
 
    # 6. remove configs
    clear_network_units()
    clear_networkd_conf_dropins()
    clear_networkd_state_files()
 
    # 7. flush settings
    flush_fou_ports()
    flush_nexthops()
    flush_routing_policy_rules()
    flush_routes()
 
    # 8. flush stream buffer and journals to make not any output from the test with the next one
    sys.stdout.flush()
    check_output('journalctl --sync')
 
    # 9. check the status of networkd
    assert not networkd_is_failed()
 
 
def setUpModule():
    rm_rf(networkd_ci_temp_dir)
    cp_r(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'conf'), networkd_ci_temp_dir)
 
    clear_network_units()
    clear_networkd_conf_dropins()
    clear_networkd_state_files()
    clear_udev_rules()
 
    setup_systemd_udev_rules()
    copy_udev_rule('00-debug-net.rules')
 
    # Save current state
    save_active_units()
    save_existing_links()
    save_routes()
    save_routing_policy_rules()
    save_timezone()
 
    setup_system_units()
 
 
def tearDownModule():
    rm_rf(networkd_ci_temp_dir)
    clear_udev_rules()
    clear_network_units()
    clear_networkd_conf_dropins()
    clear_networkd_state_files()
 
    restore_timezone()
 
    clear_system_units()
    restore_active_units()
 
    # Flush stream buffer and journals before showing the test summary.
    sys.stdout.flush()
    check_output('journalctl --sync')
 
 
class Utilities:
    # pylint: disable=no-member
 
    def check_link_exists(self, *link, expected=True):
        if expected:
            self.assertTrue(link_exists(*link))
        else:
            self.assertFalse(link_exists(*link))
 
    def check_link_attr(self, *args):
        self.assertEqual(read_link_attr(*args[:-1]), args[-1])
 
    def check_bridge_port_attr(self, master, port, attribute, expected, allow_enoent=False):
        path = os.path.join('/sys/devices/virtual/net', master, 'lower_' + port, 'brport', attribute)
        if allow_enoent and not os.path.exists(path):
            return
        with open(path, encoding='utf-8') as f:
            self.assertEqual(f.readline().strip(), expected)
 
    def check_ipv4_sysctl_attr(self, link, attribute, expected):
        self.assertEqual(read_ipv4_sysctl_attr(link, attribute), expected)
 
    def check_ipv6_sysctl_attr(self, link, attribute, expected):
        self.assertEqual(read_ipv6_sysctl_attr(link, attribute), expected)
 
    def check_ipv6_neigh_sysctl_attr(self, link, attribute, expected):
        self.assertEqual(read_ipv6_neigh_sysctl_attr(link, attribute), expected)
 
    def check_mpls_sysctl_attr(self, link, attribute, expected):
        self.assertEqual(read_mpls_sysctl_attr(link, attribute), expected)
 
    def wait_links(self, *links, trial=40):
        for _ in range(trial):
            if link_exists(*links):
                break
            time.sleep(0.5)
        else:
            self.fail('Timed out waiting for all links to be created: ' + ', '.join(list(links)))
 
    def wait_activated(self, link, state='down', trial=40):
        # wait for the interface is activated.
        needle = f'{link}: Bringing link {state}'
        flag = state.upper()
        self.wait_links(link, trial=trial)
        self.check_networkd_log(needle, trial=trial)
        for _ in range(trial):
            if flag in check_output(f'ip link show {link}'):
                break
            time.sleep(0.5)
        else:
            self.fail(f'Timed out waiting for {link} activated.')
 
    def wait_operstate(
        self, link, operstate='degraded', setup_state='configured', setup_timeout=5, fail_assert=True
    ):
        """Wait for the link to reach the specified operstate and/or setup state.
 
        Specify None or '' for either operstate or setup_state to ignore that state.
        This will recheck until the state conditions are met or the timeout expires.
 
        If the link successfully matches the requested state, this returns True.
        If this times out waiting for the link to match, the behavior depends on the
        'fail_assert' parameter; if True, this causes a test assertion failure,
        otherwise this returns False.  The default is to cause assertion failure.
 
        Note that this function matches on *exactly* the given operstate and setup_state.
        To wait for a link to reach *or exceed* a given operstate, use wait_online().
        """
        if not operstate:
            operstate = r'\S+'
        if not setup_state:
            setup_state = r'\S+'
 
        for _ in range(setup_timeout * 2):
            if not link_exists(link):
                time.sleep(0.5)
                continue
            try:
                output = networkctl_status(link)
            except subprocess.CalledProcessError:
                # networkctl status may transiently fail e.g. when networkd has not
                # yet picked up the link from the kernel. Retry until the timeout.
                time.sleep(0.5)
                continue
            if re.search(rf'(?m)^\s*State:\s+{operstate}\s+\({setup_state}\)\s*$', output):
                return True
            time.sleep(0.5)
 
        if fail_assert:
            self.fail(f'Timed out waiting for {link} to reach state {operstate}/{setup_state}')
        return False
 
    def wait_online(
        self,
        *links_with_operstate,
        timeout='20s',
        bool_any=False,
        ipv4=False,
        ipv6=False,
        setup_state='configured',
        setup_timeout=5,
        bool_dns=False,
    ):
        """Wait for the links to reach the specified operstate and/or setup state.
 
        This is similar to wait_operstate() but can be used for multiple links,
        and it also calls systemd-networkd-wait-online to wait for the given operstate.
        The operstate should be specified in the link name, like 'eth0:degraded'.
        If just a link name is provided, wait-online's default operstate to wait for is degraded.
 
        The 'timeout' parameter controls the systemd-networkd-wait-online timeout, and the
        'setup_timeout' controls the per-link timeout waiting for the setup_state.
 
        Set 'bool_any' to True to wait for any (instead of all) of the given links.
        If this is set, no setup_state checks are done.
 
        Set 'bool_dns' to True to wait for DNS servers to be accessible.
 
        Set 'ipv4' or 'ipv6' to True to wait for IPv4 address or IPv6 address, respectively, of each of the
        given links. This is applied only for the operational state 'degraded' or above.
 
        Note that this function waits for the links to reach *or exceed* the given operstate.
        However, the setup_state, if specified, must be matched *exactly*.
 
        This returns if the links reached the requested operstate/setup_state; otherwise it
        raises CalledProcessError or fails test assertion.
        """
        args = (
            wait_online_cmd
            + [f'--timeout={timeout}']
            + [f'--interface={link}' for link in links_with_operstate]
            + [f'--ignore={link}' for link in protected_links]
        )
        if bool_any:
            args += ['--any']
        if bool_dns:
            args += ['--dns']
        if ipv4:
            args += ['--ipv4']
        if ipv6:
            args += ['--ipv6']
        try:
            check_output(*args, env=wait_online_env)
        except subprocess.CalledProcessError:
            if networkd_is_failed():
                print('!!!!! systemd-networkd.service is failed !!!!!')
                call('systemctl status systemd-networkd.service')
            else:
                # show detailed status on failure
                for link in links_with_operstate:
                    name = link.split(':')[0]
                    if link_exists(name):
                        print(networkctl_status(name))
                    else:
                        print(f'Interface {name} not found.')
            raise
        if not bool_any and setup_state:
            for link in links_with_operstate:
                self.wait_operstate(link.split(':')[0], None, setup_state, setup_timeout)
 
    def wait_address(self, link, address_regex, scope='global', ipv='', timeout_sec=100):
        for _ in range(timeout_sec * 2):
            output = check_output(f'ip {ipv} address show dev {link} scope {scope}')
            if re.search(address_regex, output) and 'tentative' not in output:
                break
            time.sleep(0.5)
 
        self.assertRegex(output, address_regex)
 
    def wait_address_dropped(self, link, address_regex, scope='global', ipv='', timeout_sec=100):
        for _ in range(timeout_sec * 2):
            output = check_output(f'ip {ipv} address show dev {link} scope {scope}')
            if not re.search(address_regex, output):
                break
            time.sleep(0.5)
 
        self.assertNotRegex(output, address_regex)
 
    def wait_route(self, link, route_regex, table='main', ipv='', timeout_sec=100):
        for _ in range(timeout_sec * 2):
            output = check_output(f'ip {ipv} route show dev {link} table {table}')
            if re.search(route_regex, output):
                break
            time.sleep(0.5)
 
        self.assertRegex(output, route_regex)
 
    def wait_route_dropped(self, link, route_regex, table='main', ipv='', timeout_sec=100):
        for _ in range(timeout_sec * 2):
            output = check_output(f'ip {ipv} route show dev {link} table {table}')
            if not re.search(route_regex, output):
                break
            time.sleep(0.5)
 
        self.assertNotRegex(output, route_regex)
 
    def check_netlabel(self, interface, address, label='system_u:object_r:root_t:s0'):
        if not shutil.which('selinuxenabled'):
            print('## Checking NetLabel skipped: selinuxenabled command not found.')
        elif call_quiet('selinuxenabled') != 0:
            print('## Checking NetLabel skipped: SELinux disabled.')
        elif not shutil.which('netlabelctl'):  # not packaged by all distros
            print('## Checking NetLabel skipped: netlabelctl command not found.')
        else:
            output = check_output('netlabelctl unlbl list')
            print(output)
            self.assertRegex(output, f'interface:{interface},address:{address},label:"{label}"')
 
    def setup_nftset(self, filter_name, filter_type, flags=''):
        if not shutil.which('nft'):
            print('## Setting up NFT sets skipped: nft command not found.')
        else:
            if call('nft add table inet sd_test') != 0:
                print('## Setting up NFT table failed.')
                self.fail()
            if call(f'nft add set inet sd_test {filter_name} {{ type {filter_type}; {flags} }}') != 0:
                print('## Setting up NFT sets failed.')
                self.fail()
 
    def teardown_nftset(self, *filters):
        if not shutil.which('nft'):
            print('## Tearing down NFT sets skipped: nft command not found.')
        else:
            for filter_name in filters:
                if call(f'nft delete set inet sd_test {filter_name}') != 0:
                    print('## Tearing down NFT sets failed.')
                    self.fail()
            if call('nft delete table inet sd_test') != 0:
                print('## Tearing down NFT table failed.')
                self.fail()
 
    def check_nftset(self, filter_name, contents):
        if not shutil.which('nft'):
            print('## Checking NFT sets skipped: nft command not found.')
        else:
            output = check_output(f'nft list set inet sd_test {filter_name}')
            print(output)
            self.assertRegex(output, r'.*elements = { [^}]*' + contents + r'[^}]* }.*')
 
    def check_networkd_log(self, contents, since=None, trial=20):
        for _ in range(trial):
            if contents in read_networkd_log(since=since):
                break
            time.sleep(0.5)
        else:
            self.fail(f'"{contents}" not found in journal.')
 
    def networkctl_check_unit(self, ifname, netdev_file=None, network_file=None, link_file=None):
        output = networkctl_status(ifname)
        print(output)
        if netdev_file:
            self.assertRegex(output, rf'NetDev File: .*/{netdev_file}\.netdev')
        else:
            self.assertNotIn('NetDev File:', output)
        if network_file:
            self.assertRegex(output, rf'Network File: .*/{network_file}\.network')
        else:
            self.assertIn('Network File: n/a', output)
        if link_file:
            self.assertRegex(output, rf'Link File: .*/{link_file}\.link')
 
 
class NetworkctlTests(unittest.TestCase, Utilities):
    def setUp(self):
        setup_common()
 
    def tearDown(self):
        tear_down_common()
 
    def test_altname(self):
        copy_network_unit('26-netdev-link-local-addressing-yes.network', '12-dummy.netdev', '12-dummy.link')
        start_networkd()
        self.wait_online('dummy98:degraded')
 
        output = networkctl_status('dummy98')
        self.assertRegex(output, 'hogehogehogehogehogehoge')
 
    def test_rename_to_altname(self):
        copy_network_unit(
            '26-netdev-link-local-addressing-yes.network',
            '12-dummy.netdev',
            '12-dummy-rename-to-altname.link',
        )
        start_networkd()
        self.wait_online('dummyalt:degraded')
 
        output = networkctl_status('dummyalt')
        self.assertIn('hogehogehogehogehogehoge', output)
        self.assertNotIn('dummy98', output)
 
    def test_reconfigure(self):
        copy_network_unit('25-address-static.network', '12-dummy.netdev', copy_dropins=False)
        start_networkd()
        self.wait_online('dummy98:routable')
 
        output = check_output('ip -4 address show dev dummy98')
        print(output)
        self.assertIn('inet 10.1.2.3/16 brd 10.1.255.255 scope global dummy98', output)
        self.assertIn('inet 10.1.2.4/16 brd 10.1.255.255 scope global secondary dummy98', output)
        self.assertIn('inet 10.2.2.4/16 brd 10.2.255.255 scope global dummy98', output)
 
        check_output('ip address del 10.1.2.3/16 dev dummy98')
        check_output('ip address del 10.1.2.4/16 dev dummy98')
        check_output('ip address del 10.2.2.4/16 dev dummy98')
 
        networkctl_reconfigure('dummy98')
        self.wait_online('dummy98:routable')
 
        output = check_output('ip -4 address show dev dummy98')
        print(output)
        self.assertIn('inet 10.1.2.3/16 brd 10.1.255.255 scope global dummy98', output)
        self.assertIn('inet 10.1.2.4/16 brd 10.1.255.255 scope global secondary dummy98', output)
        self.assertIn('inet 10.2.2.4/16 brd 10.2.255.255 scope global dummy98', output)
 
        remove_network_unit('25-address-static.network')
 
        networkctl_reload()
        self.wait_operstate('dummy98', 'degraded', setup_state='unmanaged')
 
        output = check_output('ip -4 address show dev dummy98')
        print(output)
        self.assertNotIn('inet 10.1.2.3/16 brd 10.1.255.255 scope global dummy98', output)
        self.assertNotIn('inet 10.1.2.4/16 brd 10.1.255.255 scope global secondary dummy98', output)
        self.assertNotIn('inet 10.2.2.4/16 brd 10.2.255.255 scope global dummy98', output)
 
        copy_network_unit('25-address-static.network', copy_dropins=False)
        networkctl_reload()
        self.wait_online('dummy98:routable')
 
        output = check_output('ip -4 address show dev dummy98')
        print(output)
        self.assertIn('inet 10.1.2.3/16 brd 10.1.255.255 scope global dummy98', output)
        self.assertIn('inet 10.1.2.4/16 brd 10.1.255.255 scope global secondary dummy98', output)
        self.assertIn('inet 10.2.2.4/16 brd 10.2.255.255 scope global dummy98', output)
 
    def test_renew(self):
        def check():
            self.wait_online('veth99:routable', 'veth-peer:routable')
            output = networkctl_status('veth99')
            print(output)
            self.assertRegex(output, r'Address: 192.168.5.[0-9]* \(DHCPv4 via 192.168.5.1\)')
            self.assertIn('Gateway: 192.168.5.3', output)
            self.assertRegex(output, 'DNS: 192.168.5.1\n *192.168.5.10')
            self.assertRegex(output, 'NTP: 192.168.5.1\n *192.168.5.11')
 
        copy_network_unit('25-veth.netdev', '25-dhcp-client.network', '25-dhcp-server.network')
        start_networkd()
        check()
        check_json(networkctl_json('--lines=0', '--stats', '--all', '--full'))
 
        for verb in ['renew', 'forcerenew']:
            networkctl(verb, 'veth99')
            check()
            networkctl(verb, 'veth99', 'veth99', 'veth99')
            check()
 
    def test_up_down(self):
        copy_network_unit('25-address-static.network', '12-dummy.netdev', copy_dropins=False)
        start_networkd()
        self.wait_online('dummy98:routable')
 
        networkctl('down', 'dummy98')
        self.wait_online('dummy98:off')
        networkctl('up', 'dummy98')
        self.wait_online('dummy98:routable')
        networkctl('down', 'dummy98', 'dummy98', 'dummy98')
        self.wait_online('dummy98:off')
        networkctl('up', 'dummy98', 'dummy98', 'dummy98')
        self.wait_online('dummy98:routable')
 
    def test_reload(self):
        start_networkd()
 
        copy_network_unit('11-dummy.netdev')
        networkctl_reload()
        self.wait_operstate('test1', 'off', setup_state='unmanaged')
 
        copy_network_unit('11-dummy.network')
        networkctl_reload()
        self.wait_online('test1:degraded')
 
        remove_network_unit('11-dummy.network')
        networkctl_reload()
        self.wait_operstate('test1', 'degraded', setup_state='unmanaged')
 
        remove_network_unit('11-dummy.netdev')
        networkctl_reload()
        self.wait_operstate('test1', 'degraded', setup_state='unmanaged')
 
        copy_network_unit('11-dummy.netdev', '11-dummy.network')
        networkctl_reload()
        self.wait_operstate('test1', 'degraded')
 
    def test_reload_no_reconfigure(self):
        copy_network_unit('12-dummy.netdev', '25-address-static.network', copy_dropins=False)
        start_networkd()
        self.wait_online('dummy98:routable')
 
        output = check_output('ip -4 address show dev dummy98')
        print(output)
        self.assertIn('inet 10.1.2.3/16 brd 10.1.255.255 scope global dummy98', output)
 
        with open(
            os.path.join(network_unit_dir, '25-address-static.network'), mode='w', encoding='utf-8'
        ) as f:
            f.write('[Match]\nName=dummy98\n\n[Network]\nIPv6AcceptRA=no\nAddress=10.99.0.1/24\n')
 
        networkctl('reload', '--no-reconfigure')
 
        output = check_output('ip -4 address show dev dummy98')
        print(output)
        self.assertIn('inet 10.1.2.3/16 brd 10.1.255.255 scope global dummy98', output)
        self.assertNotIn('inet 10.99.0.1/24', output)
 
        networkctl_reconfigure('dummy98')
        self.wait_online('dummy98:routable')
 
        output = check_output('ip -4 address show dev dummy98')
        print(output)
        self.assertIn('inet 10.99.0.1/24 brd 10.99.0.255 scope global dummy98', output)
        self.assertNotIn('inet 10.1.2.3/16', output)
 
    def test_glob(self):
        copy_network_unit('11-dummy.netdev', '11-dummy.network')
        start_networkd()
 
        self.wait_online('test1:degraded')
 
        output = networkctl('list')
        self.assertRegex(output, '1 lo ')
        self.assertRegex(output, 'test1')
 
        output = networkctl('list', 'test1')
        self.assertNotRegex(output, '1 lo ')
        self.assertRegex(output, 'test1')
 
        output = networkctl('list', 'te*')
        self.assertNotRegex(output, '1 lo ')
        self.assertRegex(output, 'test1')
 
        output = networkctl_status('te*')
        self.assertNotRegex(output, '1: lo ')
        self.assertRegex(output, 'test1')
 
        output = networkctl_status('tes[a-z][0-9]')
        self.assertNotRegex(output, '1: lo ')
        self.assertRegex(output, 'test1')
 
    def test_mtu(self):
        copy_network_unit('11-dummy-mtu.netdev', '11-dummy.network')
        start_networkd()
 
        self.wait_online('test1:degraded')
 
        output = networkctl_status('test1')
        self.assertRegex(output, 'MTU: 1600')
 
    def test_type(self):
        copy_network_unit('11-dummy.netdev', '11-dummy.network')
        start_networkd()
        self.wait_online('test1:degraded')
 
        output = networkctl_status('test1')
        print(output)
        self.assertRegex(output, 'Type: ether')
 
        output = networkctl_status('lo')
        print(output)
        self.assertRegex(output, 'Type: loopback')
 
    def test_unit_file(self):
        copy_network_unit('11-test-unit-file.netdev', '11-test-unit-file.network', '11-test-unit-file.link')
        start_networkd()
        self.wait_online('test1:degraded')
 
        output = networkctl_status('test1')
        print(output)
        self.assertIn('Link File: /run/systemd/network/11-test-unit-file.link', output)
        self.assertIn('/run/systemd/network/11-test-unit-file.link.d/dropin.conf', output)
        self.assertIn('Network File: /run/systemd/network/11-test-unit-file.network', output)
        self.assertIn('/run/systemd/network/11-test-unit-file.network.d/dropin.conf', output)
 
        self.check_networkd_log(
            'test1: Configuring with /run/systemd/network/11-test-unit-file.network '
            '(dropins: /run/systemd/network/11-test-unit-file.network.d/dropin.conf).'
        )
 
        output = networkctl_status('lo')
        print(output)
        self.assertIn('Link File: n/a', output)
        self.assertIn('Network File: n/a', output)
 
    def test_delete_links(self):
        copy_network_unit('11-dummy.netdev', '25-veth.netdev')
        start_networkd()
        self.wait_links('test1', 'veth99', 'veth-peer')
        networkctl('delete', 'test1', 'veth99')
        self.check_link_exists('test1', 'veth99', 'veth-peer', expected=False)
 
    def test_label(self):
        networkctl('label')
 
 
class NetworkdMatchTests(unittest.TestCase, Utilities):
    def setUp(self):
        setup_common()
 
    def tearDown(self):
        tear_down_common()
 
    def test_match(self):
        copy_network_unit(
            '12-dummy-mac.netdev',
            '12-dummy-match-mac-01.network',
            '12-dummy-match-mac-02.network',
            '12-dummy-match-renamed.network',
            '12-dummy-match-altname.network',
            '12-dummy-altname.link',
        )
        start_networkd()
 
        self.wait_online('dummy98:routable')
        output = networkctl_status('dummy98')
        self.assertIn('Network File: /run/systemd/network/12-dummy-match-mac-01.network', output)
        output = check_output('ip -4 address show dev dummy98')
        self.assertIn('10.0.0.1/16', output)
 
        check_output('ip link set dev dummy98 down')
        check_output('ip link set dev dummy98 address 12:34:56:78:9a:02')
 
        self.wait_address('dummy98', '10.0.0.2/16', ipv='-4', timeout_sec=10)
        self.wait_online('dummy98:routable')
        output = networkctl_status('dummy98')
        self.assertIn('Network File: /run/systemd/network/12-dummy-match-mac-02.network', output)
 
        check_output('ip link set dev dummy98 down')
        check_output('ip link set dev dummy98 name dummy98-1')
 
        self.wait_address('dummy98-1', '10.0.1.2/16', ipv='-4', timeout_sec=10)
        self.wait_online('dummy98-1:routable')
        output = networkctl_status('dummy98-1')
        self.assertIn('Network File: /run/systemd/network/12-dummy-match-renamed.network', output)
 
        check_output('ip link set dev dummy98-1 down')
        check_output('ip link set dev dummy98-1 name dummy98-2')
        udevadm_trigger('/sys/class/net/dummy98-2')
 
        self.wait_address('dummy98-2', '10.0.2.2/16', ipv='-4', timeout_sec=10)
        self.wait_online('dummy98-2:routable')
        output = networkctl_status('dummy98-2')
        self.assertIn('Network File: /run/systemd/network/12-dummy-match-altname.network', output)
 
    def test_match_udev_property(self):
        copy_network_unit(
            '12-dummy.netdev',
            '13-not-match-udev-property.network',
            '14-match-udev-property.network',
        )
        start_networkd()
        self.wait_online('dummy98:routable')
 
        output = networkctl_status('dummy98')
        print(output)
        self.assertRegex(output, 'Network File: /run/systemd/network/14-match-udev-property')
 
 
class WaitOnlineTests(unittest.TestCase, Utilities):
    def setUp(self):
        setup_common()
 
    def tearDown(self):
        tear_down_common()
 
    def test_wait_online_any(self):
        copy_network_unit('25-bridge.netdev', '25-bridge.network', '11-dummy.netdev', '11-dummy.network')
        start_networkd()
 
        self.wait_online('bridge99', 'test1:degraded', bool_any=True)
 
        self.wait_operstate('bridge99', '(off|no-carrier)', setup_state='configuring')
        self.wait_operstate('test1', 'degraded')
 
    def do_test_wait_online_dns(
        self,
        global_dns='',
        fallback_dns='',
        expect_timeout=False,
        network_dropin=None,
    ):
        global wait_online_env
 
        if network_dropin is not None:
            network_dropin_path = os.path.join(
                network_unit_dir,
                '25-dhcp-client-use-dns-ipv4.network.d/test.conf',
            )
            mkdir_p(os.path.dirname(network_dropin_path))
            with open(network_dropin_path, 'w') as f:
                f.write(network_dropin)
 
        copy_network_unit(
            '25-veth.netdev',
            '25-dhcp-client-use-dns-ipv4.network',
            '25-dhcp-server.network',
        )
        start_networkd()
        self.wait_online('veth-peer:routable')
 
        # Unless given, clear global DNS configuration
        resolved_dropin = '/run/systemd/resolved.conf.d/global-dns.conf'
        mkdir_p(os.path.dirname(resolved_dropin))
        with open(resolved_dropin, 'w') as f:
            f.write(f'''
[Resolve]
DNS={global_dns}
FallbackDNS={fallback_dns}
''')
        self.addCleanup(os.remove, resolved_dropin)
        check_output('systemctl reload systemd-resolved')
 
        try:
            wait_online_env_copy = wait_online_env.copy()
 
            wait_online_env['SYSTEMD_LOG_LEVEL'] = 'debug'
            wait_online_env['SYSTEMD_LOG_TARGET'] = 'console'
 
            self.wait_online('veth99:routable', bool_dns=True)
 
            if expect_timeout:
                # The above should have thrown an exception.
                self.fail('Expected systemd-networkd-wait-online to time out')
 
        except subprocess.CalledProcessError as e:
            if expect_timeout:
                self.assertRegex(
                    e.output,
                    'veth99: No link-specific DNS server is accessible',
                    f'Missing expected log message:\n{e.output}',
                )
            else:
                self.fail(f'Command timed out:\n{e.output}')
        finally:
            wait_online_env = wait_online_env_copy
 
    def test_wait_online_dns(self):
        """test systemd-networkd-wait-online with --dns"""
        self.do_test_wait_online_dns()
 
    def test_wait_online_dns_global(self):
        """
        test systemd-networkd-wait-online with --dns, expect pass due to global DNS
        """
 
        # Set UseDNS=no, and allow global DNS to be used.
        self.do_test_wait_online_dns(
            global_dns='192.168.5.1',
            network_dropin=(
                '''
[DHCPv4]
UseDNS=no
'''
            ),
        )
 
    def test_wait_online_dns_expect_timeout(self):
        """test systemd-networkd-wait-online with --dns, and expect timeout"""
 
        # Explicitly set DNSDefaultRoute=yes, and require link-specific DNS to be used.
        self.do_test_wait_online_dns(
            expect_timeout=True,
            network_dropin=(
                '''
[Network]
DNSDefaultRoute=yes
[DHCPv4]
UseDNS=no
'''
            ),
        )
 
    def test_wait_online_dns_expect_timeout_global(self):
        """
        test systemd-networkd-wait-online with --dns, and expect timeout
        despite global DNS
        """
 
        # Configure Domains=~., and expect timeout despite global DNS servers
        # being available.
        self.do_test_wait_online_dns(
            expect_timeout=True,
            global_dns='192.168.5.1',
            network_dropin=(