model_test.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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. "bytes"
  9. "encoding/json"
  10. "fmt"
  11. "io/ioutil"
  12. "math/rand"
  13. "os"
  14. "path/filepath"
  15. "strconv"
  16. "testing"
  17. "time"
  18. "github.com/syncthing/protocol"
  19. "github.com/syncthing/syncthing/lib/config"
  20. "github.com/syncthing/syncthing/lib/db"
  21. "github.com/syndtr/goleveldb/leveldb"
  22. "github.com/syndtr/goleveldb/leveldb/storage"
  23. )
  24. var device1, device2 protocol.DeviceID
  25. var defaultConfig *config.Wrapper
  26. var defaultFolderConfig config.FolderConfiguration
  27. func init() {
  28. device1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  29. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  30. defaultFolderConfig = config.FolderConfiguration{
  31. ID: "default",
  32. RawPath: "testdata",
  33. Devices: []config.FolderDeviceConfiguration{
  34. {
  35. DeviceID: device1,
  36. },
  37. },
  38. }
  39. _defaultConfig := config.Configuration{
  40. Folders: []config.FolderConfiguration{defaultFolderConfig},
  41. Devices: []config.DeviceConfiguration{
  42. {
  43. DeviceID: device1,
  44. },
  45. },
  46. Options: config.OptionsConfiguration{
  47. // Don't remove temporaries directly on startup
  48. KeepTemporariesH: 1,
  49. },
  50. }
  51. defaultConfig = config.Wrap("/tmp/test", _defaultConfig)
  52. }
  53. var testDataExpected = map[string]protocol.FileInfo{
  54. "foo": {
  55. Name: "foo",
  56. Flags: 0,
  57. Modified: 0,
  58. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0x7, Hash: []uint8{0xae, 0xc0, 0x70, 0x64, 0x5f, 0xe5, 0x3e, 0xe3, 0xb3, 0x76, 0x30, 0x59, 0x37, 0x61, 0x34, 0xf0, 0x58, 0xcc, 0x33, 0x72, 0x47, 0xc9, 0x78, 0xad, 0xd1, 0x78, 0xb6, 0xcc, 0xdf, 0xb0, 0x1, 0x9f}}},
  59. },
  60. "empty": {
  61. Name: "empty",
  62. Flags: 0,
  63. Modified: 0,
  64. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0x0, Hash: []uint8{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}}},
  65. },
  66. "bar": {
  67. Name: "bar",
  68. Flags: 0,
  69. Modified: 0,
  70. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}},
  71. },
  72. }
  73. func init() {
  74. // Fix expected test data to match reality
  75. for n, f := range testDataExpected {
  76. fi, _ := os.Stat("testdata/" + n)
  77. f.Flags = uint32(fi.Mode())
  78. f.Modified = fi.ModTime().Unix()
  79. testDataExpected[n] = f
  80. }
  81. }
  82. func TestRequest(t *testing.T) {
  83. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  84. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  85. // device1 shares default, but device2 doesn't
  86. m.AddFolder(defaultFolderConfig)
  87. m.StartFolderRO("default")
  88. m.ServeBackground()
  89. m.ScanFolder("default")
  90. bs := make([]byte, protocol.BlockSize)
  91. // Existing, shared file
  92. bs = bs[:6]
  93. err := m.Request(device1, "default", "foo", 0, nil, 0, nil, bs)
  94. if err != nil {
  95. t.Error(err)
  96. }
  97. if bytes.Compare(bs, []byte("foobar")) != 0 {
  98. t.Errorf("Incorrect data from request: %q", string(bs))
  99. }
  100. // Existing, nonshared file
  101. err = m.Request(device2, "default", "foo", 0, nil, 0, nil, bs)
  102. if err == nil {
  103. t.Error("Unexpected nil error on insecure file read")
  104. }
  105. // Nonexistent file
  106. err = m.Request(device1, "default", "nonexistent", 0, nil, 0, nil, bs)
  107. if err == nil {
  108. t.Error("Unexpected nil error on insecure file read")
  109. }
  110. // Shared folder, but disallowed file name
  111. err = m.Request(device1, "default", "../walk.go", 0, nil, 0, nil, bs)
  112. if err == nil {
  113. t.Error("Unexpected nil error on insecure file read")
  114. }
  115. // Negative offset
  116. err = m.Request(device1, "default", "foo", -4, nil, 0, nil, bs[:0])
  117. if err == nil {
  118. t.Error("Unexpected nil error on insecure file read")
  119. }
  120. // Larger block than available
  121. bs = bs[:42]
  122. err = m.Request(device1, "default", "foo", 0, nil, 0, nil, bs)
  123. if err == nil {
  124. t.Error("Unexpected nil error on insecure file read")
  125. }
  126. }
  127. func genFiles(n int) []protocol.FileInfo {
  128. files := make([]protocol.FileInfo, n)
  129. t := time.Now().Unix()
  130. for i := 0; i < n; i++ {
  131. files[i] = protocol.FileInfo{
  132. Name: fmt.Sprintf("file%d", i),
  133. Modified: t,
  134. Blocks: []protocol.BlockInfo{{0, 100, []byte("some hash bytes")}},
  135. }
  136. }
  137. return files
  138. }
  139. func BenchmarkIndex_10000(b *testing.B) {
  140. benchmarkIndex(b, 10000)
  141. }
  142. func BenchmarkIndex_100(b *testing.B) {
  143. benchmarkIndex(b, 100)
  144. }
  145. func benchmarkIndex(b *testing.B, nfiles int) {
  146. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  147. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  148. m.AddFolder(defaultFolderConfig)
  149. m.StartFolderRO("default")
  150. m.ServeBackground()
  151. files := genFiles(nfiles)
  152. m.Index(device1, "default", files, 0, nil)
  153. b.ResetTimer()
  154. for i := 0; i < b.N; i++ {
  155. m.Index(device1, "default", files, 0, nil)
  156. }
  157. b.ReportAllocs()
  158. }
  159. func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
  160. benchmarkIndexUpdate(b, 10000, 10000)
  161. }
  162. func BenchmarkIndexUpdate_10000_100(b *testing.B) {
  163. benchmarkIndexUpdate(b, 10000, 100)
  164. }
  165. func BenchmarkIndexUpdate_10000_1(b *testing.B) {
  166. benchmarkIndexUpdate(b, 10000, 1)
  167. }
  168. func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
  169. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  170. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  171. m.AddFolder(defaultFolderConfig)
  172. m.StartFolderRO("default")
  173. m.ServeBackground()
  174. files := genFiles(nfiles)
  175. ufiles := genFiles(nufiles)
  176. m.Index(device1, "default", files, 0, nil)
  177. b.ResetTimer()
  178. for i := 0; i < b.N; i++ {
  179. m.IndexUpdate(device1, "default", ufiles, 0, nil)
  180. }
  181. b.ReportAllocs()
  182. }
  183. type FakeConnection struct {
  184. id protocol.DeviceID
  185. requestData []byte
  186. }
  187. func (FakeConnection) Close() error {
  188. return nil
  189. }
  190. func (f FakeConnection) Start() {
  191. }
  192. func (f FakeConnection) ID() protocol.DeviceID {
  193. return f.id
  194. }
  195. func (f FakeConnection) Name() string {
  196. return ""
  197. }
  198. func (f FakeConnection) Option(string) string {
  199. return ""
  200. }
  201. func (FakeConnection) Index(string, []protocol.FileInfo, uint32, []protocol.Option) error {
  202. return nil
  203. }
  204. func (FakeConnection) IndexUpdate(string, []protocol.FileInfo, uint32, []protocol.Option) error {
  205. return nil
  206. }
  207. func (f FakeConnection) Request(folder, name string, offset int64, size int, hash []byte, flags uint32, options []protocol.Option) ([]byte, error) {
  208. return f.requestData, nil
  209. }
  210. func (FakeConnection) ClusterConfig(protocol.ClusterConfigMessage) {}
  211. func (FakeConnection) Ping() bool {
  212. return true
  213. }
  214. func (FakeConnection) Statistics() protocol.Statistics {
  215. return protocol.Statistics{}
  216. }
  217. func BenchmarkRequest(b *testing.B) {
  218. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  219. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  220. m.AddFolder(defaultFolderConfig)
  221. m.ServeBackground()
  222. m.ScanFolder("default")
  223. const n = 1000
  224. files := make([]protocol.FileInfo, n)
  225. t := time.Now().Unix()
  226. for i := 0; i < n; i++ {
  227. files[i] = protocol.FileInfo{
  228. Name: fmt.Sprintf("file%d", i),
  229. Modified: t,
  230. Blocks: []protocol.BlockInfo{{0, 100, []byte("some hash bytes")}},
  231. }
  232. }
  233. fc := FakeConnection{
  234. id: device1,
  235. requestData: []byte("some data to return"),
  236. }
  237. m.AddConnection(fc, fc)
  238. m.Index(device1, "default", files, 0, nil)
  239. b.ResetTimer()
  240. for i := 0; i < b.N; i++ {
  241. data, err := m.requestGlobal(device1, "default", files[i%n].Name, 0, 32, nil, 0, nil)
  242. if err != nil {
  243. b.Error(err)
  244. }
  245. if data == nil {
  246. b.Error("nil data")
  247. }
  248. }
  249. }
  250. func TestDeviceRename(t *testing.T) {
  251. ccm := protocol.ClusterConfigMessage{
  252. ClientName: "syncthing",
  253. ClientVersion: "v0.9.4",
  254. }
  255. defer os.Remove("tmpconfig.xml")
  256. rawCfg := config.New(device1)
  257. rawCfg.Devices = []config.DeviceConfiguration{
  258. {
  259. DeviceID: device1,
  260. },
  261. }
  262. cfg := config.Wrap("tmpconfig.xml", rawCfg)
  263. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  264. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  265. m.ServeBackground()
  266. if cfg.Devices()[device1].Name != "" {
  267. t.Errorf("Device already has a name")
  268. }
  269. m.ClusterConfig(device1, ccm)
  270. if cfg.Devices()[device1].Name != "" {
  271. t.Errorf("Device already has a name")
  272. }
  273. ccm.Options = []protocol.Option{
  274. {
  275. Key: "name",
  276. Value: "tester",
  277. },
  278. }
  279. m.ClusterConfig(device1, ccm)
  280. if cfg.Devices()[device1].Name != "tester" {
  281. t.Errorf("Device did not get a name")
  282. }
  283. ccm.Options[0].Value = "tester2"
  284. m.ClusterConfig(device1, ccm)
  285. if cfg.Devices()[device1].Name != "tester" {
  286. t.Errorf("Device name got overwritten")
  287. }
  288. cfgw, err := config.Load("tmpconfig.xml", protocol.LocalDeviceID)
  289. if err != nil {
  290. t.Error(err)
  291. return
  292. }
  293. if cfgw.Devices()[device1].Name != "tester" {
  294. t.Errorf("Device name not saved in config")
  295. }
  296. }
  297. func TestClusterConfig(t *testing.T) {
  298. cfg := config.New(device1)
  299. cfg.Devices = []config.DeviceConfiguration{
  300. {
  301. DeviceID: device1,
  302. Introducer: true,
  303. },
  304. {
  305. DeviceID: device2,
  306. },
  307. }
  308. cfg.Folders = []config.FolderConfiguration{
  309. {
  310. ID: "folder1",
  311. Devices: []config.FolderDeviceConfiguration{
  312. {DeviceID: device1},
  313. {DeviceID: device2},
  314. },
  315. },
  316. {
  317. ID: "folder2",
  318. Devices: []config.FolderDeviceConfiguration{
  319. {DeviceID: device1},
  320. {DeviceID: device2},
  321. },
  322. },
  323. }
  324. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  325. m := NewModel(config.Wrap("/tmp/test", cfg), protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  326. m.AddFolder(cfg.Folders[0])
  327. m.AddFolder(cfg.Folders[1])
  328. m.ServeBackground()
  329. cm := m.clusterConfig(device2)
  330. if l := len(cm.Folders); l != 2 {
  331. t.Fatalf("Incorrect number of folders %d != 2", l)
  332. }
  333. r := cm.Folders[0]
  334. if r.ID != "folder1" {
  335. t.Errorf("Incorrect folder %q != folder1", r.ID)
  336. }
  337. if l := len(r.Devices); l != 2 {
  338. t.Errorf("Incorrect number of devices %d != 2", l)
  339. }
  340. if id := r.Devices[0].ID; bytes.Compare(id, device1[:]) != 0 {
  341. t.Errorf("Incorrect device ID %x != %x", id, device1)
  342. }
  343. if r.Devices[0].Flags&protocol.FlagIntroducer == 0 {
  344. t.Error("Device1 should be flagged as Introducer")
  345. }
  346. if id := r.Devices[1].ID; bytes.Compare(id, device2[:]) != 0 {
  347. t.Errorf("Incorrect device ID %x != %x", id, device2)
  348. }
  349. if r.Devices[1].Flags&protocol.FlagIntroducer != 0 {
  350. t.Error("Device2 should not be flagged as Introducer")
  351. }
  352. r = cm.Folders[1]
  353. if r.ID != "folder2" {
  354. t.Errorf("Incorrect folder %q != folder2", r.ID)
  355. }
  356. if l := len(r.Devices); l != 2 {
  357. t.Errorf("Incorrect number of devices %d != 2", l)
  358. }
  359. if id := r.Devices[0].ID; bytes.Compare(id, device1[:]) != 0 {
  360. t.Errorf("Incorrect device ID %x != %x", id, device1)
  361. }
  362. if r.Devices[0].Flags&protocol.FlagIntroducer == 0 {
  363. t.Error("Device1 should be flagged as Introducer")
  364. }
  365. if id := r.Devices[1].ID; bytes.Compare(id, device2[:]) != 0 {
  366. t.Errorf("Incorrect device ID %x != %x", id, device2)
  367. }
  368. if r.Devices[1].Flags&protocol.FlagIntroducer != 0 {
  369. t.Error("Device2 should not be flagged as Introducer")
  370. }
  371. }
  372. func TestIgnores(t *testing.T) {
  373. arrEqual := func(a, b []string) bool {
  374. if len(a) != len(b) {
  375. return false
  376. }
  377. for i := range a {
  378. if a[i] != b[i] {
  379. return false
  380. }
  381. }
  382. return true
  383. }
  384. // Assure a clean start state
  385. ioutil.WriteFile("testdata/.stfolder", nil, 0644)
  386. ioutil.WriteFile("testdata/.stignore", []byte(".*\nquux\n"), 0644)
  387. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  388. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  389. m.AddFolder(defaultFolderConfig)
  390. m.StartFolderRO("default")
  391. m.ServeBackground()
  392. expected := []string{
  393. ".*",
  394. "quux",
  395. }
  396. ignores, _, err := m.GetIgnores("default")
  397. if err != nil {
  398. t.Error(err)
  399. }
  400. if !arrEqual(ignores, expected) {
  401. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  402. }
  403. ignores = append(ignores, "pox")
  404. err = m.SetIgnores("default", ignores)
  405. if err != nil {
  406. t.Error(err)
  407. }
  408. ignores2, _, err := m.GetIgnores("default")
  409. if err != nil {
  410. t.Error(err)
  411. }
  412. if arrEqual(expected, ignores2) {
  413. t.Errorf("Incorrect ignores: %v == %v", ignores2, expected)
  414. }
  415. if !arrEqual(ignores, ignores2) {
  416. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  417. }
  418. err = m.SetIgnores("default", expected)
  419. if err != nil {
  420. t.Error(err)
  421. }
  422. ignores, _, err = m.GetIgnores("default")
  423. if err != nil {
  424. t.Error(err)
  425. }
  426. if !arrEqual(ignores, expected) {
  427. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  428. }
  429. ignores, _, err = m.GetIgnores("doesnotexist")
  430. if err == nil {
  431. t.Error("No error")
  432. }
  433. err = m.SetIgnores("doesnotexist", expected)
  434. if err == nil {
  435. t.Error("No error")
  436. }
  437. m.AddFolder(config.FolderConfiguration{ID: "fresh", RawPath: "XXX"})
  438. ignores, _, err = m.GetIgnores("fresh")
  439. if err != nil {
  440. t.Error(err)
  441. }
  442. if len(ignores) > 0 {
  443. t.Errorf("Expected no ignores, got: %v", ignores)
  444. }
  445. }
  446. func TestRefuseUnknownBits(t *testing.T) {
  447. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  448. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  449. m.AddFolder(defaultFolderConfig)
  450. m.ServeBackground()
  451. m.ScanFolder("default")
  452. m.Index(device1, "default", []protocol.FileInfo{
  453. {
  454. Name: "invalid1",
  455. Flags: (protocol.FlagsAll + 1) &^ protocol.FlagInvalid,
  456. },
  457. {
  458. Name: "invalid2",
  459. Flags: (protocol.FlagsAll + 2) &^ protocol.FlagInvalid,
  460. },
  461. {
  462. Name: "invalid3",
  463. Flags: (1 << 31) &^ protocol.FlagInvalid,
  464. },
  465. {
  466. Name: "valid",
  467. Flags: protocol.FlagsAll &^ (protocol.FlagInvalid | protocol.FlagSymlink),
  468. },
  469. }, 0, nil)
  470. for _, name := range []string{"invalid1", "invalid2", "invalid3"} {
  471. f, ok := m.CurrentGlobalFile("default", name)
  472. if ok || f.Name == name {
  473. t.Error("Invalid file found or name match")
  474. }
  475. }
  476. f, ok := m.CurrentGlobalFile("default", "valid")
  477. if !ok || f.Name != "valid" {
  478. t.Error("Valid file not found or name mismatch", ok, f)
  479. }
  480. }
  481. func TestROScanRecovery(t *testing.T) {
  482. ldb, _ := leveldb.Open(storage.NewMemStorage(), nil)
  483. set := db.NewFileSet("default", ldb)
  484. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  485. {Name: "dummyfile"},
  486. })
  487. fcfg := config.FolderConfiguration{
  488. ID: "default",
  489. RawPath: "testdata/rotestfolder",
  490. RescanIntervalS: 1,
  491. }
  492. cfg := config.Wrap("/tmp/test", config.Configuration{
  493. Folders: []config.FolderConfiguration{fcfg},
  494. Devices: []config.DeviceConfiguration{
  495. {
  496. DeviceID: device1,
  497. },
  498. },
  499. })
  500. os.RemoveAll(fcfg.RawPath)
  501. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb)
  502. m.AddFolder(fcfg)
  503. m.StartFolderRO("default")
  504. m.ServeBackground()
  505. waitFor := func(status string) error {
  506. timeout := time.Now().Add(2 * time.Second)
  507. for {
  508. if time.Now().After(timeout) {
  509. return fmt.Errorf("Timed out waiting for status: %s, current status: %s", status, m.cfg.Folders()["default"].Invalid)
  510. }
  511. _, _, err := m.State("default")
  512. if err == nil && status == "" {
  513. return nil
  514. }
  515. if err != nil && err.Error() == status {
  516. return nil
  517. }
  518. time.Sleep(10 * time.Millisecond)
  519. }
  520. }
  521. if err := waitFor("folder path missing"); err != nil {
  522. t.Error(err)
  523. return
  524. }
  525. os.Mkdir(fcfg.RawPath, 0700)
  526. if err := waitFor("folder marker missing"); err != nil {
  527. t.Error(err)
  528. return
  529. }
  530. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  531. if err != nil {
  532. t.Error(err)
  533. return
  534. }
  535. fd.Close()
  536. if err := waitFor(""); err != nil {
  537. t.Error(err)
  538. return
  539. }
  540. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  541. if err := waitFor("folder marker missing"); err != nil {
  542. t.Error(err)
  543. return
  544. }
  545. os.Remove(fcfg.RawPath)
  546. if err := waitFor("folder path missing"); err != nil {
  547. t.Error(err)
  548. return
  549. }
  550. }
  551. func TestRWScanRecovery(t *testing.T) {
  552. ldb, _ := leveldb.Open(storage.NewMemStorage(), nil)
  553. set := db.NewFileSet("default", ldb)
  554. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  555. {Name: "dummyfile"},
  556. })
  557. fcfg := config.FolderConfiguration{
  558. ID: "default",
  559. RawPath: "testdata/rwtestfolder",
  560. RescanIntervalS: 1,
  561. }
  562. cfg := config.Wrap("/tmp/test", config.Configuration{
  563. Folders: []config.FolderConfiguration{fcfg},
  564. Devices: []config.DeviceConfiguration{
  565. {
  566. DeviceID: device1,
  567. },
  568. },
  569. })
  570. os.RemoveAll(fcfg.RawPath)
  571. m := NewModel(cfg, protocol.LocalDeviceID, "device", "syncthing", "dev", ldb)
  572. m.AddFolder(fcfg)
  573. m.StartFolderRW("default")
  574. m.ServeBackground()
  575. waitFor := func(status string) error {
  576. timeout := time.Now().Add(2 * time.Second)
  577. for {
  578. if time.Now().After(timeout) {
  579. return fmt.Errorf("Timed out waiting for status: %s, current status: %s", status, m.cfg.Folders()["default"].Invalid)
  580. }
  581. _, _, err := m.State("default")
  582. if err == nil && status == "" {
  583. return nil
  584. }
  585. if err != nil && err.Error() == status {
  586. return nil
  587. }
  588. time.Sleep(10 * time.Millisecond)
  589. }
  590. }
  591. if err := waitFor("folder path missing"); err != nil {
  592. t.Error(err)
  593. return
  594. }
  595. os.Mkdir(fcfg.RawPath, 0700)
  596. if err := waitFor("folder marker missing"); err != nil {
  597. t.Error(err)
  598. return
  599. }
  600. fd, err := os.Create(filepath.Join(fcfg.RawPath, ".stfolder"))
  601. if err != nil {
  602. t.Error(err)
  603. return
  604. }
  605. fd.Close()
  606. if err := waitFor(""); err != nil {
  607. t.Error(err)
  608. return
  609. }
  610. os.Remove(filepath.Join(fcfg.RawPath, ".stfolder"))
  611. if err := waitFor("folder marker missing"); err != nil {
  612. t.Error(err)
  613. return
  614. }
  615. os.Remove(fcfg.RawPath)
  616. if err := waitFor("folder path missing"); err != nil {
  617. t.Error(err)
  618. return
  619. }
  620. }
  621. func TestGlobalDirectoryTree(t *testing.T) {
  622. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  623. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  624. m.AddFolder(defaultFolderConfig)
  625. m.ServeBackground()
  626. b := func(isfile bool, path ...string) protocol.FileInfo {
  627. flags := uint32(protocol.FlagDirectory)
  628. blocks := []protocol.BlockInfo{}
  629. if isfile {
  630. flags = 0
  631. blocks = []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}}
  632. }
  633. return protocol.FileInfo{
  634. Name: filepath.Join(path...),
  635. Flags: flags,
  636. Modified: 0x666,
  637. Blocks: blocks,
  638. }
  639. }
  640. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  641. testdata := []protocol.FileInfo{
  642. b(false, "another"),
  643. b(false, "another", "directory"),
  644. b(true, "another", "directory", "afile"),
  645. b(false, "another", "directory", "with"),
  646. b(false, "another", "directory", "with", "a"),
  647. b(true, "another", "directory", "with", "a", "file"),
  648. b(true, "another", "directory", "with", "file"),
  649. b(true, "another", "file"),
  650. b(false, "other"),
  651. b(false, "other", "rand"),
  652. b(false, "other", "random"),
  653. b(false, "other", "random", "dir"),
  654. b(false, "other", "random", "dirx"),
  655. b(false, "other", "randomx"),
  656. b(false, "some"),
  657. b(false, "some", "directory"),
  658. b(false, "some", "directory", "with"),
  659. b(false, "some", "directory", "with", "a"),
  660. b(true, "some", "directory", "with", "a", "file"),
  661. b(true, "rootfile"),
  662. }
  663. expectedResult := map[string]interface{}{
  664. "another": map[string]interface{}{
  665. "directory": map[string]interface{}{
  666. "afile": filedata,
  667. "with": map[string]interface{}{
  668. "a": map[string]interface{}{
  669. "file": filedata,
  670. },
  671. "file": filedata,
  672. },
  673. },
  674. "file": filedata,
  675. },
  676. "other": map[string]interface{}{
  677. "rand": map[string]interface{}{},
  678. "random": map[string]interface{}{
  679. "dir": map[string]interface{}{},
  680. "dirx": map[string]interface{}{},
  681. },
  682. "randomx": map[string]interface{}{},
  683. },
  684. "some": map[string]interface{}{
  685. "directory": map[string]interface{}{
  686. "with": map[string]interface{}{
  687. "a": map[string]interface{}{
  688. "file": filedata,
  689. },
  690. },
  691. },
  692. },
  693. "rootfile": filedata,
  694. }
  695. mm := func(data interface{}) string {
  696. bytes, err := json.Marshal(data)
  697. if err != nil {
  698. panic(err)
  699. }
  700. return string(bytes)
  701. }
  702. m.Index(device1, "default", testdata, 0, nil)
  703. result := m.GlobalDirectoryTree("default", "", -1, false)
  704. if mm(result) != mm(expectedResult) {
  705. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  706. }
  707. result = m.GlobalDirectoryTree("default", "another", -1, false)
  708. if mm(result) != mm(expectedResult["another"]) {
  709. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  710. }
  711. result = m.GlobalDirectoryTree("default", "", 0, false)
  712. currentResult := map[string]interface{}{
  713. "another": map[string]interface{}{},
  714. "other": map[string]interface{}{},
  715. "some": map[string]interface{}{},
  716. "rootfile": filedata,
  717. }
  718. if mm(result) != mm(currentResult) {
  719. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  720. }
  721. result = m.GlobalDirectoryTree("default", "", 1, false)
  722. currentResult = map[string]interface{}{
  723. "another": map[string]interface{}{
  724. "directory": map[string]interface{}{},
  725. "file": filedata,
  726. },
  727. "other": map[string]interface{}{
  728. "rand": map[string]interface{}{},
  729. "random": map[string]interface{}{},
  730. "randomx": map[string]interface{}{},
  731. },
  732. "some": map[string]interface{}{
  733. "directory": map[string]interface{}{},
  734. },
  735. "rootfile": filedata,
  736. }
  737. if mm(result) != mm(currentResult) {
  738. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  739. }
  740. result = m.GlobalDirectoryTree("default", "", -1, true)
  741. currentResult = map[string]interface{}{
  742. "another": map[string]interface{}{
  743. "directory": map[string]interface{}{
  744. "with": map[string]interface{}{
  745. "a": map[string]interface{}{},
  746. },
  747. },
  748. },
  749. "other": map[string]interface{}{
  750. "rand": map[string]interface{}{},
  751. "random": map[string]interface{}{
  752. "dir": map[string]interface{}{},
  753. "dirx": map[string]interface{}{},
  754. },
  755. "randomx": map[string]interface{}{},
  756. },
  757. "some": map[string]interface{}{
  758. "directory": map[string]interface{}{
  759. "with": map[string]interface{}{
  760. "a": map[string]interface{}{},
  761. },
  762. },
  763. },
  764. }
  765. if mm(result) != mm(currentResult) {
  766. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  767. }
  768. result = m.GlobalDirectoryTree("default", "", 1, true)
  769. currentResult = map[string]interface{}{
  770. "another": map[string]interface{}{
  771. "directory": map[string]interface{}{},
  772. },
  773. "other": map[string]interface{}{
  774. "rand": map[string]interface{}{},
  775. "random": map[string]interface{}{},
  776. "randomx": map[string]interface{}{},
  777. },
  778. "some": map[string]interface{}{
  779. "directory": map[string]interface{}{},
  780. },
  781. }
  782. if mm(result) != mm(currentResult) {
  783. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  784. }
  785. result = m.GlobalDirectoryTree("default", "another", 0, false)
  786. currentResult = map[string]interface{}{
  787. "directory": map[string]interface{}{},
  788. "file": filedata,
  789. }
  790. if mm(result) != mm(currentResult) {
  791. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  792. }
  793. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  794. currentResult = map[string]interface{}{
  795. "with": map[string]interface{}{},
  796. }
  797. if mm(result) != mm(currentResult) {
  798. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  799. }
  800. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  801. currentResult = map[string]interface{}{
  802. "with": map[string]interface{}{
  803. "a": map[string]interface{}{},
  804. },
  805. }
  806. if mm(result) != mm(currentResult) {
  807. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  808. }
  809. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  810. currentResult = map[string]interface{}{
  811. "with": map[string]interface{}{
  812. "a": map[string]interface{}{
  813. "file": filedata,
  814. },
  815. },
  816. }
  817. if mm(result) != mm(currentResult) {
  818. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  819. }
  820. result = m.GlobalDirectoryTree("default", "another", -1, true)
  821. currentResult = map[string]interface{}{
  822. "directory": map[string]interface{}{
  823. "with": map[string]interface{}{
  824. "a": map[string]interface{}{},
  825. },
  826. },
  827. }
  828. if mm(result) != mm(currentResult) {
  829. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  830. }
  831. // No prefix matching!
  832. result = m.GlobalDirectoryTree("default", "som", -1, false)
  833. currentResult = map[string]interface{}{}
  834. if mm(result) != mm(currentResult) {
  835. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  836. }
  837. }
  838. func TestGlobalDirectorySelfFixing(t *testing.T) {
  839. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  840. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  841. m.AddFolder(defaultFolderConfig)
  842. m.ServeBackground()
  843. b := func(isfile bool, path ...string) protocol.FileInfo {
  844. flags := uint32(protocol.FlagDirectory)
  845. blocks := []protocol.BlockInfo{}
  846. if isfile {
  847. flags = 0
  848. blocks = []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}}
  849. }
  850. return protocol.FileInfo{
  851. Name: filepath.Join(path...),
  852. Flags: flags,
  853. Modified: 0x666,
  854. Blocks: blocks,
  855. }
  856. }
  857. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  858. testdata := []protocol.FileInfo{
  859. b(true, "another", "directory", "afile"),
  860. b(true, "another", "directory", "with", "a", "file"),
  861. b(true, "another", "directory", "with", "file"),
  862. b(false, "other", "random", "dirx"),
  863. b(false, "other", "randomx"),
  864. b(false, "some", "directory", "with", "x"),
  865. b(true, "some", "directory", "with", "a", "file"),
  866. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  867. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  868. }
  869. expectedResult := map[string]interface{}{
  870. "another": map[string]interface{}{
  871. "directory": map[string]interface{}{
  872. "afile": filedata,
  873. "with": map[string]interface{}{
  874. "a": map[string]interface{}{
  875. "file": filedata,
  876. },
  877. "file": filedata,
  878. },
  879. },
  880. },
  881. "other": map[string]interface{}{
  882. "random": map[string]interface{}{
  883. "dirx": map[string]interface{}{},
  884. },
  885. "randomx": map[string]interface{}{},
  886. },
  887. "some": map[string]interface{}{
  888. "directory": map[string]interface{}{
  889. "with": map[string]interface{}{
  890. "a": map[string]interface{}{
  891. "file": filedata,
  892. },
  893. "x": map[string]interface{}{},
  894. },
  895. },
  896. },
  897. "this": map[string]interface{}{
  898. "is": map[string]interface{}{
  899. "a": map[string]interface{}{
  900. "deep": map[string]interface{}{
  901. "invalid": map[string]interface{}{
  902. "directory": map[string]interface{}{},
  903. },
  904. },
  905. },
  906. },
  907. },
  908. "xthis": map[string]interface{}{
  909. "is": map[string]interface{}{
  910. "a": map[string]interface{}{
  911. "deep": map[string]interface{}{
  912. "invalid": map[string]interface{}{
  913. "file": filedata,
  914. },
  915. },
  916. },
  917. },
  918. },
  919. }
  920. mm := func(data interface{}) string {
  921. bytes, err := json.Marshal(data)
  922. if err != nil {
  923. panic(err)
  924. }
  925. return string(bytes)
  926. }
  927. m.Index(device1, "default", testdata, 0, nil)
  928. result := m.GlobalDirectoryTree("default", "", -1, false)
  929. if mm(result) != mm(expectedResult) {
  930. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  931. }
  932. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  933. currentResult := map[string]interface{}{
  934. "invalid": map[string]interface{}{
  935. "file": filedata,
  936. },
  937. }
  938. if mm(result) != mm(currentResult) {
  939. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  940. }
  941. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  942. currentResult = map[string]interface{}{
  943. "invalid": map[string]interface{}{},
  944. }
  945. if mm(result) != mm(currentResult) {
  946. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  947. }
  948. // !!! This is actually BAD, because we don't have enough level allowance
  949. // to accept this file, hence the tree is left unbuilt !!!
  950. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  951. currentResult = map[string]interface{}{}
  952. if mm(result) != mm(currentResult) {
  953. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  954. }
  955. }
  956. func genDeepFiles(n, d int) []protocol.FileInfo {
  957. rand.Seed(int64(n))
  958. files := make([]protocol.FileInfo, n)
  959. t := time.Now().Unix()
  960. for i := 0; i < n; i++ {
  961. path := ""
  962. for i := 0; i <= d; i++ {
  963. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  964. }
  965. sofar := ""
  966. for _, path := range filepath.SplitList(path) {
  967. sofar = filepath.Join(sofar, path)
  968. files[i] = protocol.FileInfo{
  969. Name: sofar,
  970. }
  971. i++
  972. }
  973. files[i].Modified = t
  974. files[i].Blocks = []protocol.BlockInfo{{0, 100, []byte("some hash bytes")}}
  975. }
  976. return files
  977. }
  978. func BenchmarkTree_10000_50(b *testing.B) {
  979. benchmarkTree(b, 10000, 50)
  980. }
  981. func BenchmarkTree_100_50(b *testing.B) {
  982. benchmarkTree(b, 100, 50)
  983. }
  984. func BenchmarkTree_100_10(b *testing.B) {
  985. benchmarkTree(b, 100, 10)
  986. }
  987. func benchmarkTree(b *testing.B, n1, n2 int) {
  988. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  989. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  990. m.AddFolder(defaultFolderConfig)
  991. m.ServeBackground()
  992. m.ScanFolder("default")
  993. files := genDeepFiles(n1, n2)
  994. m.Index(device1, "default", files, 0, nil)
  995. b.ResetTimer()
  996. for i := 0; i < b.N; i++ {
  997. m.GlobalDirectoryTree("default", "", -1, false)
  998. }
  999. b.ReportAllocs()
  1000. }
  1001. func TestIgnoreDelete(t *testing.T) {
  1002. db, _ := leveldb.Open(storage.NewMemStorage(), nil)
  1003. m := NewModel(defaultConfig, protocol.LocalDeviceID, "device", "syncthing", "dev", db)
  1004. // This folder should ignore external deletes
  1005. cfg := defaultFolderConfig
  1006. cfg.IgnoreDelete = true
  1007. m.AddFolder(cfg)
  1008. m.ServeBackground()
  1009. m.StartFolderRW("default")
  1010. m.ScanFolder("default")
  1011. // Get a currently existing file
  1012. f, ok := m.CurrentGlobalFile("default", "foo")
  1013. if !ok {
  1014. t.Fatal("foo should exist")
  1015. }
  1016. // Mark it for deletion
  1017. f.Flags = protocol.FlagDeleted
  1018. f.Version = f.Version.Update(142) // arbitrary short remote ID
  1019. f.Blocks = nil
  1020. // Send the index
  1021. m.Index(device1, "default", []protocol.FileInfo{f}, 0, nil)
  1022. // Make sure we ignored it
  1023. f, ok = m.CurrentGlobalFile("default", "foo")
  1024. if !ok {
  1025. t.Fatal("foo should exist")
  1026. }
  1027. if f.IsDeleted() {
  1028. t.Fatal("foo should not be marked for deletion")
  1029. }
  1030. }