Exemple #1
0
// NewAggregate takes a named aggregating function `[float64] => float64` and makes it into a MetricFunction.
func NewAggregate(name string, aggregator func([]float64) float64) function.MetricFunction {
	return function.MetricFunction{
		Name:          name,
		MinArguments:  1,
		MaxArguments:  1,
		AllowsGroupBy: true,
		Compute: func(context *function.EvaluationContext, args []function.Expression, groups function.Groups) (function.Value, error) {
			argument := args[0]
			value, err := argument.Evaluate(context)
			if err != nil {
				return nil, err
			}
			seriesList, err := value.ToSeriesList(context.Timerange)
			if err != nil {
				return nil, err
			}
			result := aggregate.AggregateBy(seriesList, aggregator, groups.List, groups.Collapses)
			groupNames := make([]string, len(groups.List))
			for i, group := range groups.List {
				groupNames[i] += group
			}
			if len(groups.List) == 0 {
				result.Query = fmt.Sprintf("%s(%s)", name, value.GetName())
			} else {
				verbName := "group"
				if groups.Collapses {
					verbName = "collapse"
				}
				result.Query = fmt.Sprintf("%s(%s %s by %s)", name, value.GetName(), verbName, strings.Join(groupNames, ", "))
			}
			result.Name = result.Query
			return result, nil
		},
	}
}
Exemple #2
0
// NewAggregate takes a named aggregating function `[float64] => float64` and makes it into a MetricFunction.
func NewAggregate(name string, aggregator func([]float64) float64) function.MetricFunction {
	return function.MetricFunction{
		Name:          name,
		MinArguments:  1,
		MaxArguments:  1,
		AllowsGroupBy: true,
		Compute: func(context function.EvaluationContext, args []function.Expression, groups []string) (function.Value, error) {
			argument := args[0]
			value, err := argument.Evaluate(context)
			if err != nil {
				return nil, err
			}
			seriesList, err := value.ToSeriesList(context.Timerange)
			if err != nil {
				return nil, err
			}
			result := aggregate.AggregateBy(seriesList, aggregator, groups)
			groupNames := make([]string, len(groups))
			for i, group := range groups {
				groupNames[i] += group
			}
			if len(groups) == 0 {
				result.Name = fmt.Sprintf("%s(%s)", name, value.GetName())
			} else {
				result.Name = fmt.Sprintf("%s(%s group by %s)", name, value.GetName(), strings.Join(groupNames, ", "))
			}
			return function.SeriesListValue(result), nil
		},
	}
}