testutils_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. // Copyright (C) 2016 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 https://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "context"
  9. "io/ioutil"
  10. "os"
  11. "testing"
  12. "time"
  13. "github.com/thejerf/suture/v4"
  14. "github.com/syncthing/syncthing/lib/config"
  15. "github.com/syncthing/syncthing/lib/db"
  16. "github.com/syncthing/syncthing/lib/db/backend"
  17. "github.com/syncthing/syncthing/lib/events"
  18. "github.com/syncthing/syncthing/lib/fs"
  19. "github.com/syncthing/syncthing/lib/ignore"
  20. "github.com/syncthing/syncthing/lib/protocol"
  21. "github.com/syncthing/syncthing/lib/rand"
  22. )
  23. var (
  24. myID, device1, device2 protocol.DeviceID
  25. defaultCfgWrapper config.Wrapper
  26. defaultCfgWrapperCancel context.CancelFunc
  27. defaultFolderConfig config.FolderConfiguration
  28. defaultFs fs.Filesystem
  29. defaultCfg config.Configuration
  30. defaultAutoAcceptCfg config.Configuration
  31. )
  32. func init() {
  33. myID, _ = protocol.DeviceIDFromString("ZNWFSWE-RWRV2BD-45BLMCV-LTDE2UR-4LJDW6J-R5BPWEB-TXD27XJ-IZF5RA4")
  34. device1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  35. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  36. defaultCfgWrapper, defaultCfgWrapperCancel = createTmpWrapper(config.New(myID))
  37. defaultFolderConfig = testFolderConfig("testdata")
  38. defaultFs = defaultFolderConfig.Filesystem()
  39. waiter, _ := defaultCfgWrapper.Modify(func(cfg *config.Configuration) {
  40. cfg.SetDevice(newDeviceConfiguration(cfg.Defaults.Device, device1, "device1"))
  41. cfg.SetFolder(defaultFolderConfig)
  42. cfg.Options.KeepTemporariesH = 1
  43. })
  44. waiter.Wait()
  45. defaultCfg = defaultCfgWrapper.RawCopy()
  46. defaultAutoAcceptCfg = config.Configuration{
  47. Version: config.CurrentVersion,
  48. Devices: []config.DeviceConfiguration{
  49. {
  50. DeviceID: myID, // self
  51. },
  52. {
  53. DeviceID: device1,
  54. AutoAcceptFolders: true,
  55. },
  56. {
  57. DeviceID: device2,
  58. AutoAcceptFolders: true,
  59. },
  60. },
  61. Defaults: config.Defaults{
  62. Folder: config.FolderConfiguration{
  63. Path: ".",
  64. },
  65. },
  66. }
  67. }
  68. func createTmpWrapper(cfg config.Configuration) (config.Wrapper, context.CancelFunc) {
  69. tmpFile, err := ioutil.TempFile("", "syncthing-testConfig-")
  70. if err != nil {
  71. panic(err)
  72. }
  73. wrapper := config.Wrap(tmpFile.Name(), cfg, myID, events.NoopLogger)
  74. tmpFile.Close()
  75. if cfgService, ok := wrapper.(suture.Service); ok {
  76. ctx, cancel := context.WithCancel(context.Background())
  77. go cfgService.Serve(ctx)
  78. return wrapper, cancel
  79. }
  80. return wrapper, func() {}
  81. }
  82. func tmpDefaultWrapper() (config.Wrapper, config.FolderConfiguration, context.CancelFunc) {
  83. w, cancel := createTmpWrapper(defaultCfgWrapper.RawCopy())
  84. fcfg := testFolderConfigTmp()
  85. _, _ = w.Modify(func(cfg *config.Configuration) {
  86. cfg.SetFolder(fcfg)
  87. })
  88. return w, fcfg, cancel
  89. }
  90. func testFolderConfigTmp() config.FolderConfiguration {
  91. tmpDir := createTmpDir()
  92. return testFolderConfig(tmpDir)
  93. }
  94. func testFolderConfig(path string) config.FolderConfiguration {
  95. cfg := newFolderConfiguration(defaultCfgWrapper, "default", "default", fs.FilesystemTypeBasic, path)
  96. cfg.FSWatcherEnabled = false
  97. cfg.Devices = append(cfg.Devices, config.FolderDeviceConfiguration{DeviceID: device1})
  98. return cfg
  99. }
  100. func testFolderConfigFake() config.FolderConfiguration {
  101. cfg := newFolderConfiguration(defaultCfgWrapper, "default", "default", fs.FilesystemTypeFake, rand.String(32)+"?content=true")
  102. cfg.FSWatcherEnabled = false
  103. cfg.Devices = append(cfg.Devices, config.FolderDeviceConfiguration{DeviceID: device1})
  104. return cfg
  105. }
  106. func setupModelWithConnection(t testing.TB) (*testModel, *fakeConnection, config.FolderConfiguration, context.CancelFunc) {
  107. t.Helper()
  108. w, fcfg, cancel := tmpDefaultWrapper()
  109. m, fc := setupModelWithConnectionFromWrapper(t, w)
  110. return m, fc, fcfg, cancel
  111. }
  112. func setupModelWithConnectionFromWrapper(t testing.TB, w config.Wrapper) (*testModel, *fakeConnection) {
  113. t.Helper()
  114. m := setupModel(t, w)
  115. fc := addFakeConn(m, device1)
  116. fc.folder = "default"
  117. _ = m.ScanFolder("default")
  118. return m, fc
  119. }
  120. func setupModel(t testing.TB, w config.Wrapper) *testModel {
  121. t.Helper()
  122. m := newModel(t, w, myID, "syncthing", "dev", nil)
  123. m.ServeBackground()
  124. <-m.started
  125. m.ScanFolders()
  126. return m
  127. }
  128. type testModel struct {
  129. *model
  130. cancel context.CancelFunc
  131. evCancel context.CancelFunc
  132. stopped chan struct{}
  133. }
  134. func newModel(t testing.TB, cfg config.Wrapper, id protocol.DeviceID, clientName, clientVersion string, protectedFiles []string) *testModel {
  135. t.Helper()
  136. evLogger := events.NewLogger()
  137. ldb, err := db.NewLowlevel(backend.OpenMemory(), evLogger)
  138. if err != nil {
  139. t.Fatal(err)
  140. }
  141. m := NewModel(cfg, id, clientName, clientVersion, ldb, protectedFiles, evLogger).(*model)
  142. ctx, cancel := context.WithCancel(context.Background())
  143. go evLogger.Serve(ctx)
  144. return &testModel{
  145. model: m,
  146. evCancel: cancel,
  147. stopped: make(chan struct{}),
  148. }
  149. }
  150. func (m *testModel) ServeBackground() {
  151. ctx, cancel := context.WithCancel(context.Background())
  152. m.cancel = cancel
  153. go func() {
  154. m.model.Serve(ctx)
  155. close(m.stopped)
  156. }()
  157. <-m.started
  158. }
  159. func cleanupModel(m *testModel) {
  160. if m.cancel != nil {
  161. m.cancel()
  162. <-m.stopped
  163. }
  164. m.evCancel()
  165. m.db.Close()
  166. os.Remove(m.cfg.ConfigPath())
  167. }
  168. func cleanupModelAndRemoveDir(m *testModel, dir string) {
  169. cleanupModel(m)
  170. os.RemoveAll(dir)
  171. }
  172. func createTmpDir() string {
  173. tmpDir, err := ioutil.TempDir("", "syncthing_testFolder-")
  174. if err != nil {
  175. panic("Failed to create temporary testing dir")
  176. }
  177. return tmpDir
  178. }
  179. type alwaysChangedKey struct {
  180. fs fs.Filesystem
  181. name string
  182. }
  183. // alwaysChanges is an ignore.ChangeDetector that always returns true on Changed()
  184. type alwaysChanged struct {
  185. seen map[alwaysChangedKey]struct{}
  186. }
  187. func newAlwaysChanged() *alwaysChanged {
  188. return &alwaysChanged{
  189. seen: make(map[alwaysChangedKey]struct{}),
  190. }
  191. }
  192. func (c *alwaysChanged) Remember(fs fs.Filesystem, name string, _ time.Time) {
  193. c.seen[alwaysChangedKey{fs, name}] = struct{}{}
  194. }
  195. func (c *alwaysChanged) Reset() {
  196. c.seen = make(map[alwaysChangedKey]struct{})
  197. }
  198. func (c *alwaysChanged) Seen(fs fs.Filesystem, name string) bool {
  199. _, ok := c.seen[alwaysChangedKey{fs, name}]
  200. return ok
  201. }
  202. func (c *alwaysChanged) Changed() bool {
  203. return true
  204. }
  205. func localSize(t *testing.T, m Model, folder string) db.Counts {
  206. t.Helper()
  207. snap := dbSnapshot(t, m, folder)
  208. defer snap.Release()
  209. return snap.LocalSize()
  210. }
  211. func globalSize(t *testing.T, m Model, folder string) db.Counts {
  212. t.Helper()
  213. snap := dbSnapshot(t, m, folder)
  214. defer snap.Release()
  215. return snap.GlobalSize()
  216. }
  217. func receiveOnlyChangedSize(t *testing.T, m Model, folder string) db.Counts {
  218. t.Helper()
  219. snap := dbSnapshot(t, m, folder)
  220. defer snap.Release()
  221. return snap.ReceiveOnlyChangedSize()
  222. }
  223. func needSize(t *testing.T, m Model, folder string) db.Counts {
  224. t.Helper()
  225. snap := dbSnapshot(t, m, folder)
  226. defer snap.Release()
  227. return snap.NeedSize(protocol.LocalDeviceID)
  228. }
  229. func dbSnapshot(t *testing.T, m Model, folder string) *db.Snapshot {
  230. t.Helper()
  231. snap, err := m.DBSnapshot(folder)
  232. if err != nil {
  233. t.Fatal(err)
  234. }
  235. return snap
  236. }
  237. // Reach in and update the ignore matcher to one that always does
  238. // reloads when asked to, instead of checking file mtimes. This is
  239. // because we will be changing the files on disk often enough that the
  240. // mtimes will be unreliable to determine change status.
  241. func folderIgnoresAlwaysReload(t testing.TB, m *testModel, fcfg config.FolderConfiguration) {
  242. t.Helper()
  243. m.removeFolder(fcfg)
  244. fset := newFileSet(t, fcfg.ID, fcfg.Filesystem(), m.db)
  245. ignores := ignore.New(fcfg.Filesystem(), ignore.WithCache(true), ignore.WithChangeDetector(newAlwaysChanged()))
  246. m.fmut.Lock()
  247. m.addAndStartFolderLockedWithIgnores(fcfg, fset, ignores)
  248. m.fmut.Unlock()
  249. }
  250. func basicClusterConfig(local, remote protocol.DeviceID, folders ...string) protocol.ClusterConfig {
  251. var cc protocol.ClusterConfig
  252. for _, folder := range folders {
  253. cc.Folders = append(cc.Folders, protocol.Folder{
  254. ID: folder,
  255. Devices: []protocol.Device{
  256. {
  257. ID: local,
  258. },
  259. {
  260. ID: remote,
  261. },
  262. },
  263. })
  264. }
  265. return cc
  266. }
  267. func localIndexUpdate(m *testModel, folder string, fs []protocol.FileInfo) {
  268. m.fmut.RLock()
  269. fset := m.folderFiles[folder]
  270. m.fmut.RUnlock()
  271. fset.Update(protocol.LocalDeviceID, fs)
  272. seq := fset.Sequence(protocol.LocalDeviceID)
  273. filenames := make([]string, len(fs))
  274. for i, file := range fs {
  275. filenames[i] = file.Name
  276. }
  277. m.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{
  278. "folder": folder,
  279. "items": len(fs),
  280. "filenames": filenames,
  281. "sequence": seq,
  282. "version": seq, // legacy for sequence
  283. })
  284. }
  285. func newDeviceConfiguration(defaultCfg config.DeviceConfiguration, id protocol.DeviceID, name string) config.DeviceConfiguration {
  286. cfg := defaultCfg.Copy()
  287. cfg.DeviceID = id
  288. cfg.Name = name
  289. return cfg
  290. }
  291. func newFileSet(t testing.TB, folder string, fs fs.Filesystem, ldb *db.Lowlevel) *db.FileSet {
  292. t.Helper()
  293. fset, err := db.NewFileSet(folder, fs, ldb)
  294. if err != nil {
  295. t.Fatal(err)
  296. }
  297. return fset
  298. }
  299. func replace(t testing.TB, w config.Wrapper, to config.Configuration) {
  300. t.Helper()
  301. waiter, err := w.Modify(func(cfg *config.Configuration) {
  302. *cfg = to
  303. })
  304. if err != nil {
  305. t.Fatal(err)
  306. }
  307. waiter.Wait()
  308. }
  309. func pauseFolder(t testing.TB, w config.Wrapper, id string, paused bool) {
  310. t.Helper()
  311. waiter, err := w.Modify(func(cfg *config.Configuration) {
  312. _, i, _ := cfg.Folder(id)
  313. cfg.Folders[i].Paused = paused
  314. })
  315. if err != nil {
  316. t.Fatal(err)
  317. }
  318. waiter.Wait()
  319. }
  320. func setFolder(t testing.TB, w config.Wrapper, fcfg config.FolderConfiguration) {
  321. t.Helper()
  322. waiter, err := w.Modify(func(cfg *config.Configuration) {
  323. cfg.SetFolder(fcfg)
  324. })
  325. if err != nil {
  326. t.Fatal(err)
  327. }
  328. waiter.Wait()
  329. }
  330. func pauseDevice(t testing.TB, w config.Wrapper, id protocol.DeviceID, paused bool) {
  331. t.Helper()
  332. waiter, err := w.Modify(func(cfg *config.Configuration) {
  333. _, i, _ := cfg.Device(id)
  334. cfg.Devices[i].Paused = paused
  335. })
  336. if err != nil {
  337. t.Fatal(err)
  338. }
  339. waiter.Wait()
  340. }
  341. func setDevice(t testing.TB, w config.Wrapper, device config.DeviceConfiguration) {
  342. t.Helper()
  343. waiter, err := w.Modify(func(cfg *config.Configuration) {
  344. cfg.SetDevice(device)
  345. })
  346. if err != nil {
  347. t.Fatal(err)
  348. }
  349. waiter.Wait()
  350. }
  351. func addDevice2(t testing.TB, w config.Wrapper, fcfg config.FolderConfiguration) {
  352. waiter, err := w.Modify(func(cfg *config.Configuration) {
  353. cfg.SetDevice(newDeviceConfiguration(cfg.Defaults.Device, device2, "device2"))
  354. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{DeviceID: device2})
  355. cfg.SetFolder(fcfg)
  356. })
  357. must(t, err)
  358. waiter.Wait()
  359. }