rwfolder_test.go 23 KB

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