frr_configurator.py 9.12 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#!/usr/bin/env python3

# Copyright (C) 2018 Simon Redman <sredman@cs.utah.edu>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

18 19
# For future reference, here is the OSPFv6 RFC: https://tools.ietf.org/html/rfc2740.html

20 21 22
import ssh_helper

import argparse
23
import datetime
24
import getpass
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
import ipaddress
from netdiff import NetJsonParser


OSPF_CONF_TEMPLATE = """#
# ospf6d.conf generated by frr_configurator on {date}
#
hostname {hostname}
password zebra
log file /var/log/frr/ospf6d.log
service advanced-vty

{interfaces}

router ospf6
40
  router-id {router_id}
41 42 43
{router_info}
"""

44 45 46 47 48
ZEBRA_CONF_TEMPLATE = """#
# zebra.conf generated by frr_configurator on {date}
#
hostname {hostname}
password zebra
49
enable password zebra
50 51 52 53 54 55 56 57
log file /var/log/frr/zebra.log

{interfaces}

ip forwarding
line vty
"""

58
# interface should be replaced with the Linux interface to speak OSPF on
59
# One of these per interface should be put in the interfaces section of the OSPF_CONF_TEMPLATE
60 61
INTERFACE_LINE_TEMPLATE = "interface {interface}"

62 63 64 65 66
# interface should be replaced with the Linux interface to run FRR on
# address_prefix should be replaced with an IPv6 interface address in prefix notation (::1/128, for example)
# One of these per interface should be put in the interfaces section of the ZEBRA_CONF_TEMPLATE
ZEBRA_INTERFACE_LINE_TEMPLATE = INTERFACE_LINE_TEMPLATE + "\n  ipv6 address {address_prefix}"

67 68 69 70
# AREA is an OSPF concept, but it looks like FRR only implements AREA as 0
# range should be replaced with the prefix of the interface, for instance 'fd00:10:10:2:54:28ff:fe8b:1395/64'
# interface should be replaced with the interface OSPF is being used on
# One of these per interface should be put in the router_info section
71
ROUTER_LINE_TEMPLATE = "  area 0.0.0.0 range {range}\n  interface {interface} area 0.0.0.0"
72

73
OSPF_CONF_FILENAME = "/etc/frr/ospf6d.conf"
74
ZEBRA_CONF_FILENAME = "/etc/frr/zebra.conf"
75
CONFIG_PUSH_COMMAND_TEMPLATE = "echo '{config}' | sudo tee {filename}"
76 77 78

ENABLE_DAEMON_COMMAND_TEMPLATE = "sudo sed -i 's/{daemon}=no/{daemon}=yes/' /etc/frr/daemons"

79 80 81
# Disable integrated config mode per https://frrouting.org/user-guide/vtysh.html#integrated-configuration-mode
DISABLE_INTEGRATED_COMMAND = "sudo sed -i 's/service integrated-vtysh-config/no service integrated-vtysh-config/' /etc/frr/vtysh.conf && sudo rm /etc/frr/frr.conf"

82 83 84
START_DAEMON_COMMAND = "sudo systemctl restart frr"
STOP_DAEMON_COMMAND = "sudo systemctl stop frr"

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

def build_ospf_conf_for_host(host, hostname, interfaces):
    """
    Construct the OSPFv6 config file for the host specified

    :param host: unique IPv4 address of the host to build a config file for
    :param hostname: human-readable name associated with this host
    :param interfaces: mapping of interface names to IPv6 addresses on that interface
    :return: ospf6d config file
    """
    interfaces_strs = []
    router_info_strs = []

    assert type(host) is ipaddress.IPv4Address, "Host should be an ip address to build a config for"
    # More specifically, I need an IPv4Address because I am using it for the OSPF router-id which needs to be an IPv4Address-shaped thing

    for interface in interfaces.keys():
        interfaces_strs.append(INTERFACE_LINE_TEMPLATE.format(
            interface=interface
        ))
        router_info_strs.append(ROUTER_LINE_TEMPLATE.format(
            range=interfaces[interface],
            interface=interface,
        ))

    config = OSPF_CONF_TEMPLATE.format(
        date=datetime.datetime.today(),
        hostname=hostname,
        router_id=host,
        interfaces=str.join('\n', interfaces_strs),
        router_info=str.join('\n', router_info_strs),
    )

    return config
119 120


121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
def build_zebra_conf_for_host(hostname, interfaces):
    interfaces_strs = []

    for interface in interfaces.keys():
        interfaces_strs.append(ZEBRA_INTERFACE_LINE_TEMPLATE.format(
            interface=interface,
            address_prefix=interfaces[interface]
        ))

    config = ZEBRA_CONF_TEMPLATE.format(
        date=datetime.datetime.today(),
        hostname=hostname,
        interfaces=str.join('\n', interfaces_strs)
    )

    return config


