blob: 1d501e8f2da192dcfd20032c0e6f908df15afe96 [file] [log] [blame]
Filip Tehlar229f5fc2022-08-09 14:44:47 +00001package main
2
3import (
4 "fmt"
5 "io/ioutil"
6 "os"
7 "strings"
8
9 "gopkg.in/yaml.v3"
10)
11
12type NetDevConfig map[string]interface{}
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010013type ContainerConfig map[string]interface{}
Filip Tehlar229f5fc2022-08-09 14:44:47 +000014
15type YamlTopology struct {
16 Devices []NetDevConfig `yaml:"devices"`
Maros Ondrejickadb823ed2022-12-14 16:30:04 +010017 Containers []ContainerConfig `yaml:"containers"`
18 Volumes []string `yaml:"volumes"`
Filip Tehlar229f5fc2022-08-09 14:44:47 +000019}
20
21func AddAddress(device, address, ns string) error {
22 c := []string{"ip", "addr", "add", address, "dev", device}
23 cmd := appendNetns(c, ns)
24 err := cmd.Run()
25 if err != nil {
26 return fmt.Errorf("failed to set ip address for %s: %v", device, err)
27 }
28 return nil
29}
30
31func convertToNetConfig(t *YamlTopology) (*NetTopology, error) {
32 var topology NetTopology
33 for _, dev := range t.Devices {
34 topology = append(topology, NewNetConfig(dev))
35 }
36 return &topology, nil
37}
38
39func loadTopoFile(topoName string) (*NetTopology, error) {
40 var yamlTopo YamlTopology
41
42 data, err := ioutil.ReadFile(topoName)
43 if err != nil {
44 return nil, fmt.Errorf("read error: %v", err)
45 }
46
47 err = yaml.Unmarshal(data, &yamlTopo)
48 if err != nil {
49 return nil, fmt.Errorf("error parsing topology data: %v", err)
50 }
51
52 return convertToNetConfig(&yamlTopo)
53}
54
55func LoadTopology(path, topoName string) (*NetTopology, error) {
56 dir, err := os.Open(path)
57 if err != nil {
58 return nil, err
59 }
60 defer dir.Close()
61
62 files, err := dir.Readdir(0)
63 if err != nil {
64 return nil, err
65 }
66
67 for i := range files {
68 file := files[i]
69 fileName := file.Name()
70
71 // cut off file extension
72 f := strings.Split(fileName, ".")[0]
73 if f == topoName {
74 return loadTopoFile(path + fileName)
75 }
76 }
77 return nil, fmt.Errorf("topology '%s' not found", topoName)
78}