test_cqm.py 154 KB
Newer Older
1
DEBUG_OUTPUT = True
2
CHECK_ALL_SCRIPTS = False
3
WHITEBOX_TESTING = False
4
5
6
7
8
9
POLL_INTERVAL = 0.1
ENABLE_LOGGING = True
LOG_FILE = "test_cqm.log"
CQM_CONFIG_FILE_ENTRY = """
[bgsched]

10
11
12
13
[bgpm]
mpirun: /bin/true
mmcs_server_ip = 127.0.0.1

14
15
16
17
[cqm]
log_dir: /tmp
progress_interval: 0.2
poll_process_groups_interval: 0.2
18
19
progress_interval: 0.2

20
21
22
23
24
25
26
27
28
29
30
31
"""

# override the cobalt config file before the cqm component is loaded
import Cobalt
import TestCobalt
config_file = Cobalt.CONFIG_FILES[0]
config_fp = open(config_file, "w")
config_fp.write(CQM_CONFIG_FILE_ENTRY)
config_fp.close()

import ConfigParser
from nose.tools import timed, TimeExpired
32
from nose.tools import raises
33
34
35
import os
import os.path
import pwd
Paul Rich's avatar
Paul Rich committed
36
import grp
37
38
39
40
41
42
43
import tempfile
from threading import Lock, Condition
import traceback
import types
import unittest
import xmlrpclib

44
45
from mock import patch

46
47
48
49
50
51
52
53
54
import Cobalt.Components.cqm
from Cobalt.Components.base import Component, exposed, automatic, query
from Cobalt.Components.cqm import QueueManager, Signal_Map
from Cobalt.Components.slp import TimingServiceLocator
from Cobalt.Data import IncrID, Data, DataDict
import Cobalt.Exceptions
from Cobalt.Exceptions import QueueError, ComponentLookupError, DataCreationError, \
    JobRunError, JobPreemptionError, JobDeleteError
from Cobalt.Proxy import ComponentProxy
55
from Cobalt.Util import Timer, sleep
56
57
58
59

from test_base import TestComponent
from TestCobalt.Utilities.ThreadSupport import *
from TestCobalt.Utilities.Time import timeout
60
from TestCobalt.Utilities.disable import disabled
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

# if logging is enabled, send all cqm and generic component logging to a file
if ENABLE_LOGGING:
    import testsuite
    from TestCobalt.Utilities.Logging import setup_file_logging
    testsuite.DISABLE_LOGGING = False
    setup_file_logging("cqm", LOG_FILE, "DEBUG")
    setup_file_logging("%s %s" % (QueueManager.implementation, QueueManager.name), LOG_FILE, "DEBUG")
    setup_file_logging("generic component", LOG_FILE, "DEBUG")

# define appropriate routine for debugging output
if DEBUG_OUTPUT:
    def debug_print(msg):
        print msg
else:
    def debug_print(*args):
        pass

# setup white box testing module
import TestCobalt.Utilities.WhiteBox
from TestCobalt.Utilities.WhiteBox import whitebox
TestCobalt.Utilities.WhiteBox.WHITEBOX_TESTING = WHITEBOX_TESTING

# get name of user running the tests
try:
    uid = os.getuid()
    username = pwd.getpwuid(uid).pw_name
except:
    username = "nobody"


class TestCQMComponent (TestComponent):
    cqm_jobid = None

    def setup(self):
        TestComponent.setup(self)

    def setup_jobid(self):
        if TestCQMComponent.cqm_jobid != None:
            Cobalt.Components.cqm.cqm_id_gen.set(TestCQMComponent.cqm_jobid)
Paul Rich's avatar
Paul Rich committed
101

102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
    def teardown(self):
        if Cobalt.Components.cqm.cqm_id_gen != None:
            TestCQMComponent.cqm_jobid = Cobalt.Components.cqm.cqm_id_gen.get()
        TestComponent.teardown(self)


class TestCQMQueueManagement (TestCQMComponent):
    def setup(self):
        TestCQMComponent.setup(self)
        self.cqm = QueueManager()
        self.setup_jobid()

    def teardown(self):
        del self.cqm
        TestCQMComponent.teardown(self)
Paul Rich's avatar
Paul Rich committed
117

118
119
    def test_add_queues(self):
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
Paul Rich's avatar
Paul Rich committed
120

121
122
123
        assert len(self.cqm.Queues) == 1
        assert 'default' in self.cqm.Queues
        assert self.cqm.Queues['default'].tag == 'queue'
Paul Rich's avatar
Paul Rich committed
124

125
126
    def test_get_queues(self):
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
Paul Rich's avatar
Paul Rich committed
127

128
        results = self.cqm.get_queues([{'tag':"queue", 'name':"default"}])
Paul Rich's avatar
Paul Rich committed
129

130
131
        assert len(results) == 1
        assert results[0].name == 'default'
Paul Rich's avatar
Paul Rich committed
132

133
134
        self.cqm.add_queues([{'tag':"queue", 'name':"foo"}])
        self.cqm.add_queues([{'tag':"queue", 'name':"bar"}])
Paul Rich's avatar
Paul Rich committed
135

136
        results = self.cqm.get_queues([{'tag':"queue", 'name':"default"}])
Paul Rich's avatar
Paul Rich committed
137

138
139
140
141
        assert len(results) == 1
        assert results[0].name == 'default'

        results = self.cqm.get_queues([{'tag':"queue", 'name':"*"}])
Paul Rich's avatar
Paul Rich committed
142

143
        assert len(results) == 3
Paul Rich's avatar
Paul Rich committed
144

145
146
147
148
    def test_del_queues(self):
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
        self.cqm.add_queues([{'tag':"queue", 'name':"foo"}])
        self.cqm.add_queues([{'name':"empty"}])
Paul Rich's avatar
Paul Rich committed
149

150
151
152
153
154
155
156
157
158
159
        self.cqm.add_jobs([{'tag':"job", 'queue':"default", 'user':"dilbert"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"default", 'user':"wally"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"foo", 'user':"dilbert"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"foo", 'user':"wally"}])

        results = self.cqm.get_jobs([{'tag':"job", 'user':"dilbert"}])
        assert len(results) == 2

        results = self.cqm.get_jobs([{'tag':"job", 'user':"wally"}])
        assert len(results) == 2
Paul Rich's avatar
Paul Rich committed
160

161
162
163
164
165
166
167
168
169
170
171
172
173
        try:
            self.cqm.del_queues([{'tag':"queue", 'name':"foo"}])
        except Exception:
            pass
        else:
            assert not "able to delete queue with jobs in it"

        results = self.cqm.get_jobs([{'tag':"job", 'queue':"default"}])
        assert len(results) == 2

        results = self.cqm.get_jobs([{'tag':"job", 'queue':"foo"}])
        assert len(results) == 2

Paul Rich's avatar
Paul Rich committed
174
        self.cqm.del_queues([{'tag':"queue", 'name':"foo"}], force=True)
175
176
177
178
179
180

        results = self.cqm.get_jobs([{'tag':"job", 'queue':"default"}])
        assert len(results) == 2

        results = self.cqm.get_jobs([{'tag':"job", 'queue':"foo"}])
        assert len(results) == 0
Paul Rich's avatar
Paul Rich committed
181

182
183
184
        r = self.cqm.del_queues([{'name':"empty"}])
        r = self.cqm.get_queues([{'name':"empty"}])
        assert len(r) == 0
Paul Rich's avatar
Paul Rich committed
185

186
187
    def test_set_queues(self):
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
Paul Rich's avatar
Paul Rich committed
188

189
190
191
192
193
194
195
196
        self.cqm.set_queues([{'tag':"queue", 'name':"default"}], {'state':'running'})
        results = self.cqm.get_queues([{'tag':"queue", 'name':"default"}])
        assert results[0].state == 'running'

        self.cqm.add_queues([{'tag':"queue", 'name':"foo"}])
        self.cqm.add_queues([{'tag':"queue", 'name':"bar"}])
        self.cqm.set_queues([{'tag':"queue", 'name':"*"}], {'state':'stopped'})
        results = self.cqm.get_queues([{'tag':"queue", 'name':"*"}])
Paul Rich's avatar
Paul Rich committed
197

198
        assert results[0].state == results[1].state == results[2].state == 'stopped'
Paul Rich's avatar
Paul Rich committed
199

200
201
202
203
204
205
206
207
208
209

