-
Notifications
You must be signed in to change notification settings - Fork 110
/
client.go
668 lines (598 loc) · 18.9 KB
/
client.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
// Package client contains a gRPC based robot.Robot client.
package client
import (
"context"
"strings"
"sync"
"time"
"github.com/edaniels/golog"
"github.com/fullstorydev/grpcurl"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/grpcreflect"
"github.com/pkg/errors"
"go.uber.org/multierr"
commonpb "go.viam.com/api/common/v1"
pb "go.viam.com/api/robot/v1"
"go.viam.com/utils"
"go.viam.com/utils/pexec"
"go.viam.com/utils/protoutils"
"go.viam.com/utils/rpc"
"google.golang.org/grpc/codes"
reflectpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
"google.golang.org/grpc/status"
"go.viam.com/rdk/config"
"go.viam.com/rdk/discovery"
"go.viam.com/rdk/grpc"
"go.viam.com/rdk/operation"
rprotoutils "go.viam.com/rdk/protoutils"
"go.viam.com/rdk/referenceframe"
"go.viam.com/rdk/registry"
"go.viam.com/rdk/resource"
"go.viam.com/rdk/robot"
framesystemparts "go.viam.com/rdk/robot/framesystem/parts"
)
var (
// ErrMissingClientRegistration is used when there is no resource client registered for the subtype.
ErrMissingClientRegistration = errors.New("resource client registration doesn't exist")
// errUnimplemented is used for any unimplemented methods that should
// eventually be implemented server side or faked client side.
errUnimplemented = errors.New("unimplemented")
)
// RobotClient satisfies the robot.Robot interface through a gRPC based
// client conforming to the robot.proto contract.
type RobotClient struct {
address string
conn rpc.ClientConn
client pb.RobotServiceClient
refClient *grpcreflect.Client
dialOptions []rpc.DialOption
resourceClients map[resource.Name]interface{}
remoteNameMap map[resource.Name]resource.Name
mu *sync.RWMutex
resourceNames []resource.Name
resourceRPCSubtypes []resource.RPCSubtype
connected bool
changeChan chan bool
activeBackgroundWorkers *sync.WaitGroup
cancelBackgroundWorkers func()
logger golog.Logger
notifyParent func()
closeContext context.Context
}
// New constructs a new RobotClient that is served at the given address. The given
// context can be used to cancel the operation.
func New(ctx context.Context, address string, logger golog.Logger, opts ...RobotClientOption) (*RobotClient, error) {
var rOpts robotClientOpts
for _, opt := range opts {
opt.apply(&rOpts)
}
closeCtx, cancel := context.WithCancel(ctx)
rc := &RobotClient{
address: address,
cancelBackgroundWorkers: cancel,
mu: &sync.RWMutex{},
activeBackgroundWorkers: &sync.WaitGroup{},
logger: logger,
closeContext: closeCtx,
dialOptions: rOpts.dialOptions,
notifyParent: nil,
resourceClients: make(map[resource.Name]interface{}),
remoteNameMap: make(map[resource.Name]resource.Name),
}
if err := rc.connect(ctx); err != nil {
return nil, err
}
// refresh once to hydrate the robot.
if err := rc.Refresh(ctx); err != nil {
return nil, multierr.Combine(err, rc.conn.Close())
}
var refreshTime time.Duration
if rOpts.refreshEvery == nil {
refreshTime = 10 * time.Second
} else {
refreshTime = *rOpts.refreshEvery
}
if refreshTime > 0 {
rc.activeBackgroundWorkers.Add(1)
utils.ManagedGo(func() {
rc.RefreshEvery(closeCtx, refreshTime)
}, rc.activeBackgroundWorkers.Done)
}
if rOpts.checkConnectedEvery != 0 {
rc.activeBackgroundWorkers.Add(1)
utils.ManagedGo(func() {
rc.checkConnection(closeCtx, rOpts.checkConnectedEvery, rOpts.reconnectEvery)
}, rc.activeBackgroundWorkers.Done)
}
return rc, nil
}
// SetParentNotifier set the notifier function, robot client will use that the relay changes.
func (rc *RobotClient) SetParentNotifier(f func()) {
rc.mu.Lock()
defer rc.mu.Unlock()
rc.notifyParent = f
}
// Connected exposes whether a robot client is connected to the remote.
func (rc *RobotClient) Connected() bool {
rc.mu.RLock()
defer rc.mu.RUnlock()
return rc.connected
}
// Changed watches for whether the remote has changed.
func (rc *RobotClient) Changed() <-chan bool {
rc.mu.Lock()
defer rc.mu.Unlock()
if rc.changeChan == nil {
rc.changeChan = make(chan bool)
}
return rc.changeChan
}
func (rc *RobotClient) connect(ctx context.Context) error {
if rc.conn != nil {
if err := rc.conn.Close(); err != nil {
return err
}
}
conn, err := grpc.Dial(ctx, rc.address, rc.logger, rc.dialOptions...)
if err != nil {
return err
}
rc.mu.Lock()
defer rc.mu.Unlock()
client := pb.NewRobotServiceClient(conn)
refClient := grpcreflect.NewClient(rc.closeContext, reflectpb.NewServerReflectionClient(conn))
rc.conn = conn
rc.client = client
rc.refClient = refClient
rc.connected = true
if len(rc.resourceClients) != 0 {
if err := rc.updateResources(ctx, updateReasonReconnect); err != nil {
return err
}
}
if rc.changeChan != nil {
rc.changeChan <- true
}
if rc.notifyParent != nil {
rc.notifyParent()
}
return nil
}
type updateReason byte
const (
updateReasonReconnect updateReason = iota
updateReasonRefresh
)
func (rc *RobotClient) updateResourceClients(ctx context.Context, reason updateReason) error {
activeResources := make(map[resource.Name]bool)
for _, name := range rc.resourceNames {
activeResources[name] = true
switch reason {
case updateReasonRefresh:
case updateReasonReconnect:
fallthrough
default:
if client, ok := rc.resourceClients[name]; ok {
newClient, err := rc.createClient(name)
if err != nil {
return err
}
currResource, err := resource.ReconfigureResource(ctx, client, newClient)
if err != nil {
return err
}
rc.resourceClients[name] = currResource
}
}
}
for resourceName, client := range rc.resourceClients {
// check if no longer an active resource
if !activeResources[resourceName] {
if err := utils.TryClose(ctx, client); err != nil {
rc.Logger().Error(err)
continue
}
delete(rc.resourceClients, resourceName)
}
}
return nil
}
// checkConnection either checks if the client is still connected, or attempts to reconnect to the remote.
func (rc *RobotClient) checkConnection(ctx context.Context, checkEvery, reconnectEvery time.Duration) {
for {
var waitTime time.Duration
if rc.connected {
waitTime = checkEvery
} else {
if reconnectEvery != 0 {
waitTime = reconnectEvery
} else {
// if reconnectEvery is unset, we will not attempt to reconnect
return
}
}
if !utils.SelectContextOrWait(ctx, waitTime) {
return
}
if !rc.connected {
rc.Logger().Debugw("trying to reconnect to remote at address", "address", rc.address)
if err := rc.connect(ctx); err != nil {
rc.Logger().Debugw("failed to reconnect remote", "error", err, "address", rc.address)
continue
}
rc.Logger().Debugw("successfully reconnected remote at address", "address", rc.address)
} else {
check := func() error {
timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if _, _, err := rc.resources(timeoutCtx); err != nil {
return err
}
return nil
}
var outerError error
for attempt := 0; attempt < 3; attempt++ {
err := check()
if err != nil {
outerError = err
// if pipe is closed, we know for sure we lost connection
if strings.Contains(err.Error(), "read/write on closed pipe") {
break
} else {
// otherwise retry
continue
}
} else {
outerError = nil
break
}
}
if outerError != nil {
rc.Logger().Errorw(
"lost connection to remote",
"error", outerError,
"address", rc.address,
"reconnect_interval", reconnectEvery.Seconds(),
)
rc.mu.Lock()
rc.connected = false
if rc.changeChan != nil {
rc.changeChan <- true
}
if rc.notifyParent != nil {
rc.Logger().Debugf("connection was lost for remote %q", rc.address)
rc.notifyParent()
}
rc.mu.Unlock()
}
}
}
}
// Close cleanly closes the underlying connections and stops the refresh goroutine
// if it is running.
func (rc *RobotClient) Close(ctx context.Context) error {
rc.cancelBackgroundWorkers()
rc.activeBackgroundWorkers.Wait()
if rc.changeChan != nil {
close(rc.changeChan)
rc.changeChan = nil
}
rc.refClient.Reset()
return rc.conn.Close()
}
func (rc *RobotClient) checkConnected() error {
if !rc.connected {
return errors.Errorf("not connected to remote robot at %s", rc.address)
}
return nil
}
// RefreshEvery refreshes the robot on the interval given by every until the
// given context is done.
func (rc *RobotClient) RefreshEvery(ctx context.Context, every time.Duration) {
ticker := time.NewTicker(every)
defer ticker.Stop()
for {
if !utils.SelectContextOrWaitChan(ctx, ticker.C) {
return
}
if err := rc.Refresh(ctx); err != nil {
// we want to keep refreshing and hopefully the ticker is not
// too fast so that we do not thrash.
rc.Logger().Errorw("failed to refresh status", "error", err)
}
}
}
// RemoteByName returns a remote robot by name. It is assumed to exist on the
// other end. Right now this method is unimplemented.
func (rc *RobotClient) RemoteByName(name string) (robot.Robot, bool) {
panic(errUnimplemented)
}
// ResourceByName returns resource by name.
func (rc *RobotClient) ResourceByName(name resource.Name) (interface{}, error) {
rc.mu.RLock()
if err := rc.checkConnected(); err != nil {
rc.mu.RUnlock()
return nil, err
}
// see if a remote name matches the name if so then return the remote client
if val, ok := rc.remoteNameMap[name]; ok {
name = val
}
if client, ok := rc.resourceClients[name]; ok {
rc.mu.RUnlock()
return client, nil
}
rc.mu.RUnlock()
rc.mu.Lock()
defer rc.mu.Unlock()
// one final check but under a more strict lock
if client, ok := rc.resourceClients[name]; ok {
return client, nil
}
resourceClient, err := rc.createClient(name)
if err != nil {
return nil, err
}
rc.resourceClients[name] = resourceClient
return resourceClient, nil
}
func (rc *RobotClient) createClient(name resource.Name) (interface{}, error) {
c := registry.ResourceSubtypeLookup(name.Subtype)
if c == nil || c.RPCClient == nil {
if name.Namespace != resource.ResourceNamespaceRDK {
return grpc.NewForeignResource(name, rc.conn), nil
}
return nil, ErrMissingClientRegistration
}
// pass in conn
nameR := name.ShortName()
resourceClient := c.RPCClient(rc.closeContext, rc.conn, nameR, rc.Logger())
if c.Reconfigurable == nil {
return resourceClient, nil
}
return c.Reconfigurable(resourceClient)
}
func (rc *RobotClient) resources(ctx context.Context) ([]resource.Name, []resource.RPCSubtype, error) {
resp, err := rc.client.ResourceNames(ctx, &pb.ResourceNamesRequest{})
if err != nil {
return nil, nil, err
}
var resTypes []resource.RPCSubtype
typesResp, err := rc.client.ResourceRPCSubtypes(ctx, &pb.ResourceRPCSubtypesRequest{})
if err == nil {
reflSource := grpcurl.DescriptorSourceFromServer(ctx, rc.refClient)
resTypes = make([]resource.RPCSubtype, 0, len(typesResp.ResourceRpcSubtypes))
for _, resSubtype := range typesResp.ResourceRpcSubtypes {
symDesc, err := reflSource.FindSymbol(resSubtype.ProtoService)
if err != nil {
// Note: This happens right now if a client is talking to a main server
// that has a remote or similarly if a server is talking to a remote that
// has a remote. This can be solved by either integrating reflection into
// robot.proto or by overriding the gRPC reflection service to return
// reflection results from its remotes.
rc.Logger().Debugw("failed to find symbol for resource subtype", "subtype", resSubtype, "error", err)
continue
}
svcDesc, ok := symDesc.(*desc.ServiceDescriptor)
if !ok {
return nil, nil, errors.Errorf("expected descriptor to be service descriptor but got %T", symDesc)
}
resTypes = append(resTypes, resource.RPCSubtype{
Subtype: rprotoutils.ResourceNameFromProto(resSubtype.Subtype).Subtype,
Desc: svcDesc,
})
}
} else {
if s, ok := status.FromError(err); !(ok && (s.Code() == codes.Unimplemented)) {
return nil, nil, err
}
}
resources := make([]resource.Name, 0, len(resp.Resources))
for _, name := range resp.Resources {
newName := rprotoutils.ResourceNameFromProto(name)
resources = append(resources, newName)
}
return resources, resTypes, nil
}
// Refresh manually updates the underlying parts of the robot based
// on its metadata response.
func (rc *RobotClient) Refresh(ctx context.Context) (err error) {
rc.mu.Lock()
defer rc.mu.Unlock()
if err := rc.checkConnected(); err != nil {
return err
}
return rc.updateResources(ctx, updateReasonRefresh)
}
func (rc *RobotClient) updateResources(ctx context.Context, reason updateReason) error {
// call metadata service.
names, rpcSubtypes, err := rc.resources(ctx)
// only return if it is not unimplemented - means a bigger error came up
if err != nil && status.Code(err) != codes.Unimplemented {
return err
}
if err == nil {
rc.resourceNames = make([]resource.Name, 0, len(names))
rc.resourceNames = append(rc.resourceNames, names...)
rc.resourceRPCSubtypes = rpcSubtypes
}
rc.updateRemoteNameMap()
return rc.updateResourceClients(ctx, reason)
}
func (rc *RobotClient) updateRemoteNameMap() {
tempMap := make(map[resource.Name]resource.Name)
dupMap := make(map[resource.Name]bool)
for _, n := range rc.resourceNames {
if err := n.Validate(); err != nil {
rc.Logger().Error(err)
continue
}
tempName := resource.RemoveRemoteName(n)
// If the short name already exists in the map then there is a collision and we make the long name empty.
if _, ok := tempMap[tempName]; ok {
dupMap[tempName] = true
} else {
tempMap[tempName] = n
}
}
for key := range dupMap {
delete(tempMap, key)
}
rc.remoteNameMap = tempMap
}
// RemoteNames returns the names of all known remotes.
func (rc *RobotClient) RemoteNames() []string {
return nil
}
// ProcessManager returns a useless process manager for the sake of
// satisfying the robot.Robot interface. Maybe it should not be part
// of the interface!
func (rc *RobotClient) ProcessManager() pexec.ProcessManager {
return pexec.NoopProcessManager
}
// OperationManager returns nil.
func (rc *RobotClient) OperationManager() *operation.Manager {
return nil
}
// ResourceNames returns all resource names.
func (rc *RobotClient) ResourceNames() []resource.Name {
rc.mu.RLock()
defer rc.mu.RUnlock()
if err := rc.checkConnected(); err != nil {
rc.Logger().Errorw("failed to get remote resource names", "error", err)
return nil
}
names := make([]resource.Name, 0, len(rc.resourceNames))
for _, v := range rc.resourceNames {
rName := resource.NewName(v.Namespace, v.ResourceType, v.ResourceSubtype, v.Name)
names = append(
names,
rName.PrependRemote(v.Remote),
)
}
return names
}
// ResourceRPCSubtypes returns a list of all known resource subtypes.
func (rc *RobotClient) ResourceRPCSubtypes() []resource.RPCSubtype {
rc.mu.RLock()
defer rc.mu.RUnlock()
if err := rc.checkConnected(); err != nil {
rc.Logger().Errorw("failed to get remote resource types", "error", err)
return nil
}
subtypes := make([]resource.RPCSubtype, 0, len(rc.resourceRPCSubtypes))
for _, v := range rc.resourceRPCSubtypes {
vCopy := v
subtypes = append(
subtypes,
vCopy,
)
}
return subtypes
}
// Logger returns the logger being used for this robot.
func (rc *RobotClient) Logger() golog.Logger {
return rc.logger
}
// DiscoverComponents takes a list of discovery queries and returns corresponding
// component configurations.
func (rc *RobotClient) DiscoverComponents(ctx context.Context, qs []discovery.Query) ([]discovery.Discovery, error) {
pbQueries := make([]*pb.DiscoveryQuery, 0, len(qs))
for _, q := range qs {
pbQueries = append(
pbQueries,
&pb.DiscoveryQuery{Subtype: string(q.SubtypeName), Model: q.Model},
)
}
resp, err := rc.client.DiscoverComponents(ctx, &pb.DiscoverComponentsRequest{Queries: pbQueries})
if err != nil {
return nil, err
}
discoveries := make([]discovery.Discovery, 0, len(resp.Discovery))
for _, disc := range resp.Discovery {
q := discovery.Query{
SubtypeName: resource.SubtypeName(disc.Query.Subtype),
Model: disc.Query.Model,
}
discoveries = append(
discoveries, discovery.Discovery{
Query: q,
Results: disc.Results.AsMap(),
})
}
return discoveries, nil
}
// FrameSystemConfig returns the info of each individual part that makes up the frame system.
func (rc *RobotClient) FrameSystemConfig(ctx context.Context, additionalTransforms []*commonpb.Transform) (framesystemparts.Parts, error) {
resp, err := rc.client.FrameSystemConfig(ctx, &pb.FrameSystemConfigRequest{
SupplementalTransforms: additionalTransforms,
})
if err != nil {
return nil, err
}
cfgs := resp.GetFrameSystemConfigs()
result := make([]*config.FrameSystemPart, 0, len(cfgs))
for _, cfg := range cfgs {
part, err := config.ProtobufToFrameSystemPart(cfg)
if err != nil {
return nil, err
}
result = append(result, part)
}
return framesystemparts.Parts(result), nil
}
// TransformPose will transform the pose of the requested poseInFrame to the desired frame in the robot's frame system.
func (rc *RobotClient) TransformPose(
ctx context.Context,
query *referenceframe.PoseInFrame,
destination string,
additionalTransforms []*commonpb.Transform,
) (*referenceframe.PoseInFrame, error) {
resp, err := rc.client.TransformPose(ctx, &pb.TransformPoseRequest{
Destination: destination,
Source: referenceframe.PoseInFrameToProtobuf(query),
SupplementalTransforms: additionalTransforms,
})
if err != nil {
return nil, err
}
return referenceframe.ProtobufToPoseInFrame(resp.Pose), nil
}
// Status takes a list of resource names and returns their corresponding statuses. If no names are passed in, return all statuses.
func (rc *RobotClient) Status(ctx context.Context, resourceNames []resource.Name) ([]robot.Status, error) {
names := make([]*commonpb.ResourceName, 0, len(resourceNames))
for _, name := range resourceNames {
names = append(names, rprotoutils.ResourceNameToProto(name))
}
resp, err := rc.client.GetStatus(ctx, &pb.GetStatusRequest{ResourceNames: names})
if err != nil {
return nil, err
}
statuses := make([]robot.Status, 0, len(resp.Status))
for _, status := range resp.Status {
statuses = append(
statuses, robot.Status{
Name: rprotoutils.ResourceNameFromProto(status.Name),
Status: status.Status.AsMap(),
})
}
return statuses, nil
}
// StopAll cancels all current and outstanding operations for the robot and stops all actuators and movement.
func (rc *RobotClient) StopAll(ctx context.Context, extra map[resource.Name]map[string]interface{}) error {
e := []*pb.StopExtraParameters{}
for name, params := range extra {
param, err := protoutils.StructToStructPb(params)
if err != nil {
rc.Logger().Warnf("failed to convert extra params for resource %s with error: %s", name.Name, err)
continue
}
p := &pb.StopExtraParameters{
Name: rprotoutils.ResourceNameToProto(name),
Params: param,
}
e = append(e, p)
}
_, err := rc.client.StopAll(ctx, &pb.StopAllRequest{Extra: e})
return err
}