2015-01-21 19:07:45 +00:00
|
|
|
// Copyright 2013 The Prometheus Authors
|
2014-05-28 17:44:54 +00:00
|
|
|
// 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.
|
|
|
|
|
2015-05-28 19:22:08 +00:00
|
|
|
package template
|
2014-05-28 17:44:54 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2014-06-05 13:07:54 +00:00
|
|
|
"math"
|
|
|
|
"regexp"
|
|
|
|
"sort"
|
2014-06-05 17:44:19 +00:00
|
|
|
"strings"
|
2016-12-24 09:44:04 +00:00
|
|
|
"time"
|
2014-06-10 14:30:06 +00:00
|
|
|
|
|
|
|
html_template "html/template"
|
|
|
|
text_template "text/template"
|
2014-05-28 17:44:54 +00:00
|
|
|
|
2015-08-20 15:18:46 +00:00
|
|
|
"github.com/prometheus/common/model"
|
2016-12-24 23:37:46 +00:00
|
|
|
"github.com/prometheus/prometheus/pkg/labels"
|
promql: Allow per-query contexts.
For Weaveworks' Frankenstein, we need to support multitenancy. In
Frankenstein, we initially solved this without modifying the promql
package at all: we constructed a new promql.Engine for every
query and injected a storage implementation into that engine which would
be primed to only collect data for a given user.
This is problematic to upstream, however. Prometheus assumes that there
is only one engine: the query concurrency gate is part of the engine,
and the engine contains one central cancellable context to shut down all
queries. Also, creating a new engine for every query seems like overkill.
Thus, we want to be able to pass per-query contexts into a single engine.
This change gets rid of the promql.Engine's built-in base context and
allows passing in a per-query context instead. Central cancellation of
all queries is still possible by deriving all passed-in contexts from
one central one, but this is now the responsibility of the caller. The
central query context is now created in main() and passed into the
relevant components (web handler / API, rule manager).
In a next step, the per-query context would have to be passed to the
storage implementation, so that the storage can implement multi-tenancy
or other features based on the contextual information.
2016-09-15 11:52:50 +00:00
|
|
|
"golang.org/x/net/context"
|
2014-05-28 17:44:54 +00:00
|
|
|
|
2015-03-30 17:43:19 +00:00
|
|
|
"github.com/prometheus/prometheus/promql"
|
2015-05-29 11:30:30 +00:00
|
|
|
"github.com/prometheus/prometheus/util/strutil"
|
2014-05-28 17:44:54 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// A version of vector that's easier to use from templates.
|
|
|
|
type sample struct {
|
|
|
|
Labels map[string]string
|
|
|
|
Value float64
|
|
|
|
}
|
|
|
|
type queryResult []*sample
|
|
|
|
|
2014-06-05 13:07:54 +00:00
|
|
|
type queryResultByLabelSorter struct {
|
|
|
|
results queryResult
|
|
|
|
by string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (q queryResultByLabelSorter) Len() int {
|
|
|
|
return len(q.results)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (q queryResultByLabelSorter) Less(i, j int) bool {
|
|
|
|
return q.results[i].Labels[q.by] < q.results[j].Labels[q.by]
|
|
|
|
}
|
|
|
|
|
|
|
|
func (q queryResultByLabelSorter) Swap(i, j int) {
|
|
|
|
q.results[i], q.results[j] = q.results[j], q.results[i]
|
|
|
|
}
|
|
|
|
|
2016-12-24 09:44:04 +00:00
|
|
|
func query(ctx context.Context, q string, ts time.Time, queryEngine *promql.Engine) (queryResult, error) {
|
|
|
|
query, err := queryEngine.NewInstantQuery(q, ts)
|
2014-06-10 14:30:06 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
promql: Allow per-query contexts.
For Weaveworks' Frankenstein, we need to support multitenancy. In
Frankenstein, we initially solved this without modifying the promql
package at all: we constructed a new promql.Engine for every
query and injected a storage implementation into that engine which would
be primed to only collect data for a given user.
This is problematic to upstream, however. Prometheus assumes that there
is only one engine: the query concurrency gate is part of the engine,
and the engine contains one central cancellable context to shut down all
queries. Also, creating a new engine for every query seems like overkill.
Thus, we want to be able to pass per-query contexts into a single engine.
This change gets rid of the promql.Engine's built-in base context and
allows passing in a per-query context instead. Central cancellation of
all queries is still possible by deriving all passed-in contexts from
one central one, but this is now the responsibility of the caller. The
central query context is now created in main() and passed into the
relevant components (web handler / API, rule manager).
In a next step, the per-query context would have to be passed to the
storage implementation, so that the storage can implement multi-tenancy
or other features based on the contextual information.
2016-09-15 11:52:50 +00:00
|
|
|
res := query.Exec(ctx)
|
2015-05-11 07:12:28 +00:00
|
|
|
if res.Err != nil {
|
|
|
|
return nil, res.Err
|
|
|
|
}
|
2016-12-24 23:37:46 +00:00
|
|
|
var vector promql.Vector
|
2015-05-11 07:12:28 +00:00
|
|
|
|
|
|
|
switch v := res.Value.(type) {
|
2016-12-24 23:37:46 +00:00
|
|
|
case promql.Matrix:
|
2015-05-11 07:12:28 +00:00
|
|
|
return nil, errors.New("matrix return values not supported")
|
2016-12-24 23:37:46 +00:00
|
|
|
case promql.Vector:
|
2015-05-11 07:12:28 +00:00
|
|
|
vector = v
|
2016-12-24 23:37:46 +00:00
|
|
|
case promql.Scalar:
|
|
|
|
vector = promql.Vector{promql.Sample{
|
|
|
|
Point: promql.Point(v),
|
2015-05-11 07:12:28 +00:00
|
|
|
}}
|
2016-12-24 23:37:46 +00:00
|
|
|
case promql.String:
|
|
|
|
vector = promql.Vector{promql.Sample{
|
|
|
|
Metric: labels.FromStrings("__value__", v.V),
|
|
|
|
Point: promql.Point{T: v.T},
|
2015-05-11 07:12:28 +00:00
|
|
|
}}
|
|
|
|
default:
|
|
|
|
panic("template.query: unhandled result value type")
|
2014-06-10 14:30:06 +00:00
|
|
|
}
|
2014-05-28 17:44:54 +00:00
|
|
|
|
2015-03-30 17:43:19 +00:00
|
|
|
// promql.Vector is hard to work with in templates, so convert to
|
2014-06-10 14:30:06 +00:00
|
|
|
// base data types.
|
2016-12-24 23:37:46 +00:00
|
|
|
// TODO(fabxc): probably not true anymore after type rework.
|
2014-06-10 14:30:06 +00:00
|
|
|
var result = make(queryResult, len(vector))
|
|
|
|
for n, v := range vector {
|
|
|
|
s := sample{
|
2016-12-24 23:37:46 +00:00
|
|
|
Value: v.V,
|
|
|
|
Labels: v.Metric.Map(),
|
2014-06-10 14:30:06 +00:00
|
|
|
}
|
|
|
|
result[n] = &s
|
|
|
|
}
|
|
|
|
return result, nil
|
|
|
|
}
|
2014-05-28 17:44:54 +00:00
|
|
|
|
2015-08-24 13:07:27 +00:00
|
|
|
// Expander executes templates in text or HTML mode with a common set of Prometheus template functions.
|
|
|
|
type Expander struct {
|
2014-06-10 14:30:06 +00:00
|
|
|
text string
|
|
|
|
name string
|
|
|
|
data interface{}
|
|
|
|
funcMap text_template.FuncMap
|
|
|
|
}
|
|
|
|
|
2014-12-10 15:16:49 +00:00
|
|
|
// NewTemplateExpander returns a template expander ready to use.
|
2016-09-15 22:58:06 +00:00
|
|
|
func NewTemplateExpander(ctx context.Context, text string, name string, data interface{}, timestamp model.Time, queryEngine *promql.Engine, pathPrefix string) *Expander {
|
2015-08-24 13:07:27 +00:00
|
|
|
return &Expander{
|
2014-06-10 14:30:06 +00:00
|
|
|
text: text,
|
|
|
|
name: name,
|
|
|
|
data: data,
|
|
|
|
funcMap: text_template.FuncMap{
|
|
|
|
"query": func(q string) (queryResult, error) {
|
2016-12-24 23:37:46 +00:00
|
|
|
return query(ctx, q, timestamp.Time(), queryEngine)
|
2014-06-10 14:30:06 +00:00
|
|
|
},
|
|
|
|
"first": func(v queryResult) (*sample, error) {
|
|
|
|
if len(v) > 0 {
|
|
|
|
return v[0], nil
|
|
|
|
}
|
|
|
|
return nil, errors.New("first() called on vector with no elements")
|
|
|
|
},
|
|
|
|
"label": func(label string, s *sample) string {
|
|
|
|
return s.Labels[label]
|
|
|
|
},
|
|
|
|
"value": func(s *sample) float64 {
|
|
|
|
return s.Value
|
|
|
|
},
|
|
|
|
"strvalue": func(s *sample) string {
|
|
|
|
return s.Labels["__value__"]
|
|
|
|
},
|
|
|
|
"args": func(args ...interface{}) map[string]interface{} {
|
|
|
|
result := make(map[string]interface{})
|
|
|
|
for i, a := range args {
|
|
|
|
result[fmt.Sprintf("arg%d", i)] = a
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
},
|
|
|
|
"reReplaceAll": func(pattern, repl, text string) string {
|
|
|
|
re := regexp.MustCompile(pattern)
|
|
|
|
return re.ReplaceAllString(text, repl)
|
|
|
|
},
|
|
|
|
"safeHtml": func(text string) html_template.HTML {
|
|
|
|
return html_template.HTML(text)
|
|
|
|
},
|
2014-07-25 12:23:47 +00:00
|
|
|
"match": regexp.MatchString,
|
|
|
|
"title": strings.Title,
|
2016-08-15 11:00:22 +00:00
|
|
|
"toUpper": strings.ToUpper,
|
|
|
|
"toLower": strings.ToLower,
|
2015-05-28 19:33:48 +00:00
|
|
|
"graphLink": strutil.GraphLinkForExpression,
|
|
|
|
"tableLink": strutil.TableLinkForExpression,
|
2014-06-10 14:30:06 +00:00
|
|
|
"sortByLabel": func(label string, v queryResult) queryResult {
|
|
|
|
sorter := queryResultByLabelSorter{v[:], label}
|
|
|
|
sort.Stable(sorter)
|
|
|
|
return v
|
|
|
|
},
|
|
|
|
"humanize": func(v float64) string {
|
2015-03-28 18:51:41 +00:00
|
|
|
if v == 0 || math.IsNaN(v) || math.IsInf(v, 0) {
|
2014-06-11 10:32:19 +00:00
|
|
|
return fmt.Sprintf("%.4g", v)
|
2014-06-10 14:30:06 +00:00
|
|
|
}
|
|
|
|
if math.Abs(v) >= 1 {
|
|
|
|
prefix := ""
|
|
|
|
for _, p := range []string{"k", "M", "G", "T", "P", "E", "Z", "Y"} {
|
|
|
|
if math.Abs(v) < 1000 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
prefix = p
|
|
|
|
v /= 1000
|
2014-06-05 13:07:54 +00:00
|
|
|
}
|
2014-06-11 10:32:19 +00:00
|
|
|
return fmt.Sprintf("%.4g%s", v, prefix)
|
2014-12-10 15:16:49 +00:00
|
|
|
}
|
|
|
|
prefix := ""
|
|
|
|
for _, p := range []string{"m", "u", "n", "p", "f", "a", "z", "y"} {
|
|
|
|
if math.Abs(v) >= 1 {
|
|
|
|
break
|
2014-06-10 14:30:06 +00:00
|
|
|
}
|
2014-12-10 15:16:49 +00:00
|
|
|
prefix = p
|
|
|
|
v *= 1000
|
2014-06-10 14:30:06 +00:00
|
|
|
}
|
2014-12-10 15:16:49 +00:00
|
|
|
return fmt.Sprintf("%.4g%s", v, prefix)
|
2014-06-10 14:30:06 +00:00
|
|
|
},
|
|
|
|
"humanize1024": func(v float64) string {
|
2015-03-28 18:51:41 +00:00
|
|
|
if math.Abs(v) <= 1 || math.IsNaN(v) || math.IsInf(v, 0) {
|
2014-06-11 10:32:19 +00:00
|
|
|
return fmt.Sprintf("%.4g", v)
|
2014-06-05 13:07:54 +00:00
|
|
|
}
|
|
|
|
prefix := ""
|
2014-06-10 14:30:06 +00:00
|
|
|
for _, p := range []string{"ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"} {
|
|
|
|
if math.Abs(v) < 1024 {
|
2014-06-05 13:07:54 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
prefix = p
|
2014-06-10 14:30:06 +00:00
|
|
|
v /= 1024
|
2014-06-05 13:07:54 +00:00
|
|
|
}
|
2014-06-11 10:32:19 +00:00
|
|
|
return fmt.Sprintf("%.4g%s", v, prefix)
|
|
|
|
},
|
|
|
|
"humanizeDuration": func(v float64) string {
|
2015-03-28 18:51:41 +00:00
|
|
|
if math.IsNaN(v) || math.IsInf(v, 0) {
|
|
|
|
return fmt.Sprintf("%.4g", v)
|
|
|
|
}
|
2014-06-11 10:32:19 +00:00
|
|
|
if v == 0 {
|
|
|
|
return fmt.Sprintf("%.4gs", v)
|
|
|
|
}
|
|
|
|
if math.Abs(v) >= 1 {
|
|
|
|
sign := ""
|
|
|
|
if v < 0 {
|
|
|
|
sign = "-"
|
|
|
|
v = -v
|
|
|
|
}
|
2015-02-26 17:17:04 +00:00
|
|
|
seconds := int64(v) % 60
|
2014-06-11 10:32:19 +00:00
|
|
|
minutes := (int64(v) / 60) % 60
|
|
|
|
hours := (int64(v) / 60 / 60) % 24
|
|
|
|
days := (int64(v) / 60 / 60 / 24)
|
|
|
|
// For days to minutes, we display seconds as an integer.
|
|
|
|
if days != 0 {
|
2015-02-26 17:17:04 +00:00
|
|
|
return fmt.Sprintf("%s%dd %dh %dm %ds", sign, days, hours, minutes, seconds)
|
2014-06-11 10:32:19 +00:00
|
|
|
}
|
|
|
|
if hours != 0 {
|
2015-02-26 17:17:04 +00:00
|
|
|
return fmt.Sprintf("%s%dh %dm %ds", sign, hours, minutes, seconds)
|
2014-06-11 10:32:19 +00:00
|
|
|
}
|
|
|
|
if minutes != 0 {
|
2015-02-26 17:17:04 +00:00
|
|
|
return fmt.Sprintf("%s%dm %ds", sign, minutes, seconds)
|
2014-06-11 10:32:19 +00:00
|
|
|
}
|
|
|
|
// For seconds, we display 4 significant digts.
|
2015-02-26 17:17:04 +00:00
|
|
|
return fmt.Sprintf("%s%.4gs", sign, v)
|
2014-12-10 15:16:49 +00:00
|
|
|
}
|
|
|
|
prefix := ""
|
|
|
|
for _, p := range []string{"m", "u", "n", "p", "f", "a", "z", "y"} {
|
|
|
|
if math.Abs(v) >= 1 {
|
|
|
|
break
|
2014-06-11 10:32:19 +00:00
|
|
|
}
|
2014-12-10 15:16:49 +00:00
|
|
|
prefix = p
|
|
|
|
v *= 1000
|
2014-06-11 10:32:19 +00:00
|
|
|
}
|
2014-12-10 15:16:49 +00:00
|
|
|
return fmt.Sprintf("%.4g%ss", v, prefix)
|
2014-06-10 14:30:06 +00:00
|
|
|
},
|
2015-06-23 15:46:57 +00:00
|
|
|
"humanizeTimestamp": func(v float64) string {
|
|
|
|
if math.IsNaN(v) || math.IsInf(v, 0) {
|
|
|
|
return fmt.Sprintf("%.4g", v)
|
|
|
|
}
|
2015-08-20 15:18:46 +00:00
|
|
|
t := model.TimeFromUnixNano(int64(v * 1e9)).Time().UTC()
|
2015-06-23 15:46:57 +00:00
|
|
|
return fmt.Sprint(t)
|
|
|
|
},
|
2015-03-24 21:04:38 +00:00
|
|
|
"pathPrefix": func() string {
|
2015-03-30 17:43:19 +00:00
|
|
|
return pathPrefix
|
2015-03-24 21:04:38 +00:00
|
|
|
},
|
2014-06-05 13:07:54 +00:00
|
|
|
},
|
2014-05-28 17:44:54 +00:00
|
|
|
}
|
2014-06-10 14:30:06 +00:00
|
|
|
}
|
|
|
|
|
2015-08-24 13:07:27 +00:00
|
|
|
// Funcs adds the functions in fm to the Expander's function map.
|
2015-06-23 15:46:57 +00:00
|
|
|
// Existing functions will be overwritten in case of conflict.
|
2015-08-24 13:07:27 +00:00
|
|
|
func (te Expander) Funcs(fm text_template.FuncMap) {
|
2015-06-23 15:46:57 +00:00
|
|
|
for k, v := range fm {
|
|
|
|
te.funcMap[k] = v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-08-24 13:07:27 +00:00
|
|
|
// Expand expands a template in text (non-HTML) mode.
|
|
|
|
func (te Expander) Expand() (result string, resultErr error) {
|
2014-06-10 14:30:06 +00:00
|
|
|
// It'd better to have no alert description than to kill the whole process
|
|
|
|
// if there's a bug in the template.
|
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
var ok bool
|
|
|
|
resultErr, ok = r.(error)
|
|
|
|
if !ok {
|
2014-12-10 15:16:49 +00:00
|
|
|
resultErr = fmt.Errorf("panic expanding template %v: %v", te.name, r)
|
2014-06-10 14:30:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
2014-05-28 17:44:54 +00:00
|
|
|
|
2014-06-10 14:30:06 +00:00
|
|
|
tmpl, err := text_template.New(te.name).Funcs(te.funcMap).Parse(te.text)
|
2015-11-28 13:45:32 +00:00
|
|
|
tmpl.Option("missingkey=zero")
|
2014-05-28 17:44:54 +00:00
|
|
|
if err != nil {
|
2014-12-10 15:16:49 +00:00
|
|
|
return "", fmt.Errorf("error parsing template %v: %v", te.name, err)
|
2014-05-28 17:44:54 +00:00
|
|
|
}
|
2015-09-12 23:06:40 +00:00
|
|
|
var buffer bytes.Buffer
|
2014-06-10 14:30:06 +00:00
|
|
|
err = tmpl.Execute(&buffer, te.data)
|
2014-05-28 17:44:54 +00:00
|
|
|
if err != nil {
|
2014-12-10 15:16:49 +00:00
|
|
|
return "", fmt.Errorf("error executing template %v: %v", te.name, err)
|
2014-05-28 17:44:54 +00:00
|
|
|
}
|
|
|
|
return buffer.String(), nil
|
|
|
|
}
|
|
|
|
|
2015-08-24 13:07:27 +00:00
|
|
|
// ExpandHTML expands a template with HTML escaping, with templates read from the given files.
|
|
|
|
func (te Expander) ExpandHTML(templateFiles []string) (result string, resultErr error) {
|
2014-06-10 14:30:06 +00:00
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
var ok bool
|
|
|
|
resultErr, ok = r.(error)
|
|
|
|
if !ok {
|
2014-12-10 15:16:49 +00:00
|
|
|
resultErr = fmt.Errorf("panic expanding template %v: %v", te.name, r)
|
2014-06-10 14:30:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2014-07-25 16:32:17 +00:00
|
|
|
tmpl := html_template.New(te.name).Funcs(html_template.FuncMap(te.funcMap))
|
2015-11-28 13:45:32 +00:00
|
|
|
tmpl.Option("missingkey=zero")
|
2014-07-29 16:28:48 +00:00
|
|
|
tmpl.Funcs(html_template.FuncMap{
|
|
|
|
"tmpl": func(name string, data interface{}) (html_template.HTML, error) {
|
|
|
|
var buffer bytes.Buffer
|
|
|
|
err := tmpl.ExecuteTemplate(&buffer, name, data)
|
|
|
|
return html_template.HTML(buffer.String()), err
|
|
|
|
},
|
|
|
|
})
|
|
|
|
tmpl, err := tmpl.Parse(te.text)
|
2014-05-28 17:44:54 +00:00
|
|
|
if err != nil {
|
2014-12-10 15:16:49 +00:00
|
|
|
return "", fmt.Errorf("error parsing template %v: %v", te.name, err)
|
2014-05-28 17:44:54 +00:00
|
|
|
}
|
2014-06-10 14:30:06 +00:00
|
|
|
if len(templateFiles) > 0 {
|
|
|
|
_, err = tmpl.ParseFiles(templateFiles...)
|
|
|
|
if err != nil {
|
2014-12-10 15:16:49 +00:00
|
|
|
return "", fmt.Errorf("error parsing template files for %v: %v", te.name, err)
|
2014-05-28 17:44:54 +00:00
|
|
|
}
|
|
|
|
}
|
2015-09-12 23:06:40 +00:00
|
|
|
var buffer bytes.Buffer
|
2014-06-10 14:30:06 +00:00
|
|
|
err = tmpl.Execute(&buffer, te.data)
|
|
|
|
if err != nil {
|
2014-12-10 15:16:49 +00:00
|
|
|
return "", fmt.Errorf("error executing template %v: %v", te.name, err)
|
2014-06-10 14:30:06 +00:00
|
|
|
}
|
|
|
|
return buffer.String(), nil
|
2014-05-28 17:44:54 +00:00
|
|
|
}
|