folder_sendrecv_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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.MinBlockSize, 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.MinBlockSize)
  235. expectPulls := int(shift / protocol.MinBlockSize)
  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.MinBlockSize, 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.MinBlockSize, 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. func TestDeregisterOnFailInCopy(t *testing.T) {
  371. file := setUpFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  372. defer os.Remove("testdata/" + fs.TempName("filex"))
  373. db := db.OpenMemory()
  374. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  375. m.AddFolder(defaultFolderConfig)
  376. f := setUpSendReceiveFolder(m)
  377. // queue.Done should be called by the finisher routine
  378. f.queue.Push("filex", 0, time.Time{})
  379. f.queue.Pop()
  380. if f.queue.lenProgress() != 1 {
  381. t.Fatal("Expected file in progress")
  382. }
  383. copyChan := make(chan copyBlocksState)
  384. pullChan := make(chan pullBlockState)
  385. finisherBufferChan := make(chan *sharedPullerState)
  386. finisherChan := make(chan *sharedPullerState)
  387. dbUpdateChan := make(chan dbUpdateJob, 1)
  388. go f.copierRoutine(copyChan, pullChan, finisherBufferChan)
  389. go f.finisherRoutine(ignore.New(defaultFs), finisherChan, dbUpdateChan, make(chan string))
  390. f.handleFile(file, copyChan, finisherChan, dbUpdateChan)
  391. // Receive a block at puller, to indicate that at least a single copier
  392. // loop has been performed.
  393. toPull := <-pullChan
  394. // Wait until copier is trying to pass something down to the puller again
  395. time.Sleep(100 * time.Millisecond)
  396. // Close the file
  397. toPull.sharedPullerState.fail("test", os.ErrNotExist)
  398. // Unblock copier
  399. <-pullChan
  400. select {
  401. case state := <-finisherBufferChan:
  402. // At this point the file should still be registered with both the job
  403. // queue, and the progress emitter. Verify this.
  404. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  405. t.Fatal("Could not find file")
  406. }
  407. // Pass the file down the real finisher, and give it time to consume
  408. finisherChan <- state
  409. time.Sleep(100 * time.Millisecond)
  410. state.mut.Lock()
  411. stateFd := state.fd
  412. state.mut.Unlock()
  413. if stateFd != nil {
  414. t.Fatal("File not closed?")
  415. }
  416. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  417. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  418. }
  419. // Doing it again should have no effect
  420. finisherChan <- state
  421. time.Sleep(100 * time.Millisecond)
  422. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  423. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  424. }
  425. case <-time.After(time.Second):
  426. t.Fatal("Didn't get anything to the finisher")
  427. }
  428. }
  429. func TestDeregisterOnFailInPull(t *testing.T) {
  430. file := setUpFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  431. defer os.Remove("testdata/" + fs.TempName("filex"))
  432. db := db.OpenMemory()
  433. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  434. m.AddFolder(defaultFolderConfig)
  435. f := setUpSendReceiveFolder(m)
  436. // queue.Done should be called by the finisher routine
  437. f.queue.Push("filex", 0, time.Time{})
  438. f.queue.Pop()
  439. if f.queue.lenProgress() != 1 {
  440. t.Fatal("Expected file in progress")
  441. }
  442. copyChan := make(chan copyBlocksState)
  443. pullChan := make(chan pullBlockState)
  444. finisherBufferChan := make(chan *sharedPullerState)
  445. finisherChan := make(chan *sharedPullerState)
  446. dbUpdateChan := make(chan dbUpdateJob, 1)
  447. go f.copierRoutine(copyChan, pullChan, finisherBufferChan)
  448. go f.pullerRoutine(pullChan, finisherBufferChan)
  449. go f.finisherRoutine(ignore.New(defaultFs), finisherChan, dbUpdateChan, make(chan string))
  450. f.handleFile(file, copyChan, finisherChan, dbUpdateChan)
  451. // Receive at finisher, we should error out as puller has nowhere to pull
  452. // from.
  453. select {
  454. case state := <-finisherBufferChan:
  455. // At this point the file should still be registered with both the job
  456. // queue, and the progress emitter. Verify this.
  457. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  458. t.Fatal("Could not find file")
  459. }
  460. // Pass the file down the real finisher, and give it time to consume
  461. finisherChan <- state
  462. time.Sleep(100 * time.Millisecond)
  463. state.mut.Lock()
  464. stateFd := state.fd
  465. state.mut.Unlock()
  466. if stateFd != nil {
  467. t.Fatal("File not closed?")
  468. }
  469. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  470. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  471. }
  472. // Doing it again should have no effect
  473. finisherChan <- state
  474. time.Sleep(100 * time.Millisecond)
  475. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  476. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  477. }
  478. case <-time.After(time.Second):
  479. t.Fatal("Didn't get anything to the finisher")
  480. }
  481. }
  482. func TestIssue3164(t *testing.T) {
  483. m := setUpModel(protocol.FileInfo{})
  484. f := setUpSendReceiveFolder(m)
  485. defaultFs.RemoveAll("issue3164")
  486. defer defaultFs.RemoveAll("issue3164")
  487. if err := defaultFs.MkdirAll("issue3164/oktodelete/foobar", 0777); err != nil {
  488. t.Fatal(err)
  489. }
  490. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/foobar/file", []byte("Hello"), 0644); err != nil {
  491. t.Fatal(err)
  492. }
  493. if err := ioutil.WriteFile("testdata/issue3164/oktodelete/file", []byte("Hello"), 0644); err != nil {
  494. t.Fatal(err)
  495. }
  496. file := protocol.FileInfo{
  497. Name: "issue3164",
  498. }
  499. matcher := ignore.New(defaultFs)
  500. if err := matcher.Parse(bytes.NewBufferString("(?d)oktodelete"), ""); err != nil {
  501. t.Fatal(err)
  502. }
  503. dbUpdateChan := make(chan dbUpdateJob, 1)
  504. f.handleDeleteDir(file, matcher, dbUpdateChan, make(chan string))
  505. if _, err := defaultFs.Stat("testdata/issue3164"); !fs.IsNotExist(err) {
  506. t.Fatal(err)
  507. }
  508. }
  509. func TestDiff(t *testing.T) {
  510. for i, test := range diffTestData {
  511. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  512. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  513. _, d := blockDiff(a, b)
  514. if len(d) != len(test.d) {
  515. t.Fatalf("Incorrect length for diff %d; %d != %d", i, len(d), len(test.d))
  516. } else {
  517. for j := range test.d {
  518. if d[j].Offset != test.d[j].Offset {
  519. t.Errorf("Incorrect offset for diff %d block %d; %d != %d", i, j, d[j].Offset, test.d[j].Offset)
  520. }
  521. if d[j].Size != test.d[j].Size {
  522. t.Errorf("Incorrect length for diff %d block %d; %d != %d", i, j, d[j].Size, test.d[j].Size)
  523. }
  524. }
  525. }
  526. }
  527. }
  528. func BenchmarkDiff(b *testing.B) {
  529. testCases := make([]struct{ a, b []protocol.BlockInfo }, 0, len(diffTestData))
  530. for _, test := range diffTestData {
  531. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  532. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  533. testCases = append(testCases, struct{ a, b []protocol.BlockInfo }{a, b})
  534. }
  535. b.ReportAllocs()
  536. b.ResetTimer()
  537. for i := 0; i < b.N; i++ {
  538. for _, tc := range testCases {
  539. blockDiff(tc.a, tc.b)
  540. }
  541. }
  542. }
  543. func TestDiffEmpty(t *testing.T) {
  544. emptyCases := []struct {
  545. a []protocol.BlockInfo
  546. b []protocol.BlockInfo
  547. need int
  548. have int
  549. }{
  550. {nil, nil, 0, 0},
  551. {[]protocol.BlockInfo{{Offset: 3, Size: 1}}, nil, 0, 0},
  552. {nil, []protocol.BlockInfo{{Offset: 3, Size: 1}}, 1, 0},
  553. }
  554. for _, emptyCase := range emptyCases {
  555. h, n := blockDiff(emptyCase.a, emptyCase.b)
  556. if len(h) != emptyCase.have {
  557. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  558. }
  559. if len(n) != emptyCase.need {
  560. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  561. }
  562. }
  563. }