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