base.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. "go.etcd.io/etcd/etcdserver"
  22. "go.etcd.io/etcd/etcdserver/api"
  23. "go.etcd.io/etcd/etcdserver/api/v2error"
  24. "go.etcd.io/etcd/etcdserver/api/v2http/httptypes"
  25. "go.etcd.io/etcd/pkg/logutil"
  26. "go.etcd.io/etcd/version"
  27. "github.com/coreos/pkg/capnslog"
  28. "go.uber.org/zap"
  29. )
  30. var (
  31. plog = capnslog.NewPackageLogger("go.etcd.io/etcd", "etcdserver/api/etcdhttp")
  32. mlog = logutil.NewMergeLogger(plog)
  33. )
  34. const (
  35. configPath = "/config"
  36. varsPath = "/debug/vars"
  37. versionPath = "/version"
  38. )
  39. // HandleBasic adds handlers to a mux for serving JSON etcd client requests
  40. // that do not access the v2 store.
  41. func HandleBasic(mux *http.ServeMux, server etcdserver.ServerPeer) {
  42. mux.HandleFunc(varsPath, serveVars)
  43. // TODO: deprecate '/config/local/log' in v3.5
  44. mux.HandleFunc(configPath+"/local/log", logHandleFunc)
  45. HandleMetricsHealth(mux, server)
  46. mux.HandleFunc(versionPath, versionHandler(server.Cluster(), serveVersion))
  47. }
  48. func versionHandler(c api.Cluster, fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
  49. return func(w http.ResponseWriter, r *http.Request) {
  50. v := c.Version()
  51. if v != nil {
  52. fn(w, r, v.String())
  53. } else {
  54. fn(w, r, "not_decided")
  55. }
  56. }
  57. }
  58. func serveVersion(w http.ResponseWriter, r *http.Request, clusterV string) {
  59. if !allowMethod(w, r, "GET") {
  60. return
  61. }
  62. vs := version.Versions{
  63. Server: version.Version,
  64. Cluster: clusterV,
  65. }
  66. w.Header().Set("Content-Type", "application/json")
  67. b, err := json.Marshal(&vs)
  68. if err != nil {
  69. plog.Panicf("cannot marshal versions to json (%v)", err)
  70. }
  71. w.Write(b)
  72. }
  73. // TODO: deprecate '/config/local/log' in v3.5
  74. func logHandleFunc(w http.ResponseWriter, r *http.Request) {
  75. if !allowMethod(w, r, "PUT") {
  76. return
  77. }
  78. in := struct{ Level string }{}
  79. d := json.NewDecoder(r.Body)
  80. if err := d.Decode(&in); err != nil {
  81. WriteError(nil, w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid json body"))
  82. return
  83. }
  84. logl, err := capnslog.ParseLevel(strings.ToUpper(in.Level))
  85. if err != nil {
  86. WriteError(nil, w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid log level "+in.Level))
  87. return
  88. }
  89. plog.Noticef("globalLogLevel set to %q", logl.String())
  90. capnslog.SetGlobalLogLevel(logl)
  91. w.WriteHeader(http.StatusNoContent)
  92. }
  93. func serveVars(w http.ResponseWriter, r *http.Request) {
  94. if !allowMethod(w, r, "GET") {
  95. return
  96. }
  97. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  98. fmt.Fprintf(w, "{\n")
  99. first := true
  100. expvar.Do(func(kv expvar.KeyValue) {
  101. if !first {
  102. fmt.Fprintf(w, ",\n")
  103. }
  104. first = false
  105. fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
  106. })
  107. fmt.Fprintf(w, "\n}\n")
  108. }
  109. func allowMethod(w http.ResponseWriter, r *http.Request, m string) bool {
  110. if m == r.Method {
  111. return true
  112. }
  113. w.Header().Set("Allow", m)
  114. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  115. return false
  116. }
  117. // WriteError logs and writes the given Error to the ResponseWriter
  118. // If Error is an etcdErr, it is rendered to the ResponseWriter
  119. // Otherwise, it is assumed to be a StatusInternalServerError
  120. func WriteError(lg *zap.Logger, w http.ResponseWriter, r *http.Request, err error) {
  121. if err == nil {
  122. return
  123. }
  124. switch e := err.(type) {
  125. case *v2error.Error:
  126. e.WriteTo(w)
  127. case *httptypes.HTTPError:
  128. if et := e.WriteTo(w); et != nil {
  129. if lg != nil {
  130. lg.Debug(
  131. "failed to write v2 HTTP error",
  132. zap.String("remote-addr", r.RemoteAddr),
  133. zap.String("internal-server-error", e.Error()),
  134. zap.Error(et),
  135. )
  136. } else {
  137. plog.Debugf("error writing HTTPError (%v) to %s", et, r.RemoteAddr)
  138. }
  139. }
  140. default:
  141. switch err {
  142. case etcdserver.ErrTimeoutDueToLeaderFail, etcdserver.ErrTimeoutDueToConnectionLost, etcdserver.ErrNotEnoughStartedMembers,
  143. etcdserver.ErrUnhealthy:
  144. if lg != nil {
  145. lg.Warn(
  146. "v2 response error",
  147. zap.String("remote-addr", r.RemoteAddr),
  148. zap.String("internal-server-error", err.Error()),
  149. )
  150. } else {
  151. mlog.MergeError(err)
  152. }
  153. default:
  154. if lg != nil {
  155. lg.Warn(
  156. "unexpected v2 response error",
  157. zap.String("remote-addr", r.RemoteAddr),
  158. zap.String("internal-server-error", err.Error()),
  159. )
  160. } else {
  161. mlog.MergeErrorf("got unexpected response error (%v)", err)
  162. }
  163. }
  164. herr := httptypes.NewHTTPError(http.StatusInternalServerError, "Internal Server Error")
  165. if et := herr.WriteTo(w); et != nil {
  166. if lg != nil {
  167. lg.Debug(
  168. "failed to write v2 HTTP error",
  169. zap.String("remote-addr", r.RemoteAddr),
  170. zap.String("internal-server-error", err.Error()),
  171. zap.Error(et),
  172. )
  173. } else {
  174. plog.Debugf("error writing HTTPError (%v) to %s", et, r.RemoteAddr)
  175. }
  176. }
  177. }
  178. }