class TestCQMJobManagement (TestCQMComponent):
    def setup(self):
        TestCQMComponent.setup(self)
        self.cqm = QueueManager()
        self.setup_jobid()

    def teardown(self):
        del self.cqm
        TestCQMComponent.teardown(self)
Paul Rich's avatar
Paul Rich committed
210

211
212
213
214
215
216
217
218
219
220
221
    def test_add_jobs(self):
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
        self.cqm.add_queues([{'tag':"queue", 'name':"foo"}])
        self.cqm.add_queues([{'tag':"queue", 'name':"bar"}])

        try:
            self.cqm.add_jobs([{'queue':"not a valid name"}])
        except QueueError:
            pass
        else:
            assert not "trying to add a job to a non-existent queue should raise an Exception"
Paul Rich's avatar
Paul Rich committed
222

223
        self.cqm.add_jobs([{'tag':"job", 'queue':"default"}])
Paul Rich's avatar
Paul Rich committed
224

225
226
        results = self.cqm.get_queues([{'tag':"queue", 'name':"default"}])
        assert len(results[0].jobs) == 1
Paul Rich's avatar
Paul Rich committed
227

228
229
        results = self.cqm.get_queues([{'tag':"queue", 'name':"foo"}])
        assert len(results[0].jobs) == 0
Paul Rich's avatar
Paul Rich committed
230

231
232
233
234
235
236
237
238
239
        results = self.cqm.get_queues([{'tag':"queue", 'name':"bar"}])
        assert len(results[0].jobs) == 0

    def test_get_jobs(self):
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
        self.cqm.add_queues([{'tag':"queue", 'name':"foo"}])
        self.cqm.add_queues([{'tag':"queue", 'name':"bar"}])

        self.cqm.add_jobs([{'tag':"job", 'queue':"default"}])
Paul Rich's avatar
Paul Rich committed
240

241
242
        results = self.cqm.get_jobs([{'tag':"job", 'jobid':"*"}])
        assert len(results) == 1
Paul Rich's avatar
Paul Rich committed
243

244
245
246
247
248
249
250
251
252
253
        self.cqm.add_jobs([{'tag':"job", 'queue':"foo"}])

        results = self.cqm.get_jobs([{'tag':"job", 'jobid':"*"}])
        assert len(results) == 2

        results = self.cqm.get_jobs([{'tag':"job", 'jobid':"*", 'queue':"foo"}])
        assert len(results) == 1

        results = self.cqm.get_jobs([{'tag':"job", 'jobid':"*", 'queue':"bar"}])
        assert len(results) == 0
Paul Rich's avatar
Paul Rich committed
254

255
256
257
    def test_del_jobs(self):
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
        self.cqm.add_queues([{'tag':"queue", 'name':"foo"}])
Paul Rich's avatar
Paul Rich committed
258

259
260
261
262
263
264
265
266
267
268
        self.cqm.add_jobs([{'tag':"job", 'queue':"default", 'user':"dilbert"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"default", 'user':"wally"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"foo", 'user':"dilbert"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"foo", 'user':"wally"}])

        results = self.cqm.get_jobs([{'tag':"job", 'user':"dilbert"}])
        assert len(results) == 2

        results = self.cqm.get_jobs([{'tag':"job", 'user':"wally"}])
        assert len(results) == 2
Paul Rich's avatar
Paul Rich committed
269

270
271
272
273
274
275
276
277
278
279
280
281
        results = self.cqm.del_jobs([{'tag':"job", 'user':"wally"}])
        assert len(results) == 2

        results = self.cqm.get_jobs([{'tag':"job", 'user':"dilbert"}])
        assert len(results) == 2

        results = self.cqm.get_jobs([{'tag':"job", 'user':"wally"}])
        assert len(results) == 0

    def test_set_jobs(self):
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
        self.cqm.add_queues([{'tag':"queue", 'name':"foo"}])
Paul Rich's avatar
Paul Rich committed
282

283
284
        self.cqm.add_jobs([{'tag':"job", 'queue':"default"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"foo"}])
Paul Rich's avatar
Paul Rich committed
285

286
287
288
        self.cqm.set_jobs([{'tag':"job", 'queue':"*"}], {'jobname':"hello"})
        results = self.cqm.get_jobs([{'tag':"job", 'jobname':"hello"}])
        assert len(results) == 2
Paul Rich's avatar
Paul Rich committed
289

290
291
292
293
294
295
296
297
298
299
300
301
        self.cqm.set_jobs([{'tag':"job", 'queue':"foo"}], {'jobname':"goodbye"})
        results = self.cqm.get_jobs([{'tag':"job", 'jobname':"hello"}])
        assert len(results) == 1

    def test_set_jobid(self):
        # create a local QueueManager so that we can be sure no jobids have been used
        id = Cobalt.Components.cqm.cqm_id_gen.get() + 10
        self.cqm.add_queues([{'name':"default"}])
        self.cqm.set_jobid(id, "crusher")
        self.cqm.add_jobs([{'queue':"default"}])
        r = self.cqm.get_jobs([{'jobid':id}])
        assert len(r) == 1
Paul Rich's avatar
Paul Rich committed
302

303
304
305
306
307
    def test_move_jobs(self):
        self.cqm.add_queues([{'name':"default"}])
        self.cqm.add_queues([{'name':"foo"}])
        self.cqm.add_queues([{'name':"restricted"}])
        self.cqm.set_queues([{'name':"restricted"}], {'users':"alice"})
Paul Rich's avatar
Paul Rich committed
308

309
        self.cqm.add_jobs([{'queue':"default", 'jobname':"hello"}])
Paul Rich's avatar
Paul Rich committed
310

311
312
313
314
315
316
        try:
            self.cqm.set_jobs([{'jobname':"hello"}], {'queue': "jonx"})
        except QueueError:
            pass
        else:
            assert not "moving a job to a non-existent queue should cause an exception"
Paul Rich's avatar
Paul Rich committed
317

318
319
320
321
        self.cqm.set_jobs([{'jobname':"hello"}], {'queue': "foo"})
        r = self.cqm.get_jobs([{'jobname':"hello", 'queue':"*"}])
        assert len(r) == 1
        assert r[0].queue == "foo"
Paul Rich's avatar
Paul Rich committed
322

323
324
325
326
327
328
        try:
            self.cqm.set_jobs([{'jobname':"hello"}], {'queue': "restricted"})
        except QueueError:
            pass
        else:
            assert not "a job failing can_queue should prevent the set_jobs from succeeding"
Paul Rich's avatar
Paul Rich committed
329

Paul Rich's avatar
Paul Rich committed
330
331
332
333
334
335
    def test_queue_job_group_restriction(self):
        #Note: apparently CentOS likes to not add your user to your user's default group.  Make sure that
        #grp will actually return you as a member of the gid you're running under. --PMR
        group_name = grp.getgrgid(os.getegid()).gr_name #group we're running under for verification check.
        self.cqm.add_queues([{'name':"default"}])
        self.cqm.add_queues([{'name':"restricted-group"}])
336
337
        self.cqm.set_queues([{'name':"restricted-group"}],
                {'groups':'ThisGroupDefinitelyDoesntExist'})
Paul Rich's avatar
Paul Rich committed
338
339
340
341
342
343
344
345

        self.cqm.add_jobs([{'queue':"default", 'jobname':"hello", 'user':pwd.getpwuid(os.getuid()).pw_name}])
        try:
            self.cqm.set_jobs([{'jobname':"hello"}], {'queue': "restricted-group"})
        except QueueError:
            pass
        else:
            assert False, "A job not in a specified group must fail to queue."
346
347
348
349
350
351
352
        #Disabled until a better, more portable way, is devised to test this.
        #This current version is extremely environment dependent.
        #self.cqm.set_queues([{'name':"restricted-group"}], {'groups':'cobalt'})
        #self.cqm.set_jobs([{'jobname':"hello"}], {'queue': "restricted-group"})
        #r = self.cqm.get_jobs([{'jobname':"hello", 'queue':"*"}])
        #assert len(r) == 1
        #assert r[0].queue == "restricted-group"
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
    def test_set_job_score_type_from_float(self):
        # Ensure that job scores are set to a float and are appropriately cast
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"default"}])
        self.cqm.set_jobs([{'tag':"job", 'queue':"*"}], {'score':0.1})
        job = self.cqm.get_jobs([{'tag':"job", 'queue':"default"}])[0]
        assert type(job.score) == type(0.0), "Job score not float type when set from float"

    def test_set_job_score_type_from_int(self):
        # Ensure that job scores are set to a float and are appropriately cast
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"default"}])
        self.cqm.set_jobs([{'tag':"job", 'queue':"*"}], {'score':1})
        job = self.cqm.get_jobs([{'tag':"job", 'queue':"default"}])[0]
        assert type(job.score) == type(0.0), "Job score not float type when set from int"

    def test_set_job_score_type_from_string(self):
        # Ensure that job scores are set to a float and are appropriately cast
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"default"}])
        self.cqm.set_jobs([{'tag':"job", 'queue':"*"}], {'score': "0.1"})
        job = self.cqm.get_jobs([{'tag':"job", 'queue':"default"}])[0]
        assert type(job.score) == type(0.0), "Job score not float type when set from string"

    @raises(Cobalt.Exceptions.QueueError)
    def test_set_job_score_bad_string(self):
        # Refuse to queue if score cannot be cast to a float.
        self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
        self.cqm.add_jobs([{'tag':"job", 'queue':"default"}])
        self.cqm.set_jobs([{'tag':"job", 'queue':"*"}], {'score': "NotANumber"})

