indexhandler.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. // Copyright (C) 2020 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "context"
  9. "fmt"
  10. "sync"
  11. "time"
  12. "github.com/syncthing/syncthing/lib/config"
  13. "github.com/syncthing/syncthing/lib/db"
  14. "github.com/syncthing/syncthing/lib/events"
  15. "github.com/syncthing/syncthing/lib/protocol"
  16. "github.com/syncthing/syncthing/lib/svcutil"
  17. "github.com/syncthing/syncthing/lib/ur"
  18. )
  19. type indexHandler struct {
  20. conn protocol.Connection
  21. downloads *deviceDownloadState
  22. folder string
  23. folderIsReceiveEncrypted bool
  24. prevSequence int64
  25. evLogger events.Logger
  26. cond *sync.Cond
  27. paused bool
  28. fset *db.FileSet
  29. runner service
  30. }
  31. func newIndexHandler(conn protocol.Connection, downloads *deviceDownloadState, folder config.FolderConfiguration, fset *db.FileSet, runner service, startInfo *clusterConfigDeviceInfo, evLogger events.Logger) *indexHandler {
  32. myIndexID := fset.IndexID(protocol.LocalDeviceID)
  33. mySequence := fset.Sequence(protocol.LocalDeviceID)
  34. var startSequence int64
  35. // This is the other side's description of what it knows
  36. // about us. Lets check to see if we can start sending index
  37. // updates directly or need to send the index from start...
  38. if startInfo.local.IndexID == myIndexID {
  39. // They say they've seen our index ID before, so we can
  40. // send a delta update only.
  41. if startInfo.local.MaxSequence > mySequence {
  42. // Safety check. They claim to have more or newer
  43. // index data than we have - either we have lost
  44. // index data, or reset the index without resetting
  45. // the IndexID, or something else weird has
  46. // happened. We send a full index to reset the
  47. // situation.
  48. l.Infof("Device %v folder %s is delta index compatible, but seems out of sync with reality", conn.DeviceID().Short(), folder.Description())
  49. startSequence = 0
  50. } else {
  51. l.Debugf("Device %v folder %s is delta index compatible (mlv=%d)", conn.DeviceID().Short(), folder.Description(), startInfo.local.MaxSequence)
  52. startSequence = startInfo.local.MaxSequence
  53. }
  54. } else if startInfo.local.IndexID != 0 {
  55. // They say they've seen an index ID from us, but it's
  56. // not the right one. Either they are confused or we
  57. // must have reset our database since last talking to
  58. // them. We'll start with a full index transfer.
  59. l.Infof("Device %v folder %s has mismatching index ID for us (%v != %v)", conn.DeviceID().Short(), folder.Description(), startInfo.local.IndexID, myIndexID)
  60. startSequence = 0
  61. } else {
  62. l.Debugf("Device %v folder %s has no index ID for us", conn.DeviceID().Short(), folder.Description())
  63. }
  64. // This is the other side's description of themselves. We
  65. // check to see that it matches the IndexID we have on file,
  66. // otherwise we drop our old index data and expect to get a
  67. // completely new set.
  68. theirIndexID := fset.IndexID(conn.DeviceID())
  69. if startInfo.remote.IndexID == 0 {
  70. // They're not announcing an index ID. This means they
  71. // do not support delta indexes and we should clear any
  72. // information we have from them before accepting their
  73. // index, which will presumably be a full index.
  74. l.Debugf("Device %v folder %s does not announce an index ID", conn.DeviceID().Short(), folder.Description())
  75. fset.Drop(conn.DeviceID())
  76. } else if startInfo.remote.IndexID != theirIndexID {
  77. // The index ID we have on file is not what they're
  78. // announcing. They must have reset their database and
  79. // will probably send us a full index. We drop any
  80. // information we have and remember this new index ID
  81. // instead.
  82. l.Infof("Device %v folder %s has a new index ID (%v)", conn.DeviceID().Short(), folder.Description(), startInfo.remote.IndexID)
  83. fset.Drop(conn.DeviceID())
  84. fset.SetIndexID(conn.DeviceID(), startInfo.remote.IndexID)
  85. }
  86. return &indexHandler{
  87. conn: conn,
  88. downloads: downloads,
  89. folder: folder.ID,
  90. folderIsReceiveEncrypted: folder.Type == config.FolderTypeReceiveEncrypted,
  91. prevSequence: startSequence,
  92. evLogger: evLogger,
  93. fset: fset,
  94. runner: runner,
  95. cond: sync.NewCond(new(sync.Mutex)),
  96. }
  97. }
  98. // waitForFileset waits for the handler to resume and fetches the current fileset.
  99. func (s *indexHandler) waitForFileset(ctx context.Context) (*db.FileSet, error) {
  100. s.cond.L.Lock()
  101. defer s.cond.L.Unlock()
  102. for s.paused {
  103. select {
  104. case <-ctx.Done():
  105. return nil, ctx.Err()
  106. default:
  107. s.cond.Wait()
  108. }
  109. }
  110. return s.fset, nil
  111. }
  112. func (s *indexHandler) Serve(ctx context.Context) (err error) {
  113. l.Debugf("Starting index handler for %s to %s at %s (slv=%d)", s.folder, s.conn.DeviceID().Short(), s.conn, s.prevSequence)
  114. stop := make(chan struct{})
  115. defer func() {
  116. err = svcutil.NoRestartErr(err)
  117. l.Debugf("Exiting index handler for %s to %s at %s: %v", s.folder, s.conn.DeviceID().Short(), s.conn, err)
  118. close(stop)
  119. }()
  120. // Broadcast the pause cond when the context quits
  121. go func() {
  122. select {
  123. case <-ctx.Done():
  124. s.cond.Broadcast()
  125. case <-stop:
  126. }
  127. }()
  128. // We need to send one index, regardless of whether there is something to send or not
  129. fset, err := s.waitForFileset(ctx)
  130. if err != nil {
  131. return err
  132. }
  133. err = s.sendIndexTo(ctx, fset)
  134. // Subscribe to LocalIndexUpdated (we have new information to send) and
  135. // DeviceDisconnected (it might be us who disconnected, so we should
  136. // exit).
  137. sub := s.evLogger.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  138. defer sub.Unsubscribe()
  139. evChan := sub.C()
  140. ticker := time.NewTicker(time.Minute)
  141. defer ticker.Stop()
  142. for err == nil {
  143. fset, err = s.waitForFileset(ctx)
  144. if err != nil {
  145. return err
  146. }
  147. // While we have sent a sequence at least equal to the one
  148. // currently in the database, wait for the local index to update. The
  149. // local index may update for other folders than the one we are
  150. // sending for.
  151. if fset.Sequence(protocol.LocalDeviceID) <= s.prevSequence {
  152. select {
  153. case <-ctx.Done():
  154. return ctx.Err()
  155. case <-evChan:
  156. case <-ticker.C:
  157. }
  158. continue
  159. }
  160. err = s.sendIndexTo(ctx, fset)
  161. // Wait a short amount of time before entering the next loop. If there
  162. // are continuous changes happening to the local index, this gives us
  163. // time to batch them up a little.
  164. select {
  165. case <-ctx.Done():
  166. return ctx.Err()
  167. case <-time.After(250 * time.Millisecond):
  168. }
  169. }
  170. return err
  171. }
  172. // resume might be called because the folder was actually resumed, or just
  173. // because the folder config changed (and thus the runner and potentially fset).
  174. func (s *indexHandler) resume(fset *db.FileSet, runner service) {
  175. s.cond.L.Lock()
  176. s.paused = false
  177. s.fset = fset
  178. s.runner = runner
  179. s.cond.Broadcast()
  180. s.cond.L.Unlock()
  181. }
  182. func (s *indexHandler) pause() {
  183. s.cond.L.Lock()
  184. if s.paused {
  185. s.evLogger.Log(events.Failure, "index handler got paused while already paused")
  186. }
  187. s.paused = true
  188. s.fset = nil
  189. s.runner = nil
  190. s.cond.Broadcast()
  191. s.cond.L.Unlock()
  192. }
  193. // sendIndexTo sends file infos with a sequence number higher than prevSequence and
  194. // returns the highest sent sequence number.
  195. func (s *indexHandler) sendIndexTo(ctx context.Context, fset *db.FileSet) error {
  196. // Keep track of the previous sequence we sent. This is separate from
  197. // s.prevSequence because the latter will skip over holes in the
  198. // sequence numberings, while sentPrevSequence should always be
  199. // precisely the highest previously sent sequence.
  200. sentPrevSequence := s.prevSequence
  201. initial := s.prevSequence == 0
  202. batch := db.NewFileInfoBatch(nil)
  203. var batchError error
  204. batch.SetFlushFunc(func(fs []protocol.FileInfo) error {
  205. select {
  206. case <-ctx.Done():
  207. return ctx.Err()
  208. default:
  209. }
  210. if len(fs) == 0 {
  211. // can't happen, flush is not called with an empty batch
  212. panic("bug: flush called with empty batch (race condition?)")
  213. }
  214. if batchError != nil {
  215. // can't happen, once an error is returned the index sender exits
  216. panic(fmt.Sprintf("bug: once failed it should stay failed (%v)", batchError))
  217. }
  218. l.Debugf("%v: Sending %d files (<%d bytes)", s, len(fs), batch.Size())
  219. lastSequence := fs[len(fs)-1].Sequence
  220. var err error
  221. if initial {
  222. initial = false
  223. err = s.conn.Index(ctx, &protocol.Index{
  224. Folder: s.folder,
  225. Files: fs,
  226. LastSequence: lastSequence,
  227. })
  228. } else {
  229. err = s.conn.IndexUpdate(ctx, &protocol.IndexUpdate{
  230. Folder: s.folder,
  231. Files: fs,
  232. PrevSequence: sentPrevSequence,
  233. LastSequence: lastSequence,
  234. })
  235. }
  236. if err != nil {
  237. batchError = err
  238. return err
  239. }
  240. sentPrevSequence = lastSequence
  241. return nil
  242. })
  243. var err error
  244. var f protocol.FileInfo
  245. snap, err := fset.Snapshot()
  246. if err != nil {
  247. return svcutil.AsFatalErr(err, svcutil.ExitError)
  248. }
  249. defer snap.Release()
  250. previousWasDelete := false
  251. snap.WithHaveSequence(s.prevSequence+1, func(fi protocol.FileIntf) bool {
  252. // This is to make sure that renames (which is an add followed by a delete) land in the same batch.
  253. // Even if the batch is full, we allow a last delete to slip in, we do this by making sure that
  254. // the batch ends with a non-delete, or that the last item in the batch is already a delete
  255. if batch.Full() && (!fi.IsDeleted() || previousWasDelete) {
  256. if err = batch.Flush(); err != nil {
  257. return false
  258. }
  259. }
  260. if fi.SequenceNo() < s.prevSequence+1 {
  261. s.logSequenceAnomaly("database returned sequence lower than requested", map[string]any{
  262. "sequence": fi.SequenceNo(),
  263. "start": s.prevSequence + 1,
  264. })
  265. }
  266. if f.Sequence > 0 && fi.SequenceNo() <= f.Sequence {
  267. s.logSequenceAnomaly("database returned non-increasing sequence", map[string]any{
  268. "sequence": fi.SequenceNo(),
  269. "start": s.prevSequence + 1,
  270. "previous": f.Sequence,
  271. })
  272. // Abort this round of index sending - the next one will pick
  273. // up from the last successful one with the repeaired db.
  274. defer func() {
  275. if fixed, dbErr := fset.RepairSequence(); dbErr != nil {
  276. l.Warnln("Failed repairing sequence entries:", dbErr)
  277. panic("Failed repairing sequence entries")
  278. } else {
  279. s.evLogger.Log(events.Failure, "detected and repaired non-increasing sequence")
  280. l.Infof("Repaired %v sequence entries in database", fixed)
  281. }
  282. }()
  283. return false
  284. }
  285. f = fi.(protocol.FileInfo)
  286. // If this is a folder receiving encrypted files only, we
  287. // mustn't ever send locally changed file infos. Those aren't
  288. // encrypted and thus would be a protocol error at the remote.
  289. if s.folderIsReceiveEncrypted && fi.IsReceiveOnlyChanged() {
  290. return true
  291. }
  292. f = prepareFileInfoForIndex(f)
  293. previousWasDelete = f.IsDeleted()
  294. batch.Append(f)
  295. return true
  296. })
  297. if err != nil {
  298. return err
  299. }
  300. if err := batch.Flush(); err != nil {
  301. return err
  302. }
  303. // Use the sequence of the snapshot we iterated as a starting point for the
  304. // next run. Previously we used the sequence of the last file we sent,
  305. // however it's possible that a higher sequence exists, just doesn't need to
  306. // be sent (e.g. in a receive-only folder, when a local change was
  307. // reverted). No point trying to send nothing again.
  308. s.prevSequence = snap.Sequence(protocol.LocalDeviceID)
  309. return nil
  310. }
  311. func (s *indexHandler) receive(fs []protocol.FileInfo, update bool, op string, prevSequence, lastSequence int64) error {
  312. deviceID := s.conn.DeviceID()
  313. s.cond.L.Lock()
  314. paused := s.paused
  315. fset := s.fset
  316. runner := s.runner
  317. s.cond.L.Unlock()
  318. if paused {
  319. l.Infof("%v for paused folder %q", op, s.folder)
  320. return fmt.Errorf("%v: %w", s.folder, ErrFolderPaused)
  321. }
  322. defer runner.SchedulePull()
  323. s.downloads.Update(s.folder, makeForgetUpdate(fs))
  324. if !update {
  325. fset.Drop(deviceID)
  326. }
  327. l.Debugf("Received %d files for %s from %s, prevSeq=%d, lastSeq=%d", len(fs), s.folder, deviceID.Short(), prevSequence, lastSequence)
  328. // Verify that the previous sequence number matches what we expected
  329. if exp := fset.Sequence(deviceID); prevSequence > 0 && prevSequence != exp {
  330. s.logSequenceAnomaly("index update with unexpected sequence", map[string]any{
  331. "prevSeq": prevSequence,
  332. "lastSeq": lastSequence,
  333. "batch": len(fs),
  334. "expectedPrev": exp,
  335. })
  336. }
  337. for i := range fs {
  338. // Verify index in relation to the claimed sequence boundaries
  339. if fs[i].Sequence < prevSequence {
  340. s.logSequenceAnomaly("file with sequence before prevSequence", map[string]any{
  341. "prevSeq": prevSequence,
  342. "lastSeq": lastSequence,
  343. "batch": len(fs),
  344. "seenSeq": fs[i].Sequence,
  345. "atIndex": i,
  346. })
  347. }
  348. if lastSequence > 0 && fs[i].Sequence > lastSequence {
  349. s.logSequenceAnomaly("file with sequence after lastSequence", map[string]any{
  350. "prevSeq": prevSequence,
  351. "lastSeq": lastSequence,
  352. "batch": len(fs),
  353. "seenSeq": fs[i].Sequence,
  354. "atIndex": i,
  355. })
  356. }
  357. if i > 0 && fs[i].Sequence <= fs[i-1].Sequence {
  358. s.logSequenceAnomaly("index update with non-increasing sequence", map[string]any{
  359. "prevSeq": prevSequence,
  360. "lastSeq": lastSequence,
  361. "batch": len(fs),
  362. "seenSeq": fs[i].Sequence,
  363. "atIndex": i,
  364. "precedingSeq": fs[i-1].Sequence,
  365. })
  366. }
  367. // The local attributes should never be transmitted over the wire.
  368. // Make sure they look like they weren't.
  369. fs[i].LocalFlags = 0
  370. fs[i].VersionHash = nil
  371. }
  372. // Verify the claimed last sequence number
  373. if lastSequence > 0 && len(fs) > 0 && lastSequence != fs[len(fs)-1].Sequence {
  374. s.logSequenceAnomaly("index update with unexpected last sequence", map[string]any{
  375. "prevSeq": prevSequence,
  376. "lastSeq": lastSequence,
  377. "batch": len(fs),
  378. "seenSeq": fs[len(fs)-1].Sequence,
  379. })
  380. }
  381. fset.Update(deviceID, fs)
  382. seq := fset.Sequence(deviceID)
  383. s.evLogger.Log(events.RemoteIndexUpdated, map[string]interface{}{
  384. "device": deviceID.String(),
  385. "folder": s.folder,
  386. "items": len(fs),
  387. "sequence": seq,
  388. "version": seq, // legacy for sequence
  389. })
  390. return nil
  391. }
  392. func (s *indexHandler) logSequenceAnomaly(msg string, extra map[string]any) {
  393. extraStrs := make(map[string]string, len(extra))
  394. for k, v := range extra {
  395. extraStrs[k] = fmt.Sprint(v)
  396. }
  397. s.evLogger.Log(events.Failure, ur.FailureData{
  398. Description: msg,
  399. Extra: extraStrs,
  400. })
  401. }
  402. func prepareFileInfoForIndex(f protocol.FileInfo) protocol.FileInfo {
  403. // Mark the file as invalid if any of the local bad stuff flags are set.
  404. f.RawInvalid = f.IsInvalid()
  405. // If the file is marked LocalReceive (i.e., changed locally on a
  406. // receive only folder) we do not want it to ever become the
  407. // globally best version, invalid or not.
  408. if f.IsReceiveOnlyChanged() {
  409. f.Version = protocol.Vector{}
  410. }
  411. // The trailer with the encrypted fileinfo is device local, don't send info
  412. // about that to remotes
  413. f.Size -= int64(f.EncryptionTrailerSize)
  414. f.EncryptionTrailerSize = 0
  415. // never sent externally
  416. f.LocalFlags = 0
  417. f.VersionHash = nil
  418. f.InodeChangeNs = 0
  419. return f
  420. }
  421. func (s *indexHandler) String() string {
  422. return fmt.Sprintf("indexHandler@%p for %s to %s at %s", s, s.folder, s.conn.DeviceID().Short(), s.conn)
  423. }
  424. type indexHandlerRegistry struct {
  425. evLogger events.Logger
  426. conn protocol.Connection
  427. downloads *deviceDownloadState
  428. indexHandlers *serviceMap[string, *indexHandler]
  429. startInfos map[string]*clusterConfigDeviceInfo
  430. folderStates map[string]*indexHandlerFolderState
  431. mut sync.Mutex
  432. }
  433. type indexHandlerFolderState struct {
  434. cfg config.FolderConfiguration
  435. fset *db.FileSet
  436. runner service
  437. }
  438. func newIndexHandlerRegistry(conn protocol.Connection, downloads *deviceDownloadState, evLogger events.Logger) *indexHandlerRegistry {
  439. r := &indexHandlerRegistry{
  440. evLogger: evLogger,
  441. conn: conn,
  442. downloads: downloads,
  443. indexHandlers: newServiceMap[string, *indexHandler](evLogger),
  444. startInfos: make(map[string]*clusterConfigDeviceInfo),
  445. folderStates: make(map[string]*indexHandlerFolderState),
  446. mut: sync.Mutex{},
  447. }
  448. return r
  449. }
  450. func (r *indexHandlerRegistry) String() string {
  451. return fmt.Sprintf("indexHandlerRegistry/%v", r.conn.DeviceID().Short())
  452. }
  453. func (r *indexHandlerRegistry) Serve(ctx context.Context) error {
  454. // Running the index handler registry means running the individual index
  455. // handler children.
  456. return r.indexHandlers.Serve(ctx)
  457. }
  458. func (r *indexHandlerRegistry) startLocked(folder config.FolderConfiguration, fset *db.FileSet, runner service, startInfo *clusterConfigDeviceInfo) {
  459. r.indexHandlers.RemoveAndWait(folder.ID, 0)
  460. delete(r.startInfos, folder.ID)
  461. is := newIndexHandler(r.conn, r.downloads, folder, fset, runner, startInfo, r.evLogger)
  462. r.indexHandlers.Add(folder.ID, is)
  463. // This new connection might help us get in sync.
  464. runner.SchedulePull()
  465. }
  466. // AddIndexInfo starts an index handler for given folder, unless it is paused.
  467. // If it is paused, the given startInfo is stored to start the sender once the
  468. // folder is resumed.
  469. // If an index handler is already running, it will be stopped first.
  470. func (r *indexHandlerRegistry) AddIndexInfo(folder string, startInfo *clusterConfigDeviceInfo) {
  471. r.mut.Lock()
  472. defer r.mut.Unlock()
  473. if r.indexHandlers.RemoveAndWait(folder, 0) == nil {
  474. l.Debugf("Removed index sender for device %v and folder %v due to added pending", r.conn.DeviceID().Short(), folder)
  475. }
  476. folderState, ok := r.folderStates[folder]
  477. if !ok {
  478. l.Debugf("Pending index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  479. r.startInfos[folder] = startInfo
  480. return
  481. }
  482. r.startLocked(folderState.cfg, folderState.fset, folderState.runner, startInfo)
  483. }
  484. // Remove stops a running index handler or removes one pending to be started.
  485. // It is a noop if the folder isn't known.
  486. func (r *indexHandlerRegistry) Remove(folder string) {
  487. r.mut.Lock()
  488. defer r.mut.Unlock()
  489. l.Debugf("Removing index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  490. r.indexHandlers.RemoveAndWait(folder, 0)
  491. delete(r.startInfos, folder)
  492. l.Debugf("Removed index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  493. }
  494. // RemoveAllExcept stops all running index handlers and removes those pending to be started,
  495. // except mentioned ones.
  496. // It is a noop if the folder isn't known.
  497. func (r *indexHandlerRegistry) RemoveAllExcept(except map[string]remoteFolderState) {
  498. r.mut.Lock()
  499. defer r.mut.Unlock()
  500. r.indexHandlers.Each(func(folder string, is *indexHandler) error {
  501. if _, ok := except[folder]; !ok {
  502. r.indexHandlers.RemoveAndWait(folder, 0)
  503. l.Debugf("Removed index handler for device %v and folder %v (removeAllExcept)", r.conn.DeviceID().Short(), folder)
  504. }
  505. return nil
  506. })
  507. for folder := range r.startInfos {
  508. if _, ok := except[folder]; !ok {
  509. delete(r.startInfos, folder)
  510. l.Debugf("Removed pending index handler for device %v and folder %v (removeAllExcept)", r.conn.DeviceID().Short(), folder)
  511. }
  512. }
  513. }
  514. // RegisterFolderState must be called whenever something about the folder
  515. // changes. The exception being if the folder is removed entirely, then call
  516. // Remove. The fset and runner arguments may be nil, if given folder is paused.
  517. func (r *indexHandlerRegistry) RegisterFolderState(folder config.FolderConfiguration, fset *db.FileSet, runner service) {
  518. if !folder.SharedWith(r.conn.DeviceID()) {
  519. r.Remove(folder.ID)
  520. return
  521. }
  522. r.mut.Lock()
  523. if folder.Paused {
  524. r.folderPausedLocked(folder.ID)
  525. } else {
  526. r.folderRunningLocked(folder, fset, runner)
  527. }
  528. r.mut.Unlock()
  529. }
  530. // folderPausedLocked stops a running index handler.
  531. // It is a noop if the folder isn't known or has not been started yet.
  532. func (r *indexHandlerRegistry) folderPausedLocked(folder string) {
  533. l.Debugf("Pausing index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  534. delete(r.folderStates, folder)
  535. if is, ok := r.indexHandlers.Get(folder); ok {
  536. is.pause()
  537. l.Debugf("Paused index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  538. } else {
  539. l.Debugf("No index handler for device %v and folder %v to pause", r.conn.DeviceID().Short(), folder)
  540. }
  541. }
  542. // folderRunningLocked resumes an already running index handler or starts it, if it
  543. // was added while paused.
  544. // It is a noop if the folder isn't known.
  545. func (r *indexHandlerRegistry) folderRunningLocked(folder config.FolderConfiguration, fset *db.FileSet, runner service) {
  546. r.folderStates[folder.ID] = &indexHandlerFolderState{
  547. cfg: folder,
  548. fset: fset,
  549. runner: runner,
  550. }
  551. is, isOk := r.indexHandlers.Get(folder.ID)
  552. if info, ok := r.startInfos[folder.ID]; ok {
  553. if isOk {
  554. r.indexHandlers.RemoveAndWait(folder.ID, 0)
  555. l.Debugf("Removed index handler for device %v and folder %v in resume", r.conn.DeviceID().Short(), folder.ID)
  556. }
  557. r.startLocked(folder, fset, runner, info)
  558. delete(r.startInfos, folder.ID)
  559. l.Debugf("Started index handler for device %v and folder %v in resume", r.conn.DeviceID().Short(), folder.ID)
  560. } else if isOk {
  561. l.Debugf("Resuming index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  562. is.resume(fset, runner)
  563. } else {
  564. l.Debugf("Not resuming index handler for device %v and folder %v as none is paused and there is no start info", r.conn.DeviceID().Short(), folder.ID)
  565. }
  566. }
  567. func (r *indexHandlerRegistry) ReceiveIndex(folder string, fs []protocol.FileInfo, update bool, op string, prevSequence, lastSequence int64) error {
  568. r.mut.Lock()
  569. defer r.mut.Unlock()
  570. is, isOk := r.indexHandlers.Get(folder)
  571. if !isOk {
  572. l.Infof("%v for nonexistent or paused folder %q", op, folder)
  573. return fmt.Errorf("%s: %w", folder, ErrFolderMissing)
  574. }
  575. return is.receive(fs, update, op, prevSequence, lastSequence)
  576. }
  577. // makeForgetUpdate takes an index update and constructs a download progress update
  578. // causing to forget any progress for files which we've just been sent.
  579. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  580. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  581. for _, file := range files {
  582. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  583. continue
  584. }
  585. updates = append(updates, protocol.FileDownloadProgressUpdate{
  586. Name: file.Name,
  587. Version: file.Version,
  588. UpdateType: protocol.FileDownloadProgressUpdateTypeForget,
  589. })
  590. }
  591. return updates
  592. }