github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/libnetwork/cmd/networkdb-test/dbserver/ndbServer.go (about) 1 package dbserver 2 3 import ( 4 "errors" 5 "fmt" 6 "log" 7 "net" 8 "net/http" 9 "os" 10 "strconv" 11 12 "github.com/docker/docker/libnetwork/cmd/networkdb-test/dummyclient" 13 "github.com/docker/docker/libnetwork/diagnostic" 14 "github.com/docker/docker/libnetwork/networkdb" 15 "github.com/sirupsen/logrus" 16 ) 17 18 var nDB *networkdb.NetworkDB 19 var server *diagnostic.Server 20 var ipAddr string 21 22 var testerPaths2Func = map[string]diagnostic.HTTPHandlerFunc{ 23 "/myip": ipaddress, 24 } 25 26 func ipaddress(ctx interface{}, w http.ResponseWriter, r *http.Request) { 27 fmt.Fprintf(w, "%s\n", ipAddr) 28 } 29 30 // Server starts the server 31 func Server(args []string) { 32 logrus.Infof("[SERVER] Starting with arguments %v", args) 33 if len(args) < 1 { 34 log.Fatal("Port number is a mandatory argument, aborting...") 35 } 36 port, _ := strconv.Atoi(args[0]) 37 var localNodeName string 38 var ok bool 39 if localNodeName, ok = os.LookupEnv("TASK_ID"); !ok { 40 log.Fatal("TASK_ID environment variable not set, aborting...") 41 } 42 logrus.Infof("[SERVER] Starting node %s on port %d", localNodeName, port) 43 44 ip, err := getIPInterface("eth0") 45 if err != nil { 46 logrus.Errorf("%s There was a problem with the IP %s\n", localNodeName, err) 47 return 48 } 49 ipAddr = ip 50 logrus.Infof("%s uses IP %s\n", localNodeName, ipAddr) 51 52 server = diagnostic.New() 53 server.Init() 54 conf := networkdb.DefaultConfig() 55 conf.Hostname = localNodeName 56 conf.AdvertiseAddr = ipAddr 57 conf.BindAddr = ipAddr 58 nDB, err = networkdb.New(conf) 59 if err != nil { 60 logrus.Infof("%s error in the DB init %s\n", localNodeName, err) 61 return 62 } 63 64 // Register network db handlers 65 server.RegisterHandler(nDB, networkdb.NetDbPaths2Func) 66 server.RegisterHandler(nil, testerPaths2Func) 67 server.RegisterHandler(nDB, dummyclient.DummyClientPaths2Func) 68 server.EnableDiagnostic("", port) 69 // block here 70 select {} 71 } 72 73 func getIPInterface(name string) (string, error) { 74 ifaces, err := net.Interfaces() 75 if err != nil { 76 return "", err 77 } 78 for _, iface := range ifaces { 79 if iface.Name != name { 80 continue // not the name specified 81 } 82 83 if iface.Flags&net.FlagUp == 0 { 84 return "", errors.New("Interfaces is down") 85 } 86 87 addrs, err := iface.Addrs() 88 if err != nil { 89 return "", err 90 } 91 for _, addr := range addrs { 92 var ip net.IP 93 switch v := addr.(type) { 94 case *net.IPNet: 95 ip = v.IP 96 case *net.IPAddr: 97 ip = v.IP 98 } 99 if ip == nil || ip.IsLoopback() { 100 continue 101 } 102 ip = ip.To4() 103 if ip == nil { 104 continue 105 } 106 return ip.String(), nil 107 } 108 return "", errors.New("Interfaces does not have a valid IPv4") 109 } 110 return "", errors.New("Interface not found") 111 }