folder_sendrecv_test.go 22 KB

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