progressemitter_test.go 11 KB

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