-
Notifications
You must be signed in to change notification settings - Fork 110
/
reader.go
651 lines (561 loc) · 19.2 KB
/
reader.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
package config
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"runtime"
"github.com/a8m/envsubst"
"github.com/pkg/errors"
apppb "go.viam.com/api/app/v1"
"go.viam.com/utils"
"go.viam.com/utils/artifact"
"go.viam.com/utils/rpc"
"golang.org/x/sys/cpu"
"go.viam.com/rdk/logging"
"go.viam.com/rdk/resource"
rutils "go.viam.com/rdk/utils"
)
// RDK versioning variables which are replaced by LD flags.
var (
Version = ""
GitRevision = ""
)
func getAgentInfo() (*apppb.AgentInfo, error) {
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
ips, err := utils.GetAllLocalIPv4s()
if err != nil {
return nil, err
}
arch := runtime.GOARCH
// "arm" is used for arm32. "arm64" is used for versions after v7
if arch == "arm" {
// armv7 added LPAE (Large Page Address Extension).
// this is an official way to detect armv7
// https://go-review.googlesource.com/c/go/+/525637/2/src/internal/cpu/cpu_arm.go#36
if cpu.ARM.HasLPAE {
arch = "arm32v7"
} else {
// fallback to armv6
arch = "arm32v6"
}
}
platform := fmt.Sprintf("%s/%s", runtime.GOOS, arch)
return &apppb.AgentInfo{
Host: hostname,
Ips: ips,
Os: runtime.GOOS,
Version: Version,
GitRevision: GitRevision,
Platform: &platform,
}, nil
}
var (
// ViamDotDir is the directory for Viam's cached files.
ViamDotDir string
viamPackagesDir string
)
func init() {
//nolint:errcheck
home, _ := os.UserHomeDir()
ViamDotDir = filepath.Join(home, ".viam")
viamPackagesDir = filepath.Join(ViamDotDir, "packages")
}
func getCloudCacheFilePath(id string) string {
return filepath.Join(ViamDotDir, fmt.Sprintf("cached_cloud_config_%s.json", id))
}
func readFromCache(id string) (*Config, error) {
r, err := os.Open(getCloudCacheFilePath(id))
if err != nil {
return nil, err
}
defer utils.UncheckedErrorFunc(r.Close)
unprocessedConfig := &Config{
ConfigFilePath: "",
}
if err := json.NewDecoder(r).Decode(unprocessedConfig); err != nil {
// clear the cache if we cannot parse the file.
clearCache(id)
return nil, errors.Wrap(err, "cannot parse the cached config as json")
}
return unprocessedConfig, nil
}
func storeToCache(id string, cfg *Config) error {
if err := os.MkdirAll(ViamDotDir, 0o700); err != nil {
return err
}
md, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
reader := bytes.NewReader(md)
path := getCloudCacheFilePath(id)
return artifact.AtomicStore(path, reader, id)
}
func clearCache(id string) {
utils.UncheckedErrorFunc(func() error {
return os.Remove(getCloudCacheFilePath(id))
})
}
func readCertificateDataFromCloudGRPC(ctx context.Context,
signalingInsecure bool,
cloudConfigFromDisk *Cloud,
logger logging.Logger,
) (*Cloud, error) {
conn, err := CreateNewGRPCClient(ctx, cloudConfigFromDisk, logger)
if err != nil {
return nil, err
}
defer utils.UncheckedErrorFunc(conn.Close)
service := apppb.NewRobotServiceClient(conn)
res, err := service.Certificate(ctx, &apppb.CertificateRequest{Id: cloudConfigFromDisk.ID})
if err != nil {
// Check cache?
return nil, err
}
if !signalingInsecure {
if res.TlsCertificate == "" {
return nil, errors.New("no TLS certificate yet from cloud; try again later")
}
if res.TlsPrivateKey == "" {
return nil, errors.New("no TLS private key yet from cloud; try again later")
}
}
// TODO(RSDK-539): we might want to use an internal type here. The gRPC api will not return a Cloud json struct.
return &Cloud{
TLSCertificate: res.TlsCertificate,
TLSPrivateKey: res.TlsPrivateKey,
}, nil
}
// shouldCheckForCert checks the Cloud config to see if the TLS cert should be refetched.
func shouldCheckForCert(prevCloud, cloud *Cloud) bool {
// only checking the same fields as the ones that are explicitly overwritten in mergeCloudConfig
diffFQDN := prevCloud.FQDN != cloud.FQDN
diffLocalFQDN := prevCloud.LocalFQDN != cloud.LocalFQDN
diffSignalingAddr := prevCloud.SignalingAddress != cloud.SignalingAddress
diffSignalInsecure := prevCloud.SignalingInsecure != cloud.SignalingInsecure
diffManagedBy := prevCloud.ManagedBy != cloud.ManagedBy
diffLocSecret := prevCloud.LocationSecret != cloud.LocationSecret || !isLocationSecretsEqual(prevCloud, cloud)
return diffFQDN || diffLocalFQDN || diffSignalingAddr || diffSignalInsecure || diffManagedBy || diffLocSecret
}
func isLocationSecretsEqual(prevCloud, cloud *Cloud) bool {
if len(prevCloud.LocationSecrets) != len(cloud.LocationSecrets) {
return false
}
for i := range cloud.LocationSecrets {
if cloud.LocationSecrets[i].Secret != prevCloud.LocationSecrets[i].Secret {
return false
}
if cloud.LocationSecrets[i].ID != prevCloud.LocationSecrets[i].ID {
return false
}
}
return true
}
// readFromCloud fetches a robot config from the cloud based
// on the given config.
func readFromCloud(
ctx context.Context,
originalCfg,
prevCfg *Config,
shouldReadFromCache bool,
checkForNewCert bool,
logger logging.Logger,
) (*Config, error) {
logger.Debug("reading configuration from the cloud")
cloudCfg := originalCfg.Cloud
unprocessedConfig, cached, err := getFromCloudOrCache(ctx, cloudCfg, shouldReadFromCache, logger)
if err != nil {
if !cached {
err = errors.Wrap(err, "error getting cloud config")
}
return nil, err
}
// process the config
cfg, err := processConfigFromCloud(unprocessedConfig, logger)
if err != nil {
// If we cannot process the config from the cache we should clear it.
if cached {
// clear cache
logger.Warn("Detected failure to process the cached config, clearing cache.")
clearCache(cloudCfg.ID)
}
return nil, err
}
if cfg.Cloud == nil {
return nil, errors.New("expected config to have cloud section")
}
// empty if not cached, since its a separate request, which we check next
tlsCertificate := cfg.Cloud.TLSCertificate
tlsPrivateKey := cfg.Cloud.TLSPrivateKey
if !cached {
// get cached certificate data
// read cached config from fs.
// process the config with fromReader() use processed config as cachedConfig to update the cert data.
unproccessedCachedConfig, err := readFromCache(cloudCfg.ID)
if err == nil {
cachedConfig, err := processConfigFromCloud(unproccessedCachedConfig, logger)
if err != nil {
// clear cache
logger.Warn("Detected failure to process the cached config when retrieving TLS config, clearing cache.")
clearCache(cloudCfg.ID)
return nil, err
}
if cachedConfig.Cloud != nil {
tlsCertificate = cachedConfig.Cloud.TLSCertificate
tlsPrivateKey = cachedConfig.Cloud.TLSPrivateKey
}
} else if !os.IsNotExist(err) {
return nil, err
}
}
if prevCfg != nil && shouldCheckForCert(prevCfg.Cloud, cfg.Cloud) {
checkForNewCert = true
}
if checkForNewCert || tlsCertificate == "" || tlsPrivateKey == "" {
logger.Debug("reading tlsCertificate from the cloud")
// Use the SignalingInsecure from the Cloud config returned from the app not the initial config.
certData, err := readCertificateDataFromCloudGRPC(ctx, cfg.Cloud.SignalingInsecure, cloudCfg, logger)
if err != nil {
if !errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
if tlsCertificate == "" || tlsPrivateKey == "" {
return nil, errors.Wrap(err, "error getting certificate data from cloud; try again later")
}
logger.Warnw("failed to refresh certificate data; using cached for now", "error", err)
} else {
tlsCertificate = certData.TLSCertificate
tlsPrivateKey = certData.TLSPrivateKey
}
}
fqdn := cfg.Cloud.FQDN
localFQDN := cfg.Cloud.LocalFQDN
signalingAddress := cfg.Cloud.SignalingAddress
signalingInsecure := cfg.Cloud.SignalingInsecure
managedBy := cfg.Cloud.ManagedBy
locationSecret := cfg.Cloud.LocationSecret
locationSecrets := cfg.Cloud.LocationSecrets
mergeCloudConfig := func(to *Config) {
*to.Cloud = *cloudCfg
to.Cloud.FQDN = fqdn
to.Cloud.LocalFQDN = localFQDN
to.Cloud.SignalingAddress = signalingAddress
to.Cloud.SignalingInsecure = signalingInsecure
to.Cloud.ManagedBy = managedBy
to.Cloud.LocationSecret = locationSecret
to.Cloud.LocationSecrets = locationSecrets
to.Cloud.TLSCertificate = tlsCertificate
to.Cloud.TLSPrivateKey = tlsPrivateKey
}
mergeCloudConfig(cfg)
// TODO(RSDK-1960): add more tests around config caching
unprocessedConfig.Cloud.TLSCertificate = tlsCertificate
unprocessedConfig.Cloud.TLSPrivateKey = tlsPrivateKey
if err := storeToCache(cloudCfg.ID, unprocessedConfig); err != nil {
logger.Errorw("failed to cache config", "error", err)
}
return cfg, nil
}
// Read reads a config from the given file.
func Read(
ctx context.Context,
filePath string,
logger logging.Logger,
) (*Config, error) {
buf, err := envsubst.ReadFile(filePath)
if err != nil {
return nil, err
}
return FromReader(ctx, filePath, bytes.NewReader(buf), logger)
}
// ReadLocalConfig reads a config from the given file but does not fetch any config from the remote servers.
func ReadLocalConfig(
ctx context.Context,
filePath string,
logger logging.Logger,
) (*Config, error) {
buf, err := envsubst.ReadFile(filePath)
if err != nil {
return nil, err
}
return fromReader(ctx, filePath, bytes.NewReader(buf), logger, false)
}
// FromReader reads a config from the given reader and specifies
// where, if applicable, the file the reader originated from.
func FromReader(
ctx context.Context,
originalPath string,
r io.Reader,
logger logging.Logger,
) (*Config, error) {
return fromReader(ctx, originalPath, r, logger, true)
}
// FromReader reads a config from the given reader and specifies
// where, if applicable, the file the reader originated from.
func fromReader(
ctx context.Context,
originalPath string,
r io.Reader,
logger logging.Logger,
shouldReadFromCloud bool,
) (*Config, error) {
// First read and processes config from disk
unprocessedConfig := Config{
ConfigFilePath: originalPath,
}
err := json.NewDecoder(r).Decode(&unprocessedConfig)
if err != nil {
return nil, errors.Wrapf(err, "failed to decode Config from json")
}
cfgFromDisk, err := processConfigLocalConfig(&unprocessedConfig, logger)
if err != nil {
return nil, errors.Wrapf(err, "failed to process Config")
}
if shouldReadFromCloud && cfgFromDisk.Cloud != nil {
cfg, err := readFromCloud(ctx, cfgFromDisk, nil, true, true, logger)
return cfg, err
}
return cfgFromDisk, err
}
// processConfigFromCloud returns a copy of the current config with all attributes parsed
// and config validated with the assumption the config came from the cloud.
// Returns an error if the unprocessedConfig is non-valid.
func processConfigFromCloud(unprocessedConfig *Config, logger logging.Logger) (*Config, error) {
return processConfig(unprocessedConfig, true, logger)
}
// processConfigLocalConfig returns a copy of the current config with all attributes parsed
// and config validated with the assumption the config came from a local file.
// Returns an error if the unprocessedConfig is non-valid.
func processConfigLocalConfig(unprocessedConfig *Config, logger logging.Logger) (*Config, error) {
return processConfig(unprocessedConfig, false, logger)
}
func processConfig(unprocessedConfig *Config, fromCloud bool, logger logging.Logger) (*Config, error) {
if err := unprocessedConfig.Ensure(fromCloud, logger); err != nil {
return nil, err
}
cfg, err := unprocessedConfig.CopyOnlyPublicFields()
if err != nil {
return nil, errors.Wrap(err, "error copying config")
}
if err := cfg.ReplacePlaceholders(); err != nil {
logger.Errorw("error during placeholder replacement", "err", err)
}
// Copy does not presve ConfigFilePath and we need to pass it along manually
cfg.ConfigFilePath = unprocessedConfig.ConfigFilePath
// See if default service already exists in the config
defaultServices := resource.DefaultServices()
unconfiguredDefaultServices := make(map[resource.API]resource.Name, len(defaultServices))
for _, name := range defaultServices {
unconfiguredDefaultServices[name.API] = name
}
for _, c := range cfg.Services {
delete(unconfiguredDefaultServices, c.API)
}
for _, defaultServiceName := range unconfiguredDefaultServices {
cfg.Services = append(cfg.Services, resource.Config{
Name: defaultServiceName.Name,
Model: resource.DefaultServiceModel,
API: defaultServiceName.API,
})
}
// We keep track of resource configs per API to facilitate linking resource configs to
// its associated resource configs. Associated resource configs are configs that are
// linked to and used by a different resource config.
resCfgsPerAPI := map[resource.API][]*resource.Config{}
processResources := func(confs []resource.Config) error {
for idx, conf := range confs {
copied := conf
// for resource to resource associations
resCfgsPerAPI[copied.API] = append(resCfgsPerAPI[copied.API], &confs[idx])
resName := copied.ResourceName()
reg, ok := resource.LookupRegistration(resName.API, copied.Model)
if !ok || reg.AttributeMapConverter == nil {
continue
}
converted, err := reg.AttributeMapConverter(conf.Attributes)
if err != nil {
return errors.Wrapf(err, "error converting attributes for (%s, %s)", resName.API, copied.Model)
}
confs[idx].ConvertedAttributes = converted
}
return nil
}
if err := processResources(cfg.Components); err != nil {
return nil, err
}
if err := processResources(cfg.Services); err != nil {
return nil, err
}
convertAndAssociateResourceConfigs := func(
resName *resource.Name,
remoteName *string,
associatedCfgs []resource.AssociatedResourceConfig,
) error {
for subIdx, associatedConf := range associatedCfgs {
conv, ok := resource.LookupAssociatedConfigRegistration(associatedConf.API)
if !ok {
continue
}
var convertedAttrs interface{} = associatedConf.Attributes
if conv.AttributeMapConverter != nil {
converted, err := conv.AttributeMapConverter(associatedConf.Attributes)
if err != nil {
return errors.Wrap(err, "error converting associated resource config attributes")
}
// associated resource configs for local resources might be missing the resource name,
// which can be inferred from its resource config.
// associated resource configs for remote resources might be missing the remote name for the resource,
// which can be inferred from its remote config.
converted.UpdateResourceNames(func(oldName resource.Name) resource.Name {
newName := oldName
if resName != nil {
newName = *resName
}
if remoteName != nil {
newName = newName.PrependRemote(*remoteName)
}
return newName
})
associatedCfgs[subIdx].ConvertedAttributes = converted
convertedAttrs = converted
}
// for APIs with an associated config linker, link the current associated config with
// each resource config of that API.
for _, assocConf := range resCfgsPerAPI[associatedConf.API] {
reg, ok := resource.LookupRegistration(associatedConf.API, assocConf.Model)
if !ok || reg.AssociatedConfigLinker == nil {
continue
}
if err := reg.AssociatedConfigLinker(assocConf.ConvertedAttributes, convertedAttrs); err != nil {
return errors.Wrapf(err, "error associating resource association config to resource %q", assocConf.Model)
}
}
}
return nil
}
processAssociations := func(confs []resource.Config) error {
for _, conf := range confs {
copied := conf
resName := copied.ResourceName()
if err := convertAndAssociateResourceConfigs(&resName, nil, conf.AssociatedResourceConfigs); err != nil {
return errors.Wrapf(err, "error processing associated service configs for %q", resName)
}
}
return nil
}
if err := processAssociations(cfg.Components); err != nil {
return nil, err
}
if err := processAssociations(cfg.Services); err != nil {
return nil, err
}
for _, c := range cfg.Remotes {
if err := convertAndAssociateResourceConfigs(nil, &c.Name, c.AssociatedResourceConfigs); err != nil {
return nil, errors.Wrapf(err, "error processing associated service configs for remote %q", c.Name)
}
}
if err := cfg.Ensure(fromCloud, logger); err != nil {
return nil, err
}
return cfg, nil
}
// getFromCloudOrCache returns the config from the gRPC endpoint. If failures during cloud lookup fallback to the
// local cache if the error indicates it should.
func getFromCloudOrCache(ctx context.Context, cloudCfg *Cloud, shouldReadFromCache bool, logger logging.Logger) (*Config, bool, error) {
var cached bool
cfg, errorShouldCheckCache, err := getFromCloudGRPC(ctx, cloudCfg, logger)
if err != nil {
if shouldReadFromCache && errorShouldCheckCache {
logger.Warnw("failed to read config from cloud, checking cache", "error", err)
cachedConfig, cacheErr := readFromCache(cloudCfg.ID)
if cacheErr != nil {
if os.IsNotExist(cacheErr) {
// Return original http error if failed to load from cache.
return nil, cached, err
}
// return cache err
return nil, cached, cacheErr
}
logger.Warnw("unable to get cloud config; using cached version", "error", err)
cached = true
return cachedConfig, cached, nil
}
return nil, cached, err
}
return cfg, cached, nil
}
// getFromCloudGRPC actually does the fetching of the robot config from the gRPC endpoint.
func getFromCloudGRPC(ctx context.Context, cloudCfg *Cloud, logger logging.Logger) (*Config, bool, error) {
shouldCheckCacheOnFailure := true
conn, err := CreateNewGRPCClient(ctx, cloudCfg, logger)
if err != nil {
return nil, shouldCheckCacheOnFailure, err
}
defer utils.UncheckedErrorFunc(conn.Close)
agentInfo, err := getAgentInfo()
if err != nil {
return nil, shouldCheckCacheOnFailure, err
}
service := apppb.NewRobotServiceClient(conn)
res, err := service.Config(ctx, &apppb.ConfigRequest{Id: cloudCfg.ID, AgentInfo: agentInfo})
if err != nil {
// Check cache?
return nil, shouldCheckCacheOnFailure, err
}
cfg, err := FromProto(res.Config, logger)
if err != nil {
// Check cache?
return nil, shouldCheckCacheOnFailure, err
}
return cfg, false, nil
}
// CreateNewGRPCClient creates a new grpc cloud configured to communicate with the robot service based on the cloud config given.
func CreateNewGRPCClient(ctx context.Context, cloudCfg *Cloud, logger logging.Logger) (rpc.ClientConn, error) {
u, err := url.Parse(cloudCfg.AppAddress)
if err != nil {
return nil, err
}
dialOpts := make([]rpc.DialOption, 0, 2)
// Only add credentials when secret is set.
if cloudCfg.Secret != "" {
dialOpts = append(dialOpts, rpc.WithEntityCredentials(cloudCfg.ID,
rpc.Credentials{
Type: rutils.CredentialsTypeRobotSecret,
Payload: cloudCfg.Secret,
},
))
}
if u.Scheme == "http" {
dialOpts = append(dialOpts, rpc.WithInsecure())
}
return rpc.DialDirectGRPC(ctx, u.Host, logger.AsZap(), dialOpts...)
}
// CreateNewGRPCClientWithAPIKey creates a new grpc cloud configured to communicate with the robot service
// based on the cloud config and API key given.
func CreateNewGRPCClientWithAPIKey(ctx context.Context, cloudCfg *Cloud,
apiKey, apiKeyID string, logger logging.Logger,
) (rpc.ClientConn, error) {
u, err := url.Parse(cloudCfg.AppAddress)
if err != nil {
return nil, err
}
dialOpts := make([]rpc.DialOption, 0, 2)
dialOpts = append(dialOpts, rpc.WithEntityCredentials(apiKeyID,
rpc.Credentials{
Type: rpc.CredentialsTypeAPIKey,
Payload: apiKey,
},
))
if u.Scheme == "http" {
dialOpts = append(dialOpts, rpc.WithInsecure())
}
return rpc.DialDirectGRPC(ctx, u.Host, logger.AsZap(), dialOpts...)
}