This repository has been archived by the owner on Nov 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathkinesis.go
193 lines (167 loc) · 4.44 KB
/
kinesis.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kinesis"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/prometheus/prometheus/prompb"
"go.uber.org/zap"
)
const MaxNumberOfBuffer = 1000
const MaxPutRecordsSize = 4500000 // 5MB
const MaxPutRecordsEntries = 500
const DefaultAWSRegion = "ap-northeast-1"
type Config struct {
streamName string
writeInterval time.Duration
AWSRegion string
}
type kinesisWriter struct {
svc *kinesis.Kinesis
writeInterval time.Duration
streamName string
writeCh chan Records
mutex sync.Mutex
}
func newWriter(config Config) *kinesisWriter {
awsConfig := aws.NewConfig()
if config.AWSRegion != "" {
awsConfig = awsConfig.WithRegion(config.AWSRegion)
} else {
awsConfig = awsConfig.WithRegion(DefaultAWSRegion)
}
if os.Getenv("AWS_ACCESS_KEY_ID") != "" && os.Getenv("AWS_SECRET_ACCESS_KEY") != "" {
cred := credentials.NewEnvCredentials()
awsConfig = awsConfig.WithCredentials(cred)
}
svc := session.Must(session.NewSessionWithOptions(session.Options{
Config: *awsConfig,
}))
w := kinesisWriter{
streamName: config.streamName,
svc: kinesis.New(svc),
writeInterval: config.writeInterval,
writeCh: make(chan Records, MaxNumberOfBuffer),
}
go w.run()
return &w
}
func (writer *kinesisWriter) receive(w http.ResponseWriter, r *http.Request) {
compressed, err := ioutil.ReadAll(r.Body)
if err != nil {
logger.Error("read failed", zap.NamedError("error", err))
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
reqBuf, err := snappy.Decode(nil, compressed)
if err != nil {
logger.Error("decode failed", zap.NamedError("error", err))
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var req prompb.WriteRequest
if err := proto.Unmarshal(reqBuf, &req); err != nil {
logger.Error("unmarshal failed", zap.NamedError("error", err))
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
records := parseRecords(req.Timeseries)
writer.writeCh <- records
}
func (w *kinesisWriter) close() {
close(w.writeCh)
}
func (w *kinesisWriter) run() {
rs := make([]*kinesis.PutRecordsRequestEntry, 0, MaxPutRecordsEntries)
var bytes int
ticker := time.NewTicker(w.writeInterval)
for {
select {
case <-ticker.C:
w.mutex.Lock()
if err := w.send(rs, w.svc); err != nil {
logger.Error("send failed", zap.NamedError("error", err))
}
bytes = 0
rs = make([]*kinesis.PutRecordsRequestEntry, 0, MaxPutRecordsEntries)
w.mutex.Unlock()
case records, ok := <-w.writeCh:
if !ok {
logger.Warn("write channel closed. send current buffer")
if err := w.send(rs, w.svc); err != nil {
logger.Error("send failed", zap.NamedError("error", err))
}
return
}
tmp, l := w.write(records)
w.mutex.Lock()
if len(rs) == 0 {
bytes += l
rs = append(rs, tmp...)
w.mutex.Unlock()
continue
}
if bytes+l > MaxPutRecordsSize ||
len(rs)+len(tmp) > MaxPutRecordsEntries {
logger.Debug("send",
zap.Int("bytes", bytes),
zap.Int("entries", len(rs)),
)
if err := w.send(rs, w.svc); err != nil {
logger.Error("send failed", zap.NamedError("error", err))
}
bytes = 0
rs = make([]*kinesis.PutRecordsRequestEntry, 0, MaxPutRecordsEntries)
}
bytes += l
rs = append(rs, tmp...)
w.mutex.Unlock()
}
}
}
func (w *kinesisWriter) write(records Records) ([]*kinesis.PutRecordsRequestEntry, int) {
rs := make([]*kinesis.PutRecordsRequestEntry, len(records))
var l int
for i, record := range records {
// to json
j, err := json.Marshal(record)
if err != nil {
logger.Error("marshal error", zap.NamedError("error", err))
continue
}
j = append(j, newLine)
// compress to gzip
/*
var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write(append(j, newLine))
w.Close()
*/
rs[i] = &kinesis.PutRecordsRequestEntry{
Data: j,
PartitionKey: aws.String(record.Name),
}
// l += b.Len()
l += len(j)
}
return rs, l
}
func (w *kinesisWriter) send(entries []*kinesis.PutRecordsRequestEntry, svc *kinesis.Kinesis) error {
if len(entries) == 0 {
return nil
}
input := &kinesis.PutRecordsInput{
Records: entries,
StreamName: aws.String(w.streamName),
}
_, err := w.svc.PutRecords(input)
return err
}