-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
124 lines (113 loc) · 2.49 KB
/
client.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package ninjato
import (
"errors"
"log"
"net"
"runtime"
"time"
"github.com/pierrec/lz4"
"github.com/ClickHouse-Ninja/ninjato/src/binary"
"github.com/ClickHouse-Ninja/ninjato/src/point"
)
type Client interface {
Push(*Point) error
}
const (
PayloadSize = 16 * 1024
BacklogSize = 10000
)
func NewClient(service string, config ClientConfig) (_ Client, err error) {
var (
backlog = BacklogSize
concurrency = runtime.NumCPU()
)
if config.BacklogSize > 0 {
backlog = config.BacklogSize
}
if config.Concurrency > 0 {
concurrency = config.Concurrency
}
client := client{
debug: config.Debug,
logger: log.Printf,
service: service,
backlog: make(chan *Point, backlog),
}
if client.address, err = net.ResolveUDPAddr("udp", config.Address); err != nil {
return nil, err
}
for i := 0; i < concurrency; i++ {
if err = client.background(i); err != nil {
return nil, err
}
}
return &client, nil
}
type client struct {
service string
address *net.UDPAddr
backlog chan *Point
debug bool
logger func(string, ...interface{})
}
var ErrBacklogIsFull = errors.New("backlog is full")
func (cl *client) Push(p *Point) error {
select {
case cl.backlog <- p:
return nil
default:
return ErrBacklogIsFull
}
}
func (cl *client) background(num int) error {
var (
flush = time.NewTicker(10 * time.Second)
compressed = &buffer{}
uncompressed = &buffer{}
encoder = binary.Encoder{Output: uncompressed}
compressor = lz4.NewWriter(compressed)
conn, err = net.DialUDP("udp", nil, cl.address)
)
if err != nil {
return err
}
go func() {
for {
var count uint16
encoder.String(cl.service)
collect:
for {
select {
case p := <-cl.backlog:
if err := point.Marshal(&encoder, p); err != nil {
break collect
}
if count++; uncompressed.len >= PayloadSize {
break collect
}
case <-flush.C:
break collect
}
}
if count > 0 {
if _, err := compressor.Write(uncompressed.bytes()); err != nil {
cl.logger("compressor %v", err)
}
if err := compressor.Flush(); err != nil {
cl.logger("LZ4 flush: %v", err)
}
if _, err := conn.Write(compressed.bytes()); err != nil {
cl.logger("conn write: %v", err)
}
if cl.debug {
cl.logger("goroutine=%d, count=%d, buffer=%d compressed=%d", num, count, uncompressed.len, compressed.len)
}
compressor.Reset(compressed)
uncompressed.reset()
}
compressed.reset()
}
}()
return nil
}
var _ Client = (*client)(nil)