progressemitter_test.go 11 KB

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