model_test.go 30 KB

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