test_docker.py 10.2 KB
Newer Older
André Anjos's avatar
André Anjos committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

###############################################################################
#                                                                             #
# Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.core module of the BEAT platform.             #
#                                                                             #
# Commercial License Usage                                                    #
# Licensees holding valid commercial BEAT licenses may use this file in       #
# accordance with the terms contained in a written agreement between you      #
# and Idiap. For further information contact tto@idiap.ch                     #
#                                                                             #
# Alternatively, this file may be used under the terms of the GNU Affero      #
# Public License version 3 as published by the Free Software and appearing    #
# in the file LICENSE.AGPL included in the packaging of this file.            #
# The BEAT platform is distributed in the hope that it will be useful, but    #
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY  #
# or FITNESS FOR A PARTICULAR PURPOSE.                                        #
#                                                                             #
# You should have received a copy of the GNU Affero Public License along      #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
#                                                                             #
###############################################################################


"""Asynchronous process I/O with the Subprocess module
"""

import os
import sys
import time
35
import unittest
André Anjos's avatar
André Anjos committed
36
import pkg_resources
37
import time
André Anjos's avatar
André Anjos committed
38

39 40
import docker
import requests
André Anjos's avatar
André Anjos committed
41

42
from ..dock import Popen, Host
43
from . import tmp_prefix
André Anjos's avatar
André Anjos committed
44 45 46 47 48 49 50 51 52 53 54 55

# in case you want to see the printouts dynamically, set to ``True``
if False:
  import logging
  logger = logging.getLogger() #root logger
  logger.setLevel(logging.DEBUG)
  ch = logging.StreamHandler()
  ch.setLevel(logging.DEBUG)
  ch.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
  logger.addHandler(ch)


56 57
class AsyncTest(unittest.TestCase):

58 59
  @classmethod
  def setUpClass(cls):
60
    cls.host = Host()
61
    cls.host.setup(raise_on_errors=False)
62 63


64 65 66
  @classmethod
  def tearDownClass(cls):
    cls.host.teardown()
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115


  def test_echo(self):

    string = "hello, world"
    with Popen(self.host, 'debian:8.4', ["echo", string]) as p:
      status = p.wait()
      self.assertEqual(status, 0)
      self.assertEqual(p.stdout, string + '\n')
      self.assertEqual(p.stderr, '')

    assert not self.host.containers #all containers are gone


  def test_non_existing(self):

    self.assertRaises(docker.errors.NotFound, Popen,
      self.host, 'debian:8.4', ["sdfsdfdsf329909092"])

    self.host.teardown()

    assert not self.host.containers #all containers are gone


  def test_timeout(self):

    sleep_for = 100 # seconds
    with Popen(self.host, 'debian:8.4', ["sleep", str(sleep_for)]) as p:

      try:
        retval = p.wait(timeout=0.5)
        assert False, "timeout never occurred after %d seconds" % sleep_for
      except requests.exceptions.ReadTimeout as e:
        self.assertEqual(p.status(), 'running')

      p.kill()
      status = p.wait()
      self.assertEqual(p.status(), 'exited')
      self.assertEqual(status, 137)
      self.assertEqual(p.stdout, '')
      self.assertEqual(p.stderr, '')

    assert not self.host.containers #all containers are gone


  def test_does_not_timeout(self):

    sleep_for = 0.5 # seconds
    with Popen(self.host, 'debian:8.4', ["sleep", str(sleep_for)]) as p:
116
      status = p.wait(5) #should not timeout
117 118 119 120 121 122 123 124 125 126
      self.assertEqual(p.status(), 'exited')
      self.assertEqual(status, 0)
      self.assertEqual(p.stdout, '')
      self.assertEqual(p.stderr, '')

    assert not self.host.containers #all containers are gone


  def test_memory_limit(self):

127
    with Popen(self.host, 'Python 2.7 (1.1.0)', ['python', '-c', '; '.join([
128 129 130
      "print('Before')",
      "import sys; sys.stdout.flush()",
      "d = '0' * (10 * 1024 * 1024)",
131
      "import time; time.sleep(5)",
132 133
      "print('After')",
      ]),
134
      ], virtual_memory_in_megabytes=4) as p:
135

136 137
      time.sleep(2)
      stats = p.statistics()
138 139 140 141 142 143 144 145 146 147 148
      status = p.wait()
      self.assertEqual(p.status(), 'exited')
      self.assertEqual(status, 137)
      self.assertEqual(p.stdout.strip(), 'Before')
      self.assertEqual(p.stderr, '')

    assert not self.host.containers #all containers are gone


  def test_memory_limit2(self):

149
    with Popen(self.host, 'Python 2.7 (1.1.0)', ['python', '-c', '; '.join([
150 151 152
      "print('Before')",
      "import sys; sys.stdout.flush()",
      "d = '0' * (10 * 1024 * 1024)",
153
      "import time; time.sleep(5)",
154 155
      "print('After')",
      ]),
156
      ], virtual_memory_in_megabytes=100) as p:
157

158
      time.sleep(2)
159 160
      stats = p.statistics()
      status = p.wait()
161 162 163 164
      assert stats['memory']['percent'] > 10, 'Memory check failed, ' \
          '%d%% <= 10%%' % stats['memory']['percent']
      assert stats['memory']['percent'] < 15, 'Memory check failed, ' \
          '%d%% >= 15%%' % stats['memory']['percent']
