manager.go 8.2 KB

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