wrapper.go 8.1 KB

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