385
386
class Task (Data):
    required_fields = ['jobid', 'location', 'user', 'cwd', 'executable', 'args', ]
Paul Rich's avatar
Paul Rich committed
387
    fields = Data.fields + ["id", "jobid", "location", "size", "mode", "user", "executable", "args", "env", "cwd", "umask",
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
        "kernel", "kerneloptions", "cobalt_log_file", "exit_status", "state", ]

    def __init__(self, spec):
        Data.__init__(self, spec)
        self.id = spec.get("id")
        self.jobid = spec.get("jobid")
        self.location = spec.get('location') or []
        self.size = spec.get('size')
        self.mode = spec.get('mode', 'co')
        self.user = spec.get('user', "")
        self.executable = spec.get('executable')
        self.args = " ".join(spec.get('args') or [])
        self.env = spec.get('env') or {}
        self.cwd = spec.get('cwd')
        self.umask = spec.get('umask')
        self.kernel = spec.get('kernel')
        self.kerneloptions = spec.get('kerneloptions')
        self.cobalt_log_file = spec.get('cobalt_log_file')

        self.exit_status = None

    def _get_state (self):
        if self.exit_status is None:
            return "running"
        else:
            return "terminated"
Paul Rich's avatar
Paul Rich committed
414

415
416
417
418
419
420
421
422
    state = property(_get_state)

class TaskDict (DataDict):
    """Default container for tasks.  Keyed by task id. """

    item_cls = None
    key = "id"
    id_gen = IncrID()
Paul Rich's avatar
Paul Rich committed
423

424
425
    # def __init__ (self):
    #     self.id_gen = IncrID()
Paul Rich's avatar
Paul Rich committed
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
464
465
466
467
468
469
470
471
472
473
    def q_add (self, specs, callback=None, cargs={}):
        for spec in specs:
            if spec.get("id", "*") != "*":
                raise DataCreationError("cannot specify an id")
            spec['id'] = self.id_gen.next()
        return DataDict.q_add(self, specs)

class SimulatedTaskManager (Component):
    """
    A simulated task management component that provides the ability to control the state and actions of the task for the purposes
    of testing other components.  It is expected that this class will be used to build the real components that are exposed via
    XML-RPC.
    """

    def __init__(self, *args, **kwargs):
        Component.__init__(self, *args, **kwargs)
        self.tasks = TaskDict()
        self.excs = {'add':[], 'signal':[], 'wait':[], 'reserve':[]}
        self.ops = []
        self.op_index = 0
        self.__lock = Lock()
        self.__cond = Condition(self.__lock)

    def __raise_pending_exc(self, op_type, *args):
        exc = None
        cb = None
        try:
            self.__lock.acquire()
            if len(self.excs[op_type]) > 0:
                exc, cb = self.excs[op_type].pop(0)
        finally:
            self.__lock.release()
        if cb != None:
            cb(op_type, exc, *args)
        if exc != None:
            op = [op_type, exc]
            op.extend(args)
            self.__op_add(op)
            raise exc

    def __op_add(self, op):
        try:
            self.__lock.acquire()
            self.ops.append(op)
            self.__cond.notify()
        finally:
            self.__lock.release()
474

475
476
477
478
479
    def add_tasks(self, specs):
        self.__raise_pending_exc('add', specs)
        tasks = self.tasks.q_add(specs)
        self.__op_add(['add', None, tasks])
        return tasks
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
    def get_tasks(self, specs):
        return self.tasks.q_get(specs)

    def wait_tasks(self, specs):
        self.__raise_pending_exc('wait', specs)
        tasks = [task for task in self.tasks.q_get(specs) if task.exit_status is not None]
        for task in tasks:
            del self.tasks[task.id]
        self.__op_add(['wait', None, tasks])
        return tasks

    def signal_tasks(self, specs, signame = Signal_Map.terminate):
        self.__raise_pending_exc('signal', specs, signame)
        tasks = [task for task in self.tasks.q_get(specs) if task.exit_status is None]
        self.__op_add(['signal', None, tasks, signame])
        return tasks

    def complete_tasks(self, specs, exit_status):
        tasks = self.tasks.q_get(specs)
        for task in tasks:
            task.exit_status = exit_status
        return tasks

    def reserve_resources_until(self, location, duration, jobid):
        self.__raise_pending_exc('reserve')
506
        #self.__op_add(['reserve', None])
507
        return True #FIXME: Make this respond to a settable option, so we can fail as well.
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535

    def op_wait(self):
        try:
            self.__lock.acquire()
            while self.op_index == len(self.ops):
                self.__cond.wait(1.0)
            op = self.ops[self.op_index]
            self.op_index += 1
        finally:
            self.__lock.release()
        return op

    def add_exc(self, op_type, exc, cb = None):
        try:
            self.__lock.acquire()
            self.excs[op_type].append([exc, cb])
        finally:
            self.__lock.release()

    def clear_excs(self, op_type):
        try:
            self.__lock.acquire()
            self.excs[op_type] = []
        finally:
            self.__lock.release()

class SystemTask (Task):
    required_fields = Task.required_fields + ['size']
536
    fields = Task.fields + ["stdin", "stdout", "stderr", ]
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551

    def __init__(self, spec):
        Task.__init__(self, spec)
        self.stdin = spec.get('stdin')
        self.stdout = spec.get('stdout')
        self.stderr = spec.get('stderr')

class SimulatedSystem (SimulatedTaskManager):
    """
    A simulated system component that provides the ability to control the state and actions of the process groups for the
    purposes of testing other components.
    """
    name = "system"
    implementation = "SimSystem"
    logger = setup_file_logging("%s %s" % (implementation, name), LOG_FILE, "DEBUG")
552

553
554
555
    def __init__(self, *args, **kwargs):
        SimulatedTaskManager.__init__(self, *args, **kwargs)
        self.tasks.item_cls = SystemTask
556

557
    def add_process_groups(self, specs):
558
559
560
561
        self.logger.debug("add_process_groups called: %s", specs)
        tasks = self.add_tasks(specs)
        self.logger.debug("add_process_groups returning: %s", [t.id for t in tasks])
        return tasks
562

563
    add_process_groups = exposed(query(add_process_groups))
564

565
    def get_process_groups(self, specs):
566
567
568
569
        self.logger.debug("get_process_groups called: %s", specs)
        tasks = self.get_tasks(specs)
        self.logger.debug("get_process_groups returning: %s", [t.id for t in tasks])
        return tasks
570
571
572
573
574
575
576

    get_process_groups = exposed(query(get_process_groups))

    def wait_process_groups(self, specs):
        return self.wait_tasks(specs)

    wait_process_groups = exposed(query(wait_process_groups))
577

578
579
580
581
582
583
584
585
586
587
    def signal_process_groups(self, specs, signame="SIGINT"):
        return self.signal_tasks(specs, signame)

    signal_process_groups = exposed(query(signal_process_groups))

    def reserve_resources_until(self, location, duration, jobid):
        return SimulatedTaskManager.reserve_resources_until(self, location, duration, jobid)

    reserve_resources_until = exposed(reserve_resources_until)

588
class Child (Data):
Paul Rich's avatar
Paul Rich committed
589
    fields = Data.fields + ['id', 'args', 'env', 'tag', 'runid', 'label', 'stdout', 'stderr', 'complete', 'lost_child',
590
591
        'exit_status', 'signum', 'core_dump']
    required = Data.required + ['id']
592
593

    def __init__(self, spec):
