Просмотр исходного кода

Add syncthing stall detection watchdog

Toby Chui 1 день назад
Родитель
Сommit
e76911be96

+ 4 - 0
src/mod/fileservers/servers/syncthingserv/engine.go

@@ -46,6 +46,9 @@ type engine interface {
 	//Offers lists the folders a device wants to share with the server
 	//Offers lists the folders a device wants to share with the server
 	Offers(deviceID string) []Offer
 	Offers(deviceID string) []Offer
 	Rescan(folderID string) error
 	Rescan(folderID string) error
+	//RestartFolder stops a folder and starts it again, like pausing and
+	//resuming it, which gives up the requests a device never answered
+	RestartFolder(folderID string) error
 	//LocalBytes is the size of a folder as Syncthing counts it
 	//LocalBytes is the size of a folder as Syncthing counts it
 	LocalBytes(folderID string) (int64, bool)
 	LocalBytes(folderID string) (int64, bool)
 	//UnknownDevices tried to connect but nobody added them
 	//UnknownDevices tried to connect but nobody added them
@@ -62,6 +65,7 @@ type FolderStatus struct {
 	GlobalBytes int64
 	GlobalBytes int64
 	NeedFiles   int
 	NeedFiles   int
 	NeedBytes   int64
 	NeedBytes   int64
+	PulledBytes int64 //What arrived of the files being pulled right now
 	Changed     time.Time
 	Changed     time.Time
 }
 }
 
 

+ 36 - 0
src/mod/fileservers/servers/syncthingserv/engine_syncthing.go

@@ -244,6 +244,7 @@ func (e *stEngine) FolderStatus(id string) FolderStatus {
 	if need, err := in.NeedSize(id, protocol.LocalDeviceID); err == nil {
 	if need, err := in.NeedSize(id, protocol.LocalDeviceID); err == nil {
 		status.NeedFiles, status.NeedBytes = need.Files+need.Deleted, need.Bytes
 		status.NeedFiles, status.NeedBytes = need.Files+need.Deleted, need.Bytes
 	}
 	}
+	status.PulledBytes = in.FolderProgressBytesCompleted(id)
 	return status
 	return status
 }
 }
 
 
@@ -300,6 +301,41 @@ func (e *stEngine) Rescan(folderID string) error {
 	return in.ScanFolderSubdirs(folderID, nil)
 	return in.ScanFolderSubdirs(folderID, nil)
 }
 }
 
 
