wrapper.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. mut sync.Mutex
  55. subs []Committer
  56. sMut 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. sMut: sync.NewMutex(),
  66. }
  67. w.replaces = make(chan Configuration)
  68. return w
  69. }
  70. // Load loads an existing file on disk and returns a new configuration
  71. // wrapper.
  72. func Load(path string, myID protocol.DeviceID) (*Wrapper, error) {
  73. fd, err := os.Open(path)
  74. if err != nil {
  75. return nil, err
  76. }
  77. defer fd.Close()
  78. cfg, err := ReadXML(fd, myID)
  79. if err != nil {
  80. return nil, err
  81. }
  82. return Wrap(path, cfg), nil
  83. }
  84. func (w *Wrapper) ConfigPath() string {
  85. return w.path
  86. }
  87. // Stop stops the Serve() loop. Set and Replace operations will panic after a
  88. // Stop.
  89. func (w *Wrapper) Stop() {
  90. close(w.replaces)
  91. }
  92. // Subscribe registers the given handler to be called on any future
  93. // configuration changes.
  94. func (w *Wrapper) Subscribe(c Committer) {
  95. w.sMut.Lock()
  96. w.subs = append(w.subs, c)
  97. w.sMut.Unlock()
  98. }
  99. // Unsubscribe de-registers the given handler from any future calls to
  100. // configuration changes
  101. func (w *Wrapper) Unsubscribe(c Committer) {
  102. w.sMut.Lock()
  103. for i := range w.subs {
  104. if w.subs[i] == c {
  105. copy(w.subs[i:], w.subs[i+1:])
  106. w.subs[len(w.subs)-1] = nil
  107. w.subs = w.subs[:len(w.subs)-1]
  108. break
  109. }
  110. }
  111. w.sMut.Unlock()
  112. }
  113. // Raw returns the currently wrapped Configuration object.
  114. func (w *Wrapper) Raw() Configuration {
  115. return w.cfg
  116. }
  117. // Replace swaps the current configuration object for the given one.
  118. func (w *Wrapper) Replace(cfg Configuration) CommitResponse {
  119. w.mut.Lock()
  120. defer w.mut.Unlock()
  121. return w.replaceLocked(cfg)
  122. }
  123. func (w *Wrapper) replaceLocked(to Configuration) CommitResponse {
  124. from := w.cfg
  125. for _, sub := range w.subs {
  126. if debug {
  127. l.Debugln(sub, "verifying configuration")
  128. }
  129. if err := sub.VerifyConfiguration(from, to); err != nil {
  130. if debug {
  131. l.Debugln(sub, "rejected config:", err)
  132. }
  133. return CommitResponse{
  134. ValidationError: err,
  135. }
  136. }
  137. }
  138. allOk := true
  139. for _, sub := range w.subs {
  140. if debug {
  141. l.Debugln(sub, "committing configuration")
  142. }
  143. ok := sub.CommitConfiguration(from, to)
  144. if !ok {
  145. if debug {
  146. l.Debugln(sub, "requires restart")
  147. }
  148. allOk = false
  149. }
  150. }
  151. w.cfg = to
  152. w.deviceMap = nil
  153. w.folderMap = nil
  154. return CommitResponse{
  155. RequiresRestart: !allOk,
  156. }
  157. }
  158. // Devices returns a map of devices. Device structures should not be changed,
  159. // other than for the purpose of updating via SetDevice().
  160. func (w *Wrapper) Devices() map[protocol.DeviceID]DeviceConfiguration {
  161. w.mut.Lock()
  162. defer w.mut.Unlock()
  163. if w.deviceMap == nil {
  164. w.deviceMap = make(map[protocol.DeviceID]DeviceConfiguration, len(w.cfg.Devices))
  165. for _, dev := range w.cfg.Devices {
  166. w.deviceMap[dev.DeviceID] = dev
  167. }
  168. }
  169. return w.deviceMap
  170. }
  171. // SetDevice adds a new device to the configuration, or overwrites an existing
  172. // device with the same ID.
  173. func (w *Wrapper) SetDevice(dev DeviceConfiguration) CommitResponse {
  174. w.mut.Lock()
  175. defer w.mut.Unlock()
  176. newCfg := w.cfg.Copy()
  177. replaced := false
  178. for i := range newCfg.Devices {
  179. if newCfg.Devices[i].DeviceID == dev.DeviceID {
  180. newCfg.Devices[i] = dev
  181. replaced = true
  182. break
  183. }
  184. }
  185. if !replaced {
  186. newCfg.Devices = append(w.cfg.Devices, dev)
  187. }
  188. return w.replaceLocked(newCfg)
  189. }
  190. // Folders returns a map of folders. Folder structures should not be changed,
  191. // other than for the purpose of updating via SetFolder().
  192. func (w *Wrapper) Folders() map[string]FolderConfiguration {
  193. w.mut.Lock()
  194. defer w.mut.Unlock()
  195. if w.folderMap == nil {
  196. w.folderMap = make(map[string]FolderConfiguration, len(w.cfg.Folders))
  197. for _, fld := range w.cfg.Folders {
  198. w.folderMap[fld.ID] = fld
  199. }
  200. }
  201. return w.folderMap
  202. }
  203. // SetFolder adds a new folder to the configuration, or overwrites an existing
  204. // folder with the same ID.
  205. func (w *Wrapper) SetFolder(fld FolderConfiguration) CommitResponse {
  206. w.mut.Lock()
  207. defer w.mut.Unlock()
  208. newCfg := w.cfg.Copy()
  209. replaced := false
  210. for i := range newCfg.Folders {
  211. if newCfg.Folders[i].ID == fld.ID {
  212. newCfg.Folders[i] = fld
  213. replaced = true
  214. break
  215. }
  216. }
  217. if !replaced {
  218. newCfg.Folders = append(w.cfg.Folders, fld)
  219. }
  220. return w.replaceLocked(newCfg)
  221. }
  222. // Options returns the current options configuration object.
  223. func (w *Wrapper) Options() OptionsConfiguration {
  224. w.mut.Lock()
  225. defer w.mut.Unlock()
  226. return w.cfg.Options
  227. }
  228. // SetOptions replaces the current options configuration object.
  229. func (w *Wrapper) SetOptions(opts OptionsConfiguration) CommitResponse {
  230. w.mut.Lock()
  231. defer w.mut.Unlock()
  232. newCfg := w.cfg.Copy()
  233. newCfg.Options = opts
  234. return w.replaceLocked(newCfg)
  235. }
  236. // GUI returns the current GUI configuration object.
  237. func (w *Wrapper) GUI() GUIConfiguration {
  238. w.mut.Lock()
  239. defer w.mut.Unlock()
  240. return w.cfg.GUI
  241. }
  242. // SetGUI replaces the current GUI configuration object.
  243. func (w *Wrapper) SetGUI(gui GUIConfiguration) CommitResponse {
  244. w.mut.Lock()
  245. defer w.mut.Unlock()
  246. newCfg := w.cfg.Copy()
  247. newCfg.GUI = gui
  248. return w.replaceLocked(newCfg)
  249. }
  250. // IgnoredDevice returns whether or not connection attempts from the given
  251. // device should be silently ignored.
  252. func (w *Wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  253. w.mut.Lock()
  254. defer w.mut.Unlock()
  255. for _, device := range w.cfg.IgnoredDevices {
  256. if device == id {
  257. return true
  258. }
  259. }
  260. return false
  261. }
  262. // Save writes the configuration to disk, and generates a ConfigSaved event.
  263. func (w *Wrapper) Save() error {
  264. fd, err := osutil.CreateAtomic(w.path, 0600)
  265. if err != nil {
  266. return err
  267. }
  268. if err := w.cfg.WriteXML(fd); err != nil {
  269. fd.Close()
  270. return err
  271. }
  272. if err := fd.Close(); err != nil {
  273. return err
  274. }
  275. events.Default.Log(events.ConfigSaved, w.cfg)
  276. return nil
  277. }