594
595
596
597
598
599
600
601
602
603
604
605
606
607
        Data.__init__(self, spec)
        self.id = spec.get('id')
        self.args = spec.get('args', [])
        self.env = spec.get('env', {})
        self.tag = spec.get('tag', None)
        self.runid = spec.get('runid', None)
        self.label = spec.get('label', "")
        self.stdout = []
        self.stderr = []
        self.complete = False
        self.lock_child = False
        self.exit_status = None
        self.signum = 0
        self.core_dump = False
608
609
610
611
        self.return_output = False
        self.lost_child = False


612
613
614
615
616
617
618
619
620
621
622
623
624

class ChildDict (DataDict):
    item_cls = Child
    key = 'id'

    def __init__(self):
        self.id_gen = IncrID()
        self.runids = {}

    def q_add (self, specs, callback=None, cargs={}):
        for spec in specs:
            if spec.get("id", "*") != "*":
                raise DataCreationError("cannot specify an id")
625
            spec['id'] = self.id_gen.next()
626
627
628
629
630
631
632
633
634
635
636
637
638
        children = DataDict.q_add(self, specs)
        self.runids.update(dict([(child.runid, child) for child in children if child.runid is not None]))
        return children

    def q_del(self, specs, callback=None, cargs={}):
        children = DataDict.q_del(self, specs, callback, cargs)
        for child in children:
            try:
                del self.runids[child.runid]
            except KeyError:
                pass

class SimulatedForker (Component):
Paul Rich's avatar
Paul Rich committed
639

640
641
642
643
    name = 'system_script_forker'
    implementation = 'system_script_forker'

    _logger = setup_file_logging("%s %s" % (implementation, name), LOG_FILE, "DEBUG")
644
    def __init__(self, *args, **kwargs):
645
646
        Component.__init__(self, *args, **kwargs)
        self.children = ChildDict()
647
648
649
650
651
652
653
654
655
656
657
658
        self.requested_exception = None
        self.requested_exception_set = False
        self.requested_return_value = None
        self.requested_return_value_set = False

    def set_requested_exception(self, exception):
        self.requested_exception = exception
        self.requested_exception_set = True

    def set_requested_return_value(self, reutrn_value):
        self.requested_return_value_set = True
        self.requested_return_value = return_value
Paul Rich's avatar
Paul Rich committed
659

660
661
662
663
664
665
666
667
668
669
670
671
    def clear_requested_effect(self):
        if self.requested_exception_set:
            self.requested_exception = False
            exception_to_rase = self.requested_exception
            self.requested_exception = None
            raise exception_to_raise
        if self.requested_return_value_set:
            self.requested_return_value_set = False
            req_return_value = self.requested_return_value
            self.requested_return_value = None
            return (True, req_return_value)
        return (False, None)
Paul Rich's avatar
Paul Rich committed
672

673

674
    def fork(self, args, tag=None, label=None, env=None, preexec_data=None, runid=None):
Paul Rich's avatar
Paul Rich committed
675

676
677
678
        is_preset_return, preset_return = self.clear_requested_effect()
        if is_preset_return:
            return preset_return
679

680
        child = self.children.q_add([{'id':'*', 'args':args, 'env':env, 'tag':tag, 'runid':runid, 'label':label, 'exit_status':0, 'complete':True}])
681

682
683
        return child[0].id
    fork = exposed(fork)
684
685

    def get_children(self, tag=None, child_ids=None):
686
687
688
        is_preset_return, preset_return = self.clear_requested_effect()
        if is_preset_return:
            return preset_return
Paul Rich's avatar
Paul Rich committed
689

690
691
692
693
694
695
696
697
698
699
700
701
702
703
        if child_ids is None:
            return [child for child in self.children.itervalues() if tag is None or child.tag == tag]
        else:
            ret = []
            for child_id in child_ids:
                try:
                    child = self.children[child_id]
                except KeyError:
                    # the requested child no longer exists so make up a dummy child and mark it as lost
                    child = self.item_cls({'id':child_id})
                    child.lost_child = True
                    child.tag = tag
                    child.complete = True
                if tag is None or child.tag == tag:
704
                    ret.append(child.to_rx())
705
706
707
708
            return ret

    get_children = exposed(get_children)

709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
    def update_childeren(self):
        #childeren = self.get_childeren({'id':'*'})
        for child in self.children:
            self._logger.debug("found child %s" % self.children[child])
            self.children[child].complete = True
            self.children[child].exit_status = 0

        return
    update_childeren = automatic(update_childeren,1.0)


    def signal(self, child_id, signame):
        is_preset_return, preset_return = self.clear_requested_effect()
        if is_preset_return:
            return preset_return
        if not self.children.has_key(child_id):
            self._logger.error("Child %s: child not found; unable to signal", child_id)
            return

        try:
            signum = getattr(signal, signame)
        except AttributeError:
            self.logger_logger.error("%s: %s is not a valid signal name; child not signaled", child.label, signame)
            raise

        child[child_id].exit_status = 1
        child[child_id].completed = True
        #don't actually send a signal since we never actually forked anything
737

738
    signal = exposed(signal)
Paul Rich's avatar
Paul Rich committed
739

740
741
742
743
744
745
746
    def active_list(self):
        '''Only useful for pg_forker runs

        '''
        is_preset_return, preset_return = self.clear_requested_effect()
        if is_preset_return:
            return preset_return
Paul Rich's avatar
Paul Rich committed
747
        raise NotImplementedError
748
    active_list = exposed(active_list)
Paul Rich's avatar
Paul Rich committed
749

750
751
752
753
754
755
756
    def get_status(self):
        '''Only useful for pg_forker runs

        '''
        is_preset_return, preset_return = self.clear_requested_effect()
        if is_preset_return:
            return preset_return
Paul Rich's avatar
Paul Rich committed
757
        raise NotImplementedError
758
759
    get_status = exposed(get_status)

760
    def cleanup_children(self, child_ids):
Paul Rich's avatar
Paul Rich committed
761

762
763
764
        is_preset_return, preset_return = self.clear_requested_effect()
        if is_preset_return:
            return preset_return
Paul Rich's avatar
Paul Rich committed
765

766
767
768
        self.children.q_del([{'id':id} for id in child_ids])

    cleanup_children = exposed(cleanup_children)
769

770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803


class BogusException1 (Exception):
    fault_code = Cobalt.Exceptions.fault_code_counter.next()

class BogusException2 (Exception):
    fault_code = Cobalt.Exceptions.fault_code_counter.next()

def cqm_config_file_update(options = {}):
    config_file = Cobalt.CONFIG_FILES[0]
    config_fp = open(config_file, "w")
    config_fp.write(CQM_CONFIG_FILE_ENTRY)
    for option, value in options.iteritems():
        print >>config_fp, "%s: %s" % (option, value)
    config_fp.close()
    config = ConfigParser.ConfigParser()
    config.read(Cobalt.CONFIG_FILES)
    Cobalt.Components.cqm.config = config

def check_output_files(fn_bases, exist = True, fail_msg = None):
    try:
        for fn_base in fn_bases:
            out_fn = "%s.out" % (fn_base,)
            if os.path.exists(out_fn) != exist:
                if fail_msg != None:
                    assert False, "file %s; %s" % (out_fn, fail_msg)
                elif exist:
                    assert False, "file %s does not exist" % (out_fn,)
                else:
                    assert False, "file %s exists and shouldn't" % (out_fn,)
    finally:
        delete_output_files(fn_bases)

def wait_output_files(fn_bases):
804
    return
805
806
807
808
    try:
        for fn_base in fn_bases:
            out_fn = "%s.out" % (fn_base,)
            while not os.path.exists(out_fn):
809
                sleep(POLL_INTERVAL)
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
    finally:
        delete_output_files(fn_bases)

def delete_output_files(fn_bases):
    for fn_base in fn_bases:
        out_fn = "%s.out" % (fn_base,)
        try:
            os.unlink(out_fn)
        except OSError:
            pass

def create_input_files(fn_bases):
    for fn_base in fn_bases:
        sh_fn = "%s.sh" % (fn_base,)
        in_fn = "%s.in" % (fn_base,)
        fp = open(in_fn, "w")
        print >>fp, "input to %s" % (sh_fn,)
        fp.close()

def delete_input_files(fn_bases):
    for fn_base in fn_bases:
        in_fn = "%s.in" % (fn_base,)
        try:
            os.unlink(in_fn)
        except OSError:
            pass

