server.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package server
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "strings"
  7. "time"
  8. etcdErr "github.com/coreos/etcd/error"
  9. "github.com/coreos/etcd/log"
  10. "github.com/coreos/etcd/server/v1"
  11. "github.com/coreos/etcd/server/v2"
  12. "github.com/coreos/etcd/store"
  13. "github.com/coreos/go-raft"
  14. "github.com/gorilla/mux"
  15. )
  16. // This is the default implementation of the Server interface.
  17. type Server struct {
  18. http.Server
  19. peerServer *PeerServer
  20. registry *Registry
  21. store store.Store
  22. name string
  23. url string
  24. tlsConf *TLSConfig
  25. tlsInfo *TLSInfo
  26. corsOrigins map[string]bool
  27. }
  28. // Creates a new Server.
  29. func New(name string, urlStr string, listenHost string, tlsConf *TLSConfig, tlsInfo *TLSInfo, peerServer *PeerServer, registry *Registry, store store.Store) *Server {
  30. s := &Server{
  31. Server: http.Server{
  32. Handler: mux.NewRouter(),
  33. TLSConfig: &tlsConf.Server,
  34. Addr: listenHost,
  35. },
  36. name: name,
  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.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. // 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 [%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. return s.peerServer.dispatch(c, w, req)
  147. }
  148. // Sets a comma-delimited list of origins that are allowed.
  149. func (s *Server) AllowOrigins(origins string) error {
  150. // Construct a lookup of all origins.
  151. m := make(map[string]bool)
  152. for _, v := range strings.Split(origins, ",") {
  153. if v != "*" {
  154. if _, err := url.Parse(v); err != nil {
  155. return fmt.Errorf("Invalid CORS origin: %s", err)
  156. }
  157. }
  158. m[v] = true
  159. }
  160. s.corsOrigins = m
  161. return nil
  162. }
  163. // Determines whether the server will allow a given CORS origin.
  164. func (s *Server) OriginAllowed(origin string) bool {
  165. return s.corsOrigins["*"] || s.corsOrigins[origin]
  166. }
  167. // Handler to return the current version of etcd.
  168. func (s *Server) GetVersionHandler(w http.ResponseWriter, req *http.Request) error {
  169. w.WriteHeader(http.StatusOK)
  170. fmt.Fprintf(w, "etcd %s", releaseVersion)
  171. return nil
  172. }
  173. // Handler to return the current leader's raft address
  174. func (s *Server) GetLeaderHandler(w http.ResponseWriter, req *http.Request) error {
  175. leader := s.peerServer.RaftServer().Leader()
  176. if leader == "" {
  177. return etcdErr.NewError(etcdErr.EcodeLeaderElect, "", store.UndefIndex, store.UndefTerm)
  178. }
  179. w.WriteHeader(http.StatusOK)
  180. url, _ := s.registry.PeerURL(leader)
  181. w.Write([]byte(url))
  182. return nil
  183. }
  184. // Handler to return all the known machines in the current cluster.
  185. func (s *Server) GetMachinesHandler(w http.ResponseWriter, req *http.Request) error {
  186. machines := s.registry.ClientURLs(s.peerServer.RaftServer().Leader(), s.name)
  187. w.WriteHeader(http.StatusOK)
  188. w.Write([]byte(strings.Join(machines, ", ")))
  189. return nil
  190. }
  191. // Retrieves stats on the Raft server.
  192. func (s *Server) GetStatsHandler(w http.ResponseWriter, req *http.Request) error {
  193. w.Write(s.peerServer.Stats())
  194. return nil
  195. }
  196. // Retrieves stats on the leader.
  197. func (s *Server) GetLeaderStatsHandler(w http.ResponseWriter, req *http.Request) error {
  198. if s.peerServer.RaftServer().State() == raft.Leader {
  199. w.Write(s.peerServer.PeerStats())
  200. return nil
  201. }
  202. leader := s.peerServer.RaftServer().Leader()
  203. if leader == "" {
  204. return etcdErr.NewError(300, "", store.UndefIndex, store.UndefTerm)
  205. }
  206. hostname, _ := s.registry.ClientURL(leader)
  207. redirect(hostname, w, req)
  208. return nil
  209. }
  210. // Retrieves stats on the leader.
  211. func (s *Server) GetStoreStatsHandler(w http.ResponseWriter, req *http.Request) error {
  212. w.Write(s.store.JsonStats())
  213. return nil
  214. }
  215. // Executes a speed test to evaluate the performance of update replication.
  216. func (s *Server) SpeedTestHandler(w http.ResponseWriter, req *http.Request) error {
  217. count := 1000
  218. c := make(chan bool, count)
  219. for i := 0; i < count; i++ {
  220. go func() {
  221. for j := 0; j < 10; j++ {
  222. c := &store.CreateCommand{
  223. Key: "foo",
  224. Value: "bar",
  225. ExpireTime: time.Unix(0, 0),
  226. Force: true,
  227. }
  228. s.peerServer.RaftServer().Do(c)
  229. }
  230. c <- true
  231. }()
  232. }
  233. for i := 0; i < count; i++ {
  234. <-c
  235. }
  236. w.WriteHeader(http.StatusOK)
  237. w.Write([]byte("speed test success"))
  238. return nil
  239. }