topogen 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
topogen/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """topogen topology generator"""
2
+
3
+ import importlib.metadata as importlib_metadata
4
+
5
+ from .config import Config
6
+ from .render import Renderer
7
+ from .main import main
8
+
9
+ _metadata = importlib_metadata.metadata("topogen")
10
+ __version__ = _metadata["Version"]
11
+ __description__ = _metadata["Summary"]
12
+
13
+
14
+ __all__ = ["Config", "Renderer", "main"]
topogen/colorlog.py ADDED
@@ -0,0 +1,36 @@
1
+ """
2
+ colorful log message formatter
3
+ based on
4
+ https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
5
+
6
+ """
7
+
8
+ import logging
9
+
10
+
11
+ class CustomFormatter(logging.Formatter):
12
+ """return a formatter that prints log messages with color"""
13
+
14
+ grey = "\x1b[38;20m"
15
+ yellow = "\x1b[33;20m"
16
+ red = "\x1b[31;20m"
17
+ cyan = "\x1b[36;20m"
18
+ bold_red = "\x1b[31;1m"
19
+ reset = "\x1b[0m"
20
+ template = (
21
+ # "%(asctime)s - %(levelname)s - %(name)s - %(message)s (%(filename)s:%(lineno)d)"
22
+ "%(asctime)s - %(message)s - (%(filename)s:%(lineno)d)"
23
+ )
24
+
25
+ FORMATS = {
26
+ logging.DEBUG: grey + template + reset,
27
+ logging.INFO: cyan + template + reset,
28
+ logging.WARNING: yellow + template + reset,
29
+ logging.ERROR: red + template + reset,
30
+ logging.CRITICAL: bold_red + template + reset,
31
+ }
32
+
33
+ def format(self, record):
34
+ log_fmt = self.FORMATS.get(record.levelno)
35
+ formatter = logging.Formatter(log_fmt)
36
+ return formatter.format(record)
topogen/config.py ADDED
@@ -0,0 +1,43 @@
1
+ """configuration for topogen"""
2
+
3
+ import logging
4
+ from dataclasses import dataclass
5
+ from ipaddress import IPv4Network
6
+
7
+ from serde import deserialize, serialize, SerdeError
8
+ from serde.toml import from_toml, to_toml
9
+
10
+ _LOGGER = logging.getLogger(__name__)
11
+
12
+
13
+ @deserialize
14
+ @serialize
15
+ @dataclass
16
+ class Config:
17
+ """topology generator configuration"""
18
+
19
+ loopbacks: IPv4Network = IPv4Network("10.0.0.0/8")
20
+ p2pnets: IPv4Network = IPv4Network("172.16.0.0/12")
21
+ nameserver: str = "8.8.8.8"
22
+ domainname: str = "virl.lab"
23
+ username: str = "cisco"
24
+ password: str = "cisco"
25
+
26
+ @classmethod
27
+ def load(cls, filename: str) -> "Config":
28
+ """load the configuration from the given file"""
29
+ try:
30
+ with open(filename, encoding="utf-8") as handle:
31
+ cfg = from_toml(cls, handle.read())
32
+ _LOGGER.info("Configuration loaded from file %s", filename)
33
+ except (FileNotFoundError, TypeError, SerdeError) as exc:
34
+ if not isinstance(exc, FileNotFoundError):
35
+ _LOGGER.error(exc)
36
+ cfg = cls()
37
+ _LOGGER.warning("using configuration defaults")
38
+ return cfg
39
+
40
+ def save(self, filename: str):
41
+ """save the configuration to the given file"""
42
+ with open(filename, "w+", encoding="utf-8") as handle:
43
+ handle.write(to_toml(self))
topogen/dnshost.py ADDED
@@ -0,0 +1,112 @@
1
+ """configuration template for a DNS host"""
2
+
3
+ from textwrap import dedent
4
+
5
+ from jinja2 import BaseLoader, Environment
6
+
7
+ from topogen.config import Config
8
+ from topogen.models import DNShost, TopogenNode
9
+
10
+
11
+ def dnshostconfig(cfg: Config, node: TopogenNode, hosts: list[DNShost]) -> str:
12
+ """renders the DNS host template"""
13
+ basic_config = dedent(
14
+ r"""
15
+ # this is a shell script which will be sourced at boot
16
+ hostname {{ node.hostname }}
17
+ # configurable user account
18
+ USERNAME={{ config.username }}
19
+ # consider to configure a strong password here instead of the var
20
+ PASSWORD={{ config.password }}
21
+
22
+ # if static IP is needed on this gateway host:
23
+ #
24
+ # ifdown eth0
25
+ # cat <<EOF >/etc/network/interfaces
26
+ # auto lo
27
+ # iface lo inet loopback
28
+ #
29
+ # auto eth0
30
+ # iface eth0 inet static
31
+ # hostname dns-host
32
+ # address 172.16.5.10/25
33
+ # gateway 172.16.5.1
34
+ # EOF
35
+ #
36
+ # cat <<EOF >/etc/resolv.conf
37
+ # nameserver 1.2.3.4 1.2.3.5
38
+ # search corp.com
39
+ # EOF
40
+ # ifup eth0
41
+
42
+ # if a proxy is needed, add it here
43
+ #
44
+ # export HTTPS_PROXY="http://proxy.corp.com:80/"
45
+ # export HTTP_PROXY="http://proxy.corp.com:80/"
46
+
47
+ apk update
48
+ apk add dnsmasq iptables
49
+
50
+ cat <<EOF >/etc/dnsmasq.conf
51
+ domain-needed
52
+ bogus-priv
53
+ resolv-file=/etc/resolv.dnsmasq
54
+ no-poll
55
+ local=/{{ config.domainname }}/
56
+ interface=eth1
57
+ no-dhcp-interface=eth1
58
+ log-queries
59
+ conf-dir=/etc/dnsmasq.d/,*.conf
60
+ EOF
61
+
62
+ ip link set eth1 up
63
+ ip address add {{ node.interfaces[0].address }} dev eth1
64
+ ip route add {{ config.loopbacks }} via {{ node.interfaces[1].address.ip }}
65
+ ip route add {{ config.p2pnets }} via {{ node.interfaces[1].address.ip }}
66
+
67
+ {%- for host in hosts %}
68
+ echo -e "{{ host.ipv4 }}\t{{ host.name }}.{{ config.domainname }}" >>/etc/hosts
69
+ {%- endfor %}
70
+
71
+ cp /etc/resolv.conf /etc/resolv.dnsmasq
72
+ cat <<EOF >/etc/resolv.conf
73
+ nameserver 127.0.0.1
74
+ search {{ config.domainname }}
75
+ EOF
76
+
77
+ # configure SSH params
78
+ SSH_DIR=/home/{{ config.username }}/.ssh
79
+ mkdir -p $SSH_DIR
80
+ chown {{ config.username }}.{{ config.username }} $SSH_DIR
81
+ cat <<EOF >$SSH_DIR/config
82
+ # this is NOT secure but we can not truly differentiate CIDR
83
+ # notation network prefixes as given by the config and have a
84
+ # matching host line...
85
+ # if grepcidr (http://www.pc-tools.net/unix/grepcidr/) would be
86
+ # available, then we could do something like this
87
+ #
88
+ # Match exec "grepcidr {{ config.loopbacks }} <(echo %h) &>/dev/null"
89
+ # KexAlgorithms
90
+ # ...
91
+ # instead we allow this globally (insecure but good enough for a virtual
92
+ # lab)
93
+ KexAlgorithms +diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
94
+ EOF
95
+
96
+ # prevent UDHCPC from overwriting resolv.conf
97
+ UDHCPC="/etc/udhcpc"
98
+ UDHCPC_CONF="$UDHCPC/udhcpc.conf"
99
+ mkdir -p "$UDHCPC"
100
+
101
+ echo "NO_DNS=eth0" >$UDHCPC_CONF
102
+
103
+ # make it a router, masquerading outgoing packets
104
+ iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
105
+ echo 1 > /proc/sys/net/ipv4/ip_forward
106
+
107
+ service dnsmasq start
108
+ """
109
+ )
110
+
111
+ template = Environment(loader=BaseLoader).from_string(basic_config) # type: ignore
112
+ return template.render(node=node, config=cfg, hosts=hosts)
topogen/lxcfrr.py ADDED
@@ -0,0 +1,33 @@
1
+ """configuration template for a LXC frr host"""
2
+
3
+ from textwrap import dedent
4
+
5
+ from jinja2 import BaseLoader, Environment
6
+
7
+ from topogen.config import Config
8
+ from topogen.models import TopogenNode
9
+
10
+
11
+ def lxcfrr_bootconfig(
12
+ cfg: Config, node: TopogenNode, protocols: list[str], nameserver: str, dhcp: bool
13
+ ) -> str:
14
+ """renders the LXC FRR boot.sh config"""
15
+ basic_config = dedent(
16
+ r"""
17
+ #/bin/bash
18
+ {%- if dhcp %}
19
+ /sbin/udhcpc -i eth0
20
+ {%- endif %}
21
+ sed -r -e 's/^#(MAX_FDS=1024)$/\1/' -i /etc/frr/daemons
22
+ {%- for proto in protocols %}
23
+ sed -r -e 's/^({{ proto }}d=)no$/\1yes/' -i /etc/frr/daemons
24
+ {%- endfor %}
25
+ echo "nameserver {{ nameserver }}" >/etc/resolv.conf
26
+ echo "search {{ config.domainname }}" >>/etc/resolv.conf
27
+ """
28
+ ).lstrip("\n")
29
+
30
+ template = Environment(loader=BaseLoader).from_string(basic_config) # type: ignore
31
+ return template.render(
32
+ node=node, config=cfg, protocols=protocols, nameserver=nameserver, dhcp=dhcp
33
+ )
topogen/main.py ADDED
@@ -0,0 +1,186 @@
1
+ """
2
+ a static topology generator
3
+ argument parsing and logging
4
+ """
5
+
6
+ import argparse
7
+ import logging
8
+ import os
9
+ import sys
10
+
11
+ import topogen
12
+ from topogen.models import TopogenError
13
+ from topogen.render import Renderer, get_templates
14
+ from topogen.colorlog import CustomFormatter
15
+
16
+ _LOGGER = logging.getLogger(__name__)
17
+
18
+
19
+ def valid_node_count(value):
20
+ ivalue = int(value)
21
+ if ivalue < 2 or ivalue > 1000:
22
+ raise argparse.ArgumentTypeError(
23
+ f"invalid value {value}. Valid values are from 2-1000."
24
+ )
25
+ return ivalue
26
+
27
+
28
+ def create_argparser():
29
+ """create the argparser for topogen"""
30
+ parser = argparse.ArgumentParser(
31
+ prog=topogen.__name__, description=topogen.__description__
32
+ )
33
+ config_settings = parser.add_argument_group("configuration")
34
+
35
+ config_settings.add_argument(
36
+ "-c",
37
+ "--config",
38
+ dest="configfile",
39
+ help="Use the configuration from this file, defaults to %(default)s",
40
+ default="config.toml",
41
+ )
42
+ config_settings.add_argument(
43
+ "-w",
44
+ "--write",
45
+ dest="writeconfig",
46
+ action="store_true",
47
+ help="Write the default configuration to a file and exit",
48
+ default=False,
49
+ )
50
+ config_settings.add_argument(
51
+ "-v", "--version", action="version", version=f"%(prog)s {topogen.__version__}"
52
+ )
53
+ config_settings.add_argument(
54
+ "-l",
55
+ "--loglevel",
56
+ type=str,
57
+ default=os.environ.get("LOG_LEVEL", "WARN"),
58
+ help="DEBUG, INFO, WARN, ERROR, CRITICAL, defaults to %(default)s",
59
+ )
60
+ config_settings.add_argument(
61
+ "-p",
62
+ "--progress",
63
+ action="store_true",
64
+ help="show a progress bar",
65
+ )
66
+
67
+ parser.add_argument(
68
+ "--ca",
69
+ dest="cafile",
70
+ help="Use the CA certificate from this file (PEM format), defaults to %(default)s",
71
+ default="ca.pem",
72
+ )
73
+ parser.add_argument(
74
+ "-i",
75
+ "--insecure",
76
+ action="store_true",
77
+ help="If no CA provided, do not verify TLS (insecure!)",
78
+ default=False,
79
+ )
80
+ parser.add_argument(
81
+ "-d",
82
+ "--distance",
83
+ type=int,
84
+ default=200,
85
+ help="Node distance, default %(default)d",
86
+ )
87
+ parser.add_argument(
88
+ "-L",
89
+ "--labname",
90
+ type=str,
91
+ default="topogen lab",
92
+ help='Lab name to create, default "%(default)s"',
93
+ )
94
+ parser.add_argument(
95
+ "-T",
96
+ "--template",
97
+ type=str,
98
+ help='Template name to use, defaults to "%(default)s"',
99
+ default="iosv",
100
+ )
101
+ parser.add_argument(
102
+ "--list-templates",
103
+ dest="listtemplates",
104
+ action="store_true",
105
+ help="List all available templates",
106
+ )
107
+ parser.add_argument(
108
+ "-m",
109
+ "--mode",
110
+ choices=("nx", "simple"),
111
+ default="simple",
112
+ help='mode of operation, default is "%(default)s"',
113
+ )
114
+ parser.add_argument(
115
+ "nodes",
116
+ nargs="?",
117
+ type=valid_node_count,
118
+ help="Number of nodes to generate (2-1000)",
119
+ )
120
+ return parser
121
+
122
+
123
+ def get_log_level(level_name: str) -> tuple[int, bool]:
124
+ log_levels = {
125
+ "CRITICAL": logging.CRITICAL,
126
+ "ERROR": logging.ERROR,
127
+ "WARN": logging.WARNING,
128
+ "WARNING": logging.WARNING,
129
+ "INFO": logging.INFO,
130
+ "DEBUG": logging.DEBUG,
131
+ "NOTSET": logging.NOTSET,
132
+ }
133
+ level_name = level_name.upper()
134
+ if level_name in log_levels:
135
+ return log_levels[level_name], False
136
+ else:
137
+ return logging.WARNING, True
138
+
139
+
140
+ def setup_logging(loglevel: str):
141
+ """sets up the logging, takes the given loglevel and uses the custom,
142
+ colorful log formatter
143
+ """
144
+ logging.basicConfig(level=logging.WARN)
145
+ level, unknown_loglevel = get_log_level(loglevel)
146
+ logging.root.setLevel(level)
147
+ custom_formatter = CustomFormatter()
148
+ for handler in logging.root.handlers:
149
+ handler.setFormatter(custom_formatter)
150
+ if unknown_loglevel:
151
+ _LOGGER.warning("Unknown log level: %s", loglevel.upper())
152
+
153
+
154
+ def main():
155
+ """main function, returns 0 on success, 1 otherwise"""
156
+ parser = create_argparser()
157
+ args = parser.parse_args()
158
+ setup_logging(args.loglevel)
159
+
160
+ cfg = topogen.Config.load(args.configfile)
161
+ if args.writeconfig:
162
+ cfg.save(args.configfile)
163
+ return 0
164
+
165
+ if args.insecure:
166
+ args.cafile = None
167
+
168
+ if args.listtemplates:
169
+ print("Available templates: ", ", ".join(get_templates()))
170
+ return 0
171
+
172
+ try:
173
+ renderer = Renderer(args, cfg)
174
+ # argparse ensures correct mode
175
+ if args.mode == "simple":
176
+ retval = renderer.render_node_sequence()
177
+ else: # args.mode == "nx":
178
+ retval = renderer.render_node_network()
179
+ except TopogenError as exc:
180
+ _LOGGER.error(exc)
181
+ retval = 1
182
+ return retval
183
+
184
+
185
+ if __name__ == "__main__":
186
+ sys.exit(main())
topogen/models.py ADDED
@@ -0,0 +1,70 @@
1
+ """models for topogen topology generator"""
2
+
3
+ from dataclasses import dataclass, replace
4
+ from ipaddress import IPv4Address, IPv4Interface
5
+
6
+
7
+ class TopogenError(Exception):
8
+ """Base class for all errors raised by topogen"""
9
+
10
+
11
+ @dataclass
12
+ class Point:
13
+ """a point in a carthesian coordinate system"""
14
+
15
+ x: int
16
+ y: int
17
+
18
+
19
+ class CoordsGenerator:
20
+ """a generator which generates square spiral coordinates"""
21
+
22
+ DIRSM = {"l": "u", "u": "r", "r": "d", "d": "l"}
23
+
24
+ def __init__(self, distance: int = 200):
25
+ self.distance = distance
26
+ self.step = 1
27
+ self.dir = "u"
28
+ self.point = Point(0, 0)
29
+
30
+ def __iter__(self):
31
+ while True:
32
+ for _ in (0, 1):
33
+ for _ in range(self.step):
34
+ yield replace(self.point)
35
+ if self.dir == "u":
36
+ self.point.y += self.distance
37
+ elif self.dir == "r":
38
+ self.point.x += self.distance
39
+ elif self.dir == "d":
40
+ self.point.y -= self.distance
41
+ else: # self.dir == "l"
42
+ self.point.x -= self.distance
43
+ self.dir = CoordsGenerator.DIRSM[self.dir]
44
+ self.step += 1
45
+
46
+
47
+ @dataclass
48
+ class TopogenInterface:
49
+ """interface of a node, slot is the physical slot in the device"""
50
+
51
+ address: IPv4Interface
52
+ description: str = ""
53
+ slot: int = 0
54
+
55
+
56
+ @dataclass
57
+ class TopogenNode:
58
+ """a node of a topology"""
59
+
60
+ hostname: str
61
+ loopback: IPv4Interface | None
62
+ interfaces: list[TopogenInterface]
63
+
64
+
65
+ @dataclass
66
+ class DNShost:
67
+ """a DNS host of a topology, this typically only exists once"""
68
+
69
+ name: str
70
+ ipv4: IPv4Address