limiter.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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) VerifyConfiguration(from, to config.Configuration) error {
  106. return nil
  107. }
  108. func (lim *limiter) CommitConfiguration(from, to config.Configuration) bool {
  109. // to ensure atomic update of configuration
  110. lim.mu.Lock()
  111. defer lim.mu.Unlock()
  112. // Delete, add or update limiters for devices
  113. lim.processDevicesConfigurationLocked(from, to)
  114. if from.Options.MaxRecvKbps == to.Options.MaxRecvKbps &&
  115. from.Options.MaxSendKbps == to.Options.MaxSendKbps &&
  116. from.Options.LimitBandwidthInLan == to.Options.LimitBandwidthInLan {
  117. return true
  118. }
  119. limited := false
  120. sendLimitStr := "is unlimited"
  121. recvLimitStr := "is unlimited"
  122. // The rate variables are in KiB/s in the config (despite the camel casing
  123. // of the name). We multiply by 1024 to get bytes/s.
  124. if to.Options.MaxRecvKbps <= 0 {
  125. lim.read.SetLimit(rate.Inf)
  126. } else {
  127. lim.read.SetLimit(1024 * rate.Limit(to.Options.MaxRecvKbps))
  128. recvLimitStr = fmt.Sprintf("limit is %d KiB/s", to.Options.MaxRecvKbps)
  129. limited = true
  130. }
  131. if to.Options.MaxSendKbps <= 0 {
  132. lim.write.SetLimit(rate.Inf)
  133. } else {
  134. lim.write.SetLimit(1024 * rate.Limit(to.Options.MaxSendKbps))
  135. sendLimitStr = fmt.Sprintf("limit is %d KiB/s", to.Options.MaxSendKbps)
  136. limited = true
  137. }
  138. lim.limitsLAN.set(to.Options.LimitBandwidthInLan)
  139. l.Infof("Overall send rate %s, receive rate %s", sendLimitStr, recvLimitStr)
  140. if limited {
  141. if to.Options.LimitBandwidthInLan {
  142. l.Infoln("Rate limits apply to LAN connections")
  143. } else {
  144. l.Infoln("Rate limits do not apply to LAN connections")
  145. }
  146. }
  147. return true
  148. }
  149. func (lim *limiter) String() string {
  150. // required by config.Committer interface
  151. return "connections.limiter"
  152. }
  153. func (lim *limiter) getLimiters(remoteID protocol.DeviceID, rw io.ReadWriter, isLAN bool) (io.Reader, io.Writer) {
  154. lim.mu.Lock()
  155. wr := lim.newLimitedWriterLocked(remoteID, rw, isLAN)
  156. rd := lim.newLimitedReaderLocked(remoteID, rw, isLAN)
  157. lim.mu.Unlock()
  158. return rd, wr
  159. }
  160. func (lim *limiter) newLimitedReaderLocked(remoteID protocol.DeviceID, r io.Reader, isLAN bool) io.Reader {
  161. return &limitedReader{
  162. reader: r,
  163. waiterHolder: waiterHolder{
  164. waiter: totalWaiter{lim.getReadLimiterLocked(remoteID), lim.read},
  165. limitsLAN: &lim.limitsLAN,
  166. isLAN: isLAN,
  167. },
  168. }
  169. }
  170. func (lim *limiter) newLimitedWriterLocked(remoteID protocol.DeviceID, w io.Writer, isLAN bool) io.Writer {
  171. return &limitedWriter{
  172. writer: w,
  173. waiterHolder: waiterHolder{
  174. waiter: totalWaiter{lim.getWriteLimiterLocked(remoteID), lim.write},
  175. limitsLAN: &lim.limitsLAN,
  176. isLAN: isLAN,
  177. },
  178. }
  179. }
  180. func (lim *limiter) getReadLimiterLocked(deviceID protocol.DeviceID) *rate.Limiter {
  181. return getRateLimiter(lim.deviceReadLimiters, deviceID)
  182. }
  183. func (lim *limiter) getWriteLimiterLocked(deviceID protocol.DeviceID) *rate.Limiter {
  184. return getRateLimiter(lim.deviceWriteLimiters, deviceID)
  185. }
  186. func getRateLimiter(m map[protocol.DeviceID]*rate.Limiter, deviceID protocol.DeviceID) *rate.Limiter {
  187. limiter, ok := m[deviceID]
  188. if !ok {
  189. limiter = rate.NewLimiter(rate.Inf, limiterBurstSize)
  190. m[deviceID] = limiter
  191. }
  192. return limiter
  193. }
  194. // limitedReader is a rate limited io.Reader
  195. type limitedReader struct {
  196. reader io.Reader
  197. waiterHolder
  198. }
  199. func (r *limitedReader) Read(buf []byte) (int, error) {
  200. n, err := r.reader.Read(buf)
  201. if !r.unlimited() {
  202. r.take(n)
  203. }
  204. return n, err
  205. }
  206. // limitedWriter is a rate limited io.Writer
  207. type limitedWriter struct {
  208. writer io.Writer
  209. waiterHolder
  210. }
  211. func (w *limitedWriter) Write(buf []byte) (int, error) {
  212. if w.unlimited() {
  213. return w.writer.Write(buf)
  214. }
  215. // This does (potentially) multiple smaller writes in order to be less
  216. // bursty with large writes and slow rates.
  217. written := 0
  218. for written < len(buf) {
  219. toWrite := maxSingleWriteSize
  220. if toWrite > len(buf)-written {
  221. toWrite = len(buf) - written
  222. }
  223. w.take(toWrite)
  224. n, err := w.writer.Write(buf[written : written+toWrite])
  225. written += n
  226. if err != nil {
  227. return written, err
  228. }
  229. }
  230. return written, nil
  231. }
  232. // waiterHolder is the common functionality around having and evaluating a
  233. // waiter, valid for both writers and readers
  234. type waiterHolder struct {
  235. waiter waiter
  236. limitsLAN *atomicBool
  237. isLAN bool
  238. }
  239. // unlimited returns true if the waiter is not limiting the rate
  240. func (w waiterHolder) unlimited() bool {
  241. if w.isLAN && !w.limitsLAN.get() {
  242. return true
  243. }
  244. return w.waiter.Limit() == rate.Inf
  245. }
  246. // take is a utility function to consume tokens, because no call to WaitN
  247. // must be larger than the limiter burst size or it will hang.
  248. func (w waiterHolder) take(tokens int) {
  249. // For writes we already split the buffer into smaller operations so those
  250. // will always end up in the fast path below. For reads, however, we don't
  251. // control the size of the incoming buffer and don't split the calls
  252. // into the lower level reads so we might get a large amount of data and
  253. // end up in the loop further down.
  254. if tokens < limiterBurstSize {
  255. // Fast path. We won't get an error from WaitN as we don't pass a
  256. // context with a deadline.
  257. _ = w.waiter.WaitN(context.TODO(), tokens)
  258. return
  259. }
  260. for tokens > 0 {
  261. // Consume limiterBurstSize tokens at a time until we're done.
  262. if tokens > limiterBurstSize {
  263. _ = w.waiter.WaitN(context.TODO(), limiterBurstSize)
  264. tokens -= limiterBurstSize
  265. } else {
  266. _ = w.waiter.WaitN(context.TODO(), tokens)
  267. tokens = 0
  268. }
  269. }
  270. }
  271. type atomicBool int32
  272. func (b *atomicBool) set(v bool) {
  273. if v {
  274. atomic.StoreInt32((*int32)(b), 1)
  275. } else {
  276. atomic.StoreInt32((*int32)(b), 0)
  277. }
  278. }
  279. func (b *atomicBool) get() bool {
  280. return atomic.LoadInt32((*int32)(b)) != 0
  281. }
  282. // totalWaiter waits for all of the waiters
  283. type totalWaiter []waiter
  284. func (tw totalWaiter) WaitN(ctx context.Context, n int) error {
  285. for _, w := range tw {
  286. if err := w.WaitN(ctx, n); err != nil {
  287. // error here is context cancellation, most likely, so we abort
  288. // early
  289. return err
  290. }
  291. }
  292. return nil
  293. }
  294. func (tw totalWaiter) Limit() rate.Limit {
  295. min := rate.Inf
  296. for _, w := range tw {
  297. if l := w.Limit(); l < min {
  298. min = l
  299. }
  300. }
  301. return min
  302. }