dnssecsocket/gorilla-server/main.go

400 lines
11 KiB
Go
Raw Normal View History

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("\t", 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, "<html><body>Echo Server</body></html>")
}
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
}
tmp := string(GETbody(ge, "http://stackapi:4000/me"))
log.Println("processAddEvent() recieved json=", tmp)
tmp = string(GETbody(ge, "http://stackapi:4000/clusters"))
log.Println("processAddEvent() recieved json=", tmp)
// stackapi:4000/vms/jcarr.com?count=1&cpu=2&ram=512&disk=25
url := ge.Account.URL + "vms/jcarr.com?count=1&cpu=2&ram=512&disk=25"
json := newFetchBody(ge, "POST", url)
log.Println("processAddEvent() recieved json=", json)
/*
m, ok := gjson.Parse(tmp).Value().(map[string]interface{})
if !ok {
// not a map
log.Println("processAddEvent() not a map m=", m)
}
log.Println("processAddEvent() m=", m)
*/
/*
tmp = string(GETbody(ge, "http://stackapi:4000/vms/jcarr.com"))
log.Println("processAddEvent() recieved json=", tmp)
tmp = string(GETbody(ge, "http://stackapi:4000/vm/v000196"))
log.Println("processAddEvent() recieved json=", tmp)
JSONtoVM(ge, tmp)
*/
/*
url := ge.Account.URL + "me"
json := newFetchBody(ge, "GET", url)
log.Println("processAddEvent() recieved json=", json)
json = string(fetchGET(ge.Account.Token, "http://stackapi:4000/clusters"))
log.Println("processAddEvent() recieved json=", json)
url = ge.Account.URL + "vms/testing.com?count=1&cpu=2&ram=512&disk=25"
json = newFetchBody(ge, "POST", url)
log.Println("processAddEvent() recieved json=", json)
*/
e := pb.MakeOkResponse()
e.Account = ge.Account
e.Comment = "processAddEvent() LOGIN WORKED"
log.Println(e.Comment)
return e
}
// This is the 'orig' code
// TODO: phase this out for more common code
func origLoginCheck(ge *pb.Event) bool {
var url string
var httpType string
httpType = "GET"
url = ge.Account.URL + "me"
log.Println("origLoginCheck() ", httpType, url)
req, err := http.NewRequest(httpType, url, nil)
if err != nil {
ge.Comment = "origLoginCheck() FAILED can't make new req"
log.Println(ge.Comment)
return false
}
req.Header.Set("X-Wit-Auth", ge.Account.Token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
ge.Comment = "origLoginCheck() FAILED Can't exec the req to list networks " + err.Error()
log.Println(ge.Comment)
return false
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
ge.Comment = "origLoginCheck() FAILED can't read resp"
log.Println(ge.Comment)
return false
}
log.Printf("origLoginCheck() ", "RESPONSE =", string(body))
if body == nil {
ge.Comment = "origLoginCheck() FAILED RESPONSE is nil"
log.Println(ge.Comment)
return false
} else {
len := len(body)
log.Println("origLoginCheck() ", "body = ", string(body))
log.Println("origLoginCheck() ", "body len = ", len)
email := gjson.Get(string(body), "email")
log.Println("origLoginCheck() ", "email = ", email.String())
log.Println("origLoginCheck() ", "ge.Account.Username = ", ge.Account.Username)
if (email.String() == ge.Account.Username) {
ge.Comment = "origLoginCheck() THIS TOTALLY WORKED MAN"
log.Println(ge.Comment)
return true
}
}
ge.Comment = "origLoginCheck() FAILED "
log.Println(ge.Comment)
return false
}