2019-01-24 20:15:10 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
2018-12-11 18:24:31 +00:00
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/zeebo/admission/admproto"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
kb = 1024
|
|
|
|
)
|
|
|
|
|
|
|
|
// Parser is a PacketDest that sends data to a MetricDest
|
|
|
|
type Parser struct {
|
2019-01-01 09:41:27 +00:00
|
|
|
dest MetricDest
|
|
|
|
filters []*PacketFilter
|
2018-12-11 18:24:31 +00:00
|
|
|
scratch sync.Pool
|
|
|
|
}
|
|
|
|
|
2019-01-01 09:41:27 +00:00
|
|
|
// NewParser creates a Parser. It sends metrics to dest, provided they pass all
|
2018-12-11 18:24:31 +00:00
|
|
|
// of the provided PacketFilters
|
2019-01-01 09:41:27 +00:00
|
|
|
func NewParser(dest MetricDest, filters ...*PacketFilter) *Parser {
|
2018-12-11 18:24:31 +00:00
|
|
|
return &Parser{
|
2019-01-01 09:41:27 +00:00
|
|
|
dest: dest,
|
|
|
|
filters: filters,
|
2018-12-11 18:24:31 +00:00
|
|
|
scratch: sync.Pool{
|
|
|
|
New: func() interface{} {
|
|
|
|
var x [10 * kb]byte
|
|
|
|
return &x
|
|
|
|
},
|
2019-01-01 09:41:27 +00:00
|
|
|
},
|
|
|
|
}
|
2018-12-11 18:24:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Packet implements PacketDest
|
|
|
|
func (p *Parser) Packet(data []byte, ts time.Time) (err error) {
|
|
|
|
data, err = admproto.CheckChecksum(data)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-01-01 09:41:27 +00:00
|
|
|
|
2018-12-11 18:24:31 +00:00
|
|
|
scratch := p.scratch.Get().(*[10 * kb]byte)
|
|
|
|
defer p.scratch.Put(scratch)
|
2019-01-01 09:41:27 +00:00
|
|
|
|
2018-12-11 18:24:31 +00:00
|
|
|
r := admproto.NewReaderWith((*scratch)[:])
|
|
|
|
data, appb, instb, err := r.Begin(data)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-01-01 09:41:27 +00:00
|
|
|
|
2018-12-11 18:24:31 +00:00
|
|
|
app, inst := string(appb), string(instb)
|
2019-01-01 09:41:27 +00:00
|
|
|
for _, filter := range p.filters {
|
|
|
|
if !filter.Filter(app, inst) {
|
2018-12-11 18:24:31 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2019-01-01 09:41:27 +00:00
|
|
|
|
2018-12-11 18:24:31 +00:00
|
|
|
var key []byte
|
|
|
|
var value float64
|
|
|
|
for len(data) > 0 {
|
|
|
|
data, key, value, err = r.Next(data)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-01-01 09:41:27 +00:00
|
|
|
err = p.dest.Metric(app, inst, key, value, ts)
|
2018-12-11 18:24:31 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("failed to write metric: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
2019-01-01 09:41:27 +00:00
|
|
|
|
2018-12-11 18:24:31 +00:00
|
|
|
return nil
|
|
|
|
}
|