rwfolder_test.go 15 KB

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