server.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. package server
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. "net/http"
  6. "net/url"
  7. "strings"
  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/store"
  12. "github.com/coreos/go-raft"
  13. "github.com/gorilla/mux"
  14. )
  15. // This is the default implementation of the Server interface.
  16. type Server struct {
  17. http.Server
  18. raftServer *raft.Server
  19. registry *Registry
  20. store *store.Store
  21. name string
  22. url string
  23. tlsConf *TLSConfig
  24. tlsInfo *TLSInfo
  25. corsOrigins map[string]bool
  26. }
  27. // Creates a new Server.
  28. func New(name string, urlStr string, listenHost string, tlsConf *TLSConfig, tlsInfo *TLSInfo, raftServer *raft.Server, registry *Registry, store *store.Store) *Server {
  29. s := &Server{
  30. Server: http.Server{
  31. Handler: mux.NewRouter(),
  32. TLSConfig: &tlsConf.Server,
  33. Addr: listenHost,
  34. },
  35. store: store,
  36. registry: registry,
  37. url: urlStr,
  38. tlsConf: tlsConf,
  39. tlsInfo: tlsInfo,
  40. raftServer: raftServer,
  41. }
  42. // Install the routes for each version of the API.
  43. s.installV1()
  44. return s
  45. }
  46. // The current Raft committed index.
  47. func (s *Server) CommitIndex() uint64 {
  48. return s.raftServer.CommitIndex()
  49. }
  50. // The current Raft term.
  51. func (s *Server) Term() uint64 {
  52. return s.raftServer.Term()
  53. }
  54. // The server URL.
  55. func (s *Server) URL() string {
  56. return s.url
  57. }
  58. // Returns a reference to the Store.
  59. func (s *Server) Store() *store.Store {
  60. return s.store
  61. }
  62. func (s *Server) installV1() {
  63. s.handleFuncV1("/v1/keys/{key:.*}", v1.GetKeyHandler).Methods("GET")
  64. s.handleFuncV1("/v1/keys/{key:.*}", v1.SetKeyHandler).Methods("POST", "PUT")
  65. s.handleFuncV1("/v1/keys/{key:.*}", v1.DeleteKeyHandler).Methods("DELETE")
  66. s.handleFuncV1("/v1/watch/{key:.*}", v1.WatchKeyHandler).Methods("GET", "POST")
  67. }
  68. // Adds a v1 server handler to the router.
  69. func (s *Server) handleFuncV1(path string, f func(http.ResponseWriter, *http.Request, v1.Server) error) *mux.Route {
  70. return s.handleFunc(path, func(w http.ResponseWriter, req *http.Request, s *Server) error {
  71. return f(w, req, s)
  72. })
  73. }
  74. // Adds a server handler to the router.
  75. func (s *Server) handleFunc(path string, f func(http.ResponseWriter, *http.Request, *Server) error) *mux.Route {
  76. r := s.Handler.(*mux.Router)
  77. // Wrap the standard HandleFunc interface to pass in the server reference.
  78. return r.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
  79. // Log request.
  80. log.Debugf("[recv] %s %s [%s]", req.Method, s.url, req.URL.Path, req.RemoteAddr)
  81. // Write CORS header.
  82. if s.OriginAllowed("*") {
  83. w.Header().Add("Access-Control-Allow-Origin", "*")
  84. } else if origin := req.Header.Get("Origin"); s.OriginAllowed(origin) {
  85. w.Header().Add("Access-Control-Allow-Origin", origin)
  86. }
  87. // Execute handler function and return error if necessary.
  88. if err := f(w, req, s); err != nil {
  89. if etcdErr, ok := err.(*etcdErr.Error); ok {
  90. log.Debug("Return error: ", (*etcdErr).Error())
  91. etcdErr.Write(w)
  92. } else {
  93. http.Error(w, err.Error(), http.StatusInternalServerError)
  94. }
  95. }
  96. })
  97. }
  98. // Start to listen and response etcd client command
  99. func (s *Server) ListenAndServe() {
  100. log.Infof("etcd server [name %s, listen on %s, advertised url %s]", s.name, s.Server.Addr, s.url)
  101. if s.tlsConf.Scheme == "http" {
  102. log.Fatal(s.Server.ListenAndServe())
  103. } else {
  104. log.Fatal(s.Server.ListenAndServeTLS(s.tlsInfo.CertFile, s.tlsInfo.KeyFile))
  105. }
  106. }
  107. func (s *Server) Dispatch(c raft.Command, w http.ResponseWriter, req *http.Request) error {
  108. if s.raftServer.State() == raft.Leader {
  109. event, err := s.raftServer.Do(c)
  110. if err != nil {
  111. return err
  112. }
  113. if event == nil {
  114. return etcdErr.NewError(300, "Empty result from raft", store.UndefIndex, store.UndefTerm)
  115. }
  116. response := event.(*store.Event).Response()
  117. b, _ := json.Marshal(response)
  118. w.WriteHeader(http.StatusOK)
  119. w.Write(b)
  120. return nil
  121. } else {
  122. leader := s.raftServer.Leader()
  123. // No leader available.
  124. if leader == "" {
  125. return etcdErr.NewError(300, "", store.UndefIndex, store.UndefTerm)
  126. }
  127. url, _ := s.registry.PeerURL(leader)
  128. redirect(url, w, req)
  129. return nil
  130. }
  131. }
  132. // Sets a comma-delimited list of origins that are allowed.
  133. func (s *Server) AllowOrigins(origins string) error {
  134. // Construct a lookup of all origins.
  135. m := make(map[string]bool)
  136. for _, v := range strings.Split(origins, ",") {
  137. if v != "*" {
  138. if _, err := url.Parse(v); err != nil {
  139. return fmt.Errorf("Invalid CORS origin: %s", err)
  140. }
  141. }
  142. m[v] = true
  143. }
  144. s.corsOrigins = m
  145. return nil
  146. }
  147. // Determines whether the server will allow a given CORS origin.
  148. func (s *Server) OriginAllowed(origin string) bool {
  149. return s.corsOrigins["*"] || s.corsOrigins[origin]
  150. }