Compare commits

..
Author SHA1 Message Date
Cédric VerstraetenandClaude Opus 5.5 a37c5b1623 Tell the Hub which settings come from environment variables
The agent applies AGENT_* (and, in ConfigMap mode, GLOBAL_AGENT_*)
environment variables again on every start. A remote-config change the Hub
saves to such a setting is written to config.json and then undone at the
next restart; in ConfigMap mode config.json is ignored entirely.

receive-config now carries "env_managed": {"all": bool, "paths": [...]}:
"all" in ConfigMap mode, and the JSON paths of the settings set by
environment variables (e.g. "capture.ipcamera.rtsp"), so the Hub can show
them read-only. It is omitted when no setting comes from the environment.

envConfigFields maps each AGENT_* variable to the Config field it sets;
tests keep it in step with applyAgentEnvVars.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:19:34 +00:00
Cédric Verstraeten 3d65b42f32 Merge pull request #368 from EpicMouse123/feature/region-multi-polygon
Support multiple polygons in AGENT_REGION_POLYGON
2026-11-27 11:54:50 +01:00
adam.witwickiandClaude Opus 5.5 59f43d2877 Support multiple polygons in AGENT_REGION_POLYGON
AGENT_REGION_POLYGON could only describe one motion region, although
motion detection already evaluates several regions independently. This
left agents configured through environment variables (ConfigMap mode)
unable to use multiple regions.

Polygons can now be separated by "|":

  AGENT_REGION_POLYGON="64,36;576,36;608,324;32,324|700,40;900,40;900,300"

Each part becomes its own polygon with IDs "0", "1", ... assigned in
order. Empty parts and parts with fewer than 3 valid points are skipped.
A value without "|" parses as before.

Closes #366

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:15:00 +00:00
Cédric Verstraeten 5b134731fa Merge pull request #364 from kerberos-io/feat/mqtt-failover-brokers
mqtt: support ActiveMQ failover URIs with multiple brokers
2026-11-23 21:19:17 +01:00
cedricveandClaude Opus 5.5 33cc8a46ed mqtt: keep commas that are part of a single broker URI
Splitting the MQTT URI on every comma broke previously valid single-broker
URIs with commas in the query string, credentials or path (for example
wss://broker/mqtt?token=a,b). A comma now only separates brokers when the
text after it starts with a URI scheme ("scheme://"); other commas stay in
the current broker URI. Adds regression cases for these URIs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 20:06:08 +00:00
cedricveandClaude Opus 5.5 7d70361870 mqtt: support ActiveMQ failover URIs with multiple brokers
The MQTT URI can now list several brokers, either as an ActiveMQ-style
failover URI (as used by Amazon MQ active/standby brokers) or as a plain
comma-separated list:

  failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)

