handlers.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package main
  2. import (
  3. "encoding/json"
  4. "github.com/coreos/go-raft"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. )
  9. //--------------------------------------
  10. // Internal HTTP Handlers via server port
  11. //--------------------------------------
  12. // Get all the current logs
  13. func GetLogHttpHandler(w http.ResponseWriter, req *http.Request) {
  14. debug("[recv] GET http://%v/log", server.Name())
  15. w.Header().Set("Content-Type", "application/json")
  16. w.WriteHeader(http.StatusOK)
  17. json.NewEncoder(w).Encode(server.LogEntries())
  18. }
  19. func VoteHttpHandler(w http.ResponseWriter, req *http.Request) {
  20. rvreq := &raft.RequestVoteRequest{}
  21. err := decodeJsonRequest(req, rvreq)
  22. if err == nil {
  23. debug("[recv] POST http://%v/vote [%s]", server.Name(), rvreq.CandidateName)
  24. if resp := server.RequestVote(rvreq); resp != nil {
  25. w.WriteHeader(http.StatusOK)
  26. json.NewEncoder(w).Encode(resp)
  27. return
  28. }
  29. }
  30. warn("[vote] ERROR: %v", err)
  31. w.WriteHeader(http.StatusInternalServerError)
  32. }
  33. func AppendEntriesHttpHandler(w http.ResponseWriter, req *http.Request) {
  34. aereq := &raft.AppendEntriesRequest{}
  35. err := decodeJsonRequest(req, aereq)
  36. if err == nil {
  37. debug("[recv] POST http://%s/log/append [%d]", server.Name(), len(aereq.Entries))
  38. if resp := server.AppendEntries(aereq); resp != nil {
  39. w.WriteHeader(http.StatusOK)
  40. json.NewEncoder(w).Encode(resp)
  41. if !resp.Success {
  42. debug("[Append Entry] Step back")
  43. }
  44. return
  45. }
  46. }
  47. warn("[append] ERROR: %v", err)
  48. w.WriteHeader(http.StatusInternalServerError)
  49. }
  50. func SnapshotHttpHandler(w http.ResponseWriter, req *http.Request) {
  51. aereq := &raft.SnapshotRequest{}
  52. err := decodeJsonRequest(req, aereq)
  53. if err == nil {
  54. debug("[recv] POST http://%s/snapshot/ ", server.Name())
  55. if resp, _ := server.SnapshotRecovery(aereq); resp != nil {
  56. w.WriteHeader(http.StatusOK)
  57. json.NewEncoder(w).Encode(resp)
  58. return
  59. }
  60. }
  61. warn("[snapshot] ERROR: %v", err)
  62. w.WriteHeader(http.StatusInternalServerError)
  63. }
  64. func clientHttpHandler(w http.ResponseWriter, req *http.Request) {
  65. debug("[recv] Get http://%v/client/ ", server.Name())
  66. w.WriteHeader(http.StatusOK)
  67. client := address + ":" + strconv.Itoa(clientPort)
  68. w.Write([]byte(client))
  69. }
  70. func JoinHttpHandler(w http.ResponseWriter, req *http.Request) {
  71. command := &JoinCommand{}
  72. if err := decodeJsonRequest(req, command); err == nil {
  73. debug("Receive Join Request from %s", command.Name)
  74. excute(command, &w, req)
  75. } else {
  76. w.WriteHeader(http.StatusInternalServerError)
  77. return
  78. }
  79. }
  80. //--------------------------------------
  81. // external HTTP Handlers via client port
  82. //--------------------------------------
  83. func Multiplexer(w http.ResponseWriter, req *http.Request) {
  84. if req.Method == "GET" {
  85. GetHttpHandler(&w, req)
  86. } else if req.Method == "POST" {
  87. SetHttpHandler(&w, req)
  88. } else if req.Method == "DELETE" {
  89. DeleteHttpHandler(&w, req)
  90. } else {
  91. w.WriteHeader(http.StatusMethodNotAllowed)
  92. return
  93. }
  94. }
  95. func SetHttpHandler(w *http.ResponseWriter, req *http.Request) {
  96. key := req.URL.Path[len("/v1/keys/"):]
  97. debug("[recv] POST http://%v/v1/keys/%s", server.Name(), key)
  98. command := &SetCommand{}
  99. command.Key = key
  100. command.Value = req.FormValue("value")
  101. strDuration := req.FormValue("ttl")
  102. if strDuration != "" {
  103. duration, err := strconv.Atoi(strDuration)
  104. if err != nil {
  105. warn("raftd: Bad duration: %v", err)
  106. (*w).WriteHeader(http.StatusInternalServerError)
  107. return
  108. }
  109. command.ExpireTime = time.Now().Add(time.Second * (time.Duration)(duration))
  110. } else {
  111. command.ExpireTime = time.Unix(0, 0)
  112. }
  113. excute(command, w, req)
  114. }
  115. func DeleteHttpHandler(w *http.ResponseWriter, req *http.Request) {
  116. key := req.URL.Path[len("/v1/keys/"):]
  117. debug("[recv] DELETE http://%v/v1/keys/%s", server.Name(), key)
  118. command := &DeleteCommand{}
  119. command.Key = key
  120. excute(command, w, req)
  121. }
  122. func excute(c Command, w *http.ResponseWriter, req *http.Request) {
  123. if server.State() == "leader" {
  124. if body, err := server.Do(c); err != nil {
  125. warn("Commit failed %v", err)
  126. (*w).WriteHeader(http.StatusInternalServerError)
  127. return
  128. } else {
  129. (*w).WriteHeader(http.StatusOK)
  130. if body == nil {
  131. return
  132. }
  133. body, ok := body.([]byte)
  134. if !ok {
  135. panic("wrong type")
  136. }
  137. (*w).Write(body)
  138. return
  139. }
  140. } else {
  141. // current no leader
  142. if server.Leader() == "" {
  143. (*w).WriteHeader(http.StatusInternalServerError)
  144. return
  145. }
  146. // tell the client where is the leader
  147. debug("Redirect to the leader %s", server.Leader())
  148. path := req.URL.Path
  149. var scheme string
  150. if scheme = req.URL.Scheme; scheme == "" {
  151. scheme = "http://"
  152. }
  153. url := scheme + leaderClient() + path
  154. debug("redirect to %s", url)
  155. http.Redirect(*w, req, url, http.StatusTemporaryRedirect)
  156. return
  157. }
  158. (*w).WriteHeader(http.StatusInternalServerError)
  159. return
  160. }
  161. func MasterHttpHandler(w http.ResponseWriter, req *http.Request) {
  162. w.WriteHeader(http.StatusOK)
  163. w.Write([]byte(server.Leader()))
  164. }
  165. func GetHttpHandler(w *http.ResponseWriter, req *http.Request) {
  166. key := req.URL.Path[len("/v1/keys/"):]
  167. debug("[recv] GET http://%v/v1/keys/%s", server.Name(), key)
  168. command := &GetCommand{}
  169. command.Key = key
  170. if body, err := command.Apply(server); err != nil {
  171. warn("raftd: Unable to write file: %v", err)
  172. (*w).WriteHeader(http.StatusInternalServerError)
  173. return
  174. } else {
  175. (*w).WriteHeader(http.StatusOK)
  176. body, ok := body.([]byte)
  177. if !ok {
  178. panic("wrong type")
  179. }
  180. (*w).Write(body)
  181. return
  182. }
  183. }
  184. func ListHttpHandler(w http.ResponseWriter, req *http.Request) {
  185. prefix := req.URL.Path[len("/v1/list/"):]
  186. debug("[recv] GET http://%v/v1/list/%s", server.Name(), prefix)
  187. command := &ListCommand{}
  188. command.Prefix = prefix
  189. if body, err := command.Apply(server); err != nil {
  190. warn("raftd: Unable to write file: %v", err)
  191. w.WriteHeader(http.StatusInternalServerError)
  192. return
  193. } else {
  194. w.WriteHeader(http.StatusOK)
  195. body, ok := body.([]byte)
  196. if !ok {
  197. panic("wrong type")
  198. }
  199. w.Write(body)
  200. return
  201. }
  202. }
  203. func WatchHttpHandler(w http.ResponseWriter, req *http.Request) {
  204. key := req.URL.Path[len("/v1/watch/"):]
  205. command := &WatchCommand{}
  206. command.Key = key
  207. if req.Method == "GET" {
  208. debug("[recv] GET http://%v/watch/%s", server.Name(), key)
  209. command.SinceIndex = 0
  210. } else if req.Method == "POST" {
  211. debug("[recv] POST http://%v/watch/%s", server.Name(), key)
  212. content := req.FormValue("index")
  213. sinceIndex, err := strconv.ParseUint(string(content), 10, 64)
  214. if err != nil {
  215. w.WriteHeader(http.StatusBadRequest)
  216. }
  217. command.SinceIndex = sinceIndex
  218. } else {
  219. w.WriteHeader(http.StatusMethodNotAllowed)
  220. return
  221. }
  222. if body, err := command.Apply(server); err != nil {
  223. warn("raftd: Unable to write file: %v", err)
  224. w.WriteHeader(http.StatusInternalServerError)
  225. return
  226. } else {
  227. w.WriteHeader(http.StatusOK)
  228. body, ok := body.([]byte)
  229. if !ok {
  230. panic("wrong type")
  231. }
  232. w.Write(body)
  233. return
  234. }
  235. }