-
Notifications
You must be signed in to change notification settings - Fork 110
/
collector.go
293 lines (262 loc) · 8.13 KB
/
collector.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Package data contains the code involved with Viam's Data Management Platform for automatically collecting component
// readings from robots.
package data
import (
"context"
"fmt"
"sync"
"time"
"github.com/edaniels/golog"
"github.com/pkg/errors"
"go.opencensus.io/trace"
v1 "go.viam.com/api/app/datasync/v1"
"go.viam.com/utils"
"go.viam.com/utils/protoutils"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/timestamppb"
"go.viam.com/rdk/resource"
"go.viam.com/rdk/services/datamanager/datacapture"
)
// The cutoff at which if interval < cutoff, a sleep based capture func is used instead of a ticker.
var sleepCaptureCutoff = 2 * time.Millisecond
// Capturer provides a function for capturing a single protobuf reading from the underlying component.
type Capturer interface {
Capture(ctx context.Context, params map[string]*anypb.Any) (interface{}, error)
}
// CaptureFunc allows the creation of simple Capturers with anonymous functions.
type CaptureFunc func(ctx context.Context, params map[string]*anypb.Any) (interface{}, error)
// Capture allows any CaptureFunc to conform to the Capturer interface.
func (cf CaptureFunc) Capture(ctx context.Context, params map[string]*anypb.Any) (interface{}, error) {
return cf(ctx, params)
}
// Collector collects data to some target.
type Collector interface {
SetTarget(file *datacapture.File)
GetTarget() *datacapture.File
Close()
Collect()
}
type collector struct {
queue chan *v1.SensorData
interval time.Duration
params map[string]*anypb.Any
lock *sync.Mutex
logger golog.Logger
target *datacapture.File
backgroundWorkers sync.WaitGroup
cancelCtx context.Context
cancel context.CancelFunc
capturer Capturer
closed bool
}
// SetTarget updates the file being written to by the collector.
func (c *collector) SetTarget(file *datacapture.File) {
c.lock.Lock()
defer c.lock.Unlock()
if err := c.target.Sync(); err != nil {
c.logger.Errorw("failed to flush file to disk", "error", err)
}
c.target = file
}
// GetTarget returns the file being written to by the collector.
func (c *collector) GetTarget() *datacapture.File {
c.lock.Lock()
defer c.lock.Unlock()
return c.target
}
// Close closes the channels backing the Collector. It should always be called before disposing of a Collector to avoid
// leaking goroutines.
func (c *collector) Close() {
if c.closed {
return
}
c.cancel()
c.backgroundWorkers.Wait()
c.lock.Lock()
defer c.lock.Unlock()
if err := c.target.Sync(); err != nil {
c.logger.Errorw("failed to flush target to disk", "error", err)
}
c.closed = true
}
// Collect starts the Collector, causing it to run c.capturer.Capture every c.interval, and write the results to
// c.target.
func (c *collector) Collect() {
_, span := trace.StartSpan(c.cancelCtx, "data::collector::Collect")
defer span.End()
c.backgroundWorkers.Add(1)
utils.PanicCapturingGo(func() {
defer c.backgroundWorkers.Done()
c.capture()
})
c.backgroundWorkers.Add(1)
utils.PanicCapturingGo(func() {
defer c.backgroundWorkers.Done()
if err := c.write(); err != nil {
c.logger.Errorw(fmt.Sprintf("failed to write to file %s", c.target.GetPath()), "error", err)
}
})
c.closed = false
}
// Go's time.Ticker has inconsistent performance with durations of below 1ms [0], so we use a time.Sleep based approach
// when the configured capture interval is below 2ms. A Ticker based approach is kept for longer capture intervals to
// avoid wasting CPU on a thread that's idling for the vast majority of the time.
// [0]: https://www.mail-archive.com/golang-nuts@googlegroups.com/msg46002.html
func (c *collector) capture() {
if c.interval < sleepCaptureCutoff {
c.sleepBasedCapture()
} else {
c.tickerBasedCapture()
}
}
func (c *collector) sleepBasedCapture() {
next := time.Now().Add(c.interval)
captureWorkers := sync.WaitGroup{}
for {
time.Sleep(time.Until(next))
if err := c.cancelCtx.Err(); err != nil {
if !errors.Is(err, context.Canceled) {
c.logger.Errorw("unexpected error in collector context", "error", err)
}
captureWorkers.Wait()
close(c.queue)
return
}
select {
case <-c.cancelCtx.Done():
captureWorkers.Wait()
close(c.queue)
return
default:
captureWorkers.Add(1)
utils.PanicCapturingGo(func() {
defer captureWorkers.Done()
c.getAndPushNextReading()
})
}
next = next.Add(c.interval)
}
}
func (c *collector) tickerBasedCapture() {
ticker := time.NewTicker(c.interval)
defer ticker.Stop()
captureWorkers := sync.WaitGroup{}
for {
if err := c.cancelCtx.Err(); err != nil {
if !errors.Is(err, context.Canceled) {
c.logger.Errorw("unexpected error in collector context", "error", err)
}
captureWorkers.Wait()
close(c.queue)
return
}
select {
case <-c.cancelCtx.Done():
captureWorkers.Wait()
close(c.queue)
return
case <-ticker.C:
captureWorkers.Add(1)
utils.PanicCapturingGo(func() {
defer captureWorkers.Done()
c.getAndPushNextReading()
})
}
}
}
func (c *collector) getAndPushNextReading() {
timeRequested := timestamppb.New(time.Now().UTC())
reading, err := c.capturer.Capture(c.cancelCtx, c.params)
timeReceived := timestamppb.New(time.Now().UTC())
if err != nil {
if errors.Is(err, context.Canceled) {
c.logger.Debugw("error while capturing data", "error", err)
return
}
c.logger.Errorw("error while capturing data", "error", err)
return
}
var msg v1.SensorData
switch v := reading.(type) {
case []byte:
msg = v1.SensorData{
Metadata: &v1.SensorMetadata{
TimeRequested: timeRequested,
TimeReceived: timeReceived,
},
Data: &v1.SensorData_Binary{
Binary: v,
},
}
default:
// If it's not bytes, it's a struct.
pbReading, err := protoutils.StructToStructPb(reading)
if err != nil {
c.logger.Errorw("error while converting reading to structpb.Struct", "error", err)
return
}
msg = v1.SensorData{
Metadata: &v1.SensorMetadata{
TimeRequested: timeRequested,
TimeReceived: timeReceived,
},
Data: &v1.SensorData_Struct{
Struct: pbReading,
},
}
}
select {
// If c.queue is full, c.queue <- a can block indefinitely. This additional select block allows cancel to
// still work when this happens.
case <-c.cancelCtx.Done():
return
case c.queue <- &msg:
return
}
}
// NewCollector returns a new Collector with the passed capturer and configuration options. It calls capturer at the
// specified Interval, and appends the resulting reading to target.
func NewCollector(capturer Capturer, params CollectorParams) (Collector, error) {
if err := params.Validate(); err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to construct collector for %s", params.ComponentName))
}
cancelCtx, cancelFunc := context.WithCancel(context.Background())
return &collector{
queue: make(chan *v1.SensorData, params.QueueSize),
interval: params.Interval,
params: params.MethodParams,
lock: &sync.Mutex{},
logger: params.Logger,
target: params.Target,
cancelCtx: cancelCtx,
cancel: cancelFunc,
backgroundWorkers: sync.WaitGroup{},
capturer: capturer,
closed: false,
}, nil
}
func (c *collector) write() error {
for msg := range c.queue {
if err := c.appendMessage(msg); err != nil {
return err
}
}
return nil
}
func (c *collector) appendMessage(msg *v1.SensorData) error {
c.lock.Lock()
defer c.lock.Unlock()
if err := c.target.WriteNext(msg); err != nil {
return err
}
return nil
}
// InvalidInterfaceErr is the error describing when an interface not conforming to the expected resource.Subtype was
// passed into a CollectorConstructor.
func InvalidInterfaceErr(typeName resource.SubtypeName) error {
return errors.Errorf("passed interface does not conform to expected resource type %s", typeName)
}
// FailedToReadErr is the error describing when a Capturer was unable to get the reading of a method.
func FailedToReadErr(component, method string, err error) error {
return errors.Errorf("failed to get reading of method %s of component %s: %v", method, component, err)
}