test_worker.py 12.2 KB
Newer Older
Philip ABBET's avatar
Philip ABBET 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

###############################################################################
#                                                                             #
# Copyright (c) 2017 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/.           #
#                                                                             #
###############################################################################


# Tests for experiment execution

import os
import logging
logger = logging.getLogger(__name__)

import gevent

from gevent import monkey
monkey.patch_socket(dns=False)
monkey.patch_ssl()

import unittest
import simplejson
from time import time

from ..scripts import worker
from ..worker import WorkerController
from ..dock import Host

from . import prefix, tmp_prefix


WORKER1 = 'worker1'
WORKER2 = 'worker2'


CONFIGURATION1 = {
  'queue': 'queue',
  'inputs': {
    'in_data': {
      'set': 'double',
      'protocol': 'double',
      'database': 'integers_db/1',
      'output': 'a',
      'path': 'ec/89/e5/6e161d2cb012ef6ac8acf59bf453a6328766f90dc9baba9eb14ea23c55',
      'endpoint': 'a',
      'hash': 'ec89e56e161d2cb012ef6ac8acf59bf453a6328766f90dc9baba9eb14ea23c55',
      'channel': 'integers'
    }
  },
  'algorithm': 'user/integers_echo/1',
  'parameters': {},
  'environment': {
    'name': 'Python 2.7',
    'version': '1.1.0'
  },
  'outputs': {
    'out_data': {
      'path': '20/61/b6/2df3c3bedd5366f4a625c5d87ffbf5a26007c46c456e9abf21b46c6681',
      'endpoint': 'out_data',
      'hash': '2061b62df3c3bedd5366f4a625c5d87ffbf5a26007c46c456e9abf21b46c6681',
      'channel': 'integers'
    }
  },
  'nb_slots': 1,
  'channel': 'integers'
}


CONFIGURATION2 = {
  'queue': 'queue',
  'inputs': {
    'in_data': {
      'set': 'double',
      'protocol': 'double',
      'database': 'integers_db/1',
      'output': 'a',
      'path': 'ec/89/e5/6e161d2cb012ef6ac8acf59bf453a6328766f90dc9baba9eb14ea23c55',
      'endpoint': 'a',
      'hash': 'ec89e56e161d2cb012ef6ac8acf59bf453a6328766f90dc9baba9eb14ea23c55',
      'channel': 'integers'
    }
  },
  'algorithm': 'user/integers_echo/1',
  'parameters': {},
  'environment': {
    'name': 'Python 2.7',
    'version': '1.1.0'
  },
  'outputs': {
    'out_data': {
      'path': '40/61/b6/2df3c3bedd5366f4a625c5d87ffbf5a26007c46c456e9abf21b46c6681',
      'endpoint': 'out_data',
      'hash': '4061b62df3c3bedd5366f4a625c5d87ffbf5a26007c46c456e9abf21b46c6681',
      'channel': 'integers'
    }
  },
  'nb_slots': 1,
  'channel': 'integers'
}



class WorkerThread(gevent.Greenlet):

  def __init__(self, arguments):
    super(WorkerThread, self).__init__()

    self.arguments = arguments


  def _run(self):
    worker.main(self.arguments)



