-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathencoder.go
93 lines (76 loc) · 1.59 KB
/
encoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package sflow
import (
"encoding/binary"
"errors"
"io"
"net"
)
var (
ErrNoSamplesProvided = errors.New("sflow: no samples provided for encoding")
)
type Encoder struct {
ip net.IP
subAgentId uint32
sequenceNum uint32
Uptime uint32
}
// NewEncoder returns a new sFlow encoder.
func NewEncoder(source net.IP, subAgentId uint32, initialSequenceNumber uint32) *Encoder {
return &Encoder{
ip: source,
subAgentId: subAgentId,
sequenceNum: initialSequenceNumber,
}
}
// Encode encodes an sFlow v5 datagram with the given samples and
// writes the packet to w.
func (e *Encoder) Encode(w io.Writer, samples []Sample) error {
if len(samples) == 0 {
return ErrNoSamplesProvided
}
var err error
// sFlow v5
err = binary.Write(w, binary.BigEndian, uint32(5))
if err != nil {
return err
}
// Check IP version
ipVersion := uint32(1)
ipBytes := []byte(e.ip.To4())
if ipBytes == nil {
ipVersion = 2
ipBytes = []byte(e.ip.To16())
}
err = binary.Write(w, binary.BigEndian, ipVersion)
if err != nil {
return err
}
_, err = w.Write(ipBytes)
if err != nil {
return err
}
err = binary.Write(w, binary.BigEndian, e.subAgentId)
if err != nil {
return err
}
err = binary.Write(w, binary.BigEndian, e.sequenceNum)
if err != nil {
return err
}
err = binary.Write(w, binary.BigEndian, e.Uptime)
if err != nil {
return err
}
err = binary.Write(w, binary.BigEndian, uint32(len(samples)))
if err != nil {
return err
}
for _, sample := range samples {
err = sample.encode(w)
if err != nil {
return err
}
}
e.sequenceNum++
return nil
}