limiter.go 9.7 KB

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