wrapper.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. package config
  7. import (
  8. "os"
  9. "sync/atomic"
  10. "time"
  11. "github.com/syncthing/syncthing/lib/events"
  12. "github.com/syncthing/syncthing/lib/osutil"
  13. "github.com/syncthing/syncthing/lib/protocol"
  14. "github.com/syncthing/syncthing/lib/sync"
  15. )
  16. // The Committer interface is implemented by objects that need to know about
  17. // or have a say in configuration changes.
  18. //
  19. // When the configuration is about to be changed, VerifyConfiguration() is
  20. // called for each subscribing object, with the old and new configuration. A
  21. // nil error is returned if the new configuration is acceptable (i.e. does not
  22. // contain any errors that would prevent it from being a valid config).
  23. // Otherwise an error describing the problem is returned.
  24. //
  25. // If any subscriber returns an error from VerifyConfiguration(), the
  26. // configuration change is not committed and an error is returned to whoever
  27. // tried to commit the broken config.
  28. //
  29. // If all verification calls returns nil, CommitConfiguration() is called for
  30. // each subscribing object. The callee returns true if the new configuration
  31. // has been successfully applied, otherwise false. Any Commit() call returning
  32. // false will result in a "restart needed" response to the API/user. Note that
  33. // the new configuration will still have been applied by those who were
  34. // capable of doing so.
  35. type Committer interface {
  36. VerifyConfiguration(from, to Configuration) error
  37. CommitConfiguration(from, to Configuration) (handled bool)
  38. String() string
  39. }
  40. // Waiter allows to wait for the given config operation to complete.
  41. type Waiter interface {
  42. Wait()
  43. }
  44. type noopWaiter struct{}
  45. func (noopWaiter) Wait() {}
  46. // A Wrapper around a Configuration that manages loads, saves and published
  47. // notifications of changes to registered Handlers
  48. type Wrapper interface {
  49. ConfigPath() string
  50. RawCopy() Configuration
  51. Replace(cfg Configuration) (Waiter, error)
  52. RequiresRestart() bool
  53. Save() error
  54. GUI() GUIConfiguration
  55. SetGUI(gui GUIConfiguration) (Waiter, error)
  56. LDAP() LDAPConfiguration
  57. Options() OptionsConfiguration
  58. SetOptions(opts OptionsConfiguration) (Waiter, error)
  59. Folder(id string) (FolderConfiguration, bool)
  60. Folders() map[string]FolderConfiguration
  61. FolderList() []FolderConfiguration
  62. SetFolder(fld FolderConfiguration) (Waiter, error)
  63. SetFolders(folders []FolderConfiguration) (Waiter, error)
  64. Device(id protocol.DeviceID) (DeviceConfiguration, bool)
  65. Devices() map[protocol.DeviceID]DeviceConfiguration
  66. RemoveDevice(id protocol.DeviceID) (Waiter, error)
  67. SetDevice(DeviceConfiguration) (Waiter, error)
  68. SetDevices([]DeviceConfiguration) (Waiter, error)
  69. AddOrUpdatePendingDevice(device protocol.DeviceID, name, address string)
  70. AddOrUpdatePendingFolder(id, label string, device protocol.DeviceID)
  71. IgnoredDevice(id protocol.DeviceID) bool
  72. IgnoredFolder(device protocol.DeviceID, folder string) bool
  73. Subscribe(c Committer)
  74. Unsubscribe(c Committer)
  75. }
  76. type wrapper struct {
  77. cfg Configuration
  78. path string
  79. evLogger events.Logger
  80. waiter Waiter // Latest ongoing config change
  81. subs []Committer
  82. mut sync.Mutex
  83. requiresRestart uint32 // an atomic bool
  84. }
  85. // Wrap wraps an existing Configuration structure and ties it to a file on
  86. // disk.
  87. func Wrap(path string, cfg Configuration, evLogger events.Logger) Wrapper {
  88. w := &wrapper{
  89. cfg: cfg,
  90. path: path,
  91. evLogger: evLogger,
  92. waiter: noopWaiter{}, // Noop until first config change
  93. mut: sync.NewMutex(),
  94. }
  95. return w
  96. }
  97. // Load loads an existing file on disk and returns a new configuration
  98. // wrapper.
  99. func Load(path string, myID protocol.DeviceID, evLogger events.Logger) (Wrapper, int, error) {
  100. fd, err := os.Open(path)
  101. if err != nil {
  102. return nil, 0, err
  103. }
  104. defer fd.Close()
  105. cfg, originalVersion, err := ReadXML(fd, myID)
  106. if err != nil {
  107. return nil, 0, err
  108. }
  109. return Wrap(path, cfg, evLogger), originalVersion, nil
  110. }
  111. func (w *wrapper) ConfigPath() string {
  112. return w.path
  113. }
  114. // Subscribe registers the given handler to be called on any future
  115. // configuration changes.
  116. func (w *wrapper) Subscribe(c Committer) {
  117. w.mut.Lock()
  118. w.subs = append(w.subs, c)
  119. w.mut.Unlock()
  120. }
  121. // Unsubscribe de-registers the given handler from any future calls to
  122. // configuration changes and only returns after a potential ongoing config
  123. // change is done.
  124. func (w *wrapper) Unsubscribe(c Committer) {
  125. w.mut.Lock()
  126. for i := range w.subs {
  127. if w.subs[i] == c {
  128. copy(w.subs[i:], w.subs[i+1:])
  129. w.subs[len(w.subs)-1] = nil
  130. w.subs = w.subs[:len(w.subs)-1]
  131. break
  132. }
  133. }
  134. waiter := w.waiter
  135. w.mut.Unlock()
  136. // Waiting mustn't be done under lock, as the goroutines in notifyListener
  137. // may dead-lock when trying to access lock on config read operations.
  138. waiter.Wait()
  139. }
  140. // RawCopy returns a copy of the currently wrapped Configuration object.
  141. func (w *wrapper) RawCopy() Configuration {
  142. w.mut.Lock()
  143. defer w.mut.Unlock()
  144. return w.cfg.Copy()
  145. }
  146. // Replace swaps the current configuration object for the given one.
  147. func (w *wrapper) Replace(cfg Configuration) (Waiter, error) {
  148. w.mut.Lock()
  149. defer w.mut.Unlock()
  150. return w.replaceLocked(cfg.Copy())
  151. }
  152. func (w *wrapper) replaceLocked(to Configuration) (Waiter, error) {
  153. from := w.cfg
  154. if err := to.clean(); err != nil {
  155. return noopWaiter{}, err
  156. }
  157. for _, sub := range w.subs {
  158. l.Debugln(sub, "verifying configuration")
  159. if err := sub.VerifyConfiguration(from.Copy(), to.Copy()); err != nil {
  160. l.Debugln(sub, "rejected config:", err)
  161. return noopWaiter{}, err
  162. }
  163. }
  164. w.cfg = to
  165. w.waiter = w.notifyListeners(from.Copy(), to.Copy())
  166. return w.waiter, nil
  167. }
  168. func (w *wrapper) notifyListeners(from, to Configuration) Waiter {
  169. wg := sync.NewWaitGroup()
  170. wg.Add(len(w.subs))
  171. for _, sub := range w.subs {
  172. go func(commiter Committer) {
  173. w.notifyListener(commiter, from, to)
  174. wg.Done()
  175. }(sub)
  176. }
  177. return wg
  178. }
  179. func (w *wrapper) notifyListener(sub Committer, from, to Configuration) {
  180. l.Debugln(sub, "committing configuration")
  181. if !sub.CommitConfiguration(from, to) {
  182. l.Debugln(sub, "requires restart")
  183. w.setRequiresRestart()
  184. }
  185. }
  186. // Devices returns a map of devices.
  187. func (w *wrapper) Devices() map[protocol.DeviceID]DeviceConfiguration {
  188. w.mut.Lock()
  189. defer w.mut.Unlock()
  190. deviceMap := make(map[protocol.DeviceID]DeviceConfiguration, len(w.cfg.Devices))
  191. for _, dev := range w.cfg.Devices {
  192. deviceMap[dev.DeviceID] = dev.Copy()
  193. }
  194. return deviceMap
  195. }
  196. // SetDevices adds new devices to the configuration, or overwrites existing
  197. // devices with the same ID.
  198. func (w *wrapper) SetDevices(devs []DeviceConfiguration) (Waiter, error) {
  199. w.mut.Lock()
  200. defer w.mut.Unlock()
  201. newCfg := w.cfg.Copy()
  202. var replaced bool
  203. for oldIndex := range devs {
  204. replaced = false
  205. for newIndex := range newCfg.Devices {
  206. if newCfg.Devices[newIndex].DeviceID == devs[oldIndex].DeviceID {
  207. newCfg.Devices[newIndex] = devs[oldIndex].Copy()
  208. replaced = true
  209. break
  210. }
  211. }
  212. if !replaced {
  213. newCfg.Devices = append(newCfg.Devices, devs[oldIndex].Copy())
  214. }
  215. }
  216. return w.replaceLocked(newCfg)
  217. }
  218. // SetDevice adds a new device to the configuration, or overwrites an existing
  219. // device with the same ID.
  220. func (w *wrapper) SetDevice(dev DeviceConfiguration) (Waiter, error) {
  221. return w.SetDevices([]DeviceConfiguration{dev})
  222. }
  223. // RemoveDevice removes the device from the configuration
  224. func (w *wrapper) RemoveDevice(id protocol.DeviceID) (Waiter, error) {
  225. w.mut.Lock()
  226. defer w.mut.Unlock()
  227. newCfg := w.cfg.Copy()
  228. for i := range newCfg.Devices {
  229. if newCfg.Devices[i].DeviceID == id {
  230. newCfg.Devices = append(newCfg.Devices[:i], newCfg.Devices[i+1:]...)
  231. return w.replaceLocked(newCfg)
  232. }
  233. }
  234. return noopWaiter{}, nil
  235. }
  236. // Folders returns a map of folders. Folder structures should not be changed,
  237. // other than for the purpose of updating via SetFolder().
  238. func (w *wrapper) Folders() map[string]FolderConfiguration {
  239. w.mut.Lock()
  240. defer w.mut.Unlock()
  241. folderMap := make(map[string]FolderConfiguration, len(w.cfg.Folders))
  242. for _, fld := range w.cfg.Folders {
  243. folderMap[fld.ID] = fld.Copy()
  244. }
  245. return folderMap
  246. }
  247. // FolderList returns a slice of folders.
  248. func (w *wrapper) FolderList() []FolderConfiguration {
  249. w.mut.Lock()
  250. defer w.mut.Unlock()
  251. return w.cfg.Copy().Folders
  252. }
  253. // SetFolder adds a new folder to the configuration, or overwrites an existing
  254. // folder with the same ID.
  255. func (w *wrapper) SetFolder(fld FolderConfiguration) (Waiter, error) {
  256. return w.SetFolders([]FolderConfiguration{fld})
  257. }
  258. // SetFolders adds new folders to the configuration, or overwrites existing
  259. // folders with the same ID.
  260. func (w *wrapper) SetFolders(folders []FolderConfiguration) (Waiter, error) {
  261. w.mut.Lock()
  262. defer w.mut.Unlock()
  263. newCfg := w.cfg.Copy()
  264. inds := make(map[string]int, len(w.cfg.Folders))
  265. for i, folder := range newCfg.Folders {
  266. inds[folder.ID] = i
  267. }
  268. filtered := folders[:0]
  269. for _, folder := range folders {
  270. if i, ok := inds[folder.ID]; ok {
  271. newCfg.Folders[i] = folder
  272. } else {
  273. filtered = append(filtered, folder)
  274. }
  275. }
  276. newCfg.Folders = append(newCfg.Folders, filtered...)
  277. return w.replaceLocked(newCfg)
  278. }
  279. // Options returns the current options configuration object.
  280. func (w *wrapper) Options() OptionsConfiguration {
  281. w.mut.Lock()
  282. defer w.mut.Unlock()
  283. return w.cfg.Options.Copy()
  284. }
  285. // SetOptions replaces the current options configuration object.
  286. func (w *wrapper) SetOptions(opts OptionsConfiguration) (Waiter, error) {
  287. w.mut.Lock()
  288. defer w.mut.Unlock()
  289. newCfg := w.cfg.Copy()
  290. newCfg.Options = opts.Copy()
  291. return w.replaceLocked(newCfg)
  292. }
  293. func (w *wrapper) LDAP() LDAPConfiguration {
  294. w.mut.Lock()
  295. defer w.mut.Unlock()
  296. return w.cfg.LDAP.Copy()
  297. }
  298. // GUI returns the current GUI configuration object.
  299. func (w *wrapper) GUI() GUIConfiguration {
  300. w.mut.Lock()
  301. defer w.mut.Unlock()
  302. return w.cfg.GUI.Copy()
  303. }
  304. // SetGUI replaces the current GUI configuration object.
  305. func (w *wrapper) SetGUI(gui GUIConfiguration) (Waiter, error) {
  306. w.mut.Lock()
  307. defer w.mut.Unlock()
  308. newCfg := w.cfg.Copy()
  309. newCfg.GUI = gui.Copy()
  310. return w.replaceLocked(newCfg)
  311. }
  312. // IgnoredDevice returns whether or not connection attempts from the given
  313. // device should be silently ignored.
  314. func (w *wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  315. w.mut.Lock()
  316. defer w.mut.Unlock()
  317. for _, device := range w.cfg.IgnoredDevices {
  318. if device.ID == id {
  319. return true
  320. }
  321. }
  322. return false
  323. }
  324. // IgnoredFolder returns whether or not share attempts for the given
  325. // folder should be silently ignored.
  326. func (w *wrapper) IgnoredFolder(device protocol.DeviceID, folder string) bool {
  327. dev, ok := w.Device(device)
  328. if !ok {
  329. return false
  330. }
  331. return dev.IgnoredFolder(folder)
  332. }
  333. // Device returns the configuration for the given device and an "ok" bool.
  334. func (w *wrapper) Device(id protocol.DeviceID) (DeviceConfiguration, bool) {
  335. w.mut.Lock()
  336. defer w.mut.Unlock()
  337. for _, device := range w.cfg.Devices {
  338. if device.DeviceID == id {
  339. return device.Copy(), true
  340. }
  341. }
  342. return DeviceConfiguration{}, false
  343. }
  344. // Folder returns the configuration for the given folder and an "ok" bool.
  345. func (w *wrapper) Folder(id string) (FolderConfiguration, bool) {
  346. w.mut.Lock()
  347. defer w.mut.Unlock()
  348. for _, folder := range w.cfg.Folders {
  349. if folder.ID == id {
  350. return folder.Copy(), true
  351. }
  352. }
  353. return FolderConfiguration{}, false
  354. }
  355. // Save writes the configuration to disk, and generates a ConfigSaved event.
  356. func (w *wrapper) Save() error {
  357. w.mut.Lock()
  358. defer w.mut.Unlock()
  359. fd, err := osutil.CreateAtomic(w.path)
  360. if err != nil {
  361. l.Debugln("CreateAtomic:", err)
  362. return err
  363. }
  364. if err := w.cfg.WriteXML(fd); err != nil {
  365. l.Debugln("WriteXML:", err)
  366. fd.Close()
  367. return err
  368. }
  369. if err := fd.Close(); err != nil {
  370. l.Debugln("Close:", err)
  371. return err
  372. }
  373. w.evLogger.Log(events.ConfigSaved, w.cfg)
  374. return nil
  375. }
  376. func (w *wrapper) RequiresRestart() bool {
  377. return atomic.LoadUint32(&w.requiresRestart) != 0
  378. }
  379. func (w *wrapper) setRequiresRestart() {
  380. atomic.StoreUint32(&w.requiresRestart, 1)
  381. }
  382. func (w *wrapper) AddOrUpdatePendingDevice(device protocol.DeviceID, name, address string) {
  383. w.mut.Lock()
  384. defer w.mut.Unlock()
  385. for i := range w.cfg.PendingDevices {
  386. if w.cfg.PendingDevices[i].ID == device {
  387. w.cfg.PendingDevices[i].Time = time.Now().Round(time.Second)
  388. w.cfg.PendingDevices[i].Name = name
  389. w.cfg.PendingDevices[i].Address = address
  390. return
  391. }
  392. }
  393. w.cfg.PendingDevices = append(w.cfg.PendingDevices, ObservedDevice{
  394. Time: time.Now().Round(time.Second),
  395. ID: device,
  396. Name: name,
  397. Address: address,
  398. })
  399. }
  400. func (w *wrapper) AddOrUpdatePendingFolder(id, label string, device protocol.DeviceID) {
  401. w.mut.Lock()
  402. defer w.mut.Unlock()
  403. for i := range w.cfg.Devices {
  404. if w.cfg.Devices[i].DeviceID == device {
  405. for j := range w.cfg.Devices[i].PendingFolders {
  406. if w.cfg.Devices[i].PendingFolders[j].ID == id {
  407. w.cfg.Devices[i].PendingFolders[j].Label = label
  408. w.cfg.Devices[i].PendingFolders[j].Time = time.Now().Round(time.Second)
  409. return
  410. }
  411. }
  412. w.cfg.Devices[i].PendingFolders = append(w.cfg.Devices[i].PendingFolders, ObservedFolder{
  413. Time: time.Now().Round(time.Second),
  414. ID: id,
  415. Label: label,
  416. })
  417. return
  418. }
  419. }
  420. panic("bug: adding pending folder for non-existing device")
  421. }