github.com/sbuss/deis@v1.6.1/swarm/swarm.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io/ioutil" 8 "log" 9 "net/http" 10 "os" 11 "os/exec" 12 "strings" 13 "text/template" 14 "time" 15 16 "github.com/coreos/go-etcd/etcd" 17 "github.com/deis/deis/tests/utils" 18 ) 19 20 //Response struct 21 type Response struct { 22 ClientURL string `json:"clientURL"` 23 Name string `json:"name"` 24 PeerURL string `json:"peerURL"` 25 State string `json:"state"` 26 } 27 28 const ( 29 swarmpath = "/deis/scheduler/swarm/node" 30 swarmetcd = "/deis/scheduler/swarm/host" 31 etcdport = "4001" 32 timeout time.Duration = 3 * time.Second 33 ttl time.Duration = timeout * 2 34 ) 35 36 func run(cmd string) { 37 var cmdBuf bytes.Buffer 38 tmpl := template.Must(template.New("cmd").Parse(cmd)) 39 if err := tmpl.Execute(&cmdBuf, nil); err != nil { 40 log.Fatal(err) 41 } 42 cmdString := cmdBuf.String() 43 fmt.Println(cmdString) 44 var cmdl *exec.Cmd 45 cmdl = exec.Command("sh", "-c", cmdString) 46 if _, _, err := utils.RunCommandWithStdoutStderr(cmdl); err != nil { 47 log.Fatal(err) 48 } else { 49 fmt.Println("ok") 50 } 51 } 52 53 func getleaderHost() string { 54 var response []Response 55 var host string 56 client := &http.Client{} 57 resp, _ := client.Get("http://" + os.Getenv("HOST") + ":7001/v2/admin/machines") 58 defer resp.Body.Close() 59 body, _ := ioutil.ReadAll(resp.Body) 60 json.Unmarshal(body, &response) 61 for _, node := range response { 62 if node.State == "leader" { 63 host = strings.Split(node.ClientURL, "//")[1] 64 } 65 } 66 return host 67 } 68 69 func publishService(client *etcd.Client, host string, ttl uint64) { 70 for { 71 setEtcd(client, swarmetcd, host, ttl) 72 time.Sleep(timeout) 73 } 74 } 75 76 func setEtcd(client *etcd.Client, key, value string, ttl uint64) { 77 _, err := client.Set(key, value, ttl) 78 if err != nil { 79 log.Println(err) 80 } 81 } 82 func main() { 83 etcdproto := "etcd://" + getleaderHost() + swarmpath 84 etcdhost := os.Getenv("HOST") 85 addr := "--addr=" + etcdhost + ":2375" 86 client := etcd.NewClient([]string{"http://" + etcdhost + ":" + etcdport}) 87 switch os.Args[1] { 88 case "join": 89 run("./deis-swarm join " + addr + " " + etcdproto) 90 case "manage": 91 go publishService(client, etcdhost, uint64(ttl.Seconds())) 92 run("./deis-swarm manage " + etcdproto) 93 } 94 }