rwfolder_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. "bytes"
  9. "context"
  10. "crypto/rand"
  11. "io"
  12. "io/ioutil"
  13. "os"
  14. "path/filepath"
  15. "testing"
  16. "time"
  17. "github.com/syncthing/syncthing/lib/db"
  18. "github.com/syncthing/syncthing/lib/fs"
  19. "github.com/syncthing/syncthing/lib/ignore"
  20. "github.com/syncthing/syncthing/lib/protocol"
  21. "github.com/syncthing/syncthing/lib/scanner"
  22. "github.com/syncthing/syncthing/lib/sync"
  23. )
  24. func TestMain(m *testing.M) {
  25. // We do this to make sure that the temp file required for the tests
  26. // does not get removed during the tests. Also set the prefix so it's
  27. // found correctly regardless of platform.
  28. if fs.TempPrefix != fs.WindowsTempPrefix {
  29. originalPrefix := fs.TempPrefix
  30. fs.TempPrefix = fs.WindowsTempPrefix
  31. defer func() {
  32. fs.TempPrefix = originalPrefix
  33. }()
  34. }
  35. future := time.Now().Add(time.Hour)
  36. err := os.Chtimes(filepath.Join("testdata", fs.TempName("file")), future, future)
  37. if err != nil {
  38. panic(err)
  39. }
  40. os.Exit(m.Run())
  41. }
  42. var blocks = []protocol.BlockInfo{
  43. {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
  44. {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}},
  45. {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}},
  46. {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}},
  47. {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}},
  48. {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}},
  49. {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}},
  50. {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}},
  51. {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}},
  52. }
  53. var folders = []string{"default"}
  54. func setUpFile(filename string, blockNumbers []int) protocol.FileInfo {
  55. // Create existing file
  56. existingBlocks := make([]protocol.BlockInfo, len(blockNumbers))
  57. for i := range blockNumbers {
  58. existingBlocks[i] = blocks[blockNumbers[i]]
  59. }
  60. return protocol.FileInfo{
  61. Name: filename,
  62. Blocks: existingBlocks,
  63. }
  64. }
  65. func setUpModel(file protocol.FileInfo) *Model {
  66. db := db.OpenMemory()
  67. model := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  68. model.AddFolder(defaultFolderConfig)
  69. // Update index
  70. model.updateLocalsFromScanning("default", []protocol.FileInfo{file})
  71. return model
  72. }
  73. func setUpSendReceiveFolder(model *Model) *sendReceiveFolder {
  74. f := &sendReceiveFolder{
  75. folder: folder{
  76. stateTracker: newStateTracker("default"),
  77. model: model,
  78. initialScanFinished: make(chan struct{}),
  79. ctx: context.TODO(),
  80. },
  81. fs: fs.NewMtimeFS(fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata"), db.NewNamespacedKV(model.db, "mtime")),
  82. queue: newJobQueue(),
  83. errors: make(map[string]string),
  84. errorsMut: sync.NewMutex(),
  85. }
  86. // Folders are never actually started, so no initial scan will be done
  87. close(f.initialScanFinished)
  88. return f
  89. }
  90. // Layout of the files: (indexes from the above array)
  91. // 12345678 - Required file
  92. // 02005008 - Existing file (currently in the index)
  93. // 02340070 - Temp file on the disk
  94. func TestHandleFile(t *testing.T) {
  95. // After the diff between required and existing we should:
  96. // Copy: 2, 5, 8
  97. // Pull: 1, 3, 4, 6, 7
  98. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  99. existingFile := setUpFile("filex", existingBlocks)
  100. requiredFile := existingFile
  101. requiredFile.Blocks = blocks[1:]
  102. m := setUpModel(existingFile)
  103. f := setUpSendReceiveFolder(m)
  104. copyChan := make(chan copyBlocksState, 1)
  105. dbUpdateChan := make(chan dbUpdateJob, 1)
  106. f.handleFile(requiredFile, copyChan, nil, dbUpdateChan)
  107. // Receive the results
  108. toCopy := <-copyChan
  109. if len(toCopy.blocks) != 8 {
  110. t.Errorf("Unexpected count of copy blocks: %d != 8", len(toCopy.blocks))
  111. }
  112. for _, block := range blocks[1:] {
  113. found := false
  114. for _, toCopyBlock := range toCopy.blocks {
  115. if string(toCopyBlock.Hash) == string(block.Hash) {
  116. found = true
  117. break
  118. }
  119. }
  120. if !found {
  121. t.Errorf("Did not find block %s", block.String())
  122. }
  123. }
  124. }
  125. func TestHandleFileWithTemp(t *testing.T) {
  126. // After diff between required and existing we should:
  127. // Copy: 2, 5, 8
  128. // Pull: 1, 3, 4, 6, 7
  129. // After dropping out blocks already on the temp file we should:
  130. // Copy: 5, 8
  131. // Pull: 1, 6
  132. existingBlocks := []int{0, 2, 0, 0, 5, 0, 0, 8}
  133. existingFile := setUpFile("file", existingBlocks)
  134. requiredFile := existingFile
  135. requiredFile.Blocks = blocks[1:]
  136. m := setUpModel(existingFile)
  137. f := setUpSendReceiveFolder(m)
  138. copyChan := make(chan copyBlocksState, 1)
  139. dbUpdateChan := make(chan dbUpdateJob, 1)
  140. f.handleFile(requiredFile, copyChan, nil, dbUpdateChan)
  141. // Receive the results
  142. toCopy := <-copyChan
  143. if len(toCopy.blocks) != 4 {
  144. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  145. }
  146. for _, idx := range []int{1, 5, 6, 8} {
  147. found := false
  148. block := blocks[idx]
  149. for _, toCopyBlock := range toCopy.blocks {
  150. if string(toCopyBlock.Hash) == string(block.Hash) {
  151. found = true
  152. break
  153. }
  154. }
  155. if !found {
  156. t.Errorf("Did not find block %s", block.String())
  157. }
  158. }
  159. }
  160. func TestCopierFinder(t *testing.T) {
  161. // After diff between required and existing we should:
  162. // Copy: 1, 2, 3, 4, 6, 7, 8
  163. // Since there is no existing file, nor a temp file
  164. // After dropping out blocks found locally:
  165. // Pull: 1, 5, 6, 8
  166. tempFile := filepath.Join("testdata", fs.TempName("file2"))
  167. err := os.Remove(tempFile)
  168. if err != nil && !os.IsNotExist(err) {
  169. t.Error(err)
  170. }
  171. existingBlocks := []int{0, 2, 3, 4, 0, 0, 7, 0}
  172. existingFile := setUpFile(fs.TempName("file"), existingBlocks)
  173. requiredFile := existingFile
  174. requiredFile.Blocks = blocks[1:]
  175. requiredFile.Name = "file2"
  176. m := setUpModel(existingFile)
  177. f := setUpSendReceiveFolder(m)
  178. copyChan := make(chan copyBlocksState)
  179. pullChan := make(chan pullBlockState, 4)
  180. finisherChan := make(chan *sharedPullerState, 1)
  181. dbUpdateChan := make(chan dbUpdateJob, 1)
  182. // Run a single fetcher routine
  183. go f.copierRoutine(copyChan, pullChan, finisherChan)
  184. f.handleFile(requiredFile, copyChan, finisherChan, dbUpdateChan)
  185. pulls := []pullBlockState{<-pullChan, <-pullChan, <-pullChan, <-pullChan}
  186. finish := <-finisherChan
  187. select {
  188. case <-pullChan:
  189. t.Fatal("Pull channel has data to be read")
  190. case <-finisherChan:
  191. t.Fatal("Finisher channel has data to be read")
  192. default:
  193. }
  194. // Verify that the right blocks went into the pull list.
  195. // They are pulled in random order.
  196. for _, idx := range []int{1, 5, 6, 8} {
  197. found := false
  198. block := blocks[idx]
  199. for _, pulledBlock := range pulls {
  200. if string(pulledBlock.block.Hash) == string(block.Hash) {
  201. found = true
  202. break
  203. }
  204. }
  205. if !found {
  206. t.Errorf("Did not find block %s", block.String())
  207. }
  208. if string(finish.file.Blocks[idx-1].Hash) != string(blocks[idx].Hash) {
  209. t.Errorf("Block %d mismatch: %s != %s", idx, finish.file.Blocks[idx-1].String(), blocks[idx].String())
  210. }
  211. }
  212. // Verify that the fetched blocks have actually been written to the temp file
  213. blks, err := scanner.HashFile(context.TODO(), fs.NewFilesystem(fs.FilesystemTypeBasic, "."), tempFile, protocol.BlockSize, nil, false)
  214. if err != nil {
  215. t.Log(err)
  216. }
  217. for _, eq := range []int{2, 3, 4, 7} {
  218. if string(blks[eq-1].Hash) != string(blocks[eq].Hash) {
  219. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  220. }
  221. }
  222. finish.fd.Close()
  223. os.Remove(tempFile)
  224. }
  225. func TestWeakHash(t *testing.T) {
  226. tempFile := filepath.Join("testdata", fs.TempName("weakhash"))
  227. var shift int64 = 10
  228. var size int64 = 1 << 20
  229. expectBlocks := int(size / protocol.BlockSize)
  230. expectPulls := int(shift / protocol.BlockSize)
  231. if shift > 0 {
  232. expectPulls++
  233. }
  234. cleanup := func() {
  235. for _, path := range []string{tempFile, "testdata/weakhash"} {
  236. os.Remove(path)
  237. }
  238. }
  239. cleanup()
  240. defer cleanup()
  241. f, err := os.Create("testdata/weakhash")
  242. if err != nil {
  243. t.Error(err)
  244. }
  245. defer f.Close()
  246. _, err = io.CopyN(f, rand.Reader, size)
  247. if err != nil {
  248. t.Error(err)
  249. }
  250. info, err := f.Stat()
  251. if err != nil {
  252. t.Error(err)
  253. }
  254. // Create two files, second file has `shifted` bytes random prefix, yet
  255. // both are of the same length, for example:
  256. // File 1: abcdefgh
  257. // File 2: xyabcdef
  258. f.Seek(0, os.SEEK_SET)
  259. existing, err := scanner.Blocks(context.TODO(), f, protocol.BlockSize, size, nil, true)
  260. if err != nil {
  261. t.Error(err)
  262. }
  263. f.Seek(0, os.SEEK_SET)
  264. remainder := io.LimitReader(f, size-shift)
  265. prefix := io.LimitReader(rand.Reader, shift)
  266. nf := io.MultiReader(prefix, remainder)
  267. desired, err := scanner.Blocks(context.TODO(), nf, protocol.BlockSize, size, nil, true)
  268. if err != nil {
  269. t.Error(err)
  270. }
  271. existingFile := protocol.FileInfo{
  272. Name: "weakhash",
  273. Blocks: existing,
  274. Size: size,
  275. ModifiedS: info.ModTime().Unix(),
  276. ModifiedNs: int32(info.ModTime().Nanosecond()),
  277. }
  278. desiredFile := protocol.FileInfo{
  279. Name: "weakhash",
  280. Size: size,
  281. Blocks: desired,
  282. ModifiedS: info.ModTime().Unix() + 1,
  283. }
  284. // Setup the model/pull environment
  285. m := setUpModel(existingFile)
  286. fo := setUpSendReceiveFolder(m)
  287. copyChan := make(chan copyBlocksState)
  288. pullChan := make(chan pullBlockState, expectBlocks)
  289. finisherChan := make(chan *sharedPullerState, 1)
  290. dbUpdateChan := make(chan dbUpdateJob, 1)
  291. // Run a single fetcher routine
  292. go fo.copierRoutine(copyChan, pullChan, finisherChan)
  293. // Test 1 - no weak hashing, file gets fully repulled (`expectBlocks` pulls).
  294. fo.WeakHashThresholdPct = 101
  295. fo.handleFile(desiredFile, copyChan, finisherChan, dbUpdateChan)
  296. var pulls []pullBlockState
  297. for len(pulls) < expectBlocks {
  298. select {
  299. case pull := <-pullChan:
  300. pulls = append(pulls, pull)
  301. case <-time.After(10 * time.Second):
  302. t.Errorf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  303. }
  304. }
  305. finish := <-finisherChan
  306. select {
  307. case <-pullChan:
  308. t.Fatal("Pull channel has data to be read")
  309. case <-finisherChan:
  310. t.Fatal("Finisher channel has data to be read")
  311. default:
  312. }
  313. finish.fd.Close()
  314. if err := os.Remove(tempFile); err != nil && !os.IsNotExist(err) {
  315. t.Error(err)
  316. }
  317. // Test 2 - using weak hash, expectPulls blocks pulled.
  318. fo.WeakHashThresholdPct = -1
  319. fo.handleFile(desiredFile, copyChan, finisherChan, dbUpdateChan)
  320. pulls = pulls[:0]
  321. for len(pulls) < expectPulls {
  322. select {
  323. case pull := <-pullChan:
  324. pulls = append(pulls, pull)
  325. case <-time.After(10 * time.Second):
  326. t.Errorf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  327. }
  328. }
  329. finish = <-finisherChan
  330. finish.fd.Close()
  331. expectShifted := expectBlocks - expectPulls
  332. if finish.copyOriginShifted != expectShifted {
  333. t.Errorf("did not copy %d shifted", expectShifted)
  334. }
  335. }
  336. // Test that updating a file removes its old blocks from the blockmap
  337. func TestCopierCleanup(t *testing.T) {
  338. iterFn := func(folder, file string, index int32) bool {
  339. return true
  340. }
  341. // Create a file
  342. file := setUpFile("test", []int{0})
  343. m := setUpModel(file)
  344. file.Blocks = []protocol.BlockInfo{blocks[1]}
  345. file.Version = file.Version.Update(protocol.LocalDeviceID.Short())
  346. // Update index (removing old blocks)
  347. m.updateLocalsFromScanning("default", []protocol.FileInfo{file})
  348. if m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  349. t.Error("Unexpected block found")
  350. }
  351. if !m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  352. t.Error("Expected block not found")
  353. }
  354. file.Blocks = []protocol.BlockInfo{blocks[0]}
  355. file.Version = file.Version.Update(protocol.LocalDeviceID.Short())
  356. // Update index (removing old blocks)
  357. m.updateLocalsFromScanning("default", []protocol.FileInfo{file})
  358. if !m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  359. t.Error("Unexpected block found")
  360. }
  361. if m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  362. t.Error("Expected block not found")
  363. }
  364. }
  365. // Make sure that the copier routine hashes the content when asked, and pulls
  366. // if it fails to find the block.
  367. func TestLastResortPulling(t *testing.T) {
  368. // Add a file to index (with the incorrect block representation, as content
  369. // doesn't actually match the block list)
  370. file := setUpFile("empty", []int{0})
  371. m := setUpModel(file)
  372. // Pretend that we are handling a new file of the same content but
  373. // with a different name (causing to copy that particular block)
  374. file.Name = "newfile"
  375. iterFn := func(folder, file string, index int32) bool {
  376. return true
  377. }
  378. f := setUpSendReceiveFolder(m)
  379. copyChan := make(chan copyBlocksState)
  380. pullChan := make(chan pullBlockState, 1)
  381. finisherChan := make(chan *sharedPullerState, 1)
  382. dbUpdateChan := make(chan dbUpdateJob, 1)
  383. // Run a single copier routine
  384. go f.copierRoutine(copyChan, pullChan, finisherChan)
  385. f.handleFile(file, copyChan, finisherChan, dbUpdateChan)
  386. // Copier should hash empty file, realise that the region it has read
  387. // doesn't match the hash which was advertised by the block map, fix it
  388. // and ask to pull the block.
  389. <-pullChan
  390. // Verify that it did fix the incorrect hash.
  391. if m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  392. t.Error("Found unexpected block")
  393. }
  394. if !m.finder.Iterate(folders, scanner.SHA256OfNothing, iterFn) {
  395. t.Error("Expected block not found")
  396. }
  397. (<-finisherChan).fd.Close()
  398. os.Remove(filepath.Join("testdata", fs.TempName("newfile")))
  399. }
  400. func TestDeregisterOnFailInCopy(t *testing.T) {
  401. file := setUpFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  402. defer os.Remove("testdata/" + fs.TempName("filex"))
  403. db := db.OpenMemory()
  404. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  405. m.AddFolder(defaultFolderConfig)
  406. f := setUpSendReceiveFolder(m)
  407. // queue.Done should be called by the finisher routine
  408. f.queue.Push("filex", 0, time.Time{})
  409. f.queue.Pop()
  410. if f.queue.lenProgress() != 1 {
  411. t.Fatal("Expected file in progress")
  412. }
  413. copyChan := make(chan copyBlocksState)
  414. pullChan := make(chan pullBlockState)
  415. finisherBufferChan := make(chan *sharedPullerState)
  416. finisherChan := make(chan *sharedPullerState)
  417. dbUpdateChan := make(chan dbUpdateJob, 1)
  418. go f.copierRoutine(copyChan, pullChan, finisherBufferChan)
  419. go f.finisherRoutine(ignore.New(defaultFs), finisherChan, dbUpdateChan, make(chan string))
  420. f.handleFile(file, copyChan, finisherChan, dbUpdateChan)
  421. // Receive a block at puller, to indicate that at least a single copier
  422. // loop has been performed.
  423. toPull := <-pullChan
  424. // Wait until copier is trying to pass something down to the puller again
  425. time.Sleep(100 * time.Millisecond)
  426. // Close the file
  427. toPull.sharedPullerState.fail("test", os.ErrNotExist)
  428. // Unblock copier
  429. <-pullChan
  430. select {
  431. case state := <-finisherBufferChan:
  432. // At this point the file should still be registered with both the job
  433. // queue, and the progress emitter. Verify this.
  434. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  435. t.Fatal("Could not find file")
  436. }
  437. // Pass the file down the real finisher, and give it time to consume
  438. finisherChan <- state
  439. time.Sleep(100 * time.Millisecond)
  440. state.mut.Lock()
  441. stateFd := state.fd
  442. state.mut.Unlock()
  443. if stateFd != nil {
  444. t.Fatal("File not closed?")
  445. }
  446. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  447. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  448. }
  449. // Doing it again should have no effect
  450. finisherChan <- state
  451. time.Sleep(100 * time.Millisecond)
  452. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  453. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  454. }
  455. case <-time.After(time.Second):
  456. t.Fatal("Didn't get anything to the finisher")
  457. }
  458. }
  459. func TestDeregisterOnFailInPull(t *testing.T) {
  460. file := setUpFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  461. defer os.Remove("testdata/" + fs.TempName("filex"))
  462. db := db.OpenMemory()
  463. m := NewModel(defaultConfig, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  464. m.AddFolder(defaultFolderConfig)
  465. f := setUpSendReceiveFolder(m)
  466. // queue.Done should be called by the finisher routine
  467. f.queue.Push("filex", 0, time.Time{})
  468. f.queue.Pop()
  469. if f.queue.lenProgress() != 1 {
  470. t.Fatal("Expected file in progress")
  471. }
  472. copyChan := make(chan copyBlocksState)
  473. pullChan := make(chan pullBlockState)
  474. finisherBufferChan := make(chan *sharedPullerState)
  475. finisherChan := make(chan *sharedPullerState)
  476. dbUpdateChan := make(chan dbUpdateJob, 1)
  477. go f.copierRoutine(copyChan, pullChan, finisherBufferChan)
  478. go f.pullerRoutine(pullChan, finisherBufferChan)
  479. go f.finisherRoutine(ignore.New(defaultFs), finisherChan, dbUpdateChan, make(chan string))
  480. f.handleFile(file, copyChan, finisherChan, dbUpdateChan)
  481. // Receive at finisher, we should error out as puller has nowhere to pull
  482. // from.
  483. select {
  484. case state := <-finisherBufferChan:
  485. // At this point the file should still be registered with both the job
  486. // queue, and the progress emitter. Verify this.
  487. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  488. t.Fatal("Could not find file")
  489. }
  490. // Pass the file down the real finisher, and give it time to consume
  491. finisherChan <- state
  492. time.Sleep(100 * time.Millisecond)
  493. state.mut.Lock()
  494. stateFd := state.fd
  495. state.mut.Unlock()
  496. if stateFd != nil {
  497. t.Fatal("File not closed?")
  498. }
  499. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  500. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  501. }
  502. // Doing it again should have no effect
  503. finisherChan <- state
  504. time.Sleep(100 * time.Millisecond)
  505. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  506. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  507. }
  508. case <-time.After(time.Second):
  509. t.Fatal("Didn't get anything to the finisher")
  510. }
  511. }
  512. func TestIssue3164(t *testing.T) {
  513. m := setUpModel(protocol.FileInfo{})
  514. f := setUpSendReceiveFolder(m)
  515. defaultFs.RemoveAll("issue3164")
  516. defer defaultFs.RemoveAll("issue3164")
  517. if err := defaultFs.MkdirAll("issue3164/oktodelete/foobar", 0777); err != nil {
  518. t.Fatal(err)
  519. }
  520. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/foobar/file", []byte("Hello"), 0644); err != nil {
  521. t.Fatal(err)
  522. }
  523. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/file", []byte("Hello"), 0644); err != nil {
  524. t.Fatal(err)
  525. }
  526. file := protocol.FileInfo{
  527. Name: "issue3164",
  528. }
  529. matcher := ignore.New(defaultFs)
  530. if err := matcher.Parse(bytes.NewBufferString("(?d)oktodelete"), ""); err != nil {
  531. t.Fatal(err)
  532. }
  533. dbUpdateChan := make(chan dbUpdateJob, 1)
  534. f.handleDeleteDir(file, matcher, dbUpdateChan, make(chan string))
  535. if _, err := defaultFs.Stat("testdata/issue3164"); !fs.IsNotExist(err) {
  536. t.Fatal(err)
  537. }
  538. }