base.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. var (
  55. healthSuccess = prometheus.NewCounter(prometheus.CounterOpts{
  56. Namespace: "etcd",
  57. Subsystem: "server",
  58. Name: "health_success",
  59. Help: "The total number of successful health checks",
  60. })
  61. healthFailed = prometheus.NewCounter(prometheus.CounterOpts{
  62. Namespace: "etcd",
  63. Subsystem: "server",
  64. Name: "health_failures",
  65. Help: "The total number of failed health checks",
  66. })
  67. )
  68. func init() {
  69. prometheus.MustRegister(healthSuccess)
  70. prometheus.MustRegister(healthFailed)
  71. }
  72. func healthHandler(server *etcdserver.EtcdServer) http.HandlerFunc {
  73. return func(w http.ResponseWriter, r *http.Request) {
  74. if !allowMethod(w, r, "GET") {
  75. return
  76. }
  77. if uint64(server.Leader()) == raft.None {
  78. http.Error(w, `{"health": "false"}`, http.StatusServiceUnavailable)
  79. healthFailed.Inc()
  80. return
  81. }
  82. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  83. defer cancel()
  84. if _, err := server.Do(ctx, etcdserverpb.Request{Method: "QGET"}); err != nil {
  85. http.Error(w, `{"health": "false"}`, http.StatusServiceUnavailable)
  86. healthFailed.Inc()
  87. return
  88. }
  89. w.WriteHeader(http.StatusOK)
  90. w.Write([]byte(`{"health": "true"}`))
  91. healthSuccess.Inc()
  92. }
  93. }
  94. func versionHandler(c api.Cluster, fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
  95. return func(w http.ResponseWriter, r *http.Request) {
  96. v := c.Version()
  97. if v != nil {
  98. fn(w, r, v.String())
  99. } else {
  100. fn(w, r, "not_decided")
  101. }
  102. }
  103. }
  104. func serveVersion(w http.ResponseWriter, r *http.Request, clusterV string) {
  105. if !allowMethod(w, r, "GET") {
  106. return
  107. }
  108. vs := version.Versions{
  109. Server: version.Version,
  110. Cluster: clusterV,
  111. }
  112. w.Header().Set("Content-Type", "application/json")
  113. b, err := json.Marshal(&vs)
  114. if err != nil {
  115. plog.Panicf("cannot marshal versions to json (%v)", err)
  116. }
  117. w.Write(b)
  118. }
  119. func logHandleFunc(w http.ResponseWriter, r *http.Request) {
  120. if !allowMethod(w, r, "PUT") {
  121. return
  122. }
  123. in := struct{ Level string }{}
  124. d := json.NewDecoder(r.Body)
  125. if err := d.Decode(&in); err != nil {
  126. WriteError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid json body"))
  127. return
  128. }
  129. logl, err := capnslog.ParseLevel(strings.ToUpper(in.Level))
  130. if err != nil {
  131. WriteError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid log level "+in.Level))
  132. return
  133. }
  134. plog.Noticef("globalLogLevel set to %q", logl.String())
  135. capnslog.SetGlobalLogLevel(logl)
  136. w.WriteHeader(http.StatusNoContent)
  137. }
  138. func serveVars(w http.ResponseWriter, r *http.Request) {
  139. if !allowMethod(w, r, "GET") {
  140. return
  141. }
  142. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  143. fmt.Fprintf(w, "{\n")
  144. first := true
  145. expvar.Do(func(kv expvar.KeyValue) {
  146. if !first {
  147. fmt.Fprintf(w, ",\n")
  148. }
  149. first = false
  150. fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
  151. })
  152. fmt.Fprintf(w, "\n}\n")
  153. }
  154. func allowMethod(w http.ResponseWriter, r *http.Request, m string) bool {
  155. if m == r.Method {
  156. return true
  157. }
  158. w.Header().Set("Allow", m)
  159. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  160. return false
  161. }
  162. // WriteError logs and writes the given Error to the ResponseWriter
  163. // If Error is an etcdErr, it is rendered to the ResponseWriter
  164. // Otherwise, it is assumed to be a StatusInternalServerError
  165. func WriteError(w http.ResponseWriter, r *http.Request, err error) {
  166. if err == nil {
  167. return
  168. }
  169. switch e := err.(type) {
  170. case *etcdErr.Error:
  171. e.WriteTo(w)
  172. case *httptypes.HTTPError:
  173. if et := e.WriteTo(w); et != nil {
  174. plog.Debugf("error writing HTTPError (%v) to %s", et, r.RemoteAddr)
  175. }
  176. default:
  177. switch err {
  178. case etcdserver.ErrTimeoutDueToLeaderFail, etcdserver.ErrTimeoutDueToConnectionLost, etcdserver.ErrNotEnoughStartedMembers, etcdserver.ErrUnhealthy:
  179. mlog.MergeError(err)
  180. default:
  181. mlog.MergeErrorf("got unexpected response error (%v)", err)
  182. }
  183. herr := httptypes.NewHTTPError(http.StatusInternalServerError, "Internal Server Error")
  184. if et := herr.WriteTo(w); et != nil {
  185. plog.Debugf("error writing HTTPError (%v) to %s", et, r.RemoteAddr)
  186. }
  187. }
  188. }