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{} |
Filip Tehlar | 229f5fc | 2022-08-09 14:44:47 +0000 | [diff] [blame] | 14 | |
| 15 | type YamlTopology struct { |
| 16 | Devices []NetDevConfig `yaml:"devices"` |
Maros Ondrejicka | db823ed | 2022-12-14 16:30:04 +0100 | [diff] [blame^] | 17 | Containers []ContainerConfig `yaml:"containers"` |
| 18 | Volumes []string `yaml:"volumes"` |
Filip Tehlar | 229f5fc | 2022-08-09 14:44:47 +0000 | [diff] [blame] | 19 | } |
| 20 | |
| 21 | func 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 | |
| 31 | func 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 | |
| 39 | func 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 | |
| 55 | func 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 | } |