-
Notifications
You must be signed in to change notification settings - Fork 6
/
batchInserter.go
251 lines (231 loc) · 7.52 KB
/
batchInserter.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/**
* Copyright 2019 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// package batchInserter provides a wrapper around the db.Inserter to provide a
// way to group records together before inserting, in order to decrease
// database requests needed for inserting.
package batchInserter
import (
"errors"
"sync"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/metrics/provider"
"github.com/goph/emperror"
db "github.com/xmidt-org/codex-db"
"github.com/xmidt-org/webpa-common/logging"
"github.com/xmidt-org/webpa-common/semaphore"
)
const (
minParseWorkers = 1
minInsertWorkers = 1
defaultInsertWorkers = 5
minMaxBatchSize = 0
defaultMaxBatchSize = 1
minMaxBatchWaitTime = time.Duration(1) * time.Millisecond
defaultMinQueueSize = 5
)
var (
defaultLogger = log.NewNopLogger()
)
var (
ErrBadBeginning = errors.New("invalid value for the beginning time of the record")
ErrBadData = errors.New("data nil or empty")
)
// defaultTicker is the production code that produces a ticker. Note that we don't
// want to return *time.Ticker, as we want to be able to inject something for testing.
// We also need to return a closure to stop the ticker, so that we can call ticker.Stop() without
// being dependent on the *time.Ticker interface.
func defaultTicker(d time.Duration) (<-chan time.Time, func()) {
ticker := time.NewTicker(d)
return ticker.C, ticker.Stop
}
type TimeTracker interface {
TrackTime(time.Duration)
}
// BatchInserter manages batching events that need to be inserted, ensuring
// that an event that needs to be inserted isn't waiting for longer than a set
// period of time and that each batch doesn't pass a specified size.
type BatchInserter struct {
numBatchers int
insertQueue chan RecordWithTime
inserter db.Inserter
timeTracker TimeTracker
insertWorkers semaphore.Interface
wg sync.WaitGroup
measures *Measures
logger log.Logger
config Config
ticker func(time.Duration) (<-chan time.Time, func())
}
// Config holds the configuration values for a batch inserter.
type Config struct {
ParseWorkers int
MaxInsertWorkers int
MaxBatchSize int
MaxBatchWaitTime time.Duration
QueueSize int
}
// RecordWithTime provides the db record and the time this event was received by a service
type RecordWithTime struct {
Record db.Record
Beginning time.Time
}
// NewBatchInserter creates a BatchInserter with the given values, ensuring
// that the configuration and other values given are valid. If configuration
// values aren't valid, a default value is used.
func NewBatchInserter(config Config, logger log.Logger, metricsRegistry provider.Provider, inserter db.Inserter, timeTracker TimeTracker) (*BatchInserter, error) {
if inserter == nil {
return nil, errors.New("no inserter")
}
if config.ParseWorkers < minParseWorkers {
config.ParseWorkers = minParseWorkers
}
if config.MaxInsertWorkers < minInsertWorkers {
config.MaxInsertWorkers = defaultInsertWorkers
}
if config.MaxBatchSize < minMaxBatchSize {
config.MaxBatchSize = defaultMaxBatchSize
}
if config.MaxBatchWaitTime < minMaxBatchWaitTime {
config.MaxBatchWaitTime = minMaxBatchWaitTime
}
if config.QueueSize < defaultMinQueueSize {
config.QueueSize = defaultMinQueueSize
}
if logger == nil {
logger = defaultLogger
}
measures := NewMeasures(metricsRegistry)
workers := semaphore.New(config.MaxInsertWorkers)
queue := make(chan RecordWithTime, config.QueueSize)
b := BatchInserter{
config: config,
logger: logger,
measures: measures,
numBatchers: config.ParseWorkers,
insertWorkers: workers,
inserter: inserter,
insertQueue: queue,
ticker: defaultTicker,
timeTracker: timeTracker,
}
return &b, nil
}
// Start starts the batcher, which pulls from the queue inside of the BatchInserter.
func (b *BatchInserter) Start() {
for i := 0; i < b.numBatchers; i++ {
b.wg.Add(1)
go b.batchRecords()
}
}
// Insert adds the event to the queue inside of BatchInserter, preparing for it
// to be inserted. This can block, if the queue is full. If the record has
// certain fields empty, an error is returned.
func (b *BatchInserter) Insert(rwt RecordWithTime) error {
if b.timeTracker != nil && rwt.Beginning.IsZero() {
return ErrBadBeginning
}
if rwt.Record.Data == nil || len(rwt.Record.Data) == 0 {
return ErrBadData
}
b.insertQueue <- rwt
if b.measures != nil {
b.measures.InsertingQueue.Add(1.0)
}
return nil
}
// Stop closes the internal queue and waits for the workers to finish
// processing what has already been added. This can block as it waits for
// everything to stop. After Stop() is called, Insert() should not be called
// again, or there will be a panic.
// TODO: ensure consumers can't cause a panic?
func (b *BatchInserter) Stop() {
close(b.insertQueue)
b.wg.Wait()
// Grab all the workers to make sure they are done.
for i := 0; i < b.config.MaxInsertWorkers; i++ {
b.insertWorkers.Acquire()
}
}
func (b *BatchInserter) batchRecords() {
var (
insertRecords bool
ticker <-chan time.Time
stop func()
)
defer b.wg.Done()
for rwt := range b.insertQueue {
if b.measures != nil {
b.measures.InsertingQueue.Add(-1.0)
}
ticker, stop = b.ticker(b.config.MaxBatchWaitTime)
records := []db.Record{rwt.Record}
beginTimes := []time.Time{rwt.Beginning}
for {
select {
case <-ticker:
insertRecords = true
case r, ok := <-b.insertQueue:
// if ok is false, the queue is closed.
if !ok {
insertRecords = true
break
}
if b.measures != nil {
b.measures.InsertingQueue.Add(-1.0)
}
records = append(records, r.Record)
beginTimes = append(beginTimes, r.Beginning)
if b.config.MaxBatchSize != 0 && len(records) >= b.config.MaxBatchSize {
insertRecords = true
break
}
}
if insertRecords {
b.insertWorkers.Acquire()
go b.insertRecords(records, beginTimes)
insertRecords = false
break
}
}
stop()
}
}
func (b *BatchInserter) insertRecords(records []db.Record, beginTimes []time.Time) {
defer b.insertWorkers.Release()
err := b.inserter.InsertRecords(records...)
if err != nil {
if b.measures != nil {
b.measures.DroppedEventsFromDbFailCount.Add(float64(len(records)))
}
logging.Error(b.logger, emperror.Context(err)...).Log(logging.MessageKey(),
"Failed to add records to the database", logging.ErrorKey(), err.Error())
b.sendTimes(beginTimes, time.Now())
return
}
b.sendTimes(beginTimes, time.Now())
logging.Debug(b.logger).Log(logging.MessageKey(), "Successfully upserted device information", "records", records)
logging.Info(b.logger).Log(logging.MessageKey(), "Successfully upserted device information", "records", len(records))
}
func (b *BatchInserter) sendTimes(beginTimes []time.Time, endTime time.Time) {
if b.timeTracker != nil {
for _, beginTime := range beginTimes {
b.timeTracker.TrackTime(endTime.Sub(beginTime))
}
logging.Debug(b.logger).Log(logging.MessageKey(), "Successfully tracked time taken to insert records")
}
}