wrapper.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 https://mozilla.org/MPL/2.0/.
  6. //go:generate counterfeiter -o mocks/mocked_wrapper.go --fake-name Wrapper . Wrapper
  7. package config
  8. import (
  9. "context"
  10. "errors"
  11. "os"
  12. "reflect"
  13. "sync/atomic"
  14. "time"
  15. "github.com/syncthing/syncthing/lib/events"
  16. "github.com/syncthing/syncthing/lib/osutil"
  17. "github.com/syncthing/syncthing/lib/protocol"
  18. "github.com/syncthing/syncthing/lib/sync"
  19. )
  20. const (
  21. maxModifications = 1000
  22. minSaveInterval = 5 * time.Second
  23. )
  24. var errTooManyModifications = errors.New("too many concurrent config modifications")
  25. // The Committer interface is implemented by objects that need to know about
  26. // or have a say in configuration changes.
  27. //
  28. // When the configuration is about to be changed, VerifyConfiguration() is
  29. // called for each subscribing object, with the old and new configuration. A
  30. // nil error is returned if the new configuration is acceptable (i.e. does not
  31. // contain any errors that would prevent it from being a valid config).
  32. // Otherwise an error describing the problem is returned.
  33. //
  34. // If any subscriber returns an error from VerifyConfiguration(), the
  35. // configuration change is not committed and an error is returned to whoever
  36. // tried to commit the broken config.
  37. //
  38. // If all verification calls returns nil, CommitConfiguration() is called for
  39. // each subscribing object. The callee returns true if the new configuration
  40. // has been successfully applied, otherwise false. Any Commit() call returning
  41. // false will result in a "restart needed" response to the API/user. Note that
  42. // the new configuration will still have been applied by those who were
  43. // capable of doing so.
  44. //
  45. // A Committer must take care not to hold any locks while changing the
  46. // configuration (e.g. calling Wrapper.SetFolder), that are also acquired in any
  47. // methods of the Committer interface.
  48. type Committer interface {
  49. VerifyConfiguration(from, to Configuration) error
  50. CommitConfiguration(from, to Configuration) (handled bool)
  51. String() string
  52. }
  53. // Waiter allows to wait for the given config operation to complete.
  54. type Waiter interface {
  55. Wait()
  56. }
  57. type noopWaiter struct{}
  58. func (noopWaiter) Wait() {}
  59. // ModifyFunction gets a pointer to a copy of the currently active configuration
  60. // for modification.
  61. type ModifyFunction func(*Configuration)
  62. // Wrapper handles a Configuration, i.e. it provides methods to access, change
  63. // and save the config, and notifies registered subscribers (Committer) of
  64. // changes.
  65. //
  66. // Modify allows changing the currently active configuration through the given
  67. // ModifyFunction. It can be called concurrently: All calls will be queued and
  68. // called in order.
  69. type Wrapper interface {
  70. ConfigPath() string
  71. MyID() protocol.DeviceID
  72. RawCopy() Configuration
  73. RequiresRestart() bool
  74. Save() error
  75. Modify(ModifyFunction) (Waiter, error)
  76. RemoveFolder(id string) (Waiter, error)
  77. RemoveDevice(id protocol.DeviceID) (Waiter, error)
  78. GUI() GUIConfiguration
  79. LDAP() LDAPConfiguration
  80. Options() OptionsConfiguration
  81. Folder(id string) (FolderConfiguration, bool)
  82. Folders() map[string]FolderConfiguration
  83. FolderList() []FolderConfiguration
  84. FolderPasswords(device protocol.DeviceID) map[string]string
  85. DefaultFolder() FolderConfiguration
  86. Device(id protocol.DeviceID) (DeviceConfiguration, bool)
  87. Devices() map[protocol.DeviceID]DeviceConfiguration
  88. DeviceList() []DeviceConfiguration
  89. DefaultDevice() DeviceConfiguration
  90. IgnoredDevices() []ObservedDevice
  91. IgnoredDevice(id protocol.DeviceID) bool
  92. IgnoredFolder(device protocol.DeviceID, folder string) bool
  93. Subscribe(c Committer) Configuration
  94. Unsubscribe(c Committer)
  95. }
  96. type wrapper struct {
  97. cfg Configuration
  98. path string
  99. evLogger events.Logger
  100. myID protocol.DeviceID
  101. queue chan modifyEntry
  102. waiter Waiter // Latest ongoing config change
  103. subs []Committer
  104. mut sync.Mutex
  105. requiresRestart uint32 // an atomic bool
  106. }
  107. // Wrap wraps an existing Configuration structure and ties it to a file on
  108. // disk.
  109. // The returned Wrapper is a suture.Service, thus needs to be started (added to
  110. // a supervisor).
  111. func Wrap(path string, cfg Configuration, myID protocol.DeviceID, evLogger events.Logger) Wrapper {
  112. w := &wrapper{
  113. cfg: cfg,
  114. path: path,
  115. evLogger: evLogger,
  116. myID: myID,
  117. queue: make(chan modifyEntry, maxModifications),
  118. waiter: noopWaiter{}, // Noop until first config change
  119. mut: sync.NewMutex(),
  120. }
  121. return w
  122. }
  123. // Load loads an existing file on disk and returns a new configuration
  124. // wrapper.
  125. // The returned Wrapper is a suture.Service, thus needs to be started (added to
  126. // a supervisor).
  127. func Load(path string, myID protocol.DeviceID, evLogger events.Logger) (Wrapper, int, error) {
  128. fd, err := os.Open(path)
  129. if err != nil {
  130. return nil, 0, err
  131. }
  132. defer fd.Close()
  133. cfg, originalVersion, err := ReadXML(fd, myID)
  134. if err != nil {
  135. return nil, 0, err
  136. }
  137. return Wrap(path, cfg, myID, evLogger), originalVersion, nil
  138. }
  139. func (w *wrapper) ConfigPath() string {
  140. return w.path
  141. }
  142. func (w *wrapper) MyID() protocol.DeviceID {
  143. return w.myID
  144. }
  145. // Subscribe registers the given handler to be called on any future
  146. // configuration changes. It returns the config that is in effect while
  147. // subscribing, that can be used for initial setup.
  148. func (w *wrapper) Subscribe(c Committer) Configuration {
  149. w.mut.Lock()
  150. defer w.mut.Unlock()
  151. w.subs = append(w.subs, c)
  152. return w.cfg.Copy()
  153. }
  154. // Unsubscribe de-registers the given handler from any future calls to
  155. // configuration changes and only returns after a potential ongoing config
  156. // change is done.
  157. func (w *wrapper) Unsubscribe(c Committer) {
  158. w.mut.Lock()
  159. for i := range w.subs {
  160. if w.subs[i] == c {
  161. copy(w.subs[i:], w.subs[i+1:])
  162. w.subs[len(w.subs)-1] = nil
  163. w.subs = w.subs[:len(w.subs)-1]
  164. break
  165. }
  166. }
  167. waiter := w.waiter
  168. w.mut.Unlock()
  169. // Waiting mustn't be done under lock, as the goroutines in notifyListener
  170. // may dead-lock when trying to access lock on config read operations.
  171. waiter.Wait()
  172. }
  173. // RawCopy returns a copy of the currently wrapped Configuration object.
  174. func (w *wrapper) RawCopy() Configuration {
  175. w.mut.Lock()
  176. defer w.mut.Unlock()
  177. return w.cfg.Copy()
  178. }
  179. func (w *wrapper) Modify(fn ModifyFunction) (Waiter, error) {
  180. return w.modifyQueued(fn)
  181. }
  182. func (w *wrapper) modifyQueued(modifyFunc ModifyFunction) (Waiter, error) {
  183. e := modifyEntry{
  184. modifyFunc: modifyFunc,
  185. res: make(chan modifyResult),
  186. }
  187. select {
  188. case w.queue <- e:
  189. default:
  190. return noopWaiter{}, errTooManyModifications
  191. }
  192. res := <-e.res
  193. return res.w, res.err
  194. }
  195. func (w *wrapper) Serve(ctx context.Context) error {
  196. defer w.serveSave()
  197. var e modifyEntry
  198. saveTimer := time.NewTimer(0)
  199. <-saveTimer.C
  200. saveTimerRunning := false
  201. for {
  202. select {
  203. case e = <-w.queue:
  204. case <-saveTimer.C:
  205. w.serveSave()
  206. saveTimerRunning = false
  207. continue
  208. case <-ctx.Done():
  209. return ctx.Err()
  210. }
  211. var waiter Waiter = noopWaiter{}
  212. var err error
  213. // Let the caller modify the config.
  214. to := w.RawCopy()
  215. e.modifyFunc(&to)
  216. // Check if the config was actually changed at all.
  217. w.mut.Lock()
  218. if !reflect.DeepEqual(w.cfg, to) {
  219. waiter, err = w.replaceLocked(to)
  220. if !saveTimerRunning {
  221. saveTimer.Reset(minSaveInterval)
  222. saveTimerRunning = true
  223. }
  224. }
  225. w.mut.Unlock()
  226. e.res <- modifyResult{
  227. w: waiter,
  228. err: err,
  229. }
  230. // Wait for all subscriber to handle the config change before continuing
  231. // to process the next change.
  232. done := make(chan struct{})
  233. go func() {
  234. waiter.Wait()
  235. close(done)
  236. }()
  237. select {
  238. case <-done:
  239. case <-ctx.Done():
  240. return ctx.Err()
  241. }
  242. }
  243. }
  244. func (w *wrapper) serveSave() {
  245. if err := w.Save(); err != nil {
  246. l.Warnln("Failed to save config:", err)
  247. }
  248. }
  249. func (w *wrapper) replaceLocked(to Configuration) (Waiter, error) {
  250. from := w.cfg
  251. if err := to.prepare(w.myID); err != nil {
  252. return noopWaiter{}, err
  253. }
  254. for _, sub := range w.subs {
  255. l.Debugln(sub, "verifying configuration")
  256. if err := sub.VerifyConfiguration(from.Copy(), to.Copy()); err != nil {
  257. l.Debugln(sub, "rejected config:", err)
  258. return noopWaiter{}, err
  259. }
  260. }
  261. w.cfg = to
  262. w.waiter = w.notifyListeners(from.Copy(), to.Copy())
  263. return w.waiter, nil
  264. }
  265. func (w *wrapper) notifyListeners(from, to Configuration) Waiter {
  266. wg := sync.NewWaitGroup()
  267. wg.Add(len(w.subs))
  268. for _, sub := range w.subs {
  269. go func(commiter Committer) {
  270. w.notifyListener(commiter, from, to)
  271. wg.Done()
  272. }(sub)
  273. }
  274. return wg
  275. }
  276. func (w *wrapper) notifyListener(sub Committer, from, to Configuration) {
  277. l.Debugln(sub, "committing configuration")
  278. if !sub.CommitConfiguration(from, to) {
  279. l.Debugln(sub, "requires restart")
  280. w.setRequiresRestart()
  281. }
  282. }
  283. // Devices returns a map of devices.
  284. func (w *wrapper) Devices() map[protocol.DeviceID]DeviceConfiguration {
  285. w.mut.Lock()
  286. defer w.mut.Unlock()
  287. deviceMap := make(map[protocol.DeviceID]DeviceConfiguration, len(w.cfg.Devices))
  288. for _, dev := range w.cfg.Devices {
  289. deviceMap[dev.DeviceID] = dev.Copy()
  290. }
  291. return deviceMap
  292. }
  293. // DeviceList returns a slice of devices.
  294. func (w *wrapper) DeviceList() []DeviceConfiguration {
  295. w.mut.Lock()
  296. defer w.mut.Unlock()
  297. return w.cfg.Copy().Devices
  298. }
  299. // RemoveDevice removes the device from the configuration
  300. func (w *wrapper) RemoveDevice(id protocol.DeviceID) (Waiter, error) {
  301. return w.modifyQueued(func(cfg *Configuration) {
  302. if _, i, ok := cfg.Device(id); ok {
  303. cfg.Devices = append(cfg.Devices[:i], cfg.Devices[i+1:]...)
  304. }
  305. })
  306. }
  307. func (w *wrapper) DefaultDevice() DeviceConfiguration {
  308. w.mut.Lock()
  309. defer w.mut.Unlock()
  310. return w.cfg.Defaults.Device.Copy()
  311. }
  312. // Folders returns a map of folders.
  313. func (w *wrapper) Folders() map[string]FolderConfiguration {
  314. w.mut.Lock()
  315. defer w.mut.Unlock()
  316. folderMap := make(map[string]FolderConfiguration, len(w.cfg.Folders))
  317. for _, fld := range w.cfg.Folders {
  318. folderMap[fld.ID] = fld.Copy()
  319. }
  320. return folderMap
  321. }
  322. // FolderList returns a slice of folders.
  323. func (w *wrapper) FolderList() []FolderConfiguration {
  324. w.mut.Lock()
  325. defer w.mut.Unlock()
  326. return w.cfg.Copy().Folders
  327. }
  328. // RemoveFolder removes the folder from the configuration
  329. func (w *wrapper) RemoveFolder(id string) (Waiter, error) {
  330. return w.modifyQueued(func(cfg *Configuration) {
  331. if _, i, ok := cfg.Folder(id); ok {
  332. cfg.Folders = append(cfg.Folders[:i], cfg.Folders[i+1:]...)
  333. }
  334. })
  335. }
  336. // FolderPasswords returns the folder passwords set for this device, for
  337. // folders that have an encryption password set.
  338. func (w *wrapper) FolderPasswords(device protocol.DeviceID) map[string]string {
  339. w.mut.Lock()
  340. defer w.mut.Unlock()
  341. return w.cfg.FolderPasswords(device)
  342. }
  343. func (w *wrapper) DefaultFolder() FolderConfiguration {
  344. w.mut.Lock()
  345. defer w.mut.Unlock()
  346. return w.cfg.Defaults.Folder.Copy()
  347. }
  348. // Options returns the current options configuration object.
  349. func (w *wrapper) Options() OptionsConfiguration {
  350. w.mut.Lock()
  351. defer w.mut.Unlock()
  352. return w.cfg.Options.Copy()
  353. }
  354. func (w *wrapper) LDAP() LDAPConfiguration {
  355. w.mut.Lock()
  356. defer w.mut.Unlock()
  357. return w.cfg.LDAP.Copy()
  358. }
  359. // GUI returns the current GUI configuration object.
  360. func (w *wrapper) GUI() GUIConfiguration {
  361. w.mut.Lock()
  362. defer w.mut.Unlock()
  363. return w.cfg.GUI.Copy()
  364. }
  365. // IgnoredDevice returns whether or not connection attempts from the given
  366. // device should be silently ignored.
  367. func (w *wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  368. w.mut.Lock()
  369. defer w.mut.Unlock()
  370. for _, device := range w.cfg.IgnoredDevices {
  371. if device.ID == id {
  372. return true
  373. }
  374. }
  375. return false
  376. }
  377. // IgnoredDevices returns a slice of ignored devices.
  378. func (w *wrapper) IgnoredDevices() []ObservedDevice {
  379. w.mut.Lock()
  380. defer w.mut.Unlock()
  381. res := make([]ObservedDevice, len(w.cfg.IgnoredDevices))
  382. copy(res, w.cfg.IgnoredDevices)
  383. return res
  384. }
  385. // IgnoredFolder returns whether or not share attempts for the given
  386. // folder should be silently ignored.
  387. func (w *wrapper) IgnoredFolder(device protocol.DeviceID, folder string) bool {
  388. dev, ok := w.Device(device)
  389. if !ok {
  390. return false
  391. }
  392. return dev.IgnoredFolder(folder)
  393. }
  394. // Device returns the configuration for the given device and an "ok" bool.
  395. func (w *wrapper) Device(id protocol.DeviceID) (DeviceConfiguration, bool) {
  396. w.mut.Lock()
  397. defer w.mut.Unlock()
  398. device, _, ok := w.cfg.Device(id)
  399. if !ok {
  400. return DeviceConfiguration{}, false
  401. }
  402. return device.Copy(), ok
  403. }
  404. // Folder returns the configuration for the given folder and an "ok" bool.
  405. func (w *wrapper) Folder(id string) (FolderConfiguration, bool) {
  406. w.mut.Lock()
  407. defer w.mut.Unlock()
  408. fcfg, _, ok := w.cfg.Folder(id)
  409. if !ok {
  410. return FolderConfiguration{}, false
  411. }
  412. return fcfg.Copy(), ok
  413. }
  414. // Save writes the configuration to disk, and generates a ConfigSaved event.
  415. func (w *wrapper) Save() error {
  416. w.mut.Lock()
  417. defer w.mut.Unlock()
  418. fd, err := osutil.CreateAtomic(w.path)
  419. if err != nil {
  420. l.Debugln("CreateAtomic:", err)
  421. return err
  422. }
  423. if err := w.cfg.WriteXML(fd); err != nil {
  424. l.Debugln("WriteXML:", err)
  425. fd.Close()
  426. return err
  427. }
  428. if err := fd.Close(); err != nil {
  429. l.Debugln("Close:", err)
  430. return err
  431. }
  432. w.evLogger.Log(events.ConfigSaved, w.cfg)
  433. return nil
  434. }
  435. func (w *wrapper) RequiresRestart() bool {
  436. return atomic.LoadUint32(&w.requiresRestart) != 0
  437. }
  438. func (w *wrapper) setRequiresRestart() {
  439. atomic.StoreUint32(&w.requiresRestart, 1)
  440. }
  441. type modifyEntry struct {
  442. modifyFunc ModifyFunction
  443. res chan modifyResult
  444. }
  445. type modifyResult struct {
  446. w Waiter
  447. err error
  448. }