progressemitter_test.go 11 KB

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