2020-03-10 22:39:06 +00:00
|
|
|
package geo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2020-03-18 19:28:02 +00:00
|
|
|
|
2020-03-10 22:39:06 +00:00
|
|
|
"github.com/golang/geo/s2"
|
|
|
|
"github.com/influxdata/telegraf"
|
|
|
|
"github.com/influxdata/telegraf/plugins/processors"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Geo struct {
|
|
|
|
LatField string `toml:"lat_field"`
|
|
|
|
LonField string `toml:"lon_field"`
|
|
|
|
TagKey string `toml:"tag_key"`
|
|
|
|
CellLevel int `toml:"cell_level"`
|
|
|
|
}
|
|
|
|
|
|
|
|
var SampleConfig = `
|
2020-03-18 19:28:02 +00:00
|
|
|
## The name of the lat and lon fields containing WGS-84 latitude and
|
|
|
|
## longitude in decimal degrees.
|
|
|
|
# lat_field = "lat"
|
|
|
|
# lon_field = "lon"
|
2020-03-10 22:39:06 +00:00
|
|
|
|
|
|
|
## New tag to create
|
2020-03-18 19:28:02 +00:00
|
|
|
# tag_key = "s2_cell_id"
|
2020-03-10 22:39:06 +00:00
|
|
|
|
|
|
|
## Cell level (see https://s2geometry.io/resources/s2cell_statistics.html)
|
2020-03-18 19:28:02 +00:00
|
|
|
# cell_level = 9
|
2020-03-10 22:39:06 +00:00
|
|
|
`
|
|
|
|
|
|
|
|
func (g *Geo) SampleConfig() string {
|
|
|
|
return SampleConfig
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Geo) Description() string {
|
2020-03-18 19:28:02 +00:00
|
|
|
return "Add the S2 Cell ID as a tag based on latitude and longitude fields"
|
2020-03-10 22:39:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Geo) Init() error {
|
|
|
|
if g.CellLevel < 0 || g.CellLevel > 30 {
|
|
|
|
return fmt.Errorf("invalid cell level %d", g.CellLevel)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Geo) Apply(in ...telegraf.Metric) []telegraf.Metric {
|
|
|
|
for _, point := range in {
|
|
|
|
var latOk, lonOk bool
|
|
|
|
var lat, lon float64
|
|
|
|
for _, field := range point.FieldList() {
|
|
|
|
switch field.Key {
|
|
|
|
case g.LatField:
|
|
|
|
lat, latOk = field.Value.(float64)
|
|
|
|
case g.LonField:
|
|
|
|
lon, lonOk = field.Value.(float64)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if latOk && lonOk {
|
|
|
|
cellID := s2.CellIDFromLatLng(s2.LatLngFromDegrees(lat, lon))
|
|
|
|
if cellID.IsValid() {
|
|
|
|
value := cellID.Parent(g.CellLevel).ToToken()
|
|
|
|
point.AddTag(g.TagKey, value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return in
|
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
processors.Add("s2geo", func() telegraf.Processor {
|
|
|
|
return &Geo{
|
|
|
|
LatField: "lat",
|
|
|
|
LonField: "lon",
|
|
|
|
TagKey: "s2_cell_id",
|
|
|
|
CellLevel: 9,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|