topomap_parser.py 7.37 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#!/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.

import argparse
19
import copy
20 21
from collections import namedtuple
import json
22
import socket
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

# A lan is defined by a netmask and a cost
Lan = namedtuple('Lan', ['netmask', 'cost', ])


def parse_comment_line(line):
    """
    Get the next action by parsing TMCD's comment

    :param line:
    :return: String indicating the next action
    """
    body = line.split(' ')

    assert body[0] == "#", "Unexpected input to parse_comment_line"

    assert body[1].endswith(':'), "Unexpected comment body syntax"

    # Remove that trailing colon
    option = body[1][:-1]

    return option


def raise_unexpected_option_error(option):
    raise ValueError('Unexpected option: {option}'.format(option=option))


def parse_node_line(line):
    """
    Parse a line formatted as node_name, links, where node_name is any string and links is a space-
    separated list of net names and attached interface IP addresses
    :param line:
    :return: Tuple of node name and dict of net names -> ip addresses
    """
    node, nets = line.split(',')
    nets = nets.split(' ')

    nets_dict = {}

    for net in nets:
        net_name, ip = net.split(':')
        nets_dict[net_name] = ip

    return node, nets_dict


def parse_link_line(line):
    """
    Parse a line formatted as a comma-separated list of lan parameters starting with its name
    :param line:
    :return:
    """
    name, *parameters = line.split(',')

    return name, Lan(*parameters)

80

81 82 83 84 85 86
def parse_topomap(topomap):
    """
    Parse the passed topomap string into a Python dictionary
    It shall contain one key per datatype defined in TMCD's topomap, currently 'nodes' and 'lans'
    'nodes' shall map to a dictionary of node names -> parameters
    'lans' shall map to a dictionary of lan names -> parameters
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
    :param topomap: File to open and parse
    :return: Dictionary as defined above
    """

    to_return = {}

    option = ''
    switch = {
        'nodes': parse_node_line,
        'lans': parse_link_line,
        'default': lambda x: raise_unexpected_option_error(option), # Take the line, ignore it, and print a semi-useful error
    }

    with open(topomap, 'r') as contents:
        for line in contents:
            line = line.strip() # Clean whitespace
            if line.startswith('#'):
                option = parse_comment_line(line)
                if not option in to_return:
                    to_return[option] = {}
            else:
                key, value = switch.get(option, switch['default'])(line)
                to_return[option][key] = value

    return to_return


115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
def get_management_ips_of_nodes(nodes, node_nickname):
    """
    Given a list of node names (e.g., 'node1'), resolve their FQDN to their management ips

    :param nodes: List of node names
    :type nodes: list[str]
    :param node_nickname: Nickname of a single node from which the FQDN will be parsed. E.x.: node1.instance.project.emulab.net
    :return: mapping of node names to ip addresses
    """
    FQDN_template = "{host}.{instance}.{project}.{domain}"

    management_ips = {}

    nickname_parts = node_nickname.split('.')
    # nickname_parts[0] is the hostname of a particular node and the part we will be replacing
    instance = nickname_parts[1]
    project = nickname_parts[2]
    domain = '.'.join(nickname_parts[3:])

    for host in nodes:
        FQDN = FQDN_template.format(host=host, instance=instance, project=project, domain=domain)
        IP = socket.gethostbyname(FQDN)
        management_ips[host] = IP

    return management_ips


142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
def parse_topomap_to_netjson(topomap):
    """
    Convert the Emulab topomap file into NetJSON [http://netjson.org/]

    :param topomap: File to open and parse
    :return: Python dictionary in NetJSON format
    """
    netjson = {}
    nodes = []
    links = []

    netjson['type'] = "NetworkGraph"
    netjson['protocol'] = "static"
    netjson['version'] = None
    netjson['metric'] = None
    netjson['nodes'] = nodes
    netjson['links'] = links

    topodict = parse_topomap(topomap)
161 162
    node_names = [node for node in topodict['nodes'].keys()]
    management_ips = get_management_ips_of_nodes(node_names, socket.gethostname())
163 164 165 166 167 168 169

    for node_name in topodict['nodes']:
        node = {}
        interfaces = topodict['nodes'][node_name]
        local_addresses = []
        properties = {}

170 171 172
        local_addresses.append(management_ips[node_name])

        node['id'] = management_ips[node_name]
173 174 175 176
        node['label'] = node_name
        node['local_addresses'] = local_addresses
        node['properties'] = properties

177
        properties['lans'] = interfaces
178 179
        # Add a management-ip property, which should be the IP address or hostname to use for remote access
        properties['management-ip'] = management_ips[node_name]
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216

        for lan in interfaces:
            local_addresses.append(interfaces[lan])
        nodes.append(node)

    # Construct NetJSON link objects
    for lan_name in topodict['lans']:
        link = {}
        properties = {}

        lan = topodict['lans'][lan_name]

        link['cost'] = lan.cost
        link['properties'] = properties

        properties['netmask'] = lan.netmask

        # Since Emulab does not, to my knowledge, present link information in a convenient way we have to parse
        # each node to look for two on the same LAN
        for node1_idx in range(0, len(netjson['nodes'])):
            node1 = netjson['nodes'][node1_idx]
            if lan_name in node1['properties']['lans']:
                # We have found one node, look for a second
                for node2_idx in range(node1_idx + 1, len(netjson['nodes'])):
                    node2 = netjson['nodes'][node2_idx]
                    if lan_name in node2['properties']['lans']:
                        # We have found two nodes. Make a link
                        link['source'] = node1['id']
                        link['target'] = node2['id']
                        links.append(copy.deepcopy(link))
                        # Make the reverse link, since there are only bi-directional links in Emulab
                        link['source'] = node2['id']
                        link['target'] = node1['id']
                        links.append(copy.deepcopy(link))
    return netjson


217
if __name__ == "__main__":
218
    parser = argparse.ArgumentParser("Parse Emulab's topomap into netjson")
219 220 221
    parser.add_argument("--in-file", action='store', default='/var/emulab/boot/topomap', type=str,
                        help="Path to the netinfo file to parse")
    parser.add_argument("--out-file", action='store', default='./netinfo.json', type=str,
222
                        help="Path to the where the result should be written. Existing file will be overwritten")
223 224 225

    args = parser.parse_args()

226
    netjson = parse_topomap_to_netjson(args.in_file)
227 228

    with open(args.out_file, 'w') as out_file:
229
        out_file.write(json.dumps(netjson))