base.go 4.3 KB

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