rwfolder_test.go 23 KB

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