test_worker.py 13.7 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
#!/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
Philip ABBET's avatar
Philip ABBET committed
32

Philip ABBET's avatar
Philip ABBET committed
33
34
35
36
37
import logging
logger = logging.getLogger(__name__)

import unittest
import simplejson
Philip ABBET's avatar
Philip ABBET committed
38
import multiprocessing
Philip ABBET's avatar
Philip ABBET committed
39
40
41
42
43
44
45
46
47
from time import time

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

from . import prefix, tmp_prefix


Philip ABBET's avatar
Philip ABBET committed
48
49
50
#----------------------------------------------------------


Philip ABBET's avatar
Philip ABBET committed
51
52
53
54
WORKER1 = 'worker1'
WORKER2 = 'worker2'


Philip ABBET's avatar
Philip ABBET committed
55
56
57
#----------------------------------------------------------


Philip ABBET's avatar
Philip ABBET committed
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
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'
}


Philip ABBET's avatar
Philip ABBET committed
91
92
93
#----------------------------------------------------------


Philip ABBET's avatar
Philip ABBET committed
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
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'
}


Philip ABBET's avatar
Philip ABBET committed
127
128
#----------------------------------------------------------

Philip ABBET's avatar
Philip ABBET committed
129

Philip ABBET's avatar
Philip ABBET committed
130
class WorkerProcess(multiprocessing.Process):
Philip ABBET's avatar
Philip ABBET committed
131

Philip ABBET's avatar
Philip ABBET committed
132
133
  def __init__(self, queue, arguments):
    super(WorkerProcess, self).__init__()
Philip ABBET's avatar
Philip ABBET committed
134

Philip ABBET's avatar
Philip ABBET committed
135
    self.queue = queue
Philip ABBET's avatar
Philip ABBET committed
136
137
138
    self.arguments = arguments


Philip ABBET's avatar
Philip ABBET committed
139
140
  def run(self):
    self.queue.put('STARTED')
Philip ABBET's avatar
Philip ABBET committed
141
142
143
    worker.main(self.arguments)


Philip ABBET's avatar
Philip ABBET committed
144
145
#----------------------------------------------------------

Philip ABBET's avatar
Philip ABBET committed
146
147
148
149
150
151

class TestOneWorker(unittest.TestCase):

  def __init__(self, methodName='runTest'):
    super(TestOneWorker, self).__init__(methodName)
    self.controller = None
Philip ABBET's avatar
Philip ABBET committed
152
    self.worker_process = None
Philip ABBET's avatar
Philip ABBET committed
153
154
155
156
157
158
    self.docker = False


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

Philip ABBET's avatar
Philip ABBET committed
159
160
161
162
163
164
165
166
167
168
169
170
    connected_workers = []

    def onWorkerReady(name):
      connected_workers.append(name)

    self.controller = WorkerController(
      '127.0.0.1',
      port=None,
      callbacks=dict(
        onWorkerReady = onWorkerReady,
      )
    )
Philip ABBET's avatar
Philip ABBET committed
171
172

    args = [
Philip ABBET's avatar
Philip ABBET committed
173
174
175
176
      '--prefix=%s' % prefix,
      '--cache=%s' % tmp_prefix,
      '--name=%s' % WORKER1,
      self.controller.address,
Philip ABBET's avatar
Philip ABBET committed
177
178
179
180
181
    ]

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

Philip ABBET's avatar
Philip ABBET committed
182
183
    self.worker_process = WorkerProcess(multiprocessing.Queue(), args)
    self.worker_process.start()
Philip ABBET's avatar
Philip ABBET committed
184

Philip ABBET's avatar
Philip ABBET committed
185
    self.worker_process.queue.get()
Philip ABBET's avatar
Philip ABBET committed
186
187
188
189
190
191
192
193
194

    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)

Philip ABBET's avatar
Philip ABBET committed
195
196
197
    self.assertEqual(len(connected_workers), 1)
    self.assertTrue(WORKER1 in connected_workers)

