limiter.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // Copyright (C) 2017 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 connections
  7. import (
  8. "context"
  9. "fmt"
  10. "io"
  11. "sync/atomic"
  12. "github.com/syncthing/syncthing/lib/config"
  13. "github.com/syncthing/syncthing/lib/protocol"
  14. "github.com/syncthing/syncthing/lib/sync"
  15. "golang.org/x/time/rate"
  16. )
  17. // limiter manages a read and write rate limit, reacting to config changes
  18. // as appropriate.
  19. type limiter struct {
  20. myID protocol.DeviceID
  21. mu sync.Mutex
  22. write *rate.Limiter
  23. read *rate.Limiter
  24. limitsLAN atomic.Bool
  25. deviceReadLimiters map[protocol.DeviceID]*rate.Limiter
  26. deviceWriteLimiters map[protocol.DeviceID]*rate.Limiter
  27. }
  28. type waiter interface {
  29. // This is the rate limiting operation
  30. WaitN(ctx context.Context, n int) error
  31. Limit() rate.Limit
  32. }
  33. const (
  34. limiterBurstSize = 4 * 128 << 10
  35. )
  36. func newLimiter(myId protocol.DeviceID, cfg config.Wrapper) *limiter {
  37. l := &limiter{
  38. myID: myId,
  39. write: rate.NewLimiter(rate.Inf, limiterBurstSize),
  40. read: rate.NewLimiter(rate.Inf, limiterBurstSize),
  41. mu: sync.NewMutex(),
  42. deviceReadLimiters: make(map[protocol.DeviceID]*rate.Limiter),
  43. deviceWriteLimiters: make(map[protocol.DeviceID]*rate.Limiter),
  44. }
  45. cfg.Subscribe(l)
  46. prev := config.Configuration{Options: config.OptionsConfiguration{MaxRecvKbps: -1, MaxSendKbps: -1}}
  47. l.CommitConfiguration(prev, cfg.RawCopy())
  48. return l
  49. }
  50. // This function sets limiters according to corresponding DeviceConfiguration
  51. func (lim *limiter) setLimitsLocked(device config.DeviceConfiguration) bool {
  52. readLimiter := lim.getReadLimiterLocked(device.DeviceID)
  53. writeLimiter := lim.getWriteLimiterLocked(device.DeviceID)
  54. // limiters for this device are created so we can store previous rates for logging
  55. previousReadLimit := readLimiter.Limit()
  56. previousWriteLimit := writeLimiter.Limit()
  57. currentReadLimit := rate.Limit(device.MaxRecvKbps) * 1024
  58. currentWriteLimit := rate.Limit(device.MaxSendKbps) * 1024
  59. if device.MaxSendKbps <= 0 {
  60. currentWriteLimit = rate.Inf
  61. }
  62. if device.MaxRecvKbps <= 0 {
  63. currentReadLimit = rate.Inf
  64. }
  65. // Nothing about this device has changed. Start processing next device
  66. if previousWriteLimit == currentWriteLimit && previousReadLimit == currentReadLimit {
  67. return false
  68. }
  69. readLimiter.SetLimit(currentReadLimit)
  70. writeLimiter.SetLimit(currentWriteLimit)
  71. return true
  72. }
  73. // This function handles removing, adding and updating of device limiters.
  74. func (lim *limiter) processDevicesConfigurationLocked(from, to config.Configuration) {
  75. seen := make(map[protocol.DeviceID]struct{})
  76. // Mark devices which should not be removed, create new limiters if needed and assign new limiter rate
  77. for _, dev := range to.Devices {
  78. if dev.DeviceID == lim.myID {
  79. // This limiter was created for local device. Should skip this device
  80. continue
  81. }
  82. seen[dev.DeviceID] = struct{}{}
  83. if lim.setLimitsLocked(dev) {
  84. readLimitStr := "is unlimited"
  85. if dev.MaxRecvKbps > 0 {
  86. readLimitStr = fmt.Sprintf("limit is %d KiB/s", dev.MaxRecvKbps)
  87. }
  88. writeLimitStr := "is unlimited"
  89. if dev.MaxSendKbps > 0 {
  90. writeLimitStr = fmt.Sprintf("limit is %d KiB/s", dev.MaxSendKbps)
  91. }
  92. l.Infof("Device %s send rate %s, receive rate %s", dev.DeviceID, writeLimitStr, readLimitStr)
  93. }
  94. }
  95. // Delete remote devices which were removed in new configuration
  96. for _, dev := range from.Devices {
  97. if _, ok := seen[dev.DeviceID]; !ok {
  98. l.Debugf("deviceID: %s should be removed", dev.DeviceID)
  99. delete(lim.deviceWriteLimiters, dev.DeviceID)
  100. delete(lim.deviceReadLimiters, dev.DeviceID)
  101. }
  102. }
  103. }
  104. func (lim *limiter) CommitConfiguration(from, to config.Configuration) bool {
  105. // to ensure atomic update of configuration
  106. lim.mu.Lock()
  107. defer lim.mu.Unlock()
  108. // Delete, add or update limiters for devices
  109. lim.processDevicesConfigurationLocked(from, to)
  110. if from.Options.MaxRecvKbps == to.Options.MaxRecvKbps &&
  111. from.Options.MaxSendKbps == to.Options.MaxSendKbps &&
  112. from.Options.LimitBandwidthInLan == to.Options.LimitBandwidthInLan {
  113. return true
  114. }
  115. limited := false
  116. sendLimitStr := "is unlimited"
  117. recvLimitStr := "is unlimited"
  118. // The rate variables are in KiB/s in the config (despite the camel casing
  119. // of the name). We multiply by 1024 to get bytes/s.
  120. if to.Options.MaxRecvKbps <= 0 {
  121. lim.read.SetLimit(rate.Inf)
  122. } else {
  123. lim.read.SetLimit(1024 * rate.Limit(to.Options.MaxRecvKbps))
  124. recvLimitStr = fmt.Sprintf("limit is %d KiB/s", to.Options.MaxRecvKbps)
  125. limited = true
  126. }
  127. if to.Options.MaxSendKbps <= 0 {
  128. lim.write.SetLimit(rate.Inf)
  129. } else {
  130. lim.write.SetLimit(1024 * rate.Limit(to.Options.MaxSendKbps))
  131. sendLimitStr = fmt.Sprintf("limit is %d KiB/s", to.Options.MaxSendKbps)
  132. limited = true
  133. }
  134. lim.limitsLAN.Store(to.Options.LimitBandwidthInLan)
  135. l.Infof("Overall send rate %s, receive rate %s", sendLimitStr, recvLimitStr)
  136. if limited {
  137. if to.Options.LimitBandwidthInLan {
  138. l.Infoln("Rate limits apply to LAN connections")
  139. } else {
  140. l.Infoln("Rate limits do not apply to LAN connections")
  141. }
  142. }
  143. return true
  144. }
  145. func (*limiter) String() string {
  146. // required by config.Committer interface
  147. return "connections.limiter"
  148. }
  149. func (lim *limiter) getLimiters(remoteID protocol.DeviceID, rw io.ReadWriter, isLAN bool) (io.Reader, io.Writer) {
  150. lim.mu.Lock()
  151. wr := lim.newLimitedWriterLocked(remoteID, rw, isLAN)
  152. rd := lim.newLimitedReaderLocked(remoteID, rw, isLAN)
  153. lim.mu.Unlock()
  154. return rd, wr
  155. }
  156. func (lim *limiter) newLimitedReaderLocked(remoteID protocol.DeviceID, r io.Reader, isLAN bool) io.Reader {
  157. return &limitedReader{
  158. reader: r,
  159. waiterHolder: waiterHolder{
  160. waiter: totalWaiter{lim.getReadLimiterLocked(remoteID), lim.read},
  161. limitsLAN: &lim.limitsLAN,
  162. isLAN: isLAN,
  163. },
  164. }
  165. }
  166. func (lim *limiter) newLimitedWriterLocked(remoteID protocol.DeviceID, w io.Writer, isLAN bool) io.Writer {
  167. return &limitedWriter{
  168. writer: w,
  169. waiterHolder: waiterHolder{
  170. waiter: totalWaiter{lim.getWriteLimiterLocked(remoteID), lim.write},
  171. limitsLAN: &lim.limitsLAN,
  172. isLAN: isLAN,
  173. },
  174. }
  175. }
  176. func (lim *limiter) getReadLimiterLocked(deviceID protocol.DeviceID) *rate.Limiter {
  177. return getRateLimiter(lim.deviceReadLimiters, deviceID)
  178. }
  179. func (lim *limiter) getWriteLimiterLocked(deviceID protocol.DeviceID) *rate.Limiter {
  180. return getRateLimiter(lim.deviceWriteLimiters, deviceID)
  181. }
  182. func getRateLimiter(m map[protocol.DeviceID]*rate.Limiter, deviceID protocol.DeviceID) *rate.Limiter {
  183. limiter, ok := m[deviceID]
  184. if !ok {
  185. limiter = rate.NewLimiter(rate.Inf, limiterBurstSize)
  186. m[deviceID] = limiter
  187. }
  188. return limiter
  189. }
  190. // limitedReader is a rate limited io.Reader
  191. type limitedReader struct {
  192. reader io.Reader
  193. waiterHolder
  194. }
  195. func (r *limitedReader) Read(buf []byte) (int, error) {
  196. n, err := r.reader.Read(buf)
  197. if !r.unlimited() {
  198. r.take(n)
  199. }
  200. return n, err
  201. }
  202. // limitedWriter is a rate limited io.Writer
  203. type limitedWriter struct {
  204. writer io.Writer
  205. waiterHolder
  206. }
  207. func (w *limitedWriter) Write(buf []byte) (int, error) {
  208. if w.unlimited() {
  209. return w.writer.Write(buf)
  210. }
  211. // This does (potentially) multiple smaller writes in order to be less
  212. // bursty with large writes and slow rates. At the same time we don't
  213. // want to do hilarious amounts of tiny writes when the rate is high, so
  214. // try to be a bit adaptable. We range from the minimum write size of 1
  215. // KiB up to the limiter burst size, aiming for about a write every
  216. // 10ms.
  217. singleWriteSize := int(w.waiter.Limit() / 100) // 10ms worth of data
  218. singleWriteSize = ((singleWriteSize / 1024) + 1) * 1024 // round up to the next kibibyte
  219. if singleWriteSize > limiterBurstSize {
  220. singleWriteSize = limiterBurstSize
  221. }
  222. written := 0
  223. for written < len(buf) {
  224. toWrite := singleWriteSize
  225. if toWrite > len(buf)-written {
  226. toWrite = len(buf) - written
  227. }
  228. w.take(toWrite)
  229. n, err := w.writer.Write(buf[written : written+toWrite])
  230. written += n
  231. if err != nil {
  232. return written, err
  233. }
  234. }
  235. return written, nil
  236. }
  237. // waiterHolder is the common functionality around having and evaluating a
  238. // waiter, valid for both writers and readers
  239. type waiterHolder struct {
  240. waiter waiter
  241. limitsLAN *atomic.Bool
  242. isLAN bool
  243. }
  244. // unlimited returns true if the waiter is not limiting the rate
  245. func (w waiterHolder) unlimited() bool {
  246. if w.isLAN && !w.limitsLAN.Load() {
  247. return true
  248. }
  249. return w.waiter.Limit() == rate.Inf
  250. }
  251. // take is a utility function to consume tokens, because no call to WaitN
  252. // must be larger than the limiter burst size or it will hang.
  253. func (w waiterHolder) take(tokens int) {
  254. // For writes we already split the buffer into smaller operations so those
  255. // will always end up in the fast path below. For reads, however, we don't
  256. // control the size of the incoming buffer and don't split the calls
  257. // into the lower level reads so we might get a large amount of data and
  258. // end up in the loop further down.
  259. if tokens <= limiterBurstSize {
  260. // Fast path. We won't get an error from WaitN as we don't pass a
  261. // context with a deadline.
  262. _ = w.waiter.WaitN(context.TODO(), tokens)
  263. return
  264. }
  265. for tokens > 0 {
  266. // Consume limiterBurstSize tokens at a time until we're done.
  267. if tokens > limiterBurstSize {
  268. _ = w.waiter.WaitN(context.TODO(), limiterBurstSize)
  269. tokens -= limiterBurstSize
  270. } else {
  271. _ = w.waiter.WaitN(context.TODO(), tokens)
  272. tokens = 0
  273. }
  274. }
  275. }
  276. // totalWaiter waits for all of the waiters
  277. type totalWaiter []waiter
  278. func (tw totalWaiter) WaitN(ctx context.Context, n int) error {
  279. for _, w := range tw {
  280. if err := w.WaitN(ctx, n); err != nil {
  281. // error here is context cancellation, most likely, so we abort
  282. // early
  283. return err
  284. }
  285. }
  286. return nil
  287. }
  288. func (tw totalWaiter) Limit() rate.Limit {
  289. min := rate.Inf
  290. for _, w := range tw {
  291. if l := w.Limit(); l < min {
  292. min = l
  293. }
  294. }
  295. return min
  296. }