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 (
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"sync/atomic"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type closerfunc func() error
|
|
|
|
|
|
|
|
func (f closerfunc) Close() error { return f() }
|
|
|
|
|
2019-01-01 09:41:27 +00:00
|
|
|
// Deliver kicks off a goroutine that reads packets from source and delivers them
|
|
|
|
// to dest. To stop delivery, call Close on the return value then close the source.
|
|
|
|
func Deliver(source Source, dest PacketDest) io.Closer {
|
2018-12-11 18:24:31 +00:00
|
|
|
done := new(uint32)
|
2019-01-01 09:41:27 +00:00
|
|
|
|
2018-12-11 18:24:31 +00:00
|
|
|
go func() {
|
2019-01-01 09:41:27 +00:00
|
|
|
for atomic.LoadUint32(done) == 0 {
|
|
|
|
data, ts, err := source.Next()
|
2018-12-11 18:24:31 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("failed getting packet: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
2019-01-01 09:41:27 +00:00
|
|
|
err = dest.Packet(data, ts)
|
2018-12-11 18:24:31 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("failed delivering packet: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
2019-01-01 09:41:27 +00:00
|
|
|
|
2018-12-11 18:24:31 +00:00
|
|
|
return closerfunc(func() error {
|
|
|
|
atomic.StoreUint32(done, 1)
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Source reads incoming packets
|
|
|
|
type Source interface {
|
|
|
|
Next() (data []byte, ts time.Time, err error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// PacketDest handles packets
|
|
|
|
type PacketDest interface {
|
|
|
|
Packet(data []byte, ts time.Time) error
|
|
|
|
}
|
|
|
|
|
|
|
|
// MetricDest handles metrics
|
|
|
|
type MetricDest interface {
|
2019-01-01 09:41:27 +00:00
|
|
|
Metric(application, instance string, key []byte, val float64, ts time.Time) error
|
2018-12-11 18:24:31 +00:00
|
|
|
}
|