progressemitter_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. // Copyright (C) 2014 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. "fmt"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "testing"
  13. "time"
  14. "github.com/syncthing/syncthing/lib/config"
  15. "github.com/syncthing/syncthing/lib/events"
  16. "github.com/syncthing/syncthing/lib/protocol"
  17. "github.com/syncthing/syncthing/lib/sync"
  18. )
  19. var timeout = 100 * time.Millisecond
  20. func caller(skip int) string {
  21. _, file, line, ok := runtime.Caller(skip + 1)
  22. if !ok {
  23. return "unknown"
  24. }
  25. return fmt.Sprintf("%s:%d", filepath.Base(file), line)
  26. }
  27. func expectEvent(w *events.Subscription, t *testing.T, size int) {
  28. event, err := w.Poll(timeout)
  29. if err != nil {
  30. t.Fatal("Unexpected error:", err, "at", caller(1))
  31. }
  32. if event.Type != events.DownloadProgress {
  33. t.Fatal("Unexpected event:", event, "at", caller(1))
  34. }
  35. data := event.Data.(map[string]map[string]*pullerProgress)
  36. if len(data) != size {
  37. t.Fatal("Unexpected event data size:", data, "at", caller(1))
  38. }
  39. }
  40. func expectTimeout(w *events.Subscription, t *testing.T) {
  41. _, err := w.Poll(timeout)
  42. if err != events.ErrTimeout {
  43. t.Fatal("Unexpected non-Timeout error:", err, "at", caller(1))
  44. }
  45. }
  46. func TestProgressEmitter(t *testing.T) {
  47. w := events.Default.Subscribe(events.DownloadProgress)
  48. c := createTmpWrapper(config.Configuration{})
  49. defer os.Remove(c.ConfigPath())
  50. c.SetOptions(config.OptionsConfiguration{
  51. ProgressUpdateIntervalS: 0,
  52. })
  53. p := NewProgressEmitter(c)
  54. go p.Serve()
  55. p.interval = 0
  56. expectTimeout(w, t)
  57. s := sharedPullerState{
  58. updated: time.Now(),
  59. mut: sync.NewRWMutex(),
  60. }
  61. p.Register(&s)
  62. expectEvent(w, t, 1)
  63. expectTimeout(w, t)
  64. s.copyDone(protocol.BlockInfo{})
  65. expectEvent(w, t, 1)
  66. expectTimeout(w, t)
  67. s.copiedFromOrigin()
  68. expectEvent(w, t, 1)
  69. expectTimeout(w, t)
  70. s.pullStarted()
  71. expectEvent(w, t, 1)
  72. expectTimeout(w, t)
  73. s.pullDone(protocol.BlockInfo{})
  74. expectEvent(w, t, 1)
  75. expectTimeout(w, t)
  76. p.Deregister(&s)
  77. expectEvent(w, t, 0)
  78. expectTimeout(w, t)
  79. }
  80. func TestSendDownloadProgressMessages(t *testing.T) {
  81. c := createTmpWrapper(config.Configuration{})
  82. defer os.Remove(c.ConfigPath())
  83. c.SetOptions(config.OptionsConfiguration{
  84. ProgressUpdateIntervalS: 0,
  85. TempIndexMinBlocks: 10,
  86. })
  87. fc := &fakeConnection{}
  88. p := NewProgressEmitter(c)
  89. p.temporaryIndexSubscribe(fc, []string{"folder", "folder2"})
  90. p.registry["folder"] = make(map[string]*sharedPullerState)
  91. p.registry["folder2"] = make(map[string]*sharedPullerState)
  92. p.registry["folderXXX"] = make(map[string]*sharedPullerState)
  93. expect := func(updateIdx int, state *sharedPullerState, updateType protocol.FileDownloadProgressUpdateType, version protocol.Vector, blocks []int32, remove bool) {
  94. messageIdx := -1
  95. for i, msg := range fc.downloadProgressMessages {
  96. if msg.folder == state.folder {
  97. messageIdx = i
  98. break
  99. }
  100. }
  101. if messageIdx < 0 {
  102. t.Errorf("Message for folder %s does not exist at %s", state.folder, caller(1))
  103. }
  104. msg := fc.downloadProgressMessages[messageIdx]
  105. // Don't know the index (it's random due to iterating maps)
  106. if updateIdx == -1 {
  107. for i, upd := range msg.updates {
  108. if upd.Name == state.file.Name {
  109. updateIdx = i
  110. break
  111. }
  112. }
  113. }
  114. if updateIdx == -1 {
  115. t.Errorf("Could not find update for %s at %s", state.file.Name, caller(1))
  116. }
  117. if updateIdx > len(msg.updates)-1 {
  118. t.Errorf("Update at index %d does not exist at %s", updateIdx, caller(1))
  119. }
  120. update := msg.updates[updateIdx]
  121. if update.UpdateType != updateType {
  122. t.Errorf("Wrong update type at %s", caller(1))
  123. }
  124. if !update.Version.Equal(version) {
  125. t.Errorf("Wrong version at %s", caller(1))
  126. }
  127. if len(update.BlockIndexes) != len(blocks) {
  128. t.Errorf("Wrong indexes. Have %d expect %d at %s", len(update.BlockIndexes), len(blocks), caller(1))
  129. }
  130. for i := range update.BlockIndexes {
  131. if update.BlockIndexes[i] != blocks[i] {
  132. t.Errorf("Index %d incorrect at %s", i, caller(1))
  133. }
  134. }
  135. if remove {
  136. fc.downloadProgressMessages = append(fc.downloadProgressMessages[:messageIdx], fc.downloadProgressMessages[messageIdx+1:]...)
  137. }
  138. }
  139. expectEmpty := func() {
  140. if len(fc.downloadProgressMessages) > 0 {
  141. t.Errorf("Still have something at %s: %#v", caller(1), fc.downloadProgressMessages)
  142. }
  143. }
  144. now := time.Now()
  145. tick := func() time.Time {
  146. now = now.Add(time.Second)
  147. return now
  148. }
  149. if len(fc.downloadProgressMessages) != 0 {
  150. t.Error("Expected no requests")
  151. }
  152. v1 := (protocol.Vector{}).Update(0)
  153. v2 := (protocol.Vector{}).Update(1)
  154. // Requires more than 10 blocks to work.
  155. blocks := make([]protocol.BlockInfo, 11)
  156. state1 := &sharedPullerState{
  157. folder: "folder",
  158. file: protocol.FileInfo{
  159. Name: "state1",
  160. Version: v1,
  161. Blocks: blocks,
  162. },
  163. mut: sync.NewRWMutex(),
  164. availableUpdated: time.Now(),
  165. }
  166. p.registry["folder"]["1"] = state1
  167. // Has no blocks, hence no message is sent
  168. sendMsgs(p)
  169. expectEmpty()
  170. // Returns update for puller with new extra blocks
  171. state1.available = []int32{1}
  172. sendMsgs(p)
  173. expect(0, state1, protocol.UpdateTypeAppend, v1, []int32{1}, true)
  174. expectEmpty()
  175. // Does nothing if nothing changes
  176. sendMsgs(p)
  177. expectEmpty()
  178. // Does nothing if timestamp updated, but no new blocks (should never happen)
  179. state1.availableUpdated = tick()
  180. sendMsgs(p)
  181. expectEmpty()
  182. // Does not return an update if date blocks change but date does not (should never happen)
  183. state1.available = []int32{1, 2}
  184. sendMsgs(p)
  185. expectEmpty()
  186. // If the date and blocks changes, returns only the diff
  187. state1.availableUpdated = tick()
  188. sendMsgs(p)
  189. expect(0, state1, protocol.UpdateTypeAppend, v1, []int32{2}, true)
  190. expectEmpty()
  191. // Returns forget and update if puller version has changed
  192. state1.file.Version = v2
  193. sendMsgs(p)
  194. expect(0, state1, protocol.UpdateTypeForget, v1, nil, false)
  195. expect(1, state1, protocol.UpdateTypeAppend, v2, []int32{1, 2}, true)
  196. expectEmpty()
  197. // Returns forget and append if sharedPullerState creation timer changes.
  198. state1.available = []int32{1}
  199. state1.availableUpdated = tick()
  200. state1.created = tick()
  201. sendMsgs(p)
  202. expect(0, state1, protocol.UpdateTypeForget, v2, nil, false)
  203. expect(1, state1, protocol.UpdateTypeAppend, v2, []int32{1}, true)
  204. expectEmpty()
  205. // Sends an empty update if new file exists, but does not have any blocks yet. (To indicate that the old blocks are no longer available)
  206. state1.file.Version = v1
  207. state1.available = nil
  208. state1.availableUpdated = tick()
  209. sendMsgs(p)
  210. expect(0, state1, protocol.UpdateTypeForget, v2, nil, false)
  211. expect(1, state1, protocol.UpdateTypeAppend, v1, nil, true)
  212. expectEmpty()
  213. // Updates for multiple files and folders can be combined
  214. state1.available = []int32{1, 2, 3}
  215. state1.availableUpdated = tick()
  216. state2 := &sharedPullerState{
  217. folder: "folder2",
  218. file: protocol.FileInfo{
  219. Name: "state2",
  220. Version: v1,
  221. Blocks: blocks,
  222. },
  223. mut: sync.NewRWMutex(),
  224. available: []int32{1, 2, 3},
  225. availableUpdated: time.Now(),
  226. }
  227. state3 := &sharedPullerState{
  228. folder: "folder",
  229. file: protocol.FileInfo{
  230. Name: "state3",
  231. Version: v1,
  232. Blocks: blocks,
  233. },
  234. mut: sync.NewRWMutex(),
  235. available: []int32{1, 2, 3},
  236. availableUpdated: time.Now(),
  237. }
  238. state4 := &sharedPullerState{
  239. folder: "folder2",
  240. file: protocol.FileInfo{
  241. Name: "state4",
  242. Version: v1,
  243. Blocks: blocks,
  244. },
  245. mut: sync.NewRWMutex(),
  246. available: []int32{1, 2, 3},
  247. availableUpdated: time.Now(),
  248. }
  249. p.registry["folder2"]["2"] = state2
  250. p.registry["folder"]["3"] = state3
  251. p.registry["folder2"]["4"] = state4
  252. sendMsgs(p)
  253. expect(-1, state1, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, false)
  254. expect(-1, state3, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, true)
  255. expect(-1, state2, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, false)
  256. expect(-1, state4, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, true)
  257. expectEmpty()
  258. // Returns forget if puller no longer exists, as well as updates if it has been updated.
  259. state1.available = []int32{1, 2, 3, 4, 5}
  260. state1.availableUpdated = tick()
  261. state2.available = []int32{1, 2, 3, 4, 5}
  262. state2.availableUpdated = tick()
  263. delete(p.registry["folder"], "3")
  264. delete(p.registry["folder2"], "4")
  265. sendMsgs(p)
  266. expect(-1, state1, protocol.UpdateTypeAppend, v1, []int32{4, 5}, false)
  267. expect(-1, state3, protocol.UpdateTypeForget, v1, nil, true)
  268. expect(-1, state2, protocol.UpdateTypeAppend, v1, []int32{4, 5}, false)
  269. expect(-1, state4, protocol.UpdateTypeForget, v1, nil, true)
  270. expectEmpty()
  271. // Deletions are sent only once (actual bug I found writing the tests)
  272. sendMsgs(p)
  273. sendMsgs(p)
  274. expectEmpty()
  275. // Not sent for "inactive" (symlinks, dirs, or wrong folder) pullers
  276. // Directory
  277. state5 := &sharedPullerState{
  278. folder: "folder",
  279. file: protocol.FileInfo{
  280. Name: "state5",
  281. Version: v1,
  282. Type: protocol.FileInfoTypeDirectory,
  283. Blocks: blocks,
  284. },
  285. mut: sync.NewRWMutex(),
  286. available: []int32{1, 2, 3},
  287. availableUpdated: time.Now(),
  288. }
  289. // Symlink
  290. state6 := &sharedPullerState{
  291. folder: "folder",
  292. file: protocol.FileInfo{
  293. Name: "state6",
  294. Version: v1,
  295. Type: protocol.FileInfoTypeSymlink,
  296. },
  297. mut: sync.NewRWMutex(),
  298. available: []int32{1, 2, 3},
  299. availableUpdated: time.Now(),
  300. }
  301. // Some other directory
  302. state7 := &sharedPullerState{
  303. folder: "folderXXX",
  304. file: protocol.FileInfo{
  305. Name: "state7",
  306. Version: v1,
  307. Blocks: blocks,
  308. },
  309. mut: sync.NewRWMutex(),
  310. available: []int32{1, 2, 3},
  311. availableUpdated: time.Now(),
  312. }
  313. // Less than 10 blocks
  314. state8 := &sharedPullerState{
  315. folder: "folder",
  316. file: protocol.FileInfo{
  317. Name: "state8",
  318. Version: v1,
  319. Blocks: blocks[:3],
  320. },
  321. mut: sync.NewRWMutex(),
  322. available: []int32{1, 2, 3},
  323. availableUpdated: time.Now(),
  324. }
  325. p.registry["folder"]["5"] = state5
  326. p.registry["folder"]["6"] = state6
  327. p.registry["folderXXX"]["7"] = state7
  328. p.registry["folder"]["8"] = state8
  329. sendMsgs(p)
  330. expectEmpty()
  331. // Device is no longer subscribed to a particular folder
  332. delete(p.registry["folder"], "1") // Clean up first
  333. delete(p.registry["folder2"], "2") // Clean up first
  334. sendMsgs(p)
  335. expect(-1, state1, protocol.UpdateTypeForget, v1, nil, true)
  336. expect(-1, state2, protocol.UpdateTypeForget, v1, nil, true)
  337. expectEmpty()
  338. p.registry["folder"]["1"] = state1
  339. p.registry["folder2"]["2"] = state2
  340. p.registry["folder"]["3"] = state3
  341. p.registry["folder2"]["4"] = state4
  342. sendMsgs(p)
  343. expect(-1, state1, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3, 4, 5}, false)
  344. expect(-1, state3, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, true)
  345. expect(-1, state2, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3, 4, 5}, false)
  346. expect(-1, state4, protocol.UpdateTypeAppend, v1, []int32{1, 2, 3}, true)
  347. expectEmpty()
  348. p.temporaryIndexUnsubscribe(fc)
  349. p.temporaryIndexSubscribe(fc, []string{"folder"})
  350. sendMsgs(p)
  351. // See progressemitter.go for explanation why this is commented out.
  352. // Search for state.cleanup
  353. //expect(-1, state2, protocol.UpdateTypeForget, v1, nil, false)
  354. //expect(-1, state4, protocol.UpdateTypeForget, v1, nil, true)
  355. expectEmpty()
  356. // Cleanup when device no longer exists
  357. p.temporaryIndexUnsubscribe(fc)
  358. sendMsgs(p)
  359. _, ok := p.sentDownloadStates[fc.ID()]
  360. if ok {
  361. t.Error("Should not be there")
  362. }
  363. }
  364. func sendMsgs(p *ProgressEmitter) {
  365. p.mut.Lock()
  366. defer p.mut.Unlock()
  367. p.sendDownloadProgressMessagesLocked()
  368. }