165 166 167 168 169 170 171 172 173 174 175 176 177
      self.assertEqual(p.status(), 'exited')
      self.assertEqual(status, 0)
      self.assertEqual(p.stdout.strip(), 'Before\nAfter')
      self.assertEqual(p.stderr, '')

    assert not self.host.containers #all containers are gone


  def notest_limit_stdout(self):

    # disabled: we limit the maximum output to 1M internally

    size = 2**16 #bytes
178
    with Popen(self.host, 'Python 2.7 (1.1.0)', ['python', '-c', '; '.join([
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
      "import sys",
      "for i in range(%d): sys.stdout.write('%%d\n' %% i)" % size,
      "sys.stdout.flush()",
      ]),
      ], buflen=size) as p:

      status = p.wait()
      self.assertEqual(status, 0)
      data = p.stdout
      self.assertEqual(len(data), size)
      expected = str(size-1)
      assert data.rstrip().endswith(expected)
      self.assertEqual(p.stderr, '')

    assert not self.host.containers #all containers are gone


  def notest_limit_stderr(self):

    # disabled: we limit the maximum output to 1M internally

    size = 2**16 #bytes
201
    with Popen(self.host, 'Python 2.7 (1.1.0)', ['python', '-c', '; '.join([
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
      "import sys",
      "for i in range(%d): sys.stderr.write('%%d\n' %% i)" % size,
      "sys.stderr.flush()",
      ]),
      ], buflen=size) as p:

      status = p.wait()
      self.assertEqual(status, 0)
      data = p.stderr
      self.assertEqual(len(data), size)
      expected = str(size-1)
      assert data.rstrip().endswith(expected)
      self.assertEqual(p.stdout, '')

    assert not self.host.containers #all containers are gone


  def notest_limit_both(self):

    # disabled: we limit the maximum output to 1M internally

    size = 2**16 #bytes
224
    with Popen(self.host, 'Python 2.7 (1.1.0)', ['python', '-c', '; '.join([
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
      "import sys",
      "for i in range(%d): sys.stdout.write('%%d\n' %% i)" % size,
      "sys.stdout.flush()",
      "for i in range(%d): sys.stderr.write('%%d\n' %% i)" % size,
      "sys.stderr.flush()",
      ]),
      ], buflen=size) as p:

      status = p.wait()
      self.assertEqual(status, 0)

      data = p.stdout
      self.assertEqual(len(data), size)
      expected = str(size-1)
      assert data.rstrip().endswith(expected)

      data = p.stderr
      self.assertEqual(len(data), size)
      expected = str(size-1)
      assert data.rstrip().endswith(expected)

    assert not self.host.containers #all containers are gone


  def _run_cpulimit(self, processes, max_cpu_percent, sleep_time):

    program = pkg_resources.resource_filename(__name__, 'cpu_stress.py')
    tmp_name = os.path.join('/tmp', os.path.basename(program))

254
    with Popen(self.host, 'Python 2.7 (1.1.0)', ['python', tmp_name,
255
        str(processes)], max_cpu_percent=max_cpu_percent,
256
        configuration_path=program) as p:
257 258 259 260 261 262

      p.statistics() # start recording
      time.sleep(sleep_time)
      stats = p.statistics()
      self.assertEqual(p.status(), 'running')
      percent = stats['cpu']['percent']
263
      assert percent < (1.1*max_cpu_percent), "%.2f%% is more than 20%% off the expected ceiling at %d%%!" % (percent, max_cpu_percent)
264

265 266 267
      # make sure nothing is there anymore
      p.kill()
      self.assertEqual(p.wait(), 137)
268 269 270 271 272

    assert not self.host.containers #all containers are gone


  def test_cpulimit_at_20percent(self):
273
    # runs 1 process that should consume at most 20% of the host CPU
274 275 276 277
    self._run_cpulimit(1, 20, 3)


  def test_cpulimit_at_100percent(self):
278
    # runs 4 processes that should consume 50% of the host CPU
279
    self._run_cpulimit(4, 100, 3)
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350



class HostTest(unittest.TestCase):

  def setUp(self):
    Host.images_cache = {}


  def test_images_cache(self):
    self.assertEqual(len(Host.images_cache), 0)

    # Might take some time
    start = time.time()

    host = Host()
    host.setup(raise_on_errors=False)
    host.teardown()

    stop = time.time()

    nb_images = len(Host.images_cache)
    self.assertTrue(nb_images > 0)

    self.assertTrue(stop - start > 2.0)

    # Should be instantaneous
    start = time.time()

    host = Host()
    host.setup(raise_on_errors=False)
    host.teardown()

    stop = time.time()

    self.assertEqual(len(Host.images_cache), nb_images)

    self.assertTrue(stop - start < 1.0)


  def test_images_cache_file(self):
    self.assertEqual(len(Host.images_cache), 0)

    # Might take some time
    start = time.time()

    host = Host(images_cache=os.path.join(tmp_prefix, 'images_cache.json'))
    host.setup(raise_on_errors=False)
    host.teardown()

    stop = time.time()

    nb_images = len(Host.images_cache)
    self.assertTrue(nb_images > 0)

    self.assertTrue(stop - start > 2.0)

    Host.images_cache = {}

    # Should be instantaneous
    start = time.time()

    host = Host(images_cache=os.path.join(tmp_prefix, 'images_cache.json'))
    host.setup(raise_on_errors=False)
    host.teardown()

    stop = time.time()

    self.assertEqual(len(Host.images_cache), nb_images)

    self.assertTrue(stop - start < 1.0)