cache.go 7.4 KB

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