class TestOneWorker(unittest.TestCase):

  def __init__(self, methodName='runTest'):
    super(TestOneWorker, self).__init__(methodName)
    self.controller = None
    self.worker_thread = None
    self.docker = False


  def setUp(self):
    self.tearDown()   # In case another test failed badly during its setUp()

    self.controller = WorkerController('127.0.0.1', port=None)

    args = [
        '--prefix=%s' % prefix,
        '--cache=%s' % tmp_prefix,
        '--name=%s' % WORKER1,
        self.controller.address,
    ]

    if self.docker:
      args.insert(3, '--docker')

    self.worker_thread = WorkerThread(args)

    self.worker_thread.start()

    start = time()
    while len(self.controller.workers) == 0:
      self.assertTrue(self.controller.process(100) is None)
      self.assertTrue(time() - start < 10)  # Exit after 10 seconds

    self.assertEqual(len(self.controller.workers), 1)
    self.assertTrue(WORKER1 in self.controller.workers)


  def tearDown(self):
    if self.worker_thread is not None:
      self.worker_thread.kill()
      self.worker_thread = None

    if self.controller is not None:
      self.controller.destroy()
      self.controller = None


  def _wait(self, max=100):
    message = None
    nb = 0

    while (message is None) and (nb < max):
      message = self.controller.process(100)
      nb += 1

    return message


  def _check_done(self, message, expected_worker, expected_job_id):
    self.assertTrue(message is not None)

    (worker, status, job_id, data) = message

    self.assertEqual(worker, expected_worker)
    self.assertEqual(status, WorkerController.DONE)
    self.assertEqual(job_id, expected_job_id)

    result = simplejson.loads(data[0])

    self.assertEqual(result['status'], 0)


  def test_success(self):
    self.controller.execute(WORKER1, 1, CONFIGURATION1)

    message = self._wait()

    self._check_done(message, WORKER1, 1)


  def test_processing_error(self):
    config = dict(CONFIGURATION1)
    config['algorithm'] = 'user/integers_crash/1'

    self.controller.execute(WORKER1, 1, config)

    (worker, status, job_id, data) = self._wait()

    self.assertEqual(worker, WORKER1)
    self.assertEqual(status, WorkerController.DONE)
    self.assertEqual(job_id, 1)

    result = simplejson.loads(data[0])

    self.assertEqual(result['status'], 1)
    self.assertTrue('a = b' in result['user_error'])


  def test_error_unknown_algorithm(self):
    config = dict(CONFIGURATION1)
    config['algorithm'] = 'user/unknown/1'

    self.controller.execute(WORKER1, 1, config)

    (worker, status, job_id, data) = self._wait()

    self.assertEqual(worker, WORKER1)
    self.assertEqual(status, WorkerController.JOB_ERROR)
    self.assertEqual(job_id, 1)
    self.assertTrue(len(data) > 0)


  def test_error_syntax_error(self):
    config = dict(CONFIGURATION1)
    config['algorithm'] = 'user/syntax_error/1'

    self.controller.execute(WORKER1, 1, config)

    (worker, status, job_id, data) = self._wait()

    self.assertEqual(worker, WORKER1)
    self.assertEqual(status, WorkerController.JOB_ERROR)
    self.assertEqual(job_id, 1)
    self.assertTrue(len(data) > 0)


  def test_worker_shutdown(self):
    worker.stop = True

    self.assertTrue(self.controller.process(2000) is None)
    self.assertEqual(len(self.controller.workers), 0)

    worker.stop = False


  def test_error_busy(self):
    config = dict(CONFIGURATION1)
    config['algorithm'] = 'user/integers_echo_slow/1'

    self.controller.execute(WORKER1, 1, config)
    self.controller.execute(WORKER1, 2, config)

    (worker, status, job_id, data) = self._wait()

    self.assertEqual(worker, WORKER1)
    self.assertEqual(status, WorkerController.JOB_ERROR)
    self.assertEqual(job_id, 2)
    self.assertEqual(data[0], 'Worker is already busy')

    message = self._wait()

    self._check_done(message, WORKER1, 1)


  def test_reuse(self):
    self.controller.execute(WORKER1, 1, CONFIGURATION1)
    message = self._wait()
    self._check_done(message, WORKER1, 1)

    self.controller.execute(WORKER1, 2, CONFIGURATION1)
    message = self._wait()
    self._check_done(message, WORKER1, 2)


  def test_cancel(self):
    config = dict(CONFIGURATION1)
    config['algorithm'] = 'user/integers_echo_slow/1'

    self.controller.execute(WORKER1, 1, config)
    self.controller.cancel(WORKER1)

    (worker, status, job_id, data) = self._wait()

    self.assertEqual(worker, WORKER1)
    self.assertEqual(status, WorkerController.CANCELLED)
    self.assertEqual(job_id, 1)
    self.assertEqual(len(data), 0)


  def test_error_cancel_free_worker(self):
    self.controller.cancel(WORKER1)

    (worker, status, job_id, data) = self._wait()

    self.assertEqual(worker, WORKER1)
    self.assertEqual(status, WorkerController.ERROR)
    self.assertTrue(job_id is None)
    self.assertEqual(data[0], "Worker isn't busy")



