base.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdhttp
  15. import (
  16. "encoding/json"
  17. "expvar"
  18. "fmt"
  19. "net/http"
  20. "strings"
  21. "time"
  22. etcdErr "github.com/coreos/etcd/error"
  23. "github.com/coreos/etcd/etcdserver"
  24. "github.com/coreos/etcd/etcdserver/api"
  25. "github.com/coreos/etcd/etcdserver/api/v2http/httptypes"
  26. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  27. "github.com/coreos/etcd/pkg/logutil"
  28. "github.com/coreos/etcd/raft"
  29. "github.com/coreos/etcd/version"
  30. "github.com/coreos/pkg/capnslog"
  31. "github.com/prometheus/client_golang/prometheus"
  32. "golang.org/x/net/context"
  33. )
  34. var (
  35. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdserver/api/etcdhttp")
  36. mlog = logutil.NewMergeLogger(plog)
  37. )
  38. const (
  39. configPath = "/config"
  40. metricsPath = "/metrics"
  41. healthPath = "/health"
  42. varsPath = "/debug/vars"
  43. versionPath = "/version"
  44. )
  45. // HandleBasic adds handlers to a mux for serving JSON etcd client requests
  46. // that do not access the v2 store.
  47. func HandleBasic(mux *http.ServeMux, server *etcdserver.EtcdServer) {
  48. mux.HandleFunc(varsPath, serveVars)
  49. mux.HandleFunc(configPath+"/local/log", logHandleFunc)
  50. mux.Handle(metricsPath, prometheus.Handler())
  51. mux.Handle(healthPath, healthHandler(server))
  52. mux.HandleFunc(versionPath, versionHandler(server.Cluster(), serveVersion))
  53. }
  54. func healthHandler(server *etcdserver.EtcdServer) http.HandlerFunc {
  55. return func(w http.ResponseWriter, r *http.Request) {
  56. if !allowMethod(w, r, "GET") {
  57. return
  58. }
  59. if uint64(server.Leader()) == raft.None {
  60. http.Error(w, `{"health": "false"}`, http.StatusServiceUnavailable)
  61. return
  62. }
  63. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  64. defer cancel()
  65. if _, err := server.Do(ctx, etcdserverpb.Request{Method: "QGET"}); err != nil {
  66. http.Error(w, `{"health": "false"}`, http.StatusServiceUnavailable)
  67. return
  68. }
  69. w.WriteHeader(http.StatusOK)
  70. w.Write([]byte(`{"health": "true"}`))
  71. }
  72. }
  73. func versionHandler(c api.Cluster, fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
  74. return func(w http.ResponseWriter, r *http.Request) {
  75. v := c.Version()
  76. if v != nil {
  77. fn(w, r, v.String())
  78. } else {
  79. fn(w, r, "not_decided")
  80. }
  81. }
  82. }
  83. func serveVersion(w http.ResponseWriter, r *http.Request, clusterV string) {
  84. if !allowMethod(w, r, "GET") {
  85. return
  86. }
  87. vs := version.Versions{
  88. Server: version.Version,
  89. Cluster: clusterV,
  90. }
  91. w.Header().Set("Content-Type", "application/json")
  92. b, err := json.Marshal(&vs)
  93. if err != nil {
  94. plog.Panicf("cannot marshal versions to json (%v)", err)
  95. }
  96. w.Write(b)
  97. }
  98. func logHandleFunc(w http.ResponseWriter, r *http.Request) {
  99. if !allowMethod(w, r, "PUT") {
  100. return
  101. }
  102. in := struct{ Level string }{}
  103. d := json.NewDecoder(r.Body)
  104. if err := d.Decode(&in); err != nil {
  105. WriteError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid json body"))
  106. return
  107. }
  108. logl, err := capnslog.ParseLevel(strings.ToUpper(in.Level))
  109. if err != nil {
  110. WriteError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid log level "+in.Level))
  111. return
  112. }
  113. plog.Noticef("globalLogLevel set to %q", logl.String())
  114. capnslog.SetGlobalLogLevel(logl)
  115. w.WriteHeader(http.StatusNoContent)
  116. }
  117. func serveVars(w http.ResponseWriter, r *http.Request) {
  118. if !allowMethod(w, r, "GET") {
  119. return
  120. }
  121. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  122. fmt.Fprintf(w, "{\n")
  123. first := true
  124. expvar.Do(func(kv expvar.KeyValue) {
  125. if !first {
  126. fmt.Fprintf(w, ",\n")
  127. }
  128. first = false
  129. fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
  130. })
  131. fmt.Fprintf(w, "\n}\n")
  132. }
  133. func allowMethod(w http.ResponseWriter, r *http.Request, m string) bool {
  134. if m == r.Method {
  135. return true
  136. }
  137. w.Header().Set("Allow", m)
  138. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  139. return false
  140. }
  141. // WriteError logs and writes the given Error to the ResponseWriter
  142. // If Error is an etcdErr, it is rendered to the ResponseWriter
  143. // Otherwise, it is assumed to be a StatusInternalServerError
  144. func WriteError(w http.ResponseWriter, r *http.Request, err error) {
  145. if err == nil {
  146. return
  147. }
  148. switch e := err.(type) {
  149. case *etcdErr.Error:
  150. e.WriteTo(w)
  151. case *httptypes.HTTPError:
  152. if et := e.WriteTo(w); et != nil {
  153. plog.Debugf("error writing HTTPError (%v) to %s", et, r.RemoteAddr)
  154. }
  155. default:
  156. switch err {
  157. case etcdserver.ErrTimeoutDueToLeaderFail, etcdserver.ErrTimeoutDueToConnectionLost, etcdserver.ErrNotEnoughStartedMembers, etcdserver.ErrUnhealthy:
  158. mlog.MergeError(err)
  159. default:
  160. mlog.MergeErrorf("got unexpected response error (%v)", err)
  161. }
  162. herr := httptypes.NewHTTPError(http.StatusInternalServerError, "Internal Server Error")
  163. if et := herr.WriteTo(w); et != nil {
  164. plog.Debugf("error writing HTTPError (%v) to %s", et, r.RemoteAddr)
  165. }
  166. }
  167. }