wrapper.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 http://mozilla.org/MPL/2.0/.
  6. package config
  7. import (
  8. "os"
  9. "github.com/syncthing/syncthing/lib/events"
  10. "github.com/syncthing/syncthing/lib/osutil"
  11. "github.com/syncthing/syncthing/lib/protocol"
  12. "github.com/syncthing/syncthing/lib/sync"
  13. "github.com/syncthing/syncthing/lib/util"
  14. )
  15. // The Committer interface is implemented by objects that need to know about
  16. // or have a say in configuration changes.
  17. //
  18. // When the configuration is about to be changed, VerifyConfiguration() is
  19. // called for each subscribing object, with the old and new configuration. A
  20. // nil error is returned if the new configuration is acceptable (i.e. does not
  21. // contain any errors that would prevent it from being a valid config).
  22. // Otherwise an error describing the problem is returned.
  23. //
  24. // If any subscriber returns an error from VerifyConfiguration(), the
  25. // configuration change is not committed and an error is returned to whoever
  26. // tried to commit the broken config.
  27. //
  28. // If all verification calls returns nil, CommitConfiguration() is called for
  29. // each subscribing object. The callee returns true if the new configuration
  30. // has been successfully applied, otherwise false. Any Commit() call returning
  31. // false will result in a "restart needed" response to the API/user. Note that
  32. // the new configuration will still have been applied by those who were
  33. // capable of doing so.
  34. type Committer interface {
  35. VerifyConfiguration(from, to Configuration) error
  36. CommitConfiguration(from, to Configuration) (handled bool)
  37. String() string
  38. }
  39. type CommitResponse struct {
  40. ValidationError error
  41. RequiresRestart bool
  42. }
  43. var ResponseNoRestart = CommitResponse{
  44. ValidationError: nil,
  45. RequiresRestart: false,
  46. }
  47. // A wrapper around a Configuration that manages loads, saves and published
  48. // notifications of changes to registered Handlers
  49. type Wrapper struct {
  50. cfg Configuration
  51. path string
  52. deviceMap map[protocol.DeviceID]DeviceConfiguration
  53. folderMap map[string]FolderConfiguration
  54. replaces chan Configuration
  55. subs []Committer
  56. mut sync.Mutex
  57. }
  58. // Wrap wraps an existing Configuration structure and ties it to a file on
  59. // disk.
  60. func Wrap(path string, cfg Configuration) *Wrapper {
  61. w := &Wrapper{
  62. cfg: cfg,
  63. path: path,
  64. mut: sync.NewMutex(),
  65. }
  66. w.replaces = make(chan Configuration)
  67. return w
  68. }
  69. // Load loads an existing file on disk and returns a new configuration
  70. // wrapper.
  71. func Load(path string, myID protocol.DeviceID) (*Wrapper, error) {
  72. fd, err := os.Open(path)
  73. if err != nil {
  74. return nil, err
  75. }
  76. defer fd.Close()
  77. cfg, err := ReadXML(fd, myID)
  78. if err != nil {
  79. return nil, err
  80. }
  81. return Wrap(path, cfg), nil
  82. }
  83. func (w *Wrapper) ConfigPath() string {
  84. return w.path
  85. }
  86. // Stop stops the Serve() loop. Set and Replace operations will panic after a
  87. // Stop.
  88. func (w *Wrapper) Stop() {
  89. close(w.replaces)
  90. }
  91. // Subscribe registers the given handler to be called on any future
  92. // configuration changes.
  93. func (w *Wrapper) Subscribe(c Committer) {
  94. w.mut.Lock()
  95. w.subs = append(w.subs, c)
  96. w.mut.Unlock()
  97. }
  98. // Unsubscribe de-registers the given handler from any future calls to
  99. // configuration changes
  100. func (w *Wrapper) Unsubscribe(c Committer) {
  101. w.mut.Lock()
  102. for i := range w.subs {
  103. if w.subs[i] == c {
  104. copy(w.subs[i:], w.subs[i+1:])
  105. w.subs[len(w.subs)-1] = nil
  106. w.subs = w.subs[:len(w.subs)-1]
  107. break
  108. }
  109. }
  110. w.mut.Unlock()
  111. }
  112. // Raw returns the currently wrapped Configuration object.
  113. func (w *Wrapper) Raw() Configuration {
  114. return w.cfg
  115. }
  116. // Replace swaps the current configuration object for the given one.
  117. func (w *Wrapper) Replace(cfg Configuration) CommitResponse {
  118. w.mut.Lock()
  119. defer w.mut.Unlock()
  120. return w.replaceLocked(cfg)
  121. }
  122. func (w *Wrapper) replaceLocked(to Configuration) CommitResponse {
  123. from := w.cfg
  124. for _, sub := range w.subs {
  125. l.Debugln(sub, "verifying configuration")
  126. if err := sub.VerifyConfiguration(from, to); err != nil {
  127. l.Debugln(sub, "rejected config:", err)
  128. return CommitResponse{
  129. ValidationError: err,
  130. }
  131. }
  132. }
  133. allOk := true
  134. for _, sub := range w.subs {
  135. l.Debugln(sub, "committing configuration")
  136. ok := sub.CommitConfiguration(from, to)
  137. if !ok {
  138. l.Debugln(sub, "requires restart")
  139. allOk = false
  140. }
  141. }
  142. w.cfg = to
  143. w.deviceMap = nil
  144. w.folderMap = nil
  145. return CommitResponse{
  146. RequiresRestart: !allOk,
  147. }
  148. }
  149. // Devices returns a map of devices. Device structures should not be changed,
  150. // other than for the purpose of updating via SetDevice().
  151. func (w *Wrapper) Devices() map[protocol.DeviceID]DeviceConfiguration {
  152. w.mut.Lock()
  153. defer w.mut.Unlock()
  154. if w.deviceMap == nil {
  155. w.deviceMap = make(map[protocol.DeviceID]DeviceConfiguration, len(w.cfg.Devices))
  156. for _, dev := range w.cfg.Devices {
  157. w.deviceMap[dev.DeviceID] = dev
  158. }
  159. }
  160. return w.deviceMap
  161. }
  162. // SetDevice adds a new device to the configuration, or overwrites an existing
  163. // device with the same ID.
  164. func (w *Wrapper) SetDevice(dev DeviceConfiguration) CommitResponse {
  165. w.mut.Lock()
  166. defer w.mut.Unlock()
  167. newCfg := w.cfg.Copy()
  168. replaced := false
  169. for i := range newCfg.Devices {
  170. if newCfg.Devices[i].DeviceID == dev.DeviceID {
  171. newCfg.Devices[i] = dev
  172. replaced = true
  173. break
  174. }
  175. }
  176. if !replaced {
  177. newCfg.Devices = append(w.cfg.Devices, dev)
  178. }
  179. return w.replaceLocked(newCfg)
  180. }
  181. // Folders returns a map of folders. Folder structures should not be changed,
  182. // other than for the purpose of updating via SetFolder().
  183. func (w *Wrapper) Folders() map[string]FolderConfiguration {
  184. w.mut.Lock()
  185. defer w.mut.Unlock()
  186. if w.folderMap == nil {
  187. w.folderMap = make(map[string]FolderConfiguration, len(w.cfg.Folders))
  188. for _, fld := range w.cfg.Folders {
  189. w.folderMap[fld.ID] = fld
  190. }
  191. }
  192. return w.folderMap
  193. }
  194. // SetFolder adds a new folder to the configuration, or overwrites an existing
  195. // folder with the same ID.
  196. func (w *Wrapper) SetFolder(fld FolderConfiguration) CommitResponse {
  197. w.mut.Lock()
  198. defer w.mut.Unlock()
  199. newCfg := w.cfg.Copy()
  200. replaced := false
  201. for i := range newCfg.Folders {
  202. if newCfg.Folders[i].ID == fld.ID {
  203. newCfg.Folders[i] = fld
  204. replaced = true
  205. break
  206. }
  207. }
  208. if !replaced {
  209. newCfg.Folders = append(w.cfg.Folders, fld)
  210. }
  211. return w.replaceLocked(newCfg)
  212. }
  213. // Options returns the current options configuration object.
  214. func (w *Wrapper) Options() OptionsConfiguration {
  215. w.mut.Lock()
  216. defer w.mut.Unlock()
  217. return w.cfg.Options
  218. }
  219. // SetOptions replaces the current options configuration object.
  220. func (w *Wrapper) SetOptions(opts OptionsConfiguration) CommitResponse {
  221. w.mut.Lock()
  222. defer w.mut.Unlock()
  223. newCfg := w.cfg.Copy()
  224. newCfg.Options = opts
  225. return w.replaceLocked(newCfg)
  226. }
  227. // GUI returns the current GUI configuration object.
  228. func (w *Wrapper) GUI() GUIConfiguration {
  229. w.mut.Lock()
  230. defer w.mut.Unlock()
  231. return w.cfg.GUI
  232. }
  233. // SetGUI replaces the current GUI configuration object.
  234. func (w *Wrapper) SetGUI(gui GUIConfiguration) CommitResponse {
  235. w.mut.Lock()
  236. defer w.mut.Unlock()
  237. newCfg := w.cfg.Copy()
  238. newCfg.GUI = gui
  239. return w.replaceLocked(newCfg)
  240. }
  241. // IgnoredDevice returns whether or not connection attempts from the given
  242. // device should be silently ignored.
  243. func (w *Wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  244. w.mut.Lock()
  245. defer w.mut.Unlock()
  246. for _, device := range w.cfg.IgnoredDevices {
  247. if device == id {
  248. return true
  249. }
  250. }
  251. return false
  252. }
  253. // Save writes the configuration to disk, and generates a ConfigSaved event.
  254. func (w *Wrapper) Save() error {
  255. fd, err := osutil.CreateAtomic(w.path, 0600)
  256. if err != nil {
  257. return err
  258. }
  259. if err := w.cfg.WriteXML(fd); err != nil {
  260. fd.Close()
  261. return err
  262. }
  263. if err := fd.Close(); err != nil {
  264. return err
  265. }
  266. events.Default.Log(events.ConfigSaved, w.cfg)
  267. return nil
  268. }
  269. func (w *Wrapper) GlobalDiscoveryServers() []string {
  270. var servers []string
  271. for _, srv := range w.cfg.Options.GlobalAnnServers {
  272. switch srv {
  273. case "default":
  274. servers = append(servers, DefaultDiscoveryServers...)
  275. case "default-v4":
  276. servers = append(servers, DefaultDiscoveryServersV4...)
  277. case "default-v6":
  278. servers = append(servers, DefaultDiscoveryServersV6...)
  279. default:
  280. servers = append(servers, srv)
  281. }
  282. }
  283. return util.UniqueStrings(servers)
  284. }