server.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. if b, ok := event.([]byte); ok {
  156. w.WriteHeader(http.StatusOK)
  157. w.Write(b)
  158. }
  159. var b []byte
  160. if strings.HasPrefix(req.URL.Path, "/v1") {
  161. b, _ = json.Marshal(event.(*store.Event).Response())
  162. } else {
  163. b, _ = json.Marshal(event.(*store.Event))
  164. }
  165. w.WriteHeader(http.StatusOK)
  166. w.Write(b)
  167. return nil
  168. } else {
  169. leader := s.peerServer.Leader()
  170. // No leader available.
  171. if leader == "" {
  172. return etcdErr.NewError(300, "", store.UndefIndex, store.UndefTerm)
  173. }
  174. var url string
  175. switch c.(type) {
  176. case *JoinCommand, *RemoveCommand:
  177. url, _ = s.registry.PeerURL(leader)
  178. default:
  179. url, _ = s.registry.URL(leader)
  180. }
  181. redirect(url, w, req)
  182. return nil
  183. }
  184. }
  185. // Sets a comma-delimited list of origins that are allowed.
  186. func (s *Server) AllowOrigins(origins string) error {
  187. // Construct a lookup of all origins.
  188. m := make(map[string]bool)
  189. for _, v := range strings.Split(origins, ",") {
  190. if v != "*" {
  191. if _, err := url.Parse(v); err != nil {
  192. return fmt.Errorf("Invalid CORS origin: %s", err)
  193. }
  194. }
  195. m[v] = true
  196. }
  197. s.corsOrigins = m
  198. return nil
  199. }
  200. // Determines whether the server will allow a given CORS origin.
  201. func (s *Server) OriginAllowed(origin string) bool {
  202. return s.corsOrigins["*"] || s.corsOrigins[origin]
  203. }
  204. // Handler to return the current version of etcd.
  205. func (s *Server) GetVersionHandler(w http.ResponseWriter, req *http.Request) error {
  206. w.WriteHeader(http.StatusOK)
  207. fmt.Fprintf(w, "etcd %s", releaseVersion)
  208. return nil
  209. }
  210. // Handler to return the current leader's raft address
  211. func (s *Server) GetLeaderHandler(w http.ResponseWriter, req *http.Request) error {
  212. leader := s.peerServer.Leader()
  213. if leader == "" {
  214. return etcdErr.NewError(etcdErr.EcodeLeaderElect, "", store.UndefIndex, store.UndefTerm)
  215. }
  216. w.WriteHeader(http.StatusOK)
  217. url, _ := s.registry.PeerURL(leader)
  218. w.Write([]byte(url))
  219. return nil
  220. }
  221. // Handler to return all the known machines in the current cluster.
  222. func (s *Server) GetMachinesHandler(w http.ResponseWriter, req *http.Request) error {
  223. machines := s.registry.URLs(s.peerServer.Leader(), s.name)
  224. w.WriteHeader(http.StatusOK)
  225. w.Write([]byte(strings.Join(machines, ", ")))
  226. return nil
  227. }
  228. // Retrieves stats on the Raft server.
  229. func (s *Server) GetStatsHandler(w http.ResponseWriter, req *http.Request) error {
  230. w.Write(s.peerServer.Stats())
  231. return nil
  232. }
  233. // Retrieves stats on the leader.
  234. func (s *Server) GetLeaderStatsHandler(w http.ResponseWriter, req *http.Request) error {
  235. if s.peerServer.State() == raft.Leader {
  236. w.Write(s.peerServer.PeerStats())
  237. return nil
  238. }
  239. leader := s.peerServer.Leader()
  240. if leader == "" {
  241. return etcdErr.NewError(300, "", store.UndefIndex, store.UndefTerm)
  242. }
  243. hostname, _ := s.registry.URL(leader)
  244. redirect(hostname, w, req)
  245. return nil
  246. }
  247. // Retrieves stats on the leader.
  248. func (s *Server) GetStoreStatsHandler(w http.ResponseWriter, req *http.Request) error {
  249. w.Write(s.store.JsonStats())
  250. return nil
  251. }
  252. // Executes a speed test to evaluate the performance of update replication.
  253. func (s *Server) SpeedTestHandler(w http.ResponseWriter, req *http.Request) error {
  254. count := 1000
  255. c := make(chan bool, count)
  256. for i := 0; i < count; i++ {
  257. go func() {
  258. for j := 0; j < 10; j++ {
  259. c := &store.UpdateCommand{
  260. Key: "foo",
  261. Value: "bar",
  262. ExpireTime: time.Unix(0, 0),
  263. }
  264. s.peerServer.Do(c)
  265. }
  266. c <- true
  267. }()
  268. }
  269. for i := 0; i < count; i++ {
  270. <-c
  271. }
  272. w.WriteHeader(http.StatusOK)
  273. w.Write([]byte("speed test success"))
  274. return nil
  275. }