func newNode(commands ...string) { switch commands[0] { case "host": var name string if len(commands) == 2 { name = commands[1] } h, err := mn.NewHost(name) if err != nil { log.Println(err) return } fmt.Println("Host", h.NodeName(), "created") scheme.AddNode(h) case "router": var name string if len(commands) == 2 { name = commands[1] } h, err := mn.NewRouter(name) if err != nil { log.Println(err) return } fmt.Println("Host", h.NodeName(), "created") scheme.AddNode(h) case "switch": var name string if len(commands) == 2 { name = commands[1] } s, err := mn.NewSwitch(name) if err != nil { log.Println(err) return } fmt.Println("Switch", s.NodeName(), "created") scheme.AddNode(s) names = append(names, s.NodeName()) case "link": var left, right mn.Link args := commands[1:] if len(args) < 2 { log.Println("At least two nodes required, e.g.: new link a,b") return } n1 := args[0] n2 := args[1] if len(args) >= 3 && args[2] != "" { if err := json.Unmarshal([]byte(args[2]), &left); err != nil { log.Println(err) return } } if len(args) >= 4 && args[3] != "" { if err := json.Unmarshal([]byte(args[3]), &right); err != nil { log.Println(err) return } } node1, found := scheme.GetNode(n1) if !found { log.Println("No such node:", n1, "create it first") return } node2, found := scheme.GetNode(n2) if !found { log.Println("No such node:", n2, "create it first") return } pair := mn.NewLink(node1, node2, left, right) if err := pair.Create(); err != nil { log.Println("Unable to create pair:", err) return } pair, err := pair.Up() if err != nil { log.Println("Can't bring it up,", err) } node1.AddLink(pair.Left) node2.AddLink(pair.Right) if pair.IsPatch() { fmt.Println("[Patch]", node1.NodeName(), "<--->", node2.NodeName()) } return } }
func main() { // creating and instance of Scheme struct, which is just a // a storage for futher nodes scheme := mn.NewScheme() defer scheme.Release() // create new host h1 host1, err := mn.NewHost("h1") if err != nil { panic(err) } // create new switch with random name sw, err := mn.NewSwitch() if err != nil { panic(err) } // interconnect nodes pair := mn.NewLink(sw, host1, mn.Link{Cidr: "noip"}, mn.Link{Cidr: "192.168.44.1/24"}) // physically create link if err := pair.Create(); err != nil { panic(err) } // apply cidr, routes, bring interfaces up pair, err = pair.Up() if err != nil { panic(err) } sw.AddLink(pair.Left) host1.AddLink(pair.Right) scheme.AddNode(host1) scheme.AddNode(sw) // repeat for host2 host2, err := mn.NewHost("h2") if err != nil { panic(err) } pair2 := mn.NewLink(sw, host2, mn.Link{Cidr: "noip"}, mn.Link{Cidr: "192.168.44.2/24"}) if err := pair2.Create(); err != nil { panic(err) } pair2, err = pair2.Up() if err != nil { panic(err) } sw.AddLink(pair2.Left) host2.AddLink(pair2.Right) scheme.AddNode(host2) // now we can run some command host1.RunProcess("ping", "-c1", "192.168.44.2") time.Sleep(time.Second * 1) }