-
Notifications
You must be signed in to change notification settings - Fork 110
/
builtin.go
697 lines (621 loc) · 23.3 KB
/
builtin.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
// Package builtin contains a service type that can be used to capture data from a robot's components.
package builtin
import (
"context"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"time"
"github.com/edaniels/golog"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
goutils "go.viam.com/utils"
"go.viam.com/rdk/config"
"go.viam.com/rdk/data"
"go.viam.com/rdk/protoutils"
"go.viam.com/rdk/registry"
"go.viam.com/rdk/resource"
"go.viam.com/rdk/robot"
"go.viam.com/rdk/services/datamanager"
"go.viam.com/rdk/services/datamanager/datacapture"
"go.viam.com/rdk/services/datamanager/datasync"
"go.viam.com/rdk/services/datamanager/model"
"go.viam.com/rdk/utils"
)
func init() {
registry.RegisterService(datamanager.Subtype, resource.DefaultModelName, registry.Service{
Constructor: func(ctx context.Context, r robot.Robot, c config.Service, logger golog.Logger) (interface{}, error) {
return NewBuiltIn(ctx, r, c, logger)
},
})
cType := config.ServiceType(datamanager.SubtypeName)
config.RegisterServiceAttributeMapConverter(cType, func(attributes config.AttributeMap) (interface{}, error) {
var conf Config
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{TagName: "json", Result: &conf})
if err != nil {
return nil, err
}
if err := decoder.Decode(attributes); err != nil {
return nil, err
}
return &conf, nil
}, &Config{})
resource.AddDefaultService(datamanager.Named(resource.DefaultModelName))
}
// TODO: re-determine if queue size is optimal given we now support 10khz+ capture rates
// The Collector's queue should be big enough to ensure that .capture() is never blocked by the queue being
// written to disk. A default value of 250 was chosen because even with the fastest reasonable capture interval (1ms),
// this would leave 250ms for a (buffered) disk write before blocking, which seems sufficient for the size of
// writes this would be performing.
const defaultCaptureQueueSize = 250
// Default bufio.Writer buffer size in bytes.
const defaultCaptureBufferSize = 4096
// Attributes to initialize the collector for a component or remote.
type dataCaptureConfig struct {
Name string `json:"name"`
Model string `json:"model"`
Type resource.SubtypeName `json:"type"`
Method string `json:"method"`
CaptureFrequencyHz float32 `json:"capture_frequency_hz"`
CaptureQueueSize int `json:"capture_queue_size"`
CaptureBufferSize int `json:"capture_buffer_size"`
AdditionalParams map[string]string `json:"additional_params"`
Disabled bool `json:"disabled"`
RemoteRobotName string // Empty if this component is locally accessed
Tags []string `json:"tags"`
}
type dataCaptureConfigs struct {
Attributes []dataCaptureConfig `json:"capture_methods"`
}
// Config describes how to configure the service.
type Config struct {
CaptureDir string `json:"capture_dir"`
AdditionalSyncPaths []string `json:"additional_sync_paths"`
SyncIntervalMins float64 `json:"sync_interval_mins"`
CaptureDisabled bool `json:"capture_disabled"`
ScheduledSyncDisabled bool `json:"sync_disabled"`
ModelsToDeploy []*model.Model `json:"models_on_robot"`
}
// builtIn initializes and orchestrates data capture collectors for registered component/methods.
type builtIn struct {
r robot.Robot
logger golog.Logger
captureDir string
captureDisabled bool
collectors map[componentMethodMetadata]collectorAndConfig
lock sync.Mutex
backgroundWorkers sync.WaitGroup
updateCollectorsCancelFn func()
waitAfterLastModifiedSecs int
additionalSyncPaths []string
syncDisabled bool
syncIntervalMins float64
syncer datasync.Manager
syncerConstructor datasync.ManagerConstructor
modelManager model.Manager
modelManagerConstructor model.ManagerConstructor
}
var viamCaptureDotDir = filepath.Join(os.Getenv("HOME"), "capture", ".viam")
// NewBuiltIn returns a new data manager service for the given robot.
func NewBuiltIn(_ context.Context, r robot.Robot, _ config.Service, logger golog.Logger) (datamanager.Service, error) {
// Set syncIntervalMins = -1 as we rely on initOrUpdateSyncer to instantiate a syncer
// on first call to Update, even if syncIntervalMins value is 0, and the default value for int64 is 0.
dataManagerSvc := &builtIn{
r: r,
logger: logger,
captureDir: viamCaptureDotDir,
collectors: make(map[componentMethodMetadata]collectorAndConfig),
backgroundWorkers: sync.WaitGroup{},
lock: sync.Mutex{},
syncIntervalMins: -1,
additionalSyncPaths: []string{},
waitAfterLastModifiedSecs: 10,
syncerConstructor: datasync.NewDefaultManager,
modelManagerConstructor: model.NewDefaultManager,
}
return dataManagerSvc, nil
}
// Close releases all resources managed by data_manager.
func (svc *builtIn) Close(_ context.Context) error {
svc.lock.Lock()
defer svc.lock.Unlock()
svc.closeCollectors()
if svc.syncer != nil {
svc.syncer.Close()
}
svc.cancelSyncBackgroundRoutine()
svc.backgroundWorkers.Wait()
return nil
}
func (svc *builtIn) closeCollectors() {
wg := sync.WaitGroup{}
for md, collector := range svc.collectors {
currCollector := collector
wg.Add(1)
go func() {
defer wg.Done()
currCollector.Collector.Close()
}()
delete(svc.collectors, md)
}
wg.Wait()
}
// Parameters stored for each collector.
type collectorAndConfig struct {
Collector data.Collector
Attributes dataCaptureConfig
}
// Identifier for a particular collector: component name, component model, component type,
// method parameters, and method name.
type componentMethodMetadata struct {
ComponentName string
ComponentModel string
MethodParams string
MethodMetadata data.MethodMetadata
}
// Get time.Duration from hz.
func getDurationFromHz(captureFrequencyHz float32) time.Duration {
if captureFrequencyHz == 0 {
return time.Duration(0)
}
return time.Duration(float32(time.Second) / captureFrequencyHz)
}
// Initialize a collector for the component/method or update it if it has previously been created.
// Return the component/method metadata which is used as a key in the collectors map.
func (svc *builtIn) initializeOrUpdateCollector(
attributes dataCaptureConfig, updateCaptureDir bool) (
*componentMethodMetadata, error,
) {
// Create component/method metadata to check if the collector exists.
metadata := data.MethodMetadata{
Subtype: attributes.Type,
MethodName: attributes.Method,
}
componentMetadata := componentMethodMetadata{
ComponentName: attributes.Name,
ComponentModel: attributes.Model,
MethodParams: fmt.Sprintf("%v", attributes.AdditionalParams),
MethodMetadata: metadata,
}
// Build metadata.
captureMetadata, err := datacapture.BuildCaptureMetadata(attributes.Type, attributes.Name,
attributes.Model, attributes.Method, attributes.AdditionalParams, attributes.Tags)
if err != nil {
return nil, err
}
// TODO: DATA-451 https://viam.atlassian.net/browse/DATA-451 (validate method params)
if storedCollectorParams, ok := svc.collectors[componentMetadata]; ok {
collector := storedCollectorParams.Collector
previousAttributes := storedCollectorParams.Attributes
// If the attributes have not changed, keep the current collector and update the target capture file if needed.
if reflect.DeepEqual(previousAttributes, attributes) {
if updateCaptureDir {
targetFile, err := datacapture.NewFile(svc.captureDir, captureMetadata)
if err != nil {
return nil, err
}
collector.SetTarget(targetFile)
}
return &componentMetadata, nil
}
// Otherwise, close the current collector and instantiate a new one below.
collector.Close()
}
// Get the resource corresponding to the component subtype and name.
resourceType := resource.NewSubtype(
resource.ResourceNamespaceRDK,
resource.ResourceTypeComponent,
attributes.Type,
)
// Get the resource from the local or remote robot.
var res interface{}
if attributes.RemoteRobotName != "" {
remoteRobot, exists := svc.r.RemoteByName(attributes.RemoteRobotName)
if !exists {
return nil, errors.Errorf("failed to find remote %s", attributes.RemoteRobotName)
}
res, err = remoteRobot.ResourceByName(resource.NameFromSubtype(resourceType, attributes.Name))
} else {
res, err = svc.r.ResourceByName(resource.NameFromSubtype(resourceType, attributes.Name))
}
if err != nil {
return nil, err
}
// Get collector constructor for the component subtype and method.
collectorConstructor := data.CollectorLookup(metadata)
if collectorConstructor == nil {
return nil, errors.Errorf("failed to find collector for %s", metadata)
}
// Parameters to initialize collector.
interval := getDurationFromHz(attributes.CaptureFrequencyHz)
targetFile, err := datacapture.NewFile(svc.captureDir, captureMetadata)
if err != nil {
return nil, err
}
// Set queue size to defaultCaptureQueueSize if it was not set in the config.
captureQueueSize := attributes.CaptureQueueSize
if captureQueueSize == 0 {
captureQueueSize = defaultCaptureQueueSize
}
captureBufferSize := attributes.CaptureBufferSize
if captureBufferSize == 0 {
captureBufferSize = defaultCaptureBufferSize
}
methodParams, err := protoutils.ConvertStringMapToAnyPBMap(attributes.AdditionalParams)
if err != nil {
return nil, err
}
// Create a collector for this resource and method.
params := data.CollectorParams{
ComponentName: attributes.Name,
Interval: interval,
MethodParams: methodParams,
Target: targetFile,
QueueSize: captureQueueSize,
BufferSize: captureBufferSize,
Logger: svc.logger,
}
collector, err := (*collectorConstructor)(res, params)
if err != nil {
return nil, err
}
svc.lock.Lock()
svc.collectors[componentMetadata] = collectorAndConfig{collector, attributes}
svc.lock.Unlock()
// TODO: Handle errors more gracefully.
collector.Collect()
return &componentMetadata, nil
}
// getCollectorFromConfig returns the collector and metadata that is referenced based on specific config atrributes
func (svc *builtIn) getCollectorFromConfig(attributes dataCaptureConfig) (data.Collector, *componentMethodMetadata, error) {
// Create component/method metadata to check if the collector exists.
metadata := data.MethodMetadata{
Subtype: attributes.Type,
MethodName: attributes.Method,
}
componentMetadata := componentMethodMetadata{
ComponentName: attributes.Name,
ComponentModel: attributes.Model,
MethodParams: fmt.Sprintf("%v", attributes.AdditionalParams),
MethodMetadata: metadata,
}
if storedCollectorParams, ok := svc.collectors[componentMetadata]; ok {
collector := storedCollectorParams.Collector
return collector, &componentMetadata, nil
}
return nil, nil, errors.Errorf("no collector was found with config %v", attributes)
}
func (svc *builtIn) initOrUpdateSyncer(_ context.Context, intervalMins float64, cfg *config.Config) error {
// If user updates sync config while a sync is occurring, the running sync will be cancelled.
// TODO DATA-235: fix that
if svc.syncer != nil {
// If previously we were syncing, close the old syncer and cancel the old updateCollectors goroutine.
svc.syncer.Close()
svc.syncer = nil
}
svc.cancelSyncBackgroundRoutine()
// Kick off syncer if we're running it.
if intervalMins > 0 {
syncer, err := svc.syncerConstructor(svc.logger, cfg)
if err != nil {
return errors.Wrap(err, "failed to initialize new syncer")
}
svc.syncer = syncer
// Sync existing files in captureDir.
var previouslyCaptured []string
//nolint
_ = filepath.Walk(svc.captureDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if info.IsDir() {
return nil
}
previouslyCaptured = append(previouslyCaptured, path)
return nil
})
svc.syncer.Sync(previouslyCaptured)
// Validate svc.additionSyncPaths all exist, and create them if not. Then sync files in svc.additionalSyncPaths.
svc.syncer.Sync(svc.buildAdditionalSyncPaths())
// Kick off background routine to periodically sync files.
svc.startSyncBackgroundRoutine(intervalMins)
}
return nil
}
// Sync performs a non-scheduled sync of the data in the capture directory.
func (svc *builtIn) Sync(_ context.Context) error {
if svc.syncer == nil {
return errors.New("called Sync on data manager service with nil syncer")
}
err := svc.syncDataCaptureFiles()
if err != nil {
return err
}
svc.syncAdditionalSyncPaths()
return nil
}
func (svc *builtIn) syncDataCaptureFiles() error {
svc.lock.Lock()
oldFiles := make([]string, 0, len(svc.collectors))
currCollectors := make(map[componentMethodMetadata]collectorAndConfig)
for k, v := range svc.collectors {
currCollectors[k] = v
}
svc.lock.Unlock()
for _, collector := range currCollectors {
// Create new target and set it.
attributes := collector.Attributes
captureMetadata, err := datacapture.BuildCaptureMetadata(attributes.Type, attributes.Name,
attributes.Model, attributes.Method, attributes.AdditionalParams, attributes.Tags)
if err != nil {
return err
}
nextTarget, err := datacapture.NewFile(svc.captureDir, captureMetadata)
if err != nil {
return err
}
oldFiles = append(oldFiles, collector.Collector.GetTarget().GetPath())
collector.Collector.SetTarget(nextTarget)
}
svc.syncer.Sync(oldFiles)
return nil
}
func (svc *builtIn) buildAdditionalSyncPaths() []string {
svc.lock.Lock()
currAdditionalSyncPaths := svc.additionalSyncPaths
waitAfterLastModified := svc.waitAfterLastModifiedSecs
svc.lock.Unlock()
var filepathsToSync []string
// Loop through additional sync paths and add files from each to the syncer.
for _, asp := range currAdditionalSyncPaths {
// Check that additional sync paths directories exist. If not, create directories accordingly.
if _, err := os.Stat(asp); errors.Is(err, os.ErrNotExist) {
err := os.Mkdir(asp, os.ModePerm)
if err != nil {
svc.logger.Errorw("data manager unable to create a directory specified as an additional sync path", "error", err)
}
} else {
// Traverse all files in 'asp' directory and append them to a list of files to be synced.
now := time.Now()
//nolint
_ = filepath.Walk(asp, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if info.IsDir() {
return nil
}
// If a file was modified within the past waitAfterLastModifiedSecs seconds, do not sync it (data
// may still be being written).
if diff := now.Sub(info.ModTime()); diff < (time.Duration(waitAfterLastModified) * time.Second) {
return nil
}
filepathsToSync = append(filepathsToSync, path)
return nil
})
}
}
return filepathsToSync
}
// Syncs files under svc.additionalSyncPaths. If any of the directories do not exist, creates them.
func (svc *builtIn) syncAdditionalSyncPaths() {
svc.syncer.Sync(svc.buildAdditionalSyncPaths())
}
// Update updates the data manager service when the config has changed.
func (svc *builtIn) Update(ctx context.Context, cfg *config.Config) error {
svcConfig, ok, err := getServiceConfig(cfg)
// Service is not in the config, has been removed from it, or is incorrectly formatted in the config.
// Close any collectors.
if !ok {
svc.closeCollectors()
return err
}
// Check that we have models to download and appropriate credentials.
if len(svcConfig.ModelsToDeploy) > 0 && cfg.Cloud != nil {
if svc.modelManager == nil {
modelManager, err := svc.modelManagerConstructor(svc.logger, cfg)
if err != nil {
return errors.Wrap(err, "failed to initialize new modelManager")
}
svc.modelManager = modelManager
}
// Download models from models_on_robot.
modelsToDeploy := svcConfig.ModelsToDeploy
errorChannel := make(chan error, len(modelsToDeploy))
go svc.modelManager.DownloadModels(cfg, modelsToDeploy, errorChannel)
if len(errorChannel) != 0 {
var errMsgs []string
for err := range errorChannel {
errMsgs = append(errMsgs, err.Error())
}
return errors.New(strings.Join(errMsgs[:], ", "))
}
}
toggledCaptureOff := (svc.captureDisabled != svcConfig.CaptureDisabled) && svcConfig.CaptureDisabled
svc.captureDisabled = svcConfig.CaptureDisabled
var allComponentAttributes []dataCaptureConfig
// Service is disabled, so close all collectors and clear the map so we can instantiate new ones if we enable this service.
if toggledCaptureOff {
svc.closeCollectors()
svc.collectors = make(map[componentMethodMetadata]collectorAndConfig)
} else {
allComponentAttributes, err = buildDataCaptureConfigs(cfg)
if err != nil {
svc.logger.Warn(err.Error())
return err
}
if len(allComponentAttributes) == 0 {
svc.logger.Info("no components with data_manager service configuration")
}
}
toggledSync := svc.syncDisabled != svcConfig.ScheduledSyncDisabled
svc.syncDisabled = svcConfig.ScheduledSyncDisabled
toggledSyncOff := toggledSync && svc.syncDisabled
toggledSyncOn := toggledSync && !svc.syncDisabled
// If sync has been toggled on, sync previously captured files and update the capture directory.
updateCaptureDir := (svc.captureDir != svcConfig.CaptureDir) || toggledSyncOn
svc.captureDir = svcConfig.CaptureDir
// Stop syncing if newly disabled in the config.
if toggledSyncOff {
if err := svc.initOrUpdateSyncer(ctx, 0, cfg); err != nil {
return err
}
} else if toggledSyncOn || (svcConfig.SyncIntervalMins != svc.syncIntervalMins) ||
!reflect.DeepEqual(svcConfig.AdditionalSyncPaths, svc.additionalSyncPaths) {
// If the sync config has changed, update the syncer.
svc.lock.Lock()
svc.additionalSyncPaths = svcConfig.AdditionalSyncPaths
svc.lock.Unlock()
svc.syncIntervalMins = svcConfig.SyncIntervalMins
if err := svc.initOrUpdateSyncer(ctx, svcConfig.SyncIntervalMins, cfg); err != nil {
return err
}
}
// Initialize or add a collector based on changes to the component configurations.
newCollectorMetadata := make(map[componentMethodMetadata]bool)
for _, attributes := range allComponentAttributes {
if !attributes.Disabled && attributes.CaptureFrequencyHz > 0 && !svc.captureDisabled {
componentMetadata, err := svc.initializeOrUpdateCollector(
attributes, updateCaptureDir)
if err != nil {
svc.logger.Errorw("failed to initialize or update collector", "error", err)
} else {
newCollectorMetadata[*componentMetadata] = true
}
} else if attributes.Disabled {
// if disabled, make sure that it is closed, so it doesn't keep collecting data.
collector, md, err := svc.getCollectorFromConfig(attributes)
if err != nil {
svc.logger.Errorw("collector ", attributes.Name, " was not found", "info", err)
} else {
collector.Close()
delete(svc.collectors, *md)
}
}
}
// If a component/method has been removed from the config, close the collector and remove it from the map.
for componentMetadata, params := range svc.collectors {
if _, present := newCollectorMetadata[componentMetadata]; !present {
params.Collector.Close()
delete(svc.collectors, componentMetadata)
}
}
return nil
}
func (svc *builtIn) uploadData(cancelCtx context.Context, intervalMins float64) {
svc.backgroundWorkers.Add(1)
goutils.PanicCapturingGo(func() {
defer svc.backgroundWorkers.Done()
// time.Duration loses precision at low floating point values, so turn intervalMins to milliseconds.
intervalMillis := 60000.0 * intervalMins
ticker := time.NewTicker(time.Millisecond * time.Duration(intervalMillis))
defer ticker.Stop()
for {
if err := cancelCtx.Err(); err != nil {
if !errors.Is(err, context.Canceled) {
svc.logger.Errorw("data manager context closed unexpectedly", "error", err)
}
return
}
select {
case <-cancelCtx.Done():
return
case <-ticker.C:
err := svc.syncDataCaptureFiles()
if err != nil {
svc.logger.Errorw("data capture files failed to sync", "error", err)
}
// TODO DATA-660: There's a risk of deadlock where we're in this case when Close is called, which
// acquires svc.lock, which prevents this call from ever acquiring the lock/finishing.
svc.syncAdditionalSyncPaths()
}
}
})
}
func (svc *builtIn) startSyncBackgroundRoutine(intervalMins float64) {
cancelCtx, fn := context.WithCancel(context.Background())
svc.updateCollectorsCancelFn = fn
svc.uploadData(cancelCtx, intervalMins)
}
func (svc *builtIn) cancelSyncBackgroundRoutine() {
if svc.updateCollectorsCancelFn != nil {
svc.updateCollectorsCancelFn()
svc.updateCollectorsCancelFn = nil
}
}
// Get the config associated with the data manager service.
// Returns a boolean for whether a config is returned and an error if the
// config was incorrectly formatted.
func getServiceConfig(cfg *config.Config) (*Config, bool, error) {
for _, c := range cfg.Services {
// Compare service type and name.
if c.ResourceName().ResourceSubtype == datamanager.SubtypeName && c.ConvertedAttributes != nil {
svcConfig, ok := c.ConvertedAttributes.(*Config)
// Incorrect configuration is an error.
if !ok {
return &Config{}, false, utils.NewUnexpectedTypeError(svcConfig, c.ConvertedAttributes)
}
return svcConfig, true, nil
}
}
// Data Manager Service is not in the config, which is not an error.
return &Config{}, false, nil
}
func getAttrsFromServiceConfig(resourceSvcConfig config.ResourceLevelServiceConfig) (dataCaptureConfigs, error) {
var attrs dataCaptureConfigs
configs, err := config.TransformAttributeMapToStruct(&attrs, resourceSvcConfig.Attributes)
if err != nil {
return dataCaptureConfigs{}, err
}
convertedConfigs, ok := configs.(*dataCaptureConfigs)
if !ok {
return dataCaptureConfigs{}, utils.NewUnexpectedTypeError(convertedConfigs, configs)
}
return *convertedConfigs, nil
}
// Build the component configs associated with the data manager service.
func buildDataCaptureConfigs(cfg *config.Config) ([]dataCaptureConfig, error) {
var componentDataCaptureConfigs []dataCaptureConfig
for _, c := range cfg.Components {
// Iterate over all component-level service configs of type data_manager.
for _, componentSvcConfig := range c.ServiceConfig {
if componentSvcConfig.Type == datamanager.SubtypeName {
attrs, err := getAttrsFromServiceConfig(componentSvcConfig)
if err != nil {
return componentDataCaptureConfigs, err
}
for _, attrs := range attrs.Attributes {
attrs.Name = c.Name
attrs.Model = c.Model
attrs.Type = c.Type
componentDataCaptureConfigs = append(componentDataCaptureConfigs, attrs)
}
}
}
}
for _, r := range cfg.Remotes {
// Iterate over all remote-level service configs of type data_manager.
for _, resourceSvcConfig := range r.ServiceConfig {
if resourceSvcConfig.Type == datamanager.SubtypeName {
attrs, err := getAttrsFromServiceConfig(resourceSvcConfig)
if err != nil {
return componentDataCaptureConfigs, err
}
for _, attrs := range attrs.Attributes {
name, err := resource.NewFromString(attrs.Name)
if err != nil {
return componentDataCaptureConfigs, err
}
attrs.Name = name.Name
attrs.Type = name.ResourceSubtype
attrs.RemoteRobotName = r.Name
componentDataCaptureConfigs = append(componentDataCaptureConfigs, attrs)
}
}
}
}
return componentDataCaptureConfigs, nil
}