Each broker is registered with paho, which tries them in order on
connect and reconnect. Transport options after the closing parenthesis
are ignored. The diagnostics dialer is only installed when every broker
uses a TCP-based scheme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:55:47 +00:00
7 changed files with 631 additions and 46 deletions
+1 -1
View File
@@ -336,7 +336,7 @@ Notes:
| `AGENT_AUTO_CLEAN_MIN_FREE_SPACE` | When `AUTO_CLEAN` is enabled and no `MAX_SIZE` is set, keep at least this much free space (in MB) on the recordings disk before deleting the oldest (already-uploaded first) recordings. Defaults to 5% of the disk. | "" |
| `AGENT_TIME` | Enable the timetable for Kerberos Agent | "false" |
| `AGENT_TIMETABLE` | A (weekly) time table to specify when to make recordings "start1,end1,start2,end2;start1.. | "" |
| `AGENT_REGION_POLYGON` | A single polygon set for motion detection: "x1,y1;x2,y2;x3,y3;... | "" |
| `AGENT_REGION_POLYGON` | One or more polygons for motion detection. Points are "x,y" separated by ";", polygons are separated by "\|": "x1,y1;x2,y2;x3,y3\|x1,y1;x2,y2;x3,y3". Each polygon needs at least 3 points. | "" |
| `AGENT_CAPTURE_IPCAMERA_RTSP` | Full-HD RTSP or RTSPS endpoint for the target camera. | "" |
| `AGENT_CAPTURE_IPCAMERA_RTSP_TRANSPORT` | Transport for the RTSP streams: "tcp", "udp" or "auto" (UDP first, falls back to TCP). | "tcp" |
| `AGENT_CAPTURE_IPCAMERA_SUB_RTSP` | RTSP or RTSPS sub-stream endpoint used for livestreaming (WebRTC). | "" |
+180
View File
@@ -0,0 +1,180 @@
package config
import (
"os"
"reflect"
"sort"
"strings"
"github.com/kerberos-io/agent/machinery/src/models"
)
// envConfigFields maps every AGENT_* environment variable that
// applyAgentEnvVars reads to the Config field it sets, as a Go field path.
// TestEnvConfigFieldsCoverEveryEnvVar keeps this table in step with the
// switch in applyAgentEnvVars.
var envConfigFields = map[string]string{
"AGENT_KEY": "Key",
"AGENT_NAME": "FriendlyName",
"AGENT_TIMEZONE": "Timezone",
"AGENT_OFFLINE": "Offline",
"AGENT_AUTO_CLEAN": "AutoClean",
"AGENT_AUTO_CLEAN_MAX_SIZE": "MaxDirectorySize",
"AGENT_AUTO_CLEAN_MIN_FREE_SPACE": "MinFreeSpace",
"AGENT_CAPTURE_IPCAMERA_RTSP": "Capture.IPCamera.RTSP",
"AGENT_CAPTURE_IPCAMERA_RTSP_TRANSPORT": "Capture.IPCamera.RTSPTransport",
"AGENT_CAPTURE_IPCAMERA_SUB_RTSP": "Capture.IPCamera.SubRTSP",
"AGENT_CAPTURE_IPCAMERA_BASE_WIDTH": "Capture.IPCamera.BaseWidth",
"AGENT_CAPTURE_IPCAMERA_BASE_HEIGHT": "Capture.IPCamera.BaseHeight",
"AGENT_CAPTURE_IPCAMERA_ONVIF": "Capture.IPCamera.ONVIF",
"AGENT_CAPTURE_IPCAMERA_ONVIF_XADDR": "Capture.IPCamera.ONVIFXAddr",
"AGENT_CAPTURE_IPCAMERA_ONVIF_USERNAME": "Capture.IPCamera.ONVIFUsername",
"AGENT_CAPTURE_IPCAMERA_ONVIF_PASSWORD": "Capture.IPCamera.ONVIFPassword",
"AGENT_CAPTURE_IPCAMERA_ONVIF_CHANNEL": "Capture.IPCamera.ONVIFChannel",
"AGENT_CAPTURE_RECORDING": "Capture.Recording",
"AGENT_CAPTURE_CONTINUOUS": "Capture.Continuous",
"AGENT_CAPTURE_LIVEVIEW": "Capture.Liveview",
"AGENT_CAPTURE_MOTION": "Capture.Motion",
"AGENT_CAPTURE_ONVIF_MOTION": "Capture.ONVIFMotion",
"AGENT_CAPTURE_SNAPSHOTS": "Capture.Snapshots",
"AGENT_CAPTURE_PRERECORDING": "Capture.PreRecording",
"AGENT_CAPTURE_POSTRECORDING": "Capture.PostRecording",
"AGENT_CAPTURE_MAXLENGTH": "Capture.MaxLengthRecording",
"AGENT_CAPTURE_PIXEL_CHANGE": "Capture.PixelChangeThreshold",
"AGENT_CAPTURE_FRAGMENTED": "Capture.Fragmented",
"AGENT_CAPTURE_FRAGMENTED_DURATION": "Capture.FragmentedDuration",
"AGENT_CAPTURE_LIVEVIEW_CHUNKING": "Capture.LiveviewChunking",
"AGENT_TIME": "Time",
"AGENT_TIMETABLE": "Timetable",
"AGENT_REGION_POLYGON": "Region.Polygon",
"AGENT_MQTT_URI": "MQTTURI",
"AGENT_MQTT_USERNAME": "MQTTUsername",
"AGENT_MQTT_PASSWORD": "MQTTPassword",
"AGENT_REALTIME_PROCESSING": "RealtimeProcessing",
"AGENT_REALTIME_PROCESSING_TOPIC": "RealtimeProcessingTopic",
"AGENT_STUN_URI": "STUNURI",
"AGENT_FORCE_TURN": "ForceTurn",
"AGENT_TURN_URI": "TURNURI",
"AGENT_TURN_USERNAME": "TURNUsername",
"AGENT_TURN_PASSWORD": "TURNPassword",
"AGENT_CLOUD": "Cloud",
"AGENT_REMOVE_AFTER_UPLOAD": "RemoveAfterUpload",
"AGENT_HUB_ENCRYPTION": "HubEncryption",
"AGENT_HUB_URI": "HubURI",
"AGENT_HUB_KEY": "HubKey",
"AGENT_HUB_PRIVATE_KEY": "HubPrivateKey",
"AGENT_HUB_SITE": "HubSite",
"AGENT_HUB_REGION": "S3.Region",
"AGENT_KERBEROSVAULT_URI": "KStorage.URI",
"AGENT_KERBEROSVAULT_ACCESS_KEY": "KStorage.AccessKey",
"AGENT_KERBEROSVAULT_SECRET_KEY": "KStorage.SecretAccessKey",
"AGENT_KERBEROSVAULT_PROVIDER": "KStorage.Provider",
"AGENT_KERBEROSVAULT_DIRECTORY": "KStorage.Directory",
"AGENT_KERBEROSVAULT_CUSTOM_HEADERS": "KStorage.CustomHeaders",
"AGENT_KERBEROSVAULT_MAX_RETRIES": "KStorage.MaxRetries",
"AGENT_KERBEROSVAULT_TIMEOUT": "KStorage.Timeout",
"AGENT_KERBEROSVAULT_SECONDARY_URI": "KStorageSecondary.URI",
"AGENT_KERBEROSVAULT_SECONDARY_ACCESS_KEY": "KStorageSecondary.AccessKey",
"AGENT_KERBEROSVAULT_SECONDARY_SECRET_KEY": "KStorageSecondary.SecretAccessKey",
"AGENT_KERBEROSVAULT_SECONDARY_PROVIDER": "KStorageSecondary.Provider",
"AGENT_KERBEROSVAULT_SECONDARY_DIRECTORY": "KStorageSecondary.Directory",
"AGENT_KERBEROSVAULT_SECONDARY_CUSTOM_HEADERS": "KStorageSecondary.CustomHeaders",
"AGENT_DROPBOX_ACCESS_TOKEN": "Dropbox.AccessToken",
"AGENT_DROPBOX_DIRECTORY": "Dropbox.Directory",
"AGENT_ENCRYPTION": "Encryption.Enabled",
"AGENT_ENCRYPTION_RECORDINGS": "Encryption.Recordings",
"AGENT_ENCRYPTION_FINGERPRINT": "Encryption.Fingerprint",
"AGENT_ENCRYPTION_PRIVATE_KEY": "Encryption.PrivateKey",
"AGENT_ENCRYPTION_SYMMETRIC_KEY": "Encryption.SymmetricKey",
"AGENT_SIGNING": "Signing.Enabled",
"AGENT_SIGNING_PRIVATE_KEY": "Signing.PrivateKey",
}
// EnvManaged tells a remote editor (the Hub) which settings come from
// environment variables. The agent applies those again on every start, so a
// change saved to them through the Hub is undone at the next restart.
//
// All is true in ConfigMap mode: the configuration is then built only from
// GLOBAL_AGENT_* and AGENT_* variables and the saved config.json is ignored,
// so no remote change survives a restart. Paths lists the JSON paths of the
// configuration fields set by environment variables, e.g.
// "capture.ipcamera.rtsp".
type EnvManaged struct {
All bool `json:"all"`
Paths []string `json:"paths"`
}
// IsEmpty reports whether no setting is managed by environment variables.
func (e EnvManaged) IsEmpty() bool {
return !e.All && len(e.Paths) == 0
}
// EnvManagedConfig reports which settings the current environment variables
// manage, following the same rules as OverrideWithEnvironmentVariables.
func EnvManagedConfig() EnvManaged {
standalone := os.Getenv("DEPLOYMENT") == "" || os.Getenv("DEPLOYMENT") == "agent"
seen := map[string]bool{}
add := func(goPath string) {
if path, ok := configJSONPath(goPath); ok {
seen[path] = true
}
}
if os.Getenv("DEPLOYMENT_NAME") != "" {
add("Name")
}
for _, env := range os.Environ() {
fullKey := strings.SplitN(env, "=", 2)[0]
key := fullKey
if strings.HasPrefix(fullKey, "GLOBAL_AGENT_") {
// GLOBAL_AGENT_* variables are only applied in standalone and
// ConfigMap mode, not in Factory/MongoDB mode.
if !standalone {
continue
}
key = strings.TrimPrefix(fullKey, "GLOBAL_")
}
if goPath, ok := envConfigFields[key]; ok {
add(goPath)
}
}
paths := make([]string, 0, len(seen))
for path := range seen {
paths = append(paths, path)
}
sort.Strings(paths)
return EnvManaged{
All: standalone && isConfigMapMode(),
Paths: paths,
}
}
// configJSONPath converts a Go field path of models.Config (e.g.
// "Capture.IPCamera.RTSP") into its JSON path (e.g. "capture.ipcamera.rtsp").
func configJSONPath(goPath string) (string, bool) {
t := reflect.TypeOf(models.Config{})
segments := strings.Split(goPath, ".")
jsonSegments := make([]string, 0, len(segments))
for _, segment := range segments {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return "", false
}
field, ok := t.FieldByName(segment)
if !ok {
return "", false
}
name := strings.Split(field.Tag.Get("json"), ",")[0]
if name == "" || name == "-" {
name = field.Name
}
jsonSegments = append(jsonSegments, name)
t = field.Type
}
return strings.Join(jsonSegments, "."), true
}
+177
View File
@@ -0,0 +1,177 @@
package config
import (
"os"
"reflect"
"regexp"
"strings"
"testing"
"github.com/kerberos-io/agent/machinery/src/models"
)
// Every AGENT_* variable handled by applyAgentEnvVars needs an entry in
// envConfigFields, and the table must not list variables that are not handled.
func TestEnvConfigFieldsCoverEveryEnvVar(t *testing.T) {
source, err := os.ReadFile("main.go")
if err != nil {
t.Fatal(err)
}
start := strings.Index(string(source), "func applyAgentEnvVars(")
if start < 0 {
t.Fatal("applyAgentEnvVars not found in main.go")
}
handled := map[string]bool{}
for _, match := range regexp.MustCompile(`case "(AGENT_[A-Z0-9_]+)":`).FindAllStringSubmatch(string(source[start:]), -1) {
handled[match[1]] = true
}
if len(handled) == 0 {
t.Fatal("no AGENT_* cases found")
}
for key := range handled {
if _, ok := envConfigFields[key]; !ok {
t.Errorf("%s is handled by applyAgentEnvVars but missing from envConfigFields", key)
}
}
for key := range envConfigFields {
if !handled[key] {
t.Errorf("%s is in envConfigFields but not handled by applyAgentEnvVars", key)
}
}
}
func TestEnvConfigFieldsResolveToJSONPaths(t *testing.T) {
for key, goPath := range envConfigFields {
if _, ok := configJSONPath(goPath); !ok {
t.Errorf("%s: %q is not a field path of models.Config", key, goPath)
}
}
want := map[string]string{
"AGENT_CAPTURE_IPCAMERA_RTSP": "capture.ipcamera.rtsp",
"AGENT_CAPTURE_PIXEL_CHANGE": "capture.pixelChangeThreshold",
"AGENT_REGION_POLYGON": "region.polygon",
"AGENT_KERBEROSVAULT_SECONDARY_URI": "kstorage_secondary.uri",
"AGENT_NAME": "friendly_name",
"AGENT_HUB_REGION": "s3.region",
}
for key, path := range want {
got, _ := configJSONPath(envConfigFields[key])
if got != path {
t.Errorf("%s: path = %q, want %q", key, got, path)
}
}
}
// Setting a variable on its own must change the field the table names.
func TestEnvConfigFieldsMatchApplyAgentEnvVars(t *testing.T) {
samples := map[string]string{
"AGENT_TIMETABLE": "0,43199,43200,86400",
"AGENT_REGION_POLYGON": "0,0;10,0;10,10",
}
for key, goPath := range envConfigFields {
t.Run(key, func(t *testing.T) {
configuration := &models.Configuration{}
initConfigPointers(&configuration.Config)
field := configField(reflect.ValueOf(&configuration.Config).Elem(), goPath)
if !field.IsValid() {
t.Fatalf("%q not found", goPath)
}
sample, ok := samples[key]
if !ok {
switch underlying(field.Type()).Kind() {
case reflect.String:
sample = "sample"
default:
sample = "7"
}
}
t.Setenv(key, sample)
applyAgentEnvVars(configuration, "", false)
field = configField(reflect.ValueOf(&configuration.Config).Elem(), goPath)
if !field.IsValid() || field.IsZero() {
t.Fatalf("%s=%q did not set %s", key, sample, goPath)
}
})
}
}
func TestEnvManagedConfig(t *testing.T) {
clearAgentEnv(t)
t.Run("nothing set", func(t *testing.T) {
if got := EnvManagedConfig(); !got.IsEmpty() {
t.Fatalf("got %+v, want empty", got)
}
})
t.Run("standalone with AGENT_* variables", func(t *testing.T) {
t.Setenv("AGENT_CAPTURE_IPCAMERA_RTSP", "rtsp://camera/stream")
t.Setenv("AGENT_REGION_POLYGON", "0,0;10,0;10,10")
t.Setenv("DEPLOYMENT_NAME", "agent-front-door")
got := EnvManagedConfig()
want := EnvManaged{All: false, Paths: []string{"capture.ipcamera.rtsp", "name", "region.polygon"}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %+v, want %+v", got, want)
}
})
t.Run("ConfigMap mode manages everything", func(t *testing.T) {
t.Setenv("GLOBAL_AGENT_TIMEZONE", "Europe/Brussels")
t.Setenv("AGENT_CAPTURE_IPCAMERA_RTSP", "rtsp://camera/stream")
got := EnvManagedConfig()
want := EnvManaged{All: true, Paths: []string{"capture.ipcamera.rtsp", "timezone"}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %+v, want %+v", got, want)
}
})
t.Run("Factory mode ignores GLOBAL_AGENT_* variables", func(t *testing.T) {
t.Setenv("DEPLOYMENT", "factory")
t.Setenv("GLOBAL_AGENT_TIMEZONE", "Europe/Brussels")
t.Setenv("AGENT_CAPTURE_IPCAMERA_RTSP", "rtsp://camera/stream")
got := EnvManagedConfig()
want := EnvManaged{All: false, Paths: []string{"capture.ipcamera.rtsp"}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %+v, want %+v", got, want)
}
})
}
// clearAgentEnv unsets variables that would leak into these tests from the
// environment running them; t.Setenv restores them afterwards.
func clearAgentEnv(t *testing.T) {
for _, env := range os.Environ() {
key := strings.SplitN(env, "=", 2)[0]
if strings.HasPrefix(key, "AGENT_") || strings.HasPrefix(key, "GLOBAL_AGENT_") ||
key == "DEPLOYMENT" || key == "DEPLOYMENT_NAME" {
t.Setenv(key, "")
os.Unsetenv(key)
}
}
}
func underlying(t reflect.Type) reflect.Type {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}
// configField follows a Go field path through (pointer) structs.
func configField(v reflect.Value, goPath string) reflect.Value {
for _, segment := range strings.Split(goPath, ".") {
for v.Kind() == reflect.Ptr {
if v.IsNil() {
return reflect.Value{}
}
v = v.Elem()
}
v = v.FieldByName(segment)
if !v.IsValid() {
return v
}
}
return v
}
+35 -29
View File
@@ -308,6 +308,39 @@ func initConfigPointers(config *models.Config) {
}
}
// parseRegionPolygons parses the AGENT_REGION_POLYGON value into motion
// regions. Points are "x,y" pairs separated by ";", and several polygons can
// be given separated by "|", e.g. "0,0;10,0;10,10|20,20;30,20;30,30". Each
// part becomes its own polygon, with IDs "0", "1", ... assigned in order.
// Invalid points are ignored, and empty parts or parts with fewer than 3 valid
// points are skipped.
func parseRegionPolygons(value string) []models.Polygon {
polygons := []models.Polygon{}
for _, part := range strings.Split(value, "|") {
var coordinates []models.Coordinate
for _, pair := range strings.Split(part, ";") {
xy := strings.Split(strings.TrimSpace(pair), ",")
if len(xy) != 2 {
continue
}
x, errX := strconv.ParseFloat(strings.TrimSpace(xy[0]), 64)
y, errY := strconv.ParseFloat(strings.TrimSpace(xy[1]), 64)
if errX != nil || errY != nil {
continue
}
coordinates = append(coordinates, models.Coordinate{X: x, Y: y})
}
if len(coordinates) < 3 {
continue
}
polygons = append(polygons, models.Polygon{
ID: strconv.Itoa(len(polygons)),
Coordinates: coordinates,
})
}
return polygons
}
// applyAgentEnvVars applies the AGENT_* environment variables (optionally
// carrying the given prefix, e.g. "GLOBAL_") onto configuration.Config. When
// applyDefaults is true, defaults (such as the signing key) are applied after
@@ -503,35 +536,8 @@ func applyAgentEnvVars(configuration *models.Configuration, prefix string, apply
break
case "AGENT_REGION_POLYGON":
var coordinates []models.Coordinate
// Convert value to coordinates array
// 0,0;1,1;2,2;3,3
coordinatesString := strings.Split(value, ";")
for _, coordinateString := range coordinatesString {
coordinate := strings.Split(coordinateString, ",")
if len(coordinate) == 2 {
x, err := strconv.ParseFloat(coordinate[0], 64)
if err != nil {
continue
}
y, err := strconv.ParseFloat(coordinate[1], 64)
if err != nil {
continue
}
coordinates = append(coordinates, models.Coordinate{
X: x,
Y: y,
})
}
}
configuration.Config.Region.Polygon = []models.Polygon{
{
Coordinates: coordinates,
ID: "0",
},
}
// One or more polygons: "x,y;x,y;x,y|x,y;x,y;x,y"
configuration.Config.Region.Polygon = parseRegionPolygons(value)
break
/* MQTT settings for bi-directional communication */
+91
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"os"
"reflect"
"testing"
"time"
@@ -152,3 +153,93 @@ func TestFactoryConfigRetryableErrors(t *testing.T) {
t.Fatal("decode errors should not retry")
}
}
func TestParseRegionPolygons(t *testing.T) {
square := []models.Coordinate{{X: 0, Y: 0}, {X: 10, Y: 0}, {X: 10, Y: 10}, {X: 0, Y: 10}}
triangle := []models.Coordinate{{X: 20, Y: 20}, {X: 30, Y: 20}, {X: 30, Y: 30}}
tests := []struct {
name string
value string
want []models.Polygon
}{
{
name: "single polygon parses as before",
value: "0,0;10,0;10,10;0,10",
want: []models.Polygon{{ID: "0", Coordinates: square}},
},
{
name: "multiple polygons separated by pipe",
value: "0,0;10,0;10,10;0,10|20,20;30,20;30,30",
want: []models.Polygon{{ID: "0", Coordinates: square}, {ID: "1", Coordinates: triangle}},
},
{
name: "issue example",
value: "64,36;576,36;608,324;32,324|700,40;900,40;900,300",
want: []models.Polygon{
{ID: "0", Coordinates: []models.Coordinate{{X: 64, Y: 36}, {X: 576, Y: 36}, {X: 608, Y: 324}, {X: 32, Y: 324}}},
{ID: "1", Coordinates: []models.Coordinate{{X: 700, Y: 40}, {X: 900, Y: 40}, {X: 900, Y: 300}}},
},
},
{
name: "empty parts are skipped and ids stay sequential",
value: "|0,0;10,0;10,10;0,10||20,20;30,20;30,30|",
want: []models.Polygon{{ID: "0", Coordinates: square}, {ID: "1", Coordinates: triangle}},
},
{
name: "parts with fewer than 3 points are skipped",
value: "1,1;2,2|0,0;10,0;10,10;0,10|5,5",
want: []models.Polygon{{ID: "0", Coordinates: square}},
},
{
name: "invalid points are ignored before counting",
value: "0,0;x,1;10,0;10;10,10;0,10;",
want: []models.Polygon{{ID: "0", Coordinates: square}},
},
{
name: "whitespace is trimmed",
value: " 0, 0 ; 10,0;10 ,10; 0,10 | 20,20; 30,20 ;30,30 ",
want: []models.Polygon{{ID: "0", Coordinates: square}, {ID: "1", Coordinates: triangle}},
},
{
name: "decimal coordinates",
value: "0.5,0.5;10.25,0;10,10.75",
want: []models.Polygon{{ID: "0", Coordinates: []models.Coordinate{{X: 0.5, Y: 0.5}, {X: 10.25, Y: 0}, {X: 10, Y: 10.75}}}},
},
{name: "empty value", value: "", want: []models.Polygon{}},
{name: "only separators", value: "||", want: []models.Polygon{}},
{name: "single polygon with too few points", value: "0,0;10,10", want: []models.Polygon{}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := parseRegionPolygons(test.value)
if !reflect.DeepEqual(got, test.want) {
t.Fatalf("parseRegionPolygons(%q) = %+v, want %+v", test.value, got, test.want)
}
})
}
}
func TestApplyAgentEnvVarsRegionPolygon(t *testing.T) {
for _, prefix := range []string{"", "GLOBAL_"} {
t.Run("prefix="+prefix, func(t *testing.T) {
t.Setenv(prefix+"AGENT_REGION_POLYGON", "0,0;10,0;10,10;0,10|20,20;30,20;30,30")
configuration := &models.Configuration{}
initConfigPointers(&configuration.Config)
applyAgentEnvVars(configuration, prefix, false)
polygons := configuration.Config.Region.Polygon
if len(polygons) != 2 {
t.Fatalf("got %d polygons, want 2: %+v", len(polygons), polygons)
}
if polygons[0].ID != "0" || polygons[1].ID != "1" {
t.Fatalf("got ids %q, %q, want \"0\", \"1\"", polygons[0].ID, polygons[1].ID)
}
if len(polygons[0].Coordinates) != 4 || len(polygons[1].Coordinates) != 3 {
t.Fatalf("got %d and %d points, want 4 and 3", len(polygons[0].Coordinates), len(polygons[1].Coordinates))
}
})
}
}
+82 -15
View File
@@ -14,6 +14,7 @@ import (
"net"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
@@ -58,21 +59,76 @@ func init() {
mqtt.ERROR = pahoErrorLogger{}
}
func enableMQTTConnectionDiagnostics(options *mqtt.ClientOptions, brokerURL string) {
if !strings.Contains(brokerURL, "://") {
options.SetCustomOpenConnectionFn(openMQTTConnection)
return
// parseMQTTBrokers turns the configured MQTT URI into the list of brokers to
// connect to. Besides a single broker URI it accepts an ActiveMQ-style
// failover URI, as used by Amazon MQ active/standby brokers:
//
// failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)
//
// and a plain comma-separated list of broker URIs. Transport options after
// the closing parenthesis (e.g. "?randomize=false") are ignored: paho tries
// the brokers in the order they are listed, on connect and on reconnect.
//
// A comma only separates brokers when the text after it starts with a URI
// scheme ("scheme://"). Any other comma belongs to the current broker URI,
// so existing single-broker URIs with commas in their credentials, path or
// query string (e.g. "wss://broker/mqtt?token=a,b") keep working.
func parseMQTTBrokers(raw string) []string {
raw = strings.TrimSpace(raw)
if len(raw) >= len("failover:") && strings.EqualFold(raw[:len("failover:")], "failover:") {
raw = strings.TrimSpace(raw[len("failover:"):])
if strings.HasPrefix(raw, "(") {
if end := strings.LastIndex(raw, ")"); end > 0 {
raw = raw[1:end]
} else {
raw = raw[1:]
}
}
}
parsedURL, err := url.Parse(brokerURL)
if err != nil {
return
segments := []string{}
for _, segment := range strings.Split(raw, ",") {
if len(segments) > 0 && !mqttBrokerSchemePattern.MatchString(strings.TrimSpace(segment)) {
segments[len(segments)-1] += "," + segment
continue
}
segments = append(segments, segment)
}
switch strings.ToLower(parsedURL.Scheme) {
case "", "mqtt", "tcp", "ssl", "tls", "mqtts", "mqtt+ssl", "tcps":
options.SetCustomOpenConnectionFn(openMQTTConnection)
brokers := []string{}
for _, broker := range segments {
if broker = strings.TrimSpace(broker); broker != "" {
brokers = append(brokers, broker)
}
}
return brokers
}
// mqttBrokerSchemePattern matches the start of a URI with a scheme (RFC 3986).
var mqttBrokerSchemePattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.-]*://`)
// enableMQTTConnectionDiagnostics installs our instrumented TCP/TLS dialer.
// The custom dialer is used for every broker, so it is only installed when
// all brokers use a TCP-based scheme (WebSocket brokers keep paho's dialer).
func enableMQTTConnectionDiagnostics(options *mqtt.ClientOptions, brokerURLs []string) {
if len(brokerURLs) == 0 {
return
}
for _, brokerURL := range brokerURLs {
if !strings.Contains(brokerURL, "://") {
continue
}
parsedURL, err := url.Parse(brokerURL)
if err != nil {
return
}
switch strings.ToLower(parsedURL.Scheme) {
case "", "mqtt", "tcp", "ssl", "tls", "mqtts", "mqtt+ssl", "tcps":
default:
return
}
}
options.SetCustomOpenConnectionFn(openMQTTConnection)
}
func openMQTTConnection(uri *url.URL, options mqtt.ClientOptions) (net.Conn, error) {
@@ -270,8 +326,11 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
// We will set the MQTT endpoint to which we want to connect
// and share and receive messages to/from.
mqttURL := config.MQTTURI
opts.AddBroker(mqttURL)
// The URI may list several brokers (failover), paho tries them in order.
mqttBrokers := parseMQTTBrokers(config.MQTTURI)
for _, broker := range mqttBrokers {
opts.AddBroker(broker)
}
// Our MQTT broker can have username/password credentials
// to protect it from the outside.
@@ -282,7 +341,8 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
opts.SetPassword(mqtt_password)
}
log.WithFields(log.Fields{
"broker_configured": mqttURL != "",
"broker_configured": len(mqttBrokers) > 0,
"broker_count": len(mqttBrokers),
"component": "routers/mqtt",
"event": "credentials_configured",
"password_configured": mqtt_password != "",
@@ -292,7 +352,7 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
// Some extra options to make sure the connection behaves
// properly. More information here: github.com/eclipse/paho.mqtt.golang.
//opts.SetCleanSession(true)
enableMQTTConnectionDiagnostics(opts, mqttURL)
enableMQTTConnectionDiagnostics(opts, mqttBrokers)
opts.SetCleanSession(false)
opts.SetResumeSubs(true)
opts.SetStore(mqtt.NewMemoryStore())
@@ -354,7 +414,7 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
"event": "connected",
}).Info("MQTT broker connected")
log.WithFields(log.Fields{
"broker_configured": mqttURL != "",
"broker_configured": len(mqttBrokers) > 0,
"component": "routers/mqtt",
"event": "connection_details",
}).Debug("MQTT connection details")
@@ -788,6 +848,13 @@ func HandleRequestConfig(mqttClient mqtt.Client, hubKey string, payload models.P
// Unset encryption part.
delete(configMap, "encryption")
// Tell the Hub which settings come from environment variables:
// those are applied again on every start, so the Hub shows them
// as read-only instead of saving changes that would be undone.
if envManaged := configService.EnvManagedConfig(); !envManaged.IsEmpty() && configMap != nil {
configMap["env_managed"] = envManaged
}
message := models.Message{
Payload: models.Payload{
Action: "receive-config",
+65 -1
View File
@@ -23,12 +23,15 @@ func TestEnableMQTTConnectionDiagnostics(t *testing.T) {
{name: "TCP", brokerURL: "tcp://broker.example:1883", want: true},
{name: "default TCP", brokerURL: "broker.example:1883", want: true},
{name: "WebSocket", brokerURL: "wss://broker.example/mqtt", want: false},
{name: "ActiveMQ failover", brokerURL: "failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)", want: true},
{name: "mixed TCP and WebSocket", brokerURL: "tcp://b-1.example:1883,wss://b-2.example/mqtt", want: false},
{name: "empty", brokerURL: "", want: false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
options := mqtt.NewClientOptions()
enableMQTTConnectionDiagnostics(options, test.brokerURL)
enableMQTTConnectionDiagnostics(options, parseMQTTBrokers(test.brokerURL))
if got := options.CustomOpenConnectionFn != nil; got != test.want {
t.Fatalf("CustomOpenConnectionFn configured = %t, want %t", got, test.want)
}
@@ -206,3 +209,64 @@ func TestRemoteSessionReservationIsIdempotent(t *testing.T) {
t.Fatalf("duplicate reserve() error = %v, want %v", err, errRemoteSessionExists)
}
}
func TestParseMQTTBrokers(t *testing.T) {
tests := []struct {
name string
raw string
want []string
}{
{name: "single", raw: "mqtt+ssl://broker.example:8883", want: []string{"mqtt+ssl://broker.example:8883"}},
{name: "empty", raw: " ", want: []string{}},
{
name: "Amazon MQ failover",
raw: "failover:(mqtt+ssl://b-1.mq.eu-west-2.amazonaws.com:8883,mqtt+ssl://b-2.mq.eu-west-2.amazonaws.com:8883)",
want: []string{"mqtt+ssl://b-1.mq.eu-west-2.amazonaws.com:8883", "mqtt+ssl://b-2.mq.eu-west-2.amazonaws.com:8883"},
},
{
name: "failover with spaces and transport options",
raw: " FAILOVER:( ssl://b-1.example:8883 , ssl://b-2.example:8883 )?randomize=false",
want: []string{"ssl://b-1.example:8883", "ssl://b-2.example:8883"},
},
{name: "failover without parentheses", raw: "failover:tcp://b-1.example:1883", want: []string{"tcp://b-1.example:1883"}},
{name: "comma separated", raw: "tcp://b-1.example:1883,tcp://b-2.example:1883", want: []string{"tcp://b-1.example:1883", "tcp://b-2.example:1883"}},
{name: "comma in query string", raw: "wss://broker.example/mqtt?token=a,b", want: []string{"wss://broker.example/mqtt?token=a,b"}},
{name: "comma in password", raw: "mqtt+ssl://user:p,ss@broker.example:8883", want: []string{"mqtt+ssl://user:p,ss@broker.example:8883"}},
{name: "comma in path", raw: "wss://broker.example/a,b/mqtt", want: []string{"wss://broker.example/a,b/mqtt"}},
{name: "comma followed by text that looks like a scheme without slashes", raw: "wss://broker.example/mqtt?list=a,b:c", want: []string{"wss://broker.example/mqtt?list=a,b:c"}},
{
name: "failover with commas inside a broker URI",
raw: "failover:(wss://b-1.example/mqtt?token=a,b,wss://b-2.example/mqtt?token=c,d)",
want: []string{"wss://b-1.example/mqtt?token=a,b", "wss://b-2.example/mqtt?token=c,d"},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := parseMQTTBrokers(test.raw)
if len(got) != len(test.want) {
t.Fatalf("parseMQTTBrokers(%q) = %q, want %q", test.raw, got, test.want)
}
for i := range got {
if got[i] != test.want[i] {
t.Fatalf("parseMQTTBrokers(%q) = %q, want %q", test.raw, got, test.want)
}
}
})
}
}
func TestConfigureMQTTOptionsRegistersFailoverBrokers(t *testing.T) {
options := mqtt.NewClientOptions()
for _, broker := range parseMQTTBrokers("failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)") {
options.AddBroker(broker)
}
if len(options.Servers) != 2 {
t.Fatalf("registered %d brokers, want 2", len(options.Servers))
}
for i, host := range []string{"b-1.example:8883", "b-2.example:8883"} {
if options.Servers[i].Scheme != "mqtt+ssl" || options.Servers[i].Host != host {
t.Fatalf("broker %d = %s, want mqtt+ssl://%s", i, options.Servers[i], host)
}
}
}