Compare commits

..
Author SHA1 Message Date
Cédric Verstraeten 774df33c4d Merge pull request #371 from kerberos-io/feat/env-managed-config
Tell the Hub which settings come from environment variables
2026-11-27 15:38:13 +01:00
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
7 changed files with 515 additions and 55 deletions
+24 -25
View File
@@ -8,29 +8,21 @@ on:
workflow_dispatch:
jobs:
# Build one image per architecture. Only architectures we also ship in
# releases (amd64 + arm64): the golang/debian trixie base images don't
# provide arm/v6, which made every nightly fail since February.
nightly-build:
# Nightlies always build the latest master: schedules run on the default
# branch, and manual runs from any other branch are skipped.
if: github.ref == 'refs/heads/master'
nightly-build-amd64:
runs-on: ubuntu-latest
strategy:
# Let every architecture finish, so one broken build doesn't hide the others.
fail-fast: false
matrix:
architecture: [amd64, arm64]
architecture: [amd64]
steps:
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
# Check out the triggering commit (master HEAD) so the code matches the
# $GITHUB_SHA used in the image tags.
- name: Checkout
uses: actions/checkout@v4
with:
ref: master
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
@@ -39,25 +31,32 @@ jobs:
- name: Available platforms
run: echo ${{ steps.buildx.outputs.platforms }}
- name: Run Buildx
run: docker buildx build --build-arg VERSION=$(echo $GITHUB_SHA | cut -c1-7) --platform linux/${{matrix.architecture}} -t kerberos/agent-nightly:arch-${{matrix.architecture}}-$(echo $GITHUB_SHA | cut -c1-7) --push .
# Create the multi-arch manifest once, after all architectures are pushed.
# Previously each build job created/appended to it in parallel, so the
# result depended on which job finished last.
nightly-manifest:
run: docker buildx build --build-arg VERSION=$(echo $GITHUB_SHA | cut -c1-7) --platform linux/${{matrix.architecture}} -t kerberos/agent-nightly:arch-$(echo ${{matrix.architecture}} | tr / -)-$(echo $GITHUB_SHA | cut -c1-7) --push .
- name: Create new and append to manifest
run: docker buildx imagetools create -t kerberos/agent-nightly:$(echo $GITHUB_SHA | cut -c1-7) kerberos/agent-nightly:arch-$(echo ${{matrix.architecture}} | tr / -)-$(echo $GITHUB_SHA | cut -c1-7)
nightly-build-other:
runs-on: ubuntu-latest
needs: nightly-build
strategy:
matrix:
architecture: [arm64, arm/v7, arm/v6]
steps:
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Checkout
uses: actions/checkout@v4
with:
ref: master
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v3
- name: Create manifest
run: |
SHORT_SHA=$(echo $GITHUB_SHA | cut -c1-7)
docker buildx imagetools create -t kerberos/agent-nightly:$SHORT_SHA \
kerberos/agent-nightly:arch-amd64-$SHORT_SHA \
kerberos/agent-nightly:arch-arm64-$SHORT_SHA
- name: Available platforms
run: echo ${{ steps.buildx.outputs.platforms }}
- name: Run Buildx
run: docker buildx build --build-arg VERSION=$(echo $GITHUB_SHA | cut -c1-7) --platform linux/${{matrix.architecture}} -t kerberos/agent-nightly:arch-$(echo ${{matrix.architecture}} | tr / -)-$(echo $GITHUB_SHA | cut -c1-7) --push .
- name: Create new and append to manifest
run: docker buildx imagetools create --append -t kerberos/agent-nightly:$(echo $GITHUB_SHA | cut -c1-7) kerberos/agent-nightly:arch-$(echo ${{matrix.architecture}} | tr / -)-$(echo $GITHUB_SHA | cut -c1-7)
+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))
}
})
}
}
+7
View File
@@ -848,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",