folder_sendrecv_test.go 23 KB

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