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" import "github.com/tidwall/gjson" // const API = "http://stackapi:4000/" type network struct { Subdomain string `json:"subdomain"` } /* func checkLogin(ge *pb.Event) bool { if (ge.Account == nil) { log.Println("checkLogin() pb.Event.Account == nil ERROR") return false } if (origLoginCheck(ge) == true) { log.Println("checkLogin() LOGIN WORKED") return true } log.Println("checkLogin() LOGIN FAILED. ATTEMPT updateToken(ge)") return updateToken(ge) } */ func fetchNetworks(ge *pb.Event) []network { var networks []network req, err := http.NewRequest("GET", ge.Account.URL + "clusters", nil) if err != nil { log.Fatal("can't make new req") } req.Header.Set("X-Wit-Auth", ge.Account.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(ge *pb.Event, network string) []vm { var vms []vm req, err := http.NewRequest("GET", ge.Account.URL + "vms/" + network, nil) if err != nil { log.Fatal("can't make new req") } req.Header.Set("X-Wit-Auth", ge.Account.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 } // 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 sendProtobuf(conn *websocket.Conn, msg *pb.Event) { log.Println("sendProtobuf() START") data, _ := proto.Marshal(msg) err := conn.WriteMessage(websocket.BinaryMessage, data) if err != nil { log.Println("sendProtobuf() write:", err) } log.Println("sendProtobuf() END") } 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 { // probably this should never happen since the client socket connection should have // already been dropped. If a user is doing this, the account should probably be // terminated as abuse log.Println("\teventHandler() GOT websocket.TextMessage (ERROR. NO HANDLER FOR THIS YET)") log.Println("\teventHandler() GOT websocket.TextMessage (ERROR. THIS SHOULD NEVER HAPPEN)") log.Println("\teventHandler() GOT websocket.TextMessage (ERROR. SUSPEND THIS USER)") } if mytype == websocket.BinaryMessage { log.Println("\teventHandler() GOT websocket.BinaryMessage") pdata := new(pb.Event) var e *pb.Event e = new(pb.Event) err = proto.Unmarshal(message, pdata) if (err != nil) { log.Printf("readConn() something fucked up happened in Unmarshal") } log.Printf("\teventHandler() pdata.Type =", pdata.Type) log.Printf("\teventHandler() recv binary: %s", pdata) if pdata.Type == pb.Event_GET { log.Printf("\teventHandler() DOING Event_GET") e = processGetEvent(pdata) } else if pdata.Type == pb.Event_LOGIN { log.Printf("\teventHandler() DOING Event_LOGIN") e = processLoginEvent(pdata) } else if pdata.Type == pb.Event_ADD { log.Printf("\teventHandler() DOING Event_ADD") e = processAddEvent(pdata) } if (e == nil) { e = pb.MakeFailResponse() e.Comment = "websocket.BinaryMessage LOGIN FAILED" } e.Account = pdata.Account log.Println("\teventHandler() e.Comment =", e.Comment) 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) } } // Gets a list of all the customer VM's func processGetEvent(ge *pb.Event) *pb.Event { log.Println("processGetEvent() START") if (checkLogin(ge) == false) { e := pb.MakeFailResponse() e.Comment = "processGetEvent() LOGIN FAILED on checkLogin(ge)" log.Println(e.Comment) return e } log.Println("processGetEvent() ge.Account.Token =", ge.Account.Token) log.Println("processGetEvent() ge.Account.Username =", ge.Account.Username) log.Println("processGetEvent() ge.Account.Email =", ge.Account.Email) e := pb.Event{} networks := fetchNetworks(ge) for _, network := range(networks) { 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, network.Subdomain) for _, vm := range(vms) { evm := pb.Event_VM{} evm.Name = vm.Name evm.Cpus = 1 evm.Memory = 512 evm.Disk = 20 evm.Hostname = vm.Name + "." + enetwork.Name + ".customers.wprod.wit.com" e.Vms = append(e.Vms, &evm) log.Println("\tvm.Name =",vm.Name) log.Println("\tvm =",vm) } } return &e } /* // should check a user can login here func processLoginEvent(ge *pb.Event) *pb.Event { log.Println("processLoginEvent() LOGIN START") if (checkLogin(ge) == false) { e := pb.MakeFailResponse() e.Comment = "LOGIN FAILED" log.Println(e.Comment) return e } e := pb.MakeOkResponse() e.Account = ge.Account e.Comment = "processLoginEvent() LOGIN WORKED" log.Println(e.Comment) return e } */ func JSONtoVM(ge *pb.Event, json string) { tmp := "network_addr" value := gjson.Get(json, tmp) println(tmp, "=", value.String()) tmp = "public_mac" value = gjson.Get(json, tmp) println(tmp, "=", value.String()) tmp = "public_addr" value = gjson.Get(json, tmp) println(tmp, "=", value.String()) } func processAddEvent(ge *pb.Event) *pb.Event { log.Println("processAddEvent() START ge.Account =", ge.Account) if (checkLogin(ge) == false) { e := pb.MakeFailResponse() e.Comment = "processAddEvent() LOGIN FAILED. ge.Account = nil" log.Println(e.Comment) return e } url := ge.Account.URL + "vms/jcarr.com?count=1&cpu=2&ram=512&disk=25" newVM := string(POSTbody(ge, url)) log.Println("processAddEvent() recieved newVM=", newVM) e := pb.MakeOkResponse() e.Account = ge.Account e.Comment = newVM log.Println(e.Comment) return e }