limiter.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. mu sync.Mutex
  21. write *rate.Limiter
  22. read *rate.Limiter
  23. limitsLAN atomicBool
  24. deviceReadLimiters map[protocol.DeviceID]*rate.Limiter
  25. deviceWriteLimiters map[protocol.DeviceID]*rate.Limiter
  26. }
  27. type waiter interface {
  28. // This is the rate limiting operation
  29. WaitN(ctx context.Context, n int) error
  30. }
  31. const limiterBurstSize = 4 * 128 << 10
  32. func newLimiter(cfg *config.Wrapper) *limiter {
  33. l := &limiter{
  34. write: rate.NewLimiter(rate.Inf, limiterBurstSize),
  35. read: rate.NewLimiter(rate.Inf, limiterBurstSize),
  36. mu: sync.NewMutex(),
  37. deviceReadLimiters: make(map[protocol.DeviceID]*rate.Limiter),
  38. deviceWriteLimiters: make(map[protocol.DeviceID]*rate.Limiter),
  39. }
  40. cfg.Subscribe(l)
  41. prev := config.Configuration{Options: config.OptionsConfiguration{MaxRecvKbps: -1, MaxSendKbps: -1}}
  42. l.CommitConfiguration(prev, cfg.RawCopy())
  43. return l
  44. }
  45. // This function sets limiters according to corresponding DeviceConfiguration
  46. func (lim *limiter) setLimitsLocked(device config.DeviceConfiguration) bool {
  47. readLimiter := lim.getReadLimiterLocked(device.DeviceID)
  48. writeLimiter := lim.getWriteLimiterLocked(device.DeviceID)
  49. // limiters for this device are created so we can store previous rates for logging
  50. previousReadLimit := readLimiter.Limit()
  51. previousWriteLimit := writeLimiter.Limit()
  52. currentReadLimit := rate.Limit(device.MaxRecvKbps) * 1024
  53. currentWriteLimit := rate.Limit(device.MaxSendKbps) * 1024
  54. if device.MaxSendKbps <= 0 {
  55. currentWriteLimit = rate.Inf
  56. }
  57. if device.MaxRecvKbps <= 0 {
  58. currentReadLimit = rate.Inf
  59. }
  60. // Nothing about this device has changed. Start processing next device
  61. if previousWriteLimit == currentWriteLimit && previousReadLimit == currentReadLimit {
  62. return false
  63. }
  64. readLimiter.SetLimit(currentReadLimit)
  65. writeLimiter.SetLimit(currentWriteLimit)
  66. return true
  67. }
  68. // This function handles removing, adding and updating of device limiters.
  69. func (lim *limiter) processDevicesConfigurationLocked(from, to config.Configuration) {
  70. seen := make(map[protocol.DeviceID]struct{})
  71. // Mark devices which should not be removed, create new limiters if needed and assign new limiter rate
  72. for _, dev := range to.Devices {
  73. if dev.DeviceID == to.MyID {
  74. // This limiter was created for local device. Should skip this device
  75. continue
  76. }
  77. seen[dev.DeviceID] = struct{}{}
  78. if lim.setLimitsLocked(dev) {
  79. readLimitStr := "is unlimited"
  80. if dev.MaxRecvKbps > 0 {
  81. readLimitStr = fmt.Sprintf("limit is %d KiB/s", dev.MaxRecvKbps)
  82. }
  83. writeLimitStr := "is unlimited"
  84. if dev.MaxSendKbps > 0 {
  85. writeLimitStr = fmt.Sprintf("limit is %d KiB/s", dev.MaxSendKbps)
  86. }
  87. l.Infof("Device %s send rate %s, receive rate %s", dev.DeviceID, writeLimitStr, readLimitStr)
  88. }
  89. }
  90. // Delete remote devices which were removed in new configuration
  91. for _, dev := range from.Devices {
  92. if _, ok := seen[dev.DeviceID]; !ok {
  93. l.Debugf("deviceID: %s should be removed", dev.DeviceID)
  94. delete(lim.deviceWriteLimiters, dev.DeviceID)
  95. delete(lim.deviceReadLimiters, dev.DeviceID)
  96. }
  97. }
  98. }
  99. func (lim *limiter) VerifyConfiguration(from, to config.Configuration) error {
  100. return nil
  101. }
  102. func (lim *limiter) CommitConfiguration(from, to config.Configuration) bool {
  103. // to ensure atomic update of configuration
  104. lim.mu.Lock()
  105. defer lim.mu.Unlock()
  106. // Delete, add or update limiters for devices
  107. lim.processDevicesConfigurationLocked(from, to)
  108. if from.Options.MaxRecvKbps == to.Options.MaxRecvKbps &&
  109. from.Options.MaxSendKbps == to.Options.MaxSendKbps &&
  110. from.Options.LimitBandwidthInLan == to.Options.LimitBandwidthInLan {
  111. return true
  112. }
  113. // The rate variables are in KiB/s in the config (despite the camel casing
  114. // of the name). We multiply by 1024 to get bytes/s.
  115. if to.Options.MaxRecvKbps <= 0 {
  116. lim.read.SetLimit(rate.Inf)
  117. } else {
  118. lim.read.SetLimit(1024 * rate.Limit(to.Options.MaxRecvKbps))
  119. }
  120. if to.Options.MaxSendKbps <= 0 {
  121. lim.write.SetLimit(rate.Inf)
  122. } else {
  123. lim.write.SetLimit(1024 * rate.Limit(to.Options.MaxSendKbps))
  124. }
  125. lim.limitsLAN.set(to.Options.LimitBandwidthInLan)
  126. sendLimitStr := "is unlimited"
  127. recvLimitStr := "is unlimited"
  128. if to.Options.MaxSendKbps > 0 {
  129. sendLimitStr = fmt.Sprintf("limit is %d KiB/s", to.Options.MaxSendKbps)
  130. }
  131. if to.Options.MaxRecvKbps > 0 {
  132. recvLimitStr = fmt.Sprintf("limit is %d KiB/s", to.Options.MaxRecvKbps)
  133. }
  134. l.Infof("Overall send rate %s, receive rate %s", sendLimitStr, recvLimitStr)
  135. if to.Options.LimitBandwidthInLan {
  136. l.Infoln("Rate limits apply to LAN connections")
  137. } else {
  138. l.Infoln("Rate limits do not apply to LAN connections")
  139. }
  140. return true
  141. }
  142. func (lim *limiter) String() string {
  143. // required by config.Committer interface
  144. return "connections.limiter"
  145. }
  146. func (lim *limiter) getLimiters(remoteID protocol.DeviceID, rw io.ReadWriter, isLAN bool) (io.Reader, io.Writer) {
  147. lim.mu.Lock()
  148. wr := lim.newLimitedWriterLocked(remoteID, rw, isLAN)
  149. rd := lim.newLimitedReaderLocked(remoteID, rw, isLAN)
  150. lim.mu.Unlock()
  151. return rd, wr
  152. }
  153. func (lim *limiter) newLimitedReaderLocked(remoteID protocol.DeviceID, r io.Reader, isLAN bool) io.Reader {
  154. return &limitedReader{
  155. reader: r,
  156. limitsLAN: &lim.limitsLAN,
  157. waiter: totalWaiter{lim.getReadLimiterLocked(remoteID), lim.read},
  158. isLAN: isLAN,
  159. }
  160. }
  161. func (lim *limiter) newLimitedWriterLocked(remoteID protocol.DeviceID, w io.Writer, isLAN bool) io.Writer {
  162. return &limitedWriter{
  163. writer: w,
  164. limitsLAN: &lim.limitsLAN,
  165. waiter: totalWaiter{lim.getWriteLimiterLocked(remoteID), lim.write},
  166. isLAN: isLAN,
  167. }
  168. }
  169. func (lim *limiter) getReadLimiterLocked(deviceID protocol.DeviceID) *rate.Limiter {
  170. return getRateLimiter(lim.deviceReadLimiters, deviceID)
  171. }
  172. func (lim *limiter) getWriteLimiterLocked(deviceID protocol.DeviceID) *rate.Limiter {
  173. return getRateLimiter(lim.deviceWriteLimiters, deviceID)
  174. }
  175. func getRateLimiter(m map[protocol.DeviceID]*rate.Limiter, deviceID protocol.DeviceID) *rate.Limiter {
  176. limiter, ok := m[deviceID]
  177. if !ok {
  178. limiter = rate.NewLimiter(rate.Inf, limiterBurstSize)
  179. m[deviceID] = limiter
  180. }
  181. return limiter
  182. }
  183. // limitedReader is a rate limited io.Reader
  184. type limitedReader struct {
  185. reader io.Reader
  186. limitsLAN *atomicBool
  187. waiter waiter
  188. isLAN bool
  189. }
  190. func (r *limitedReader) Read(buf []byte) (int, error) {
  191. n, err := r.reader.Read(buf)
  192. if !r.isLAN || r.limitsLAN.get() {
  193. take(r.waiter, n)
  194. }
  195. return n, err
  196. }
  197. // limitedWriter is a rate limited io.Writer
  198. type limitedWriter struct {
  199. writer io.Writer
  200. limitsLAN *atomicBool
  201. waiter waiter
  202. isLAN bool
  203. }
  204. func (w *limitedWriter) Write(buf []byte) (int, error) {
  205. if !w.isLAN || w.limitsLAN.get() {
  206. take(w.waiter, len(buf))
  207. }
  208. return w.writer.Write(buf)
  209. }
  210. // take is a utility function to consume tokens from a overall rate.Limiter and deviceLimiter.
  211. // No call to WaitN can be larger than the limiter burst size so we split it up into
  212. // several calls when necessary.
  213. func take(waiter waiter, tokens int) {
  214. if tokens < limiterBurstSize {
  215. // This is the by far more common case so we get it out of the way
  216. // early.
  217. waiter.WaitN(context.TODO(), tokens)
  218. return
  219. }
  220. for tokens > 0 {
  221. // Consume limiterBurstSize tokens at a time until we're done.
  222. if tokens > limiterBurstSize {
  223. waiter.WaitN(context.TODO(), limiterBurstSize)
  224. tokens -= limiterBurstSize
  225. } else {
  226. waiter.WaitN(context.TODO(), tokens)
  227. tokens = 0
  228. }
  229. }
  230. }
  231. type atomicBool int32
  232. func (b *atomicBool) set(v bool) {
  233. if v {
  234. atomic.StoreInt32((*int32)(b), 1)
  235. } else {
  236. atomic.StoreInt32((*int32)(b), 0)
  237. }
  238. }
  239. func (b *atomicBool) get() bool {
  240. return atomic.LoadInt32((*int32)(b)) != 0
  241. }
  242. // totalWaiter waits for all of the waiters
  243. type totalWaiter []waiter
  244. func (tw totalWaiter) WaitN(ctx context.Context, n int) error {
  245. for _, w := range tw {
  246. if err := w.WaitN(ctx, n); err != nil {
  247. // error here is context cancellation, most likely, so we abort
  248. // early
  249. return err
  250. }
  251. }
  252. return nil
  253. }