client_handlers.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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/Delete 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. if store.CheckKeyword(key) {
  32. (*w).WriteHeader(http.StatusBadRequest)
  33. (*w).Write(newJsonError(400, "Set"))
  34. return
  35. }
  36. debugf("[recv] POST http://%v/v1/keys/%s", raftServer.Name(), key)
  37. value := req.FormValue("value")
  38. if len(value) == 0 {
  39. (*w).WriteHeader(http.StatusBadRequest)
  40. (*w).Write(newJsonError(200, "Set"))
  41. return
  42. }
  43. prevValue := req.FormValue("prevValue")
  44. strDuration := req.FormValue("ttl")
  45. expireTime, err := durationToExpireTime(strDuration)
  46. if err != nil {
  47. (*w).WriteHeader(http.StatusBadRequest)
  48. (*w).Write(newJsonError(202, "Set"))
  49. return
  50. }
  51. if len(prevValue) != 0 {
  52. command := &TestAndSetCommand{}
  53. command.Key = key
  54. command.Value = value
  55. command.PrevValue = prevValue
  56. command.ExpireTime = expireTime
  57. dispatch(command, w, req, true)
  58. } else {
  59. command := &SetCommand{}
  60. command.Key = key
  61. command.Value = value
  62. command.ExpireTime = expireTime
  63. dispatch(command, w, req, true)
  64. }
  65. }
  66. // Delete Handler
  67. func DeleteHttpHandler(w *http.ResponseWriter, req *http.Request) {
  68. key := req.URL.Path[len("/v1/keys/"):]
  69. debugf("[recv] DELETE http://%v/v1/keys/%s", raftServer.Name(), key)
  70. command := &DeleteCommand{}
  71. command.Key = key
  72. dispatch(command, w, req, true)
  73. }
  74. // Dispatch the command to leader
  75. func dispatch(c Command, w *http.ResponseWriter, req *http.Request, client bool) {
  76. if raftServer.State() == "leader" {
  77. if body, err := raftServer.Do(c); err != nil {
  78. if _, ok := err.(store.NotFoundError); ok {
  79. (*w).WriteHeader(http.StatusNotFound)
  80. (*w).Write(newJsonError(100, err.Error()))
  81. return
  82. }
  83. if _, ok := err.(store.TestFail); ok {
  84. (*w).WriteHeader(http.StatusBadRequest)
  85. (*w).Write(newJsonError(101, err.Error()))
  86. return
  87. }
  88. if _, ok := err.(store.NotFile); ok {
  89. (*w).WriteHeader(http.StatusBadRequest)
  90. (*w).Write(newJsonError(102, err.Error()))
  91. return
  92. }
  93. if err.Error() == errors[103] {
  94. (*w).WriteHeader(http.StatusBadRequest)
  95. (*w).Write(newJsonError(103, ""))
  96. return
  97. }
  98. (*w).WriteHeader(http.StatusInternalServerError)
  99. (*w).Write(newJsonError(300, err.Error()))
  100. return
  101. } else {
  102. if body == nil {
  103. (*w).WriteHeader(http.StatusNotFound)
  104. (*w).Write(newJsonError(300, "Empty result from raft"))
  105. } else {
  106. body, ok := body.([]byte)
  107. // this should not happen
  108. if !ok {
  109. panic("wrong type")
  110. }
  111. (*w).WriteHeader(http.StatusOK)
  112. (*w).Write(body)
  113. }
  114. return
  115. }
  116. } else {
  117. // current no leader
  118. if raftServer.Leader() == "" {
  119. (*w).WriteHeader(http.StatusInternalServerError)
  120. (*w).Write(newJsonError(300, ""))
  121. return
  122. }
  123. // tell the client where is the leader
  124. path := req.URL.Path
  125. var scheme string
  126. if scheme = req.URL.Scheme; scheme == "" {
  127. scheme = "http://"
  128. }
  129. var url string
  130. if client {
  131. clientAddr, _ := getClientAddr(raftServer.Leader())
  132. url = scheme + clientAddr + path
  133. } else {
  134. url = scheme + raftServer.Leader() + path
  135. }
  136. debugf("Redirect to %s", url)
  137. http.Redirect(*w, req, url, http.StatusTemporaryRedirect)
  138. return
  139. }
  140. (*w).WriteHeader(http.StatusInternalServerError)
  141. (*w).Write(newJsonError(300, ""))
  142. return
  143. }
  144. //--------------------------------------
  145. // State non-sensitive handlers
  146. // will not dispatch to leader
  147. // TODO: add sensitive version for these
  148. // command?
  149. //--------------------------------------
  150. // Handler to return the current leader name
  151. func LeaderHttpHandler(w http.ResponseWriter, req *http.Request) {
  152. leader := raftServer.Leader()
  153. if leader != "" {
  154. w.WriteHeader(http.StatusOK)
  155. w.Write([]byte(raftServer.Leader()))
  156. } else {
  157. // not likely, but it may happen
  158. w.WriteHeader(http.StatusInternalServerError)
  159. w.Write(newJsonError(301, ""))
  160. }
  161. }
  162. // Handler to return all the known machines in the current cluster
  163. func MachinesHttpHandler(w http.ResponseWriter, req *http.Request) {
  164. peers := raftServer.Peers()
  165. // Add itself to the machine list first
  166. // Since peer map does not contain the server itself
  167. machines, _ := getClientAddr(raftServer.Name())
  168. // Add all peers to the list and separate by comma
  169. // We do not use json here since we accept machines list
  170. // in the command line separate by comma.
  171. for peerName, _ := range peers {
  172. if addr, ok := getClientAddr(peerName); ok {
  173. machines = machines + "," + addr
  174. }
  175. }
  176. w.WriteHeader(http.StatusOK)
  177. w.Write([]byte(machines))
  178. }
  179. // Handler to return the current version of etcd
  180. func VersionHttpHandler(w http.ResponseWriter, req *http.Request) {
  181. w.WriteHeader(http.StatusOK)
  182. w.Write([]byte(releaseVersion))
  183. }
  184. // Handler to return the basic stats of etcd
  185. func StatsHttpHandler(w http.ResponseWriter, req *http.Request) {
  186. w.WriteHeader(http.StatusOK)
  187. w.Write(etcdStore.Stats())
  188. }
  189. // Get Handler
  190. func GetHttpHandler(w *http.ResponseWriter, req *http.Request) {
  191. key := req.URL.Path[len("/v1/keys/"):]
  192. debugf("[recv] GET http://%v/v1/keys/%s", raftServer.Name(), key)
  193. command := &GetCommand{}
  194. command.Key = key
  195. if body, err := command.Apply(raftServer); err != nil {
  196. if _, ok := err.(store.NotFoundError); ok {
  197. (*w).WriteHeader(http.StatusNotFound)
  198. (*w).Write(newJsonError(100, err.Error()))
  199. return
  200. }
  201. (*w).WriteHeader(http.StatusInternalServerError)
  202. (*w).Write(newJsonError(300, ""))
  203. } else {
  204. body, ok := body.([]byte)
  205. if !ok {
  206. panic("wrong type")
  207. }
  208. (*w).WriteHeader(http.StatusOK)
  209. (*w).Write(body)
  210. }
  211. }
  212. // Watch handler
  213. func WatchHttpHandler(w http.ResponseWriter, req *http.Request) {
  214. key := req.URL.Path[len("/v1/watch/"):]
  215. command := &WatchCommand{}
  216. command.Key = key
  217. if req.Method == "GET" {
  218. debugf("[recv] GET http://%v/watch/%s", raftServer.Name(), key)
  219. command.SinceIndex = 0
  220. } else if req.Method == "POST" {
  221. // watch from a specific index
  222. debugf("[recv] POST http://%v/watch/%s", raftServer.Name(), key)
  223. content := req.FormValue("index")
  224. sinceIndex, err := strconv.ParseUint(string(content), 10, 64)
  225. if err != nil {
  226. w.WriteHeader(http.StatusBadRequest)
  227. w.Write(newJsonError(203, "Watch From Index"))
  228. }
  229. command.SinceIndex = sinceIndex
  230. } else {
  231. w.WriteHeader(http.StatusMethodNotAllowed)
  232. return
  233. }
  234. if body, err := command.Apply(raftServer); err != nil {
  235. w.WriteHeader(http.StatusInternalServerError)
  236. w.Write(newJsonError(500, key))
  237. } else {
  238. w.WriteHeader(http.StatusOK)
  239. body, ok := body.([]byte)
  240. if !ok {
  241. panic("wrong type")
  242. }
  243. w.Write(body)
  244. }
  245. }
  246. // Convert string duration to time format
  247. func durationToExpireTime(strDuration string) (time.Time, error) {
  248. if strDuration != "" {
  249. duration, err := strconv.Atoi(strDuration)
  250. if err != nil {
  251. return time.Unix(0, 0), err
  252. }
  253. return time.Now().Add(time.Second * (time.Duration)(duration)), nil
  254. } else {
  255. return time.Unix(0, 0), nil
  256. }
  257. }