def create_touch_scripts(num_scripts):
    fn_bases = []
    for n in xrange(0, num_scripts):
        (fd, fn) = tempfile.mkstemp("_touch.sh", "test_cqm_")
        fn_base = fn[0:-3]
        fn_bases += [fn_base]
        sh_fn = fn
        out_fn = "%s.out" % (fn_base,)
        fp = os.fdopen(fd, "w")
        fp.write("""\
#!/bin/sh
touch %(out_fn)s
echo "%(out_fn)s has been created"
""" % {'out_fn':out_fn})
        fp.close()
        os.chmod(sh_fn, 0700)
    delete_output_files(fn_bases)
    return fn_bases

def create_wait_scripts(num_scripts, timeout):
    fn_bases = []
    for n in xrange(0, num_scripts):
        (fd, fn) = tempfile.mkstemp("_wait.sh", "test_cqm_")
        fn_base = fn[0:-3]
        fn_bases += [fn_base]
        sh_fn = fn
        in_fn = "%s.in" % (fn_base,)
        out_fn = "%s.out" % (fn_base,)
        fp = os.fdopen(fd, "w")
        fp.write("""\
#!/bin/sh
touch %(out_fn)s
echo "%(out_fn)s has been created"
n=0
echo "waiting for %(in_fn)s to be created"
while test ! -f %(in_fn)s ; do
    sleep 0.2
    n=`expr $n + 1`
    if test $n -gt %(timeout)d ; then
        rm %(out_fn)s
        echo "TIMEOUT: %(in_fn)s not found after 60 seconds" >&2
        exit 1
    fi
done
echo "%(in_fn)s now exists; deleting it"
rm %(in_fn)s
""" % {'in_fn':in_fn, 'out_fn':out_fn, 'timeout':timeout})
        fp.close()
        os.chmod(sh_fn, 0700)
    delete_input_files(fn_bases)
    delete_output_files(fn_bases)
    return fn_bases

def delete_scripts(fn_bases):
    for fn_base in fn_bases:
        sh_fn = "%s.sh" % (fn_base,)
        try:
            os.unlink(sh_fn)
        except OSError:
            pass

def get_script_filenames(fn_bases):
    return ["%s.sh" % (fn_base,) for fn_base in fn_bases]

class CQMIntegrationTestBase (TestCQMComponent):
    taskman = None

    def setup(self):
905
        debug_print("setting up CQMIntegrationTestBase")
906
907
        TestCQMComponent.setup(self)
        self.slp = TimingServiceLocator()
908
909
910
        self.system_script_forker = SimulatedForker()
        self.system_script_forker_thr = ComponentProgressThread(self.system_script_forker)
        self.system_script_forker_thr.start()
911

912
913
914
        self.taskman = SimulatedSystem()
        self.taskman_thr = ComponentProgressThread(self.taskman)
        self.taskman_thr.start()
Paul Rich's avatar
Paul Rich committed
915

916
917
918
919
920
921
922
923
924
925
926
927
928
929
    def setup_cqm(self):
        self.qm = QueueManager()
        self.qm_thr = ComponentProgressThread(self.qm)
        self.qm_thr.start()
        try:
            self.cqm = ComponentProxy("queue-manager")
        except ComponentLookupError:
            assert not "failed to connect to the queue manager component"
        queues = self.cqm.add_queues([{'tag':"queue", 'name':"default"}])
        assert len(queues) == 1
        self.setup_jobid()

    def teardown(self):
        self.qm_thr.stop()
930
931
        self.system_script_forker_thr.stop()
        self.taskman_thr.stop()
932
933
934
        del self.qm_thr
        del self.qm
        del self.slp
935
936
        del self.system_script_forker
        #del self.taskman
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
        TestCQMComponent.teardown(self)

    def get_job_query_spec(self, spec = {}):
        query_spec = {}
        query_spec.update(spec)
        if not spec.has_key("jobid"):
            if hasattr(self, "jobid"):
                query_spec['jobid'] = self.jobid
            else:
                query_spec['jobid'] = "*"
        default_query_attrs = ['is_active', 'is_runnable', 'has_completed', 'preemptable', 'user_hold', 'admin_hold', 'state']
        if WHITEBOX_TESTING:
            default_query_attrs.append('sm_state')
        for attr in default_query_attrs:
            if not spec.has_key(attr):
                query_spec[attr] = "*"
        return query_spec

    def assert_job_state(self, state):
        assert self.job['state'] == state, "expected job state to be \"%s\"; actual job state is \"%s\"" % \
            (state, self.job['state'],)

    def assert_job_sm_state(self, state):
        if WHITEBOX_TESTING:
            assert self.job['sm_state'] == state, "expected job sm_state to be \"%s\"; actual job sm_state is \"%s\"" % \
                (state, self.job['sm_state'],)

    def assert_jobid(self):
        assert self.job['jobid'] == self.jobid, "expected job id to be '%s'; actual job id is '%s'" % \
            (self.jobid, self.job['jobid'])

    def assert_next_op(self, op_type, exc_cls = types.NoneType):
        op = self.taskman.op_wait()
        assert op != None, "no operation found"
        assert op[0] == op_type, "expected op type of '%s'; actual op type is '%s'" % (op_type, op[0])
        exc = op[1]
        assert isinstance(exc, exc_cls), "expected exception type to be '%s'; actual type is '%s'" %  (exc_cls, type(exc))
        return op

    def assert_next_task_op(self, op_type, exc_cls = types.NoneType):
        op = self.assert_next_op(op_type, exc_cls)
        if exc_cls == types.NoneType:
            tasks = op[2]
            assert len(tasks) == 1
            assert tasks[0].id == self.taskid
        else:
            specs = op[2]
            assert len(specs) == 1
            spec = specs[0]
            assert spec['id'] == "*" or spec['id'] == self.taskid
        return op

    def job_get_state(self, get_spec = {}, assert_spec = {}, no_job_ok = False):
        job_spec = {}
        job_spec.update(get_spec)
        for attr, val in assert_spec.iteritems():
            if not job_spec.has_key(attr):
                job_spec[attr] = "*"
        jobs = self.cqm.get_jobs([self.get_job_query_spec(job_spec)])
        num_jobs = len(jobs)
        assert num_jobs < 2, "More than one job was returned"
        assert no_job_ok or num_jobs == 1, "Job %s not found in queue" % (self.jobid,)
        if num_jobs > 0:
            self.job = jobs[0]
            self.assert_jobid()
            if not WHITEBOX_TESTING and assert_spec.has_key("sm_state"):
                assert_spec = assert_spec.copy()
                del assert_spec['sm_state']
            for attr, val in assert_spec.iteritems():
                assert self.job[attr] == val, "expected job attribute '%s' to be '%s'; actual value is '%s'" % \
                    (attr, val, self.job[attr])
            return True
        else:
            return False

    def job_add(self, add_spec = {}, get_spec = {}, job_name = None):
        if job_name == None:
            job_name = traceback.extract_stack()[-2][2]
        job_spec = {'queue':"default", 'user':username, 'jobname':job_name, 'jobid':"*"}
        job_spec.update(add_spec)
        for attr, val in self.default_job_spec.iteritems():
            if not job_spec.has_key(attr):
                job_spec[attr] = val
        jobs = self.cqm.add_jobs([job_spec])
        assert len(jobs) < 2, "More than one job was returned"
        assert len(jobs) == 1, "Job was not successfully added to the queue"
        self.job = jobs[0]
        self.jobid = self.job['jobid']

        self.job_get_state(get_spec, \
            assert_spec = {'is_active':False, 'is_runnable':True, 'has_completed':False, 'state':"queued"})

    def job_update(self, spec, updates):
        query_spec = {}
        query_spec.update(spec)
        for key, value in updates.iteritems():
            if not query_spec.has_key(key):
                query_spec[key] = "*"
        jobs = self.cqm.set_jobs([self.get_job_query_spec(query_spec)], updates)
        assert len(jobs) < 2, "More than one job was returned"
        assert len(jobs) == 1, "Job %s not found in queue" % (self.jobid,)
        self.job = jobs[0]
        self.assert_jobid()

    def job_user_hold(self, orig_hold = "*", new_hold = True):
        jobs = self.cqm.set_jobs([self.get_job_query_spec({'user_hold':orig_hold})], {'user_hold':True})
        assert len(jobs) < 2, "More than one job was returned"
        assert len(jobs) == 1, "Job %s not found in queue" % (self.jobid,)
        self.job = jobs[0]
        self.assert_jobid()
        assert self.job['user_hold'] == new_hold

    def job_user_release(self, orig_hold = "*", new_hold = False):
        jobs = self.cqm.set_jobs([self.get_job_query_spec({'user_hold':orig_hold})], {'user_hold':False})
        assert len(jobs) < 2, "More than one job was returned"
        assert len(jobs) == 1, "Job %s not found in queue" % (self.jobid,)
        self.job = jobs[0]
        self.assert_jobid()
        assert self.job['user_hold'] == new_hold

    def job_admin_hold(self, orig_hold = "*", new_hold = True):
        jobs = self.cqm.set_jobs([self.get_job_query_spec({'admin_hold':orig_hold})], {'admin_hold':True})
        assert len(jobs) < 2, "More than one job was returned"
        assert len(jobs) == 1, "Job %s not found in queue" % (self.jobid,)
        self.job = jobs[0]
        self.assert_jobid()
        assert self.job['admin_hold'] == new_hold

    def job_admin_release(self, orig_hold = "*", new_hold = False):
        jobs = self.cqm.set_jobs([self.get_job_query_spec({'admin_hold':orig_hold})], {'admin_hold':False})
        assert len(jobs) < 2, "More than one job was returned"
        assert len(jobs) == 1, "Job %s not found in queue" % (self.jobid,)
        self.job = jobs[0]
        self.assert_jobid()
        assert self.job['admin_hold'] == new_hold

