server.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. package server
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "time"
  9. etcdErr "github.com/coreos/etcd/error"
  10. "github.com/coreos/etcd/log"
  11. "github.com/coreos/etcd/server/v1"
  12. "github.com/coreos/etcd/server/v2"
  13. "github.com/coreos/etcd/store"
  14. "github.com/coreos/go-raft"
  15. "github.com/gorilla/mux"
  16. )
  17. // This is the default implementation of the Server interface.
  18. type Server struct {
  19. http.Server
  20. peerServer *PeerServer
  21. registry *Registry
  22. store *store.Store
  23. name string
  24. url string
  25. tlsConf *TLSConfig
  26. tlsInfo *TLSInfo
  27. corsOrigins map[string]bool
  28. }
  29. // Creates a new Server.
  30. func New(name string, urlStr string, listenHost string, tlsConf *TLSConfig, tlsInfo *TLSInfo, peerServer *PeerServer, registry *Registry, store *store.Store) *Server {
  31. s := &Server{
  32. Server: http.Server{
  33. Handler: mux.NewRouter(),
  34. TLSConfig: &tlsConf.Server,
  35. Addr: listenHost,
  36. },
  37. store: store,
  38. registry: registry,
  39. url: urlStr,
  40. tlsConf: tlsConf,
  41. tlsInfo: tlsInfo,
  42. peerServer: peerServer,
  43. }
  44. // Install the routes.
  45. s.handleFunc("/version", s.GetVersionHandler).Methods("GET")
  46. s.installV1()
  47. s.installV2()
  48. return s
  49. }
  50. // The current state of the server in the cluster.
  51. func (s *Server) State() string {
  52. return s.peerServer.State()
  53. }
  54. // The node name of the leader in the cluster.
  55. func (s *Server) Leader() string {
  56. return s.peerServer.Leader()
  57. }
  58. // The current Raft committed index.
  59. func (s *Server) CommitIndex() uint64 {
  60. return s.peerServer.CommitIndex()
  61. }
  62. // The current Raft term.
  63. func (s *Server) Term() uint64 {
  64. return s.peerServer.Term()
  65. }
  66. // The server URL.
  67. func (s *Server) URL() string {
  68. return s.url
  69. }
  70. // Retrives the Peer URL for a given node name.
  71. func (s *Server) PeerURL(name string) (string, bool) {
  72. return s.registry.PeerURL(name)
  73. }
  74. // Returns a reference to the Store.
  75. func (s *Server) Store() *store.Store {
  76. return s.store
  77. }
  78. func (s *Server) installV1() {
  79. s.handleFuncV1("/v1/keys/{key:.*}", v1.GetKeyHandler).Methods("GET")
  80. s.handleFuncV1("/v1/keys/{key:.*}", v1.SetKeyHandler).Methods("POST", "PUT")
  81. s.handleFuncV1("/v1/keys/{key:.*}", v1.DeleteKeyHandler).Methods("DELETE")
  82. s.handleFuncV1("/v1/watch/{key:.*}", v1.WatchKeyHandler).Methods("GET", "POST")
  83. s.handleFunc("/v1/leader", s.GetLeaderHandler).Methods("GET")
  84. s.handleFunc("/v1/machines", s.GetMachinesHandler).Methods("GET")
  85. s.handleFunc("/v1/stats/self", s.GetStatsHandler).Methods("GET")
  86. s.handleFunc("/v1/stats/leader", s.GetLeaderStatsHandler).Methods("GET")
  87. s.handleFunc("/v1/stats/store", s.GetStoreStatsHandler).Methods("GET")
  88. }
  89. func (s *Server) installV2() {
  90. s.handleFuncV2("/v2/keys/{key:.*}", v2.GetKeyHandler).Methods("GET")
  91. s.handleFuncV2("/v2/keys/{key:.*}", v2.CreateKeyHandler).Methods("POST")
  92. s.handleFuncV2("/v2/keys/{key:.*}", v2.UpdateKeyHandler).Methods("PUT")
  93. s.handleFuncV2("/v2/keys/{key:.*}", v2.DeleteKeyHandler).Methods("DELETE")
  94. s.handleFunc("/v2/leader", s.GetLeaderHandler).Methods("GET")
  95. s.handleFunc("/v2/machines", s.GetMachinesHandler).Methods("GET")
  96. s.handleFunc("/v2/stats/self", s.GetStatsHandler).Methods("GET")
  97. s.handleFunc("/v2/stats/leader", s.GetLeaderStatsHandler).Methods("GET")
  98. s.handleFunc("/v2/stats/store", s.GetStoreStatsHandler).Methods("GET")
  99. }
  100. // Adds a v1 server handler to the router.
  101. func (s *Server) handleFuncV1(path string, f func(http.ResponseWriter, *http.Request, v1.Server) error) *mux.Route {
  102. return s.handleFunc(path, func(w http.ResponseWriter, req *http.Request) error {
  103. return f(w, req, s)
  104. })
  105. }
  106. // Adds a v2 server handler to the router.
  107. func (s *Server) handleFuncV2(path string, f func(http.ResponseWriter, *http.Request, v2.Server) error) *mux.Route {
  108. return s.handleFunc(path, func(w http.ResponseWriter, req *http.Request) error {
  109. return f(w, req, s)
  110. })
  111. }
  112. // Adds a server handler to the router.
  113. func (s *Server) handleFunc(path string, f func(http.ResponseWriter, *http.Request) error) *mux.Route {
  114. r := s.Handler.(*mux.Router)
  115. // Wrap the standard HandleFunc interface to pass in the server reference.
  116. return r.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
  117. // Log request.
  118. log.Debugf("[recv] %s %s [%s]", req.Method, s.url, req.URL.Path, req.RemoteAddr)
  119. // Write CORS header.
  120. if s.OriginAllowed("*") {
  121. w.Header().Add("Access-Control-Allow-Origin", "*")
  122. } else if origin := req.Header.Get("Origin"); s.OriginAllowed(origin) {
  123. w.Header().Add("Access-Control-Allow-Origin", origin)
  124. }
  125. // Execute handler function and return error if necessary.
  126. if err := f(w, req); err != nil {
  127. if etcdErr, ok := err.(*etcdErr.Error); ok {
  128. log.Debug("Return error: ", (*etcdErr).Error())
  129. etcdErr.Write(w)
  130. } else {
  131. http.Error(w, err.Error(), http.StatusInternalServerError)
  132. }
  133. }
  134. })
  135. }
  136. // Start to listen and response etcd client command
  137. func (s *Server) ListenAndServe() {
  138. log.Infof("etcd server [name %s, listen on %s, advertised url %s]", s.name, s.Server.Addr, s.url)
  139. if s.tlsConf.Scheme == "http" {
  140. log.Fatal(s.Server.ListenAndServe())
  141. } else {
  142. log.Fatal(s.Server.ListenAndServeTLS(s.tlsInfo.CertFile, s.tlsInfo.KeyFile))
  143. }
  144. }
  145. func (s *Server) Dispatch(c raft.Command, w http.ResponseWriter, req *http.Request) error {
  146. if s.peerServer.State() == raft.Leader {
  147. event, err := s.peerServer.Do(c)
  148. if err != nil {
  149. return err
  150. }
  151. if event == nil {
  152. return etcdErr.NewError(300, "Empty result from raft", store.UndefIndex, store.UndefTerm)
  153. }
  154. response := event.(*store.Event).Response()
  155. b, _ := json.Marshal(response)
  156. w.WriteHeader(http.StatusOK)
  157. w.Write(b)
  158. return nil
  159. } else {
  160. leader := s.peerServer.Leader()
  161. // No leader available.
  162. if leader == "" {
  163. return etcdErr.NewError(300, "", store.UndefIndex, store.UndefTerm)
  164. }
  165. url, _ := s.registry.PeerURL(leader)
  166. redirect(url, w, req)
  167. return nil
  168. }
  169. }
  170. // Sets a comma-delimited list of origins that are allowed.
  171. func (s *Server) AllowOrigins(origins string) error {
  172. // Construct a lookup of all origins.
  173. m := make(map[string]bool)
  174. for _, v := range strings.Split(origins, ",") {
  175. if v != "*" {
  176. if _, err := url.Parse(v); err != nil {
  177. return fmt.Errorf("Invalid CORS origin: %s", err)
  178. }
  179. }
  180. m[v] = true
  181. }
  182. s.corsOrigins = m
  183. return nil
  184. }
  185. // Determines whether the server will allow a given CORS origin.
  186. func (s *Server) OriginAllowed(origin string) bool {
  187. return s.corsOrigins["*"] || s.corsOrigins[origin]
  188. }
  189. // Handler to return the current version of etcd.
  190. func (s *Server) GetVersionHandler(w http.ResponseWriter, req *http.Request) error {
  191. w.WriteHeader(http.StatusOK)
  192. fmt.Fprintf(w, "etcd %s", releaseVersion)
  193. return nil
  194. }
  195. // Handler to return the current leader's raft address
  196. func (s *Server) GetLeaderHandler(w http.ResponseWriter, req *http.Request) error {
  197. leader := s.peerServer.Leader()
  198. if leader == "" {
  199. return etcdErr.NewError(etcdErr.EcodeLeaderElect, "", store.UndefIndex, store.UndefTerm)
  200. }
  201. w.WriteHeader(http.StatusOK)
  202. url, _ := s.registry.PeerURL(leader)
  203. w.Write([]byte(url))
  204. return nil
  205. }
  206. // Handler to return all the known machines in the current cluster.
  207. func (s *Server) GetMachinesHandler(w http.ResponseWriter, req *http.Request) error {
  208. machines := s.registry.URLs(s.peerServer.Leader(), s.name)
  209. w.WriteHeader(http.StatusOK)
  210. w.Write([]byte(strings.Join(machines, ", ")))
  211. return nil
  212. }
  213. // Retrieves stats on the Raft server.
  214. func (s *Server) GetStatsHandler(w http.ResponseWriter, req *http.Request) error {
  215. w.Write(s.peerServer.Stats())
  216. return nil
  217. }
  218. // Retrieves stats on the leader.
  219. func (s *Server) GetLeaderStatsHandler(w http.ResponseWriter, req *http.Request) error {
  220. if s.peerServer.State() == raft.Leader {
  221. w.Write(s.peerServer.PeerStats())
  222. return nil
  223. }
  224. leader := s.peerServer.Leader()
  225. if leader == "" {
  226. return etcdErr.NewError(300, "", store.UndefIndex, store.UndefTerm)
  227. }
  228. hostname, _ := s.registry.URL(leader)
  229. redirect(hostname, w, req)
  230. return nil
  231. }
  232. // Retrieves stats on the leader.
  233. func (s *Server) GetStoreStatsHandler(w http.ResponseWriter, req *http.Request) error {
  234. w.Write(s.store.JsonStats())
  235. return nil
  236. }
  237. // Executes a speed test to evaluate the performance of update replication.
  238. func (s *Server) SpeedTestHandler(w http.ResponseWriter, req *http.Request) error {
  239. count := 1000
  240. c := make(chan bool, count)
  241. for i := 0; i < count; i++ {
  242. go func() {
  243. for j := 0; j < 10; j++ {
  244. c := &store.UpdateCommand{
  245. Key: "foo",
  246. Value: "bar",
  247. ExpireTime: time.Unix(0, 0),
  248. }
  249. s.peerServer.Do(c)
  250. }
  251. c <- true
  252. }()
  253. }
  254. for i := 0; i < count; i++ {
  255. <-c
  256. }
  257. w.WriteHeader(http.StatusOK)
  258. w.Write([]byte("speed test success"))
  259. return nil
  260. }