No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

control.go 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package botserv
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "os"
  10. "runtime/pprof"
  11. "strings"
  12. )
  13. type JsonHandler func(http.ResponseWriter, *http.Request)
  14. func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  15. w.Header().Set("Content-Type", "application/json")
  16. h(w, req)
  17. }
  18. type Controller struct {
  19. Idg *IdGenerator
  20. Conf Config
  21. Games MapLock
  22. Memprofile string
  23. Profile string
  24. }
  25. func (c *Controller) StartGame(w http.ResponseWriter, req *http.Request) {
  26. log.Println("asked to create a game")
  27. requested_game_name := c.Idg.Hash()
  28. width, height := float32(c.Conf.Width), float32(c.Conf.Height)
  29. obstacles := 0
  30. maxPoints := c.Conf.MaxPoints
  31. mode := "deathmatch"
  32. // here we determine if we are going to run with defaults or pick them off
  33. // a posted json blob
  34. if req.Method == "POST" {
  35. body, err := ioutil.ReadAll(req.Body)
  36. if err != nil {
  37. log.Printf("unable to read request body:", err)
  38. }
  39. req.Body.Close()
  40. cfg := struct {
  41. Name string `json:"name"`
  42. Config
  43. }{}
  44. err = json.Unmarshal(body, &cfg)
  45. if err != nil {
  46. if err := json.NewEncoder(w).Encode(NewFailure(err.Error())); err != nil {
  47. http.Error(w, err.Error(), http.StatusInternalServerError)
  48. }
  49. return
  50. }
  51. requested_game_name = cfg.Name
  52. width = float32(cfg.Width)
  53. height = float32(cfg.Height)
  54. obstacles = cfg.Obstacles
  55. maxPoints = cfg.MaxPoints
  56. mode = cfg.Mode
  57. }
  58. g := c.Games.get(requested_game_name)
  59. if g == nil {
  60. log.Printf("Game '%s' non-existant; making it now", requested_game_name)
  61. g, err := NewGame(requested_game_name, width, height, obstacles, c.Conf.Tick, maxPoints, mode)
  62. if err != nil {
  63. log.Printf("problem creating game: %s: %s", requested_game_name, err)
  64. b, _ := json.Marshal(NewFailure("game creation failure"))
  65. http.Error(w, string(b), http.StatusConflict)
  66. return
  67. }
  68. go g.run()
  69. c.Games.add(g)
  70. } else {
  71. log.Printf("Game '%s' already exists: %p", requested_game_name, g)
  72. b, _ := json.Marshal(NewFailure("game already exists"))
  73. http.Error(w, string(b), http.StatusConflict)
  74. return
  75. }
  76. game_json := struct {
  77. Id string `json:"id"`
  78. }{
  79. Id: g.id,
  80. }
  81. if err := json.NewEncoder(w).Encode(game_json); err != nil {
  82. http.Error(w, err.Error(), http.StatusInternalServerError)
  83. }
  84. }
  85. func (c *Controller) ListGames(w http.ResponseWriter, req *http.Request) {
  86. log.Println("games list requested")
  87. c.Games.RLock()
  88. defer c.Games.RUnlock()
  89. type pout struct {
  90. Name string `json:"name"`
  91. Id string `json:"id"`
  92. }
  93. type gl struct {
  94. Id string `json:"id"`
  95. Players []pout `json:"players"`
  96. }
  97. ids := make([]gl, 0)
  98. for id, g := range c.Games.M {
  99. players := make([]pout, 0)
  100. // TODO - players instead of robots?
  101. for p := range g.players {
  102. for _, r := range p.Robots {
  103. players = append(players, pout{
  104. Name: r.Name,
  105. Id: r.Id,
  106. })
  107. }
  108. }
  109. ids = append(ids, gl{
  110. Id: id,
  111. Players: players,
  112. })
  113. }
  114. if err := json.NewEncoder(w).Encode(ids); err != nil {
  115. http.Error(w, err.Error(), http.StatusInternalServerError)
  116. }
  117. }
  118. func (c *Controller) GameStats(w http.ResponseWriter, req *http.Request) {
  119. // TODO: wrap this up in something similar to the JsonHandler to verify the
  120. // url? Look at gorilla routing?
  121. key, err := c.getGameId(req.URL.Path)
  122. if err != nil {
  123. b, _ := json.Marshal(NewFailure(err.Error()))
  124. http.Error(w, string(b), http.StatusBadRequest)
  125. return
  126. }
  127. log.Printf("requested stats for game: %s", key)
  128. c.Games.RLock()
  129. g, ok := c.Games.M[key]
  130. c.Games.RUnlock()
  131. if !ok {
  132. b, _ := json.Marshal(NewFailure("game not found"))
  133. http.Error(w, string(b), http.StatusNotFound)
  134. return
  135. }
  136. g.stats.RLock()
  137. defer g.stats.RUnlock()
  138. if err := json.NewEncoder(w).Encode(g.stats.PlayerStats); err != nil {
  139. http.Error(w, err.Error(), http.StatusInternalServerError)
  140. }
  141. }
  142. func (c *Controller) BW(w http.ResponseWriter, req *http.Request) {
  143. // TODO: wrap this up in something similar to the JsonHandler to verify the
  144. // url? Look at gorilla routing?
  145. key, err := c.getGameId(req.URL.Path)
  146. if err != nil {
  147. b, _ := json.Marshal(NewFailure(err.Error()))
  148. http.Error(w, string(b), http.StatusBadRequest)
  149. return
  150. }
  151. log.Printf("requested bandwidth for game: %s", key)
  152. c.Games.RLock()
  153. g, ok := c.Games.M[key]
  154. c.Games.RUnlock()
  155. if !ok {
  156. b, _ := json.Marshal(NewFailure("game not found"))
  157. http.Error(w, string(b), http.StatusNotFound)
  158. return
  159. }
  160. s := map[string][]float64{
  161. "tx": <-g.bw.Tx,
  162. "rx": <-g.bw.Rx,
  163. }
  164. if err := json.NewEncoder(w).Encode(s); err != nil {
  165. http.Error(w, err.Error(), http.StatusInternalServerError)
  166. }
  167. }
  168. func (c *Controller) StopGame(w http.ResponseWriter, req *http.Request) {
  169. key, err := c.getGameId(req.URL.Path)
  170. if err != nil {
  171. b, _ := json.Marshal(NewFailure(err.Error()))
  172. http.Error(w, string(b), http.StatusBadRequest)
  173. return
  174. }
  175. c.Games.Lock()
  176. g, ok := c.Games.M[key]
  177. defer c.Games.Unlock()
  178. if !ok {
  179. http.NotFound(w, req)
  180. return
  181. }
  182. g.kill <- true
  183. message := struct {
  184. Ok bool `json:"ok"`
  185. Message string `json:"message"`
  186. }{
  187. Ok: true,
  188. Message: fmt.Sprintf("Successfully stopped game: %s", key),
  189. }
  190. if err := json.NewEncoder(w).Encode(message); err != nil {
  191. http.Error(w, err.Error(), http.StatusInternalServerError)
  192. }
  193. }
  194. func (c *Controller) KillServer(w http.ResponseWriter, req *http.Request) {
  195. if c.Profile != "" {
  196. log.Print("trying to stop cpu profile")
  197. pprof.StopCPUProfile()
  198. log.Print("stopped cpu profile")
  199. }
  200. if c.Memprofile != "" {
  201. log.Print("trying to dump memory profile")
  202. f, err := os.Create(c.Memprofile)
  203. if err != nil {
  204. log.Fatal(err)
  205. }
  206. pprof.WriteHeapProfile(f)
  207. f.Close()
  208. log.Print("stopped memory profile dump")
  209. }
  210. log.Fatal("shit got fucked up")
  211. }
  212. func (c *Controller) Index(w http.ResponseWriter, req *http.Request) {
  213. log.Println("version requested")
  214. version := struct {
  215. Version string `json:"version"`
  216. Name string `json:"name"`
  217. }{
  218. Version: "0.1.2",
  219. Name: "Hackerbots",
  220. }
  221. if err := json.NewEncoder(w).Encode(version); err != nil {
  222. http.Error(w, err.Error(), http.StatusInternalServerError)
  223. }
  224. }
  225. func (c *Controller) getGameId(path string) (string, error) {
  226. var err error
  227. trimmed := strings.Trim(path, "/")
  228. fullPath := strings.Split(trimmed, "/")
  229. if len(fullPath) != 3 {
  230. return "", errors.New("improperly formed url")
  231. }
  232. key := fullPath[2]
  233. return key, err
  234. }