139 140 141 142 143 144 145 146 147 148 149 150
def build_ospf_confs_for_network(netgraph):
    """
    Build the ospf6d conf file for all nodes in the network

    :param netgraph: networkx graph
    :return: mapping of hosts to configurations
    """
    ospf_confs = {}

    for host in netgraph.nodes:
        interfaces = netgraph._node[host]['interfaces']
        hostname = netgraph._node[host]['label']
151
        ospf_confs[host] = build_ospf_conf_for_host(ipaddress.ip_address(host), hostname, interfaces)
152 153 154 155

    return ospf_confs


156 157 158 159 160 161 162 163 164 165 166
def build_zebra_confs_for_network(netgraph):
    zebra_confs = {}

    for host in netgraph.nodes:
        interfaces = netgraph._node[host]['interfaces']
        hostname = netgraph._node[host]['label']
        zebra_confs[host] = build_zebra_conf_for_host(hostname, interfaces)

    return zebra_confs


167 168 169 170 171 172 173 174
def configure_nodes(netgraph):
    """
    Create ospf6d and zebra conf files, push them to the relevant nodes, and enable the daemons

    :param netgraph: networkx graph object representing the network
    :return: None
    """
    ospf_push_commands = []
175
    zebra_push_commands = []
176
    ospf_enable_commands = []
177 178
    zebra_enable_commands = []

179
    hosts = [host for host in netgraph.nodes]
180
    sessions = [session for session in map(lambda host : netgraph._node[host]['session'], hosts)]
181 182

    ospf_confs = build_ospf_confs_for_network(netgraph)
183
    zebra_confs = build_zebra_confs_for_network(netgraph)
184

185 186 187 188
    # Disable integrated config mode
    disable_integrated_commands = [DISABLE_INTEGRATED_COMMAND for host in hosts]
    outputs = ssh_helper.run_commands_on_many_hosts(sessions, disable_integrated_commands)

189
    # Push ospf6d configurations to all nodes
190 191 192 193 194 195
    for host in hosts:
        push_command = CONFIG_PUSH_COMMAND_TEMPLATE.format(
            config=ospf_confs[host],
            filename=OSPF_CONF_FILENAME,
        )
        ospf_push_commands.append(push_command)
196
    outputs = ssh_helper.run_commands_on_many_hosts(sessions, ospf_push_commands)
197 198 199 200 201 202 203

    # Enable ospf6d
    for host in hosts:
        enable_command = ENABLE_DAEMON_COMMAND_TEMPLATE.format(
            daemon="ospf6d"
        )
        ospf_enable_commands.append(enable_command)
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    outputs = ssh_helper.run_commands_on_many_hosts(sessions, ospf_enable_commands)

    # Push zebra configurations to all nodes
    for host in hosts:
        push_command = CONFIG_PUSH_COMMAND_TEMPLATE.format(
            config=zebra_confs[host],
            filename=ZEBRA_CONF_FILENAME,
        )
        zebra_push_commands.append(push_command)
    outputs = ssh_helper.run_commands_on_many_hosts(sessions, zebra_push_commands)

    # Enable zebra
    for host in hosts:
        enable_command = ENABLE_DAEMON_COMMAND_TEMPLATE.format(
            daemon="zebra"
        )
        zebra_enable_commands.append(enable_command)
    outputs = ssh_helper.run_commands_on_many_hosts(sessions, zebra_enable_commands)
222

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245

def start_frr_on_network(netgraph):
    """
    Restart (or start) frr on all nodes in the network

    :param netgraph: networkx graph representing the network
    :return: None
    """
    sessions = [session for session in map(lambda host : netgraph._node[host]['session'], netgraph.nodes)]
    commands = [START_DAEMON_COMMAND for session in sessions]
    ssh_helper.run_commands_on_many_hosts(sessions, commands)


def stop_frr_on_network(netgraph):
    """
    Stop frr on all nodes in the network

    :param netgraph: networkx graph representing the network
    :return: None
    """
    sessions = [session for session in map(lambda host : netgraph._node[host]['session'], netgraph.nodes)]
    commands = [STOP_DAEMON_COMMAND for session in sessions]
    ssh_helper.run_commands_on_many_hosts(sessions, commands)
246 247


248 249 250 251 252 253
if __name__ == "__main__":
    parser = argparse.ArgumentParser("Configure Free Range Routing's OSPFv6 and Zebra for all nodes in the network")
    parser.add_argument("--in-file", action='store', type=str, required=True,
                        help="Path to the NetJSON file to parse")
    parser.add_argument("--username", action='store', type=str, default=getpass.getuser(),
                        help="Username to use on all hosts. Defaults to current user's username")
254 255
    parser.add_argument("--stop", action='store', type=bool, default=False,
                        help="Stop all services (after writing config files)")
256 257 258 259 260 261

    args = parser.parse_args()

    netgraph = NetJsonParser(file=args.in_file)
    ssh_helper.network_graph_login(netgraph.graph, args.username)

262
    configure_nodes(netgraph.graph)
263 264 265 266 267

    if args.stop:
        stop_frr_on_network(netgraph.graph)
    else:
        start_frr_on_network(netgraph.graph)
268

269
    ssh_helper.network_graph_logout(netgraph.graph)