server/control.go

255 lines
6.4 KiB
Go
Raw Normal View History

package botserv
2013-08-28 23:46:12 -07:00
import (
2013-09-01 23:00:09 -07:00
"encoding/json"
2013-11-13 23:45:02 -08:00
"errors"
"fmt"
"io/ioutil"
2013-09-28 23:00:29 -07:00
"log"
2013-08-28 23:46:12 -07:00
"net/http"
"os"
2013-09-28 23:00:29 -07:00
"runtime/pprof"
"strings"
2013-08-28 23:46:12 -07:00
)
type JsonHandler func(http.ResponseWriter, *http.Request)
func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
h(w, req)
}
2013-09-01 23:00:09 -07:00
type Controller struct {
Idg *IdGenerator
Conf Config
Games MapLock
Memprofile string
Profile string
}
func (c *Controller) StartGame(w http.ResponseWriter, req *http.Request) {
2013-10-14 00:17:12 -07:00
log.Println("asked to create a game")
requested_game_name := c.Idg.Hash()
width, height := float32(c.Conf.Width), float32(c.Conf.Height)
2013-11-16 19:57:13 -08:00
obstacles := 0
maxPoints := c.Conf.MaxPoints
mode := "deathmatch"
// here we determine if we are going to run with defaults or pick them off
// a posted json blob
if req.Method == "POST" {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf("unable to read request body:", err)
}
req.Body.Close()
2013-11-13 20:38:57 -08:00
cfg := struct {
2013-11-29 00:10:49 -08:00
Name string `json:"name"`
Config
}{}
2013-11-13 20:38:57 -08:00
err = json.Unmarshal(body, &cfg)
if err != nil {
if err := json.NewEncoder(w).Encode(NewFailure(err.Error())); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
2013-11-13 20:38:57 -08:00
requested_game_name = cfg.Name
2013-11-29 00:10:49 -08:00
width = float32(cfg.Width)
height = float32(cfg.Height)
2013-11-16 19:57:13 -08:00
obstacles = cfg.Obstacles
2013-11-29 00:10:49 -08:00
maxPoints = cfg.MaxPoints
mode = cfg.Mode
}
g := c.Games.get(requested_game_name)
if g == nil {
log.Printf("Game '%s' non-existant; making it now", requested_game_name)
var err error
g, err = NewGame(requested_game_name, width, height, obstacles, c.Conf.Tick, maxPoints, mode)
if err != nil {
log.Printf("problem creating game: %s: %s", requested_game_name, err)
b, _ := json.Marshal(NewFailure("game creation failure"))
http.Error(w, string(b), http.StatusConflict)
return
}
go g.run()
c.Games.add(g)
} else {
2013-11-29 00:10:49 -08:00
log.Printf("Game '%s' already exists: %p", requested_game_name, g)
b, _ := json.Marshal(NewFailure("game already exists"))
http.Error(w, string(b), http.StatusConflict)
return
}
2013-09-01 23:00:09 -07:00
game_json := struct {
Id string `json:"id"`
}{
Id: g.id,
}
if err := json.NewEncoder(w).Encode(game_json); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (c *Controller) ListGames(w http.ResponseWriter, req *http.Request) {
2013-10-14 00:17:12 -07:00
log.Println("games list requested")
c.Games.RLock()
defer c.Games.RUnlock()
type pout struct {
Name string `json:"name"`
Id string `json:"id"`
}
2013-09-07 19:12:46 -07:00
type gl struct {
Id string `json:"id"`
Players []pout `json:"players"`
2013-09-07 19:12:46 -07:00
}
ids := make([]gl, 0)
for id, g := range c.Games.M {
players := make([]pout, 0)
2013-11-08 21:25:42 -08:00
// TODO - players instead of robots?
for p := range g.players {
2013-11-08 21:25:42 -08:00
for _, r := range p.Robots {
players = append(players, pout{
Name: r.Name,
Id: r.Id,
})
}
2013-09-07 19:12:46 -07:00
}
ids = append(ids, gl{
2013-09-07 19:12:46 -07:00
Id: id,
Players: players,
})
2013-09-01 23:00:09 -07:00
}
if err := json.NewEncoder(w).Encode(ids); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (c *Controller) GameStats(w http.ResponseWriter, req *http.Request) {
2013-11-15 08:54:52 -08:00
// TODO: wrap this up in something similar to the JsonHandler to verify the
// url? Look at gorilla routing?
key, err := c.getGameId(req.URL.Path)
2013-11-13 23:45:02 -08:00
if err != nil {
2013-11-15 08:54:52 -08:00
b, _ := json.Marshal(NewFailure(err.Error()))
http.Error(w, string(b), http.StatusBadRequest)
return
2013-11-13 23:45:02 -08:00
}
log.Printf("requested stats for game: %s", key)
c.Games.RLock()
g, ok := c.Games.M[key]
c.Games.RUnlock()
2013-11-13 23:45:02 -08:00
if !ok {
2013-11-15 08:54:52 -08:00
b, _ := json.Marshal(NewFailure("game not found"))
http.Error(w, string(b), http.StatusNotFound)
return
}
2014-01-16 00:02:59 -08:00
g.stats.RLock()
defer g.stats.RUnlock()
2014-01-16 00:13:02 -08:00
if err := json.NewEncoder(w).Encode(g.stats.PlayerStats); err != nil {
2013-11-13 23:45:02 -08:00
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (c *Controller) BW(w http.ResponseWriter, req *http.Request) {
// TODO: wrap this up in something similar to the JsonHandler to verify the
// url? Look at gorilla routing?
key, err := c.getGameId(req.URL.Path)
if err != nil {
b, _ := json.Marshal(NewFailure(err.Error()))
http.Error(w, string(b), http.StatusBadRequest)
return
}
log.Printf("requested bandwidth for game: %s", key)
c.Games.RLock()
g, ok := c.Games.M[key]
c.Games.RUnlock()
if !ok {
b, _ := json.Marshal(NewFailure("game not found"))
http.Error(w, string(b), http.StatusNotFound)
return
}
s := map[string][]float64{
"tx": <-g.bw.Tx,
"rx": <-g.bw.Rx,
}
if err := json.NewEncoder(w).Encode(s); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// StopGame is the only mechanism to decrease the number of running games in a Controller
func (c *Controller) StopGame(w http.ResponseWriter, req *http.Request) {
key, err := c.getGameId(req.URL.Path)
2013-11-13 23:45:02 -08:00
if err != nil {
2013-11-15 08:54:52 -08:00
b, _ := json.Marshal(NewFailure(err.Error()))
http.Error(w, string(b), http.StatusBadRequest)
return
2013-11-13 23:45:02 -08:00
}
c.Games.Lock()
g, ok := c.Games.M[key]
defer c.Games.Unlock()
if !ok {
http.NotFound(w, req)
return
}
2013-11-13 23:45:02 -08:00
g.kill <- true
delete(c.Games.M, key)
2013-11-13 23:45:02 -08:00
message := struct {
Ok bool `json:"ok"`
Message string `json:"message"`
}{
Ok: true,
Message: fmt.Sprintf("Successfully stopped game: %s", key),
}
if err := json.NewEncoder(w).Encode(message); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
log.Printf("returning from StopGame")
}
2013-09-28 23:00:29 -07:00
func (c *Controller) KillServer(w http.ResponseWriter, req *http.Request) {
if c.Profile != "" {
2013-09-28 23:03:42 -07:00
log.Print("trying to stop cpu profile")
2013-09-28 23:00:29 -07:00
pprof.StopCPUProfile()
2013-09-28 23:03:42 -07:00
log.Print("stopped cpu profile")
2013-09-28 23:00:29 -07:00
}
if c.Memprofile != "" {
log.Print("trying to dump memory profile")
f, err := os.Create(c.Memprofile)
if err != nil {
log.Fatal(err)
}
pprof.WriteHeapProfile(f)
f.Close()
log.Print("stopped memory profile dump")
}
2013-09-28 23:03:42 -07:00
log.Fatal("shit got fucked up")
2013-09-28 23:00:29 -07:00
}
2013-11-07 22:05:20 -08:00
func (c *Controller) Index(w http.ResponseWriter, req *http.Request) {
2013-11-07 22:05:20 -08:00
log.Println("version requested")
version := struct {
Version string `json:"version"`
Name string `json:"name"`
}{
Version: "0.1.2",
Name: "Hackerbots",
}
if err := json.NewEncoder(w).Encode(version); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
2013-11-13 23:45:02 -08:00
func (c *Controller) getGameId(path string) (string, error) {
2013-11-13 23:45:02 -08:00
var err error
trimmed := strings.Trim(path, "/")
fullPath := strings.Split(trimmed, "/")
if len(fullPath) != 3 {
return "", errors.New("improperly formed url")
}
key := fullPath[2]
return key, err
}