server_test.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 []WorkerStatus
  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(
  102. []webMirrorStatus{convertMirrorStatus(status)},
  103. )
  104. So(err, ShouldBeNil)
  105. resp, err := http.Get(baseURL + "/jobs")
  106. So(err, ShouldBeNil)
  107. So(resp.StatusCode, ShouldEqual, http.StatusOK)
  108. body, err := ioutil.ReadAll(resp.Body)
  109. defer resp.Body.Close()
  110. So(err, ShouldBeNil)
  111. So(strings.TrimSpace(string(body)), ShouldEqual, string(expectedResponse))
  112. })
  113. })
  114. Convey("update mirror status of an inexisted worker", func(ctx C) {
  115. invalidWorker := "test_worker2"
  116. status := MirrorStatus{
  117. Name: "arch-sync2",
  118. Worker: invalidWorker,
  119. IsMaster: true,
  120. Status: Success,
  121. LastUpdate: time.Now(),
  122. Upstream: "mirrors.tuna.tsinghua.edu.cn",
  123. Size: "4GB",
  124. }
  125. resp, err := postJSON(fmt.Sprintf("%s/workers/%s/jobs/%s",
  126. baseURL, status.Worker, status.Name), status)
  127. So(err, ShouldBeNil)
  128. So(resp.StatusCode, ShouldEqual, http.StatusBadRequest)
  129. defer resp.Body.Close()
  130. var msg map[string]string
  131. err = json.NewDecoder(resp.Body).Decode(&msg)
  132. So(err, ShouldBeNil)
  133. So(msg[_errorKey], ShouldEqual, "invalid workerID "+invalidWorker)
  134. })
  135. Convey("handle client command", func(ctx C) {
  136. cmdChan := make(chan WorkerCmd, 1)
  137. workerServer := makeMockWorkerServer(cmdChan)
  138. workerPort := rand.Intn(10000) + 30000
  139. bindAddress := fmt.Sprintf("127.0.0.1:%d", workerPort)
  140. workerBaseURL := fmt.Sprintf("http://%s", bindAddress)
  141. w := WorkerStatus{
  142. ID: "test_worker_cmd",
  143. URL: workerBaseURL + "/cmd",
  144. }
  145. resp, err := postJSON(baseURL+"/workers", w)
  146. So(err, ShouldBeNil)
  147. So(resp.StatusCode, ShouldEqual, http.StatusOK)
  148. go func() {
  149. // run the mock worker server
  150. workerServer.Run(bindAddress)
  151. }()
  152. time.Sleep(50 * time.Microsecond)
  153. // verify the worker mock server is running
  154. workerResp, err := http.Get(workerBaseURL + "/ping")
  155. defer workerResp.Body.Close()
  156. So(err, ShouldBeNil)
  157. So(workerResp.StatusCode, ShouldEqual, http.StatusOK)
  158. Convey("when client send wrong cmd", func(ctx C) {
  159. clientCmd := ClientCmd{
  160. Cmd: CmdStart,
  161. MirrorID: "ubuntu-sync",
  162. WorkerID: "not_exist_worker",
  163. }
  164. resp, err := postJSON(baseURL+"/cmd", clientCmd)
  165. defer resp.Body.Close()
  166. So(err, ShouldBeNil)
  167. So(resp.StatusCode, ShouldEqual, http.StatusBadRequest)
  168. })
  169. Convey("when client send correct cmd", func(ctx C) {
  170. clientCmd := ClientCmd{
  171. Cmd: CmdStart,
  172. MirrorID: "ubuntu-sync",
  173. WorkerID: w.ID,
  174. }
  175. resp, err := postJSON(baseURL+"/cmd", clientCmd)
  176. defer resp.Body.Close()
  177. So(err, ShouldBeNil)
  178. So(resp.StatusCode, ShouldEqual, http.StatusOK)
  179. time.Sleep(50 * time.Microsecond)
  180. select {
  181. case cmd := <-cmdChan:
  182. ctx.So(cmd.Cmd, ShouldEqual, clientCmd.Cmd)
  183. ctx.So(cmd.MirrorID, ShouldEqual, clientCmd.MirrorID)
  184. default:
  185. ctx.So(0, ShouldEqual, 1)
  186. }
  187. })
  188. })
  189. })
  190. })
  191. }
  192. type mockDBAdapter struct {
  193. workerStore map[string]WorkerStatus
  194. statusStore map[string]MirrorStatus
  195. }
  196. func (b *mockDBAdapter) Init() error {
  197. return nil
  198. }
  199. func (b *mockDBAdapter) ListWorkers() ([]WorkerStatus, error) {
  200. workers := make([]WorkerStatus, len(b.workerStore))
  201. idx := 0
  202. for _, w := range b.workerStore {
  203. workers[idx] = w
  204. idx++
  205. }
  206. return workers, nil
  207. }
  208. func (b *mockDBAdapter) GetWorker(workerID string) (WorkerStatus, error) {
  209. w, ok := b.workerStore[workerID]
  210. if !ok {
  211. return WorkerStatus{}, fmt.Errorf("invalid workerId")
  212. }
  213. return w, nil
  214. }
  215. func (b *mockDBAdapter) CreateWorker(w WorkerStatus) (WorkerStatus, error) {
  216. // _, ok := b.workerStore[w.ID]
  217. // if ok {
  218. // return workerStatus{}, fmt.Errorf("duplicate worker name")
  219. // }
  220. b.workerStore[w.ID] = w
  221. return w, nil
  222. }
  223. func (b *mockDBAdapter) GetMirrorStatus(workerID, mirrorID string) (MirrorStatus, error) {
  224. id := mirrorID + "/" + workerID
  225. status, ok := b.statusStore[id]
  226. if !ok {
  227. return MirrorStatus{}, fmt.Errorf("no mirror %s exists in worker %s", mirrorID, workerID)
  228. }
  229. return status, nil
  230. }
  231. func (b *mockDBAdapter) UpdateMirrorStatus(workerID, mirrorID string, status MirrorStatus) (MirrorStatus, error) {
  232. // if _, ok := b.workerStore[workerID]; !ok {
  233. // // unregistered worker
  234. // return MirrorStatus{}, fmt.Errorf("invalid workerID %s", workerID)
  235. // }
  236. id := mirrorID + "/" + workerID
  237. b.statusStore[id] = status
  238. return status, nil
  239. }
  240. func (b *mockDBAdapter) ListMirrorStatus(workerID string) ([]MirrorStatus, error) {
  241. var mirrorStatusList []MirrorStatus
  242. // simulating a database fail
  243. if workerID == _magicBadWorkerID {
  244. return []MirrorStatus{}, fmt.Errorf("database fail")
  245. }
  246. for k, v := range b.statusStore {
  247. if wID := strings.Split(k, "/")[1]; wID == workerID {
  248. mirrorStatusList = append(mirrorStatusList, v)
  249. }
  250. }
  251. return mirrorStatusList, nil
  252. }
  253. func (b *mockDBAdapter) ListAllMirrorStatus() ([]MirrorStatus, error) {
  254. var mirrorStatusList []MirrorStatus
  255. for _, v := range b.statusStore {
  256. mirrorStatusList = append(mirrorStatusList, v)
  257. }
  258. return mirrorStatusList, nil
  259. }
  260. func (b *mockDBAdapter) Close() error {
  261. return nil
  262. }
  263. func makeMockWorkerServer(cmdChan chan WorkerCmd) *gin.Engine {
  264. r := gin.Default()
  265. r.GET("/ping", func(c *gin.Context) {
  266. c.JSON(http.StatusOK, gin.H{_infoKey: "pong"})
  267. })
  268. r.POST("/cmd", func(c *gin.Context) {
  269. var cmd WorkerCmd
  270. c.BindJSON(&cmd)
  271. cmdChan <- cmd
  272. })
  273. return r
  274. }