+// RestartFolder pauses a folder and resumes it. Syncthing only gives up a
+// block request when the folder stops, and has no restart of its own short
+// of a configuration change. Should the resume fail, the next applyConfig
+// unpauses the folder again.
+func (e *stEngine) RestartFolder(folderID string) error {
+	e.mu.Lock()
+	wrapper := e.cfg
+	e.mu.Unlock()
+	if wrapper == nil {
+		return errors.New("Syncthing is not running")
+	}
+	f, ok := wrapper.Folder(folderID)
+	if !ok {
+		return errors.New("no such folder")
+	}
+	if f.Paused {
+		return nil
+	}
+	for _, paused := range []bool{true, false} {
+		waiter, err := wrapper.Modify(func(c *config.Configuration) {
+			for i := range c.Folders {
+				if c.Folders[i].ID == folderID {
+					c.Folders[i].Paused = paused
+				}
+			}
+		})
+		if err != nil {
+			return err
+		}
+		//Returns once the folder stopped, or started again
+		waiter.Wait()
+	}
+	return nil
+}
+
 func (e *stEngine) LocalBytes(folderID string) (int64, bool) {
 func (e *stEngine) LocalBytes(folderID string) (int64, bool) {
 	in := e.internals()
 	in := e.internals()
 	if in == nil {
 	if in == nil {

+ 23 - 0
src/mod/fileservers/servers/syncthingserv/engine_syncthing_test.go

@@ -130,6 +130,29 @@ func TestEngineRunsSyncthingAsThePlanSays(t *testing.T) {
 		t.Errorf("local bytes = %d, %v", bytes, ok)
 		t.Errorf("local bytes = %d, %v", bytes, ok)
 	}
 	}
 
 
+	//A restart stops the folder and starts it again, and leaves the
+	//configuration as it was
+	waitFor(t, "the rescan to finish", 60*time.Second, func() bool {
+		return eng.FolderStatus("abcde-fghij").State == "idle"
+	})
+	before = eng.cfg.RawCopy()
+	changed := eng.FolderStatus("abcde-fghij").Changed
+	//Syncthing reports state changes to the second
+	time.Sleep(time.Until(changed.Add(time.Second)) + 100*time.Millisecond)
+	if err := eng.RestartFolder("abcde-fghij"); err != nil {
+		t.Fatalf("restart folder: %v", err)
+	}
+	if after := eng.cfg.RawCopy(); !reflect.DeepEqual(before.Folders, after.Folders) {
+		t.Errorf("restarting the folder changed its configuration")
+	}
+	waitFor(t, "the restarted folder to be idle again", 60*time.Second, func() bool {
+		st := eng.FolderStatus("abcde-fghij")
+		return st.State == "idle" && st.Changed.After(changed)
+	})
+	if err := eng.RestartFolder("no-such-folder"); err == nil {
+		t.Errorf("restarting a folder Syncthing does not have did not fail")
+	}
+
 	//Changes reach Syncthing
 	//Changes reach Syncthing
 	p.Folders[0].Mode = ModeTwoWay
 	p.Folders[0].Mode = ModeTwoWay
 	p.Folders[0].VersionDays = 0
 	p.Folders[0].VersionDays = 0

+ 13 - 1
src/mod/fileservers/servers/syncthingserv/syncthingserv.go

@@ -74,6 +74,7 @@ type Manager struct {
 	result    planResult
 	result    planResult
 	lastPath  map[string]string
 	lastPath  map[string]string
 	quotas    map[string]quotaWatch
 	quotas    map[string]quotaWatch
+	stalls    *stallWatch
 }
 }
 
 
 // NewManager prepares the manager and starts Syncthing if it was left on.
 // NewManager prepares the manager and starts Syncthing if it was left on.
@@ -95,6 +96,7 @@ func NewManager(opt *ManagerOption) (*Manager, error) {
 		eng:      eng,
 		eng:      eng,
 		lastPath: map[string]string{},
 		lastPath: map[string]string{},
 		quotas:   map[string]quotaWatch{},
 		quotas:   map[string]quotaWatch{},
+		stalls:   newStallWatch(),
 		result: planResult{
 		result: planResult{
 			DeviceReasons: map[string]Reason{},
 			DeviceReasons: map[string]Reason{},
 			FolderReasons: map[string]Reason{},
 			FolderReasons: map[string]Reason{},
@@ -189,6 +191,7 @@ func (m *Manager) startLocked() error {
 	}
 	}
 	m.running = true
 	m.running = true
 	m.result = result
 	m.result = result
+	m.stalls = newStallWatch()
 	m.gen++
 	m.gen++
 	m.quit = make(chan struct{})
 	m.quit = make(chan struct{})
 	go m.loop(m.gen, m.quit)
 	go m.loop(m.gen, m.quit)
@@ -208,10 +211,13 @@ func (m *Manager) stopLocked() {
 }
 }
 
 
 // loop applies the records again once a minute, which notices users who
 // loop applies the records again once a minute, which notices users who
-// lost their access, full quotas, and drives that went away.
+// lost their access, full quotas, and drives that went away, and restarts
+// folders that stopped receiving while syncing (watchdog.go).
 func (m *Manager) loop(gen int, quit chan struct{}) {
 func (m *Manager) loop(gen int, quit chan struct{}) {
 	ticker := time.NewTicker(reconcileInterval)
 	ticker := time.NewTicker(reconcileInterval)
 	defer ticker.Stop()
 	defer ticker.Stop()
+	stalls := time.NewTicker(stallCheckInterval)
+	defer stalls.Stop()
 	for {
 	for {
 		select {
 		select {
 		case <-quit:
 		case <-quit:
@@ -222,6 +228,12 @@ func (m *Manager) loop(gen int, quit chan struct{}) {
 				m.applyLocked()
 				m.applyLocked()
 			}
 			}
 			m.mu.Unlock()
 			m.mu.Unlock()
+		case <-stalls.C:
+			m.mu.Lock()
+			if m.running && m.gen == gen {
+				m.checkStallsLocked(time.Now())
+			}
+			m.mu.Unlock()
 		}
 		}
 	}
 	}
 }
 }

+ 17 - 2
src/mod/fileservers/servers/syncthingserv/syncthingserv_test.go

@@ -25,6 +25,8 @@ type fakeEngine struct {
 	applied  []plan
 	applied  []plan
 	offers   map[string][]Offer
 	offers   map[string][]Offer
 	bytes    map[string]int64
 	bytes    map[string]int64
+	status   map[string]FolderStatus
+	restarts []string
 	startErr error
 	startErr error
 }
 }
 
 
@@ -61,7 +63,14 @@ func (e *fakeEngine) ParseDeviceID(s string) (string, error) {
 	}
 	}
 	return s, nil
 	return s, nil
 }
 }
