test_docker.py 8.48 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 37
import pkg_resources

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

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

# 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)


54 55
class AsyncTest(unittest.TestCase):

56 57
  @classmethod
  def setUpClass(cls):
58
    cls.host = Host()
59
    cls.host.setup()
60 61


62 63 64
  @classmethod
  def tearDownClass(cls):
    cls.host.teardown()
65 66 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 116 117 118 119 120 121 122 123 124


  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:
      status = p.wait(1) #should not timeout
      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):

125
    with Popen(self.host, 'environment (1)', ['python', '-c', '; '.join([
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
      "print('Before')",
      "import sys; sys.stdout.flush()",
      "d = '0' * (10 * 1024 * 1024)",
      "import time; time.sleep(3)",
      "print('After')",
      ]),
      ], name='memory_limit', virtual_memory_in_megabytes=10) as p:

      #stats = p.statistics()
      #print stats['memory']
      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):

147
    with Popen(self.host, 'environment (1)', ['python', '-c', '; '.join([
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
      "print('Before')",
      "import sys; sys.stdout.flush()",
      "d = '0' * (10 * 1024 * 1024)",
      "import time; time.sleep(3)",
      "print('After')",
      ]),
      ], name='memory_limit2', virtual_memory_in_megabytes=100) as p:

      stats = p.statistics()
      assert stats['memory']['percent'] < 15 and stats['memory']['percent'] > 10
      status = p.wait()
      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
172
    with Popen(self.host, 'environment (1)', ['python', '-c', '; '.join([
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
      "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
195
    with Popen(self.host, 'environment (1)', ['python', '-c', '; '.join([
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
      "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
218
    with Popen(self.host, 'environment (1)', ['python', '-c', '; '.join([
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
      "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))

248
    with Popen(self.host, 'environment (1)', ['python', tmp_name,
249 250 251 252 253 254 255 256 257 258
        str(processes)], max_cpu_percent=max_cpu_percent,
        tmp_archive=program) as p:

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

259 260 261
      # make sure nothing is there anymore
      p.kill()
      self.assertEqual(p.wait(), 137)
262 263 264 265 266 267 268 269 270 271

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


  def test_cpulimit_at_20percent(self):
    self._run_cpulimit(1, 20, 3)


  def test_cpulimit_at_100percent(self):
    self._run_cpulimit(4, 100, 3)