test_leak.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. from __future__ import print_function, unicode_literals
  2. import gc
  3. import os
  4. import sys
  5. import shlex
  6. import subprocess
  7. from celery import current_app
  8. from celery.five import range
  9. from celery.tests.case import SkipTest, unittest
  10. import suite # noqa
  11. GET_RSIZE = b'/bin/ps -p {pid} -o rss='
  12. class Sizes(list):
  13. def add(self, item):
  14. if item not in self:
  15. self.append(item)
  16. def average(self):
  17. return sum(self) / len(self)
  18. class LeakFunCase(unittest.TestCase):
  19. def setUp(self):
  20. self.app = current_app
  21. self.debug = os.environ.get('TEST_LEAK_DEBUG', False)
  22. def get_rsize(self, cmd=GET_RSIZE):
  23. try:
  24. return int(subprocess.Popen(
  25. shlex.split(cmd.format(pid=os.getpid())),
  26. stdout=subprocess.PIPE).communicate()[0].strip()
  27. )
  28. except OSError as exc:
  29. raise SkipTest(
  30. 'Cannot execute command: {0!r}: {1!r}'.format(cmd, exc))
  31. def sample_allocated(self, fun, *args, **kwargs):
  32. before = self.get_rsize()
  33. fun(*args, **kwargs)
  34. gc.collect()
  35. after = self.get_rsize()
  36. return before, after
  37. def appx(self, s, r=1):
  38. """r==1 (10e1): Keep up to hundred kB,
  39. e.g. 16,268MB becomes 16,2MB."""
  40. return int(s / 10.0 ** (r + 1)) / 10.0
  41. def assertFreed(self, n, fun, *args, **kwargs):
  42. # call function first to load lazy modules etc.
  43. fun(*args, **kwargs)
  44. try:
  45. base = self.get_rsize()
  46. first = None
  47. sizes = Sizes()
  48. for i in range(n):
  49. before, after = self.sample_allocated(fun, *args, **kwargs)
  50. if not first:
  51. first = after
  52. if self.debug:
  53. print('{0!r} {1}: before/after: {2}/{3}'.format(
  54. fun, i, before, after))
  55. else:
  56. sys.stderr.write('.')
  57. sizes.add(self.appx(after))
  58. self.assertEqual(gc.collect(), 0)
  59. self.assertEqual(gc.garbage, [])
  60. try:
  61. assert self.appx(first) >= self.appx(after)
  62. except AssertionError:
  63. print('BASE: {0!r} AVG: {1!r} SIZES: {2!r}'.format(
  64. base, sizes.average(), sizes))
  65. raise
  66. finally:
  67. self.app.control.purge()
  68. class test_leaks(LeakFunCase):
  69. def test_task_apply_leak(self, its=1000):
  70. self.assertNotEqual(self.app.conf.BROKER_TRANSPORT, 'memory')
  71. @self.app.task
  72. def task1():
  73. pass
  74. try:
  75. pool_limit = self.app.conf.BROKER_POOL_LIMIT
  76. except AttributeError:
  77. return self.assertFreed(self.iterations, task1.delay)
  78. self.app.conf.BROKER_POOL_LIMIT = None
  79. try:
  80. self.app._pool = None
  81. self.assertFreed(its, task1.delay)
  82. finally:
  83. self.app.conf.BROKER_POOL_LIMIT = pool_limit
  84. def test_task_apply_leak_with_pool(self, its=1000):
  85. self.assertNotEqual(self.app.conf.BROKER_TRANSPORT, 'memory')
  86. @self.app.task
  87. def task2():
  88. pass
  89. try:
  90. pool_limit = self.app.conf.BROKER_POOL_LIMIT
  91. except AttributeError:
  92. raise SkipTest('This version does not support autopool')
  93. self.app.conf.BROKER_POOL_LIMIT = 10
  94. try:
  95. self.app._pool = None
  96. self.assertFreed(its, task2.delay)
  97. finally:
  98. self.app.conf.BROKER_POOL_LIMIT = pool_limit
  99. if __name__ == '__main__':
  100. unittest.main()