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