model_test.go 29 KB

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