limiter_test.go 12 KB

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