Paul Rich's avatar
Paul Rich committed
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
    #dep_hold tests.

    def job_add_dep_hold(self):
        #set dep hold if appropriate on job addition
        self.cqm.add_jobs([{'nodes':512, 'walltime':10,
            'queue':'default'}])
        self.cqm.add_jobs([{'nodes':512, 'walltime':10, 'queue':'default',
            'all_dependencies':'1'}])
        job1 = self.cqm.get_jobs([{'queue':'default', 'jobid':1,
            'all_dependencies':'*', 'dep_hold':'*'}])[0]
        job2 = self.cqm.get_jobs([{'queue':'default', 'jobid':2,
            'all_dependencies':'*', 'dep_hold':'*'}])[0]
        assert job1['dep_hold'] == False, "dep_hold incorrectly set."
        assert job2['dep_hold'] == True, "dep_hold not set."

    def job_dep_hold_and_release(self):
        #add two jobs, set dependencies, if deps set, make sure that we are now
        #in dep_hold
        self.cqm.add_jobs([{'nodes':512, 'walltime':10, 'queue':'default'}])
        self.cqm.add_jobs([{'nodes':512, 'walltime':10, 'queue':'default'}])
        job1 = self.cqm.set_jobs([{'queue':'default', 'jobid':2,
            'all_dependencies':'*', 'dep_hold':'*'}],
            {'all_dependencies':'1'})[0]
        assert job1['dep_hold'] is True, "Dep hold not set on adding dependency."
        #remove deps, update holds, make sure job no longer in dep_hold
        job1 = self.cqm.set_jobs([{'queue':'default', 'jobid':2,
            'all_dependencies':'*', 'dep_hold':'*'}],
            {'all_dependencies':''})[0]
        assert job1['dep_hold'] is False, "Job failed to release dep_hold"

1103
    def job_run(self, location):
1104
        debug_print("Initiating job run at %s" % location)
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
        jobs = self.cqm.run_jobs([self.get_job_query_spec()], location)
        assert len(jobs) < 2, "More than one job was returned"
        assert len(jobs) == 1, "Job %s not found in queue" % (self.jobid,)
        self.job = jobs[0]
        self.assert_jobid()
        assert self.job['is_active'] == True
        assert self.job['is_runnable'] == False
        assert self.job['has_completed'] == False

    def job_running_wait(self):
        while True:
            self.job_get_state()
            if self.job['state'] == "running":
                break
            assert self.job['is_active'] == True
            assert self.job['is_runnable'] == False
            assert self.job['has_completed'] == False
            self.assert_job_state("starting")

        tasks = self.taskman.get_tasks([{'jobid':self.jobid, 'id':"*", 'state':"*"}])
        assert len(tasks) < 2, "More than one task was returned while looking for job %s" % (self.jobid,)
        assert len(tasks) == 1, "Task associated with job %s not found" % (self.jobid,)
        self.task = tasks[0]
        assert self.task.jobid == self.jobid, "expected job id is %s; actual job id is %s" % (self.jobid, self.task.jobid)
        assert self.task.state == 'running'
        self.taskid = self.task.id

    def job_preempt(self, user = None, force = False):
        jobs = self.cqm.preempt_jobs([self.get_job_query_spec()], user, force)
        assert len(jobs) < 2, "More than one job was returned"
        assert len(jobs) == 1, "Job %s not found in queue" % (self.jobid,)
        self.job = jobs[0]
        self.assert_jobid()
        assert self.job['is_active'] == True
        assert self.job['is_runnable'] == False
        assert self.job['has_completed'] == False

    def job_preempting_wait(self):
        while True:
            self.job_get_state()
            if self.job['state'] == "preempting":
                assert self.job['is_active'] == True
                assert self.job['is_runnable'] == False
                assert self.job['has_completed'] == False
                break
            assert self.job['is_active'] == True
            assert self.job['is_runnable'] == False
            assert self.job['has_completed'] == False
1153
            sleep(POLL_INTERVAL)
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164

    def job_preempted_wait(self):
        while True:
            self.job_get_state()
            if self.job['is_active'] == False:
                assert self.job['state'] == "preempted" or self.job['state'][-5:] == "_hold"
                assert self.job['has_completed'] == False
                break
            assert self.job['is_active'] == True
            assert self.job['is_runnable'] == False
            assert self.job['has_completed'] == False
1165
            sleep(POLL_INTERVAL)
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190

    def job_kill(self, force = False, user = None, signame = Signal_Map.terminate):
        jobs = self.cqm.del_jobs([self.get_job_query_spec()], force, user, signame)
        assert len(jobs) < 2, "More than one job was returned"
        assert len(jobs) == 1, "Job %s not found in queue" % (self.jobid,)
        self.job = jobs[0]
        self.assert_jobid()

    def task_finished(self, exit_code):
        tasks = self.taskman.complete_tasks([{'id':self.taskid}], exit_code)
        assert len(tasks) < 2, "More than one task was returned while attempting to complete job %s" % (self.jobid,)
        assert len(tasks) == 1, "Task %s associated with job %s failed to complete" % (self.taskid, self.jobid)
        self.task = tasks[0]
        assert self.task.id == self.taskid, "expected task id is %s; actual task id is %s" % (self.taskid, self.task.id)
        assert self.task.jobid == self.jobid, "expected job id is %s; actual job id is %s" % (self.jobid, self.task.jobid)

    def job_finished_wait(self):
        while True:
            found_job = self.job_get_state(no_job_ok = True)
            if found_job == False:
                break
            assert self.job['is_runnable'] == False, "job is runnable and shouldn't be; state='%s'" % (self.job['state'],)
            assert (self.job['is_active'] == True and self.job['has_completed'] == False) or \
                self.job['is_active'] == False and self.job['has_completed'] == True, \
                "unexpected state: is_active=%s, has_completed=%s" % (self.job['is_active'], self.job['has_completed'])
