limiter_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. "bytes"
  9. "context"
  10. crand "crypto/rand"
  11. "io"
  12. "math/rand"
  13. "testing"
  14. "github.com/syncthing/syncthing/lib/config"
  15. "github.com/syncthing/syncthing/lib/events"
  16. "github.com/syncthing/syncthing/lib/protocol"
  17. "github.com/thejerf/suture/v4"
  18. "golang.org/x/time/rate"
  19. )
  20. var device1, device2, device3, device4 protocol.DeviceID
  21. var dev1Conf, dev2Conf, dev3Conf, dev4Conf config.DeviceConfiguration
  22. func init() {
  23. device1, _ = protocol.DeviceIDFromString("AIR6LPZ7K4PTTUXQSMUUCPQ5YWOEDFIIQJUG7772YQXXR5YD6AWQ")
  24. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  25. device3, _ = protocol.DeviceIDFromString("LGFPDIT-7SKNNJL-VJZA4FC-7QNCRKA-CE753K7-2BW5QDK-2FOZ7FR-FEP57QJ")
  26. device4, _ = protocol.DeviceIDFromString("P56IOI7-MZJNU2Y-IQGDREY-DM2MGTI-MGL3BXN-PQ6W5BM-TBBZ4TJ-XZWICQ2")
  27. }
  28. func newDeviceConfiguration(w config.Wrapper, id protocol.DeviceID, name string) config.DeviceConfiguration {
  29. cfg := w.DefaultDevice()
  30. cfg.DeviceID = id
  31. cfg.Name = name
  32. return cfg
  33. }
  34. func initConfig() (config.Wrapper, context.CancelFunc) {
  35. wrapper := config.Wrap("/dev/null", config.New(device1), device1, events.NoopLogger)
  36. dev1Conf = newDeviceConfiguration(wrapper, device1, "device1")
  37. dev2Conf = newDeviceConfiguration(wrapper, device2, "device2")
  38. dev3Conf = newDeviceConfiguration(wrapper, device3, "device3")
  39. dev4Conf = newDeviceConfiguration(wrapper, device4, "device4")
  40. var cancel context.CancelFunc = func() {}
  41. if wrapperService, ok := wrapper.(suture.Service); ok {
  42. var ctx context.Context
  43. ctx, cancel = context.WithCancel(context.Background())
  44. go wrapperService.Serve(ctx)
  45. }
  46. dev2Conf.MaxRecvKbps = rand.Int() % 100000
  47. dev2Conf.MaxSendKbps = rand.Int() % 100000
  48. waiter, _ := wrapper.Modify(func(cfg *config.Configuration) {
  49. cfg.SetDevices([]config.DeviceConfiguration{dev1Conf, dev2Conf, dev3Conf, dev4Conf})
  50. })
  51. waiter.Wait()
  52. return wrapper, cancel
  53. }
  54. func TestLimiterInit(t *testing.T) {
  55. wrapper, wrapperCancel := initConfig()
  56. defer wrapperCancel()
  57. lim := newLimiter(device1, wrapper)
  58. device2ReadLimit := dev2Conf.MaxRecvKbps
  59. device2WriteLimit := dev2Conf.MaxSendKbps
  60. expectedR := map[protocol.DeviceID]*rate.Limiter{
  61. device2: rate.NewLimiter(rate.Limit(device2ReadLimit*1024), limiterBurstSize),
  62. device3: rate.NewLimiter(rate.Inf, limiterBurstSize),
  63. device4: rate.NewLimiter(rate.Inf, limiterBurstSize),
  64. }
  65. expectedW := map[protocol.DeviceID]*rate.Limiter{
  66. device2: rate.NewLimiter(rate.Limit(device2WriteLimit*1024), limiterBurstSize),
  67. device3: rate.NewLimiter(rate.Inf, limiterBurstSize),
  68. device4: rate.NewLimiter(rate.Inf, limiterBurstSize),
  69. }
  70. actualR := lim.deviceReadLimiters
  71. actualW := lim.deviceWriteLimiters
  72. checkActualAndExpected(t, actualR, actualW, expectedR, expectedW)
  73. }
  74. func TestSetDeviceLimits(t *testing.T) {
  75. wrapper, wrapperCancel := initConfig()
  76. defer wrapperCancel()
  77. lim := newLimiter(device1, wrapper)
  78. // should still be inf/inf because this is local device
  79. dev1ReadLimit := rand.Int() % 100000
  80. dev1WriteLimit := rand.Int() % 100000
  81. dev1Conf.MaxRecvKbps = dev1ReadLimit
  82. dev1Conf.MaxSendKbps = dev1WriteLimit
  83. dev2ReadLimit := rand.Int() % 100000
  84. dev2WriteLimit := rand.Int() % 100000
  85. dev2Conf.MaxRecvKbps = dev2ReadLimit
  86. dev2Conf.MaxSendKbps = dev2WriteLimit
  87. dev3ReadLimit := rand.Int() % 10000
  88. dev3Conf.MaxRecvKbps = dev3ReadLimit
  89. waiter, _ := wrapper.Modify(func(cfg *config.Configuration) {
  90. cfg.SetDevices([]config.DeviceConfiguration{dev1Conf, dev2Conf, dev3Conf, dev4Conf})
  91. })
  92. waiter.Wait()
  93. expectedR := map[protocol.DeviceID]*rate.Limiter{
  94. device2: rate.NewLimiter(rate.Limit(dev2ReadLimit*1024), limiterBurstSize),
  95. device3: rate.NewLimiter(rate.Limit(dev3ReadLimit*1024), limiterBurstSize),
  96. device4: rate.NewLimiter(rate.Inf, limiterBurstSize),
  97. }
  98. expectedW := map[protocol.DeviceID]*rate.Limiter{
  99. device2: rate.NewLimiter(rate.Limit(dev2WriteLimit*1024), limiterBurstSize),
  100. device3: rate.NewLimiter(rate.Inf, limiterBurstSize),
  101. device4: rate.NewLimiter(rate.Inf, limiterBurstSize),
  102. }
  103. actualR := lim.deviceReadLimiters
  104. actualW := lim.deviceWriteLimiters
  105. checkActualAndExpected(t, actualR, actualW, expectedR, expectedW)
  106. }
  107. func TestRemoveDevice(t *testing.T) {
  108. wrapper, wrapperCancel := initConfig()
  109. defer wrapperCancel()
  110. lim := newLimiter(device1, wrapper)
  111. waiter, _ := wrapper.RemoveDevice(device3)
  112. waiter.Wait()
  113. expectedR := map[protocol.DeviceID]*rate.Limiter{
  114. device2: rate.NewLimiter(rate.Limit(dev2Conf.MaxRecvKbps*1024), limiterBurstSize),
  115. device4: rate.NewLimiter(rate.Inf, limiterBurstSize),
  116. }
  117. expectedW := map[protocol.DeviceID]*rate.Limiter{
  118. device2: rate.NewLimiter(rate.Limit(dev2Conf.MaxSendKbps*1024), limiterBurstSize),
  119. device4: rate.NewLimiter(rate.Inf, limiterBurstSize),
  120. }
  121. actualR := lim.deviceReadLimiters
  122. actualW := lim.deviceWriteLimiters
  123. checkActualAndExpected(t, actualR, actualW, expectedR, expectedW)
  124. }
  125. func TestAddDevice(t *testing.T) {
  126. wrapper, wrapperCancel := initConfig()
  127. defer wrapperCancel()
  128. lim := newLimiter(device1, wrapper)
  129. addedDevice, _ := protocol.DeviceIDFromString("XZJ4UNS-ENI7QGJ-J45DT6G-QSGML2K-6I4XVOG-NAZ7BF5-2VAOWNT-TFDOMQU")
  130. addDevConf := newDeviceConfiguration(wrapper, addedDevice, "addedDevice")
  131. addDevConf.MaxRecvKbps = 120
  132. addDevConf.MaxSendKbps = 240
  133. waiter, _ := wrapper.Modify(func(cfg *config.Configuration) {
  134. cfg.SetDevice(addDevConf)
  135. })
  136. waiter.Wait()
  137. expectedR := map[protocol.DeviceID]*rate.Limiter{
  138. device2: rate.NewLimiter(rate.Limit(dev2Conf.MaxRecvKbps*1024), limiterBurstSize),
  139. device3: rate.NewLimiter(rate.Inf, limiterBurstSize),
  140. device4: rate.NewLimiter(rate.Inf, limiterBurstSize),
  141. addedDevice: rate.NewLimiter(rate.Limit(addDevConf.MaxRecvKbps*1024), limiterBurstSize),
  142. }
  143. expectedW := map[protocol.DeviceID]*rate.Limiter{
  144. device2: rate.NewLimiter(rate.Limit(dev2Conf.MaxSendKbps*1024), limiterBurstSize),
  145. device3: rate.NewLimiter(rate.Inf, limiterBurstSize),
  146. device4: rate.NewLimiter(rate.Inf, limiterBurstSize),
  147. addedDevice: rate.NewLimiter(rate.Limit(addDevConf.MaxSendKbps*1024), limiterBurstSize),
  148. }
  149. actualR := lim.deviceReadLimiters
  150. actualW := lim.deviceWriteLimiters
  151. checkActualAndExpected(t, actualR, actualW, expectedR, expectedW)
  152. }
  153. func TestAddAndRemove(t *testing.T) {
  154. wrapper, wrapperCancel := initConfig()
  155. defer wrapperCancel()
  156. lim := newLimiter(device1, wrapper)
  157. addedDevice, _ := protocol.DeviceIDFromString("XZJ4UNS-ENI7QGJ-J45DT6G-QSGML2K-6I4XVOG-NAZ7BF5-2VAOWNT-TFDOMQU")
  158. addDevConf := newDeviceConfiguration(wrapper, addedDevice, "addedDevice")
  159. addDevConf.MaxRecvKbps = 120
  160. addDevConf.MaxSendKbps = 240
  161. waiter, _ := wrapper.Modify(func(cfg *config.Configuration) {
  162. cfg.SetDevice(addDevConf)
  163. })
  164. waiter.Wait()
  165. waiter, _ = wrapper.RemoveDevice(device3)
  166. waiter.Wait()
  167. expectedR := map[protocol.DeviceID]*rate.Limiter{
  168. device2: rate.NewLimiter(rate.Limit(dev2Conf.MaxRecvKbps*1024), limiterBurstSize),
  169. device4: rate.NewLimiter(rate.Inf, limiterBurstSize),
  170. addedDevice: rate.NewLimiter(rate.Limit(addDevConf.MaxRecvKbps*1024), limiterBurstSize),
  171. }
  172. expectedW := map[protocol.DeviceID]*rate.Limiter{
  173. device2: rate.NewLimiter(rate.Limit(dev2Conf.MaxSendKbps*1024), limiterBurstSize),
  174. device4: rate.NewLimiter(rate.Inf, limiterBurstSize),
  175. addedDevice: rate.NewLimiter(rate.Limit(addDevConf.MaxSendKbps*1024), limiterBurstSize),
  176. }
  177. actualR := lim.deviceReadLimiters
  178. actualW := lim.deviceWriteLimiters
  179. checkActualAndExpected(t, actualR, actualW, expectedR, expectedW)
  180. }
  181. func TestLimitedWriterWrite(t *testing.T) {
  182. // Check that the limited writer writes the correct data in the correct manner.
  183. // A buffer with random data that is larger than the write size and not
  184. // a precise multiple either.
  185. src := make([]byte, int(12.5*maxSingleWriteSize))
  186. if _, err := crand.Reader.Read(src); err != nil {
  187. t.Fatal(err)
  188. }
  189. // Write it to the destination using a limited writer, with a wrapper to
  190. // count the write calls. The defaults on the limited writer should mean
  191. // it is used (and doesn't take the fast path). In practice the limiter
  192. // won't delay the test as the burst size is large enough to accommodate
  193. // regardless of the rate.
  194. dst := new(bytes.Buffer)
  195. cw := &countingWriter{w: dst}
  196. lw := &limitedWriter{
  197. writer: cw,
  198. waiterHolder: waiterHolder{
  199. waiter: rate.NewLimiter(rate.Limit(42), limiterBurstSize),
  200. limitsLAN: new(atomicBool),
  201. isLAN: false, // enables limiting
  202. },
  203. }
  204. if _, err := io.Copy(lw, bytes.NewReader(src)); err != nil {
  205. t.Fatal(err)
  206. }
  207. // Verify there were lots of writes and that the end result is identical.
  208. if cw.writeCount != 13 {
  209. t.Error("expected lots of smaller writes, but not too many")
  210. }
  211. if !bytes.Equal(src, dst.Bytes()) {
  212. t.Error("results should be equal")
  213. }
  214. // Write it to the destination using a limited writer, with a wrapper to
  215. // count the write calls. Now we make sure the fast path is used.
  216. dst = new(bytes.Buffer)
  217. cw = &countingWriter{w: dst}
  218. lw = &limitedWriter{
  219. writer: cw,
  220. waiterHolder: waiterHolder{
  221. waiter: rate.NewLimiter(rate.Limit(42), limiterBurstSize),
  222. limitsLAN: new(atomicBool),
  223. isLAN: true, // disables limiting
  224. },
  225. }
  226. if _, err := io.Copy(lw, bytes.NewReader(src)); err != nil {
  227. t.Fatal(err)
  228. }
  229. // Verify there were a single write and that the end result is identical.
  230. if cw.writeCount != 1 {
  231. t.Error("expected just the one write")
  232. }
  233. if !bytes.Equal(src, dst.Bytes()) {
  234. t.Error("results should be equal")
  235. }
  236. // Once more, but making sure the fast path is used for an unlimited
  237. // rate, with multiple unlimited raters even (global and per-device).
  238. dst = new(bytes.Buffer)
  239. cw = &countingWriter{w: dst}
  240. lw = &limitedWriter{
  241. writer: cw,
  242. waiterHolder: waiterHolder{
  243. waiter: totalWaiter{rate.NewLimiter(rate.Inf, limiterBurstSize), rate.NewLimiter(rate.Inf, limiterBurstSize)},
  244. limitsLAN: new(atomicBool),
  245. isLAN: false, // enables limiting
  246. },
  247. }
  248. if _, err := io.Copy(lw, bytes.NewReader(src)); err != nil {
  249. t.Fatal(err)
  250. }
  251. // Verify there were a single write and that the end result is identical.
  252. if cw.writeCount != 1 {
  253. t.Error("expected just the one write")
  254. }
  255. if !bytes.Equal(src, dst.Bytes()) {
  256. t.Error("results should be equal")
  257. }
  258. // Once more, but making sure we *don't* take the fast path when there
  259. // is a combo of limited and unlimited writers.
  260. dst = new(bytes.Buffer)
  261. cw = &countingWriter{w: dst}
  262. lw = &limitedWriter{
  263. writer: cw,
  264. waiterHolder: waiterHolder{
  265. waiter: totalWaiter{
  266. rate.NewLimiter(rate.Inf, limiterBurstSize),
  267. rate.NewLimiter(rate.Limit(42), limiterBurstSize),
  268. rate.NewLimiter(rate.Inf, limiterBurstSize),
  269. },
  270. limitsLAN: new(atomicBool),
  271. isLAN: false, // enables limiting
  272. },
  273. }
  274. if _, err := io.Copy(lw, bytes.NewReader(src)); err != nil {
  275. t.Fatal(err)
  276. }
  277. // Verify there were lots of writes and that the end result is identical.
  278. if cw.writeCount != 13 {
  279. t.Error("expected just the one write")
  280. }
  281. if !bytes.Equal(src, dst.Bytes()) {
  282. t.Error("results should be equal")
  283. }
  284. }
  285. func TestTotalWaiterLimit(t *testing.T) {
  286. cases := []struct {
  287. w waiter
  288. r rate.Limit
  289. }{
  290. {
  291. totalWaiter{},
  292. rate.Inf,
  293. },
  294. {
  295. totalWaiter{rate.NewLimiter(rate.Inf, 42)},
  296. rate.Inf,
  297. },
  298. {
  299. totalWaiter{rate.NewLimiter(rate.Inf, 42), rate.NewLimiter(rate.Inf, 42)},
  300. rate.Inf,
  301. },
  302. {
  303. totalWaiter{rate.NewLimiter(rate.Inf, 42), rate.NewLimiter(rate.Limit(12), 42), rate.NewLimiter(rate.Limit(15), 42)},
  304. rate.Limit(12),
  305. },
  306. }
  307. for _, tc := range cases {
  308. l := tc.w.Limit()
  309. if l != tc.r {
  310. t.Error("incorrect limit returned")
  311. }
  312. }
  313. }
  314. func checkActualAndExpected(t *testing.T, actualR, actualW, expectedR, expectedW map[protocol.DeviceID]*rate.Limiter) {
  315. t.Helper()
  316. if len(expectedW) != len(actualW) || len(expectedR) != len(actualR) {
  317. t.Errorf("Map lengths differ!")
  318. }
  319. for key, val := range expectedR {
  320. if _, ok := actualR[key]; !ok {
  321. t.Errorf("Device %s not found in limiter", key)
  322. }
  323. if val.Limit() != actualR[key].Limit() {
  324. t.Errorf("Read limits for device %s differ actual: %f, expected: %f", key, actualR[key].Limit(), val.Limit())
  325. }
  326. if expectedW[key].Limit() != actualW[key].Limit() {
  327. t.Errorf("Write limits for device %s differ actual: %f, expected: %f", key, actualW[key].Limit(), expectedW[key].Limit())
  328. }
  329. }
  330. }
  331. type countingWriter struct {
  332. w io.Writer
  333. writeCount int
  334. }
  335. func (w *countingWriter) Write(data []byte) (int, error) {
  336. w.writeCount++
  337. return w.w.Write(data)
  338. }