server.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. package server
  2. import (
  3. "github.com/gorilla/mux"
  4. "net/http"
  5. "net/url"
  6. )
  7. // The Server provides an HTTP interface to the underlying store.
  8. type Server interface {
  9. CommitIndex() uint64
  10. Term() uint64
  11. Dispatch(Command, http.ResponseWriter, *http.Request)
  12. }
  13. // This is the default implementation of the Server interface.
  14. type server struct {
  15. http.Server
  16. raftServer *raft.Server
  17. name string
  18. url string
  19. tlsConf *TLSConfig
  20. tlsInfo *TLSInfo
  21. corsOrigins map[string]bool
  22. }
  23. // Creates a new Server.
  24. func New(name string, urlStr string, listenHost string, tlsConf *TLSConfig, tlsInfo *TLSInfo, raftServer *raft.Server) *Server {
  25. s := &server{
  26. Server: http.Server{
  27. Handler: mux.NewRouter(),
  28. TLSConfig: &tlsConf.Server,
  29. Addr: listenHost,
  30. },
  31. name: name,
  32. url: urlStr,
  33. tlsConf: tlsConf,
  34. tlsInfo: tlsInfo,
  35. raftServer: raftServer,
  36. }
  37. // Install the routes for each version of the API.
  38. s.installV1()
  39. return s
  40. }
  41. // The current Raft committed index.
  42. func (s *server) CommitIndex() uint64 {
  43. return c.raftServer.CommitIndex()
  44. }
  45. // The current Raft term.
  46. func (s *server) Term() uint64 {
  47. return c.raftServer.Term()
  48. }
  49. // Executes a command against the Raft server.
  50. func (s *server) Do(c Command, localOnly bool) (interface{}, error) {
  51. return c.raftServer.Do(s.RaftServer().Server)
  52. }
  53. func (s *server) installV1() {
  54. s.handleFunc("/v1/keys/{key:.*}", v1.GetKeyHandler).Methods("GET")
  55. s.handleFunc("/v1/keys/{key:.*}", v1.SetKeyHandler).Methods("POST", "PUT")
  56. s.handleFunc("/v1/keys/{key:.*}", v1.DeleteKeyHandler).Methods("DELETE")
  57. s.handleFunc("/v1/watch/{key:.*}", v1.WatchKeyHandler).Methods("GET", "POST")
  58. }
  59. // Adds a server handler to the router.
  60. func (s *server) handleFunc(path string, f func(http.ResponseWriter, *http.Request, Server) error) *mux.Route {
  61. r := s.Handler.(*mux.Router)
  62. // Wrap the standard HandleFunc interface to pass in the server reference.
  63. return r.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
  64. // Log request.
  65. debugf("[recv] %s %s [%s]", req.Method, s.url, req.URL.Path, req.RemoteAddr)
  66. // Write CORS header.
  67. if s.OriginAllowed("*") {
  68. w.Header().Add("Access-Control-Allow-Origin", "*")
  69. } else if s.OriginAllowed(r.Header.Get("Origin")) {
  70. w.Header().Add("Access-Control-Allow-Origin", r.Header.Get("Origin"))
  71. }
  72. // Execute handler function and return error if necessary.
  73. if err := f(w, req, s); err != nil {
  74. if etcdErr, ok := err.(*etcdErr.Error); ok {
  75. debug("Return error: ", (*etcdErr).Error())
  76. etcdErr.Write(w)
  77. } else {
  78. http.Error(w, e.Error(), http.StatusInternalServerError)
  79. }
  80. }
  81. })
  82. }
  83. // Start to listen and response etcd client command
  84. func (s *server) ListenAndServe() {
  85. infof("etcd server [name %s, listen on %s, advertised url %s]", s.name, s.Server.Addr, s.url)
  86. if s.tlsConf.Scheme == "http" {
  87. fatal(s.Server.ListenAndServe())
  88. } else {
  89. fatal(s.Server.ListenAndServeTLS(s.tlsInfo.CertFile, s.tlsInfo.KeyFile))
  90. }
  91. }
  92. // Sets a comma-delimited list of origins that are allowed.
  93. func (s *server) AllowOrigins(origins string) error {
  94. // Construct a lookup of all origins.
  95. m := make(map[string]bool)
  96. for _, v := range strings.Split(cors, ",") {
  97. if v != "*" {
  98. if _, err := url.Parse(v); err != nil {
  99. return fmt.Errorf("Invalid CORS origin: %s", err)
  100. }
  101. }
  102. m[v] = true
  103. }
  104. s.corsOrigins = m
  105. return nil
  106. }
  107. // Determines whether the server will allow a given CORS origin.
  108. func (s *server) OriginAllowed(origin string) {
  109. return s.corsOrigins["*"] || s.corsOrigins[origin]
  110. }