Jelajahi Sumber

fix: reload entity and calendar files that are replaced, not written (#1179)

James Read 1 hari lalu
induk
melakukan
f37fe9455d

+ 1 - 0
docs/modules/ROOT/pages/entities/intro.adoc

@@ -24,6 +24,7 @@ The chosen field is shown as the instance name in lists and dashboards. On the e
 === Live reload
 
 * **Entity file content** — when a watched data file is updated on disk, OliveTin reloads instances and notifies the web UI. No restart is required.
+* **Replaced or mounted files** — files that are replaced rather than written in place are reloaded too. This includes files saved by editors that write a new copy, files moved into place with `mv`, symlinks that are pointed somewhere else, and files mounted from a Kubernetes ConfigMap.
 * **New entity types in `config.yaml`** — when you add a new entry under `entities:` and reload config, OliveTin starts watching that file without a full restart.
 * **Entity file path changes** — when you change an entity's file path in config and reload, OliveTin switches to the new file without a restart.
 * **Removing or renaming entity types** — restart OliveTin if you remove an entity definition or rename its type; otherwise stale entity data may remain in memory until restart.

+ 42 - 0
service/internal/entities/entities_test.go

@@ -3,7 +3,9 @@ package entities
 import (
 	"os"
 	"path/filepath"
+	"runtime"
 	"testing"
+	"time"
 
 	config "github.com/OliveTin/OliveTin/internal/config"
 	"github.com/stretchr/testify/assert"
@@ -241,3 +243,43 @@ func TestLoadEntityFile_preservesEntitiesOnTransientFailure(t *testing.T) {
 	require.Len(t, ordered, 1, "JSON parse failure should keep last good entities")
 	assert.Equal(t, "json-kept", ordered[0].Title)
 }
+
+// Kubernetes mounts each ConfigMap file as a symlink to ..data/<name>, and
+// updates it by pointing ..data at a new directory, so the file is never
+// written in place.
+func TestSyncEntityFileWatchers_reloadsConfigMapUpdate(t *testing.T) {
+	if runtime.GOOS == "windows" {
+		t.Skip("symlinks need extra privileges on Windows")
+	}
+
+	ResetEntityWatchersForTests()
+	t.Cleanup(func() {
+		ResetEntityWatchersForTests()
+		ClearEntitiesOfType("vehicle")
+	})
+
+	dir := t.TempDir()
+	require.NoError(t, os.Mkdir(filepath.Join(dir, "..v1"), 0o755))
+	require.NoError(t, os.WriteFile(filepath.Join(dir, "..v1", "vehicles.yaml"), []byte("- title: car1\n"), 0o600))
+	require.NoError(t, os.Symlink("..v1", filepath.Join(dir, "..data")))
+	require.NoError(t, os.Symlink(filepath.Join("..data", "vehicles.yaml"), filepath.Join(dir, "vehicles.yaml")))
+
+	cfg := config.DefaultConfig()
+	cfg.SetDir(dir)
+	cfg.Entities = []*config.EntityFile{
+		{Name: "vehicle", File: "vehicles.yaml"},
+	}
+
+	SyncEntityFileWatchers(cfg)
+	require.Len(t, GetEntityInstancesOrdered("vehicle"), 1)
+
+	require.NoError(t, os.Mkdir(filepath.Join(dir, "..v2"), 0o755))
+	require.NoError(t, os.WriteFile(filepath.Join(dir, "..v2", "vehicles.yaml"), []byte("- title: car1\n- title: car2\n"), 0o600))
+	require.NoError(t, os.Symlink("..v2", filepath.Join(dir, "..data_tmp")))
+	require.NoError(t, os.Rename(filepath.Join(dir, "..data_tmp"), filepath.Join(dir, "..data")))
+	require.NoError(t, os.RemoveAll(filepath.Join(dir, "..v1")))
+
+	require.Eventually(t, func() bool {
+		return len(GetEntityInstancesOrdered("vehicle")) == 2
+	}, 3*time.Second, 50*time.Millisecond, "entities were not reloaded after a ConfigMap update")
+}

+ 184 - 8
service/internal/filehelper/file_change_notify.go

@@ -2,6 +2,7 @@ package filehelper
 
 import (
 	"fmt"
+	"os"
 	"path/filepath"
 	"sync"
 	"time"
@@ -42,11 +43,26 @@ type WatchMeta struct {
 }
 
 type watchContext struct {
-	callback        func(filename string)
-	event           *fsnotify.Event
-	meta            WatchMeta
-	filename        string
-	filedir         string
+	callback func(filename string)
+	event    *fsnotify.Event
+	watcher  *fsnotify.Watcher
+	meta     WatchMeta
+	filename string
+	filedir  string
+
+	// The fields below are only used by file watches, and only touched by the
+	// watcher's own goroutine once it has started.
+
+	// watchedPath is the file that was asked for, which may be a symlink.
+	watchedPath string
+	// resolvedPath is where watchedPath last pointed, or empty if it has not
+	// resolved yet.
+	resolvedPath string
+	// resolvedDir is the extra directory watched when resolvedPath is in a
+	// different directory to watchedPath, so in-place edits of a symlink's
+	// target are seen.
+	resolvedDir string
+
 	interestedEvent fsnotify.Op
 }
 
@@ -78,6 +94,7 @@ func WatchFileWrite(fullpath string, callback func(filename string), meta WatchM
 	ctx := &watchContext{
 		filedir:         filedir,
 		filename:        filename,
+		watchedPath:     watchKey,
 		callback:        callback,
 		interestedEvent: fsnotify.Write,
 		meta:            meta,
@@ -95,6 +112,9 @@ func WatchFileWrite(fullpath string, callback func(filename string), meta WatchM
 		return err
 	}
 
+	ctx.watcher = watcher
+	refreshResolvedPath(ctx)
+
 	done := registerFileWatch(watchKey)
 	go runWatcher(ctx, watcher, done)
 	return nil
@@ -208,12 +228,23 @@ func waitForWatcherEventOrCancel(ctx *watchContext, watcher *fsnotify.Watcher, d
 	case <-done:
 		return false
 	case event, ok := <-watcher.Events:
-		return handleWatcherEvent(ctx, event, ok)
+		return !isStopped(done) && handleWatcherEvent(ctx, event, ok)
 	case err, ok := <-watcher.Errors:
 		return handleWatcherError(ctx, err, ok)
 	}
 }
 
+// isStopped stops a watch that has been asked to stop even when an event was
+// already waiting, because select picks between ready channels at random.
+func isStopped(done <-chan struct{}) bool {
+	select {
+	case <-done:
+		return true
+	default:
+		return false
+	}
+}
+
 func handleWatcherEvent(ctx *watchContext, event fsnotify.Event, ok bool) bool {
 	if !ok {
 		return false
@@ -236,6 +267,11 @@ func handleWatcherError(ctx *watchContext, err error, ok bool) bool {
 }
 
 func consumeEvent(ctx *watchContext) {
+	if ctx.watchedPath != "" {
+		consumeFileEvent(ctx)
+		return
+	}
+
 	if ctx.filename != "" && filepath.Base(ctx.event.Name) != ctx.filename {
 		log.Tracef("fsnotify irreleventa event different file %+v", ctx.event)
 		return
@@ -254,10 +290,150 @@ func consumeRelevantEvents(ctx *watchContext) {
 	}
 }
 
+// consumeFileEvent decides whether an event means the watched file's content
+// may have changed. Writing the file in place gives a Write event, but tools
+// that replace a file give other events: editors and mv rename a new file over
+// it (Create), and Kubernetes updates a mounted ConfigMap by swapping a
+// directory symlink, so the file itself gets no event at all and only the
+// target of its symlink changes.
+func consumeFileEvent(ctx *watchContext) {
+	if isWatchedFileChange(ctx) {
+		consumeWatchedFileChange(ctx)
+		return
+	}
+
+	if isDirectoryChange(ctx.event) && refreshResolvedPath(ctx) {
+		log.Debugf("fsnotify symlink target changed for %v: %v", ctx.watchedPath, ctx.event)
+		processDebounce(ctx)
+		return
+	}
+
+	log.Tracef("fsnotify event irrelevant: %v", ctx.event)
+}
+
+// consumeWatchedFileChange reloads after a write or create at the watched
+// path. A create can leave a dangling symlink, so it only reloads once the
+// file can be read. A write always reloads, as it always has.
+func consumeWatchedFileChange(ctx *watchContext) {
+	_, resolved := resolveWatchedPath(ctx)
+	if !resolved && !ctx.event.Has(fsnotify.Write) {
+		log.Debugf("fsnotify event waiting for %v to resolve: %v", ctx.watchedPath, ctx.event)
+		return
+	}
+
+	log.Debugf("fsnotify event relevant: %v", ctx.event)
+	processDebounce(ctx)
+}
+
+func isWatchedFileChange(ctx *watchContext) bool {
+	if !ctx.event.Has(fsnotify.Write) && !ctx.event.Has(fsnotify.Create) {
+		return false
+	}
+
+	name := filepath.Clean(ctx.event.Name)
+	return name == ctx.watchedPath || (ctx.resolvedPath != "" && name == ctx.resolvedPath)
+}
+
+func isDirectoryChange(event *fsnotify.Event) bool {
+	return event.Has(fsnotify.Create) || event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove)
+}
+
+// refreshResolvedPath checks where the watched file points now, and reports
+// whether that changed. While the file is missing or a symlink is dangling,
+// for example part way through a replacement, the last target is kept and no
+// change is reported, so the file is not reloaded until it can be read.
+func refreshResolvedPath(ctx *watchContext) bool {
+	changed, _ := resolveWatchedPath(ctx)
+	return changed
+}
+
+// resolveWatchedPath updates where the watched file points. It reports
+// whether the target changed, and separately whether the file resolved at
+// all.
+func resolveWatchedPath(ctx *watchContext) (changed bool, resolved bool) {
+	target, err := filepath.EvalSymlinks(ctx.watchedPath)
+	if err != nil {
+		log.Debugf("fsnotify could not resolve %v: %v", ctx.watchedPath, err)
+		return false, false
+	}
+
+	if target == ctx.resolvedPath {
+		return false, true
+	}
+
+	ctx.resolvedPath = target
+	watchResolvedDir(ctx, filepath.Dir(target))
+	return true, true
+}
+
+func watchResolvedDir(ctx *watchContext, dir string) {
+	if dir == ctx.resolvedDir {
+		return
+	}
+
+	unwatchResolvedDir(ctx)
+
+	// The directory may be the watched directory reached through a symlink.
+	// inotify gives both paths the same watch, so adding it again would rename
+	// that watch, and removing it later would stop the main watch.
+	if sameDirectory(dir, ctx.filedir) {
+		return
+	}
+
+	if err := ctx.watcher.Add(dir); err != nil {
+		log.WithFields(log.Fields{
+			"path": ctx.watchedPath,
+			"dir":  dir,
+		}).Warnf("Could not watch the directory a symlink points to, so edits there will not be seen: %v", err)
+		return
+	}
+
+	ctx.resolvedDir = dir
+}
+
+func unwatchResolvedDir(ctx *watchContext) {
+	if ctx.resolvedDir == "" {
+		return
+	}
+
+	// A ConfigMap's old directory has already been deleted by now, and the
+	// watch went with it, so an error here is expected.
+	if err := ctx.watcher.Remove(ctx.resolvedDir); err != nil {
+		log.Debugf("fsnotify could not stop watching %v: %v", ctx.resolvedDir, err)
+	}
+
+	ctx.resolvedDir = ""
+}
+
+func sameDirectory(left, right string) bool {
+	leftInfo, err := os.Stat(left)
+	if err != nil {
+		return false
+	}
+
+	rightInfo, err := os.Stat(right)
+	if err != nil {
+		return false
+	}
+
+	return os.SameFile(leftInfo, rightInfo)
+}
+
+// debounceKey keeps file watches apart by their whole path, so two files with
+// the same name in different directories do not suppress each other.
+// Directory watches keep their existing key.
+func debounceKey(ctx *watchContext) string {
+	if ctx.watchedPath != "" {
+		return ctx.watchedPath
+	}
+	return ctx.filename
+}
+
 func processDebounce(ctx *watchContext) {
 	debounceWriteLogMutex.Lock()
 
-	logEntry, found := debounceWriteLog[ctx.filename]
+	key := debounceKey(ctx)
+	logEntry, found := debounceWriteLog[key]
 
 	if !found {
 		logEntry = &FsNotifyLogEntry{
@@ -265,7 +441,7 @@ func processDebounce(ctx *watchContext) {
 			callbackWrapper:  nil,
 		}
 
-		debounceWriteLog[ctx.filename] = logEntry
+		debounceWriteLog[key] = logEntry
 	}
 
 	log.Debugf("fsnotify event %+v", logEntry)

+ 335 - 0
service/internal/filehelper/file_watch_symlink_test.go

@@ -0,0 +1,335 @@
+package filehelper
+
+import (
+	"fmt"
+	"os"
+	"path/filepath"
+	"runtime"
+	"testing"
+	"time"
+
+	"github.com/fsnotify/fsnotify"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+)
+
+const (
+	callbackTimeout = 2 * time.Second
+	// quietPeriod is long enough for any debounced callback to have fired.
+	quietPeriod = 3 * debounceDelay
+)
+
+type watchRecorder struct {
+	calls chan string
+}
+
+func watchFileForTest(t *testing.T, path string) *watchRecorder {
+	t.Helper()
+
+	recorder := &watchRecorder{calls: make(chan string, 16)}
+	require.NoError(t, WatchFileWrite(path, func(filename string) {
+		recorder.calls <- filename
+	}, WatchMeta{}))
+	t.Cleanup(func() { StopFileWatch(path) })
+
+	return recorder
+}
+
+// expectOneCall waits for a callback, then checks no more follow, so extra
+// reloads are caught as well as missing ones.
+func (r *watchRecorder) expectOneCall(t *testing.T) {
+	t.Helper()
+
+	select {
+	case <-r.calls:
+	case <-time.After(callbackTimeout):
+		t.Fatal("expected a callback, got none")
+	}
+	r.expectNone(t)
+}
+
+func (r *watchRecorder) expectNone(t *testing.T) {
+	t.Helper()
+
+	select {
+	case name := <-r.calls:
+		t.Fatalf("unexpected callback for %s", name)
+	case <-time.After(quietPeriod):
+	}
+}
+
+func skipWithoutSymlinks(t *testing.T) {
+	t.Helper()
+
+	if runtime.GOOS == "windows" {
+		t.Skip("symlinks need extra privileges on Windows")
+	}
+}
+
+func writeFile(t *testing.T, path, content string) {
+	t.Helper()
+	require.NoError(t, os.WriteFile(path, []byte(content), 0o600))
+}
+
+func readFile(t *testing.T, path string) string {
+	t.Helper()
+	content, err := os.ReadFile(path)
+	require.NoError(t, err)
+	return string(content)
+}
+
+// replaceByRename writes a new file next to path and renames it over path, as
+// editors, mv and many deployment tools do.
+func replaceByRename(t *testing.T, path, content string) {
+	t.Helper()
+	temporary := path + ".tmp"
+	writeFile(t, temporary, content)
+	require.NoError(t, os.Rename(temporary, path))
+}
+
+// configMapDir lays out files the way the kubelet mounts a ConfigMap: each
+// file is a symlink to ..data/<name>, and ..data is a symlink to a
+// timestamped directory that is swapped on every update.
+type configMapDir struct {
+	dir     string
+	name    string
+	version int
+}
+
+// newConfigMapDir starts with the content "a: 1\n".
+func newConfigMapDir(t *testing.T) *configMapDir {
+	t.Helper()
+	skipWithoutSymlinks(t)
+
+	cm := &configMapDir{dir: t.TempDir(), name: "entities.yaml"}
+	cm.writeVersion(t, "a: 1\n")
+	require.NoError(t, os.Symlink(cm.versionDir(), filepath.Join(cm.dir, "..data")))
+	require.NoError(t, os.Symlink(filepath.Join("..data", cm.name), cm.path()))
+
+	return cm
+}
+
+func (cm *configMapDir) path() string {
+	return filepath.Join(cm.dir, cm.name)
+}
+
+func (cm *configMapDir) versionDir() string {
+	return fmt.Sprintf("..2026_11_26_00_00_%02d.%d", cm.version, cm.version)
+}
+
+func (cm *configMapDir) writeVersion(t *testing.T, content string) {
+	t.Helper()
+	cm.version++
+	require.NoError(t, os.Mkdir(filepath.Join(cm.dir, cm.versionDir()), 0o755))
+	writeFile(t, filepath.Join(cm.dir, cm.versionDir(), cm.name), content)
+}
+
+func (cm *configMapDir) pointDataAt(t *testing.T, target string) {
+	t.Helper()
+	temporary := filepath.Join(cm.dir, "..data_tmp")
+	require.NoError(t, os.Symlink(target, temporary))
+	require.NoError(t, os.Rename(temporary, filepath.Join(cm.dir, "..data")))
+}
+
+// update follows the kubelet's sequence: write a new directory, swap ..data
+// to it, then delete the old directory.
+func (cm *configMapDir) update(t *testing.T, content string) {
+	t.Helper()
+	previous := cm.versionDir()
+	cm.writeVersion(t, content)
+	cm.pointDataAt(t, cm.versionDir())
+	require.NoError(t, os.RemoveAll(filepath.Join(cm.dir, previous)))
+}
+
+func TestWatchFileWriteReloadsConfigMapUpdate(t *testing.T) {
+	cm := newConfigMapDir(t)
+	recorder := watchFileForTest(t, cm.path())
+
+	cm.update(t, "a: 2\n")
+
+	recorder.expectOneCall(t)
+	assert.Equal(t, "a: 2\n", readFile(t, cm.path()))
+}
+
+func TestWatchFileWriteReloadsEveryConfigMapUpdate(t *testing.T) {
+	cm := newConfigMapDir(t)
+	recorder := watchFileForTest(t, cm.path())
+
+	for version := 2; version <= 4; version++ {
+		content := fmt.Sprintf("a: %d\n", version)
+		cm.update(t, content)
+		recorder.expectOneCall(t)
+		assert.Equal(t, content, readFile(t, cm.path()))
+	}
+}
+
+func TestWatchFileWriteWaitsForDanglingConfigMapLink(t *testing.T) {
+	cm := newConfigMapDir(t)
+	recorder := watchFileForTest(t, cm.path())
+
+	cm.pointDataAt(t, "..missing")
+	recorder.expectNone(t)
+
+	cm.writeVersion(t, "a: 2\n")
+	cm.pointDataAt(t, cm.versionDir())
+	recorder.expectOneCall(t)
+}
+
+func TestWatchFileWriteWaitsForDanglingReplacement(t *testing.T) {
+	skipWithoutSymlinks(t)
+
+	dir := t.TempDir()
+	path := filepath.Join(dir, "entities.yaml")
+	writeFile(t, path, "a: 1\n")
+	recorder := watchFileForTest(t, path)
+
+	temporary := filepath.Join(dir, "entities.yaml.tmp")
+	require.NoError(t, os.Symlink(filepath.Join(dir, "missing.yaml"), temporary))
+	require.NoError(t, os.Rename(temporary, path))
+	recorder.expectNone(t)
+
+	writeFile(t, filepath.Join(dir, "missing.yaml"), "a: 2\n")
+	recorder.expectOneCall(t)
+}
+
+func TestWatchFileWriteReloadsRenameSave(t *testing.T) {
+	path := filepath.Join(t.TempDir(), "entities.yaml")
+	writeFile(t, path, "a: 1\n")
+	recorder := watchFileForTest(t, path)
+
+	replaceByRename(t, path, "a: 2\n")
+
+	recorder.expectOneCall(t)
+}
+
+func TestWatchFileWriteReloadsRecreatedFile(t *testing.T) {
+	path := filepath.Join(t.TempDir(), "entities.yaml")
+	writeFile(t, path, "a: 1\n")
+	recorder := watchFileForTest(t, path)
+
+	require.NoError(t, os.Remove(path))
+	recorder.expectNone(t)
+
+	replaceByRename(t, path, "a: 2\n")
+	recorder.expectOneCall(t)
+}
+
+func TestWatchFileWriteReloadsInPlaceWrite(t *testing.T) {
+	path := filepath.Join(t.TempDir(), "entities.yaml")
+	writeFile(t, path, "a: 1\n")
+	recorder := watchFileForTest(t, path)
+
+	writeFile(t, path, "a: 2\n")
+
+	recorder.expectOneCall(t)
+}
+
+func TestWatchFileWriteReloadsNewFileOnce(t *testing.T) {
+	path := filepath.Join(t.TempDir(), "entities.yaml")
+	recorder := watchFileForTest(t, path)
+
+	writeFile(t, path, "a: 1\n")
+
+	recorder.expectOneCall(t)
+}
+
+func TestWatchFileWriteFollowsSymlinkToAnotherDirectory(t *testing.T) {
+	skipWithoutSymlinks(t)
+
+	linkDir, firstDir, secondDir := t.TempDir(), t.TempDir(), t.TempDir()
+	firstTarget := filepath.Join(firstDir, "real.yaml")
+	secondTarget := filepath.Join(secondDir, "real.yaml")
+	writeFile(t, firstTarget, "a: 1\n")
+	writeFile(t, secondTarget, "b: 1\n")
+
+	path := filepath.Join(linkDir, "entities.yaml")
+	require.NoError(t, os.Symlink(firstTarget, path))
+	recorder := watchFileForTest(t, path)
+
+	writeFile(t, firstTarget, "a: 2\n")
+	recorder.expectOneCall(t)
+
+	temporary := filepath.Join(linkDir, "entities.yaml.tmp")
+	require.NoError(t, os.Symlink(secondTarget, temporary))
+	require.NoError(t, os.Rename(temporary, path))
+	recorder.expectOneCall(t)
+
+	writeFile(t, secondTarget, "b: 2\n")
+	recorder.expectOneCall(t)
+
+	writeFile(t, firstTarget, "a: 3\n")
+	recorder.expectNone(t)
+}
+
+func TestWatchFileWriteIgnoresUnrelatedChanges(t *testing.T) {
+	dir := t.TempDir()
+	path := filepath.Join(dir, "entities.yaml")
+	writeFile(t, path, "a: 1\n")
+	recorder := watchFileForTest(t, path)
+
+	other := filepath.Join(dir, "other.yaml")
+	writeFile(t, other, "b: 1\n")
+	writeFile(t, other, "b: 2\n")
+	replaceByRename(t, other, "b: 3\n")
+	require.NoError(t, os.Remove(other))
+	require.NoError(t, os.Chmod(path, 0o640))
+
+	recorder.expectNone(t)
+}
+
+func TestWatchFileWriteKeepsSameNamedFilesApart(t *testing.T) {
+	first := filepath.Join(t.TempDir(), "entities.yaml")
+	second := filepath.Join(t.TempDir(), "entities.yaml")
+	writeFile(t, first, "a: 1\n")
+	writeFile(t, second, "b: 1\n")
+	firstRecorder := watchFileForTest(t, first)
+	secondRecorder := watchFileForTest(t, second)
+
+	writeFile(t, first, "a: 2\n")
+	writeFile(t, second, "b: 2\n")
+
+	firstRecorder.expectOneCall(t)
+	secondRecorder.expectOneCall(t)
+}
+
+func TestWatchFileWriteStopsAfterStopFileWatch(t *testing.T) {
+	cm := newConfigMapDir(t)
+	recorder := watchFileForTest(t, cm.path())
+
+	StopFileWatch(cm.path())
+	cm.update(t, "a: 2\n")
+
+	recorder.expectNone(t)
+}
+
+func TestWatchDirectoryCreateStillFiresForNewFiles(t *testing.T) {
+	debounceWriteLogMutex.Lock()
+	debounceWriteLog = make(map[string]*FsNotifyLogEntry)
+	debounceWriteLogMutex.Unlock()
+
+	dir := t.TempDir()
+	calls := make(chan string, 16)
+	done := make(chan struct{})
+	t.Cleanup(func() { close(done) })
+
+	// The watch is added before the event loop starts, so the file created
+	// below cannot be missed.
+	watcher, err := fsnotify.NewWatcher()
+	require.NoError(t, err)
+	require.NoError(t, watcher.Add(dir))
+	go runWatcher(&watchContext{
+		filedir:         dir,
+		callback:        func(filename string) { calls <- filename },
+		interestedEvent: fsnotify.Create,
+	}, watcher, done)
+
+	created := filepath.Join(dir, "new.txt")
+	writeFile(t, created, "x")
+
+	select {
+	case name := <-calls:
+		assert.Equal(t, created, name)
+	case <-time.After(callbackTimeout):
+		t.Fatal("directory watch did not fire for a created file")
+	}
+}