base.go 5.2 KB

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