server.go 12 KB

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