2013-12-23 19:38:51 +00:00
|
|
|
package agent
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2014-11-18 16:03:36 +00:00
|
|
|
"fmt"
|
2017-09-25 18:40:42 +00:00
|
|
|
"net"
|
2013-12-23 19:38:51 +00:00
|
|
|
"net/http"
|
2014-03-20 00:50:57 +00:00
|
|
|
"net/http/pprof"
|
2015-04-14 00:31:53 +00:00
|
|
|
"net/url"
|
2017-07-15 07:07:08 +00:00
|
|
|
"regexp"
|
2014-02-05 22:36:13 +00:00
|
|
|
"strconv"
|
2014-08-22 19:59:47 +00:00
|
|
|
"strings"
|
2013-12-23 22:26:34 +00:00
|
|
|
"time"
|
2014-08-22 19:59:47 +00:00
|
|
|
|
2016-08-09 22:41:15 +00:00
|
|
|
"github.com/armon/go-metrics"
|
2017-08-23 14:52:48 +00:00
|
|
|
"github.com/hashicorp/consul/acl"
|
2017-07-06 10:34:00 +00:00
|
|
|
"github.com/hashicorp/consul/agent/structs"
|
2017-12-20 23:47:53 +00:00
|
|
|
"github.com/hashicorp/go-cleanhttp"
|
2014-08-22 19:59:47 +00:00
|
|
|
"github.com/mitchellh/mapstructure"
|
2013-12-23 19:38:51 +00:00
|
|
|
)
|
|
|
|
|
2017-09-26 06:11:19 +00:00
|
|
|
// MethodNotAllowedError should be returned by a handler when the HTTP method is not allowed.
|
|
|
|
type MethodNotAllowedError struct {
|
|
|
|
Method string
|
|
|
|
Allow []string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e MethodNotAllowedError) Error() string {
|
|
|
|
return fmt.Sprintf("method %s not allowed", e.Method)
|
|
|
|
}
|
|
|
|
|
2017-05-19 09:53:41 +00:00
|
|
|
// HTTPServer provides an HTTP api for an agent.
|
2013-12-23 19:38:51 +00:00
|
|
|
type HTTPServer struct {
|
2017-05-19 09:53:41 +00:00
|
|
|
*http.Server
|
2017-11-07 23:06:59 +00:00
|
|
|
ln net.Listener
|
2017-07-10 20:51:25 +00:00
|
|
|
agent *Agent
|
|
|
|
blacklist *Blacklist
|
|
|
|
|
|
|
|
// proto is filled by the agent to "http" or "https".
|
2017-05-24 13:22:56 +00:00
|
|
|
proto string
|
2014-11-14 19:39:19 +00:00
|
|
|
}
|
|
|
|
|
2017-11-29 00:06:26 +00:00
|
|
|
// endpoint is a Consul-specific HTTP handler that takes the usual arguments in
|
|
|
|
// but returns a response object and error, both of which are handled in a
|
|
|
|
// common manner by Consul's HTTP server.
|
|
|
|
type endpoint func(resp http.ResponseWriter, req *http.Request) (interface{}, error)
|
|
|
|
|
|
|
|
// unboundEndpoint is an endpoint method on a server.
|
|
|
|
type unboundEndpoint func(s *HTTPServer, resp http.ResponseWriter, req *http.Request) (interface{}, error)
|
|
|
|
|
|
|
|
// endpoints is a map from URL pattern to unbound endpoint.
|
|
|
|
var endpoints map[string]unboundEndpoint
|
|
|
|
|
|
|
|
// registerEndpoint registers a new endpoint, which should be done at package
|
|
|
|
// init() time.
|
|
|
|
func registerEndpoint(pattern string, fn unboundEndpoint) {
|
|
|
|
if endpoints == nil {
|
|
|
|
endpoints = make(map[string]unboundEndpoint)
|
|
|
|
}
|
|
|
|
if endpoints[pattern] != nil {
|
|
|
|
panic(fmt.Errorf("Pattern %q is already registered", pattern))
|
|
|
|
}
|
|
|
|
endpoints[pattern] = fn
|
|
|
|
}
|
|
|
|
|
2017-12-20 23:47:53 +00:00
|
|
|
// wrappedMux hangs on to the underlying mux for unit tests.
|
|
|
|
type wrappedMux struct {
|
|
|
|
mux *http.ServeMux
|
|
|
|
handler http.Handler
|
|
|
|
}
|
|
|
|
|
|
|
|
// ServeHTTP implements the http.Handler interface.
|
|
|
|
func (w *wrappedMux) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
|
|
|
|
w.handler.ServeHTTP(resp, req)
|
|
|
|
}
|
|
|
|
|
2017-05-19 09:53:41 +00:00
|
|
|
// handler is used to attach our handlers to the mux
|
|
|
|
func (s *HTTPServer) handler(enableDebug bool) http.Handler {
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
|
|
|
|
// handleFuncMetrics takes the given pattern and handler and wraps to produce
|
|
|
|
// metrics based on the pattern and request.
|
|
|
|
handleFuncMetrics := func(pattern string, handler http.HandlerFunc) {
|
|
|
|
// Get the parts of the pattern. We omit any initial empty for the
|
|
|
|
// leading slash, and put an underscore as a "thing" placeholder if we
|
|
|
|
// see a trailing slash, which means the part after is parsed. This lets
|
|
|
|
// us distinguish from things like /v1/query and /v1/query/<query id>.
|
|
|
|
var parts []string
|
|
|
|
for i, part := range strings.Split(pattern, "/") {
|
|
|
|
if part == "" {
|
|
|
|
if i == 0 {
|
|
|
|
continue
|
|
|
|
}
|
2016-08-09 22:41:15 +00:00
|
|
|
part = "_"
|
|
|
|
}
|
2017-05-19 09:53:41 +00:00
|
|
|
parts = append(parts, part)
|
2016-08-09 22:41:15 +00:00
|
|
|
}
|
|
|
|
|
2017-05-19 09:53:41 +00:00
|
|
|
// Register the wrapper, which will close over the expensive-to-compute
|
|
|
|
// parts from above.
|
2017-08-08 08:31:38 +00:00
|
|
|
// TODO (kyhavlov): Convert this to utilize metric labels in a major release
|
2017-05-19 09:53:41 +00:00
|
|
|
wrapper := func(resp http.ResponseWriter, req *http.Request) {
|
|
|
|
start := time.Now()
|
|
|
|
handler(resp, req)
|
2017-11-08 00:32:45 +00:00
|
|
|
key := append([]string{"http", req.Method}, parts...)
|
|
|
|
metrics.MeasureSince(append([]string{"consul"}, key...), start)
|
2017-05-19 09:53:41 +00:00
|
|
|
metrics.MeasureSince(key, start)
|
|
|
|
}
|
|
|
|
mux.HandleFunc(pattern, wrapper)
|
2016-08-09 22:41:15 +00:00
|
|
|
}
|
|
|
|
|
2017-05-19 09:53:41 +00:00
|
|
|
mux.HandleFunc("/", s.Index)
|
2017-11-29 00:06:26 +00:00
|
|
|
for pattern, fn := range endpoints {
|
|
|
|
thisFn := fn
|
|
|
|
bound := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
|
|
|
|
return thisFn(s, resp, req)
|
|
|
|
}
|
|
|
|
handleFuncMetrics(pattern, s.wrap(bound))
|
|
|
|
}
|
2014-03-20 00:50:57 +00:00
|
|
|
if enableDebug {
|
2017-05-19 09:53:41 +00:00
|
|
|
handleFuncMetrics("/debug/pprof/", pprof.Index)
|
|
|
|
handleFuncMetrics("/debug/pprof/cmdline", pprof.Cmdline)
|
|
|
|
handleFuncMetrics("/debug/pprof/profile", pprof.Profile)
|
|
|
|
handleFuncMetrics("/debug/pprof/symbol", pprof.Symbol)
|
2014-03-20 00:50:57 +00:00
|
|
|
}
|
2014-04-23 19:57:06 +00:00
|
|
|
|
2015-11-30 19:24:08 +00:00
|
|
|
// Use the custom UI dir if provided.
|
2017-05-11 17:31:58 +00:00
|
|
|
if s.agent.config.UIDir != "" {
|
2017-05-19 09:53:41 +00:00
|
|
|
mux.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(http.Dir(s.agent.config.UIDir))))
|
2017-04-21 00:02:42 +00:00
|
|
|
} else if s.agent.config.EnableUI {
|
2017-05-19 09:53:41 +00:00
|
|
|
mux.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(assetFS())))
|
2015-02-11 21:25:04 +00:00
|
|
|
}
|
2017-12-20 23:47:53 +00:00
|
|
|
|
|
|
|
// Wrap the whole mux with a handler that bans URLs with non-printable
|
|
|
|
// characters.
|
|
|
|
return &wrappedMux{
|
|
|
|
mux: mux,
|
|
|
|
handler: cleanhttp.PrintablePathCheckHandler(mux, nil),
|
|
|
|
}
|
2013-12-23 19:38:51 +00:00
|
|
|
}
|
|
|
|
|
2017-07-15 07:07:08 +00:00
|
|
|
// aclEndpointRE is used to find old ACL endpoints that take tokens in the URL
|
|
|
|
// so that we can redact them. The ACL endpoints that take the token in the URL
|
|
|
|
// are all of the form /v1/acl/<verb>/<token>, and can optionally include query
|
|
|
|
// parameters which are indicated by a question mark. We capture the part before
|
|
|
|
// the token, the token, and any query parameters after, and then reassemble as
|
|
|
|
// $1<hidden>$3 (the token in $2 isn't used), which will give:
|
|
|
|
//
|
|
|
|
// /v1/acl/clone/foo -> /v1/acl/clone/<hidden>
|
|
|
|
// /v1/acl/clone/foo?token=bar -> /v1/acl/clone/<hidden>?token=<hidden>
|
|
|
|
//
|
|
|
|
// The query parameter in the example above is obfuscated like any other, after
|
|
|
|
// this regular expression is applied, so the regular expression substitution
|
|
|
|
// results in:
|
|
|
|
//
|
|
|
|
// /v1/acl/clone/foo?token=bar -> /v1/acl/clone/<hidden>?token=bar
|
|
|
|
// ^---- $1 ----^^- $2 -^^-- $3 --^
|
|
|
|
//
|
|
|
|
// And then the loop that looks for parameters called "token" does the last
|
|
|
|
// step to get to the final redacted form.
|
|
|
|
var (
|
|
|
|
aclEndpointRE = regexp.MustCompile("^(/v1/acl/[^/]+/)([^?]+)([?]?.*)$")
|
|
|
|
)
|
|
|
|
|
2013-12-23 19:38:51 +00:00
|
|
|
// wrap is used to wrap functions to make them more convenient
|
2017-11-29 00:06:26 +00:00
|
|
|
func (s *HTTPServer) wrap(handler endpoint) http.HandlerFunc {
|
2017-05-11 17:37:47 +00:00
|
|
|
return func(resp http.ResponseWriter, req *http.Request) {
|
2017-09-25 18:40:42 +00:00
|
|
|
setHeaders(resp, s.agent.config.HTTPResponseHeaders)
|
|
|
|
setTranslateAddr(resp, s.agent.config.TranslateWANAddrs)
|
2014-12-28 04:53:19 +00:00
|
|
|
|
2015-04-12 18:17:31 +00:00
|
|
|
// Obfuscate any tokens from appearing in the logs
|
2015-04-14 00:31:53 +00:00
|
|
|
formVals, err := url.ParseQuery(req.URL.RawQuery)
|
|
|
|
if err != nil {
|
2017-05-19 09:53:41 +00:00
|
|
|
s.agent.logger.Printf("[ERR] http: Failed to decode query: %s from=%s", err, req.RemoteAddr)
|
2017-08-23 19:19:11 +00:00
|
|
|
resp.WriteHeader(http.StatusInternalServerError)
|
2015-04-14 00:31:53 +00:00
|
|
|
return
|
|
|
|
}
|
2015-04-12 18:17:31 +00:00
|
|
|
logURL := req.URL.String()
|
2015-04-14 00:31:53 +00:00
|
|
|
if tokens, ok := formVals["token"]; ok {
|
2015-04-12 18:17:31 +00:00
|
|
|
for _, token := range tokens {
|
2015-06-12 07:09:51 +00:00
|
|
|
if token == "" {
|
|
|
|
logURL += "<hidden>"
|
|
|
|
continue
|
|
|
|
}
|
2015-04-12 18:17:31 +00:00
|
|
|
logURL = strings.Replace(logURL, token, "<hidden>", -1)
|
|
|
|
}
|
|
|
|
}
|
2017-07-15 07:07:08 +00:00
|
|
|
logURL = aclEndpointRE.ReplaceAllString(logURL, "$1<hidden>$3")
|
2015-04-12 18:17:31 +00:00
|
|
|
|
2017-07-10 20:51:25 +00:00
|
|
|
if s.blacklist.Block(req.URL.Path) {
|
|
|
|
errMsg := "Endpoint is blocked by agent configuration"
|
|
|
|
s.agent.logger.Printf("[ERR] http: Request %s %v, error: %v from=%s", req.Method, logURL, err, req.RemoteAddr)
|
|
|
|
resp.WriteHeader(http.StatusForbidden)
|
|
|
|
fmt.Fprint(resp, errMsg)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-09-26 06:11:19 +00:00
|
|
|
isMethodNotAllowed := func(err error) bool {
|
|
|
|
_, ok := err.(MethodNotAllowedError)
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
2017-05-11 17:37:47 +00:00
|
|
|
handleErr := func(err error) {
|
2017-05-19 09:53:41 +00:00
|
|
|
s.agent.logger.Printf("[ERR] http: Request %s %v, error: %v from=%s", req.Method, logURL, err, req.RemoteAddr)
|
2017-08-23 14:52:48 +00:00
|
|
|
switch {
|
|
|
|
case acl.IsErrPermissionDenied(err) || acl.IsErrNotFound(err):
|
2017-08-23 19:19:11 +00:00
|
|
|
resp.WriteHeader(http.StatusForbidden)
|
2017-08-23 14:52:48 +00:00
|
|
|
fmt.Fprint(resp, err.Error())
|
2017-09-01 22:02:50 +00:00
|
|
|
case structs.IsErrRPCRateExceeded(err):
|
|
|
|
resp.WriteHeader(http.StatusTooManyRequests)
|
2017-09-26 06:11:19 +00:00
|
|
|
case isMethodNotAllowed(err):
|
|
|
|
// RFC2616 states that for 405 Method Not Allowed the response
|
|
|
|
// MUST include an Allow header containing the list of valid
|
|
|
|
// methods for the requested resource.
|
|
|
|
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
|
|
|
|
resp.Header()["Allow"] = err.(MethodNotAllowedError).Allow
|
|
|
|
resp.WriteHeader(http.StatusMethodNotAllowed) // 405
|
2017-09-01 22:02:50 +00:00
|
|
|
fmt.Fprint(resp, err.Error())
|
2017-08-23 14:52:48 +00:00
|
|
|
default:
|
2017-08-23 19:19:11 +00:00
|
|
|
resp.WriteHeader(http.StatusInternalServerError)
|
2017-08-23 14:52:48 +00:00
|
|
|
fmt.Fprint(resp, err.Error())
|
2017-05-11 17:37:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-12-23 19:38:51 +00:00
|
|
|
// Invoke the handler
|
2013-12-23 22:26:34 +00:00
|
|
|
start := time.Now()
|
|
|
|
defer func() {
|
2017-10-17 18:38:24 +00:00
|
|
|
s.agent.logger.Printf("[DEBUG] http: Request %s %v (%v) from=%s", req.Method, logURL, time.Since(start), req.RemoteAddr)
|
2013-12-23 22:26:34 +00:00
|
|
|
}()
|
2013-12-24 00:20:51 +00:00
|
|
|
obj, err := handler(resp, req)
|
2013-12-23 19:38:51 +00:00
|
|
|
if err != nil {
|
2017-05-11 17:37:47 +00:00
|
|
|
handleErr(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if obj == nil {
|
2013-12-23 19:38:51 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-05-11 17:37:47 +00:00
|
|
|
buf, err := s.marshalJSON(req, obj)
|
|
|
|
if err != nil {
|
|
|
|
handleErr(err)
|
|
|
|
return
|
2013-12-23 19:38:51 +00:00
|
|
|
}
|
2017-05-11 17:37:47 +00:00
|
|
|
resp.Header().Set("Content-Type", "application/json")
|
|
|
|
resp.Write(buf)
|
2013-12-23 19:38:51 +00:00
|
|
|
}
|
|
|
|
}
|
2013-12-24 00:20:51 +00:00
|
|
|
|
2016-05-07 00:50:58 +00:00
|
|
|
// marshalJSON marshals the object into JSON, respecting the user's pretty-ness
|
|
|
|
// configuration.
|
|
|
|
func (s *HTTPServer) marshalJSON(req *http.Request, obj interface{}) ([]byte, error) {
|
2016-11-18 06:31:19 +00:00
|
|
|
if _, ok := req.URL.Query()["pretty"]; ok || s.agent.config.DevMode {
|
2016-05-07 00:50:58 +00:00
|
|
|
buf, err := json.MarshalIndent(obj, "", " ")
|
2016-05-10 21:37:05 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
buf = append(buf, "\n"...)
|
|
|
|
return buf, nil
|
2016-05-07 00:50:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
buf, err := json.Marshal(obj)
|
2016-05-10 21:37:05 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-05-07 00:50:58 +00:00
|
|
|
return buf, err
|
|
|
|
}
|
|
|
|
|
2016-02-13 00:11:32 +00:00
|
|
|
// Returns true if the UI is enabled.
|
|
|
|
func (s *HTTPServer) IsUIEnabled() bool {
|
2017-05-11 17:31:58 +00:00
|
|
|
return s.agent.config.UIDir != "" || s.agent.config.EnableUI
|
2016-02-13 00:11:32 +00:00
|
|
|
}
|
|
|
|
|
2013-12-25 01:09:51 +00:00
|
|
|
// Renders a simple index page
|
|
|
|
func (s *HTTPServer) Index(resp http.ResponseWriter, req *http.Request) {
|
2014-04-27 19:10:38 +00:00
|
|
|
// Check if this is a non-index path
|
|
|
|
if req.URL.Path != "/" {
|
2017-08-23 19:19:11 +00:00
|
|
|
resp.WriteHeader(http.StatusNotFound)
|
2014-04-27 19:10:38 +00:00
|
|
|
return
|
2013-12-25 01:09:51 +00:00
|
|
|
}
|
2014-04-27 19:10:38 +00:00
|
|
|
|
2016-02-13 00:11:32 +00:00
|
|
|
// Give them something helpful if there's no UI so they at least know
|
|
|
|
// what this server is.
|
|
|
|
if !s.IsUIEnabled() {
|
Use fmt.Fprint/Fprintf/Fprintln
Used the following rewrite rules:
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b, c, d))) -> fmt.Fprintf(resp, a, b, c, d)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b, c))) -> fmt.Fprintf(resp, a, b, c)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b))) -> fmt.Fprintf(resp, a, b)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a))) -> fmt.Fprint(resp, a)' *.go
gofmt -w -r 'resp.Write([]byte(a + "\n")) -> fmt.Fprintln(resp, a)' *.go
gofmt -w -r 'resp.Write([]byte(a)) -> fmt.Fprint(resp, a)' *.go
2017-04-20 14:07:42 +00:00
|
|
|
fmt.Fprint(resp, "Consul Agent")
|
2014-04-27 19:10:38 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Redirect to the UI endpoint
|
2016-02-05 22:06:42 +00:00
|
|
|
http.Redirect(resp, req, "/ui/", http.StatusMovedPermanently) // 301
|
2013-12-25 01:09:51 +00:00
|
|
|
}
|
|
|
|
|
2013-12-24 00:20:51 +00:00
|
|
|
// decodeBody is used to decode a JSON request body
|
2014-04-21 22:02:36 +00:00
|
|
|
func decodeBody(req *http.Request, out interface{}, cb func(interface{}) error) error {
|
|
|
|
var raw interface{}
|
2013-12-24 00:20:51 +00:00
|
|
|
dec := json.NewDecoder(req.Body)
|
2014-04-21 22:02:36 +00:00
|
|
|
if err := dec.Decode(&raw); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Invoke the callback prior to decode
|
|
|
|
if cb != nil {
|
|
|
|
if err := cb(raw); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return mapstructure.Decode(raw, out)
|
2013-12-24 00:20:51 +00:00
|
|
|
}
|
2014-02-05 22:36:13 +00:00
|
|
|
|
2016-08-16 18:31:41 +00:00
|
|
|
// setTranslateAddr is used to set the address translation header. This is only
|
|
|
|
// present if the feature is active.
|
|
|
|
func setTranslateAddr(resp http.ResponseWriter, active bool) {
|
|
|
|
if active {
|
|
|
|
resp.Header().Set("X-Consul-Translate-Addresses", "true")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-05 22:36:13 +00:00
|
|
|
// setIndex is used to set the index response header
|
|
|
|
func setIndex(resp http.ResponseWriter, index uint64) {
|
2014-10-14 00:53:54 +00:00
|
|
|
resp.Header().Set("X-Consul-Index", strconv.FormatUint(index, 10))
|
2014-02-05 22:36:13 +00:00
|
|
|
}
|
|
|
|
|
2014-04-21 19:40:11 +00:00
|
|
|
// setKnownLeader is used to set the known leader header
|
|
|
|
func setKnownLeader(resp http.ResponseWriter, known bool) {
|
|
|
|
s := "true"
|
|
|
|
if !known {
|
|
|
|
s = "false"
|
|
|
|
}
|
2014-10-14 00:53:54 +00:00
|
|
|
resp.Header().Set("X-Consul-KnownLeader", s)
|
2014-04-21 19:40:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// setLastContact is used to set the last contact header
|
|
|
|
func setLastContact(resp http.ResponseWriter, last time.Duration) {
|
2017-06-01 11:53:27 +00:00
|
|
|
if last < 0 {
|
|
|
|
last = 0
|
|
|
|
}
|
2014-04-21 19:40:11 +00:00
|
|
|
lastMsec := uint64(last / time.Millisecond)
|
2014-10-14 00:53:54 +00:00
|
|
|
resp.Header().Set("X-Consul-LastContact", strconv.FormatUint(lastMsec, 10))
|
2014-04-21 19:40:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// setMeta is used to set the query response meta data
|
|
|
|
func setMeta(resp http.ResponseWriter, m *structs.QueryMeta) {
|
|
|
|
setIndex(resp, m.Index)
|
|
|
|
setLastContact(resp, m.LastContact)
|
|
|
|
setKnownLeader(resp, m.KnownLeader)
|
|
|
|
}
|
|
|
|
|
2014-12-28 04:53:19 +00:00
|
|
|
// setHeaders is used to set canonical response header fields
|
|
|
|
func setHeaders(resp http.ResponseWriter, headers map[string]string) {
|
|
|
|
for field, value := range headers {
|
|
|
|
resp.Header().Set(http.CanonicalHeaderKey(field), value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-05 22:36:13 +00:00
|
|
|
// parseWait is used to parse the ?wait and ?index query params
|
|
|
|
// Returns true on error
|
2014-04-21 19:26:12 +00:00
|
|
|
func parseWait(resp http.ResponseWriter, req *http.Request, b *structs.QueryOptions) bool {
|
2014-02-05 22:36:13 +00:00
|
|
|
query := req.URL.Query()
|
|
|
|
if wait := query.Get("wait"); wait != "" {
|
|
|
|
dur, err := time.ParseDuration(wait)
|
|
|
|
if err != nil {
|
2017-08-23 19:19:11 +00:00
|
|
|
resp.WriteHeader(http.StatusBadRequest)
|
Use fmt.Fprint/Fprintf/Fprintln
Used the following rewrite rules:
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b, c, d))) -> fmt.Fprintf(resp, a, b, c, d)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b, c))) -> fmt.Fprintf(resp, a, b, c)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b))) -> fmt.Fprintf(resp, a, b)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a))) -> fmt.Fprint(resp, a)' *.go
gofmt -w -r 'resp.Write([]byte(a + "\n")) -> fmt.Fprintln(resp, a)' *.go
gofmt -w -r 'resp.Write([]byte(a)) -> fmt.Fprint(resp, a)' *.go
2017-04-20 14:07:42 +00:00
|
|
|
fmt.Fprint(resp, "Invalid wait time")
|
2014-02-05 22:36:13 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
b.MaxQueryTime = dur
|
|
|
|
}
|
|
|
|
if idx := query.Get("index"); idx != "" {
|
|
|
|
index, err := strconv.ParseUint(idx, 10, 64)
|
|
|
|
if err != nil {
|
2017-08-23 19:19:11 +00:00
|
|
|
resp.WriteHeader(http.StatusBadRequest)
|
Use fmt.Fprint/Fprintf/Fprintln
Used the following rewrite rules:
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b, c, d))) -> fmt.Fprintf(resp, a, b, c, d)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b, c))) -> fmt.Fprintf(resp, a, b, c)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b))) -> fmt.Fprintf(resp, a, b)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a))) -> fmt.Fprint(resp, a)' *.go
gofmt -w -r 'resp.Write([]byte(a + "\n")) -> fmt.Fprintln(resp, a)' *.go
gofmt -w -r 'resp.Write([]byte(a)) -> fmt.Fprint(resp, a)' *.go
2017-04-20 14:07:42 +00:00
|
|
|
fmt.Fprint(resp, "Invalid index")
|
2014-02-05 22:36:13 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
b.MinQueryIndex = index
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2014-04-21 19:26:12 +00:00
|
|
|
// parseConsistency is used to parse the ?stale and ?consistent query params.
|
|
|
|
// Returns true on error
|
2017-06-27 05:04:55 +00:00
|
|
|
func parseConsistency(resp http.ResponseWriter, req *http.Request, b *structs.QueryOptions) bool {
|
2014-04-21 19:26:12 +00:00
|
|
|
query := req.URL.Query()
|
2017-06-16 08:55:53 +00:00
|
|
|
if _, ok := query["stale"]; ok {
|
|
|
|
b.AllowStale = true
|
|
|
|
}
|
2017-06-27 05:04:55 +00:00
|
|
|
if _, ok := query["consistent"]; ok {
|
|
|
|
b.RequireConsistent = true
|
|
|
|
}
|
2014-04-21 19:26:12 +00:00
|
|
|
if b.AllowStale && b.RequireConsistent {
|
2017-08-23 19:19:11 +00:00
|
|
|
resp.WriteHeader(http.StatusBadRequest)
|
Use fmt.Fprint/Fprintf/Fprintln
Used the following rewrite rules:
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b, c, d))) -> fmt.Fprintf(resp, a, b, c, d)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b, c))) -> fmt.Fprintf(resp, a, b, c)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a, b))) -> fmt.Fprintf(resp, a, b)' *.go
gofmt -w -r 'resp.Write([]byte(fmt.Sprintf(a))) -> fmt.Fprint(resp, a)' *.go
gofmt -w -r 'resp.Write([]byte(a + "\n")) -> fmt.Fprintln(resp, a)' *.go
gofmt -w -r 'resp.Write([]byte(a)) -> fmt.Fprint(resp, a)' *.go
2017-04-20 14:07:42 +00:00
|
|
|
fmt.Fprint(resp, "Cannot specify ?stale with ?consistent, conflicting semantics.")
|
2014-04-21 19:26:12 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2014-02-05 22:36:13 +00:00
|
|
|
// parseDC is used to parse the ?dc query param
|
|
|
|
func (s *HTTPServer) parseDC(req *http.Request, dc *string) {
|
|
|
|
if other := req.URL.Query().Get("dc"); other != "" {
|
|
|
|
*dc = other
|
|
|
|
} else if *dc == "" {
|
|
|
|
*dc = s.agent.config.Datacenter
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-10-19 13:59:24 +00:00
|
|
|
// parseToken is used to parse the ?token query param or the X-Consul-Token header
|
2014-08-12 18:35:22 +00:00
|
|
|
func (s *HTTPServer) parseToken(req *http.Request, token *string) {
|
|
|
|
if other := req.URL.Query().Get("token"); other != "" {
|
|
|
|
*token = other
|
2015-02-06 22:10:01 +00:00
|
|
|
return
|
2014-08-12 18:35:22 +00:00
|
|
|
}
|
2015-02-06 22:10:01 +00:00
|
|
|
|
2015-10-19 13:59:24 +00:00
|
|
|
if other := req.Header.Get("X-Consul-Token"); other != "" {
|
|
|
|
*token = other
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-02-06 22:10:01 +00:00
|
|
|
// Set the default ACLToken
|
2017-07-26 18:03:43 +00:00
|
|
|
*token = s.agent.tokens.UserToken()
|
2014-08-12 18:35:22 +00:00
|
|
|
}
|
|
|
|
|
2015-06-30 21:25:40 +00:00
|
|
|
// parseSource is used to parse the ?near=<node> query parameter, used for
|
|
|
|
// sorting by RTT based on a source node. We set the source's DC to the target
|
|
|
|
// DC in the request, if given, or else the agent's DC.
|
|
|
|
func (s *HTTPServer) parseSource(req *http.Request, source *structs.QuerySource) {
|
|
|
|
s.parseDC(req, &source.Datacenter)
|
|
|
|
if node := req.URL.Query().Get("near"); node != "" {
|
2015-07-28 17:39:37 +00:00
|
|
|
if node == "_agent" {
|
2015-07-24 21:30:53 +00:00
|
|
|
source.Node = s.agent.config.NodeName
|
|
|
|
} else {
|
|
|
|
source.Node = node
|
|
|
|
}
|
2015-06-30 21:25:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-09 19:21:49 +00:00
|
|
|
// parseMetaFilter is used to parse the ?node-meta=key:value query parameter, used for
|
|
|
|
// filtering results to nodes with the given metadata key/value
|
2017-01-11 19:41:12 +00:00
|
|
|
func (s *HTTPServer) parseMetaFilter(req *http.Request) map[string]string {
|
|
|
|
if filterList, ok := req.URL.Query()["node-meta"]; ok {
|
|
|
|
filters := make(map[string]string)
|
|
|
|
for _, filter := range filterList {
|
2017-06-02 10:04:04 +00:00
|
|
|
key, value := ParseMetaPair(filter)
|
2017-01-11 21:07:11 +00:00
|
|
|
filters[key] = value
|
2017-01-09 19:21:49 +00:00
|
|
|
}
|
2017-01-11 19:41:12 +00:00
|
|
|
return filters
|
2017-01-09 19:21:49 +00:00
|
|
|
}
|
2017-01-11 19:41:12 +00:00
|
|
|
return nil
|
2017-01-09 19:21:49 +00:00
|
|
|
}
|
|
|
|
|
2014-02-05 22:36:13 +00:00
|
|
|
// parse is a convenience method for endpoints that need
|
|
|
|
// to use both parseWait and parseDC.
|
2014-04-21 19:26:12 +00:00
|
|
|
func (s *HTTPServer) parse(resp http.ResponseWriter, req *http.Request, dc *string, b *structs.QueryOptions) bool {
|
2014-02-05 22:36:13 +00:00
|
|
|
s.parseDC(req, dc)
|
2014-08-12 18:35:22 +00:00
|
|
|
s.parseToken(req, &b.Token)
|
2017-06-27 05:04:55 +00:00
|
|
|
if parseConsistency(resp, req, b) {
|
2014-04-21 19:26:12 +00:00
|
|
|
return true
|
|
|
|
}
|
2014-02-05 22:36:13 +00:00
|
|
|
return parseWait(resp, req, b)
|
|
|
|
}
|