limiter.go 9.8 KB

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