cache.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // Copyright (C) 2015 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 discover
  7. import (
  8. "sort"
  9. stdsync "sync"
  10. "time"
  11. "github.com/syncthing/syncthing/lib/protocol"
  12. "github.com/syncthing/syncthing/lib/sync"
  13. "github.com/thejerf/suture"
  14. )
  15. // The CachingMux aggregates results from multiple Finders. Each Finder has
  16. // an associated cache time and negative cache time. The cache time sets how
  17. // long we cache and return successfull lookup results, the negative cache
  18. // time sets how long we refrain from asking about the same device ID after
  19. // receiving a negative answer. The value of zero disables caching (positive
  20. // or negative).
  21. type CachingMux struct {
  22. *suture.Supervisor
  23. finders []cachedFinder
  24. caches []*cache
  25. mut sync.Mutex
  26. }
  27. // A cachedFinder is a Finder with associated cache timeouts.
  28. type cachedFinder struct {
  29. Finder
  30. cacheTime time.Duration
  31. negCacheTime time.Duration
  32. priority int
  33. }
  34. // A prioritizedAddress is what we use to sort addresses returned from
  35. // different sources with different priorities.
  36. type prioritizedAddress struct {
  37. priority int
  38. addr string
  39. }
  40. func NewCachingMux() *CachingMux {
  41. return &CachingMux{
  42. Supervisor: suture.NewSimple("discover.cachingMux"),
  43. mut: sync.NewMutex(),
  44. }
  45. }
  46. // Add registers a new Finder, with associated cache timeouts.
  47. func (m *CachingMux) Add(finder Finder, cacheTime, negCacheTime time.Duration, priority int) {
  48. m.mut.Lock()
  49. m.finders = append(m.finders, cachedFinder{finder, cacheTime, negCacheTime, priority})
  50. m.caches = append(m.caches, newCache())
  51. m.mut.Unlock()
  52. if svc, ok := finder.(suture.Service); ok {
  53. m.Supervisor.Add(svc)
  54. }
  55. }
  56. // Lookup attempts to resolve the device ID using any of the added Finders,
  57. // while obeying the cache settings.
  58. func (m *CachingMux) Lookup(deviceID protocol.DeviceID) (direct []string, relays []Relay, err error) {
  59. var pdirect []prioritizedAddress
  60. m.mut.Lock()
  61. for i, finder := range m.finders {
  62. if cacheEntry, ok := m.caches[i].Get(deviceID); ok {
  63. // We have a cache entry. Lets see what it says.
  64. if cacheEntry.found && time.Since(cacheEntry.when) < finder.cacheTime {
  65. // It's a positive, valid entry. Use it.
  66. l.Debugln("cached discovery entry for", deviceID, "at", finder)
  67. l.Debugln(" cache:", cacheEntry)
  68. for _, addr := range cacheEntry.Direct {
  69. pdirect = append(pdirect, prioritizedAddress{finder.priority, addr})
  70. }
  71. relays = append(relays, cacheEntry.Relays...)
  72. continue
  73. }
  74. if !cacheEntry.found && time.Since(cacheEntry.when) < finder.negCacheTime {
  75. // It's a negative, valid entry. We should not make another
  76. // attempt right now.
  77. l.Debugln("negative cache entry for", deviceID, "at", finder)
  78. continue
  79. }
  80. // It's expired. Ignore and continue.
  81. }
  82. // Perform the actual lookup and cache the result.
  83. if td, tr, err := finder.Lookup(deviceID); err == nil {
  84. l.Debugln("lookup for", deviceID, "at", finder)
  85. l.Debugln(" direct:", td)
  86. l.Debugln(" relays:", tr)
  87. for _, addr := range td {
  88. pdirect = append(pdirect, prioritizedAddress{finder.priority, addr})
  89. }
  90. relays = append(relays, tr...)
  91. m.caches[i].Set(deviceID, CacheEntry{
  92. Direct: td,
  93. Relays: tr,
  94. when: time.Now(),
  95. found: len(td)+len(tr) > 0,
  96. })
  97. } else {
  98. // Lookup returned error, add a negative cache entry.
  99. m.caches[i].Set(deviceID, CacheEntry{
  100. when: time.Now(),
  101. found: false,
  102. })
  103. }
  104. }
  105. m.mut.Unlock()
  106. direct = uniqueSortedAddrs(pdirect)
  107. relays = uniqueSortedRelays(relays)
  108. l.Debugln("lookup results for", deviceID)
  109. l.Debugln(" direct: ", direct)
  110. l.Debugln(" relays: ", relays)
  111. return direct, relays, nil
  112. }
  113. func (m *CachingMux) String() string {
  114. return "discovery cache"
  115. }
  116. func (m *CachingMux) Error() error {
  117. return nil
  118. }
  119. func (m *CachingMux) ChildErrors() map[string]error {
  120. m.mut.Lock()
  121. children := make(map[string]error, len(m.finders))
  122. for _, f := range m.finders {
  123. children[f.String()] = f.Error()
  124. }
  125. m.mut.Unlock()
  126. return children
  127. }
  128. func (m *CachingMux) Cache() map[protocol.DeviceID]CacheEntry {
  129. // Res will be the "total" cache, i.e. the union of our cache and all our
  130. // children's caches.
  131. res := make(map[protocol.DeviceID]CacheEntry)
  132. m.mut.Lock()
  133. for i := range m.finders {
  134. // Each finder[i] has a corresponding cache at cache[i]. Go through it
  135. // and populate the total, if it's newer than what's already in there.
  136. // We skip any negative cache entries.
  137. for k, v := range m.caches[i].Cache() {
  138. if v.found && v.when.After(res[k].when) {
  139. res[k] = v
  140. }
  141. }
  142. // Then ask the finder itself for it's cache and do the same. If this
  143. // finder is a global discovery client, it will have no cache. If it's
  144. // a local discovery client, this will be it's current state.
  145. for k, v := range m.finders[i].Cache() {
  146. if v.found && v.when.After(res[k].when) {
  147. res[k] = v
  148. }
  149. }
  150. }
  151. m.mut.Unlock()
  152. return res
  153. }
  154. // A cache can be embedded wherever useful
  155. type cache struct {
  156. entries map[protocol.DeviceID]CacheEntry
  157. mut stdsync.Mutex
  158. }
  159. func newCache() *cache {
  160. return &cache{
  161. entries: make(map[protocol.DeviceID]CacheEntry),
  162. }
  163. }
  164. func (c *cache) Set(id protocol.DeviceID, ce CacheEntry) {
  165. c.mut.Lock()
  166. c.entries[id] = ce
  167. c.mut.Unlock()
  168. }
  169. func (c *cache) Get(id protocol.DeviceID) (CacheEntry, bool) {
  170. c.mut.Lock()
  171. ce, ok := c.entries[id]
  172. c.mut.Unlock()
  173. return ce, ok
  174. }
  175. func (c *cache) Cache() map[protocol.DeviceID]CacheEntry {
  176. c.mut.Lock()
  177. m := make(map[protocol.DeviceID]CacheEntry, len(c.entries))
  178. for k, v := range c.entries {
  179. m[k] = v
  180. }
  181. c.mut.Unlock()
  182. return m
  183. }
  184. func uniqueSortedAddrs(ss []prioritizedAddress) []string {
  185. // We sort the addresses by priority, then filter them based on seen
  186. // (first time seen is the on kept, so we retain priority).
  187. sort.Sort(prioritizedAddressList(ss))
  188. filtered := make([]string, 0, len(ss))
  189. seen := make(map[string]struct{}, len(ss))
  190. for _, s := range ss {
  191. if _, ok := seen[s.addr]; !ok {
  192. filtered = append(filtered, s.addr)
  193. seen[s.addr] = struct{}{}
  194. }
  195. }
  196. return filtered
  197. }
  198. func uniqueSortedRelays(rs []Relay) []Relay {
  199. m := make(map[string]Relay, len(rs))
  200. for _, r := range rs {
  201. m[r.URL] = r
  202. }
  203. var ur = make([]Relay, 0, len(m))
  204. for _, r := range m {
  205. ur = append(ur, r)
  206. }
  207. sort.Sort(relayList(ur))
  208. return ur
  209. }
  210. type relayList []Relay
  211. func (l relayList) Len() int {
  212. return len(l)
  213. }
  214. func (l relayList) Swap(a, b int) {
  215. l[a], l[b] = l[b], l[a]
  216. }
  217. func (l relayList) Less(a, b int) bool {
  218. return l[a].URL < l[b].URL
  219. }
  220. type prioritizedAddressList []prioritizedAddress
  221. func (l prioritizedAddressList) Len() int {
  222. return len(l)
  223. }
  224. func (l prioritizedAddressList) Swap(a, b int) {
  225. l[a], l[b] = l[b], l[a]
  226. }
  227. func (l prioritizedAddressList) Less(a, b int) bool {
  228. if l[a].priority != l[b].priority {
  229. return l[a].priority < l[b].priority
  230. }
  231. return l[a].addr < l[b].addr
  232. }