-func (e *fakeEngine) FolderStatus(id string) FolderStatus { return FolderStatus{State: "idle"} }
+func (e *fakeEngine) FolderStatus(id string) FolderStatus {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	if st, ok := e.status[id]; ok {
+		return st
+	}
+	return FolderStatus{State: "idle"}
+}
 func (e *fakeEngine) DeviceStatus(id string) DeviceStatus { return DeviceStatus{} }
 func (e *fakeEngine) DeviceStatus(id string) DeviceStatus { return DeviceStatus{} }
 func (e *fakeEngine) Offers(deviceID string) []Offer {
 func (e *fakeEngine) Offers(deviceID string) []Offer {
 	e.mu.Lock()
 	e.mu.Lock()
@@ -69,6 +78,12 @@ func (e *fakeEngine) Offers(deviceID string) []Offer {
 	return e.offers[deviceID]
 	return e.offers[deviceID]
 }
 }
 func (e *fakeEngine) Rescan(folderID string) error { return nil }
 func (e *fakeEngine) Rescan(folderID string) error { return nil }
+func (e *fakeEngine) RestartFolder(folderID string) error {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	e.restarts = append(e.restarts, folderID)
+	return nil
+}
 func (e *fakeEngine) LocalBytes(folderID string) (int64, bool) {
 func (e *fakeEngine) LocalBytes(folderID string) (int64, bool) {
 	e.mu.Lock()
 	e.mu.Lock()
 	defer e.mu.Unlock()
 	defer e.mu.Unlock()
@@ -106,7 +121,7 @@ func newEnv(t *testing.T) *testEnv {
 		t.Fatalf("database: %v", err)
 		t.Fatalf("database: %v", err)
 	}
 	}
 	t.Cleanup(db.Close)
 	t.Cleanup(db.Close)
-	env := &testEnv{eng: &fakeEngine{offers: map[string][]Offer{}, bytes: map[string]int64{}}, db: db, root: filepath.Join(dir, "drives"), password: true}
+	env := &testEnv{eng: &fakeEngine{offers: map[string][]Offer{}, bytes: map[string]int64{}, status: map[string]FolderStatus{}}, db: db, root: filepath.Join(dir, "drives"), password: true}
 	groups := map[string][]string{"alice": {"administrator"}, "bob": {"family"}, "carol": {"guests"}}
 	groups := map[string][]string{"alice": {"administrator"}, "bob": {"family"}, "carol": {"guests"}}
 	opt := &ManagerOption{
 	opt := &ManagerOption{
 		Sysdb:    db,
 		Sysdb:    db,

+ 137 - 0
src/mod/fileservers/servers/syncthingserv/watchdog.go

@@ -0,0 +1,137 @@
+package syncthingserv
+
+/*
+	Stall watchdog
+
+	Syncthing pulls a file by asking a device for each of its blocks, and
+	waits for every answer without a time limit: only the answer, the folder
+	stopping or the connection closing ends the wait. A device that keeps the
+	connection alive but never answers some requests (the iOS apps do this
+	while iOS holds them back) leaves the folder syncing forever with nothing
+	arriving. Pausing and resuming the folder gives those requests up and asks
+	again, so the watchdog does that once a syncing folder has received
+	nothing for a while.
+
+	The wait doubles each time a folder is restarted without finishing a
+	file in between, so a device that is only very slow is not restarted
+	over and over, losing the blocks it was sending each time.
+*/
+
+import (
+	"time"
+
+	"imuslab.com/arozos/mod/info/logger"
+)
+
+const (
+	stallCheckInterval = 30 * time.Second
+	stallTimeout       = 3 * time.Minute  //Syncing with nothing arriving for this long restarts the folder
+	stallTimeoutMax    = 30 * time.Minute //The longest the doubled wait gets
+	stateSyncing       = "syncing"        //Syncthing's name of the pulling state
+)
+
+// progressMark is what changes while a folder receives files.
+type progressMark struct {
+	localFiles  int   //Changes when a file is finished or deleted
+	localBytes  int64 //Changes when a file is finished or deleted
+	pulledBytes int64 //Grows as blocks of the files being pulled arrive
+}
+
+func markOf(st FolderStatus) progressMark {
+	return progressMark{localFiles: st.LocalFiles, localBytes: st.LocalBytes, pulledBytes: st.PulledBytes}
+}
+
+// finished reports a file finished or deleted since the other mark. The
+// pulled bytes also change when a restarted folder picks up its temporary
+// files again, so only these count as real progress for the backoff.
+func (p progressMark) finished(other progressMark) bool {
+	return p.localFiles != other.localFiles || p.localBytes != other.localBytes
+}
+
+type stallState struct {
+	mark    progressMark
+	syncing bool          //State at the last look
+	since   time.Time     //Last change, start of syncing, or last restart
+	timeout time.Duration //How long nothing may arrive before a restart
+}
+
+// stallWatch follows the progress of every folder.
+type stallWatch struct {
+	folders map[string]*stallState
+}
+
+func newStallWatch() *stallWatch {
+	return &stallWatch{folders: map[string]*stallState{}}
+}
+
+// observe takes the status of a folder and reports whether it has been
+// syncing with nothing arriving long enough to be restarted.
+func (w *stallWatch) observe(id string, st FolderStatus, now time.Time) bool {
+	mark := markOf(st)
+	syncing := st.State == stateSyncing
+	s, ok := w.folders[id]
+	if !ok {
+		w.folders[id] = &stallState{mark: mark, syncing: syncing, since: now, timeout: stallTimeout}
+		return false
+	}
+	if !syncing || !s.syncing {
+		//Only time spent syncing counts. The wait stays doubled unless the
+		//pull that just ended finished files: a restarted folder scans
+		//first, and should not reset it by doing so.
+		if s.syncing && mark.finished(s.mark) {
+			s.timeout = stallTimeout
+		}
+		s.mark, s.syncing, s.since = mark, syncing, now
+		return false
+	}
+	if mark != s.mark {
+		if mark.finished(s.mark) {
+			s.timeout = stallTimeout
+		}
+		s.mark, s.since = mark, now
+		return false
+	}
+	return now.Sub(s.since) >= s.timeout
+}
+
+// restarted starts the wait of a folder again, twice as long as before.
+func (w *stallWatch) restarted(id string, now time.Time) {
+	s, ok := w.folders[id]
+	if !ok {
+		return
+	}
+	s.since = now
+	s.timeout = min(s.timeout*2, stallTimeoutMax)
+}
+
+// keep forgets the folders that are not in ids.
+func (w *stallWatch) keep(ids map[string]bool) {
+	for id := range w.folders {
+		if !ids[id] {
+			delete(w.folders, id)
+		}
+	}
+}
+
+// checkStallsLocked restarts the folders that stopped receiving while
+// syncing. The caller holds m.mu.
+func (m *Manager) checkStallsLocked(now time.Time) {
+	active := map[string]bool{}
+	for _, f := range m.result.Plan.Folders {
+		if f.Paused {
+			continue
+		}
+		active[f.ID] = true
+		if !m.stalls.observe(f.ID, m.eng.FolderStatus(f.ID), now) {
+			continue
+		}
+		waited := m.stalls.folders[f.ID].timeout
+		m.stalls.restarted(f.ID, now)
+		if err := m.eng.RestartFolder(f.ID); err != nil {
+			logger.PrintAndLog(logTitle, "Folder "+f.ID+" ("+f.Label+") stalled, but could not be restarted", err)
+			continue
+		}
+		logger.PrintAndLog(logTitle, "Folder "+f.ID+" ("+f.Label+") received nothing for "+waited.String()+" while syncing, restarted it", nil)
+	}
+	m.stalls.keep(active)
+}

+ 173 - 0
src/mod/fileservers/servers/syncthingserv/watchdog_test.go

@@ -0,0 +1,173 @@
+package syncthingserv
+
+import (
+	"net/url"
+	"slices"
+	"testing"
+	"time"
+)
+
+// stallStep is one look at a folder, at an offset from the start.
+type stallStep struct {
+	at          time.Duration
+	state       string
+	localFiles  int
+	pulledBytes int64
+	wantRestart bool
+}
+
+func runStallSteps(t *testing.T, w *stallWatch, start time.Time, steps []stallStep) {
+	t.Helper()
+	for i, s := range steps {
+		st := FolderStatus{State: s.state, LocalFiles: s.localFiles, LocalBytes: int64(s.localFiles) * 100, PulledBytes: s.pulledBytes}
+		now := start.Add(s.at)
+		got := w.observe("f1", st, now)
+		if got != s.wantRestart {
+			t.Fatalf("step %d (%v, %s): restart = %v, want %v", i, s.at, s.state, got, s.wantRestart)
+		}
+		if got {
+			w.restarted("f1", now)
+		}
+	}
+}
+
+func TestStallWatchObserve(t *testing.T) {
+	m := time.Minute
+	tests := []struct {
+		name  string
+		steps []stallStep
+	}{
+		{"blocks keep arriving", []stallStep{
+			{0, "syncing", 1, 0, false},
+			{2 * m, "syncing", 1, 10, false},
+			{4 * m, "syncing", 1, 20, false},
+			{6 * m, "syncing", 1, 30, false},
+			{8 * m, "syncing", 2, 0, false},
+		}},
+		{"nothing arrives while syncing", []stallStep{
+			{0, "syncing", 1, 10, false},
+			{2 * m, "syncing", 1, 10, false},
+			{3*m - time.Second, "syncing", 1, 10, false},
+			{3 * m, "syncing", 1, 10, true},
+		}},
+		{"idle folders are left alone", []stallStep{
+			{0, "idle", 5, 0, false},
+			{10 * m, "idle", 5, 0, false},
+			{60 * m, "idle", 5, 0, false},
+		}},
+		{"only time spent syncing counts", []stallStep{
+			{0, "idle", 1, 0, false},
+			{10 * m, "scanning", 1, 0, false},
+			{11 * m, "syncing", 1, 0, false},
+			{13 * m, "syncing", 1, 0, false},
+			{14 * m, "syncing", 1, 0, true},
+		}},
+		{"waiting for another folder is not a stall", []stallStep{
+			{0, "sync-waiting", 1, 0, false},
+			{20 * m, "sync-waiting", 1, 0, false},
+		}},
+	}
+	start := time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC)
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			runStallSteps(t, newStallWatch(), start, tt.steps)
+		})
+	}
+}
+
+func TestStallWatchBackoff(t *testing.T) {
+	m := time.Minute
+	start := time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC)
+	w := newStallWatch()
+	runStallSteps(t, w, start, []stallStep{
+		{0, "syncing", 1, 50, false},
+		{3 * m, "syncing", 1, 50, true}, //First stall after 3 minutes
+		//The restarted folder scans, then picks its temporary file up again:
+		//neither resets the doubled wait
+		{4 * m, "scanning", 1, 0, false},
+		{5 * m, "syncing", 1, 50, false},
+		{10 * m, "syncing", 1, 50, false},
+		{11 * m, "syncing", 1, 50, true}, //6 minutes this time
+		{22 * m, "syncing", 1, 50, false},
+		{23 * m, "syncing", 1, 50, true}, //12 minutes
+		{46 * m, "syncing", 1, 50, false},
+		{47 * m, "syncing", 1, 50, true}, //24 minutes
+		{76 * m, "syncing", 1, 50, false},
+		{77 * m, "syncing", 1, 50, true}, //Capped at 30 minutes
+		//A finished file brings the wait back to 3 minutes
+		{80 * m, "syncing", 2, 0, false},
+		{83 * m, "syncing", 2, 0, true},
+		{89 * m, "syncing", 2, 0, true}, //6 minutes again
+		//So does a pull that finished files and went idle in between looks
+		{90 * m, "idle", 3, 0, false},
+		{91 * m, "syncing", 3, 0, false},
+		{94 * m, "syncing", 3, 0, true},
+	})
+}
+
+func TestStallWatchKeep(t *testing.T) {
+	w := newStallWatch()
+	now := time.Now()
+	for _, id := range []string{"a", "b", "c"} {
+		w.observe(id, FolderStatus{State: "syncing"}, now)
+	}
+	w.keep(map[string]bool{"b": true})
+	if len(w.folders) != 1 || w.folders["b"] == nil {
+		t.Errorf("folders after keep = %v, want only b", w.folders)
+	}
+}
+
+func TestCheckStallsRestartsOnlyStalledFolders(t *testing.T) {
+	env := newEnv(t)
+	env.m.ServerToggle(true)
+	if e := env.addDevice(t, "alice", devA1); e != "" {
+		t.Fatalf("add device: %s", e)
+	}
+	stuck, e := env.addFolder(t, "alice", url.Values{"path": {"user:/Phone/Whatsapp"}, "devices": {`["` + devA1 + `"]`}})
+	if e != "" {
+		t.Fatalf("add folder: %s", e)
+	}
+	moving, e := env.addFolder(t, "alice", url.Values{"path": {"user:/Phone/Camera"}, "devices": {`["` + devA1 + `"]`}})
+	if e != "" {
+		t.Fatalf("add folder: %s", e)
+	}
+	idle, e := env.addFolder(t, "alice", url.Values{"path": {"user:/Phone/Notes"}, "devices": {`["` + devA1 + `"]`}})
+	if e != "" {
+		t.Fatalf("add folder: %s", e)
+	}
+
+	start := time.Now()
+	check := func(offset time.Duration, pulled int64) {
+		env.eng.mu.Lock()
+		env.eng.status[stuck] = FolderStatus{State: "syncing", LocalFiles: 3795, PulledBytes: 1000}
+		env.eng.status[moving] = FolderStatus{State: "syncing", LocalFiles: 10, PulledBytes: pulled}
+		env.eng.status[idle] = FolderStatus{State: "idle", LocalFiles: 4}
+		env.eng.mu.Unlock()
+		env.m.mu.Lock()
+		env.m.checkStallsLocked(start.Add(offset))
+		env.m.mu.Unlock()
+	}
+	check(0, 0)
+	check(2*time.Minute, 100)
+	if len(env.eng.restarts) != 0 {
+		t.Fatalf("restarted %v before any folder stalled", env.eng.restarts)
+	}
+	check(3*time.Minute, 200)
+	if !slices.Equal(env.eng.restarts, []string{stuck}) {
+		t.Fatalf("restarts = %v, want only the stalled folder %s", env.eng.restarts, stuck)
+	}
+	//Right after a restart the stuck folder gets a fresh, longer wait
+	check(4*time.Minute, 300)
+	if len(env.eng.restarts) != 1 {
+		t.Fatalf("restarts = %v, want no second restart yet", env.eng.restarts)
+	}
+
+	//A paused folder is never restarted
+	if _, result, _ := env.call(t, env.m.HandleFolderEdit, "alice", url.Values{"id": {stuck}, "paused": {"true"}}); errorOf(result) != "" {
+		t.Fatalf("pause: %s", errorOf(result))
+	}
+	check(60*time.Minute, 400)
+	if len(env.eng.restarts) != 1 {
+		t.Fatalf("restarts = %v, a paused folder was restarted", env.eng.restarts)
+	}
+}