client_handlers.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package main
  2. import (
  3. "github.com/coreos/etcd/store"
  4. "net/http"
  5. "strconv"
  6. "time"
  7. )
  8. //-------------------------------------------------------------------
  9. // Handlers to handle etcd-store related request via raft client port
  10. //-------------------------------------------------------------------
  11. // Multiplex GET/POST/DELETE request to corresponding handlers
  12. func Multiplexer(w http.ResponseWriter, req *http.Request) {
  13. if req.Method == "GET" {
  14. GetHttpHandler(&w, req)
  15. } else if req.Method == "POST" {
  16. SetHttpHandler(&w, req)
  17. } else if req.Method == "DELETE" {
  18. DeleteHttpHandler(&w, req)
  19. } else {
  20. w.WriteHeader(http.StatusMethodNotAllowed)
  21. return
  22. }
  23. }
  24. //--------------------------------------
  25. // State sensitive handlers
  26. // Set/Delte will dispatch to leader
  27. //--------------------------------------
  28. // Set Command Handler
  29. func SetHttpHandler(w *http.ResponseWriter, req *http.Request) {
  30. key := req.URL.Path[len("/v1/keys/"):]
  31. debug("[recv] POST http://%v/v1/keys/%s", raftServer.Name(), key)
  32. command := &SetCommand{}
  33. command.Key = key
  34. command.Value = req.FormValue("value")
  35. if len(command.Value) == 0 {
  36. (*w).WriteHeader(http.StatusBadRequest)
  37. (*w).Write([]byte("Set: Value Required\n"))
  38. return
  39. }
  40. strDuration := req.FormValue("ttl")
  41. var err error
  42. command.ExpireTime, err = durationToExpireTime(strDuration)
  43. if err != nil {
  44. warn("The given duration is not a number: %v", err)
  45. (*w).WriteHeader(http.StatusInternalServerError)
  46. }
  47. dispatch(command, w, req, true)
  48. }
  49. // TestAndSet handler
  50. func TestAndSetHttpHandler(w http.ResponseWriter, req *http.Request) {
  51. key := req.URL.Path[len("/v1/testAndSet/"):]
  52. debug("[recv] POST http://%v/v1/testAndSet/%s", raftServer.Name(), key)
  53. command := &TestAndSetCommand{}
  54. command.Key = key
  55. command.PrevValue = req.FormValue("prevValue")
  56. command.Value = req.FormValue("value")
  57. if len(command.Value) == 0 {
  58. (w).WriteHeader(http.StatusBadRequest)
  59. (w).Write([]byte("TestAndSet: Value Required\n"))
  60. return
  61. }
  62. if len(command.PrevValue) == 0 {
  63. (w).WriteHeader(http.StatusBadRequest)
  64. (w).Write([]byte("TestAndSet: PrevValue Required\n"))
  65. return
  66. }
  67. strDuration := req.FormValue("ttl")
  68. var err error
  69. command.ExpireTime, err = durationToExpireTime(strDuration)
  70. if err != nil {
  71. warn("The given duration is not a number: %v", err)
  72. w.WriteHeader(http.StatusInternalServerError)
  73. }
  74. dispatch(command, &w, req, true)
  75. }
  76. // Delete Handler
  77. func DeleteHttpHandler(w *http.ResponseWriter, req *http.Request) {
  78. key := req.URL.Path[len("/v1/keys/"):]
  79. debug("[recv] DELETE http://%v/v1/keys/%s", raftServer.Name(), key)
  80. command := &DeleteCommand{}
  81. command.Key = key
  82. dispatch(command, w, req, true)
  83. }
  84. // Dispatch the command to leader
  85. func dispatch(c Command, w *http.ResponseWriter, req *http.Request, client bool) {
  86. if raftServer.State() == "leader" {
  87. if body, err := raftServer.Do(c); err != nil {
  88. if _, ok := err.(store.NotFoundError); ok {
  89. http.NotFound((*w), req)
  90. return
  91. }
  92. if _, ok := err.(store.TestFail); ok {
  93. (*w).WriteHeader(http.StatusBadRequest)
  94. (*w).Write([]byte(err.Error() + "\n"))
  95. return
  96. }
  97. (*w).WriteHeader(http.StatusInternalServerError)
  98. return
  99. } else {
  100. body, ok := body.([]byte)
  101. if !ok {
  102. panic("wrong type")
  103. }
  104. if body == nil {
  105. http.NotFound((*w), req)
  106. } else {
  107. (*w).WriteHeader(http.StatusOK)
  108. (*w).Write(body)
  109. }
  110. return
  111. }
  112. } else {
  113. // current no leader
  114. if raftServer.Leader() == "" {
  115. (*w).WriteHeader(http.StatusInternalServerError)
  116. return
  117. }
  118. // tell the client where is the leader
  119. path := req.URL.Path
  120. var scheme string
  121. if scheme = req.URL.Scheme; scheme == "" {
  122. scheme = "http://"
  123. }
  124. var url string
  125. if client {
  126. url = scheme + raftTransporter.GetLeaderClientAddress() + path
  127. } else {
  128. url = scheme + raftServer.Leader() + path
  129. }
  130. debug("Redirect to %s", url)
  131. http.Redirect(*w, req, url, http.StatusTemporaryRedirect)
  132. return
  133. }
  134. (*w).WriteHeader(http.StatusInternalServerError)
  135. return
  136. }
  137. //--------------------------------------
  138. // State non-sensitive handlers
  139. // will not dispatch to leader
  140. // TODO: add sensitive version for these
  141. // command?
  142. //--------------------------------------
  143. // Handler to return the current leader name
  144. func LeaderHttpHandler(w http.ResponseWriter, req *http.Request) {
  145. w.WriteHeader(http.StatusOK)
  146. w.Write([]byte(raftServer.Leader()))
  147. }
  148. // Get Handler
  149. func GetHttpHandler(w *http.ResponseWriter, req *http.Request) {
  150. key := req.URL.Path[len("/v1/keys/"):]
  151. debug("[recv] GET http://%v/v1/keys/%s", raftServer.Name(), key)
  152. command := &GetCommand{}
  153. command.Key = key
  154. if body, err := command.Apply(raftServer); err != nil {
  155. if _, ok := err.(store.NotFoundError); ok {
  156. http.NotFound((*w), req)
  157. return
  158. }
  159. (*w).WriteHeader(http.StatusInternalServerError)
  160. return
  161. } else {
  162. body, ok := body.([]byte)
  163. if !ok {
  164. panic("wrong type")
  165. }
  166. (*w).WriteHeader(http.StatusOK)
  167. (*w).Write(body)
  168. return
  169. }
  170. }
  171. // List Handler
  172. func ListHttpHandler(w http.ResponseWriter, req *http.Request) {
  173. prefix := req.URL.Path[len("/v1/list/"):]
  174. debug("[recv] GET http://%v/v1/list/%s", raftServer.Name(), prefix)
  175. command := &ListCommand{}
  176. command.Prefix = prefix
  177. if body, err := command.Apply(raftServer); err != nil {
  178. if _, ok := err.(store.NotFoundError); ok {
  179. http.NotFound(w, req)
  180. return
  181. }
  182. w.WriteHeader(http.StatusInternalServerError)
  183. return
  184. } else {
  185. w.WriteHeader(http.StatusOK)
  186. body, ok := body.([]byte)
  187. if !ok {
  188. panic("wrong type")
  189. }
  190. w.Write(body)
  191. return
  192. }
  193. }
  194. // Watch handler
  195. func WatchHttpHandler(w http.ResponseWriter, req *http.Request) {
  196. key := req.URL.Path[len("/v1/watch/"):]
  197. command := &WatchCommand{}
  198. command.Key = key
  199. if req.Method == "GET" {
  200. debug("[recv] GET http://%v/watch/%s", raftServer.Name(), key)
  201. command.SinceIndex = 0
  202. } else if req.Method == "POST" {
  203. // watch from a specific index
  204. debug("[recv] POST http://%v/watch/%s", raftServer.Name(), key)
  205. content := req.FormValue("index")
  206. sinceIndex, err := strconv.ParseUint(string(content), 10, 64)
  207. if err != nil {
  208. w.WriteHeader(http.StatusBadRequest)
  209. (w).Write([]byte("Watch From Index: Vaild Index Required\n"))
  210. }
  211. command.SinceIndex = sinceIndex
  212. } else {
  213. w.WriteHeader(http.StatusMethodNotAllowed)
  214. return
  215. }
  216. if body, err := command.Apply(raftServer); err != nil {
  217. warn("Unable to do watch command: %v", err)
  218. w.WriteHeader(http.StatusInternalServerError)
  219. return
  220. } else {
  221. w.WriteHeader(http.StatusOK)
  222. body, ok := body.([]byte)
  223. if !ok {
  224. panic("wrong type")
  225. }
  226. w.Write(body)
  227. return
  228. }
  229. }
  230. // Convert string duration to time format
  231. func durationToExpireTime(strDuration string) (time.Time, error) {
  232. if strDuration != "" {
  233. duration, err := strconv.Atoi(strDuration)
  234. if err != nil {
  235. return time.Unix(0, 0), err
  236. }
  237. return time.Now().Add(time.Second * (time.Duration)(duration)), nil
  238. } else {
  239. return time.Unix(0, 0), nil
  240. }
  241. }