VictoriaMetrics/lib/logstorage/stats_sum.go

111 lines
2.2 KiB
Go
Raw Normal View History

package logstorage
import (
"math"
"strconv"
"unsafe"
)
type statsSum struct {
2024-05-22 19:01:20 +00:00
fields []string
}
func (ss *statsSum) String() string {
2024-05-22 19:01:20 +00:00
return "sum(" + statsFuncFieldsToString(ss.fields) + ")"
}
2024-05-20 02:08:30 +00:00
func (ss *statsSum) updateNeededFields(neededFields fieldsSet) {
2024-05-22 19:01:20 +00:00
updateNeededFieldsForStatsFunc(neededFields, ss.fields)
}
func (ss *statsSum) newStatsProcessor() (statsProcessor, int) {
ssp := &statsSumProcessor{
ss: ss,
sum: nan,
}
return ssp, int(unsafe.Sizeof(*ssp))
}
type statsSumProcessor struct {
ss *statsSum
sum float64
}
func (ssp *statsSumProcessor) updateStatsForAllRows(br *blockResult) int {
2024-05-22 19:01:20 +00:00
fields := ssp.ss.fields
if len(fields) == 0 {
// Sum all the columns
for _, c := range br.getColumns() {
2024-05-20 02:08:30 +00:00
ssp.updateStateForColumn(br, c)
}
} else {
// Sum the requested columns
2024-05-22 19:01:20 +00:00
for _, field := range fields {
c := br.getColumnByName(field)
2024-05-20 02:08:30 +00:00
ssp.updateStateForColumn(br, c)
}
}
return 0
}
func (ssp *statsSumProcessor) updateStatsForRow(br *blockResult, rowIdx int) int {
2024-05-22 19:01:20 +00:00
fields := ssp.ss.fields
if len(fields) == 0 {
// Sum all the fields for the given row
for _, c := range br.getColumns() {
2024-05-20 02:08:30 +00:00
f, ok := c.getFloatValueAtRow(br, rowIdx)
if ok {
ssp.updateState(f)
}
}
} else {
// Sum only the given fields for the given row
2024-05-22 19:01:20 +00:00
for _, field := range fields {
c := br.getColumnByName(field)
2024-05-20 02:08:30 +00:00
f, ok := c.getFloatValueAtRow(br, rowIdx)
if ok {
ssp.updateState(f)
}
}
}
return 0
}
2024-05-20 02:08:30 +00:00
func (ssp *statsSumProcessor) updateStateForColumn(br *blockResult, c *blockResultColumn) {
f, count := c.sumValues(br)
if count > 0 {
ssp.updateState(f)
}
}
func (ssp *statsSumProcessor) updateState(f float64) {
if math.IsNaN(ssp.sum) {
ssp.sum = f
} else {
ssp.sum += f
}
}
func (ssp *statsSumProcessor) mergeState(sfp statsProcessor) {
src := sfp.(*statsSumProcessor)
2024-05-22 19:01:20 +00:00
if !math.IsNaN(src.sum) {
ssp.updateState(src.sum)
}
}
func (ssp *statsSumProcessor) finalizeStats() string {
return strconv.FormatFloat(ssp.sum, 'f', -1, 64)
}
func parseStatsSum(lex *lexer) (*statsSum, error) {
2024-05-22 19:01:20 +00:00
fields, err := parseStatsFuncFields(lex, "sum")
if err != nil {
return nil, err
}
ss := &statsSum{
2024-05-22 19:01:20 +00:00
fields: fields,
}
return ss, nil
}