attempt 3

Signed-off-by: Jeff Carr <jcarr@wit.com>
This commit is contained in:
Jeff Carr 2019-05-25 12:30:07 -07:00
parent 42ef854233
commit 58b80b499a
2 changed files with 21 additions and 393 deletions

View File

@ -7,13 +7,33 @@ import "net/http"
import "github.com/davecgh/go-spew/spew"
func handler(w http.ResponseWriter, r *http.Request) {
spew.Dump(r)
// spew.Dump(r)
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
log.Printf("handler: fucking unknown path")
}
func handler2(w http.ResponseWriter, r *http.Request) {
spew.Dump(r)
fmt.Fprintf(w, "Hi there, handler2 %s!", r.URL.Path[1:])
log.Printf("handler: method switch statement")
switch r.Method {
case http.MethodGet:
// Serve the resource.
log.Printf("handler2 GET")
case http.MethodPost:
// Create a new record.
log.Printf("handler2 POST")
case http.MethodPut:
// Update an existing record.
log.Printf("handler2 PUT")
case http.MethodDelete:
// Remove the record.
log.Printf("handler2 DELETE")
default:
// Give an error message.
log.Printf("handler2 DEFAULT")
}
}
func main() {

View File

@ -1,392 +0,0 @@
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) bool {
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", 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
}
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 {
// stackapi:4000/vms/jcarr.com?count=1&cpu=2&ram=512&disk=25
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
}
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")
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")
if checkLogin(ge) {
log.Println("processLoginEvent() LOGIN WORKED")
log.Println("processLoginEvent() LOGIN WORKED")
log.Println("processLoginEvent() LOGIN WORKED")
e := pb.MakeOkResponse()
e.Comment = "LOGIN WORKED"
return e
} else {
log.Println("processLoginEvent() LOGIN FAILED")
log.Println("processLoginEvent() LOGIN FAILED")
log.Println("processLoginEvent() LOGIN FAILED")
e := pb.MakeFailResponse()
e.Comment = "LOGIN FAILED"
return e
}
log.Println("processLoginEvent() END")
e := &pb.Event{}
return e
}
func processAddEvent(ge *pb.Event) *pb.Event {
log.Println("processAddEvent() START")
log.Println("processAddLoginEvent() ge.Token =", ge.Token)
log.Println("processAddEvent() NEED TO LOGIN HERE OR CHECK TOKEN WORKS")
if checkLogin(ge) {
log.Println("processAddEvent() LOGIN WORKED")
log.Println("processAddEvent() LOGIN WORKED")
log.Println("processAddEvent() LOGIN WORKED")
} else {
log.Println("processAddEvent() LOGIN FAILED")
log.Println("processAddEvent() LOGIN FAILED")
log.Println("processAddEvent() LOGIN FAILED")
e := pb.MakeFailResponse()
e.Comment = "LOGIN FAILED"
return e
}
jsonAddEvent(ge)
log.Println("processAddEvent() END")
return nil
}