|
| 1 | +package queryapi |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/go-kit/log" |
| 10 | + "github.com/go-kit/log/level" |
| 11 | + "github.com/grafana/regexp" |
| 12 | + "github.com/munnerz/goautoneg" |
| 13 | + "github.com/prometheus/prometheus/promql" |
| 14 | + "github.com/prometheus/prometheus/storage" |
| 15 | + "github.com/prometheus/prometheus/util/annotations" |
| 16 | + "github.com/prometheus/prometheus/util/httputil" |
| 17 | + v1 "github.com/prometheus/prometheus/web/api/v1" |
| 18 | + "github.com/weaveworks/common/httpgrpc" |
| 19 | + |
| 20 | + "github.com/cortexproject/cortex/pkg/querier/tripperware/queryrange" |
| 21 | + "github.com/cortexproject/cortex/pkg/util" |
| 22 | + "github.com/cortexproject/cortex/pkg/util/api" |
| 23 | +) |
| 24 | + |
| 25 | +type QueryAPI struct { |
| 26 | + queryable storage.SampleAndChunkQueryable |
| 27 | + queryEngine promql.QueryEngine |
| 28 | + now func() time.Time |
| 29 | + statsRenderer v1.StatsRenderer |
| 30 | + logger log.Logger |
| 31 | + codecs []v1.Codec |
| 32 | + CORSOrigin *regexp.Regexp |
| 33 | +} |
| 34 | + |
| 35 | +func NewQueryAPI( |
| 36 | + qe promql.QueryEngine, |
| 37 | + q storage.SampleAndChunkQueryable, |
| 38 | + statsRenderer v1.StatsRenderer, |
| 39 | + logger log.Logger, |
| 40 | + codecs []v1.Codec, |
| 41 | + CORSOrigin *regexp.Regexp, |
| 42 | +) *QueryAPI { |
| 43 | + return &QueryAPI{ |
| 44 | + queryable: q, |
| 45 | + queryEngine: qe, |
| 46 | + now: time.Now, |
| 47 | + statsRenderer: statsRenderer, |
| 48 | + logger: logger, |
| 49 | + codecs: codecs, |
| 50 | + CORSOrigin: CORSOrigin, |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +// Custom handler for Query range API |
| 55 | +func (c *QueryAPI) RangeQueryHandler(r *http.Request) (result apiFuncResult) { |
| 56 | + start, err := util.ParseTime(r.FormValue("start")) |
| 57 | + if err != nil { |
| 58 | + return invalidParamError(err, "start") |
| 59 | + } |
| 60 | + end, err := util.ParseTime(r.FormValue("end")) |
| 61 | + if err != nil { |
| 62 | + return invalidParamError(err, "end") |
| 63 | + } |
| 64 | + if end < start { |
| 65 | + return invalidParamError(queryrange.ErrEndBeforeStart, "end") |
| 66 | + } |
| 67 | + |
| 68 | + step, err := util.ParseDurationMs(r.FormValue("step")) |
| 69 | + if err != nil { |
| 70 | + return invalidParamError(err, "step") |
| 71 | + } |
| 72 | + |
| 73 | + if step <= 0 { |
| 74 | + return invalidParamError(queryrange.ErrNegativeStep, "step") |
| 75 | + } |
| 76 | + |
| 77 | + // For safety, limit the number of returned points per timeseries. |
| 78 | + // This is sufficient for 60s resolution for a week or 1h resolution for a year. |
| 79 | + if (end-start)/step > 11000 { |
| 80 | + return apiFuncResult{nil, &apiError{errorBadData, queryrange.ErrStepTooSmall}, nil, nil} |
| 81 | + } |
| 82 | + |
| 83 | + ctx := r.Context() |
| 84 | + if to := r.FormValue("timeout"); to != "" { |
| 85 | + var cancel context.CancelFunc |
| 86 | + timeout, err := util.ParseDurationMs(to) |
| 87 | + if err != nil { |
| 88 | + return invalidParamError(err, "timeout") |
| 89 | + } |
| 90 | + |
| 91 | + ctx, cancel = context.WithTimeout(ctx, convertMsToDuration(timeout)) |
| 92 | + defer cancel() |
| 93 | + } |
| 94 | + |
| 95 | + opts, err := extractQueryOpts(r) |
| 96 | + if err != nil { |
| 97 | + return apiFuncResult{nil, &apiError{errorBadData, err}, nil, nil} |
| 98 | + } |
| 99 | + qry, err := c.queryEngine.NewRangeQuery(ctx, c.queryable, opts, r.FormValue("query"), convertMsToTime(start), convertMsToTime(end), convertMsToDuration(step)) |
| 100 | + if err != nil { |
| 101 | + return invalidParamError(httpgrpc.Errorf(http.StatusBadRequest, "%s", err.Error()), "query") |
| 102 | + } |
| 103 | + // From now on, we must only return with a finalizer in the result (to |
| 104 | + // be called by the caller) or call qry.Close ourselves (which is |
| 105 | + // required in the case of a panic). |
| 106 | + defer func() { |
| 107 | + if result.finalizer == nil { |
| 108 | + qry.Close() |
| 109 | + } |
| 110 | + }() |
| 111 | + |
| 112 | + ctx = httputil.ContextFromRequest(ctx, r) |
| 113 | + |
| 114 | + res := qry.Exec(ctx) |
| 115 | + if res.Err != nil { |
| 116 | + return apiFuncResult{nil, returnAPIError(res.Err), res.Warnings, qry.Close} |
| 117 | + } |
| 118 | + |
| 119 | + warnings := res.Warnings |
| 120 | + qs := c.statsRenderer(ctx, qry.Stats(), r.FormValue("stats")) |
| 121 | + |
| 122 | + return apiFuncResult{&v1.QueryData{ |
| 123 | + ResultType: res.Value.Type(), |
| 124 | + Result: res.Value, |
| 125 | + Stats: qs, |
| 126 | + }, nil, warnings, qry.Close} |
| 127 | +} |
| 128 | + |
| 129 | +// Custom handler for Query API |
| 130 | +func (c *QueryAPI) InstantHandler(r *http.Request) (result apiFuncResult) { |
| 131 | + ts, err := util.ParseTimeParam(r, "time", c.now().Unix()) |
| 132 | + if err != nil { |
| 133 | + return invalidParamError(err, "time") |
| 134 | + } |
| 135 | + |
| 136 | + ctx := r.Context() |
| 137 | + if to := r.FormValue("timeout"); to != "" { |
| 138 | + var cancel context.CancelFunc |
| 139 | + timeout, err := util.ParseDurationMs(to) |
| 140 | + if err != nil { |
| 141 | + return invalidParamError(err, "timeout") |
| 142 | + } |
| 143 | + |
| 144 | + ctx, cancel = context.WithDeadline(ctx, c.now().Add(convertMsToDuration(timeout))) |
| 145 | + defer cancel() |
| 146 | + } |
| 147 | + |
| 148 | + opts, err := extractQueryOpts(r) |
| 149 | + if err != nil { |
| 150 | + return apiFuncResult{nil, &apiError{errorBadData, err}, nil, nil} |
| 151 | + } |
| 152 | + qry, err := c.queryEngine.NewInstantQuery(ctx, c.queryable, opts, r.FormValue("query"), convertMsToTime(ts)) |
| 153 | + if err != nil { |
| 154 | + return invalidParamError(httpgrpc.Errorf(http.StatusBadRequest, "%s", err.Error()), "query") |
| 155 | + } |
| 156 | + |
| 157 | + // From now on, we must only return with a finalizer in the result (to |
| 158 | + // be called by the caller) or call qry.Close ourselves (which is |
| 159 | + // required in the case of a panic). |
| 160 | + defer func() { |
| 161 | + if result.finalizer == nil { |
| 162 | + qry.Close() |
| 163 | + } |
| 164 | + }() |
| 165 | + |
| 166 | + ctx = httputil.ContextFromRequest(ctx, r) |
| 167 | + |
| 168 | + res := qry.Exec(ctx) |
| 169 | + if res.Err != nil { |
| 170 | + return apiFuncResult{nil, returnAPIError(res.Err), res.Warnings, qry.Close} |
| 171 | + } |
| 172 | + |
| 173 | + warnings := res.Warnings |
| 174 | + qs := c.statsRenderer(ctx, qry.Stats(), r.FormValue("stats")) |
| 175 | + |
| 176 | + return apiFuncResult{&v1.QueryData{ |
| 177 | + ResultType: res.Value.Type(), |
| 178 | + Result: res.Value, |
| 179 | + Stats: qs, |
| 180 | + }, nil, warnings, qry.Close} |
| 181 | +} |
| 182 | + |
| 183 | +func (c *QueryAPI) Wrap(f apiFunc) http.HandlerFunc { |
| 184 | + return func(w http.ResponseWriter, r *http.Request) { |
| 185 | + httputil.SetCORS(w, c.CORSOrigin, r) |
| 186 | + |
| 187 | + result := f(r) |
| 188 | + if result.finalizer != nil { |
| 189 | + defer result.finalizer() |
| 190 | + } |
| 191 | + |
| 192 | + if result.err != nil { |
| 193 | + api.RespondFromGRPCError(c.logger, w, result.err.err) |
| 194 | + return |
| 195 | + } |
| 196 | + |
| 197 | + if result.data != nil { |
| 198 | + c.respond(w, r, result.data, result.warnings, r.FormValue("query")) |
| 199 | + return |
| 200 | + } |
| 201 | + w.WriteHeader(http.StatusNoContent) |
| 202 | + } |
| 203 | +} |
| 204 | + |
| 205 | +func (c *QueryAPI) respond(w http.ResponseWriter, req *http.Request, data interface{}, warnings annotations.Annotations, query string) { |
| 206 | + warn, info := warnings.AsStrings(query, 10, 10) |
| 207 | + |
| 208 | + resp := &v1.Response{ |
| 209 | + Status: statusSuccess, |
| 210 | + Data: data, |
| 211 | + Warnings: warn, |
| 212 | + Infos: info, |
| 213 | + } |
| 214 | + |
| 215 | + codec, err := c.negotiateCodec(req, resp) |
| 216 | + if err != nil { |
| 217 | + api.RespondFromGRPCError(c.logger, w, httpgrpc.Errorf(http.StatusNotAcceptable, "%s", &apiError{errorNotAcceptable, err})) |
| 218 | + return |
| 219 | + } |
| 220 | + |
| 221 | + b, err := codec.Encode(resp) |
| 222 | + if err != nil { |
| 223 | + level.Error(c.logger).Log("error marshaling response", "url", req.URL, "err", err) |
| 224 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 225 | + return |
| 226 | + } |
| 227 | + |
| 228 | + w.Header().Set("Content-Type", codec.ContentType().String()) |
| 229 | + w.WriteHeader(http.StatusOK) |
| 230 | + if n, err := w.Write(b); err != nil { |
| 231 | + level.Error(c.logger).Log("error writing response", "url", req.URL, "bytesWritten", n, "err", err) |
| 232 | + } |
| 233 | +} |
| 234 | + |
| 235 | +func (c *QueryAPI) negotiateCodec(req *http.Request, resp *v1.Response) (v1.Codec, error) { |
| 236 | + for _, clause := range goautoneg.ParseAccept(req.Header.Get("Accept")) { |
| 237 | + for _, codec := range c.codecs { |
| 238 | + if codec.ContentType().Satisfies(clause) && codec.CanEncode(resp) { |
| 239 | + return codec, nil |
| 240 | + } |
| 241 | + } |
| 242 | + } |
| 243 | + |
| 244 | + defaultCodec := c.codecs[0] |
| 245 | + if !defaultCodec.CanEncode(resp) { |
| 246 | + return nil, fmt.Errorf("cannot encode response as %s", defaultCodec.ContentType()) |
| 247 | + } |
| 248 | + |
| 249 | + return defaultCodec, nil |
| 250 | +} |
0 commit comments