1191
            sleep(POLL_INTERVAL)
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264

    def job_exec_driver(
            self, spec = {}, config_opts = {}, job_queued = None, job_pretask = None, resource_pretask = None, exec_task = True,
            task_run = None, task_wait = None, task_active = None, task_complete = None, num_preempts = 0, job_preempt = None,
            job_preempting = None, preempt_posttask = None, job_preempted = None, preempt_pretask = None, resource_posttask = None,
            job_posttask = None, job_complete = None, script_check = CHECK_ALL_SCRIPTS, wait_script_timeout = 60):

        def _task_run(preempt = False):
            if task_wait != None:
                debug_print("JOB_EXEC: task_wait")
                task_wait()
            else:
                debug_print("JOB_EXEC: task_wait (default)")
                self.job_running_wait()
                self.assert_next_task_op('add')
            if task_active != None:
                debug_print("JOB_EXEC: task_active")
                task_active()
            if not preempt:
                if task_complete != None:
                    debug_print("JOB_EXEC: task_complete")
                    task_complete()
                else:
                    debug_print("JOB_EXEC: task_complete (default)")
                    self.task_finished(0)
                    self.assert_next_task_op('wait')

        try:
            if task_run == None:
                task_run = _task_run

            add_spec = {}
            add_spec.update(spec)
            if num_preempts > 0:
                add_spec['preemptable'] = True

            syncs = []
            configs = {}
            configs.update(config_opts)
            if job_pretask != None or script_check:
                self.job_prescripts = create_wait_scripts(1, wait_script_timeout)
                configs['job_prescripts'] = ":".join(get_script_filenames(self.job_prescripts))
                syncs += self.job_prescripts
            if resource_pretask != None or preempt_pretask != None or script_check:
                self.resource_prescripts = create_wait_scripts(1, wait_script_timeout)
                configs['resource_prescripts'] = ":".join(get_script_filenames(self.resource_prescripts))
                syncs += self.resource_prescripts
            if resource_posttask != None or preempt_posttask != None or script_check:
                self.resource_postscripts = create_wait_scripts(1, wait_script_timeout)
                configs['resource_postscripts'] = ":".join(get_script_filenames(self.resource_postscripts))
                syncs += self.resource_postscripts
            if job_posttask != None or script_check:
                self.job_postscripts = create_wait_scripts(1, wait_script_timeout)
                configs['job_postscripts'] = ":".join(get_script_filenames(self.job_postscripts))
                syncs += self.job_postscripts

            test_name = traceback.extract_stack()[-2][2]
            self.logger.debug("job_exec_info executing test '%s'" % (test_name,))
            cqm_config_file_update(configs)
            self.job_add(add_spec, job_name = test_name)
            self.assert_job_state("queued")
            if job_queued != None:
                debug_print("JOB_EXEC: job_queued")
                job_queued()

            if exec_task:
                preempt_count = 0
                resource_postscript_needed = True

                self.job_run(["R00"])

                if hasattr(self, 'job_prescripts'):
                    debug_print("JOB_EXEC: job_prescripts")
1265
                    #wait_output_files(self.job_prescripts)
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
                    self.job_get_state(assert_spec = {'state':"starting"})
                    if job_pretask != None:
                        debug_print("JOB_EXEC: job_pretask")
                        job_pretask()
                    create_input_files(self.job_prescripts)

                if hasattr(self, 'resource_prescripts'):
                    debug_print("JOB_EXEC: resource_prescripts")
                    wait_output_files(self.resource_prescripts)
                    self.job_get_state(assert_spec = {'state':"starting"})
                    if resource_pretask != None:
                        debug_print("JOB_EXEC: resource_pretask")
                        resource_pretask()
                    create_input_files(self.resource_prescripts)

                while True:
                    if preempt_count < num_preempts:
                        task_run(preempt = True)

                        preempt_count += 1
                        if job_preempt:
                            debug_print("JOB_EXEC: job_preempt")
                            rc = job_preempt()
                            if rc == False:
                                break
                        else:
                            debug_print("JOB_EXEC: job_preempt (default)")
                            self.job_preempt()
                            self.assert_next_task_op('signal')

                        if job_preempting:
                            debug_print("JOB_EXEC: job_preempting")
                            rc = job_preempting()
                            if rc == False:
                                break
                        else:
                            debug_print("JOB_EXEC: job_preempting (default)")
                            self.job_preempting_wait()
                            self.task_finished(0)
                            self.assert_next_task_op('wait')

                        rc = True
                        resource_postscript_needed = False
                        if hasattr(self, 'resource_postscripts'):
                            debug_print("JOB_EXEC: resource_postscripts (preempt)")
                            wait_output_files(self.resource_postscripts)
                            self.job_get_state(assert_spec = {'state':"preempting"})
                            if preempt_posttask != None:
                                debug_print("JOB_EXEC: preempt_posttask")
                                rc = preempt_posttask()
                            create_input_files(self.resource_postscripts)
                        resource_postscript_needed = False
                        if rc == False:
                            break

                        self.job_preempted_wait()
                        if job_preempted:
                            debug_print("JOB_EXEC: job_preempted")
                            rc = job_preempted()
                            if rc == False:
                                break

                        self.job_run(["R%02d" % (preempt_count,)])

                        rc = True
                        resource_postscript_needed = True
                        if hasattr(self, 'resource_prescripts'):
                            debug_print("JOB_EXEC: resource_prescripts (preempt)")
                            wait_output_files(self.resource_prescripts)
                            self.job_get_state(assert_spec = {'state':"starting"})
                            if preempt_pretask != None:
                                debug_print("JOB_EXEC: preempt_pretask")
                                rc = preempt_pretask()
                            create_input_files(self.resource_prescripts)
                        if rc == False:
                            break
                    else:
                        task_run(preempt = False)
                        break
                if hasattr(self, 'resource_postscripts') and resource_postscript_needed:
                    debug_print("JOB_EXEC: resource_postscripts")
                    wait_output_files(self.resource_postscripts)
                    self.job_get_state(assert_spec = {'state':"exiting"})
                    if resource_posttask != None:
                        debug_print("JOB_EXEC: resource_posttask")
                        resource_posttask()
                    create_input_files(self.resource_postscripts)
                if hasattr(self, 'job_postscripts'):
                    debug_print("JOB_EXEC: job_postscripts")
                    wait_output_files(self.job_postscripts)
                    self.job_get_state(assert_spec = {'state':"exiting"})
                    if job_posttask != None:
                        debug_print("JOB_EXEC: job_posttask")
                        job_posttask()
                    create_input_files(self.job_postscripts)
            if job_complete != None:
                debug_print("JOB_EXEC: job_complete")
                job_complete()
            else:
                debug_print("JOB_EXEC: job_complete (default)")
                self.job_finished_wait()
        finally:
            if hasattr(self, "job_prescripts"):
                del self.job_prescripts
            if hasattr(self, "resource_prescripts"):
                del self.resource_prescripts
            if hasattr(self, "resource_postscripts"):
                del self.resource_postscripts
            if hasattr(self, "job_postscripts"):
                del self.job_postscripts
            if len(syncs) > 0:
                delete_scripts(syncs)
                delete_input_files(syncs)
                delete_output_files(syncs)

Paul Rich's avatar
Paul Rich committed
1381
    @timeout(60)
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
    def test_job_exec_driver(self):
        def _job_queued():
            self.test_calls += [traceback.extract_stack()[-1][2]]
            debug_print("TEST_JOB_EXEC: _job_queued")
        def _job_pretask():
            self.test_calls += [traceback.extract_stack()[-1][2]]
            debug_print("TEST_JOB_EXEC: _job_pretask")
        def _resource_pretask():
            self.test_calls += [traceback.extract_stack()[-1][2]]
            debug_print("TEST_JOB_EXEC: _resource_pretask")
        def _task_active():
            self.test_calls += [traceback.extract_stack()[-1][2]]
            debug_print("TEST_JOB_EXEC: _task_active")
        def _preempt_posttask():
            self.test_calls += [traceback.extract_stack()[-1][2]]
            debug_print("TEST_JOB_EXEC: _preempt_postask")
        def _job_preempted():
            self.test_calls += [traceback.extract_stack()[-1][2]]
            debug_print("TEST_JOB_EXEC: _job_preempted")
        def _preempt_pretask():
            self.test_calls += [traceback.extract_stack()[-1][2]]
            debug_print("TEST_JOB_EXEC: _preempt_pretask")
        def _resource_posttask():
            self.test_calls += [traceback.extract_stack()[-1][2]]
            debug_print("TEST_JOB_EXEC: _resource_posttask")
        def _job_posttask():
            self.test_calls += [traceback.extract_stack()[-1][2]]
            debug_print("TEST_JOB_EXEC: _job_posttask")
        def _job_complete():
            self.test_calls += [traceback.extract_stack()[-1][2]]
            debug_print("TEST_JOB_EXEC: _job_complete")
            self.job_finished_wait()
        self.test_calls = []
        self.job_exec_driver(
Paul Rich's avatar
Paul Rich committed
1416
1417
1418
            #num_preempts = 1,
            job_queued = _job_queued,
            job_pretask = _job_pretask,
1419
            resource_pretask = _resource_pretask,
Paul Rich's avatar
Paul Rich committed
1420
1421
            task_active = _task_active,
            #preempt_posttask = _preempt_posttask,
1422
            #job_preempted = _job_preempted,
Paul Rich's avatar
Paul Rich committed
1423
1424
            #preempt_pretask = _preempt_pretask,
            resource_posttask = _resource_posttask,
1425
            job_posttask = _job_posttask,
1426
            job_complete = _job_complete)
Paul Rich's avatar
Paul Rich committed
1427
        #assert self.test_calls == ["_job_queued", "_job_pretask", "_resource_pretask", "_task_active", "_preempt_posttask",
