wrapper.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. "github.com/syncthing/syncthing/lib/events"
  11. "github.com/syncthing/syncthing/lib/osutil"
  12. "github.com/syncthing/syncthing/lib/protocol"
  13. "github.com/syncthing/syncthing/lib/sync"
  14. "github.com/syncthing/syncthing/lib/util"
  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. // A wrapper around a Configuration that manages loads, saves and published
  41. // notifications of changes to registered Handlers
  42. type Wrapper struct {
  43. cfg Configuration
  44. path string
  45. deviceMap map[protocol.DeviceID]DeviceConfiguration
  46. folderMap map[string]FolderConfiguration
  47. replaces chan Configuration
  48. subs []Committer
  49. mut sync.Mutex
  50. requiresRestart uint32 // an atomic bool
  51. }
  52. // Wrap wraps an existing Configuration structure and ties it to a file on
  53. // disk.
  54. func Wrap(path string, cfg Configuration) *Wrapper {
  55. w := &Wrapper{
  56. cfg: cfg,
  57. path: path,
  58. mut: sync.NewMutex(),
  59. }
  60. w.replaces = make(chan Configuration)
  61. return w
  62. }
  63. // Load loads an existing file on disk and returns a new configuration
  64. // wrapper.
  65. func Load(path string, myID protocol.DeviceID) (*Wrapper, error) {
  66. fd, err := os.Open(path)
  67. if err != nil {
  68. return nil, err
  69. }
  70. defer fd.Close()
  71. cfg, err := ReadXML(fd, myID)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return Wrap(path, cfg), nil
  76. }
  77. func (w *Wrapper) ConfigPath() string {
  78. return w.path
  79. }
  80. // Stop stops the Serve() loop. Set and Replace operations will panic after a
  81. // Stop.
  82. func (w *Wrapper) Stop() {
  83. close(w.replaces)
  84. }
  85. // Subscribe registers the given handler to be called on any future
  86. // configuration changes.
  87. func (w *Wrapper) Subscribe(c Committer) {
  88. w.mut.Lock()
  89. w.subs = append(w.subs, c)
  90. w.mut.Unlock()
  91. }
  92. // Unsubscribe de-registers the given handler from any future calls to
  93. // configuration changes
  94. func (w *Wrapper) Unsubscribe(c Committer) {
  95. w.mut.Lock()
  96. for i := range w.subs {
  97. if w.subs[i] == c {
  98. copy(w.subs[i:], w.subs[i+1:])
  99. w.subs[len(w.subs)-1] = nil
  100. w.subs = w.subs[:len(w.subs)-1]
  101. break
  102. }
  103. }
  104. w.mut.Unlock()
  105. }
  106. // RawCopy returns a copy of the currently wrapped Configuration object.
  107. func (w *Wrapper) RawCopy() Configuration {
  108. w.mut.Lock()
  109. defer w.mut.Unlock()
  110. return w.cfg.Copy()
  111. }
  112. // Replace swaps the current configuration object for the given one.
  113. func (w *Wrapper) Replace(cfg Configuration) error {
  114. w.mut.Lock()
  115. defer w.mut.Unlock()
  116. return w.replaceLocked(cfg)
  117. }
  118. func (w *Wrapper) replaceLocked(to Configuration) error {
  119. from := w.cfg
  120. if err := to.clean(); err != nil {
  121. return err
  122. }
  123. for _, sub := range w.subs {
  124. l.Debugln(sub, "verifying configuration")
  125. if err := sub.VerifyConfiguration(from, to); err != nil {
  126. l.Debugln(sub, "rejected config:", err)
  127. return err
  128. }
  129. }
  130. w.cfg = to
  131. w.deviceMap = nil
  132. w.folderMap = nil
  133. w.notifyListeners(from, to)
  134. return nil
  135. }
  136. func (w *Wrapper) notifyListeners(from, to Configuration) {
  137. for _, sub := range w.subs {
  138. go w.notifyListener(sub, from.Copy(), to.Copy())
  139. }
  140. }
  141. func (w *Wrapper) notifyListener(sub Committer, from, to Configuration) {
  142. l.Debugln(sub, "committing configuration")
  143. if !sub.CommitConfiguration(from, to) {
  144. l.Debugln(sub, "requires restart")
  145. w.setRequiresRestart()
  146. }
  147. }
  148. // Devices returns a map of devices. Device structures should not be changed,
  149. // other than for the purpose of updating via SetDevice().
  150. func (w *Wrapper) Devices() map[protocol.DeviceID]DeviceConfiguration {
  151. w.mut.Lock()
  152. defer w.mut.Unlock()
  153. if w.deviceMap == nil {
  154. w.deviceMap = make(map[protocol.DeviceID]DeviceConfiguration, len(w.cfg.Devices))
  155. for _, dev := range w.cfg.Devices {
  156. w.deviceMap[dev.DeviceID] = dev
  157. }
  158. }
  159. return w.deviceMap
  160. }
  161. // SetDevices adds new devices to the configuration, or overwrites existing
  162. // devices with the same ID.
  163. func (w *Wrapper) SetDevices(devs []DeviceConfiguration) error {
  164. w.mut.Lock()
  165. defer w.mut.Unlock()
  166. newCfg := w.cfg.Copy()
  167. var replaced bool
  168. for oldIndex := range devs {
  169. replaced = false
  170. for newIndex := range newCfg.Devices {
  171. if newCfg.Devices[newIndex].DeviceID == devs[oldIndex].DeviceID {
  172. newCfg.Devices[newIndex] = devs[oldIndex]
  173. replaced = true
  174. break
  175. }
  176. }
  177. if !replaced {
  178. newCfg.Devices = append(newCfg.Devices, devs[oldIndex])
  179. }
  180. }
  181. return w.replaceLocked(newCfg)
  182. }
  183. // SetDevice adds a new device to the configuration, or overwrites an existing
  184. // device with the same ID.
  185. func (w *Wrapper) SetDevice(dev DeviceConfiguration) error {
  186. return w.SetDevices([]DeviceConfiguration{dev})
  187. }
  188. // RemoveDevice removes the device from the configuration
  189. func (w *Wrapper) RemoveDevice(id protocol.DeviceID) error {
  190. w.mut.Lock()
  191. defer w.mut.Unlock()
  192. newCfg := w.cfg.Copy()
  193. removed := false
  194. for i := range newCfg.Devices {
  195. if newCfg.Devices[i].DeviceID == id {
  196. newCfg.Devices = append(newCfg.Devices[:i], newCfg.Devices[i+1:]...)
  197. removed = true
  198. break
  199. }
  200. }
  201. if !removed {
  202. return nil
  203. }
  204. return w.replaceLocked(newCfg)
  205. }
  206. // Folders returns a map of folders. Folder structures should not be changed,
  207. // other than for the purpose of updating via SetFolder().
  208. func (w *Wrapper) Folders() map[string]FolderConfiguration {
  209. w.mut.Lock()
  210. defer w.mut.Unlock()
  211. if w.folderMap == nil {
  212. w.folderMap = make(map[string]FolderConfiguration, len(w.cfg.Folders))
  213. for _, fld := range w.cfg.Folders {
  214. w.folderMap[fld.ID] = fld
  215. }
  216. }
  217. return w.folderMap
  218. }
  219. // SetFolder adds a new folder to the configuration, or overwrites an existing
  220. // folder with the same ID.
  221. func (w *Wrapper) SetFolder(fld FolderConfiguration) error {
  222. w.mut.Lock()
  223. defer w.mut.Unlock()
  224. newCfg := w.cfg.Copy()
  225. replaced := false
  226. for i := range newCfg.Folders {
  227. if newCfg.Folders[i].ID == fld.ID {
  228. newCfg.Folders[i] = fld
  229. replaced = true
  230. break
  231. }
  232. }
  233. if !replaced {
  234. newCfg.Folders = append(w.cfg.Folders, fld)
  235. }
  236. return w.replaceLocked(newCfg)
  237. }
  238. // Options returns the current options configuration object.
  239. func (w *Wrapper) Options() OptionsConfiguration {
  240. w.mut.Lock()
  241. defer w.mut.Unlock()
  242. return w.cfg.Options
  243. }
  244. // SetOptions replaces the current options configuration object.
  245. func (w *Wrapper) SetOptions(opts OptionsConfiguration) error {
  246. w.mut.Lock()
  247. defer w.mut.Unlock()
  248. newCfg := w.cfg.Copy()
  249. newCfg.Options = opts
  250. return w.replaceLocked(newCfg)
  251. }
  252. // GUI returns the current GUI configuration object.
  253. func (w *Wrapper) GUI() GUIConfiguration {
  254. w.mut.Lock()
  255. defer w.mut.Unlock()
  256. return w.cfg.GUI
  257. }
  258. // SetGUI replaces the current GUI configuration object.
  259. func (w *Wrapper) SetGUI(gui GUIConfiguration) error {
  260. w.mut.Lock()
  261. defer w.mut.Unlock()
  262. newCfg := w.cfg.Copy()
  263. newCfg.GUI = gui
  264. return w.replaceLocked(newCfg)
  265. }
  266. // IgnoredDevice returns whether or not connection attempts from the given
  267. // device should be silently ignored.
  268. func (w *Wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  269. w.mut.Lock()
  270. defer w.mut.Unlock()
  271. for _, device := range w.cfg.IgnoredDevices {
  272. if device == id {
  273. return true
  274. }
  275. }
  276. return false
  277. }
  278. // Device returns the configuration for the given device and an "ok" bool.
  279. func (w *Wrapper) Device(id protocol.DeviceID) (DeviceConfiguration, bool) {
  280. w.mut.Lock()
  281. defer w.mut.Unlock()
  282. for _, device := range w.cfg.Devices {
  283. if device.DeviceID == id {
  284. return device, true
  285. }
  286. }
  287. return DeviceConfiguration{}, false
  288. }
  289. // Folder returns the configuration for the given folder and an "ok" bool.
  290. func (w *Wrapper) Folder(id string) (FolderConfiguration, bool) {
  291. w.mut.Lock()
  292. defer w.mut.Unlock()
  293. for _, folder := range w.cfg.Folders {
  294. if folder.ID == id {
  295. return folder, true
  296. }
  297. }
  298. return FolderConfiguration{}, false
  299. }
  300. // Save writes the configuration to disk, and generates a ConfigSaved event.
  301. func (w *Wrapper) Save() error {
  302. fd, err := osutil.CreateAtomic(w.path)
  303. if err != nil {
  304. l.Debugln("CreateAtomic:", err)
  305. return err
  306. }
  307. if err := w.cfg.WriteXML(fd); err != nil {
  308. l.Debugln("WriteXML:", err)
  309. fd.Close()
  310. return err
  311. }
  312. if err := fd.Close(); err != nil {
  313. l.Debugln("Close:", err)
  314. return err
  315. }
  316. events.Default.Log(events.ConfigSaved, w.cfg)
  317. return nil
  318. }
  319. func (w *Wrapper) GlobalDiscoveryServers() []string {
  320. var servers []string
  321. for _, srv := range w.cfg.Options.GlobalAnnServers {
  322. switch srv {
  323. case "default":
  324. servers = append(servers, DefaultDiscoveryServers...)
  325. case "default-v4":
  326. servers = append(servers, DefaultDiscoveryServersV4...)
  327. case "default-v6":
  328. servers = append(servers, DefaultDiscoveryServersV6...)
  329. default:
  330. servers = append(servers, srv)
  331. }
  332. }
  333. return util.UniqueStrings(servers)
  334. }
  335. func (w *Wrapper) ListenAddresses() []string {
  336. var addresses []string
  337. for _, addr := range w.cfg.Options.ListenAddresses {
  338. switch addr {
  339. case "default":
  340. addresses = append(addresses, DefaultListenAddresses...)
  341. default:
  342. addresses = append(addresses, addr)
  343. }
  344. }
  345. return util.UniqueStrings(addresses)
  346. }
  347. func (w *Wrapper) RequiresRestart() bool {
  348. return atomic.LoadUint32(&w.requiresRestart) != 0
  349. }
  350. func (w *Wrapper) setRequiresRestart() {
  351. atomic.StoreUint32(&w.requiresRestart, 1)
  352. }