handlers.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. // Internal HTTP Handlers via server port
  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 clientHttpHandler(w http.ResponseWriter, req *http.Request) {
  69. debug("[recv] Get http://%v/client/ ", server.Name())
  70. w.WriteHeader(http.StatusOK)
  71. client := address + ":" + strconv.Itoa(clientPort)
  72. w.Write([]byte(client))
  73. }
  74. func JoinHttpHandler(w http.ResponseWriter, req *http.Request) {
  75. command := &JoinCommand{}
  76. if err := decodeJsonRequest(req, command); err == nil {
  77. debug("Receive Join Request from %s", command.Name)
  78. excute(command, &w, req)
  79. } else {
  80. w.WriteHeader(http.StatusInternalServerError)
  81. return
  82. }
  83. }
  84. //--------------------------------------
  85. // external HTTP Handlers via client port
  86. //--------------------------------------
  87. func SetHttpHandler(w http.ResponseWriter, req *http.Request) {
  88. key := req.URL.Path[len("/set/"):]
  89. content, err := ioutil.ReadAll(req.Body)
  90. if err != nil {
  91. warn("raftd: Unable to read: %v", err)
  92. w.WriteHeader(http.StatusInternalServerError)
  93. return
  94. }
  95. debug("[recv] POST http://%v/set/%s [%s]", server.Name(), key, content)
  96. command := &SetCommand{}
  97. command.Key = key
  98. values := strings.Split(string(content), ",")
  99. command.Value = values[0]
  100. if len(values) == 2 {
  101. duration, err := strconv.Atoi(values[1])
  102. if err != nil {
  103. warn("raftd: Bad duration: %v", err)
  104. w.WriteHeader(http.StatusInternalServerError)
  105. return
  106. }
  107. command.ExpireTime = time.Now().Add(time.Second * (time.Duration)(duration))
  108. } else {
  109. command.ExpireTime = time.Unix(0, 0)
  110. }
  111. excute(command, &w, req)
  112. }
  113. func DeleteHttpHandler(w http.ResponseWriter, req *http.Request) {
  114. key := req.URL.Path[len("/delete/"):]
  115. debug("[recv] GET http://%v/delete/%s", server.Name(), key)
  116. command := &DeleteCommand{}
  117. command.Key = key
  118. excute(command, &w, req)
  119. }
  120. func excute(c Command, w *http.ResponseWriter, req *http.Request) {
  121. if server.State() == "leader" {
  122. if body, err := server.Do(c); err != nil {
  123. warn("Commit failed %v", err)
  124. (*w).WriteHeader(http.StatusInternalServerError)
  125. return
  126. } else {
  127. (*w).WriteHeader(http.StatusOK)
  128. if body == nil {
  129. return
  130. }
  131. body, ok := body.([]byte)
  132. if !ok {
  133. panic("wrong type")
  134. }
  135. (*w).Write(body)
  136. return
  137. }
  138. } else {
  139. // current no leader
  140. if server.Leader() == "" {
  141. (*w).WriteHeader(http.StatusInternalServerError)
  142. return
  143. }
  144. // tell the client where is the leader
  145. debug("Redirect to the leader %s", server.Leader())
  146. path := req.URL.Path
  147. var scheme string
  148. if scheme = req.URL.Scheme; scheme == "" {
  149. scheme = "http://"
  150. }
  151. url := scheme + leaderClient() + path
  152. debug("redirect to %s", url)
  153. http.Redirect(*w, req, url, http.StatusTemporaryRedirect)
  154. return
  155. }
  156. (*w).WriteHeader(http.StatusInternalServerError)
  157. return
  158. }
  159. func MasterHttpHandler(w http.ResponseWriter, req *http.Request) {
  160. w.WriteHeader(http.StatusOK)
  161. w.Write([]byte(server.Leader()))
  162. }
  163. func GetHttpHandler(w http.ResponseWriter, req *http.Request) {
  164. key := req.URL.Path[len("/get/"):]
  165. debug("[recv] GET http://%v/get/%s", server.Name(), key)
  166. command := &GetCommand{}
  167. command.Key = key
  168. if body, err := command.Apply(server); err != nil {
  169. warn("raftd: Unable to write file: %v", err)
  170. w.WriteHeader(http.StatusInternalServerError)
  171. return
  172. } else {
  173. w.WriteHeader(http.StatusOK)
  174. body, ok := body.([]byte)
  175. if !ok {
  176. panic("wrong type")
  177. }
  178. w.Write(body)
  179. return
  180. }
  181. }
  182. func WatchHttpHandler(w http.ResponseWriter, req *http.Request) {
  183. key := req.URL.Path[len("/watch/"):]
  184. command := &WatchCommand{}
  185. command.Key = key
  186. if req.Method == "GET" {
  187. debug("[recv] GET http://%v/watch/%s", server.Name(), key)
  188. command.SinceIndex = 0
  189. } else if req.Method == "POST" {
  190. debug("[recv] POST http://%v/watch/%s", server.Name(), key)
  191. content, err := ioutil.ReadAll(req.Body)
  192. sinceIndex, err := strconv.ParseUint(string(content), 10, 64)
  193. if err != nil {
  194. w.WriteHeader(http.StatusBadRequest)
  195. }
  196. command.SinceIndex = sinceIndex
  197. } else {
  198. w.WriteHeader(http.StatusMethodNotAllowed)
  199. return
  200. }
  201. if body, err := command.Apply(server); err != nil {
  202. warn("raftd: Unable to write file: %v", err)
  203. w.WriteHeader(http.StatusInternalServerError)
  204. return
  205. } else {
  206. w.WriteHeader(http.StatusOK)
  207. body, ok := body.([]byte)
  208. if !ok {
  209. panic("wrong type")
  210. }
  211. w.Write(body)
  212. return
  213. }
  214. }