wrapper.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "github.com/syncthing/protocol"
  12. "github.com/syncthing/syncthing/internal/events"
  13. "github.com/syncthing/syncthing/internal/osutil"
  14. "github.com/syncthing/syncthing/internal/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" respone 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. type CommitResponse struct {
  41. ValidationError error
  42. RequiresRestart bool
  43. }
  44. var ResponseNoRestart = CommitResponse{
  45. ValidationError: nil,
  46. RequiresRestart: false,
  47. }
  48. // A wrapper around a Configuration that manages loads, saves and published
  49. // notifications of changes to registered Handlers
  50. type Wrapper struct {
  51. cfg Configuration
  52. path string
  53. deviceMap map[protocol.DeviceID]DeviceConfiguration
  54. folderMap map[string]FolderConfiguration
  55. replaces chan Configuration
  56. mut sync.Mutex
  57. subs []Committer
  58. sMut sync.Mutex
  59. }
  60. // Wrap wraps an existing Configuration structure and ties it to a file on
  61. // disk.
  62. func Wrap(path string, cfg Configuration) *Wrapper {
  63. w := &Wrapper{
  64. cfg: cfg,
  65. path: path,
  66. mut: sync.NewMutex(),
  67. sMut: sync.NewMutex(),
  68. }
  69. w.replaces = make(chan Configuration)
  70. return w
  71. }
  72. // Load loads an existing file on disk and returns a new configuration
  73. // wrapper.
  74. func Load(path string, myID protocol.DeviceID) (*Wrapper, error) {
  75. fd, err := os.Open(path)
  76. if err != nil {
  77. return nil, err
  78. }
  79. defer fd.Close()
  80. cfg, err := ReadXML(fd, myID)
  81. if err != nil {
  82. return nil, err
  83. }
  84. return Wrap(path, cfg), nil
  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.sMut.Lock()
  95. w.subs = append(w.subs, c)
  96. w.sMut.Unlock()
  97. }
  98. // Raw returns the currently wrapped Configuration object.
  99. func (w *Wrapper) Raw() Configuration {
  100. return w.cfg
  101. }
  102. // Replace swaps the current configuration object for the given one.
  103. func (w *Wrapper) Replace(cfg Configuration) CommitResponse {
  104. w.mut.Lock()
  105. defer w.mut.Unlock()
  106. return w.replaceLocked(cfg)
  107. }
  108. func (w *Wrapper) replaceLocked(to Configuration) CommitResponse {
  109. from := w.cfg
  110. for _, sub := range w.subs {
  111. if debug {
  112. l.Debugln(sub, "verifying configuration")
  113. }
  114. if err := sub.VerifyConfiguration(from, to); err != nil {
  115. if debug {
  116. l.Debugln(sub, "rejected config:", err)
  117. }
  118. return CommitResponse{
  119. ValidationError: err,
  120. }
  121. }
  122. }
  123. allOk := true
  124. for _, sub := range w.subs {
  125. if debug {
  126. l.Debugln(sub, "committing configuration")
  127. }
  128. ok := sub.CommitConfiguration(from, to)
  129. if !ok {
  130. if debug {
  131. l.Debugln(sub, "requires restart")
  132. }
  133. allOk = false
  134. }
  135. }
  136. w.cfg = to
  137. w.deviceMap = nil
  138. w.folderMap = nil
  139. return CommitResponse{
  140. RequiresRestart: !allOk,
  141. }
  142. }
  143. // Devices returns a map of devices. Device structures should not be changed,
  144. // other than for the purpose of updating via SetDevice().
  145. func (w *Wrapper) Devices() map[protocol.DeviceID]DeviceConfiguration {
  146. w.mut.Lock()
  147. defer w.mut.Unlock()
  148. if w.deviceMap == nil {
  149. w.deviceMap = make(map[protocol.DeviceID]DeviceConfiguration, len(w.cfg.Devices))
  150. for _, dev := range w.cfg.Devices {
  151. w.deviceMap[dev.DeviceID] = dev
  152. }
  153. }
  154. return w.deviceMap
  155. }
  156. // SetDevice adds a new device to the configuration, or overwrites an existing
  157. // device with the same ID.
  158. func (w *Wrapper) SetDevice(dev DeviceConfiguration) CommitResponse {
  159. w.mut.Lock()
  160. defer w.mut.Unlock()
  161. newCfg := w.cfg.Copy()
  162. replaced := false
  163. for i := range newCfg.Devices {
  164. if newCfg.Devices[i].DeviceID == dev.DeviceID {
  165. newCfg.Devices[i] = dev
  166. replaced = true
  167. break
  168. }
  169. }
  170. if !replaced {
  171. newCfg.Devices = append(w.cfg.Devices, dev)
  172. }
  173. return w.replaceLocked(newCfg)
  174. }
  175. // Folders returns a map of folders. Folder structures should not be changed,
  176. // other than for the purpose of updating via SetFolder().
  177. func (w *Wrapper) Folders() map[string]FolderConfiguration {
  178. w.mut.Lock()
  179. defer w.mut.Unlock()
  180. if w.folderMap == nil {
  181. w.folderMap = make(map[string]FolderConfiguration, len(w.cfg.Folders))
  182. for _, fld := range w.cfg.Folders {
  183. w.folderMap[fld.ID] = fld
  184. }
  185. }
  186. return w.folderMap
  187. }
  188. // SetFolder adds a new folder to the configuration, or overwrites an existing
  189. // folder with the same ID.
  190. func (w *Wrapper) SetFolder(fld FolderConfiguration) CommitResponse {
  191. w.mut.Lock()
  192. defer w.mut.Unlock()
  193. newCfg := w.cfg.Copy()
  194. replaced := false
  195. for i := range newCfg.Folders {
  196. if newCfg.Folders[i].ID == fld.ID {
  197. newCfg.Folders[i] = fld
  198. replaced = true
  199. break
  200. }
  201. }
  202. if !replaced {
  203. newCfg.Folders = append(w.cfg.Folders, fld)
  204. }
  205. return w.replaceLocked(newCfg)
  206. }
  207. // Options returns the current options configuration object.
  208. func (w *Wrapper) Options() OptionsConfiguration {
  209. w.mut.Lock()
  210. defer w.mut.Unlock()
  211. return w.cfg.Options
  212. }
  213. // SetOptions replaces the current options configuration object.
  214. func (w *Wrapper) SetOptions(opts OptionsConfiguration) CommitResponse {
  215. w.mut.Lock()
  216. defer w.mut.Unlock()
  217. newCfg := w.cfg.Copy()
  218. newCfg.Options = opts
  219. return w.replaceLocked(newCfg)
  220. }
  221. // GUI returns the current GUI configuration object.
  222. func (w *Wrapper) GUI() GUIConfiguration {
  223. w.mut.Lock()
  224. defer w.mut.Unlock()
  225. return w.cfg.GUI
  226. }
  227. // SetGUI replaces the current GUI configuration object.
  228. func (w *Wrapper) SetGUI(gui GUIConfiguration) CommitResponse {
  229. w.mut.Lock()
  230. defer w.mut.Unlock()
  231. newCfg := w.cfg.Copy()
  232. newCfg.GUI = gui
  233. return w.replaceLocked(newCfg)
  234. }
  235. // IgnoredDevice returns whether or not connection attempts from the given
  236. // device should be silently ignored.
  237. func (w *Wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  238. w.mut.Lock()
  239. defer w.mut.Unlock()
  240. for _, device := range w.cfg.IgnoredDevices {
  241. if device == id {
  242. return true
  243. }
  244. }
  245. return false
  246. }
  247. // Save writes the configuration to disk, and generates a ConfigSaved event.
  248. func (w *Wrapper) Save() error {
  249. fd, err := ioutil.TempFile(filepath.Dir(w.path), "cfg")
  250. if err != nil {
  251. return err
  252. }
  253. defer os.Remove(fd.Name())
  254. err = w.cfg.WriteXML(fd)
  255. if err != nil {
  256. fd.Close()
  257. return err
  258. }
  259. err = fd.Close()
  260. if err != nil {
  261. return err
  262. }
  263. events.Default.Log(events.ConfigSaved, w.cfg)
  264. return osutil.Rename(fd.Name(), w.path)
  265. }