wrapper.go 13 KB

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