2020-01-10 04:56:36 -08:00
|
|
|
// Copyright 2020 The Prometheus Authors
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
|
|
package httputil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/prometheus/prometheus/promql"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ctxParam int
|
|
|
|
|
|
|
|
var pathParam ctxParam
|
|
|
|
|
|
|
|
// ContextWithPath returns a new context with the given path to be used later
|
|
|
|
// when logging the query.
|
|
|
|
func ContextWithPath(ctx context.Context, path string) context.Context {
|
|
|
|
return context.WithValue(ctx, pathParam, path)
|
|
|
|
}
|
|
|
|
|
2020-02-18 08:35:16 -08:00
|
|
|
// ContextFromRequest returns a new context with identifiers of
|
2020-01-10 04:56:36 -08:00
|
|
|
// the request to be used later when logging the query.
|
2020-02-18 06:52:29 -08:00
|
|
|
func ContextFromRequest(ctx context.Context, r *http.Request) context.Context {
|
2020-02-18 07:22:26 -08:00
|
|
|
reqCtxVal := map[string]string{
|
2020-02-18 06:52:29 -08:00
|
|
|
"method": r.Method,
|
2020-01-10 04:56:36 -08:00
|
|
|
}
|
2020-02-18 06:52:29 -08:00
|
|
|
|
|
|
|
// r.RemoteAddr has no defined format, so don't return error if we cannot split it into IP:Port.
|
|
|
|
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
|
|
|
|
if ip != "" {
|
2020-02-18 07:22:26 -08:00
|
|
|
reqCtxVal["clientIP"] = ip
|
2020-02-18 06:52:29 -08:00
|
|
|
}
|
|
|
|
|
2020-01-10 04:56:36 -08:00
|
|
|
var path string
|
|
|
|
if v := ctx.Value(pathParam); v != nil {
|
|
|
|
path = v.(string)
|
2020-02-18 07:22:26 -08:00
|
|
|
reqCtxVal["path"] = path
|
2020-01-10 04:56:36 -08:00
|
|
|
}
|
2020-02-18 06:52:29 -08:00
|
|
|
|
2020-01-27 01:53:10 -08:00
|
|
|
return promql.NewOriginContext(ctx, map[string]interface{}{
|
2020-02-18 07:22:26 -08:00
|
|
|
"httpRequest": reqCtxVal,
|
2020-02-18 06:52:29 -08:00
|
|
|
})
|
2020-01-10 04:56:36 -08:00
|
|
|
}
|