package main import "flag" import "io" import "log" import "net/http" import "encoding/json" import "io/ioutil" import "github.com/golang/protobuf/proto" import pb "git.wit.com/wit/witProtobuf" import "github.com/gorilla/websocket" import "github.com/davecgh/go-spew/spew" const ( API = "http://stackapi:4000/" MAX_NETS = 10 MAX_VMS = 10 ) type network struct { Subdomain string `json:"subdomain"` } func checkLogin(token string) bool { var networks []network req, err := http.NewRequest("GET", API + "me", nil) if err != nil { log.Println("can't make new req") return false } req.Header.Set("X-Wit-Auth", token) client := &http.Client{} resp, err := client.Do(req) if err != nil { log.Println("Can't exec the req to list networks: %s", err) return false } body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Println("can't read resp") return false } log.Printf("RESPONSE =", body) if body == nil { log.Println("RESPONSE is nil") return false } else { len := len(body) err = json.Unmarshal(body, &networks) if err != nil { log.Println("body = ", body) log.Println("body len = ", len) log.Println("can't unmarshal resp for list networks: %s", err) return false } } spew.Dump(networks) return true } func fetchNetworks(token string) []network { var networks []network req, err := http.NewRequest("GET", API + "clusters", nil) if err != nil { log.Fatal("can't make new req") } req.Header.Set("X-Wit-Auth", token) client := &http.Client{} resp, err := client.Do(req) if err != nil { log.Printf("Can't exec the req to list networks: %s", err) } body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal("can't read resp") } log.Printf("NETWORKS =", body) if body == nil { log.Println("networks is nil") } else { len := len(body) err = json.Unmarshal(body, &networks) if err != nil { log.Println("body = ", body) log.Println("body len = ", len) log.Println("can't unmarshal resp for list networks: %s", err) } } spew.Dump(networks) return networks } /* { "name": "vm10", "cpu": 4, "ram": 2048, "created_on": "2019-03-18T19:22:10.755428Z", "scope": "private", "role": "k8s-node", "stage": "Creating...", "seconds_left": 300, "base_image": "debcore_guest_latest", "address_list": [ "192.168.0.1/32" ] }, */ type address struct { Address string } type vm struct { Name string `json:"name"` Role string `json:"role"` BaseImage string `json:"base_image"` } func fetchVMs(token string, network string) []vm { var vms []vm req, err := http.NewRequest("GET", API + "vms/" + network, nil) if err != nil { log.Fatal("can't make new req") } req.Header.Set("X-Wit-Auth", token) client := &http.Client{} resp, err := client.Do(req) if err != nil { log.Printf("Can't exec the req to fetch vms for %s: %s", network, err) } body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal("can't read resp") } err = json.Unmarshal(body, &vms) if err != nil { log.Fatal("can't unmarshal resp for fetch vms: ", err, "\n\n", network, string(body)) } spew.Dump(vms) return vms } func processGetEvent(ge *pb.Event) *pb.Event { log.Println("processGetEvent() START") log.Println("processGetEvent() ge.Token =", ge.Token) e := pb.Event{} networks := fetchNetworks(ge.Token) for i, network := range(networks) { if i >= MAX_NETS { break } log.Println("network.Subdomain =",network.Subdomain) log.Println("network=",network) enetwork := pb.Event_Network{} enetwork.Name = network.Subdomain e.Networks = append(e.Networks, &enetwork) vms := fetchVMs(ge.Token, network.Subdomain) for j, vm := range(vms) { if j >= MAX_VMS { break } evm := pb.Event_VM{} evm.Name = vm.Name evm.Cpus = 1 evm.Memory = 512 evm.Disk = 20 evm.Hostname = vm.Name + "." + enetwork.Name + ".lab.wit.com" e.Vms = append(e.Vms, &evm) log.Println("\tvm.Name =",vm.Name) log.Println("\tvm =",vm) } } return &e } func processLoginEvent(ge *pb.Event) *pb.Event { log.Println("processLoginEvent() START") log.Println("processLoginEvent() ge.Token =", ge.Token) log.Println("processLoginEvent() NEED TO LOGIN HERE OR CHECK TOKEN WORKS") checkLogin(ge.Token) log.Println("processLoginEvent() END") e := pb.Event{} return &e } // Also potentially look at: // https://www.reddit.com/r/golang/comments/boznnz/an_alternative_to_gorilla_sessions_jeff_manage/ var upgrader = websocket.Upgrader{ ReadBufferSize: 4096, WriteBufferSize: 4096, EnableCompression: true, CheckOrigin: func(r *http.Request) bool { return true }, } /* func sendSampleProtobuf(conn *websocket.Conn) { msg := pb.CreateSampleEvent() msg.Name = "test echo over gorilla websocket" data, _ := proto.Marshal(msg) err := conn.WriteMessage(websocket.BinaryMessage, data) if err != nil { log.Println("sendProtobuf() write:", err) } } */ func sendProtobuf(conn *websocket.Conn, msg *pb.Event) { data, _ := proto.Marshal(msg) err := conn.WriteMessage(websocket.BinaryMessage, data) if err != nil { log.Println("sendProtobuf() write:", err) } } func eventHandler(w http.ResponseWriter, r *http.Request) { log.Println("echoHandler() START") log.Println("echoHandler() ATTEMPT r.Header.Get", r.Header.Get("User-Agent")) log.Println("echoHandler() ATTEMPT r.Header", r.Header) for key, value := range r.Header { log.Println("echoHandler() HEADER key, value =", key, value) } conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Upgrade:", err) return } defer conn.Close() for { mytype, message, err := conn.ReadMessage() if err != nil { log.Println("read:", err) return } if mytype == websocket.TextMessage { log.Println("echoHandler() TextMessage mytype=", mytype) } if mytype == websocket.BinaryMessage { log.Println("echoHandler() BinaryMessage mytype=", mytype) pdata := new(pb.Event) err = proto.Unmarshal(message, pdata) if (err != nil) { log.Printf("readConn() something fucked up happened in Unmarshal") } log.Printf("recv binary: %s", pdata) if pdata.Type == pb.Event_MIGRATE { log.Printf("GOT MIGRATE") e := processGetEvent(pdata) sendProtobuf(conn, e) } if pdata.Type == pb.Event_LOGIN { log.Printf("GOT LOGIN") e := processLoginEvent(pdata) sendProtobuf(conn, e) } if pdata.Type == pb.Event_GET { log.Printf("GOT GET") e := processGetEvent(pdata) sendProtobuf(conn, e) } } } } func serveHome(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "Not found.", http.StatusNotFound) return } if r.Method != "GET" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") io.WriteString(w, "Echo Server") } var addr = flag.String("addr", ":9000", "http service address") func main() { flag.Parse() http.HandleFunc("/", serveHome) http.HandleFunc("/event", eventHandler) log.Println("Starting http.ListenAndServe() on port 9000") err := http.ListenAndServe(*addr, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }