Filip Tehlar | 229f5fc | 2022-08-09 14:44:47 +0000 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io/ioutil" |
| 6 | "os" |
| 7 | "strings" |
| 8 | |
| 9 | "gopkg.in/yaml.v3" |
| 10 | ) |
| 11 | |
| 12 | type NetDevConfig map[string]interface{} |
Maros Ondrejicka | db823ed | 2022-12-14 16:30:04 +0100 | [diff] [blame] | 13 | type ContainerConfig map[string]interface{} |
Maros Ondrejicka | f719adf | 2022-12-20 15:10:50 +0100 | [diff] [blame] | 14 | type VolumeConfig map[string]interface{} |
Filip Tehlar | 229f5fc | 2022-08-09 14:44:47 +0000 | [diff] [blame] | 15 | |
| 16 | type YamlTopology struct { |
Filip Tehlar | f3ee2b6 | 2023-01-09 12:07:09 +0100 | [diff] [blame] | 17 | Devices []NetDevConfig `yaml:"devices"` |
Maros Ondrejicka | db823ed | 2022-12-14 16:30:04 +0100 | [diff] [blame] | 18 | Containers []ContainerConfig `yaml:"containers"` |
Maros Ondrejicka | f719adf | 2022-12-20 15:10:50 +0100 | [diff] [blame] | 19 | Volumes []VolumeConfig `yaml:"volumes"` |
Filip Tehlar | 229f5fc | 2022-08-09 14:44:47 +0000 | [diff] [blame] | 20 | } |
| 21 | |
| 22 | func 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 | |
| 32 | func 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 | |
| 40 | func 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 | |
| 56 | func 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 | } |