1428
1429
1430
        #                           "_job_preempted", "_preempt_pretask", "_task_active", "_resource_posttask", "_job_posttask",
        #                           "_job_complete"]
        #This is adjusted until we have preemption back: PMR 8/8/2011
Paul Rich's avatar
Paul Rich committed
1431
1432
1433
1434
1435
        assert self.test_calls == ["_job_queued",
                                   "_job_pretask",
                                   "_resource_pretask",
                                   "_task_active",
                                   "_resource_posttask",
1436
1437
                                   "_job_posttask",
                                   "_job_complete"], "Test-call mismatch.  Got:%s" % self.test_calls
1438
1439
1440
1441
1442
        del self.test_calls

    #
    # tests for non-preemptable jobs
    #
Paul Rich's avatar
Paul Rich committed
1443
    @timeout(60)
1444
1445
1446
    def test_nonpreempt_queued__run(self):
        # a simple run
        self.job_exec_driver()
Paul Rich's avatar
Paul Rich committed
1447
    test_nonpreempt_queued__run.disabled = True
1448

Paul Rich's avatar
Paul Rich committed
1449
    @timeout(60)
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
    def test_nonpreempt_queued__run_failed(self):
        # attempting to start a new task; if the attempt fails, cqm should try again
        def _job_queued():
            self.taskman.add_exc('add', BogusException1("error1"))
            self.taskman.add_exc('add', BogusException2("error2"))
        def _task_wait():
            self.job_running_wait()
            self.assert_next_task_op('add', BogusException1)
            self.assert_next_task_op('add', BogusException2)
            self.assert_next_task_op('add')
        self.job_exec_driver(job_queued = _job_queued, task_wait = _task_wait)

Paul Rich's avatar
Paul Rich committed
1462
    @timeout(60)
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
    def test_nonpreempt_queued__hold_user(self):
        # the job is queued; test user holds and releases
        def _job_queued():
            self.assert_job_state("queued")
            self.job_user_hold()
            assert self.job['is_active'] == False
            assert self.job['is_runnable'] == False
            assert self.job['has_completed'] == False
            self.assert_job_state("user_hold")
            self.job_user_release()
            assert self.job['is_active'] == False
            assert self.job['is_runnable'] == True
            assert self.job['has_completed'] == False
            self.assert_job_state("queued")
        self.job_exec_driver(job_queued = _job_queued)

Paul Rich's avatar
Paul Rich committed
1479
    @timeout(60)
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
    def test_nonpreempt_queued__hold_admin(self):
        # the job is queued; test admin holds and releases
        def _job_queued():
            self.assert_job_state("queued")
            self.job_admin_hold()
            assert self.job['is_active'] == False
            assert self.job['is_runnable'] == False
            assert self.job['has_completed'] == False
            self.assert_job_state("admin_hold")
            self.job_admin_release()
            assert self.job['is_active'] == False
            assert self.job['is_runnable'] == True
            assert self.job['has_completed'] == False
            self.assert_job_state("queued")
        self.job_exec_driver(job_queued = _job_queued)

Paul Rich's avatar
Paul Rich committed
1496
    @timeout(60)
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
    def test_nonpreempt_queued__release(self):
        # the job is queued; attempts to release the job should be ignored (and a warning message added to the logs)
        def _job_queued():
            self.assert_job_state("queued")
            self.job_user_release()
            assert self.job['is_active'] == False
            assert self.job['is_runnable'] == True
            assert self.job['has_completed'] == False
            self.assert_job_state("queued")
            self.job_admin_release()
            assert self.job['is_active'] == False
            assert self.job['is_runnable'] == True
            assert self.job['has_completed'] == False
            self.assert_job_state("queued")
        self.job_exec_driver(job_queued = _job_queued)

Paul Rich's avatar
Paul Rich committed
1513
    @timeout(60)
1514
1515
1516
1517
1518
1519
1520
1521
    def test_nonpreempt_queued__kill(self):
        # kill a queued job
        def _job_queued():
            self.assert_job_state("queued")
            self.job_kill()
            self.assert_job_state("done")
        self.job_exec_driver(job_queued = _job_queued, exec_task = False)

Paul Rich's avatar
Paul Rich committed
1522
    @timeout(60)
1523
1524
1525
1526
1527
1528
1529
    def test_nonpreempt_queued__force_kill(self):
        # forcibly kill a queued job
        def _job_queued():
            self.assert_job_state("queued")
            self.job_kill(force = True)
        self.job_exec_driver(job_queued = _job_queued, exec_task = False)

Paul Rich's avatar
Paul Rich committed
1530
    @timeout(60)
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
    def test_nonpreempt_queued__preempt(self):
        # the job is queued; attempts to preempt the job should result in an error
        def _job_queued():
            try:
                self.job_preempt()
                assert False, "attempt to preempt while in the queued state should fail"
            except xmlrpclib.Fault, e:
                assert e.faultCode == JobPreemptionError.fault_code
            self.job_get_state(assert_spec = {'state':'queued'})
        self.job_exec_driver(job_queued = _job_queued)

Paul Rich's avatar
Paul Rich committed
1542
    @timeout(60)
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
    def test_nonpreempt_queued__walltime_adjustment(self):
        # change the walltime of a queued job
        def _job_queued():
            self.job_update({}, {'walltime':new_walltime})
            assert self.job['walltime'] == new_walltime
        def _task_active():
            self.job_get_state(assert_spec = {'walltime':new_walltime})
        new_walltime = 903245832
        self.job_exec_driver(job_queued = _job_queued, task_active = _task_active)

Paul Rich's avatar
Paul Rich committed
1553
    @timeout(60)
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
    def test_nonpreempt_hold_both(self):
        # test placing both user and admin hold simultaneously starting from a queued state
        def _job_queued():
            self.assert_job_state("queued")
            self.job_admin_hold()
            self.assert_job_state("admin_hold")
            self.job_user_hold()
            self.assert_job_state("user_hold")
            self.job_admin_release()
            self.assert_job_state("user_hold")
            self.job_user_release()
            self.assert_job_state("queued")
            self.job_user_hold()
            self.assert_job_state("user_hold")
            self.job_admin_hold()
            self.assert_job_state("user_hold")
            self.job_user_release()
            self.assert_job_state("admin_hold")
            self.job_admin_release()
            self.assert_job_state("queued")
        self.job_exec_driver(job_queued = _job_queued)

Paul Rich's avatar
Paul Rich committed
1576
    @timeout(60)
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
    def test_nonpreempt_hold_repeated(self):
        # try to place a hold that's already been placed
        def _job_queued():
            self.assert_job_state("queued")
            self.job_user_hold()
            assert self.job['is_active'] == False
            assert self.job['is_runnable'] == False
            assert self.job['has_completed'] == False
            self.assert_job_state("user_hold")
            self.job_user_hold()
            assert self.job['is_active'] == False
            assert self.job['is_runnable'] == False
            assert self.job['has_completed'] == False
            self.assert_job_state("user_hold")
            self.job_user_release()
            assert self.job['is_active'] == False
            assert self.job['is_runnable'] == True
            assert self.job['has_completed'] == False
            self.assert_job_state("queued")
            self.job_user_release()
            assert self.job['is_active'] == False
            assert self.job['is_runnable'] == True
            assert self.job['has_completed'] == False
            self.assert_job_state("queued")
        self.job_exec_driver(job_queued = _job_queued)

Paul Rich's avatar
Paul Rich committed
1603
    @timeout(60)
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
    def test_nonpreempt_hold__run(self):
        # the job is in the hold state; attempting to run the job should fail
        def _job_queued():
            self.assert_job_state("queued")
            self.job_user_hold()
            self.assert_job_state("user_hold")
        try:
            self.job_exec_driver(job_queued = _job_queued)
            assert False, "attempt to run while in a hold state should fail"
        except xmlrpclib.Fault, e:
            assert e.faultCode == JobRunError.fault_code

Paul Rich's avatar
Paul Rich committed
1616
    @timeout(60)
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
    def test_nonpreempt_hold__kill(self):
        # the job is in the hold state; killing the job should result in immediate termination
        def _job_queued():
            self.assert_job_state("queued")
            self.job_user_hold()
            self.assert_job_state("user_hold")
            self.job_kill()
            self.assert_job_state("done")
        self.job_exec_driver(job_queued = _job_queued, exec_task = False)


Paul Rich's avatar
Paul Rich committed
1628

Paul Rich's avatar
Paul Rich committed
1629