-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathservice.go
More file actions
2215 lines (1969 loc) · 59.3 KB
/
Copy pathservice.go
File metadata and controls
2215 lines (1969 loc) · 59.3 KB
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0
package agent
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
"net/url"
"os"
"regexp"
"runtime/metrics"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
cfgstore "github.com/absmach/agent/pkg/config"
"github.com/absmach/agent/pkg/devicemgr"
"github.com/absmach/agent/pkg/health"
"github.com/absmach/agent/pkg/iface"
"github.com/absmach/agent/pkg/nodered"
"github.com/absmach/agent/pkg/ota"
"github.com/absmach/agent/pkg/senml"
"github.com/absmach/agent/pkg/terminal"
"github.com/absmach/magistrala/pkg/errors"
paho "github.com/eclipse/paho.mqtt.golang"
toml "github.com/pelletier/go-toml"
)
const (
// Reset modes for the Reset method.
ResetGraceful = "graceful"
ResetImmediate = "immediate"
ResetWatchdog = "watchdog"
ResetNow = "now"
Commands = "commands"
config = "config"
view = "view"
save = "save"
char = "char"
open = "open"
close = "close"
control = "control"
data = "data"
// control subcommands for agent lifecycle management.
ctrlStop = "stop"
ctrlStart = "start"
ctrlReload = "reload"
ctrlStatus = "status"
// Exported aliases for use by the HTTP API layer.
CtrlStop = ctrlStop
CtrlStart = ctrlStart
CtrlReload = ctrlReload
export = "export"
KeyLogLevel = "log_level"
KeyHeartbeatInterval = "heartbeat_interval"
KeyTelemetryInterval = "telemetry_interval"
KeyTerminalSessionTimeout = "terminal_session_timeout"
KeyCommandSecret = "command_secret"
KeyBsValid = "bs_valid"
keyLogLevel = KeyLogLevel
keyHeartbeatInterval = KeyHeartbeatInterval
keyTelemetryInterval = KeyTelemetryInterval
keyTerminalSessionTimeout = KeyTerminalSessionTimeout
keyCommandSecret = KeyCommandSecret
keyBsValid = KeyBsValid
keyTenantID = "tenant_id"
keyChannelsCtrlID = "channels_ctrl_id"
keyChannelsDataID = "channels_data_id"
keyMqttURL = "mqtt_url"
keyMqttUsername = "mqtt_username"
keyMqttPassword = "mqtt_password"
keyMQTTPassword = "mqtt_password"
keyProvisionToken = "provision_token"
notConfigured = "not_configured"
notFound = "not_found"
senmlNameUptime = "uptime"
notAllowed = "not_allowed"
// senmlBaseGateway is the SenML base name used for gateway-scoped records.
senmlBaseGateway = "gw:"
provisionTimeout = 30 * time.Second
)
var (
startTime = time.Now()
// Version is the agent binary version, injected at build time via
// -ldflags "-X github.com/absmach/agent.Version=x.y.z".
Version = "0.0.0"
Commit = "unknown"
BuildTime = "unknown"
heapSamples = []metrics.Sample{{Name: "/memory/classes/heap/free:bytes"}}
)
var (
// errInvalidCommand indicates malformed command.
errInvalidCommand = errors.New("invalid command")
// ErrMalformedEntity indicates malformed entity specification.
ErrMalformedEntity = errors.ErrMalformedEntity
// ErrInvalidQueryParams indicates malformed URL.
ErrInvalidQueryParams = errors.New("invalid query params")
// errUnknownCommand indicates that command is not found.
errUnknownCommand = errors.New("Unknown command")
// errNoSuchService indicates service not supported.
errNoSuchService = errors.New("no such service")
// errFailedEncode indicates error in encoding.
errFailedEncode = errors.New("failed to encode")
// errFailedToPublish.
errFailedToPublish = errors.New("failed to publish")
// errFailedToCreateTerminalSession.
errFailedToCreateTerminalSession = errors.New("failed to create terminal session")
// errNoSuchTerminalSession terminal session doesnt exist error on closing.
errNoSuchTerminalSession = errors.New("no such terminal session")
// errNodeRedFailed.
errNodeRedFailed = errors.New("failed to execute node-red operation")
// errDeviceManagerFailed.
errDeviceManagerFailed = errors.New("device manager operation failed")
// errDeviceManagerDisabled indicates device manager is not configured.
errDeviceManagerDisabled = errors.New("device manager not configured")
// errRouteFailed indicates a failure routing a command to a downstream device.
errRouteFailed = errors.New("failed to route command to device")
)
// DeviceService groups the downstream-device management methods of Service.
// Handlers or components that only manage devices can depend on this narrower interface.
type DeviceService interface {
// DeviceManager handles downstream device registration and provisioning commands.
DeviceManager(ctx context.Context, uuid, cmdStr string) error
// ListDevices returns all registered downstream devices.
ListDevices() ([]devicemgr.Device, error)
// GetDevice returns a single downstream device by ID.
GetDevice(id string) (devicemgr.Device, error)
// AddDevice provisions and registers a new downstream device.
AddDevice(ctx context.Context, name, extID, extKey, ifaceType, ifaceAddr string) (devicemgr.Device, error)
// RemoveDevice removes a downstream device by ID.
RemoveDevice(id string) error
// MarkDeviceSeen records a live heartbeat for a downstream device.
MarkDeviceSeen(id string) error
// BackupDevices returns a portable snapshot of the downstream device registry.
BackupDevices() (devicemgr.Backup, error)
// RestoreDevices loads a device registry snapshot. When replace is true the
// existing registry is cleared first. It returns the number of devices written.
RestoreDevices(b devicemgr.Backup, replace bool) (int, error)
}
// Service specifies API for publishing messages and subscribing to topics.
type Service interface {
// Control command.
Control(uuid, cmdStr string) error
// Route forwards a raw payload to a downstream device's physical interface
// and publishes the device's response. cmdStr is comma-delimited:
// <device_id>,<hex_payload>[,<read_bytes>].
Route(ctx context.Context, uuid, cmdStr string) error
// Update configuration file.
AddConfig(Config) error
// Config returns Config struct created from config file.
Config() Config
// CommandSecret returns the current command secret for inbound MQTT command validation.
CommandSecret() string
// Saves config file.
ServiceConfig(ctx context.Context, uuid, cmdStr string) error
// Services returns service list.
Services() []Info
// Terminal used for terminal control of gateway.
Terminal(uuid, cmdStr string) error
// Publish message.
Publish(topic, payload string) error
// Ping publishes an immediate heartbeat SenML record to the data channel
// under the gateway/heartbeat topic, matching the periodic self-heartbeat format.
Ping() error
// NodeRed manages Node-RED flow operations.
NodeRed(cmdStr string) (string, error)
// UpdateLiveness registers or refreshes the liveness of a local service from
// an authenticated MQTT heartbeat message.
UpdateLiveness(svcname, svctype string) error
// RegisterService manually registers a local service so that it appears on
// the services list immediately, regardless of MQTT heartbeats.
RegisterService(svcname, svctype string) error
// RemoveService removes a previously registered service from the services list.
RemoveService(svcname string) error
// OTA triggers an over-the-air binary update by downloading from url.
OTA(ctx context.Context, url, sha256hex string, size uint64) error
// OTAFromData installs firmware from a binary payload received via MQTT.
// sha256hex must be the hex-encoded SHA-256 of data.
OTAFromData(ctx context.Context, data []byte, sha256hex string) error
// Reset performs a reset in the given mode. Supported modes are:
// - "graceful" – clean shutdown, save state, close connections, then exec
// - "immediate" – emergency reset with minimal cleanup, then exec
// - "watchdog" – notify the health supervisor to trigger a watchdog reset
// - "now" – alias for "immediate"
// The caller is responsible for calling syscall.Exec after a successful
// graceful or immediate reset (watchdog is handled by the supervisor).
Reset(ctx context.Context, mode string) error
// Shutdown performs a graceful shutdown: stops all service heartbeat
// tickers and disconnects the MQTT client.
Shutdown()
// OTAStatus returns whether an OTA operation is currently in progress and the last error message, if any.
OTAStatus() OTAStatusInfo
// Telemetry returns the current gateway telemetry readings (live snapshot).
Telemetry() TelemetryData
// OTAAbort cancels an in-progress OTA update. It returns an error if no OTA is running.
OTAAbort() error
// OpenDevice opens the physical interface for a registered downstream device.
OpenDevice(ctx context.Context, id string) error
// CloseDevice closes the physical interface for a registered downstream device.
CloseDevice(id string) error
// ReadDevice reads up to n bytes from the open interface of the given device.
ReadDevice(id string, n int) ([]byte, error)
// WriteDevice sends hex-encoded data to the open interface of the given device.
WriteDevice(id, hexData string) (int, error)
// GetRuntimeConfig returns the value of a single runtime-configurable key.
GetRuntimeConfig(key string) (string, error)
// SetRuntimeConfig sets a runtime-configurable key to the given value.
SetRuntimeConfig(ctx context.Context, key, value string) error
// SetPushEvent registers a callback invoked when a subsystem state changes
// (e.g. OTA progress, config updates, device list changes) so the HTTP API
// can push real-time WebSocket events to connected UI clients.
SetPushEvent(fn func(string))
// Health returns whether the agent is currently healthy according to the
// health supervisor. Returns true when the supervisor is disabled.
Health() bool
DeviceService
}
// OTAStatusInfo reports the current state of the OTA subsystem. The progress
// fields mirror the retained MQTT status message so HTTP clients can render a
// live progress bar without subscribing to MQTT.
type OTAStatusInfo struct {
Busy bool `json:"busy"`
State string `json:"state,omitempty"`
Bytes int64 `json:"bytes"`
Total int64 `json:"total"`
Progress float64 `json:"progress"`
LastError string `json:"last_error,omitempty"`
}
// TelemetryData holds the current gateway telemetry readings.
type TelemetryData struct {
Uptime float64 `json:"uptime"`
MemTotal uint64 `json:"mem_total,omitempty"`
MemAvailable uint64 `json:"mem_available,omitempty"`
MemUsed uint64 `json:"mem_used,omitempty"`
CPUTemperature *float64 `json:"cpu_temperature,omitempty"`
RSSI *float64 `json:"rssi,omitempty"`
LoadAvg1m *float64 `json:"load_avg_1m,omitempty"`
LoadAvg5m *float64 `json:"load_avg_5m,omitempty"`
LoadAvg15m *float64 `json:"load_avg_15m,omitempty"`
DiskUsagePct *float64 `json:"disk_usage_percent,omitempty"`
DevicesActive *int `json:"devices_active,omitempty"`
}
var _ Service = (*agent)(nil)
type agent struct {
ctx context.Context
mqttClient paho.Client
config *Config
noderedClient nodered.Client
logger *slog.Logger
svcs map[string]Heartbeat
svcsMu sync.RWMutex
terminals map[string]terminal.Session
termMu sync.Mutex
devices *devicemgr.Manager
sched *Scheduler
pushEvent func(typeName string)
otaBusy atomic.Bool
store cfgstore.Store
heartbeatIntervalCh chan time.Duration
telemetryIntervalCh chan time.Duration
telemetryStarted atomic.Bool
logLevel *slog.LevelVar
cfgMu sync.RWMutex
startupConfig Config
otaMu sync.Mutex
otaLastErr string
otaCancel context.CancelFunc
otaAborted atomic.Bool
otaState string
otaBytes int64
otaTotal int64
otaProgress float64
bootstrapCachePath string
runCtx context.Context
paused atomic.Bool
health *health.Supervisor
}
// New returns agent service implementation.
func New(ctx context.Context, mc paho.Client, cfg *Config, nc nodered.Client, logger *slog.Logger, devices *devicemgr.Manager, store cfgstore.Store, levelVar *slog.LevelVar, bootstrapCachePath string, sup *health.Supervisor) (Service, error) {
ag := &agent{
ctx: ctx,
mqttClient: mc,
noderedClient: nc,
config: cfg,
logger: logger,
svcs: make(map[string]Heartbeat),
terminals: make(map[string]terminal.Session),
devices: devices,
store: store,
heartbeatIntervalCh: make(chan time.Duration, 1),
telemetryIntervalCh: make(chan time.Duration, 1),
logLevel: levelVar,
startupConfig: *cfg,
bootstrapCachePath: bootstrapCachePath,
runCtx: ctx,
health: sup,
}
if devices != nil {
sched := newScheduler(devices, cfg.MQTT, cfg.TenantID, logger)
if err := sched.Start(ctx); err != nil {
logger.Warn("Failed to start device scheduler", slog.Any("error", err))
}
ag.sched = sched
}
topic := fmt.Sprintf("m/%s/c/%s/gateway/heartbeat",
cfg.TenantID, cfg.Channels.DataChan())
go ag.selfHeartbeat(ctx, topic, cfg.Heartbeat.Interval, cfg.MQTT.QoS)
if cfg.Telemetry.Interval > 0 {
telemetryTopic := fmt.Sprintf("m/%s/c/%s/gateway/telemetry",
cfg.TenantID, cfg.Channels.DataChan())
ag.telemetryStarted.Store(true)
go ag.selfTelemetry(ctx, telemetryTopic, cfg.Telemetry.Interval, cfg.MQTT.QoS)
}
return ag, nil
}
func (a *agent) SetPushEvent(fn func(string)) {
a.pushEvent = fn
}
func (a *agent) Health() bool {
if a.health == nil {
return true
}
return a.health.IsHealthy()
}
func (a *agent) Control(uuid, cmdStr string) error {
cmdArgs := strings.Split(strings.ReplaceAll(cmdStr, " ", ""), ",")
if len(cmdArgs) < 1 || cmdArgs[0] == "" {
return errInvalidCommand
}
var resp string
var err error
cmd := cmdArgs[0]
switch {
case cmd == ctrlStop:
resp = a.controlStop()
case cmd == ctrlStart:
resp = a.controlStart()
case cmd == ctrlReload:
resp = a.controlReload()
case cmd == ctrlStatus:
resp, err = a.controlStatus()
case strings.HasPrefix(cmd, "nodered-"):
resp, err = a.NodeRed(cmdStr)
default:
err = errUnknownCommand
}
if err != nil {
return err
}
return a.processResponse(uuid, cmd, resp)
}
// controlStop pauses the agent's background publishing loops (heartbeat and
// telemetry) and stops the per-device scheduler. The process stays alive so a
// subsequent control,start can resume it.
func (a *agent) controlStop() string {
a.paused.Store(true)
if a.sched != nil {
a.sched.Stop()
}
a.logger.Info("Agent paused via control command")
return "stopped"
}
// controlStart resumes the background publishing loops and restarts the
// per-device scheduler using the agent's run context. The scheduler context
// descends from the process context passed to New so device goroutines still
// terminate on shutdown; if that context is already cancelled (process is
// shutting down) the scheduler is not restarted.
func (a *agent) controlStart() string {
a.paused.Store(false)
switch {
case a.sched == nil:
// No device scheduler configured; nothing to restart.
case a.runCtx == nil || a.runCtx.Err() != nil:
a.logger.Warn("Run context unavailable; device scheduler not restarted",
slog.Any("error", contextErr(a.runCtx)))
default:
if err := a.sched.Start(a.runCtx); err != nil {
a.logger.Warn("Failed to restart device scheduler", slog.Any("error", err))
}
}
a.logger.Info("Agent resumed via control command")
return "started"
}
// contextErr returns ctx.Err() guarding against a nil context.
func contextErr(ctx context.Context) error {
if ctx == nil {
return context.Canceled
}
return ctx.Err()
}
// controlReload re-applies persisted runtime config overrides from the store so
// that out-of-band changes to the store take effect without a restart. Each
// value is validated before being applied; invalid entries (e.g. from manual
// file edits) are skipped and logged. The response lists the keys that were
// applied for auditability.
func (a *agent) controlReload() string {
if a.store == nil {
return notConfigured
}
var applied []string
for key, val := range a.store.All() {
if !settableKeys[key] {
continue
}
if err := validateSettableValue(key, val); err != nil {
a.logger.Warn("Skipping invalid persisted config value on reload",
slog.String("key", key), slog.Any("error", err))
continue
}
a.cfgMu.Lock()
ApplyConfigEntry(a.config, key, val)
a.cfgMu.Unlock()
a.applyLiveUpdate(key, val)
applied = append(applied, key)
}
sort.Strings(applied)
a.logger.Info("Agent config reloaded via control command", slog.Any("applied", applied))
if len(applied) == 0 {
return "reloaded"
}
return "reloaded:" + strings.Join(applied, ",")
}
// controlStatus reports the agent's current runtime state as a JSON document.
func (a *agent) controlStatus() (string, error) {
status := struct {
Running bool `json:"running"`
Paused bool `json:"paused"`
UptimeSeconds float64 `json:"uptime_seconds"`
Version string `json:"version"`
}{
Running: true,
Paused: a.paused.Load(),
UptimeSeconds: time.Since(startTime).Seconds(),
Version: Version,
}
b, err := json.Marshal(status)
if err != nil {
return "", errors.New(err.Error())
}
return string(b), nil
}
// Route forwards a raw payload to a downstream device's physical interface and
// publishes the device's response. cmdStr is comma-delimited:
//
// <device_id>,<hex_payload>[,<read_bytes>]
//
// The interface is opened if not already open, the hex payload is written, and
// when read_bytes is supplied (0 < n <= 65536) that many bytes are read back
// and returned as a hex string. With no read_bytes, the number of bytes written
// is returned.
func (a *agent) Route(_ context.Context, uuid, cmdStr string) error {
if a.devices == nil {
return errors.Wrap(errRouteFailed, errDeviceManagerDisabled)
}
args := strings.Split(strings.ReplaceAll(cmdStr, " ", ""), ",")
if len(args) < 2 || args[0] == "" || args[1] == "" {
return errors.Wrap(errRouteFailed, errInvalidCommand)
}
deviceID, hexPayload := args[0], args[1]
readBytes := 0
if len(args) >= 3 && args[2] != "" {
n, perr := strconv.Atoi(args[2])
if perr != nil || n <= 0 || n > 65536 {
return errors.Wrap(errRouteFailed, errInvalidCommand)
}
readBytes = n
}
// Resolve the device first so a missing device returns a clear error rather
// than surfacing as an opaque interface-open failure.
if _, err := a.devices.Get(deviceID); err != nil {
return errors.Wrap(errRouteFailed, err)
}
if err := a.devices.OpenIface(deviceID); err != nil {
return errors.Wrap(errRouteFailed, err)
}
written, err := a.devices.WriteIface(deviceID, hexPayload)
if err != nil {
return errors.Wrap(errRouteFailed, err)
}
resp := strconv.Itoa(written)
if readBytes > 0 {
read, rerr := a.devices.ReadIface(deviceID, readBytes)
if rerr != nil {
return errors.Wrap(errRouteFailed, rerr)
}
resp = fmt.Sprintf("%x", read)
}
return a.processResponse(uuid, "route", resp)
}
// Message for this command
// [{"bn":"1:", "n":"services", "vs":"view"}]
// [{"bn":"1:", "n":"config", "vs":"save, export, filename, filecontent"}]
// config_file_content is base64 encoded marshaled structure representing service conf
// Example of creation:
//
// b, _ := toml.Marshal(cfg)
// config_file_content := base64.StdEncoding.EncodeToString(b).
func (a *agent) ServiceConfig(ctx context.Context, uuid, cmdStr string) error {
rawParts := strings.Split(cmdStr, ",")
cmdArgs := make([]string, len(rawParts))
for i, p := range rawParts {
cmdArgs[i] = strings.TrimSpace(p)
}
if len(cmdArgs) < 1 {
return errInvalidCommand
}
resp := ""
cmd := cmdArgs[0]
switch cmd {
case view:
services, err := json.Marshal(a.Services())
if err != nil {
return errors.New(err.Error())
}
resp = string(services)
case save:
if len(cmdArgs) < 4 {
return errInvalidCommand
}
service := cmdArgs[1]
fileName := cmdArgs[2]
fileCont := cmdArgs[3]
if err := a.saveConfig(ctx, service, fileName, fileCont); err != nil {
return err
}
case "get":
if len(cmdArgs) < 2 || cmdArgs[1] == "" {
return errInvalidCommand
}
key := cmdArgs[1]
if key == keyCommandSecret {
if a.store == nil {
resp = notConfigured
} else if _, ok := a.store.Get(key); ok {
resp = "REDACTED"
} else {
resp = notFound
}
} else if credentialKeys[key] {
resp = notAllowed
} else if !settableKeys[key] {
resp = notFound
} else if a.store == nil {
resp = notConfigured
} else if val, ok := a.store.Get(key); ok {
resp = val
} else if fallback := a.configFallback(key); fallback != "" {
resp = fallback
} else {
resp = notFound
}
case "set":
if len(cmdArgs) < 3 || cmdArgs[1] == "" || cmdArgs[2] == "" {
return errInvalidCommand
}
key, val := cmdArgs[1], cmdArgs[2]
if !settableKeys[key] {
resp = notFound
} else {
if err := validateSettableValue(key, val); err != nil {
return err
}
if a.store == nil {
resp = notConfigured
} else {
if err := a.store.Set(key, val); err != nil {
return err
}
a.cfgMu.Lock()
ApplyConfigEntry(a.config, key, val)
a.cfgMu.Unlock()
a.applyLiveUpdate(key, val)
resp = "ok"
}
}
case "reset":
if len(cmdArgs) < 2 || cmdArgs[1] == "" {
return errInvalidCommand
}
key := cmdArgs[1]
if !settableKeys[key] {
resp = notFound
} else if a.store == nil {
resp = notConfigured
} else {
if err := a.store.Remove(key); err != nil {
return err
}
a.revertToStartup(key)
resp = "ok"
}
default:
return errInvalidCommand
}
return a.processResponse(uuid, cmd, resp)
}
func (a *agent) Terminal(uuid, cmdStr string) error {
b, err := base64.StdEncoding.DecodeString(cmdStr)
if err != nil {
return errors.New(err.Error())
}
cmdArgs := strings.Split(string(b), ",")
if len(cmdArgs) < 1 {
return errInvalidCommand
}
cmd := cmdArgs[0]
ch := ""
if len(cmdArgs) > 1 {
ch = cmdArgs[1]
}
cfg := a.Config()
switch cmd {
case char:
if err := a.terminalWrite(uuid, ch); err != nil {
return err
}
case open:
if err := a.terminalOpen(uuid, cfg.Terminal.SessionTimeout); err != nil {
return err
}
case close:
if err := a.terminalClose(uuid); err != nil {
return err
}
}
return nil
}
func (a *agent) terminalOpen(uuid string, timeout time.Duration) error {
a.termMu.Lock()
defer a.termMu.Unlock()
if _, ok := a.terminals[uuid]; !ok {
term, err := terminal.NewSession(uuid, timeout, a.Publish, a.logger)
if err != nil {
return errors.Wrap(errors.Wrap(errFailedToCreateTerminalSession, fmt.Errorf(" for %s", uuid)), err)
}
a.terminals[uuid] = term
go func() {
for range term.IsDone() {
a.termMu.Lock()
delete(a.terminals, uuid)
a.termMu.Unlock()
return
}
}()
}
return nil
}
func (a *agent) terminalClose(uuid string) error {
a.termMu.Lock()
defer a.termMu.Unlock()
if _, ok := a.terminals[uuid]; ok {
delete(a.terminals, uuid)
return nil
}
return errors.Wrap(errNoSuchTerminalSession, fmt.Errorf("session :%s", uuid))
}
func (a *agent) terminalWrite(uuid, cmd string) error {
if err := a.terminalOpen(uuid, a.Config().Terminal.SessionTimeout); err != nil {
return err
}
a.termMu.Lock()
term := a.terminals[uuid]
a.termMu.Unlock()
return term.Send([]byte(cmd))
}
func (a *agent) NodeRed(cmdStr string) (string, error) {
cmdArgs := strings.Split(strings.ReplaceAll(cmdStr, " ", ""), ",")
cmd := cmdArgs[0]
if cmd == "" {
return "", errInvalidCommand
}
var resp string
var err error
switch cmd {
case "nodered-deploy":
if len(cmdArgs) < 2 || cmdArgs[1] == "" {
return "", errInvalidCommand
}
flowData, decErr := base64.StdEncoding.DecodeString(cmdArgs[1])
if decErr != nil {
return "", errors.Wrap(errNodeRedFailed, decErr)
}
resp, err = a.noderedClient.DeployFlows(a.normalizeNodeRedFlow(string(flowData)))
case "nodered-add-flow":
if len(cmdArgs) < 2 || cmdArgs[1] == "" {
return "", errInvalidCommand
}
flowData, decErr := base64.StdEncoding.DecodeString(cmdArgs[1])
if decErr != nil {
return "", errors.Wrap(errNodeRedFailed, decErr)
}
resp, err = a.noderedClient.AddFlow(a.normalizeNodeRedFlow(string(flowData)))
case "nodered-flows":
resp, err = a.noderedClient.FetchFlows()
case "nodered-state":
resp, err = a.noderedClient.FlowState()
case "nodered-ping":
resp, err = a.noderedClient.Ping()
default:
err = errUnknownCommand
}
if err != nil {
return "", errors.Wrap(errNodeRedFailed, err)
}
return resp, nil
}
// normalizeNodeRedFlow updates deployed flow JSON so Node-RED follows the same
// MQTT target and credentials as the agent runtime config.
func (a *agent) normalizeNodeRedFlow(flowJSON string) string {
var payload any
if err := json.Unmarshal([]byte(flowJSON), &payload); err != nil {
return flowJSON
}
cfg := a.Config()
host, port, useTLS := nodeRedMQTTEndpoint(cfg.MQTT.URL)
dataChannel := cfg.Channels.DataChan()
brokerIDs := map[string]struct{}{}
patchNodeRedValue(payload, func(node map[string]any) {
nodeType, _ := node["type"].(string)
switch nodeType {
case "mqtt-broker":
id, _ := node["id"].(string)
if id != "" {
brokerIDs[id] = struct{}{}
}
if host != "" {
node["broker"] = host
}
node["port"] = port
node["gatewayid"] = cfg.MQTT.Username + "-nr"
node["usetls"] = useTLS
if useTLS && cfg.MQTT.SkipTLSVer {
node["tls"] = nodeRedTLSConfigID
} else {
delete(node, "tls")
}
node["credentials"] = map[string]any{
"user": cfg.MQTT.Username,
"password": cfg.MQTT.Password,
}
case "function":
if fn, ok := node["func"].(string); ok {
node["func"] = patchNodeRedTopic(fn, cfg.TenantID, dataChannel)
}
}
if topic, ok := node["topic"].(string); ok {
node["topic"] = patchNodeRedTopic(topic, cfg.TenantID, dataChannel)
}
})
if len(brokerIDs) == 1 {
var brokerID string
for id := range brokerIDs {
brokerID = id
}
patchNodeRedValue(payload, func(node map[string]any) {
nodeType, _ := node["type"].(string)
if nodeType != "mqtt out" {
return
}
ref, _ := node["broker"].(string)
if _, ok := brokerIDs[ref]; !ok {
node["broker"] = brokerID
}
})
}
if useTLS && cfg.MQTT.SkipTLSVer {
payload = ensureNodeRedTLSConfig(payload)
}
b, err := json.Marshal(payload)
if err != nil {
return flowJSON
}
return string(b)
}
const nodeRedTLSConfigID = "magistrala-agent-tls"
var nodeRedTopicPattern = regexp.MustCompile(`m/[^/"'\s]*/c/[^/"'\s]*/(?:data|gateway/telemetry)`)
func nodeRedMQTTEndpoint(rawURL string) (host, port string, useTLS bool) {
if rawURL == "" {
return "", "1883", false
}
parsed, err := url.Parse(rawURL)
if err != nil || parsed.Host == "" {
host = rawURL
if strings.Contains(host, "://") {
host = strings.SplitN(host, "://", 2)[1]
}
if idx := strings.Index(host, "/"); idx >= 0 {
host = host[:idx]
}
if strings.Contains(host, ":") {
parts := strings.Split(host, ":")
return parts[0], parts[len(parts)-1], false
}
return host, "1883", false
}
host = parsed.Hostname()
port = parsed.Port()
if port == "" {
port = "1883"
}
switch parsed.Scheme {
case "ssl", "tls", "mqtts":
useTLS = true
}
return host, port, useTLS
}
func patchNodeRedTopic(value, tenantID, channelID string) string {
if tenantID == "" || channelID == "" {
return value
}
return nodeRedTopicPattern.ReplaceAllString(value, fmt.Sprintf("m/%s/c/%s/gateway/telemetry", tenantID, channelID))
}
func patchNodeRedValue(value any, patch func(map[string]any)) {
switch typed := value.(type) {
case []any:
for _, item := range typed {
patchNodeRedValue(item, patch)
}
case map[string]any:
patch(typed)
for _, item := range typed {
patchNodeRedValue(item, patch)
}
}
}
func ensureNodeRedTLSConfig(payload any) any {
tlsNode := map[string]any{
"id": nodeRedTLSConfigID,
"type": "tls-config",
"name": "Magistrala MQTT TLS",
"cert": "",
"key": "",
"ca": "",
"certname": "",
"keyname": "",
"caname": "",
"servername": "",
"verifyservercert": false,
"alpnprotocol": "",
}
switch typed := payload.(type) {
case []any:
for _, item := range typed {
node, ok := item.(map[string]any)
if ok && node["id"] == nodeRedTLSConfigID {
return payload
}
}
return append(typed, tlsNode)
case map[string]any:
configs, _ := typed["configs"].([]any)
for _, item := range configs {
node, ok := item.(map[string]any)
if ok && node["id"] == nodeRedTLSConfigID {
return payload
}
}
typed["configs"] = append(configs, tlsNode)
return typed
default:
return payload
}
}
func (a *agent) processResponse(uuid, cmd, resp string) error {
payload, err := senml.EncodeString(uuid, cmd, resp)
if err != nil {
return errors.Wrap(errFailedEncode, err)
}
if err := a.publishCmd(control, string(payload)); err != nil {