-
Notifications
You must be signed in to change notification settings - Fork 27
/
comms.go
647 lines (555 loc) · 17.8 KB
/
comms.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
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
// Adapted for Orb project, modifications licensed under MPL v. 2.0:
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
package fleet
import (
"context"
"encoding/json"
"fmt"
"github.com/hashicorp/go-version"
"github.com/mainflux/mainflux/pkg/messaging"
mfnats "github.com/mainflux/mainflux/pkg/messaging/nats"
"github.com/ns1labs/orb/buildinfo"
"github.com/ns1labs/orb/policies/pb"
"go.uber.org/zap"
"time"
)
const publisher = "orb-fleet"
type AgentCommsService interface {
// Start set up communication with the message bus to communicate with agents
Start() error
// Stop end communication with the message bus
Stop() error
// NotifyAgentNewGroupMembership RPC Core -> Agent: Notify a specific Agent of new AgentGroup membership it now belongs to
NotifyAgentNewGroupMembership(a Agent, ag AgentGroup) error
// NotifyAgentGroupMemberships RPC Core -> Agent: Notify a specific Agent of all AgentGroup memberships it belongs to
NotifyAgentGroupMemberships(a Agent) error
// NotifyAgentAllDatasets RPC Core -> Agent: Notify Agent of all Policy it should currently run based on group membership and current Datasets
NotifyAgentAllDatasets(a Agent) error
// NotifyAgentStop RPC Core -> Agent: Notify Agent that it should Stop (Send the message to Agent Channel)
NotifyAgentStop(MFChannelID string, reason string) error
// NotifyGroupNewDataset RPC Core -> Agent: Notify AgentGroup of a newly created Dataset, exposing a new Policy to run
NotifyGroupNewDataset(ctx context.Context, ag AgentGroup, datasetID string, policyID string, ownerID string) error
// NotifyGroupRemoval RPC core -> Agent: Notify AgentGroup that the group has been removed
NotifyGroupRemoval(ag AgentGroup) error
// NotifyGroupPolicyRemoval RPC core -> Agent: Notify AgentGroup that a Policy has been removed
NotifyGroupPolicyRemoval(ag AgentGroup, policyID string, policyName string, backend string) error
// NotifyGroupDatasetRemoval RPC core -> Agent: Notify AgentGroup that a Dataset has been removed
NotifyGroupDatasetRemoval(ag AgentGroup, dsID string, policyID string) error
// NotifyGroupPolicyUpdate RPC core -> Agent: Notify AgentGroup that a Policy has been updated
NotifyGroupPolicyUpdate(ctx context.Context, ag AgentGroup, policyID string, ownerID string) error
}
var _ AgentCommsService = (*fleetCommsService)(nil)
const CapabilitiesTopic = "agent"
const HeartbeatsTopic = "hb"
const RPCToCoreTopic = "tocore"
const RPCFromCoreTopic = "fromcore"
const LogTopic = "log"
type fleetCommsService struct {
logger *zap.Logger
agentRepo AgentRepository
agentGroupRepo AgentGroupRepository
policyClient pb.PolicyServiceClient
// agent comms
agentPubSub mfnats.PubSub
}
func (svc fleetCommsService) NotifyGroupNewDataset(ctx context.Context, ag AgentGroup, datasetID string, policyID string, ownerID string) error {
p, err := svc.policyClient.RetrievePolicy(ctx, &pb.PolicyByIDReq{PolicyID: policyID, OwnerID: ownerID})
if err != nil {
return err
}
var pdata interface{}
if err := json.Unmarshal(p.Data, &pdata); err != nil {
return err
}
payload := []AgentPolicyRPCPayload{{
Action: "manage",
ID: policyID,
Name: p.Name,
Backend: p.Backend,
Version: p.Version,
Data: pdata,
DatasetID: datasetID,
}}
data := RPC{
SchemaVersion: CurrentRPCSchemaVersion,
Func: AgentPolicyRPCFunc,
Payload: payload,
}
body, err := json.Marshal(data)
if err != nil {
return err
}
msg := messaging.Message{
Channel: ag.MFChannelID,
Subtopic: RPCFromCoreTopic,
Publisher: publisher,
Payload: body,
Created: time.Now().UnixNano(),
}
if err := svc.agentPubSub.Publish(msg.Channel, msg); err != nil {
return err
}
return nil
}
func (svc fleetCommsService) NotifyAgentNewGroupMembership(a Agent, ag AgentGroup) error {
payload := GroupMembershipRPCPayload{
Groups: []GroupMembershipData{{Name: ag.Name.String(), ChannelID: ag.MFChannelID}},
FullList: false,
}
data := RPC{
SchemaVersion: CurrentRPCSchemaVersion,
Func: GroupMembershipRPCFunc,
Payload: payload,
}
body, err := json.Marshal(data)
if err != nil {
return err
}
msg := messaging.Message{
Channel: a.MFChannelID,
Subtopic: RPCFromCoreTopic,
Publisher: publisher,
Payload: body,
Created: time.Now().UnixNano(),
}
if err := svc.agentPubSub.Publish(msg.Channel, msg); err != nil {
return err
}
return nil
}
func (svc fleetCommsService) NotifyAgentAllDatasets(a Agent) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
groups, err := svc.agentGroupRepo.RetrieveAllByAgent(ctx, a)
if err != nil {
return err
}
if len(groups) == 0 {
// no groups, nothing to do
return nil
}
groupIDs := make([]string, len(groups))
for i, group := range groups {
groupIDs[i] = group.ID
}
// MQTT he doesn't have OwnerID, we need to look it up
a, err = svc.agentRepo.RetrieveByIDWithChannel(ctx, a.MFThingID, a.MFChannelID)
if err != nil {
return err
}
p, err := svc.policyClient.RetrievePoliciesByGroups(ctx, &pb.PoliciesByGroupsReq{GroupIDs: groupIDs, OwnerID: a.MFOwnerID})
if err != nil {
return err
}
payload := make([]AgentPolicyRPCPayload, len(p.Policies))
for i, policy := range p.Policies {
var pdata interface{}
if err := json.Unmarshal(policy.Data, &pdata); err != nil {
return err
}
payload[i] = AgentPolicyRPCPayload{
Action: "manage",
ID: policy.Id,
Name: policy.Name,
Backend: policy.Backend,
Version: policy.Version,
Data: pdata,
DatasetID: policy.DatasetId,
}
}
data := RPC{
SchemaVersion: CurrentRPCSchemaVersion,
Func: AgentPolicyRPCFunc,
Payload: payload,
}
body, err := json.Marshal(data)
if err != nil {
return err
}
msg := messaging.Message{
Channel: a.MFChannelID,
Subtopic: RPCFromCoreTopic,
Publisher: publisher,
Payload: body,
Created: time.Now().UnixNano(),
}
if err := svc.agentPubSub.Publish(msg.Channel, msg); err != nil {
return err
}
return nil
}
func (svc fleetCommsService) NotifyAgentGroupMemberships(a Agent) error {
list, err := svc.agentGroupRepo.RetrieveAllByAgent(context.Background(), a)
if err != nil {
return err
}
fullList := make([]GroupMembershipData, len(list))
for i, agentGroup := range list {
fullList[i].Name = agentGroup.Name.String()
fullList[i].ChannelID = agentGroup.MFChannelID
}
payload := GroupMembershipRPCPayload{
Groups: fullList,
FullList: true,
}
data := RPC{
SchemaVersion: CurrentRPCSchemaVersion,
Func: GroupMembershipRPCFunc,
Payload: payload,
}
body, err := json.Marshal(data)
if err != nil {
return err
}
msg := messaging.Message{
Channel: a.MFChannelID,
Subtopic: RPCFromCoreTopic,
Publisher: publisher,
Payload: body,
Created: time.Now().UnixNano(),
}
if err := svc.agentPubSub.Publish(msg.Channel, msg); err != nil {
return err
}
return nil
}
func (svc fleetCommsService) NotifyGroupRemoval(ag AgentGroup) error {
payload := GroupRemovedRPCPayload{
AgentGroupID: ag.ID,
ChannelID: ag.MFChannelID,
}
data := RPC{
SchemaVersion: CurrentRPCSchemaVersion,
Func: GroupRemovedRPCFunc,
Payload: payload,
}
body, err := json.Marshal(data)
if err != nil {
return err
}
msg := messaging.Message{
Channel: ag.MFChannelID,
Subtopic: RPCFromCoreTopic,
Publisher: publisher,
Payload: body,
Created: time.Now().UnixNano(),
}
if err := svc.agentPubSub.Publish(msg.Channel, msg); err != nil {
return err
}
return nil
}
func (svc fleetCommsService) NotifyGroupPolicyUpdate(ctx context.Context, ag AgentGroup, policyID string, ownerID string) error {
p, err := svc.policyClient.RetrievePolicy(ctx, &pb.PolicyByIDReq{PolicyID: policyID, OwnerID: ownerID})
if err != nil {
return err
}
var pdata interface{}
if err := json.Unmarshal(p.Data, &pdata); err != nil {
return err
}
payload := []AgentPolicyRPCPayload{{
Action: "manage",
ID: policyID,
Name: p.Name,
Backend: p.Backend,
Version: p.Version,
Data: pdata,
}}
data := RPC{
SchemaVersion: CurrentRPCSchemaVersion,
Func: AgentPolicyRPCFunc,
Payload: payload,
}
body, err := json.Marshal(data)
if err != nil {
return err
}
msg := messaging.Message{
Channel: ag.MFChannelID,
Subtopic: RPCFromCoreTopic,
Publisher: publisher,
Payload: body,
Created: time.Now().UnixNano(),
}
if err := svc.agentPubSub.Publish(msg.Channel, msg); err != nil {
return err
}
return nil
}
func (svc fleetCommsService) NotifyGroupPolicyRemoval(ag AgentGroup, policyID string, policyName string, backend string) error {
var payloads []AgentPolicyRPCPayload
payload := AgentPolicyRPCPayload{
Action: "remove",
ID: policyID,
Name: policyName,
Backend: backend,
}
payloads = append(payloads, payload)
data := AgentPolicyRPC{
SchemaVersion: CurrentRPCSchemaVersion,
Func: AgentPolicyRPCFunc,
Payload: payloads,
}
body, err := json.Marshal(data)
if err != nil {
return err
}
msg := messaging.Message{
Channel: ag.MFChannelID,
Subtopic: RPCFromCoreTopic,
Publisher: publisher,
Payload: body,
Created: time.Now().UnixNano(),
}
if err := svc.agentPubSub.Publish(msg.Channel, msg); err != nil {
return err
}
return nil
}
func (svc fleetCommsService) NotifyGroupDatasetRemoval(ag AgentGroup, dsID string, policyID string) error {
payload := DatasetRemovedRPCPayload{
DatasetID: dsID,
PolicyID: policyID,
}
data := RPC{
SchemaVersion: CurrentRPCSchemaVersion,
Func: DatasetRemovedRPCFunc,
Payload: payload,
}
body, err := json.Marshal(data)
if err != nil {
return err
}
msg := messaging.Message{
Channel: ag.MFChannelID,
Subtopic: RPCFromCoreTopic,
Publisher: publisher,
Payload: body,
Created: time.Now().UnixNano(),
}
if err := svc.agentPubSub.Publish(msg.Channel, msg); err != nil {
return err
}
return nil
}
func (svc fleetCommsService) NotifyAgentStop(MFChannelID string, reason string) error {
payload := AgentStopRPCPayload{Reason: reason}
data := RPC{
SchemaVersion: CurrentRPCSchemaVersion,
Func: AgentStopRPCFunc,
Payload: payload,
}
body, err := json.Marshal(data)
if err != nil {
return err
}
msg := messaging.Message{
Channel: MFChannelID,
Subtopic: RPCFromCoreTopic,
Publisher: publisher,
Payload: body,
Created: time.Now().UnixNano(),
}
if err := svc.agentPubSub.Publish(msg.Channel, msg); err != nil {
return err
}
return nil
}
func NewFleetCommsService(logger *zap.Logger, policyClient pb.PolicyServiceClient, agentRepo AgentRepository, agentGroupRepo AgentGroupRepository, agentPubSub mfnats.PubSub) AgentCommsService {
return &fleetCommsService{
logger: logger,
agentRepo: agentRepo,
agentGroupRepo: agentGroupRepo,
agentPubSub: agentPubSub,
policyClient: policyClient,
}
}
func (svc fleetCommsService) handleCapabilities(thingID string, channelID string, payload []byte) error {
var versionCheck SchemaVersionCheck
if err := json.Unmarshal(payload, &versionCheck); err != nil {
return ErrSchemaMalformed
}
if versionCheck.SchemaVersion != CurrentCapabilitiesSchemaVersion {
return ErrSchemaVersion
}
var capabilities Capabilities
if err := json.Unmarshal(payload, &capabilities); err != nil {
return ErrSchemaMalformed
}
agent := Agent{MFThingID: thingID, MFChannelID: channelID}
agent.AgentMetadata = make(map[string]interface{})
agent.AgentMetadata["backends"] = capabilities.Backends
agent.AgentMetadata["orb_agent"] = capabilities.OrbAgent
agent.AgentTags = capabilities.AgentTags
err := svc.checkVersion(buildinfo.GetMinAgentVersion(), capabilities.OrbAgent.Version, &agent)
if err != nil {
return err
}
err = svc.agentRepo.UpdateDataByIDWithChannel(context.Background(), agent)
if err != nil {
return err
}
return nil
}
func (svc fleetCommsService) checkVersion(minVersion string, agentVersion string, agent *Agent) error {
mVersion, err := version.NewVersion(minVersion)
if err != nil {
return err
}
aVersion, err := version.NewVersion(agentVersion)
if err != nil {
return err
}
if aVersion.LessThan(mVersion) {
svc.NotifyAgentStop(agent.MFChannelID, fmt.Sprintf("The orb-agent version is too old to connect to the control plane. Minimum required version: {%s}", mVersion.String()))
agent.State = UpgradeRequired
}
return nil
}
func (svc fleetCommsService) handleHeartbeat(thingID string, channelID string, payload []byte) error {
var versionCheck SchemaVersionCheck
if err := json.Unmarshal(payload, &versionCheck); err != nil {
return ErrSchemaMalformed
}
if versionCheck.SchemaVersion != CurrentHeartbeatSchemaVersion {
return ErrSchemaVersion
}
var hb Heartbeat
if err := json.Unmarshal(payload, &hb); err != nil {
return ErrSchemaMalformed
}
agent := Agent{MFThingID: thingID, MFChannelID: channelID}
agent.LastHBData = make(map[string]interface{})
// accept "offline" state request to indicate agent is going offline
if hb.State == Offline {
agent.State = Offline
agent.LastHBData["backend_state"] = BackendStateInfo{}
agent.LastHBData["policy_state"] = PolicyStateInfo{}
} else {
// otherwise, state is always "online"
agent.State = Online
agent.LastHBData["backend_state"] = hb.BackendState
agent.LastHBData["policy_state"] = hb.PolicyState
}
err := svc.agentRepo.UpdateHeartbeatByIDWithChannel(context.Background(), agent)
if err != nil {
return err
}
return nil
}
func (svc fleetCommsService) handleRPCToCore(thingID string, channelID string, payload []byte) error {
var versionCheck SchemaVersionCheck
if err := json.Unmarshal(payload, &versionCheck); err != nil {
return ErrSchemaMalformed
}
if versionCheck.SchemaVersion != CurrentRPCSchemaVersion {
return ErrSchemaVersion
}
var rpc RPC
if err := json.Unmarshal(payload, &rpc); err != nil {
return ErrSchemaMalformed
}
// dispatch
switch rpc.Func {
case GroupMembershipReqRPCFunc:
if err := svc.NotifyAgentGroupMemberships(Agent{MFThingID: thingID, MFChannelID: channelID}); err != nil {
svc.logger.Error("notify group membership failure", zap.Error(err))
return nil
}
case AgentPoliciesReqRPCFunc:
if err := svc.NotifyAgentAllDatasets(Agent{MFThingID: thingID, MFChannelID: channelID}); err != nil {
svc.logger.Error("notify agent policies failure", zap.Error(err))
return nil
}
default:
svc.logger.Warn("unsupported/unhandled agent RPC, ignoring",
zap.String("func", rpc.Func),
zap.Any("payload", rpc.Payload))
}
return nil
}
func (svc fleetCommsService) handleMsgFromAgent(msg messaging.Message) error {
// NOTE: we need to consider ALL input from the agent as untrusted, the same as untrusted HTTP API would be
// Given security context is that to get this far we know mainflux MQTT proxy has authenticated a
// username/password/channelID combination (thingID/thingKey/thingChannel which are all UUIDv4)
// channelID is globally unique across all owners and things, and can therefore substitute for an ownerID (which we do not have here)
// mainflux will not allow a thing to communicate on a channelID it does not belong to - thus it is not possible
// to brute force a channelID from another tenant without brute forcing all three UUIDs which is a lot of entropy
var payload map[string]interface{}
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return err
}
svc.logger.Debug("received agent message",
zap.Any("payload", payload),
zap.String("subtopic", msg.Subtopic),
zap.String("channel", msg.Channel),
zap.String("protocol", msg.Protocol),
zap.Int64("created", msg.Created),
zap.String("publisher", msg.Publisher))
if len(msg.Payload) > MaxMsgPayloadSize {
return ErrPayloadTooBig
}
// dispatch
switch msg.Subtopic {
case CapabilitiesTopic:
if err := svc.handleCapabilities(msg.Publisher, msg.Channel, msg.Payload); err != nil {
svc.logger.Error("capabilities failure", zap.Error(err))
return err
}
case HeartbeatsTopic:
if err := svc.handleHeartbeat(msg.Publisher, msg.Channel, msg.Payload); err != nil {
svc.logger.Error("heartbeat failure", zap.Error(err))
return err
}
case RPCToCoreTopic:
if err := svc.handleRPCToCore(msg.Publisher, msg.Channel, msg.Payload); err != nil {
svc.logger.Error("RPC to core failure", zap.Error(err))
return err
}
case LogTopic:
svc.logger.Error("implement me: LogChannel")
default:
svc.logger.Warn("unsupported/unhandled agent subtopic, ignoring",
zap.String("subtopic", msg.Subtopic),
zap.String("thing_id", msg.Publisher),
zap.String("channel_id", msg.Channel))
}
return nil
}
func (svc fleetCommsService) Start() error {
if err := svc.agentPubSub.Subscribe(fmt.Sprintf("channels.*.%s", CapabilitiesTopic), svc.handleMsgFromAgent); err != nil {
return err
}
if err := svc.agentPubSub.Subscribe(fmt.Sprintf("channels.*.%s", HeartbeatsTopic), svc.handleMsgFromAgent); err != nil {
return err
}
if err := svc.agentPubSub.Subscribe(fmt.Sprintf("channels.*.%s", RPCToCoreTopic), svc.handleMsgFromAgent); err != nil {
return err
}
if err := svc.agentPubSub.Subscribe(fmt.Sprintf("channels.*.%s", LogTopic), svc.handleMsgFromAgent); err != nil {
return err
}
svc.logger.Info("subscribed to agent channels")
return nil
}
func (svc fleetCommsService) Stop() error {
if err := svc.agentPubSub.Unsubscribe(fmt.Sprintf("channels.*.%s", CapabilitiesTopic)); err != nil {
return err
}
if err := svc.agentPubSub.Unsubscribe(fmt.Sprintf("channels.*.%s", HeartbeatsTopic)); err != nil {
return err
}
if err := svc.agentPubSub.Unsubscribe(fmt.Sprintf("channels.*.%s", RPCToCoreTopic)); err != nil {
return err
}
if err := svc.agentPubSub.Unsubscribe(fmt.Sprintf("channels.*.%s", LogTopic)); err != nil {
return err
}
svc.logger.Info("unsubscribed from agent channels")
return nil
}