limiter.go 9.7 KB

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