Keine Beschreibung
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

control.go 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. package server
  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. "sync"
  13. )
  14. // JsonHandler is a function type that allows setting the Content-Type
  15. // appropriately for views destined to serve JSON
  16. type JsonHandler func(http.ResponseWriter, *http.Request)
  17. // ServeHTTP is JsonHandler's http.Handler implementation.
  18. func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  19. w.Header().Set("Content-Type", "application/json")
  20. h(w, req)
  21. }
  22. // Controller is the shepherd of a collection of games. The main package in
  23. // server simply populates one of these and starts an http server.
  24. type Controller struct {
  25. Idg *IdGenerator
  26. Conf Config
  27. Games MapLock
  28. Memprofile string
  29. Profile string
  30. }
  31. // NewController takes a populated Config, and some parameters to determine
  32. // what sorts of profiling to deal with and returns a freshly populated
  33. // Controller.
  34. func NewController(conf Config, mprof, pprof string) *Controller {
  35. idg := NewIdGenerator()
  36. return &Controller{
  37. Idg: idg,
  38. Conf: conf,
  39. Games: MapLock{
  40. M: make(map[string]*Game),
  41. },
  42. Memprofile: mprof,
  43. Profile: pprof,
  44. }
  45. }
  46. // TODO Eventually this thing will have a select loop for dealing with game
  47. // access in a more lock-free manner?
  48. func (c *Controller) Run() {
  49. c.Idg.Run()
  50. }
  51. // StartGame is the http route responsible for responding to requests to start
  52. // games under this controller. Creates a default Config object, and populates
  53. // it according to data POSTed.
  54. func (c *Controller) StartGame(w http.ResponseWriter, req *http.Request) {
  55. log.Println("asked to create a game")
  56. requested_game_name := c.Idg.Hash()
  57. width, height := float32(c.Conf.Width), float32(c.Conf.Height)
  58. obstacles := 0
  59. maxPoints := c.Conf.MaxPoints
  60. mode := "deathmatch"
  61. // here we determine if we are going to run with defaults or pick them off
  62. // a posted json blob
  63. if req.Method == "POST" {
  64. body, err := ioutil.ReadAll(req.Body)
  65. if err != nil {
  66. log.Printf("unable to read request body: %v", err)
  67. }
  68. req.Body.Close()
  69. cfg := struct {
  70. Name string `json:"name"`
  71. Config
  72. }{}
  73. err = json.Unmarshal(body, &cfg)
  74. if err != nil {
  75. if err := json.NewEncoder(w).Encode(NewFailure(err.Error())); err != nil {
  76. http.Error(w, err.Error(), http.StatusInternalServerError)
  77. }
  78. return
  79. }
  80. requested_game_name = cfg.Name
  81. width = float32(cfg.Width)
  82. height = float32(cfg.Height)
  83. obstacles = cfg.Obstacles
  84. maxPoints = cfg.MaxPoints
  85. mode = cfg.Mode
  86. }
  87. g := c.Games.Get(requested_game_name)
  88. if g == nil {
  89. log.Printf("Game '%s' non-existant; making it now", requested_game_name)
  90. var err error
  91. g, err = NewGame(requested_game_name, width, height, obstacles, c.Conf.Tick, maxPoints, mode)
  92. if err != nil {
  93. log.Printf("problem creating game: %s: %s", requested_game_name, err)
  94. b, _ := json.Marshal(NewFailure("game creation failure"))
  95. http.Error(w, string(b), http.StatusConflict)
  96. return
  97. }
  98. go g.run()
  99. c.Games.Add(g)
  100. } else {
  101. log.Printf("Game '%s' already exists: %p", requested_game_name, g)
  102. b, _ := json.Marshal(NewFailure("game already exists"))
  103. http.Error(w, string(b), http.StatusConflict)
  104. return
  105. }
  106. game_json := struct {
  107. Id string `json:"id"`
  108. }{
  109. Id: g.id,
  110. }
  111. if err := json.NewEncoder(w).Encode(game_json); err != nil {
  112. http.Error(w, err.Error(), http.StatusInternalServerError)
  113. }
  114. }
  115. // ListGames makes a reasonable JSON response based on the games currently
  116. // being run.
  117. func (c *Controller) ListGames(w http.ResponseWriter, req *http.Request) {
  118. log.Println("games list requested")
  119. c.Games.RLock()
  120. defer c.Games.RUnlock()
  121. type pout struct {
  122. Name string `json:"name"`
  123. Id string `json:"id"`
  124. }
  125. type gl struct {
  126. Id string `json:"id"`
  127. Players []pout `json:"players"`
  128. }
  129. ids := make([]gl, 0)
  130. for id, g := range c.Games.M {
  131. players := make([]pout, 0)
  132. // TODO - players instead of robots?
  133. for p := range g.players {
  134. for _, r := range p.Robots {
  135. players = append(players, pout{
  136. Name: r.Name,
  137. Id: r.Id,
  138. })
  139. }
  140. }
  141. ids = append(ids, gl{
  142. Id: id,
  143. Players: players,
  144. })
  145. }
  146. if err := json.NewEncoder(w).Encode(ids); err != nil {
  147. http.Error(w, err.Error(), http.StatusInternalServerError)
  148. }
  149. }
  150. // GameStats provides an control mechanism to query for the stats of a single
  151. // game
  152. func (c *Controller) GameStats(w http.ResponseWriter, req *http.Request) {
  153. // TODO: wrap this up in something similar to the JsonHandler to verify the
  154. // url? Look at gorilla routing?
  155. key, err := c.getGameId(req.URL.Path)
  156. if err != nil {
  157. b, _ := json.Marshal(NewFailure(err.Error()))
  158. http.Error(w, string(b), http.StatusBadRequest)
  159. return
  160. }
  161. log.Printf("requested stats for game: %s", key)
  162. c.Games.RLock()
  163. g, ok := c.Games.M[key]
  164. c.Games.RUnlock()
  165. if !ok {
  166. b, _ := json.Marshal(NewFailure("game not found"))
  167. http.Error(w, string(b), http.StatusNotFound)
  168. return
  169. }
  170. g.stats.RLock()
  171. defer g.stats.RUnlock()
  172. if err := json.NewEncoder(w).Encode(g.stats.PlayerStats); err != nil {
  173. http.Error(w, err.Error(), http.StatusInternalServerError)
  174. }
  175. }
  176. // BW provides a route to query for current bandwidth utilization for a single
  177. // game.
  178. func (c *Controller) BW(w http.ResponseWriter, req *http.Request) {
  179. // TODO: wrap this up in something similar to the JsonHandler to verify the
  180. // url? Look at gorilla routing?
  181. key, err := c.getGameId(req.URL.Path)
  182. if err != nil {
  183. b, _ := json.Marshal(NewFailure(err.Error()))
  184. http.Error(w, string(b), http.StatusBadRequest)
  185. return
  186. }
  187. log.Printf("requested bandwidth for game: %s", key)
  188. c.Games.RLock()
  189. g, ok := c.Games.M[key]
  190. c.Games.RUnlock()
  191. if !ok {
  192. b, _ := json.Marshal(NewFailure("game not found"))
  193. http.Error(w, string(b), http.StatusNotFound)
  194. return
  195. }
  196. s := map[string][]float64{
  197. "tx": <-g.bw.Tx,
  198. "rx": <-g.bw.Rx,
  199. }
  200. if err := json.NewEncoder(w).Encode(s); err != nil {
  201. http.Error(w, err.Error(), http.StatusInternalServerError)
  202. }
  203. }
  204. // StopGame is the only mechanism to decrease the number of running games in
  205. // a Controller
  206. func (c *Controller) StopGame(w http.ResponseWriter, req *http.Request) {
  207. key, err := c.getGameId(req.URL.Path)
  208. if err != nil {
  209. b, _ := json.Marshal(NewFailure(err.Error()))
  210. http.Error(w, string(b), http.StatusBadRequest)
  211. return
  212. }
  213. c.Games.Lock()
  214. g, ok := c.Games.M[key]
  215. defer c.Games.Unlock()
  216. if !ok {
  217. http.NotFound(w, req)
  218. return
  219. }
  220. g.kill <- true
  221. delete(c.Games.M, key)
  222. message := struct {
  223. Ok bool `json:"ok"`
  224. Message string `json:"message"`
  225. }{
  226. Ok: true,
  227. Message: fmt.Sprintf("Successfully stopped game: %s", key),
  228. }
  229. if err := json.NewEncoder(w).Encode(message); err != nil {
  230. http.Error(w, err.Error(), http.StatusInternalServerError)
  231. }
  232. log.Printf("returning from StopGame")
  233. }
  234. // KillServer is my favorite method of all the methods in server: it shuts
  235. // things down respecting profiling requests.
  236. func (c *Controller) KillServer(w http.ResponseWriter, req *http.Request) {
  237. if c.Profile != "" {
  238. log.Print("trying to stop cpu profile")
  239. pprof.StopCPUProfile()
  240. log.Print("stopped cpu profile")
  241. }
  242. if c.Memprofile != "" {
  243. log.Print("trying to dump memory profile")
  244. f, err := os.Create(c.Memprofile)
  245. if err != nil {
  246. log.Fatal(err)
  247. }
  248. pprof.WriteHeapProfile(f)
  249. f.Close()
  250. log.Print("stopped memory profile dump")
  251. }
  252. log.Fatal("shit got fucked up")
  253. }
  254. // Index is the function for handling all traffic not officially in the API. It
  255. // just lets people know that this is a hackerbots server running at
  256. // a particular version.
  257. func (c *Controller) Index(w http.ResponseWriter, req *http.Request) {
  258. log.Println("version requested")
  259. version := struct {
  260. Version string `json:"version"`
  261. Name string `json:"name"`
  262. }{
  263. Version: "0.1.2",
  264. Name: "Hackerbots",
  265. }
  266. if err := json.NewEncoder(w).Encode(version); err != nil {
  267. http.Error(w, err.Error(), http.StatusInternalServerError)
  268. }
  269. }
  270. // getGameId trims the gameid off of the url. This is hokey, and makes me miss
  271. // django regex-specified routes.
  272. func (c *Controller) getGameId(path string) (string, error) {
  273. var err error
  274. trimmed := strings.Trim(path, "/")
  275. fullPath := strings.Split(trimmed, "/")
  276. if len(fullPath) != 3 {
  277. return "", errors.New("improperly formed url")
  278. }
  279. key := fullPath[2]
  280. return key, err
  281. }
  282. // MapLock is simply a map and a RWMutex
  283. // TODO: obviate the need for this in Controller.Run
  284. type MapLock struct {
  285. M map[string]*Game
  286. sync.RWMutex
  287. }
  288. // get is a function that returns a game if found, and creates one if
  289. // not found and force is true. In order to get a hash (rather than use
  290. // the string you pass) send "" for id.
  291. func (ml *MapLock) Get(id string) *Game {
  292. ml.Lock()
  293. g, _ := ml.M[id]
  294. ml.Unlock()
  295. return g
  296. }
  297. // add is used to insert a new game into this MapLock
  298. func (ml *MapLock) Add(g *Game) {
  299. ml.Lock()
  300. ml.M[g.id] = g
  301. ml.Unlock()
  302. }