dnssecsocket/gorilla-server/main.go

408 lines
10 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/"
MAX_NETS = 10
MAX_VMS = 10
)
type network struct {
Subdomain string `json:"subdomain"`
}
func checkLogin(ge *pb.Event) string {
if (origLoginCheck(ge) == true) {
log.Println("origLoginCheck() LOGIN WORKED")
return ge.Account.Token
}
log.Println("origLoginCheck() LOGIN FAILED. ATTEMPT getToken(ge)")
log.Println("origLoginCheck() LOGIN FAILED. ATTEMPT getToken(ge)")
log.Println("origLoginCheck() LOGIN FAILED. ATTEMPT getToken(ge)")
ge.Account.URL = "http://stackapi:4000"
token := getToken(ge)
return token
}
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
}
// 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_GET {
log.Printf("GOT GET")
e := processGetEvent(pdata)
sendProtobuf(conn, e)
}
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_ADD {
log.Printf("GOT ADD")
e := processAddEvent(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, "<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)
}
}
func processGetEvent(ge *pb.Event) *pb.Event {
log.Println("processGetEvent() START")
if (ge.Account == nil) {
log.Println("processGetEvent() ERROR ge.Account = nil")
log.Println("processGetEvent() ERROR ge.Account = nil")
log.Println("processGetEvent() ERROR ge.Account = nil")
e := pb.MakeFailResponse()
e.Comment = "Account = nil"
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.Account.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.Account.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 + ".customers.wprod.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.Account.Token =", ge.Account.Token)
log.Println("processLoginEvent() NEED TO LOGIN HERE OR CHECK TOKEN WORKS")
token := checkLogin(ge)
if (token == "") {
e := pb.MakeFailResponse()
e.Comment = "LOGIN FAILED"
return e
}
log.Println("processLoginEvent() LOGIN WORKED")
log.Println("processLoginEvent() LOGIN WORKED")
log.Println("processLoginEvent() LOGIN WORKED")
e := pb.MakeOkResponse()
e.Account = ge.Account
if (e.Account.Token != token) {
log.Println("processLoginEvent() GENERATED NEW TOKEN old =", e.Account.Token)
log.Println("processLoginEvent() GENERATED NEW TOKEN new =", token)
}
e.Account.Token = token
e.Comment = "LOGIN WORKED"
return e
}
func processAddEvent(ge *pb.Event) *pb.Event {
log.Println("processAddEvent() START")
log.Println("processAddLoginEvent() ge.Account.Token =", ge.Account.Token)
log.Println("processAddEvent() END")
return nil
}
/*
func jsonAddEvent(ge *pb.Event) bool {
var url string
var httpType string
httpType = "GET"
if ge.Type == pb.Event_LOGIN {
url = API + "me"
} else if ge.Type == pb.Event_ADD {
url = API + "vms/jcarr.com?count=1&cpu=2&ram=512&disk=25"
httpType = "POST"
} else if ge.Type == pb.Event_MIGRATE {
url = API + "clusters"
} else {
// if unknown, just check login
url = API + "me"
}
log.Println("jsonAddEvent() ", httpType, url)
req, err := http.NewRequest(httpType, url, nil)
if err != nil {
log.Println("can't make new req")
return false
}
req.Header.Set("X-Wit-Auth", ge.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)
log.Println("body = ", string(body))
log.Println("body len = ", len)
email := gjson.Get(string(body), "email")
log.Println("email = ", email.String())
log.Println("ge.Username = ", ge.Username)
if (email.String() == ge.Username) {
log.Println("\tTHIS TOTALLY WORKED MAN")
return true
}
}
return false
}
*/
// 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 = API + "me"
log.Println("origLoginCheck() ", httpType, url)
req, err := http.NewRequest(httpType, url, nil)
if err != nil {
log.Println("can't make new req")
return false
}
req.Header.Set("X-Wit-Auth", ge.Account.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 =", string(body))
if body == nil {
log.Println("RESPONSE is nil")
return false
} else {
len := len(body)
log.Println("body = ", string(body))
log.Println("body len = ", len)
email := gjson.Get(string(body), "email")
log.Println("email = ", email.String())
log.Println("ge.Account.Username = ", ge.Account.Username)
if (email.String() == ge.Account.Username) {
log.Println("\tTHIS TOTALLY WORKED MAN")
return true
}
}
return false
}