folder_sendrecv_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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. "runtime"
  16. "testing"
  17. "time"
  18. "github.com/syncthing/syncthing/lib/config"
  19. "github.com/syncthing/syncthing/lib/db"
  20. "github.com/syncthing/syncthing/lib/events"
  21. "github.com/syncthing/syncthing/lib/fs"
  22. "github.com/syncthing/syncthing/lib/ignore"
  23. "github.com/syncthing/syncthing/lib/protocol"
  24. "github.com/syncthing/syncthing/lib/scanner"
  25. "github.com/syncthing/syncthing/lib/sync"
  26. )
  27. var blocks = []protocol.BlockInfo{
  28. {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
  29. {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}},
  30. {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}},
  31. {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}},
  32. {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}},
  33. {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}},
  34. {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}},
  35. {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}},
  36. {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}},
  37. }
  38. var folders = []string{"default"}
  39. var diffTestData = []struct {
  40. a string
  41. b string
  42. s int
  43. d []protocol.BlockInfo
  44. }{
  45. {"contents", "contents", 1024, []protocol.BlockInfo{}},
  46. {"", "", 1024, []protocol.BlockInfo{}},
  47. {"contents", "contents", 3, []protocol.BlockInfo{}},
  48. {"contents", "cantents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}}},
  49. {"contents", "contants", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}}},
  50. {"contents", "cantants", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}}},
  51. {"contents", "", 3, []protocol.BlockInfo{{Offset: 0, Size: 0}}},
  52. {"", "contents", 3, []protocol.BlockInfo{{Offset: 0, Size: 3}, {Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  53. {"con", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  54. {"contents", "con", 3, nil},
  55. {"contents", "cont", 3, []protocol.BlockInfo{{Offset: 3, Size: 1}}},
  56. {"cont", "contents", 3, []protocol.BlockInfo{{Offset: 3, Size: 3}, {Offset: 6, Size: 2}}},
  57. }
  58. func setupFile(filename string, blockNumbers []int) protocol.FileInfo {
  59. // Create existing file
  60. existingBlocks := make([]protocol.BlockInfo, len(blockNumbers))
  61. for i := range blockNumbers {
  62. existingBlocks[i] = blocks[blockNumbers[i]]
  63. }
  64. return protocol.FileInfo{
  65. Name: filename,
  66. Blocks: existingBlocks,
  67. }
  68. }
  69. func setupSendReceiveFolder(files ...protocol.FileInfo) (*model, *sendReceiveFolder, string) {
  70. w := createTmpWrapper(defaultCfg)
  71. model := newModel(w, myID, "syncthing", "dev", db.OpenMemory(), nil)
  72. fcfg, tmpDir := testFolderConfigTmp()
  73. model.AddFolder(fcfg)
  74. // Update index
  75. if files != nil {
  76. model.updateLocalsFromScanning("default", files)
  77. }
  78. f := &sendReceiveFolder{
  79. folder: folder{
  80. stateTracker: newStateTracker("default"),
  81. model: model,
  82. initialScanFinished: make(chan struct{}),
  83. ctx: context.TODO(),
  84. FolderConfiguration: fcfg,
  85. },
  86. queue: newJobQueue(),
  87. pullErrors: make(map[string]string),
  88. pullErrorsMut: sync.NewMutex(),
  89. }
  90. f.fs = fs.NewMtimeFS(f.Filesystem(), db.NewNamespacedKV(model.db, "mtime"))
  91. // Folders are never actually started, so no initial scan will be done
  92. close(f.initialScanFinished)
  93. return model, f, tmpDir
  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, f, tmpDir := setupSendReceiveFolder(existingFile)
  108. defer func() {
  109. os.Remove(m.cfg.ConfigPath())
  110. os.Remove(tmpDir)
  111. }()
  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, f, tmpDir := setupSendReceiveFolder(existingFile)
  145. defer func() {
  146. os.Remove(m.cfg.ConfigPath())
  147. os.Remove(tmpDir)
  148. }()
  149. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  150. t.Fatal(err)
  151. }
  152. copyChan := make(chan copyBlocksState, 1)
  153. dbUpdateChan := make(chan dbUpdateJob, 1)
  154. f.handleFile(requiredFile, copyChan, nil, dbUpdateChan)
  155. // Receive the results
  156. toCopy := <-copyChan
  157. if len(toCopy.blocks) != 4 {
  158. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  159. }
  160. for _, idx := range []int{1, 5, 6, 8} {
  161. found := false
  162. block := blocks[idx]
  163. for _, toCopyBlock := range toCopy.blocks {
  164. if string(toCopyBlock.Hash) == string(block.Hash) {
  165. found = true
  166. break
  167. }
  168. }
  169. if !found {
  170. t.Errorf("Did not find block %s", block.String())
  171. }
  172. }
  173. }
  174. func TestCopierFinder(t *testing.T) {
  175. // After diff between required and existing we should:
  176. // Copy: 1, 2, 3, 4, 6, 7, 8
  177. // Since there is no existing file, nor a temp file
  178. // After dropping out blocks found locally:
  179. // Pull: 1, 5, 6, 8
  180. tempFile := fs.TempName("file2")
  181. existingBlocks := []int{0, 2, 3, 4, 0, 0, 7, 0}
  182. existingFile := setupFile(fs.TempName("file"), existingBlocks)
  183. requiredFile := existingFile
  184. requiredFile.Blocks = blocks[1:]
  185. requiredFile.Name = "file2"
  186. m, f, tmpDir := setupSendReceiveFolder(existingFile)
  187. defer func() {
  188. os.Remove(m.cfg.ConfigPath())
  189. os.Remove(tmpDir)
  190. }()
  191. if _, err := prepareTmpFile(f.Filesystem()); err != nil {
  192. t.Fatal(err)
  193. }
  194. copyChan := make(chan copyBlocksState)
  195. pullChan := make(chan pullBlockState, 4)
  196. finisherChan := make(chan *sharedPullerState, 1)
  197. dbUpdateChan := make(chan dbUpdateJob, 1)
  198. // Run a single fetcher routine
  199. go f.copierRoutine(copyChan, pullChan, finisherChan)
  200. f.handleFile(requiredFile, copyChan, finisherChan, dbUpdateChan)
  201. pulls := []pullBlockState{<-pullChan, <-pullChan, <-pullChan, <-pullChan}
  202. finish := <-finisherChan
  203. select {
  204. case <-pullChan:
  205. t.Fatal("Pull channel has data to be read")
  206. case <-finisherChan:
  207. t.Fatal("Finisher channel has data to be read")
  208. default:
  209. }
  210. // Verify that the right blocks went into the pull list.
  211. // They are pulled in random order.
  212. for _, idx := range []int{1, 5, 6, 8} {
  213. found := false
  214. block := blocks[idx]
  215. for _, pulledBlock := range pulls {
  216. if string(pulledBlock.block.Hash) == string(block.Hash) {
  217. found = true
  218. break
  219. }
  220. }
  221. if !found {
  222. t.Errorf("Did not find block %s", block.String())
  223. }
  224. if string(finish.file.Blocks[idx-1].Hash) != string(blocks[idx].Hash) {
  225. t.Errorf("Block %d mismatch: %s != %s", idx, finish.file.Blocks[idx-1].String(), blocks[idx].String())
  226. }
  227. }
  228. // Verify that the fetched blocks have actually been written to the temp file
  229. blks, err := scanner.HashFile(context.TODO(), f.Filesystem(), tempFile, protocol.MinBlockSize, nil, false)
  230. if err != nil {
  231. t.Log(err)
  232. }
  233. for _, eq := range []int{2, 3, 4, 7} {
  234. if string(blks[eq-1].Hash) != string(blocks[eq].Hash) {
  235. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  236. }
  237. }
  238. finish.fd.Close()
  239. }
  240. func TestWeakHash(t *testing.T) {
  241. // Setup the model/pull environment
  242. model, fo, tmpDir := setupSendReceiveFolder()
  243. defer func() {
  244. os.Remove(model.cfg.ConfigPath())
  245. os.Remove(tmpDir)
  246. }()
  247. ffs := fo.Filesystem()
  248. tempFile := fs.TempName("weakhash")
  249. var shift int64 = 10
  250. var size int64 = 1 << 20
  251. expectBlocks := int(size / protocol.MinBlockSize)
  252. expectPulls := int(shift / protocol.MinBlockSize)
  253. if shift > 0 {
  254. expectPulls++
  255. }
  256. f, err := ffs.Create("weakhash")
  257. if err != nil {
  258. t.Fatal(err)
  259. }
  260. defer f.Close()
  261. _, err = io.CopyN(f, rand.Reader, size)
  262. if err != nil {
  263. t.Error(err)
  264. }
  265. info, err := f.Stat()
  266. if err != nil {
  267. t.Error(err)
  268. }
  269. // Create two files, second file has `shifted` bytes random prefix, yet
  270. // both are of the same length, for example:
  271. // File 1: abcdefgh
  272. // File 2: xyabcdef
  273. f.Seek(0, os.SEEK_SET)
  274. existing, err := scanner.Blocks(context.TODO(), f, protocol.MinBlockSize, size, nil, true)
  275. if err != nil {
  276. t.Error(err)
  277. }
  278. f.Seek(0, os.SEEK_SET)
  279. remainder := io.LimitReader(f, size-shift)
  280. prefix := io.LimitReader(rand.Reader, shift)
  281. nf := io.MultiReader(prefix, remainder)
  282. desired, err := scanner.Blocks(context.TODO(), nf, protocol.MinBlockSize, size, nil, true)
  283. if err != nil {
  284. t.Error(err)
  285. }
  286. existingFile := protocol.FileInfo{
  287. Name: "weakhash",
  288. Blocks: existing,
  289. Size: size,
  290. ModifiedS: info.ModTime().Unix(),
  291. ModifiedNs: int32(info.ModTime().Nanosecond()),
  292. }
  293. desiredFile := protocol.FileInfo{
  294. Name: "weakhash",
  295. Size: size,
  296. Blocks: desired,
  297. ModifiedS: info.ModTime().Unix() + 1,
  298. }
  299. model.updateLocalsFromScanning("default", []protocol.FileInfo{existingFile})
  300. copyChan := make(chan copyBlocksState)
  301. pullChan := make(chan pullBlockState, expectBlocks)
  302. finisherChan := make(chan *sharedPullerState, 1)
  303. dbUpdateChan := make(chan dbUpdateJob, 1)
  304. // Run a single fetcher routine
  305. go fo.copierRoutine(copyChan, pullChan, finisherChan)
  306. // Test 1 - no weak hashing, file gets fully repulled (`expectBlocks` pulls).
  307. fo.WeakHashThresholdPct = 101
  308. fo.handleFile(desiredFile, copyChan, finisherChan, dbUpdateChan)
  309. var pulls []pullBlockState
  310. for len(pulls) < expectBlocks {
  311. select {
  312. case pull := <-pullChan:
  313. pulls = append(pulls, pull)
  314. case <-time.After(10 * time.Second):
  315. t.Errorf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  316. }
  317. }
  318. finish := <-finisherChan
  319. select {
  320. case <-pullChan:
  321. t.Fatal("Pull channel has data to be read")
  322. case <-finisherChan:
  323. t.Fatal("Finisher channel has data to be read")
  324. default:
  325. }
  326. finish.fd.Close()
  327. if err := ffs.Remove(tempFile); err != nil {
  328. t.Fatal(err)
  329. }
  330. // Test 2 - using weak hash, expectPulls blocks pulled.
  331. fo.WeakHashThresholdPct = -1
  332. fo.handleFile(desiredFile, copyChan, finisherChan, dbUpdateChan)
  333. pulls = pulls[:0]
  334. for len(pulls) < expectPulls {
  335. select {
  336. case pull := <-pullChan:
  337. pulls = append(pulls, pull)
  338. case <-time.After(10 * time.Second):
  339. t.Errorf("timed out, got %d pulls expected %d", len(pulls), expectPulls)
  340. }
  341. }
  342. finish = <-finisherChan
  343. finish.fd.Close()
  344. expectShifted := expectBlocks - expectPulls
  345. if finish.copyOriginShifted != expectShifted {
  346. t.Errorf("did not copy %d shifted", expectShifted)
  347. }
  348. }
  349. // Test that updating a file removes its old blocks from the blockmap
  350. func TestCopierCleanup(t *testing.T) {
  351. iterFn := func(folder, file string, index int32) bool {
  352. return true
  353. }
  354. // Create a file
  355. file := setupFile("test", []int{0})
  356. m, _, tmpDir := setupSendReceiveFolder(file)
  357. defer func() {
  358. os.Remove(m.cfg.ConfigPath())
  359. os.Remove(tmpDir)
  360. }()
  361. file.Blocks = []protocol.BlockInfo{blocks[1]}
  362. file.Version = file.Version.Update(myID.Short())
  363. // Update index (removing old blocks)
  364. m.updateLocalsFromScanning("default", []protocol.FileInfo{file})
  365. if m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  366. t.Error("Unexpected block found")
  367. }
  368. if !m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  369. t.Error("Expected block not found")
  370. }
  371. file.Blocks = []protocol.BlockInfo{blocks[0]}
  372. file.Version = file.Version.Update(myID.Short())
  373. // Update index (removing old blocks)
  374. m.updateLocalsFromScanning("default", []protocol.FileInfo{file})
  375. if !m.finder.Iterate(folders, blocks[0].Hash, iterFn) {
  376. t.Error("Unexpected block found")
  377. }
  378. if m.finder.Iterate(folders, blocks[1].Hash, iterFn) {
  379. t.Error("Expected block not found")
  380. }
  381. }
  382. func TestDeregisterOnFailInCopy(t *testing.T) {
  383. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  384. m, f, tmpDir := setupSendReceiveFolder()
  385. defer func() {
  386. os.Remove(m.cfg.ConfigPath())
  387. os.Remove(tmpDir)
  388. }()
  389. // Set up our evet subscription early
  390. s := events.Default.Subscribe(events.ItemFinished)
  391. // queue.Done should be called by the finisher routine
  392. f.queue.Push("filex", 0, time.Time{})
  393. f.queue.Pop()
  394. if f.queue.lenProgress() != 1 {
  395. t.Fatal("Expected file in progress")
  396. }
  397. copyChan := make(chan copyBlocksState)
  398. pullChan := make(chan pullBlockState)
  399. finisherBufferChan := make(chan *sharedPullerState)
  400. finisherChan := make(chan *sharedPullerState)
  401. dbUpdateChan := make(chan dbUpdateJob, 1)
  402. go f.copierRoutine(copyChan, pullChan, finisherBufferChan)
  403. go f.finisherRoutine(ignore.New(defaultFs), finisherChan, dbUpdateChan, make(chan string))
  404. f.handleFile(file, copyChan, finisherChan, dbUpdateChan)
  405. // Receive a block at puller, to indicate that at least a single copier
  406. // loop has been performed.
  407. toPull := <-pullChan
  408. // Close the file, causing errors on further access
  409. toPull.sharedPullerState.fail(os.ErrNotExist)
  410. // Unblock copier
  411. go func() {
  412. for range pullChan {
  413. }
  414. }()
  415. select {
  416. case state := <-finisherBufferChan:
  417. // At this point the file should still be registered with both the job
  418. // queue, and the progress emitter. Verify this.
  419. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  420. t.Fatal("Could not find file")
  421. }
  422. // Pass the file down the real finisher, and give it time to consume
  423. finisherChan <- state
  424. t0 := time.Now()
  425. if ev, err := s.Poll(time.Minute); err != nil {
  426. t.Fatal("Got error waiting for ItemFinished event:", err)
  427. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  428. t.Fatal("Got ItemFinished event for wrong file:", n)
  429. }
  430. t.Log("event took", time.Since(t0))
  431. state.mut.Lock()
  432. stateFd := state.fd
  433. state.mut.Unlock()
  434. if stateFd != nil {
  435. t.Fatal("File not closed?")
  436. }
  437. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  438. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  439. }
  440. // Doing it again should have no effect
  441. finisherChan <- state
  442. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  443. t.Fatal("Expected timeout, not another event", err)
  444. }
  445. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  446. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  447. }
  448. case <-time.After(time.Second):
  449. t.Fatal("Didn't get anything to the finisher")
  450. }
  451. }
  452. func TestDeregisterOnFailInPull(t *testing.T) {
  453. file := setupFile("filex", []int{0, 2, 0, 0, 5, 0, 0, 8})
  454. m, f, tmpDir := setupSendReceiveFolder()
  455. defer func() {
  456. os.Remove(m.cfg.ConfigPath())
  457. os.Remove(tmpDir)
  458. }()
  459. // Set up our evet subscription early
  460. s := events.Default.Subscribe(events.ItemFinished)
  461. // queue.Done should be called by the finisher routine
  462. f.queue.Push("filex", 0, time.Time{})
  463. f.queue.Pop()
  464. if f.queue.lenProgress() != 1 {
  465. t.Fatal("Expected file in progress")
  466. }
  467. copyChan := make(chan copyBlocksState)
  468. pullChan := make(chan pullBlockState)
  469. finisherBufferChan := make(chan *sharedPullerState)
  470. finisherChan := make(chan *sharedPullerState)
  471. dbUpdateChan := make(chan dbUpdateJob, 1)
  472. go f.copierRoutine(copyChan, pullChan, finisherBufferChan)
  473. go f.pullerRoutine(pullChan, finisherBufferChan)
  474. go f.finisherRoutine(ignore.New(defaultFs), finisherChan, dbUpdateChan, make(chan string))
  475. f.handleFile(file, copyChan, finisherChan, dbUpdateChan)
  476. // Receive at finisher, we should error out as puller has nowhere to pull
  477. // from.
  478. timeout = time.Second
  479. select {
  480. case state := <-finisherBufferChan:
  481. // At this point the file should still be registered with both the job
  482. // queue, and the progress emitter. Verify this.
  483. if f.model.progressEmitter.lenRegistry() != 1 || f.queue.lenProgress() != 1 || f.queue.lenQueued() != 0 {
  484. t.Fatal("Could not find file")
  485. }
  486. // Pass the file down the real finisher, and give it time to consume
  487. finisherChan <- state
  488. t0 := time.Now()
  489. if ev, err := s.Poll(time.Minute); err != nil {
  490. t.Fatal("Got error waiting for ItemFinished event:", err)
  491. } else if n := ev.Data.(map[string]interface{})["item"]; n != state.file.Name {
  492. t.Fatal("Got ItemFinished event for wrong file:", n)
  493. }
  494. t.Log("event took", time.Since(t0))
  495. state.mut.Lock()
  496. stateFd := state.fd
  497. state.mut.Unlock()
  498. if stateFd != nil {
  499. t.Fatal("File not closed?")
  500. }
  501. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  502. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  503. }
  504. // Doing it again should have no effect
  505. finisherChan <- state
  506. if _, err := s.Poll(time.Second); err != events.ErrTimeout {
  507. t.Fatal("Expected timeout, not another event", err)
  508. }
  509. if f.model.progressEmitter.lenRegistry() != 0 || f.queue.lenProgress() != 0 || f.queue.lenQueued() != 0 {
  510. t.Fatal("Still registered", f.model.progressEmitter.lenRegistry(), f.queue.lenProgress(), f.queue.lenQueued())
  511. }
  512. case <-time.After(time.Second):
  513. t.Fatal("Didn't get anything to the finisher")
  514. }
  515. }
  516. func TestIssue3164(t *testing.T) {
  517. m, f, tmpDir := setupSendReceiveFolder()
  518. defer func() {
  519. os.Remove(m.cfg.ConfigPath())
  520. os.Remove(tmpDir)
  521. }()
  522. ffs := f.Filesystem()
  523. ignDir := filepath.Join("issue3164", "oktodelete")
  524. subDir := filepath.Join(ignDir, "foobar")
  525. if err := ffs.MkdirAll(subDir, 0777); err != nil {
  526. t.Fatal(err)
  527. }
  528. if err := ioutil.WriteFile(filepath.Join(tmpDir, subDir, "file"), []byte("Hello"), 0644); err != nil {
  529. t.Fatal(err)
  530. }
  531. if err := ioutil.WriteFile(filepath.Join(tmpDir, ignDir, "file"), []byte("Hello"), 0644); err != nil {
  532. t.Fatal(err)
  533. }
  534. file := protocol.FileInfo{
  535. Name: "issue3164",
  536. }
  537. matcher := ignore.New(ffs)
  538. if err := matcher.Parse(bytes.NewBufferString("(?d)oktodelete"), ""); err != nil {
  539. t.Fatal(err)
  540. }
  541. dbUpdateChan := make(chan dbUpdateJob, 1)
  542. f.handleDeleteDir(file, matcher, dbUpdateChan, make(chan string))
  543. if _, err := ffs.Stat("issue3164"); !fs.IsNotExist(err) {
  544. t.Fatal(err)
  545. }
  546. }
  547. func TestDiff(t *testing.T) {
  548. for i, test := range diffTestData {
  549. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  550. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  551. _, d := blockDiff(a, b)
  552. if len(d) != len(test.d) {
  553. t.Fatalf("Incorrect length for diff %d; %d != %d", i, len(d), len(test.d))
  554. } else {
  555. for j := range test.d {
  556. if d[j].Offset != test.d[j].Offset {
  557. t.Errorf("Incorrect offset for diff %d block %d; %d != %d", i, j, d[j].Offset, test.d[j].Offset)
  558. }
  559. if d[j].Size != test.d[j].Size {
  560. t.Errorf("Incorrect length for diff %d block %d; %d != %d", i, j, d[j].Size, test.d[j].Size)
  561. }
  562. }
  563. }
  564. }
  565. }
  566. func BenchmarkDiff(b *testing.B) {
  567. testCases := make([]struct{ a, b []protocol.BlockInfo }, 0, len(diffTestData))
  568. for _, test := range diffTestData {
  569. a, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.a), test.s, -1, nil, false)
  570. b, _ := scanner.Blocks(context.TODO(), bytes.NewBufferString(test.b), test.s, -1, nil, false)
  571. testCases = append(testCases, struct{ a, b []protocol.BlockInfo }{a, b})
  572. }
  573. b.ReportAllocs()
  574. b.ResetTimer()
  575. for i := 0; i < b.N; i++ {
  576. for _, tc := range testCases {
  577. blockDiff(tc.a, tc.b)
  578. }
  579. }
  580. }
  581. func TestDiffEmpty(t *testing.T) {
  582. emptyCases := []struct {
  583. a []protocol.BlockInfo
  584. b []protocol.BlockInfo
  585. need int
  586. have int
  587. }{
  588. {nil, nil, 0, 0},
  589. {[]protocol.BlockInfo{{Offset: 3, Size: 1}}, nil, 0, 0},
  590. {nil, []protocol.BlockInfo{{Offset: 3, Size: 1}}, 1, 0},
  591. }
  592. for _, emptyCase := range emptyCases {
  593. h, n := blockDiff(emptyCase.a, emptyCase.b)
  594. if len(h) != emptyCase.have {
  595. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  596. }
  597. if len(n) != emptyCase.need {
  598. t.Errorf("incorrect have: %d != %d", len(h), emptyCase.have)
  599. }
  600. }
  601. }
  602. // TestDeleteIgnorePerms checks, that a file gets deleted when the IgnorePerms
  603. // option is true and the permissions do not match between the file on disk and
  604. // in the db.
  605. func TestDeleteIgnorePerms(t *testing.T) {
  606. m, f, tmpDir := setupSendReceiveFolder()
  607. defer func() {
  608. os.Remove(m.cfg.ConfigPath())
  609. os.Remove(tmpDir)
  610. }()
  611. f.IgnorePerms = true
  612. ffs := f.Filesystem()
  613. name := "deleteIgnorePerms"
  614. file, err := ffs.Create(name)
  615. if err != nil {
  616. t.Error(err)
  617. }
  618. defer file.Close()
  619. stat, err := file.Stat()
  620. if err != nil {
  621. t.Fatal(err)
  622. }
  623. fi, err := scanner.CreateFileInfo(stat, name, ffs)
  624. if err != nil {
  625. t.Fatal(err)
  626. }
  627. ffs.Chmod(name, 0600)
  628. scanChan := make(chan string)
  629. finished := make(chan struct{})
  630. go func() {
  631. err = f.checkToBeDeleted(fi, scanChan)
  632. close(finished)
  633. }()
  634. select {
  635. case <-scanChan:
  636. <-finished
  637. case <-finished:
  638. }
  639. if err != nil {
  640. t.Fatal(err)
  641. }
  642. }
  643. func TestCopyOwner(t *testing.T) {
  644. // Verifies that owner and group are copied from the parent, for both
  645. // files and directories.
  646. if runtime.GOOS == "windows" {
  647. t.Skip("copying owner not supported on Windows")
  648. }
  649. const (
  650. expOwner = 1234
  651. expGroup = 5678
  652. )
  653. // Set up a folder with the CopyParentOwner bit and backed by a fake
  654. // filesystem.
  655. m, f, _ := setupSendReceiveFolder()
  656. defer os.Remove(m.cfg.ConfigPath())
  657. f.folder.FolderConfiguration = config.NewFolderConfiguration(m.id, f.ID, f.Label, fs.FilesystemTypeFake, "/TestCopyOwner")
  658. f.folder.FolderConfiguration.CopyOwnershipFromParent = true
  659. f.fs = f.Filesystem()
  660. // Create a parent dir with a certain owner/group.
  661. f.fs.Mkdir("foo", 0755)
  662. f.fs.Lchown("foo", expOwner, expGroup)
  663. dir := protocol.FileInfo{
  664. Name: "foo/bar",
  665. Type: protocol.FileInfoTypeDirectory,
  666. Permissions: 0755,
  667. }
  668. // Have the folder create a subdirectory, verify that it's the correct
  669. // owner/group.
  670. dbUpdateChan := make(chan dbUpdateJob, 1)
  671. defer close(dbUpdateChan)
  672. f.handleDir(dir, dbUpdateChan)
  673. <-dbUpdateChan // empty the channel for later
  674. info, err := f.fs.Lstat("foo/bar")
  675. if err != nil {
  676. t.Fatal("Unexpected error (dir):", err)
  677. }
  678. if info.Owner() != expOwner || info.Group() != expGroup {
  679. t.Fatalf("Expected dir owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  680. }
  681. // Have the folder create a file, verify it's the correct owner/group.
  682. // File is zero sized to avoid having to handle copies/pulls.
  683. file := protocol.FileInfo{
  684. Name: "foo/bar/baz",
  685. Type: protocol.FileInfoTypeFile,
  686. Permissions: 0644,
  687. }
  688. // Wire some stuff. The flow here is handleFile() -[copierChan]->
  689. // copierRoutine() -[finisherChan]-> finisherRoutine() -[dbUpdateChan]->
  690. // back to us and we're done. The copier routine doesn't do anything,
  691. // but it's the way data is passed around. When the database update
  692. // comes the finisher is done.
  693. finisherChan := make(chan *sharedPullerState)
  694. defer close(finisherChan)
  695. copierChan := make(chan copyBlocksState)
  696. defer close(copierChan)
  697. go f.copierRoutine(copierChan, nil, finisherChan)
  698. go f.finisherRoutine(nil, finisherChan, dbUpdateChan, nil)
  699. f.handleFile(file, copierChan, nil, nil)
  700. <-dbUpdateChan
  701. info, err = f.fs.Lstat("foo/bar/baz")
  702. if err != nil {
  703. t.Fatal("Unexpected error (file):", err)
  704. }
  705. if info.Owner() != expOwner || info.Group() != expGroup {
  706. t.Fatalf("Expected file owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  707. }
  708. // Have the folder create a symlink. Verify it accordingly.
  709. symlink := protocol.FileInfo{
  710. Name: "foo/bar/sym",
  711. Type: protocol.FileInfoTypeSymlink,
  712. Permissions: 0644,
  713. SymlinkTarget: "over the rainbow",
  714. }
  715. f.handleSymlink(symlink, dbUpdateChan)
  716. <-dbUpdateChan
  717. info, err = f.fs.Lstat("foo/bar/sym")
  718. if err != nil {
  719. t.Fatal("Unexpected error (file):", err)
  720. }
  721. if info.Owner() != expOwner || info.Group() != expGroup {
  722. t.Fatalf("Expected symlink owner/group to be %d/%d, not %d/%d", expOwner, expGroup, info.Owner(), info.Group())
  723. }
  724. }