handlers.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package main
  2. import (
  3. "encoding/json"
  4. "github.com/xiangli-cmu/go-raft"
  5. "net/http"
  6. "fmt"
  7. "io/ioutil"
  8. //"bytes"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. //--------------------------------------
  14. // HTTP Handlers
  15. //--------------------------------------
  16. // Get all the current logs
  17. func GetLogHttpHandler(w http.ResponseWriter, req *http.Request) {
  18. debug("[recv] GET http://%v/log", server.Name())
  19. w.Header().Set("Content-Type", "application/json")
  20. w.WriteHeader(http.StatusOK)
  21. json.NewEncoder(w).Encode(server.LogEntries())
  22. }
  23. func VoteHttpHandler(w http.ResponseWriter, req *http.Request) {
  24. rvreq := &raft.RequestVoteRequest{}
  25. err := decodeJsonRequest(req, rvreq)
  26. if err == nil {
  27. debug("[recv] POST http://%v/vote [%s]", server.Name(), rvreq.CandidateName)
  28. if resp, _ := server.RequestVote(rvreq); resp != nil {
  29. w.WriteHeader(http.StatusOK)
  30. json.NewEncoder(w).Encode(resp)
  31. return
  32. }
  33. }
  34. warn("[vote] ERROR: %v", err)
  35. w.WriteHeader(http.StatusInternalServerError)
  36. }
  37. func AppendEntriesHttpHandler(w http.ResponseWriter, req *http.Request) {
  38. aereq := &raft.AppendEntriesRequest{}
  39. err := decodeJsonRequest(req, aereq)
  40. if err == nil {
  41. debug("[recv] POST http://%s/log/append [%d]", server.Name(), len(aereq.Entries))
  42. if resp, _ := server.AppendEntries(aereq); resp != nil {
  43. w.WriteHeader(http.StatusOK)
  44. json.NewEncoder(w).Encode(resp)
  45. if !resp.Success {
  46. debug("[Append Entry] Step back")
  47. }
  48. return
  49. }
  50. }
  51. warn("[append] ERROR: %v", err)
  52. w.WriteHeader(http.StatusInternalServerError)
  53. }
  54. func SnapshotHttpHandler(w http.ResponseWriter, req *http.Request) {
  55. aereq := &raft.SnapshotRequest{}
  56. err := decodeJsonRequest(req, aereq)
  57. if err == nil {
  58. debug("[recv] POST http://%s/snapshot/ ", server.Name())
  59. if resp, _ := server.SnapshotRecovery(aereq); resp != nil {
  60. w.WriteHeader(http.StatusOK)
  61. json.NewEncoder(w).Encode(resp)
  62. return
  63. }
  64. }
  65. warn("[snapshot] ERROR: %v", err)
  66. w.WriteHeader(http.StatusInternalServerError)
  67. }
  68. func JoinHttpHandler(w http.ResponseWriter, req *http.Request) {
  69. command := &JoinCommand{}
  70. if err := decodeJsonRequest(req, command); err == nil {
  71. debug("Receive Join Request from %s", command.Name)
  72. excute(command, &w, req)
  73. } else {
  74. w.WriteHeader(http.StatusInternalServerError)
  75. return
  76. }
  77. }
  78. func SetHttpHandler(w http.ResponseWriter, req *http.Request) {
  79. key := req.URL.Path[len("/set/"):]
  80. content, err := ioutil.ReadAll(req.Body)
  81. if err != nil {
  82. warn("raftd: Unable to read: %v", err)
  83. w.WriteHeader(http.StatusInternalServerError)
  84. return
  85. }
  86. debug("[recv] POST http://%v/set/%s [%s]", server.Name(), key, content)
  87. command := &SetCommand{}
  88. command.Key = key
  89. values := strings.Split(string(content), ",")
  90. command.Value = values[0]
  91. if len(values) == 2 {
  92. duration, err := strconv.Atoi(values[1])
  93. if err != nil {
  94. warn("raftd: Bad duration: %v", err)
  95. w.WriteHeader(http.StatusInternalServerError)
  96. return
  97. }
  98. command.ExpireTime = time.Now().Add(time.Second * (time.Duration)(duration))
  99. } else {
  100. command.ExpireTime = time.Unix(0, 0)
  101. }
  102. excute(command, &w, req)
  103. }
  104. func DeleteHttpHandler(w http.ResponseWriter, req *http.Request) {
  105. key := req.URL.Path[len("/delete/"):]
  106. debug("[recv] GET http://%v/delete/%s", server.Name(), key)
  107. command := &DeleteCommand{}
  108. command.Key = key
  109. excute(command, &w, req)
  110. }
  111. func excute(c Command, w *http.ResponseWriter, req *http.Request) {
  112. if server.State() == "leader" {
  113. if body, err := server.Do(c); err != nil {
  114. warn("Commit failed %v", err)
  115. (*w).WriteHeader(http.StatusInternalServerError)
  116. return
  117. } else {
  118. (*w).WriteHeader(http.StatusOK)
  119. if body == nil {
  120. return
  121. }
  122. body, ok := body.([]byte)
  123. if !ok {
  124. panic ("wrong type")
  125. }
  126. (*w).Write(body)
  127. return
  128. }
  129. } else {
  130. // tell the client where is the leader
  131. debug("Redirect to the leader %s", server.Leader())
  132. path := req.URL.Path
  133. url := "http://" + server.Leader() + path
  134. debug("redirect to ", url)
  135. http.Redirect(*w, req, url, http.StatusTemporaryRedirect)
  136. return
  137. }
  138. (*w).WriteHeader(http.StatusInternalServerError)
  139. return
  140. }
  141. func MasterHttpHandler(w http.ResponseWriter, req *http.Request) {
  142. w.WriteHeader(http.StatusOK)
  143. w.Write([]byte(server.Leader()))
  144. }
  145. func GetHttpHandler(w http.ResponseWriter, req *http.Request) {
  146. key := req.URL.Path[len("/get/"):]
  147. debug("[recv] GET http://%v/get/%s", server.Name(), key)
  148. command := &GetCommand{}
  149. command.Key = key
  150. if body, err := command.Apply(server); err != nil {
  151. warn("raftd: Unable to write file: %v", err)
  152. w.WriteHeader(http.StatusInternalServerError)
  153. return
  154. } else {
  155. w.WriteHeader(http.StatusOK)
  156. body, ok := body.([]byte)
  157. if !ok {
  158. panic ("wrong type")
  159. }
  160. w.Write(body)
  161. return
  162. }
  163. }
  164. func WatchHttpHandler(w http.ResponseWriter, req *http.Request) {
  165. key := req.URL.Path[len("/watch/"):]
  166. debug("[recv] GET http://%v/watch/%s", server.Name(), key)
  167. command := &WatchCommand{}
  168. command.Key = key
  169. if body, err := command.Apply(server); err != nil {
  170. warn("raftd: Unable to write file: %v", err)
  171. w.WriteHeader(http.StatusInternalServerError)
  172. return
  173. } else {
  174. w.WriteHeader(http.StatusOK)
  175. body, ok := body.([]byte)
  176. if !ok {
  177. panic ("wrong type")
  178. }
  179. w.Write(body)
  180. return
  181. }
  182. }