server_test.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. package manager
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "math/rand"
  7. "net/http"
  8. "strings"
  9. "testing"
  10. "time"
  11. "github.com/gin-gonic/gin"
  12. . "github.com/smartystreets/goconvey/convey"
  13. . "github.com/tuna/tunasync/internal"
  14. )
  15. const (
  16. _magicBadWorkerID = "magic_bad_worker_id"
  17. )
  18. func TestHTTPServer(t *testing.T) {
  19. Convey("HTTP server should work", t, func(ctx C) {
  20. InitLogger(true, true, false)
  21. s := makeHTTPServer(false)
  22. So(s, ShouldNotBeNil)
  23. s.setDBAdapter(&mockDBAdapter{
  24. workerStore: map[string]workerStatus{
  25. _magicBadWorkerID: workerStatus{
  26. ID: _magicBadWorkerID,
  27. }},
  28. statusStore: make(map[string]mirrorStatus),
  29. })
  30. port := rand.Intn(10000) + 20000
  31. baseURL := fmt.Sprintf("http://127.0.0.1:%d", port)
  32. go func() {
  33. s.Run(fmt.Sprintf("127.0.0.1:%d", port))
  34. }()
  35. time.Sleep(50 * time.Microsecond)
  36. resp, err := http.Get(baseURL + "/ping")
  37. So(err, ShouldBeNil)
  38. So(resp.StatusCode, ShouldEqual, http.StatusOK)
  39. So(resp.Header.Get("Content-Type"), ShouldEqual, "application/json; charset=utf-8")
  40. defer resp.Body.Close()
  41. body, err := ioutil.ReadAll(resp.Body)
  42. So(err, ShouldBeNil)
  43. var p map[string]string
  44. err = json.Unmarshal(body, &p)
  45. So(err, ShouldBeNil)
  46. So(p[_infoKey], ShouldEqual, "pong")
  47. Convey("when database fail", func(ctx C) {
  48. resp, err := http.Get(fmt.Sprintf("%s/workers/%s/jobs", baseURL, _magicBadWorkerID))
  49. So(err, ShouldBeNil)
  50. So(resp.StatusCode, ShouldEqual, http.StatusInternalServerError)
  51. defer resp.Body.Close()
  52. var msg map[string]string
  53. err = json.NewDecoder(resp.Body).Decode(&msg)
  54. So(err, ShouldBeNil)
  55. So(msg[_errorKey], ShouldEqual, fmt.Sprintf("failed to list jobs of worker %s: %s", _magicBadWorkerID, "database fail"))
  56. })
  57. Convey("when register a worker", func(ctx C) {
  58. w := workerStatus{
  59. ID: "test_worker1",
  60. }
  61. resp, err := postJSON(baseURL+"/workers", w)
  62. So(err, ShouldBeNil)
  63. So(resp.StatusCode, ShouldEqual, http.StatusOK)
  64. Convey("list all workers", func(ctx C) {
  65. So(err, ShouldBeNil)
  66. resp, err := http.Get(baseURL + "/workers")
  67. So(err, ShouldBeNil)
  68. defer resp.Body.Close()
  69. var actualResponseObj []WorkerInfoMsg
  70. err = json.NewDecoder(resp.Body).Decode(&actualResponseObj)
  71. So(err, ShouldBeNil)
  72. So(len(actualResponseObj), ShouldEqual, 2)
  73. })
  74. Convey("update mirror status of a existed worker", func(ctx C) {
  75. status := mirrorStatus{
  76. Name: "arch-sync1",
  77. Worker: "test_worker1",
  78. IsMaster: true,
  79. Status: Success,
  80. LastUpdate: time.Now(),
  81. Upstream: "mirrors.tuna.tsinghua.edu.cn",
  82. Size: "3GB",
  83. }
  84. resp, err := postJSON(fmt.Sprintf("%s/workers/%s/jobs/%s", baseURL, status.Worker, status.Name), status)
  85. defer resp.Body.Close()
  86. So(err, ShouldBeNil)
  87. So(resp.StatusCode, ShouldEqual, http.StatusOK)
  88. Convey("list mirror status of an existed worker", func(ctx C) {
  89. expectedResponse, err := json.Marshal([]mirrorStatus{status})
  90. So(err, ShouldBeNil)
  91. resp, err := http.Get(baseURL + "/workers/test_worker1/jobs")
  92. So(err, ShouldBeNil)
  93. So(resp.StatusCode, ShouldEqual, http.StatusOK)
  94. // err = json.NewDecoder(resp.Body).Decode(&mirrorStatusList)
  95. body, err := ioutil.ReadAll(resp.Body)
  96. defer resp.Body.Close()
  97. So(err, ShouldBeNil)
  98. So(strings.TrimSpace(string(body)), ShouldEqual, string(expectedResponse))
  99. })
  100. Convey("list all job status of all workers", func(ctx C) {
  101. expectedResponse, err := json.Marshal([]mirrorStatus{status})
  102. So(err, ShouldBeNil)
  103. resp, err := http.Get(baseURL + "/jobs")
  104. So(err, ShouldBeNil)
  105. So(resp.StatusCode, ShouldEqual, http.StatusOK)
  106. body, err := ioutil.ReadAll(resp.Body)
  107. defer resp.Body.Close()
  108. So(err, ShouldBeNil)
  109. So(strings.TrimSpace(string(body)), ShouldEqual, string(expectedResponse))
  110. })
  111. })
  112. Convey("update mirror status of an inexisted worker", func(ctx C) {
  113. invalidWorker := "test_worker2"
  114. status := mirrorStatus{
  115. Name: "arch-sync2",
  116. Worker: invalidWorker,
  117. IsMaster: true,
  118. Status: Success,
  119. LastUpdate: time.Now(),
  120. Upstream: "mirrors.tuna.tsinghua.edu.cn",
  121. Size: "4GB",
  122. }
  123. resp, err := postJSON(fmt.Sprintf("%s/workers/%s/jobs/%s",
  124. baseURL, status.Worker, status.Name), status)
  125. So(err, ShouldBeNil)
  126. So(resp.StatusCode, ShouldEqual, http.StatusBadRequest)
  127. defer resp.Body.Close()
  128. var msg map[string]string
  129. err = json.NewDecoder(resp.Body).Decode(&msg)
  130. So(err, ShouldBeNil)
  131. So(msg[_errorKey], ShouldEqual, "invalid workerID "+invalidWorker)
  132. })
  133. Convey("handle client command", func(ctx C) {
  134. cmdChan := make(chan WorkerCmd, 1)
  135. workerServer := makeMockWorkerServer(cmdChan)
  136. workerPort := rand.Intn(10000) + 30000
  137. bindAddress := fmt.Sprintf("127.0.0.1:%d", workerPort)
  138. workerBaseURL := fmt.Sprintf("http://%s", bindAddress)
  139. w := workerStatus{
  140. ID: "test_worker_cmd",
  141. URL: workerBaseURL + "/cmd",
  142. }
  143. resp, err := postJSON(baseURL+"/workers", w)
  144. So(err, ShouldBeNil)
  145. So(resp.StatusCode, ShouldEqual, http.StatusOK)
  146. go func() {
  147. // run the mock worker server
  148. workerServer.Run(bindAddress)
  149. }()
  150. time.Sleep(50 * time.Microsecond)
  151. // verify the worker mock server is running
  152. workerResp, err := http.Get(workerBaseURL + "/ping")
  153. defer workerResp.Body.Close()
  154. So(err, ShouldBeNil)
  155. So(workerResp.StatusCode, ShouldEqual, http.StatusOK)
  156. Convey("when client send wrong cmd", func(ctx C) {
  157. clientCmd := ClientCmd{
  158. Cmd: CmdStart,
  159. MirrorID: "ubuntu-sync",
  160. WorkerID: "not_exist_worker",
  161. }
  162. resp, err := postJSON(baseURL+"/cmd", clientCmd)
  163. defer resp.Body.Close()
  164. So(err, ShouldBeNil)
  165. So(resp.StatusCode, ShouldEqual, http.StatusBadRequest)
  166. })
  167. Convey("when client send correct cmd", func(ctx C) {
  168. clientCmd := ClientCmd{
  169. Cmd: CmdStart,
  170. MirrorID: "ubuntu-sync",
  171. WorkerID: w.ID,
  172. }
  173. resp, err := postJSON(baseURL+"/cmd", clientCmd)
  174. defer resp.Body.Close()
  175. So(err, ShouldBeNil)
  176. So(resp.StatusCode, ShouldEqual, http.StatusOK)
  177. time.Sleep(50 * time.Microsecond)
  178. select {
  179. case cmd := <-cmdChan:
  180. ctx.So(cmd.Cmd, ShouldEqual, clientCmd.Cmd)
  181. ctx.So(cmd.MirrorID, ShouldEqual, clientCmd.MirrorID)
  182. default:
  183. ctx.So(0, ShouldEqual, 1)
  184. }
  185. })
  186. })
  187. })
  188. })
  189. }
  190. type mockDBAdapter struct {
  191. workerStore map[string]workerStatus
  192. statusStore map[string]mirrorStatus
  193. }
  194. func (b *mockDBAdapter) Init() error {
  195. return nil
  196. }
  197. func (b *mockDBAdapter) ListWorkers() ([]workerStatus, error) {
  198. workers := make([]workerStatus, len(b.workerStore))
  199. idx := 0
  200. for _, w := range b.workerStore {
  201. workers[idx] = w
  202. idx++
  203. }
  204. return workers, nil
  205. }
  206. func (b *mockDBAdapter) GetWorker(workerID string) (workerStatus, error) {
  207. w, ok := b.workerStore[workerID]
  208. if !ok {
  209. return workerStatus{}, fmt.Errorf("invalid workerId")
  210. }
  211. return w, nil
  212. }
  213. func (b *mockDBAdapter) CreateWorker(w workerStatus) (workerStatus, error) {
  214. // _, ok := b.workerStore[w.ID]
  215. // if ok {
  216. // return workerStatus{}, fmt.Errorf("duplicate worker name")
  217. // }
  218. b.workerStore[w.ID] = w
  219. return w, nil
  220. }
  221. func (b *mockDBAdapter) GetMirrorStatus(workerID, mirrorID string) (mirrorStatus, error) {
  222. id := mirrorID + "/" + workerID
  223. status, ok := b.statusStore[id]
  224. if !ok {
  225. return mirrorStatus{}, fmt.Errorf("no mirror %s exists in worker %s", mirrorID, workerID)
  226. }
  227. return status, nil
  228. }
  229. func (b *mockDBAdapter) UpdateMirrorStatus(workerID, mirrorID string, status mirrorStatus) (mirrorStatus, error) {
  230. // if _, ok := b.workerStore[workerID]; !ok {
  231. // // unregistered worker
  232. // return mirrorStatus{}, fmt.Errorf("invalid workerID %s", workerID)
  233. // }
  234. id := mirrorID + "/" + workerID
  235. b.statusStore[id] = status
  236. return status, nil
  237. }
  238. func (b *mockDBAdapter) ListMirrorStatus(workerID string) ([]mirrorStatus, error) {
  239. var mirrorStatusList []mirrorStatus
  240. // simulating a database fail
  241. if workerID == _magicBadWorkerID {
  242. return []mirrorStatus{}, fmt.Errorf("database fail")
  243. }
  244. for k, v := range b.statusStore {
  245. if wID := strings.Split(k, "/")[1]; wID == workerID {
  246. mirrorStatusList = append(mirrorStatusList, v)
  247. }
  248. }
  249. return mirrorStatusList, nil
  250. }
  251. func (b *mockDBAdapter) ListAllMirrorStatus() ([]mirrorStatus, error) {
  252. var mirrorStatusList []mirrorStatus
  253. for _, v := range b.statusStore {
  254. mirrorStatusList = append(mirrorStatusList, v)
  255. }
  256. return mirrorStatusList, nil
  257. }
  258. func (b *mockDBAdapter) Close() error {
  259. return nil
  260. }
  261. func makeMockWorkerServer(cmdChan chan WorkerCmd) *gin.Engine {
  262. r := gin.Default()
  263. r.GET("/ping", func(c *gin.Context) {
  264. c.JSON(http.StatusOK, gin.H{_infoKey: "pong"})
  265. })
  266. r.POST("/cmd", func(c *gin.Context) {
  267. var cmd WorkerCmd
  268. c.BindJSON(&cmd)
  269. cmdChan <- cmd
  270. })
  271. return r
  272. }