server.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "net/http/pprof"
  8. "strings"
  9. "time"
  10. "github.com/coreos/raft"
  11. "github.com/gorilla/mux"
  12. etcdErr "github.com/coreos/etcd/error"
  13. "github.com/coreos/etcd/log"
  14. "github.com/coreos/etcd/metrics"
  15. "github.com/coreos/etcd/mod"
  16. "github.com/coreos/etcd/server/v1"
  17. "github.com/coreos/etcd/server/v2"
  18. "github.com/coreos/etcd/store"
  19. _ "github.com/coreos/etcd/store/v2"
  20. )
  21. type ServerConfig struct {
  22. Name string
  23. URL string
  24. CORS *corsInfo
  25. }
  26. // This is the default implementation of the Server interface.
  27. type Server struct {
  28. http.Server
  29. Config ServerConfig
  30. peerServer *PeerServer
  31. registry *Registry
  32. store store.Store
  33. router *mux.Router
  34. corsMiddleware *corsHTTPMiddleware
  35. metrics *metrics.Bucket
  36. listener net.Listener
  37. }
  38. // Creates a new Server.
  39. func New(sConfig ServerConfig, peerServer *PeerServer, registry *Registry, store store.Store, mb *metrics.Bucket) *Server {
  40. r := mux.NewRouter()
  41. cors := &corsHTTPMiddleware{r, sConfig.CORS}
  42. s := &Server{
  43. Config: sConfig,
  44. Server: http.Server{
  45. Handler: cors,
  46. },
  47. store: store,
  48. registry: registry,
  49. peerServer: peerServer,
  50. router: r,
  51. corsMiddleware: cors,
  52. metrics: mb,
  53. }
  54. // Install the routes.
  55. s.handleFunc("/version", s.GetVersionHandler).Methods("GET")
  56. s.installV1()
  57. s.installV2()
  58. s.installMod()
  59. return s
  60. }
  61. func (s *Server) EnableTracing() {
  62. s.installDebug()
  63. }
  64. // The current state of the server in the cluster.
  65. func (s *Server) State() string {
  66. return s.peerServer.RaftServer().State()
  67. }
  68. // The node name of the leader in the cluster.
  69. func (s *Server) Leader() string {
  70. return s.peerServer.RaftServer().Leader()
  71. }
  72. // The current Raft committed index.
  73. func (s *Server) CommitIndex() uint64 {
  74. return s.peerServer.RaftServer().CommitIndex()
  75. }
  76. // The current Raft term.
  77. func (s *Server) Term() uint64 {
  78. return s.peerServer.RaftServer().Term()
  79. }
  80. // The server URL.
  81. func (s *Server) URL() string {
  82. return s.Config.URL
  83. }
  84. // Retrives the Peer URL for a given node name.
  85. func (s *Server) PeerURL(name string) (string, bool) {
  86. return s.registry.PeerURL(name)
  87. }
  88. // ClientURL retrieves the Client URL for a given node name.
  89. func (s *Server) ClientURL(name string) (string, bool) {
  90. return s.registry.ClientURL(name)
  91. }
  92. // Returns a reference to the Store.
  93. func (s *Server) Store() store.Store {
  94. return s.store
  95. }
  96. func (s *Server) installV1() {
  97. s.handleFuncV1("/v1/keys/{key:.*}", v1.GetKeyHandler).Methods("GET")
  98. s.handleFuncV1("/v1/keys/{key:.*}", v1.SetKeyHandler).Methods("POST", "PUT")
  99. s.handleFuncV1("/v1/keys/{key:.*}", v1.DeleteKeyHandler).Methods("DELETE")
  100. s.handleFuncV1("/v1/watch/{key:.*}", v1.WatchKeyHandler).Methods("GET", "POST")
  101. s.handleFunc("/v1/leader", s.GetLeaderHandler).Methods("GET")
  102. s.handleFunc("/v1/machines", s.GetPeersHandler).Methods("GET")
  103. s.handleFunc("/v1/peers", s.GetPeersHandler).Methods("GET")
  104. s.handleFunc("/v1/stats/self", s.GetStatsHandler).Methods("GET")
  105. s.handleFunc("/v1/stats/leader", s.GetLeaderStatsHandler).Methods("GET")
  106. s.handleFunc("/v1/stats/store", s.GetStoreStatsHandler).Methods("GET")
  107. }
  108. func (s *Server) installV2() {
  109. s.handleFuncV2("/v2/keys/{key:.*}", v2.GetHandler).Methods("GET")
  110. s.handleFuncV2("/v2/keys/{key:.*}", v2.PostHandler).Methods("POST")
  111. s.handleFuncV2("/v2/keys/{key:.*}", v2.PutHandler).Methods("PUT")
  112. s.handleFuncV2("/v2/keys/{key:.*}", v2.DeleteHandler).Methods("DELETE")
  113. s.handleFunc("/v2/leader", s.GetLeaderHandler).Methods("GET")
  114. s.handleFunc("/v2/machines", s.GetPeersHandler).Methods("GET")
  115. s.handleFunc("/v2/peers", s.GetPeersHandler).Methods("GET")
  116. s.handleFunc("/v2/stats/self", s.GetStatsHandler).Methods("GET")
  117. s.handleFunc("/v2/stats/leader", s.GetLeaderStatsHandler).Methods("GET")
  118. s.handleFunc("/v2/stats/store", s.GetStoreStatsHandler).Methods("GET")
  119. s.handleFunc("/v2/speedTest", s.SpeedTestHandler).Methods("GET")
  120. }
  121. func (s *Server) installMod() {
  122. r := s.router
  123. r.PathPrefix("/mod").Handler(http.StripPrefix("/mod", mod.HttpHandler(s.Config.URL)))
  124. }
  125. func (s *Server) installDebug() {
  126. s.handleFunc("/debug/metrics", s.GetMetricsHandler).Methods("GET")
  127. s.router.HandleFunc("/debug/pprof", pprof.Index)
  128. s.router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
  129. s.router.HandleFunc("/debug/pprof/profile", pprof.Profile)
  130. s.router.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
  131. s.router.HandleFunc("/debug/pprof/{name}", pprof.Index)
  132. }
  133. // Adds a v1 server handler to the router.
  134. func (s *Server) handleFuncV1(path string, f func(http.ResponseWriter, *http.Request, v1.Server) error) *mux.Route {
  135. return s.handleFunc(path, func(w http.ResponseWriter, req *http.Request) error {
  136. return f(w, req, s)
  137. })
  138. }
  139. // Adds a v2 server handler to the router.
  140. func (s *Server) handleFuncV2(path string, f func(http.ResponseWriter, *http.Request, v2.Server) error) *mux.Route {
  141. return s.handleFunc(path, func(w http.ResponseWriter, req *http.Request) error {
  142. return f(w, req, s)
  143. })
  144. }
  145. // Adds a server handler to the router.
  146. func (s *Server) handleFunc(path string, f func(http.ResponseWriter, *http.Request) error) *mux.Route {
  147. r := s.router
  148. // Wrap the standard HandleFunc interface to pass in the server reference.
  149. return r.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
  150. // Log request.
  151. log.Debugf("[recv] %s %s %s [%s]", req.Method, s.Config.URL, req.URL.Path, req.RemoteAddr)
  152. // Execute handler function and return error if necessary.
  153. if err := f(w, req); err != nil {
  154. if etcdErr, ok := err.(*etcdErr.Error); ok {
  155. log.Debug("Return error: ", (*etcdErr).Error())
  156. w.Header().Set("Content-Type", "application/json")
  157. etcdErr.Write(w)
  158. } else {
  159. http.Error(w, err.Error(), http.StatusInternalServerError)
  160. }
  161. }
  162. })
  163. }
  164. // Start to listen and response etcd client command
  165. func (s *Server) Serve(listener net.Listener) error {
  166. log.Infof("etcd server [name %s, listen on %s, advertised url %s]", s.Config.Name, listener.Addr(), s.Config.URL)
  167. s.listener = listener
  168. return s.Server.Serve(listener)
  169. }
  170. // Stops the server.
  171. func (s *Server) Close() {
  172. if s.listener != nil {
  173. s.listener.Close()
  174. s.listener = nil
  175. }
  176. }
  177. // Dispatch command to the current leader
  178. func (s *Server) Dispatch(c raft.Command, w http.ResponseWriter, req *http.Request) error {
  179. ps := s.peerServer
  180. if ps.raftServer.State() == raft.Leader {
  181. result, err := ps.raftServer.Do(c)
  182. if err != nil {
  183. return err
  184. }
  185. if result == nil {
  186. return etcdErr.NewError(300, "Empty result from raft", s.Store().Index())
  187. }
  188. // response for raft related commands[join/remove]
  189. if b, ok := result.([]byte); ok {
  190. w.WriteHeader(http.StatusOK)
  191. w.Write(b)
  192. return nil
  193. }
  194. var b []byte
  195. if strings.HasPrefix(req.URL.Path, "/v1") {
  196. b, _ = json.Marshal(result.(*store.Event).Response(0))
  197. w.WriteHeader(http.StatusOK)
  198. } else {
  199. e, _ := result.(*store.Event)
  200. b, _ = json.Marshal(e)
  201. w.Header().Set("Content-Type", "application/json")
  202. // etcd index should be the same as the event index
  203. // which is also the last modified index of the node
  204. w.Header().Add("X-Etcd-Index", fmt.Sprint(e.Index()))
  205. w.Header().Add("X-Raft-Index", fmt.Sprint(s.CommitIndex()))
  206. w.Header().Add("X-Raft-Term", fmt.Sprint(s.Term()))
  207. if e.IsCreated() {
  208. w.WriteHeader(http.StatusCreated)
  209. } else {
  210. w.WriteHeader(http.StatusOK)
  211. }
  212. }
  213. w.Write(b)
  214. return nil
  215. } else {
  216. leader := ps.raftServer.Leader()
  217. // No leader available.
  218. if leader == "" {
  219. return etcdErr.NewError(300, "", s.Store().Index())
  220. }
  221. var url string
  222. switch c.(type) {
  223. case *JoinCommand, *RemoveCommand:
  224. url, _ = ps.registry.PeerURL(leader)
  225. default:
  226. url, _ = ps.registry.ClientURL(leader)
  227. }
  228. redirect(url, w, req)
  229. return nil
  230. }
  231. }
  232. // Handler to return the current version of etcd.
  233. func (s *Server) GetVersionHandler(w http.ResponseWriter, req *http.Request) error {
  234. w.WriteHeader(http.StatusOK)
  235. fmt.Fprintf(w, "etcd %s", ReleaseVersion)
  236. return nil
  237. }
  238. // Handler to return the current leader's raft address
  239. func (s *Server) GetLeaderHandler(w http.ResponseWriter, req *http.Request) error {
  240. leader := s.peerServer.RaftServer().Leader()
  241. if leader == "" {
  242. return etcdErr.NewError(etcdErr.EcodeLeaderElect, "", s.Store().Index())
  243. }
  244. w.WriteHeader(http.StatusOK)
  245. url, _ := s.registry.PeerURL(leader)
  246. w.Write([]byte(url))
  247. return nil
  248. }
  249. // Handler to return all the known peers in the current cluster.
  250. func (s *Server) GetPeersHandler(w http.ResponseWriter, req *http.Request) error {
  251. peers := s.registry.ClientURLs(s.peerServer.RaftServer().Leader(), s.Config.Name)
  252. w.WriteHeader(http.StatusOK)
  253. w.Write([]byte(strings.Join(peers, ", ")))
  254. return nil
  255. }
  256. // Retrieves stats on the Raft server.
  257. func (s *Server) GetStatsHandler(w http.ResponseWriter, req *http.Request) error {
  258. w.Write(s.peerServer.Stats())
  259. return nil
  260. }
  261. // Retrieves stats on the leader.
  262. func (s *Server) GetLeaderStatsHandler(w http.ResponseWriter, req *http.Request) error {
  263. if s.peerServer.RaftServer().State() == raft.Leader {
  264. w.Write(s.peerServer.PeerStats())
  265. return nil
  266. }
  267. leader := s.peerServer.RaftServer().Leader()
  268. if leader == "" {
  269. return etcdErr.NewError(300, "", s.Store().Index())
  270. }
  271. hostname, _ := s.registry.ClientURL(leader)
  272. redirect(hostname, w, req)
  273. return nil
  274. }
  275. // Retrieves stats on the leader.
  276. func (s *Server) GetStoreStatsHandler(w http.ResponseWriter, req *http.Request) error {
  277. w.Write(s.store.JsonStats())
  278. return nil
  279. }
  280. // Executes a speed test to evaluate the performance of update replication.
  281. func (s *Server) SpeedTestHandler(w http.ResponseWriter, req *http.Request) error {
  282. count := 1000
  283. c := make(chan bool, count)
  284. for i := 0; i < count; i++ {
  285. go func() {
  286. for j := 0; j < 10; j++ {
  287. c := s.Store().CommandFactory().CreateSetCommand("foo", false, "bar", time.Unix(0, 0))
  288. s.peerServer.RaftServer().Do(c)
  289. }
  290. c <- true
  291. }()
  292. }
  293. for i := 0; i < count; i++ {
  294. <-c
  295. }
  296. w.WriteHeader(http.StatusOK)
  297. w.Write([]byte("speed test success"))
  298. return nil
  299. }
  300. // Retrieves metrics from bucket
  301. func (s *Server) GetMetricsHandler(w http.ResponseWriter, req *http.Request) error {
  302. (*s.metrics).Dump(w)
  303. return nil
  304. }