server.go 8.5 KB

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