rwfolder_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. "crypto/rand"
  9. "io"
  10. "os"
  11. "path/filepath"
  12. "testing"
  13. "time"
  14. "github.com/syncthing/syncthing/lib/db"
  15. "github.com/syncthing/syncthing/lib/fs"
  16. "github.com/syncthing/syncthing/lib/ignore"
  17. "github.com/syncthing/syncthing/lib/protocol"
  18. "github.com/syncthing/syncthing/lib/scanner"
  19. "github.com/syncthing/syncthing/lib/sync"
  20. )
  21. func TestMain(m *testing.M) {
  22. // We do this to make sure that the temp file required for the tests
  23. // does not get removed during the tests. Also set the prefix so it's
  24. // found correctly regardless of platform.
  25. if ignore.TempPrefix != ignore.WindowsTempPrefix {
  26. originalPrefix := ignore.TempPrefix
  27. ignore.TempPrefix = ignore.WindowsTempPrefix
  28. defer func() {
  29. ignore.TempPrefix = originalPrefix
  30. }()
  31. }
  32. future := time.Now().Add(time.Hour)
  33. err := os.Chtimes(filepath.Join("testdata", ignore.TempName("file")), future, future)
  34. if err != nil {
  35. panic(err)
  36. }
  37. os.Exit(m.Run())
  38. }
  39. var blocks = []protocol.BlockInfo{
  40. {Hash: []uint8{0xfa, 0x43, 0x23, 0x9b, 0xce, 0xe7, 0xb9, 0x7c, 0xa6, 0x2f, 0x0, 0x7c, 0xc6, 0x84, 0x87, 0x56, 0xa, 0x39, 0xe1, 0x9f, 0x74, 0xf3, 0xdd, 0xe7, 0x48, 0x6d, 0xb3, 0xf9, 0x8d, 0xf8, 0xe4, 0x71}}, // Zero'ed out block
  41. {Offset: 0, Size: 0x20000, Hash: []uint8{0x7e, 0xad, 0xbc, 0x36, 0xae, 0xbb, 0xcf, 0x74, 0x43, 0xe2, 0x7a, 0x5a, 0x4b, 0xb8, 0x5b, 0xce, 0xe6, 0x9e, 0x1e, 0x10, 0xf9, 0x8a, 0xbc, 0x77, 0x95, 0x2, 0x29, 0x60, 0x9e, 0x96, 0xae, 0x6c}},
  42. {Offset: 131072, Size: 0x20000, Hash: []uint8{0x3c, 0xc4, 0x20, 0xf4, 0xb, 0x2e, 0xcb, 0xb9, 0x5d, 0xce, 0x34, 0xa8, 0xc3, 0x92, 0xea, 0xf3, 0xda, 0x88, 0x33, 0xee, 0x7a, 0xb6, 0xe, 0xf1, 0x82, 0x5e, 0xb0, 0xa9, 0x26, 0xa9, 0xc0, 0xef}},
  43. {Offset: 262144, Size: 0x20000, Hash: []uint8{0x76, 0xa8, 0xc, 0x69, 0xd7, 0x5c, 0x52, 0xfd, 0xdf, 0x55, 0xef, 0x44, 0xc1, 0xd6, 0x25, 0x48, 0x4d, 0x98, 0x48, 0x4d, 0xaa, 0x50, 0xf6, 0x6b, 0x32, 0x47, 0x55, 0x81, 0x6b, 0xed, 0xee, 0xfb}},
  44. {Offset: 393216, Size: 0x20000, Hash: []uint8{0x44, 0x1e, 0xa4, 0xf2, 0x8d, 0x1f, 0xc3, 0x1b, 0x9d, 0xa5, 0x18, 0x5e, 0x59, 0x1b, 0xd8, 0x5c, 0xba, 0x7d, 0xb9, 0x8d, 0x70, 0x11, 0x5c, 0xea, 0xa1, 0x57, 0x4d, 0xcb, 0x3c, 0x5b, 0xf8, 0x6c}},
  45. {Offset: 524288, Size: 0x20000, Hash: []uint8{0x8, 0x40, 0xd0, 0x5e, 0x80, 0x0, 0x0, 0x7c, 0x8b, 0xb3, 0x8b, 0xf7, 0x7b, 0x23, 0x26, 0x28, 0xab, 0xda, 0xcf, 0x86, 0x8f, 0xc2, 0x8a, 0x39, 0xc6, 0xe6, 0x69, 0x59, 0x97, 0xb6, 0x1a, 0x43}},
  46. {Offset: 655360, Size: 0x20000, Hash: []uint8{0x38, 0x8e, 0x44, 0xcb, 0x30, 0xd8, 0x90, 0xf, 0xce, 0x7, 0x4b, 0x58, 0x86, 0xde, 0xce, 0x59, 0xa2, 0x46, 0xd2, 0xf9, 0xba, 0xaf, 0x35, 0x87, 0x38, 0xdf, 0xd2, 0xd, 0xf9, 0x45, 0xed, 0x91}},
  47. {Offset: 786432, Size: 0x20000, Hash: []uint8{0x32, 0x28, 0xcd, 0xf, 0x37, 0x21, 0xe5, 0xd4, 0x1e, 0x58, 0x87, 0x73, 0x8e, 0x36, 0xdf, 0xb2, 0x70, 0x78, 0x56, 0xc3, 0x42, 0xff, 0xf7, 0x8f, 0x37, 0x95, 0x0, 0x26, 0xa, 0xac, 0x54, 0x72}},
  48. {Offset: 917504, Size: 0x20000, Hash: []uint8{0x96, 0x6b, 0x15, 0x6b, 0xc4, 0xf, 0x19, 0x18, 0xca, 0xbb, 0x5f, 0xd6, 0xbb, 0xa2, 0xc6, 0x2a, 0xac, 0xbb, 0x8a, 0xb9, 0xce, 0xec, 0x4c, 0xdb, 0x78, 0xec, 0x57, 0x5d, 0x33, 0xf9, 0x8e, 0xaf}},
  49. }
  50. var folders = []string{"default"}
  51. func setUpFile(filename string, blockNumbers []int) protocol.FileInfo {
  52. // Create existing file
  53. existingBlocks := make([]protocol.BlockInfo, len(blockNumbers))
  54. for i := range blockNumbers {
  55. existingBlocks[i] = blocks[blockNumbers[i]]
  56. }
  57. return protocol.FileInfo{
  58. Name: filename,
  59. Blocks: existingBlocks,
  60. }
  61. }
  62. func setUpModel(file protocol.FileInfo) *Model {
  63. db := db.OpenMemory()
  64. model := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  65. model.AddFolder(defaultFolderConfig)
  66. // Update index
  67. model.updateLocalsFromScanning("default", []protocol.FileInfo{file})
  68. return model
  69. }
  70. func setUpSendReceiveFolder(model *Model) *sendReceiveFolder {
  71. f := &sendReceiveFolder{
  72. folder: folder{
  73. stateTracker: newStateTracker("default"),
  74. model: model,
  75. initialScanCompleted: make(chan struct{}),
  76. },
  77. mtimeFS: fs.NewMtimeFS(fs.DefaultFilesystem, db.NewNamespacedKV(model.db, "mtime")),
  78. dir: "testdata",
  79. queue: newJobQueue(),
  80. errors: make(map[string]string),
  81. errorsMut: sync.NewMutex(),
  82. }
  83. // Folders are never actually started, so no initial scan will be done
  84. close(f.initialScanCompleted)
  85. return f
  86. }
  87. // Layout of the files: (indexes from the above array)
  88. // 12345678 - Required file
  89. // 02005008 - Existing file (currently in the index)
  90. // 02340070 - Temp file on the disk
  91. func TestHandleFile(t *testing.T) {
  92. // After the diff between required and existing we should:
  93. // Copy: 2, 5, 8
  94. // Pull: 1, 3, 4, 6, 7
  95. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  96. existingFile := setUpFile("filex", existingBlocks)
  97. requiredFile := existingFile
  98. requiredFile.Blocks = blocks[1:]
  99. m := setUpModel(existingFile)
  100. f := setUpSendReceiveFolder(m)
  101. copyChan := make(chan copyBlocksState, 1)
  102. f.handleFile(requiredFile, copyChan, nil)
  103. // Receive the results
  104. toCopy := <-copyChan
  105. if len(toCopy.blocks) != 8 {
  106. t.Errorf("Unexpected count of copy blocks: %d != 8", len(toCopy.blocks))
  107. }
  108. for _, block := range blocks[1:] {
  109. found := false
  110. for _, toCopyBlock := range toCopy.blocks {
  111. if string(toCopyBlock.Hash) == string(block.Hash) {
  112. found = true
  113. break
  114. }
  115. }
  116. if !found {
  117. t.Errorf("Did not find block %s", block.String())
  118. }
  119. }
  120. }
  121. func TestHandleFileWithTemp(t *testing.T) {
  122. // After diff between required and existing we should:
  123. // Copy: 2, 5, 8
  124. // Pull: 1, 3, 4, 6, 7
  125. // After dropping out blocks already on the temp file we should:
  126. // Copy: 5, 8
  127. // Pull: 1, 6
  128. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  129. existingFile := setUpFile("file", existingBlocks)
  130. requiredFile := existingFile
  131. requiredFile.Blocks = blocks[1:]
  132. m := setUpModel(existingFile)
  133. f := setUpSendReceiveFolder(m)
  134. copyChan := make(chan copyBlocksState, 1)
  135. f.handleFile(requiredFile, copyChan, nil)
  136. // Receive the results
  137. toCopy := <-copyChan
  138. if len(toCopy.blocks) != 4 {
  139. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  140. }
  141. for _, idx := range []int{1, 5, 6, 8} {
  142. found := false
  143. block := blocks[idx]
  144. for _, toCopyBlock := range toCopy.blocks {
  145. if string(toCopyBlock.Hash) == string(block.Hash) {
  146. found = true
  147. break
  148. }
  149. }
  150. if !found {
  151. t.Errorf("Did not find block %s", block.String())
  152. }
  153. }
  154. }
  155. func TestCopierFinder(t *testing.T) {
  156. // After diff between required and existing we should:
  157. // Copy: 1, 2, 3, 4, 6, 7, 8
  158. // Since there is no existing file, nor a temp file
  159. // After dropping out blocks found locally:
  160. // Pull: 1, 5, 6, 8
  161. tempFile := filepath.Join("testdata", ignore.TempName("file2"))
  162. err := os.Remove(tempFile)
  163. if err != nil && !os.IsNotExist(err) {
  164. t.Error(err)
  165. }
  166. existingBlocks := []int{0, 2, 3, 4, 0, 0, 7, 0}
  167. existingFile := setUpFile(ignore.TempName("file"), existingBlocks)
  168. requiredFile := existingFile
  169. requiredFile.Blocks = blocks[1:]
  170. requiredFile.Name = "file2"
  171. m := setUpModel(existingFile)
  172. f := setUpSendReceiveFolder(m)
  173. copyChan := make(chan copyBlocksState)
  174. pullChan := make(chan pullBlockState, 4)
  175. finisherChan := make(chan *sharedPullerState, 1)
  176. // Run a single fetcher routine
  177. go f.copierRoutine(copyChan, pullChan, finisherChan)
  178. f.handleFile(requiredFile, copyChan, finisherChan)
  179. pulls := []pullBlockState{<-pullChan, <-pullChan, <-pullChan, <-pullChan}
  180. finish := <-finisherChan
  181. select {
  182. case <-pullChan:
  183. t.Fatal("Pull channel has data to be read")
  184. case <-finisherChan:
  185. t.Fatal("Finisher channel has data to be read")
  186. default:
  187. }
  188. // Verify that the right blocks went into the pull list.
  189. // They are pulled in random order.
  190. for _, idx := range []int{1, 5, 6, 8} {
  191. found := false
  192. block := blocks[idx]
  193. for _, pulledBlock := range pulls {
  194. if string(pulledBlock.block.Hash) == string(block.Hash) {
  195. found = true
  196. break
  197. }
  198. }
  199. if !found {
  200. t.Errorf("Did not find block %s", block.String())
  201. }
  202. if string(finish.file.Blocks[idx-1].Hash) != string(blocks[idx].Hash) {
  203. t.Errorf("Block %d mismatch: %s != %s", idx, finish.file.Blocks[idx-1].String(), blocks[idx].String())
  204. }
  205. }
  206. // Verify that the fetched blocks have actually been written to the temp file
  207. blks, err := scanner.HashFile(fs.DefaultFilesystem, tempFile, protocol.BlockSize, nil, false)
  208. if err != nil {
  209. t.Log(err)
  210. }
  211. for _, eq := range []int{2, 3, 4, 7} {
  212. if string(blks[eq-1].Hash) != string(blocks[eq].Hash) {
  213. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  214. }
  215. }
  216. finish.fd.Close()
  217. os.Remove(tempFile)
  218. }
  219. func TestWeakHash(t *testing.T) {
  220. tempFile := filepath.Join("testdata", ignore.TempName("weakhash"))
  221. var shift int64 = 10
  222. var size int64 = 1 << 20
  223. expectBlocks := int(size / protocol.BlockSize)
  224. expectPulls := int(shift / protocol.BlockSize)
  225. if shift > 0 {
  226. expectPulls++
  227. }
  228. cleanup := func() {
  229. for _, path := range []string{tempFile, "testdata/weakhash"} {
  230. os.Remove(path)
  231. }
  232. }
  233. cleanup()
  234. defer cleanup()
  235. f, err := os.Create("testdata/weakhash")
  236. if err != nil {
  237. t.Error(err)
  238. }
  239. defer f.Close()
  240. _, err = io.CopyN(f, rand.Reader, size)
  241. if err != nil {
  242. t.Error(err)
  243. }
  244. info, err := f.Stat()
  245. if err != nil {
  246. t.Error(err)
  247. }
  248. // Create two files, second file has `shifted` bytes random prefix, yet
  249. // both are of the same length, for example:
  250. // File 1: abcdefgh
  251. // File 2: xyabcdef
  252. f.Seek(0, os.SEEK_SET)
  253. existing, err := scanner.Blocks(f, protocol.BlockSize, size, nil, true)
  254. if err != nil {
  255. t.Error(err)
  256. }
  257. f.Seek(0, os.SEEK_SET)
  258. remainder := io.LimitReader(f, size-shift)
  259. prefix := io.LimitReader(rand.Reader, shift)
  260. nf := io.MultiReader(prefix, remainder)
  261. desired, err := scanner.Blocks(nf, protocol.BlockSize, size, nil, true)
  262. if err != nil {
  263. t.Error(err)
  264. }
  265. existingFile := protocol.FileInfo{
  266. Name: "weakhash",
  267. Blocks: existing,
  268. Size: size,
  269. ModifiedS: info.ModTime().Unix(),
  270. ModifiedNs: int32(info.ModTime().Nanosecond()),
  271. }
  272. desiredFile := protocol.FileInfo{
  273. Name: "weakhash",
  274. Size: size,
  275. Blocks: desired,
  276. ModifiedS: info.ModTime().Unix() + 1,
  277. }
  278. // Setup the model/pull environment
  279. m := setUpModel(existingFile)
  280. fo := setUpSendReceiveFolder(m)
  281. copyChan := make(chan copyBlocksState)
  282. pullChan := make(chan pullBlockState, expectBlocks)
  283. finisherChan := make(chan *sharedPullerState, 1)
  284. // Run a single fetcher routine
  285. go fo.copierRoutine(copyChan, pullChan, finisherChan)
  286. // Test 1 - no weak hashing, file gets fully repulled (`expectBlocks` pulls).
  287. fo.WeakHashThresholdPct = 101
  288. fo.handleFile(desiredFile, copyChan, finisherChan)
  289. var pulls []pullBlockState
  290. for len(pulls) < expectBlocks {
  291. select {
  292. case pull := <-pullChan:
  293. pulls = append(pulls, pull)
  294. case <-time.After(10 * time.Second):
  295. t.Errorf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  296. }
  297. }
  298. finish := <-finisherChan
  299. select {
  300. case <-pullChan:
  301. t.Fatal("Pull channel has data to be read")
  302. case <-finisherChan:
  303. t.Fatal("Finisher channel has data to be read")
  304. default:
  305. }
  306. finish.fd.Close()
  307. if err := os.Remove(tempFile); err != nil && !os.IsNotExist(err) {
  308. t.Error(err)
  309. }
  310. // Test 2 - using weak hash, expectPulls blocks pulled.
  311. fo.WeakHashThresholdPct = -1
  312. fo.handleFile(desiredFile, copyChan, finisherChan)
  313. pulls = pulls[:0]
  314. for len(pulls) < expectPulls {
  315. select {
  316. case pull := <-pullChan:
  317. pulls = append(pulls, pull)
  318. case <-time.After(10 * time.Second):
  319. t.Errorf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  320. }
  321. }
  322. finish = <-finisherChan
  323. finish.fd.Close()
  324. expectShifted := expectBlocks - expectPulls
  325. if finish.copyOriginShifted != expectShifted {
  326. t.Errorf("did not copy %d shifted", expectShifted)
  327. }
  328. }
  329. // Test that updating a file removes it's old blocks from the blockmap
  330. func TestCopierCleanup(t *testing.T) {
  331. iterFn := func(folder, file string, index int32) bool {
  332. return true
  333. }
  334. // Create a file
  335. file := setUpFile("test", []int{0})
  336. m := setUpModel(file)
  337. file.Blocks = []protocol.BlockInfo{blocks[1]}
  338. file.Version = file.Version.Update(protocol.LocalDeviceID.Short())
  339. // Update index (removing old blocks)
  340. m.updateLocalsFromScanning("default", []protocol.FileInfo{file})
  341. if m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  342. t.Error("Unexpected block found")
  343. }
  344. if !m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  345. t.Error("Expected block not found")
  346. }
  347. file.Blocks = []protocol.BlockInfo{blocks[0]}
  348. file.Version = file.Version.Update(protocol.LocalDeviceID.Short())
  349. // Update index (removing old blocks)
  350. m.updateLocalsFromScanning("default", []protocol.FileInfo{file})
  351. if !m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  352. t.Error("Unexpected block found")
  353. }
  354. if m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  355. t.Error("Expected block not found")
  356. }
  357. }
  358. // Make sure that the copier routine hashes the content when asked, and pulls
  359. // if it fails to find the block.
  360. func TestLastResortPulling(t *testing.T) {
  361. // Add a file to index (with the incorrect block representation, as content
  362. // doesn't actually match the block list)
  363. file := setUpFile("empty", []int{0})
  364. m := setUpModel(file)
  365. // Pretend that we are handling a new file of the same content but
  366. // with a different name (causing to copy that particular block)
  367. file.Name = "newfile"
  368. iterFn := func(folder, file string, index int32) bool {
  369. return true
  370. }
  371. f := setUpSendReceiveFolder(m)
  372. copyChan := make(chan copyBlocksState)
  373. pullChan := make(chan pullBlockState, 1)
  374. finisherChan := make(chan *sharedPullerState, 1)
  375. // Run a single copier routine
  376. go f.copierRoutine(copyChan, pullChan, finisherChan)
  377. f.handleFile(file, copyChan, finisherChan)
  378. // Copier should hash empty file, realise that the region it has read
  379. // doesn't match the hash which was advertised by the block map, fix it
  380. // and ask to pull the block.
  381. <-pullChan
  382. // Verify that it did fix the incorrect hash.
  383. if m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  384. t.Error("Found unexpected block")
  385. }
  386. if !m.finder.Iterate(folders, scanner.SHA256OfNothing, iterFn) {
  387. t.Error("Expected block not found")
  388. }
  389. (<-finisherChan).fd.Close()
  390. os.Remove(filepath.Join("testdata", ignore.TempName("newfile")))
  391. }
  392. func TestDeregisterOnFailInCopy(t *testing.T) {
  393. file := setUpFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  394. defer os.Remove("testdata/" + ignore.TempName("filex"))
  395. db := db.OpenMemory()
  396. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  397. m.AddFolder(defaultFolderConfig)
  398. f := setUpSendReceiveFolder(m)
  399. // queue.Done should be called by the finisher routine
  400. f.queue.Push("filex", 0, time.Time{})
  401. f.queue.Pop()
  402. if f.queue.lenProgress() != 1 {
  403. t.Fatal("Expected file in progress")
  404. }
  405. copyChan := make(chan copyBlocksState)
  406. pullChan := make(chan pullBlockState)
  407. finisherBufferChan := make(chan *sharedPullerState)
  408. finisherChan := make(chan *sharedPullerState)
  409. go f.copierRoutine(copyChan, pullChan, finisherBufferChan)
  410. go f.finisherRoutine(finisherChan)
  411. f.handleFile(file, copyChan, finisherChan)
  412. // Receive a block at puller, to indicate that at least a single copier
  413. // loop has been performed.
  414. toPull := <-pullChan
  415. // Wait until copier is trying to pass something down to the puller again
  416. time.Sleep(100 * time.Millisecond)
  417. // Close the file
  418. toPull.sharedPullerState.fail("test", os.ErrNotExist)
  419. // Unblock copier
  420. <-pullChan
  421. select {
  422. case state := <-finisherBufferChan:
  423. // At this point the file should still be registered with both the job
  424. // queue, and the progress emitter. Verify this.
  425. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  426. t.Fatal("Could not find file")
  427. }
  428. // Pass the file down the real finisher, and give it time to consume
  429. finisherChan <- state
  430. time.Sleep(100 * time.Millisecond)
  431. state.mut.Lock()
  432. stateFd := state.fd
  433. state.mut.Unlock()
  434. if stateFd != nil {
  435. t.Fatal("File not closed?")
  436. }
  437. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  438. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  439. }
  440. // Doing it again should have no effect
  441. finisherChan <- state
  442. time.Sleep(100 * time.Millisecond)
  443. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  444. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  445. }
  446. case <-time.After(time.Second):
  447. t.Fatal("Didn't get anything to the finisher")
  448. }
  449. }
  450. func TestDeregisterOnFailInPull(t *testing.T) {
  451. file := setUpFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  452. defer os.Remove("testdata/" + ignore.TempName("filex"))
  453. db := db.OpenMemory()
  454. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db, nil)
  455. m.AddFolder(defaultFolderConfig)
  456. f := setUpSendReceiveFolder(m)
  457. // queue.Done should be called by the finisher routine
  458. f.queue.Push("filex", 0, time.Time{})
  459. f.queue.Pop()
  460. if f.queue.lenProgress() != 1 {
  461. t.Fatal("Expected file in progress")
  462. }
  463. copyChan := make(chan copyBlocksState)
  464. pullChan := make(chan pullBlockState)
  465. finisherBufferChan := make(chan *sharedPullerState)
  466. finisherChan := make(chan *sharedPullerState)
  467. go f.copierRoutine(copyChan, pullChan, finisherBufferChan)
  468. go f.pullerRoutine(pullChan, finisherBufferChan)
  469. go f.finisherRoutine(finisherChan)
  470. f.handleFile(file, copyChan, finisherChan)
  471. // Receive at finisher, we should error out as puller has nowhere to pull
  472. // from.
  473. select {
  474. case state := <-finisherBufferChan:
  475. // At this point the file should still be registered with both the job
  476. // queue, and the progress emitter. Verify this.
  477. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  478. t.Fatal("Could not find file")
  479. }
  480. // Pass the file down the real finisher, and give it time to consume
  481. finisherChan <- state
  482. time.Sleep(100 * time.Millisecond)
  483. state.mut.Lock()
  484. stateFd := state.fd
  485. state.mut.Unlock()
  486. if stateFd != nil {
  487. t.Fatal("File not closed?")
  488. }
  489. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  490. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  491. }
  492. // Doing it again should have no effect
  493. finisherChan <- state
  494. time.Sleep(100 * time.Millisecond)
  495. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  496. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  497. }
  498. case <-time.After(time.Second):
  499. t.Fatal("Didn't get anything to the finisher")
  500. }
  501. }