rwfolder_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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 http://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "os"
  9. "path/filepath"
  10. "testing"
  11. "time"
  12. "github.com/syncthing/protocol"
  13. "github.com/syncthing/syncthing/internal/scanner"
  14. "github.com/syndtr/goleveldb/leveldb"
  15. "github.com/syndtr/goleveldb/leveldb/storage"
  16. )
  17. func init() {
  18. // We do this to make sure that the temp file required for the tests does
  19. // not get removed during the tests.
  20. future := time.Now().Add(time.Hour)
  21. err := os.Chtimes(filepath.Join("testdata", defTempNamer.TempName("file")), future, future)
  22. if err != nil {
  23. panic(err)
  24. }
  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. // Layout of the files: (indexes from the above array)
  38. // 12345678 - Required file
  39. // 02005008 - Existing file (currently in the index)
  40. // 02340070 - Temp file on the disk
  41. func TestHandleFile(t *testing.T) {
  42. // After the diff between required and existing we should:
  43. // Copy: 2, 5, 8
  44. // Pull: 1, 3, 4, 6, 7
  45. // Create existing file
  46. existingFile := protocol.FileInfo{
  47. Name: "filex",
  48. Flags: 0,
  49. Modified: 0,
  50. Blocks: []protocol.BlockInfo{
  51. blocks[0], blocks[2], blocks[0], blocks[0],
  52. blocks[5], blocks[0], blocks[0], blocks[8],
  53. },
  54. }
  55. // Create target file
  56. requiredFile := existingFile
  57. requiredFile.Blocks = blocks[1:]
  58. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  59. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  60. m.AddFolder(defaultFolderConfig)
  61. // Update index
  62. m.updateLocals("default", []protocol.FileInfo{existingFile})
  63. p := rwFolder{
  64. folder: "default",
  65. dir: "testdata",
  66. model: m,
  67. }
  68. copyChan := make(chan copyBlocksState, 1)
  69. p.handleFile(requiredFile, copyChan, nil)
  70. // Receive the results
  71. toCopy := <-copyChan
  72. if len(toCopy.blocks) != 8 {
  73. t.Errorf("Unexpected count of copy blocks: %d != 8", len(toCopy.blocks))
  74. }
  75. for i, block := range toCopy.blocks {
  76. if string(block.Hash) != string(blocks[i+1].Hash) {
  77. t.Errorf("Block mismatch: %s != %s", block.String(), blocks[i+1].String())
  78. }
  79. }
  80. }
  81. func TestHandleFileWithTemp(t *testing.T) {
  82. // After diff between required and existing we should:
  83. // Copy: 2, 5, 8
  84. // Pull: 1, 3, 4, 6, 7
  85. // After dropping out blocks already on the temp file we should:
  86. // Copy: 5, 8
  87. // Pull: 1, 6
  88. // Create existing file
  89. existingFile := protocol.FileInfo{
  90. Name: "file",
  91. Flags: 0,
  92. Modified: 0,
  93. Blocks: []protocol.BlockInfo{
  94. blocks[0], blocks[2], blocks[0], blocks[0],
  95. blocks[5], blocks[0], blocks[0], blocks[8],
  96. },
  97. }
  98. // Create target file
  99. requiredFile := existingFile
  100. requiredFile.Blocks = blocks[1:]
  101. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  102. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  103. m.AddFolder(defaultFolderConfig)
  104. // Update index
  105. m.updateLocals("default", []protocol.FileInfo{existingFile})
  106. p := rwFolder{
  107. folder: "default",
  108. dir: "testdata",
  109. model: m,
  110. }
  111. copyChan := make(chan copyBlocksState, 1)
  112. p.handleFile(requiredFile, copyChan, nil)
  113. // Receive the results
  114. toCopy := <-copyChan
  115. if len(toCopy.blocks) != 4 {
  116. t.Errorf("Unexpected count of copy blocks: %d != 4", len(toCopy.blocks))
  117. }
  118. for i, eq := range []int{1, 5, 6, 8} {
  119. if string(toCopy.blocks[i].Hash) != string(blocks[eq].Hash) {
  120. t.Errorf("Block mismatch: %s != %s", toCopy.blocks[i].String(), blocks[eq].String())
  121. }
  122. }
  123. }
  124. func TestCopierFinder(t *testing.T) {
  125. // After diff between required and existing we should:
  126. // Copy: 1, 2, 3, 4, 6, 7, 8
  127. // Since there is no existing file, nor a temp file
  128. // After dropping out blocks found locally:
  129. // Pull: 1, 5, 6, 8
  130. tempFile := filepath.Join("testdata", defTempNamer.TempName("file2"))
  131. err := os.Remove(tempFile)
  132. if err != nil && !os.IsNotExist(err) {
  133. t.Error(err)
  134. }
  135. // Create existing file
  136. existingFile := protocol.FileInfo{
  137. Name: defTempNamer.TempName("file"),
  138. Flags: 0,
  139. Modified: 0,
  140. Blocks: []protocol.BlockInfo{
  141. blocks[0], blocks[2], blocks[3], blocks[4],
  142. blocks[0], blocks[0], blocks[7], blocks[0],
  143. },
  144. }
  145. // Create target file
  146. requiredFile := existingFile
  147. requiredFile.Blocks = blocks[1:]
  148. requiredFile.Name = "file2"
  149. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  150. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  151. m.AddFolder(defaultFolderConfig)
  152. // Update index
  153. m.updateLocals("default", []protocol.FileInfo{existingFile})
  154. iterFn := func(folder, file string, index int32) bool {
  155. return true
  156. }
  157. // Verify that the blocks we say exist on file, really exist in the db.
  158. for _, idx := range []int{2, 3, 4, 7} {
  159. if m.finder.Iterate(blocks[idx].Hash, iterFn) == false {
  160. t.Error("Didn't find block")
  161. }
  162. }
  163. p := rwFolder{
  164. folder: "default",
  165. dir: "testdata",
  166. model: m,
  167. }
  168. copyChan := make(chan copyBlocksState)
  169. pullChan := make(chan pullBlockState, 4)
  170. finisherChan := make(chan *sharedPullerState, 1)
  171. // Run a single fetcher routine
  172. go p.copierRoutine(copyChan, pullChan, finisherChan)
  173. p.handleFile(requiredFile, copyChan, finisherChan)
  174. pulls := []pullBlockState{<-pullChan, <-pullChan, <-pullChan, <-pullChan}
  175. finish := <-finisherChan
  176. select {
  177. case <-pullChan:
  178. t.Fatal("Finisher channel has data to be read")
  179. case <-finisherChan:
  180. t.Fatal("Finisher channel has data to be read")
  181. default:
  182. }
  183. // Verify that the right blocks went into the pull list
  184. for i, eq := range []int{1, 5, 6, 8} {
  185. if string(pulls[i].block.Hash) != string(blocks[eq].Hash) {
  186. t.Errorf("Block %d mismatch: %s != %s", eq, pulls[i].block.String(), blocks[eq].String())
  187. }
  188. if string(finish.file.Blocks[eq-1].Hash) != string(blocks[eq].Hash) {
  189. t.Errorf("Block %d mismatch: %s != %s", eq, finish.file.Blocks[eq-1].String(), blocks[eq].String())
  190. }
  191. }
  192. // Verify that the fetched blocks have actually been written to the temp file
  193. blks, err := scanner.HashFile(tempFile, protocol.BlockSize)
  194. if err != nil {
  195. t.Log(err)
  196. }
  197. for _, eq := range []int{2, 3, 4, 7} {
  198. if string(blks[eq-1].Hash) != string(blocks[eq].Hash) {
  199. t.Errorf("Block %d mismatch: %s != %s", eq, blks[eq-1].String(), blocks[eq].String())
  200. }
  201. }
  202. finish.fd.Close()
  203. os.Remove(tempFile)
  204. }
  205. // Test that updating a file removes it's old blocks from the blockmap
  206. func TestCopierCleanup(t *testing.T) {
  207. iterFn := func(folder, file string, index int32) bool {
  208. return true
  209. }
  210. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  211. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  212. m.AddFolder(defaultFolderConfig)
  213. // Create a file
  214. file := protocol.FileInfo{
  215. Name: "test",
  216. Flags: 0,
  217. Modified: 0,
  218. Blocks: []protocol.BlockInfo{blocks[0]},
  219. }
  220. // Add file to index
  221. m.updateLocals("default", []protocol.FileInfo{file})
  222. if !m.finder.Iterate(blocks[0].Hash, iterFn) {
  223. t.Error("Expected block not found")
  224. }
  225. file.Blocks = []protocol.BlockInfo{blocks[1]}
  226. file.Version = file.Version.Update(protocol.LocalDeviceID.Short())
  227. // Update index (removing old blocks)
  228. m.updateLocals("default", []protocol.FileInfo{file})
  229. if m.finder.Iterate(blocks[0].Hash, iterFn) {
  230. t.Error("Unexpected block found")
  231. }
  232. if !m.finder.Iterate(blocks[1].Hash, iterFn) {
  233. t.Error("Expected block not found")
  234. }
  235. file.Blocks = []protocol.BlockInfo{blocks[0]}
  236. file.Version = file.Version.Update(protocol.LocalDeviceID.Short())
  237. // Update index (removing old blocks)
  238. m.updateLocals("default", []protocol.FileInfo{file})
  239. if !m.finder.Iterate(blocks[0].Hash, iterFn) {
  240. t.Error("Unexpected block found")
  241. }
  242. if m.finder.Iterate(blocks[1].Hash, iterFn) {
  243. t.Error("Expected block not found")
  244. }
  245. }
  246. // Make sure that the copier routine hashes the content when asked, and pulls
  247. // if it fails to find the block.
  248. func TestLastResortPulling(t *testing.T) {
  249. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  250. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  251. m.AddFolder(defaultFolderConfig)
  252. // Add a file to index (with the incorrect block representation, as content
  253. // doesn't actually match the block list)
  254. file := protocol.FileInfo{
  255. Name: "empty",
  256. Flags: 0,
  257. Modified: 0,
  258. Blocks: []protocol.BlockInfo{blocks[0]},
  259. }
  260. m.updateLocals("default", []protocol.FileInfo{file})
  261. // Pretend that we are handling a new file of the same content but
  262. // with a different name (causing to copy that particular block)
  263. file.Name = "newfile"
  264. iterFn := func(folder, file string, index int32) bool {
  265. return true
  266. }
  267. // Check that that particular block is there
  268. if !m.finder.Iterate(blocks[0].Hash, iterFn) {
  269. t.Error("Expected block not found")
  270. }
  271. p := rwFolder{
  272. folder: "default",
  273. dir: "testdata",
  274. model: m,
  275. }
  276. copyChan := make(chan copyBlocksState)
  277. pullChan := make(chan pullBlockState, 1)
  278. finisherChan := make(chan *sharedPullerState, 1)
  279. // Run a single copier routine
  280. go p.copierRoutine(copyChan, pullChan, finisherChan)
  281. p.handleFile(file, copyChan, finisherChan)
  282. // Copier should hash empty file, realise that the region it has read
  283. // doesn't match the hash which was advertised by the block map, fix it
  284. // and ask to pull the block.
  285. <-pullChan
  286. // Verify that it did fix the incorrect hash.
  287. if m.finder.Iterate(blocks[0].Hash, iterFn) {
  288. t.Error("Found unexpected block")
  289. }
  290. if !m.finder.Iterate(scanner.SHA256OfNothing, iterFn) {
  291. t.Error("Expected block not found")
  292. }
  293. (<-finisherChan).fd.Close()
  294. os.Remove(filepath.Join("testdata", defTempNamer.TempName("newfile")))
  295. }
  296. func TestDeregisterOnFailInCopy(t *testing.T) {
  297. file := protocol.FileInfo{
  298. Name: "filex",
  299. Flags: 0,
  300. Modified: 0,
  301. Blocks: []protocol.BlockInfo{
  302. blocks[0], blocks[2], blocks[0], blocks[0],
  303. blocks[5], blocks[0], blocks[0], blocks[8],
  304. },
  305. }
  306. defer os.Remove("testdata/" + defTempNamer.TempName("filex"))
  307. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  308. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  309. m.AddFolder(defaultFolderConfig)
  310. emitter := NewProgressEmitter(defaultConfig)
  311. go emitter.Serve()
  312. p := rwFolder{
  313. folder: "default",
  314. dir: "testdata",
  315. model: m,
  316. queue: newJobQueue(),
  317. progressEmitter: emitter,
  318. }
  319. // queue.Done should be called by the finisher routine
  320. p.queue.Push("filex")
  321. p.queue.Pop()
  322. if len(p.queue.progress) != 1 {
  323. t.Fatal("Expected file in progress")
  324. }
  325. copyChan := make(chan copyBlocksState)
  326. pullChan := make(chan pullBlockState)
  327. finisherBufferChan := make(chan *sharedPullerState)
  328. finisherChan := make(chan *sharedPullerState)
  329. go p.copierRoutine(copyChan, pullChan, finisherBufferChan)
  330. go p.finisherRoutine(finisherChan)
  331. p.handleFile(file, copyChan, finisherChan)
  332. // Receive a block at puller, to indicate that atleast a single copier
  333. // loop has been performed.
  334. toPull := <-pullChan
  335. // Wait until copier is trying to pass something down to the puller again
  336. time.Sleep(100 * time.Millisecond)
  337. // Close the file
  338. toPull.sharedPullerState.fail("test", os.ErrNotExist)
  339. // Unblock copier
  340. <-pullChan
  341. select {
  342. case state := <-finisherBufferChan:
  343. // At this point the file should still be registered with both the job
  344. // queue, and the progress emitter. Verify this.
  345. if len(p.progressEmitter.registry) != 1 || len(p.queue.progress) != 1 || len(p.queue.queued) != 0 {
  346. t.Fatal("Could not find file")
  347. }
  348. // Pass the file down the real finisher, and give it time to consume
  349. finisherChan <- state
  350. time.Sleep(100 * time.Millisecond)
  351. if state.fd != nil {
  352. t.Fatal("File not closed?")
  353. }
  354. if len(p.progressEmitter.registry) != 0 || len(p.queue.progress) != 0 || len(p.queue.queued) != 0 {
  355. t.Fatal("Still registered", len(p.progressEmitter.registry), len(p.queue.progress), len(p.queue.queued))
  356. }
  357. // Doing it again should have no effect
  358. finisherChan <- state
  359. time.Sleep(100 * time.Millisecond)
  360. if len(p.progressEmitter.registry) != 0 || len(p.queue.progress) != 0 || len(p.queue.queued) != 0 {
  361. t.Fatal("Still registered")
  362. }
  363. case <-time.After(time.Second):
  364. t.Fatal("Didn't get anything to the finisher")
  365. }
  366. }
  367. func TestDeregisterOnFailInPull(t *testing.T) {
  368. file := protocol.FileInfo{
  369. Name: "filex",
  370. Flags: 0,
  371. Modified: 0,
  372. Blocks: []protocol.BlockInfo{
  373. blocks[0], blocks[2], blocks[0], blocks[0],
  374. blocks[5], blocks[0], blocks[0], blocks[8],
  375. },
  376. }
  377. defer os.Remove("testdata/" + defTempNamer.TempName("filex"))
  378. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  379. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  380. m.AddFolder(defaultFolderConfig)
  381. emitter := NewProgressEmitter(defaultConfig)
  382. go emitter.Serve()
  383. p := rwFolder{
  384. folder: "default",
  385. dir: "testdata",
  386. model: m,
  387. queue: newJobQueue(),
  388. progressEmitter: emitter,
  389. }
  390. // queue.Done should be called by the finisher routine
  391. p.queue.Push("filex")
  392. p.queue.Pop()
  393. if len(p.queue.progress) != 1 {
  394. t.Fatal("Expected file in progress")
  395. }
  396. copyChan := make(chan copyBlocksState)
  397. pullChan := make(chan pullBlockState)
  398. finisherBufferChan := make(chan *sharedPullerState)
  399. finisherChan := make(chan *sharedPullerState)
  400. go p.copierRoutine(copyChan, pullChan, finisherBufferChan)
  401. go p.pullerRoutine(pullChan, finisherBufferChan)
  402. go p.finisherRoutine(finisherChan)
  403. p.handleFile(file, copyChan, finisherChan)
  404. // Receove at finisher, we shoud error out as puller has nowhere to pull
  405. // from.
  406. select {
  407. case state := <-finisherBufferChan:
  408. // At this point the file should still be registered with both the job
  409. // queue, and the progress emitter. Verify this.
  410. if len(p.progressEmitter.registry) != 1 || len(p.queue.progress) != 1 || len(p.queue.queued) != 0 {
  411. t.Fatal("Could not find file")
  412. }
  413. // Pass the file down the real finisher, and give it time to consume
  414. finisherChan <- state
  415. time.Sleep(100 * time.Millisecond)
  416. if state.fd != nil {
  417. t.Fatal("File not closed?")
  418. }
  419. if len(p.progressEmitter.registry) != 0 || len(p.queue.progress) != 0 || len(p.queue.queued) != 0 {
  420. t.Fatal("Still registered", len(p.progressEmitter.registry), len(p.queue.progress), len(p.queue.queued))
  421. }
  422. // Doing it again should have no effect
  423. finisherChan <- state
  424. time.Sleep(100 * time.Millisecond)
  425. if len(p.progressEmitter.registry) != 0 || len(p.queue.progress) != 0 || len(p.queue.queued) != 0 {
  426. t.Fatal("Still registered")
  427. }
  428. case <-time.After(time.Second):
  429. t.Fatal("Didn't get anything to the finisher")
  430. }
  431. }