storj/cmd/statreceiver/udp.go
JT Olio 362f447d9f
cmd/statreceiver: lua-scriptable stat receiver (#636)
* cmd/statreceiver: lua-scriptable stat receiver

Change-Id: I3ce0fe3f1ef4b1f4f27eed90bac0e91cfecf22d7

* some updates

Change-Id: I7c3485adcda1278fce01ae077b4761b3ddb9fb7a

* more comments

Change-Id: I0bb22993cd934c3d40fc1da80d07e49e686b80dd

* linter fixes

Change-Id: Ied014304ecb9aadcf00a6b66ad28f856a428d150

* catch errors

Change-Id: I6e1920f1fd941e66199b30bc427285c19769fc70

* review feedback

Change-Id: I9d4051851eab18970c5f5ddcf4ff265508e541d3

* errorgroup improvements

Change-Id: I4699dda3022f0485fbb50c9dafe692d3921734ff

* too tricky

the previous thing was better for memory with lots of errors at a time
but https://play.golang.org/p/RweTMRjoSCt is too much of a foot gun

Change-Id: I23f0b3d77dd4288fcc20b3756a7110359576bf44
2018-12-11 11:24:31 -07:00

113 lines
2.2 KiB
Go

// Copyright (C) 2018 Storj Labs, Inc.
// See LICENSE for copying information.
package main
import (
"fmt"
"net"
"sync"
"time"
)
// UDPSource is a packet source
type UDPSource struct {
mtx sync.Mutex
address string
conn *net.UDPConn
buf [1024 * 10]byte
closed bool
}
// NewUDPSource creates a UDPSource that listens on address
func NewUDPSource(address string) *UDPSource {
return &UDPSource{address: address}
}
// Next implements the Source interface
func (s *UDPSource) Next() ([]byte, time.Time, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.closed {
return nil, time.Time{}, fmt.Errorf("udp source closed")
}
if s.conn == nil {
addr, err := net.ResolveUDPAddr("udp", s.address)
if err != nil {
return nil, time.Time{}, err
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return nil, time.Time{}, err
}
s.conn = conn
}
n, _, err := s.conn.ReadFrom(s.buf[:])
if err != nil {
return nil, time.Time{}, err
}
return s.buf[:n], time.Now(), nil
}
// Close closes the source
func (s *UDPSource) Close() error {
s.mtx.Lock()
defer s.mtx.Unlock()
s.closed = true
if s.conn != nil {
return s.conn.Close()
}
return nil
}
// UDPDest is a packet destination. IMPORTANT: It throws away timestamps.
type UDPDest struct {
mtx sync.Mutex
address string
addr *net.UDPAddr
conn *net.UDPConn
closed bool
}
// NewUDPDest creates a UDPDest that sends incoming packets to address.
func NewUDPDest(address string) *UDPDest {
return &UDPDest{address: address}
}
// Packet implements PacketDest
func (d *UDPDest) Packet(data []byte, ts time.Time) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.closed {
return fmt.Errorf("closed destination")
}
if d.conn == nil {
addr, err := net.ResolveUDPAddr("udp", d.address)
if err != nil {
return err
}
conn, err := net.ListenUDP("udp", &net.UDPAddr{Port: 0})
if err != nil {
return err
}
d.addr = addr
d.conn = conn
}
_, err := d.conn.WriteTo(data, d.addr)
return err
}
// Close closes the destination
func (d *UDPDest) Close() error {
d.mtx.Lock()
defer d.mtx.Unlock()
d.closed = true
if d.conn != nil {
return d.conn.Close()
}
return nil
}