class TestOneWorkerDocker(TestOneWorker):

  def __init__(self, methodName='runTest'):
    super(TestOneWorkerDocker, self).__init__(methodName)
    self.docker = True


  @classmethod
  def setUpClass(cls):
    cls.host = Host(raise_on_errors=False)



class TestTwoWorkers(unittest.TestCase):

  def __init__(self, methodName='runTest'):
    super(TestTwoWorkers, self).__init__(methodName)
    self.controller = None
    self.worker_threads = None
    self.docker = False


  def setUp(self):
    self.tearDown()   # In case another test failed badly during its setUp()

    self.controller = WorkerController('127.0.0.1', port=None)

    self.worker_threads = []

    for name in [ WORKER1, WORKER2 ]:
      args = [
          '--prefix=%s' % prefix,
          '--cache=%s' % tmp_prefix,
          '--name=%s' % name,
          self.controller.address,
      ]

      if self.docker:
        args.insert(3, '--docker')

      worker_thread = WorkerThread(args)

      worker_thread.start()

      self.worker_threads.append(worker_thread)

    start = time()
    while len(self.controller.workers) < 2:
      self.assertTrue(self.controller.process(100) is None)
      self.assertTrue(time() - start < 10)  # Exit after 10 seconds

    self.assertTrue(WORKER1 in self.controller.workers)
    self.assertTrue(WORKER2 in self.controller.workers)


  def tearDown(self):
    if self.worker_threads is not None:
      for worker_thread in self.worker_threads:
        worker_thread.kill()
      self.worker_threads = None

    if self.controller is not None:
      self.controller.destroy()
      self.controller = None


  def _test_success_one_worker(self, worker_name):
    self.controller.execute(worker_name, 1, CONFIGURATION1)

    message = None
    while message is None:
      message = self.controller.process(100)

    (worker, status, job_id, data) = message

    self.assertEqual(worker, worker_name)
    self.assertEqual(status, WorkerController.DONE)
    self.assertEqual(job_id, 1)

    result = simplejson.loads(data[0])

    self.assertEqual(result['status'], 0)


  def test_success_worker1(self):
    self._test_success_one_worker(WORKER1)


  def test_success_worker2(self):
    self._test_success_one_worker(WORKER2)


  def test_success_both_workers(self):
    def _check(worker, status, job_id, data):
      self.assertEqual(status, WorkerController.DONE)

      if worker == WORKER1:
        self.assertEqual(job_id, 1)
      else:
        self.assertEqual(worker, WORKER2)
        self.assertEqual(job_id, 2)

      result = simplejson.loads(data[0])
      self.assertEqual(result['status'], 0)


    self.controller.execute(WORKER1, 1, CONFIGURATION1)
    self.controller.execute(WORKER2, 2, CONFIGURATION2)

    message = None
    while message is None:
      message = self.controller.process(100)

    (worker1, status, job_id, data) = message
    _check(worker1, status, job_id, data)

    message = None
    while message is None:
      message = self.controller.process(100)

    (worker2, status, job_id, data) = message
    _check(worker2, status, job_id, data)

    self.assertNotEqual(worker1, worker2)



class TestTwoWorkersDocker(TestTwoWorkers):

  def __init__(self, methodName='runTest'):
    super(TestTwoWorkersDocker, self).__init__(methodName)
    self.docker = True


  @classmethod
  def setUpClass(cls):
    cls.host = Host(raise_on_errors=False)