manager.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Copyright (C) 2020 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 discover
  7. import (
  8. "context"
  9. "crypto/tls"
  10. "fmt"
  11. "sort"
  12. "time"
  13. "github.com/thejerf/suture/v4"
  14. "github.com/syncthing/syncthing/lib/config"
  15. "github.com/syncthing/syncthing/lib/events"
  16. "github.com/syncthing/syncthing/lib/protocol"
  17. "github.com/syncthing/syncthing/lib/sync"
  18. "github.com/syncthing/syncthing/lib/util"
  19. )
  20. // The Manager aggregates results from multiple Finders. Each Finder has
  21. // an associated cache time and negative cache time. The cache time sets how
  22. // long we cache and return successful lookup results, the negative cache
  23. // time sets how long we refrain from asking about the same device ID after
  24. // receiving a negative answer. The value of zero disables caching (positive
  25. // or negative).
  26. type Manager interface {
  27. FinderService
  28. ChildErrors() map[string]error
  29. }
  30. type manager struct {
  31. *suture.Supervisor
  32. myID protocol.DeviceID
  33. cfg config.Wrapper
  34. cert tls.Certificate
  35. evLogger events.Logger
  36. addressLister AddressLister
  37. finders map[string]cachedFinder
  38. mut sync.RWMutex
  39. }
  40. func NewManager(myID protocol.DeviceID, cfg config.Wrapper, cert tls.Certificate, evLogger events.Logger, lister AddressLister) Manager {
  41. m := &manager{
  42. Supervisor: suture.New("discover.Manager", util.Spec()),
  43. myID: myID,
  44. cfg: cfg,
  45. cert: cert,
  46. evLogger: evLogger,
  47. addressLister: lister,
  48. finders: make(map[string]cachedFinder),
  49. mut: sync.NewRWMutex(),
  50. }
  51. m.Add(util.AsService(m.serve, m.String()))
  52. return m
  53. }
  54. func (m *manager) serve(ctx context.Context) error {
  55. m.cfg.Subscribe(m)
  56. m.CommitConfiguration(config.Configuration{}, m.cfg.RawCopy())
  57. <-ctx.Done()
  58. m.cfg.Unsubscribe(m)
  59. return nil
  60. }
  61. func (m *manager) addLocked(identity string, finder Finder, cacheTime, negCacheTime time.Duration) {
  62. entry := cachedFinder{
  63. Finder: finder,
  64. cacheTime: cacheTime,
  65. negCacheTime: negCacheTime,
  66. cache: newCache(),
  67. token: nil,
  68. }
  69. if service, ok := finder.(suture.Service); ok {
  70. token := m.Supervisor.Add(service)
  71. entry.token = &token
  72. }
  73. m.finders[identity] = entry
  74. l.Infoln("Using discovery mechanism:", identity)
  75. }
  76. func (m *manager) removeLocked(identity string) {
  77. entry, ok := m.finders[identity]
  78. if !ok {
  79. return
  80. }
  81. if entry.token != nil {
  82. err := m.Supervisor.Remove(*entry.token)
  83. if err != nil {
  84. l.Warnf("removing discovery %s: %s", identity, err)
  85. }
  86. }
  87. delete(m.finders, identity)
  88. l.Infoln("Stopped using discovery mechanism: ", identity)
  89. }
  90. // Lookup attempts to resolve the device ID using any of the added Finders,
  91. // while obeying the cache settings.
  92. func (m *manager) Lookup(ctx context.Context, deviceID protocol.DeviceID) (addresses []string, err error) {
  93. m.mut.RLock()
  94. for _, finder := range m.finders {
  95. if cacheEntry, ok := finder.cache.Get(deviceID); ok {
  96. // We have a cache entry. Lets see what it says.
  97. if cacheEntry.found && time.Since(cacheEntry.when) < finder.cacheTime {
  98. // It's a positive, valid entry. Use it.
  99. l.Debugln("cached discovery entry for", deviceID, "at", finder)
  100. l.Debugln(" cache:", cacheEntry)
  101. addresses = append(addresses, cacheEntry.Addresses...)
  102. continue
  103. }
  104. valid := time.Now().Before(cacheEntry.validUntil) || time.Since(cacheEntry.when) < finder.negCacheTime
  105. if !cacheEntry.found && valid {
  106. // It's a negative, valid entry. We should not make another
  107. // attempt right now.
  108. l.Debugln("negative cache entry for", deviceID, "at", finder, "valid until", cacheEntry.when.Add(finder.negCacheTime), "or", cacheEntry.validUntil)
  109. continue
  110. }
  111. // It's expired. Ignore and continue.
  112. }
  113. // Perform the actual lookup and cache the result.
  114. if addrs, err := finder.Lookup(ctx, deviceID); err == nil {
  115. l.Debugln("lookup for", deviceID, "at", finder)
  116. l.Debugln(" addresses:", addrs)
  117. addresses = append(addresses, addrs...)
  118. finder.cache.Set(deviceID, CacheEntry{
  119. Addresses: addrs,
  120. when: time.Now(),
  121. found: len(addrs) > 0,
  122. })
  123. } else {
  124. // Lookup returned error, add a negative cache entry.
  125. entry := CacheEntry{
  126. when: time.Now(),
  127. found: false,
  128. }
  129. if err, ok := err.(cachedError); ok {
  130. entry.validUntil = time.Now().Add(err.CacheFor())
  131. }
  132. finder.cache.Set(deviceID, entry)
  133. }
  134. }
  135. m.mut.RUnlock()
  136. addresses = util.UniqueTrimmedStrings(addresses)
  137. sort.Strings(addresses)
  138. l.Debugln("lookup results for", deviceID)
  139. l.Debugln(" addresses: ", addresses)
  140. return addresses, nil
  141. }
  142. func (m *manager) String() string {
  143. return "discovery cache"
  144. }
  145. func (m *manager) Error() error {
  146. return nil
  147. }
  148. func (m *manager) ChildErrors() map[string]error {
  149. children := make(map[string]error, len(m.finders))
  150. m.mut.RLock()
  151. for _, f := range m.finders {
  152. children[f.String()] = f.Error()
  153. }
  154. m.mut.RUnlock()
  155. return children
  156. }
  157. func (m *manager) Cache() map[protocol.DeviceID]CacheEntry {
  158. // Res will be the "total" cache, i.e. the union of our cache and all our
  159. // children's caches.
  160. res := make(map[protocol.DeviceID]CacheEntry)
  161. m.mut.RLock()
  162. for _, finder := range m.finders {
  163. // Each finder[i] has a corresponding cache. Go through
  164. // it and populate the total, appending any addresses and keeping
  165. // the newest "when" time. We skip any negative cache finders.
  166. for k, v := range finder.cache.Cache() {
  167. if v.found {
  168. cur := res[k]
  169. if v.when.After(cur.when) {
  170. cur.when = v.when
  171. }
  172. cur.Addresses = append(cur.Addresses, v.Addresses...)
  173. res[k] = cur
  174. }
  175. }
  176. // Then ask the finder itself for its cache and do the same. If this
  177. // finder is a global discovery client, it will have no cache. If it's
  178. // a local discovery client, this will be its current state.
  179. for k, v := range finder.Cache() {
  180. if v.found {
  181. cur := res[k]
  182. if v.when.After(cur.when) {
  183. cur.when = v.when
  184. }
  185. cur.Addresses = append(cur.Addresses, v.Addresses...)
  186. res[k] = cur
  187. }
  188. }
  189. }
  190. m.mut.RUnlock()
  191. for k, v := range res {
  192. v.Addresses = util.UniqueTrimmedStrings(v.Addresses)
  193. res[k] = v
  194. }
  195. return res
  196. }
  197. func (m *manager) VerifyConfiguration(_, _ config.Configuration) error {
  198. return nil
  199. }
  200. func (m *manager) CommitConfiguration(_, to config.Configuration) (handled bool) {
  201. m.mut.Lock()
  202. defer m.mut.Unlock()
  203. toIdentities := make(map[string]struct{})
  204. if to.Options.GlobalAnnEnabled {
  205. for _, srv := range to.Options.GlobalDiscoveryServers() {
  206. toIdentities[globalDiscoveryIdentity(srv)] = struct{}{}
  207. }
  208. }
  209. if to.Options.LocalAnnEnabled {
  210. toIdentities[ipv4Identity(to.Options.LocalAnnPort)] = struct{}{}
  211. toIdentities[ipv6Identity(to.Options.LocalAnnMCAddr)] = struct{}{}
  212. }
  213. // Remove things that we're not expected to have.
  214. for identity := range m.finders {
  215. if _, ok := toIdentities[identity]; !ok {
  216. m.removeLocked(identity)
  217. }
  218. }
  219. // Add things we don't have.
  220. if to.Options.GlobalAnnEnabled {
  221. for _, srv := range to.Options.GlobalDiscoveryServers() {
  222. identity := globalDiscoveryIdentity(srv)
  223. // Skip, if it's already running.
  224. if _, ok := m.finders[identity]; ok {
  225. continue
  226. }
  227. gd, err := NewGlobal(srv, m.cert, m.addressLister, m.evLogger)
  228. if err != nil {
  229. l.Warnln("Global discovery:", err)
  230. continue
  231. }
  232. // Each global discovery server gets its results cached for five
  233. // minutes, and is not asked again for a minute when it's returned
  234. // unsuccessfully.
  235. m.addLocked(identity, gd, 5*time.Minute, time.Minute)
  236. }
  237. }
  238. if to.Options.LocalAnnEnabled {
  239. // v4 broadcasts
  240. v4Identity := ipv4Identity(to.Options.LocalAnnPort)
  241. if _, ok := m.finders[v4Identity]; !ok {
  242. bcd, err := NewLocal(m.myID, fmt.Sprintf(":%d", to.Options.LocalAnnPort), m.addressLister, m.evLogger)
  243. if err != nil {
  244. l.Warnln("IPv4 local discovery:", err)
  245. } else {
  246. m.addLocked(v4Identity, bcd, 0, 0)
  247. }
  248. }
  249. // v6 multicasts
  250. v6Identity := ipv6Identity(to.Options.LocalAnnMCAddr)
  251. if _, ok := m.finders[v6Identity]; !ok {
  252. mcd, err := NewLocal(m.myID, to.Options.LocalAnnMCAddr, m.addressLister, m.evLogger)
  253. if err != nil {
  254. l.Warnln("IPv6 local discovery:", err)
  255. } else {
  256. m.addLocked(v6Identity, mcd, 0, 0)
  257. }
  258. }
  259. }
  260. return true
  261. }