Philip ABBET's avatar
Philip ABBET committed
198
199

  def tearDown(self):
Philip ABBET's avatar
Philip ABBET committed
200
    self.stop_worker()
Philip ABBET's avatar
Philip ABBET committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217

    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


Philip ABBET's avatar
Philip ABBET committed
218
219
220
221
222
223
224
  def stop_worker(self):
    if self.worker_process is not None:
      self.worker_process.terminate()
      self.worker_process.join()
      self.worker_process = None


Philip ABBET's avatar
Philip ABBET committed
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
  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):
Philip ABBET's avatar
Philip ABBET committed
294
295
296
297
298
299
300
301
    did_shutdown = True

    def onWorkerGone(name):
      did_shutdown = (name == WORKER1)

    self.controller.callbacks.onWorkerGone = onWorkerGone

    self.stop_worker()
Philip ABBET's avatar
Philip ABBET committed
302
303
304

    self.assertTrue(self.controller.process(2000) is None)
    self.assertEqual(len(self.controller.workers), 0)
Philip ABBET's avatar
Philip ABBET committed
305
    self.assertTrue(did_shutdown)
Philip ABBET's avatar
Philip ABBET committed
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


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


Philip ABBET's avatar
Philip ABBET committed
363
364
#----------------------------------------------------------

Philip ABBET's avatar
Philip ABBET committed
365
366
367
368
369
370
371
372
373
374
375
376
377

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)


Philip ABBET's avatar
Philip ABBET committed
378
379
#----------------------------------------------------------

Philip ABBET's avatar
Philip ABBET committed
380
381
382
383
384
385

class TestTwoWorkers(unittest.TestCase):

  def __init__(self, methodName='runTest'):
    super(TestTwoWorkers, self).__init__(methodName)
    self.controller = None
Philip ABBET's avatar
Philip ABBET committed
386
    self.worker_processes = None
Philip ABBET's avatar
Philip ABBET committed
387
388
389
390
391
392
    self.docker = False


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

Philip ABBET's avatar
Philip ABBET committed
393
394
395
396
    connected_workers = []

    def onWorkerReady(name):
      connected_workers.append(name)
Philip ABBET's avatar
Philip ABBET committed
397

Philip ABBET's avatar
Philip ABBET committed
398
399
400
401
402
403
404
405
406
    self.controller = WorkerController(
      '127.0.0.1',
      port=None,
      callbacks=dict(
        onWorkerReady = onWorkerReady,
      )
    )

    self.worker_processes = []
Philip ABBET's avatar
Philip ABBET committed
407
408
409
410
411
412
413
414
415
416
417
418

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

Philip ABBET's avatar
Philip ABBET committed
419
420
      worker_process = WorkerProcess(multiprocessing.Queue(), args)
      worker_process.start()
Philip ABBET's avatar
Philip ABBET committed
421

Philip ABBET's avatar
Philip ABBET committed
422
      worker_process.queue.get()
Philip ABBET's avatar
Philip ABBET committed
423

Philip ABBET's avatar
Philip ABBET committed
424
      self.worker_processes.append(worker_process)
Philip ABBET's avatar
Philip ABBET committed
425
426
427
428
429
430
431
432
433

    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)

Philip ABBET's avatar
Philip ABBET committed
434
435
436
437
    self.assertEqual(len(connected_workers), 2)
    self.assertTrue(WORKER1 in connected_workers)
    self.assertTrue(WORKER2 in connected_workers)

Philip ABBET's avatar
Philip ABBET committed
438
439

  def tearDown(self):
Philip ABBET's avatar
Philip ABBET committed
440
441
442
443
444
    if self.worker_processes is not None:
      for worker_process in self.worker_processes:
        worker_process.terminate()
        worker_process.join()
      self.worker_processes = None
Philip ABBET's avatar
Philip ABBET committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510

    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)


Philip ABBET's avatar
Philip ABBET committed
511
512
#----------------------------------------------------------

Philip ABBET's avatar
Philip ABBET committed
513
514
515
516
517
518
519
520
521
522
523

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)