forked from ansible/ansible-runner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_transmit_worker_process.py
401 lines (303 loc) · 14 KB
/
test_transmit_worker_process.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import io
import os
import socket
import concurrent.futures
import time
import pytest
import json
from ansible_runner import run
from ansible_runner.streaming import Transmitter, Worker, Processor
import ansible_runner.interface # AWX import pattern
class TestStreamingUsage:
@pytest.fixture(autouse=True)
def reset_self_props(self):
self.status_data = None
def status_handler(self, status_data, runner_config=None):
self.status_data = status_data
def get_job_kwargs(self, job_type):
"""For this test scenaro, the ansible-runner interface kwargs"""
if job_type == 'run':
job_kwargs = dict(playbook='debug.yml')
else:
job_kwargs = dict(module='setup', host_pattern='localhost')
# also test use of user env vars
job_kwargs['envvars'] = dict(MY_ENV_VAR='bogus')
return job_kwargs
def check_artifacts(self, process_dir, job_type):
assert set(os.listdir(process_dir)) == {'artifacts', }
events_dir = os.path.join(process_dir, 'artifacts', 'job_events')
events = []
for file in os.listdir(events_dir):
with open(os.path.join(events_dir, file), 'r') as f:
if file in ('status', 'rc'):
continue
content = f.read()
events.append(json.loads(content))
stdout = '\n'.join(event['stdout'] for event in events)
if job_type == 'run':
assert 'Hello world!' in stdout
else:
assert '"ansible_facts"' in stdout
@pytest.mark.parametrize("job_type", ['run', 'adhoc'])
def test_remote_job_interface(self, tmp_path, project_fixtures, job_type):
transmit_dir = project_fixtures / 'debug'
worker_dir = tmp_path / 'for_worker'
worker_dir.mkdir()
process_dir = tmp_path / 'for_process'
process_dir.mkdir()
job_kwargs = self.get_job_kwargs(job_type)
outgoing_buffer_file = tmp_path / 'buffer_out'
outgoing_buffer_file.touch()
outgoing_buffer = outgoing_buffer_file.open('b+r')
transmitter = Transmitter(_output=outgoing_buffer, private_data_dir=transmit_dir, **job_kwargs)
for key, value in job_kwargs.items():
assert transmitter.kwargs.get(key, '') == value
status, rc = transmitter.run()
assert rc in (None, 0)
assert status == 'unstarted'
outgoing_buffer.seek(0)
sent = outgoing_buffer.read()
assert sent # should not be blank at least
assert b'zipfile' in sent
incoming_buffer_file = tmp_path / 'buffer_in'
incoming_buffer_file.touch()
incoming_buffer = incoming_buffer_file.open('b+r')
outgoing_buffer.seek(0)
worker = Worker(_input=outgoing_buffer, _output=incoming_buffer, private_data_dir=worker_dir)
worker.run()
outgoing_buffer.seek(0)
assert set(os.listdir(worker_dir)) == {'artifacts', 'inventory', 'project', 'env'}, outgoing_buffer.read()
incoming_buffer.seek(0) # again, be kind, rewind
processor = Processor(_input=incoming_buffer, private_data_dir=process_dir)
processor.run()
self.check_artifacts(str(process_dir), job_type)
@pytest.mark.parametrize("job_type", ['run', 'adhoc'])
def test_remote_job_by_sockets(self, tmp_path, project_fixtures, job_type):
"""This test case is intended to be close to how the AWX use case works
the process interacts with receptorctl with sockets
sockets are used here, but worker is manually called instead of invoked by receptor
"""
transmit_dir = project_fixtures / 'debug'
worker_dir = tmp_path / 'for_worker'
worker_dir.mkdir()
process_dir = tmp_path / 'for_process'
process_dir.mkdir()
job_kwargs = self.get_job_kwargs(job_type)
def transmit_method(transmit_sockfile_write):
return ansible_runner.interface.run(
streamer='transmit',
_output=transmit_sockfile_write,
private_data_dir=transmit_dir, **job_kwargs)
def worker_method(transmit_sockfile_read, results_sockfile_write):
return ansible_runner.interface.run(
streamer='worker',
_input=transmit_sockfile_read, _output=results_sockfile_write,
private_data_dir=worker_dir, **job_kwargs)
def process_method(results_sockfile_read):
return ansible_runner.interface.run(
streamer='process', quiet=True,
_input=results_sockfile_read,
private_data_dir=process_dir, status_handler=self.status_handler, **job_kwargs)
transmit_socket_write, transmit_socket_read = socket.socketpair()
results_socket_write, results_socket_read = socket.socketpair()
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
transmit_future = executor.submit(transmit_method, transmit_socket_write.makefile('wb'))
# In real AWX implementation, worker is done via receptorctl
executor.submit(worker_method, transmit_socket_read.makefile('rb'), results_socket_write.makefile('wb'))
while True:
if transmit_future.done():
break
time.sleep(0.05) # additionally, AWX calls cancel_callback()
res = transmit_future.result()
assert res.rc in (None, 0)
assert res.status == 'unstarted'
process_future = executor.submit(process_method, results_socket_read.makefile('rb'))
while True:
if process_future.done():
break
time.sleep(0.05) # additionally, AWX calls cancel_callback()
for s in (transmit_socket_write, transmit_socket_read, results_socket_write, results_socket_read):
s.close()
assert self.status_data is not None
if 'result_traceback' in self.status_data:
raise Exception(self.status_data['result_traceback'])
assert self.status_data.get('status') == 'successful'
assert set(os.listdir(worker_dir)) == {'artifacts', 'inventory', 'project', 'env'}
self.check_artifacts(str(process_dir), job_type)
def test_process_isolation_executable_not_exist(self, tmp_path, mocker):
"""Case transmit should not fail if process isolation executable does not exist and
worker should fail if process isolation executable does not exist
"""
mocker.patch.object(ansible_runner.interface, 'check_isolation_executable_installed', return_value=False)
job_kwargs = self.get_job_kwargs('run')
job_kwargs['process_isolation'] = True
job_kwargs['process_isolation_executable'] = 'does_not_exist'
outgoing_buffer_file = tmp_path / 'buffer_out'
outgoing_buffer_file.touch()
outgoing_buffer = outgoing_buffer_file.open('b+r')
transmitter = ansible_runner.interface.run(
streamer='transmit',
_output=outgoing_buffer,
**job_kwargs,
)
# valide process_isolation kwargs are passed to transmitter
assert transmitter.kwargs['process_isolation'] == job_kwargs['process_isolation']
assert transmitter.kwargs['process_isolation_executable'] == job_kwargs['process_isolation_executable']
# validate that transmit did not fail due to missing process isolation executable
assert transmitter.rc in (None, 0)
# validate that transmit buffer is not empty
outgoing_buffer.seek(0)
sent = outgoing_buffer.read()
assert sent # should not be blank at least
# validate buffer contains kwargs
assert b'kwargs' in sent
# validate kwargs in buffer contain correct process_isolation and process_isolation_executable
for line in sent.decode('utf-8').split('\n'):
if "kwargs" in line:
kwargs = json.loads(line).get("kwargs", {})
assert kwargs['process_isolation'] == job_kwargs['process_isolation']
assert kwargs['process_isolation_executable'] == job_kwargs['process_isolation_executable']
break
worker_dir = tmp_path / 'for_worker'
incoming_buffer_file = tmp_path / 'buffer_in'
incoming_buffer_file.touch()
incoming_buffer = incoming_buffer_file.open('b+r')
outgoing_buffer.seek(0)
# validate that worker fails raise sys.exit(1) when process isolation executable does not exist
with pytest.raises(SystemExit) as exc:
ansible_runner.interface.run(
streamer='worker',
_input=outgoing_buffer,
_output=incoming_buffer,
private_data_dir=worker_dir,
)
assert exc.value.code == 1
@pytest.fixture
def transmit_stream(project_fixtures, tmp_path):
outgoing_buffer = tmp_path / 'buffer'
outgoing_buffer.touch()
transmit_dir = project_fixtures / 'debug'
with outgoing_buffer.open('wb') as f:
transmitter = Transmitter(_output=f, private_data_dir=transmit_dir, playbook='debug.yml')
status, rc = transmitter.run()
assert rc in (None, 0)
assert status == 'unstarted'
return outgoing_buffer
@pytest.fixture
def worker_stream(transmit_stream, tmp_path):
ingoing_buffer = tmp_path / 'buffer2' # basically how some demos work
ingoing_buffer.touch()
worker_dir = tmp_path / 'worker_dir'
worker_dir.mkdir()
with transmit_stream.open('rb') as out:
with ingoing_buffer.open('wb') as f:
worker = Worker(_input=out, _output=f, private_data_dir=worker_dir)
status, rc = worker.run()
assert rc in (None, 0)
assert status == 'successful'
return ingoing_buffer
def test_worker_without_delete_no_dir(tmp_path, cli, transmit_stream):
worker_dir = tmp_path / 'for_worker'
with open(transmit_stream, 'rb') as stream:
worker_args = ['worker', '--private-data-dir', str(worker_dir)]
r = cli(worker_args, stdin=stream)
assert '{"eof": true}' in r.stdout
assert worker_dir.joinpath('project', 'debug.yml').exists()
def test_worker_without_delete_dir_exists(tmp_path, cli, transmit_stream):
worker_dir = tmp_path / 'for_worker'
worker_dir.mkdir()
test_file_path = worker_dir / 'test_file.txt'
test_file_path.write_text('data\n')
with open(transmit_stream, 'rb') as stream:
worker_args = ['worker', '--private-data-dir', str(worker_dir)]
r = cli(worker_args, stdin=stream)
assert '{"eof": true}' in r.stdout
assert worker_dir.joinpath('project', 'debug.yml').exists()
assert test_file_path.exists()
def test_worker_delete_no_dir(tmp_path, cli, transmit_stream):
"""
Case where non-existing --delete is provided to worker command
it should always delete everything both before and after the run
"""
worker_dir = tmp_path / 'for_worker'
with open(transmit_stream, 'rb') as f:
worker_args = ['worker', '--private-data-dir', str(worker_dir), '--delete']
r = cli(worker_args, stdin=f)
assert '{"eof": true}' in r.stdout
assert not worker_dir.exists()
assert not worker_dir.joinpath('project', 'debug.yml').exists()
def test_worker_delete_dir_exists(tmp_path, cli, transmit_stream):
"""
Case where non-existing --delete is provided to worker command
it should always delete everything both before and after the run
"""
worker_dir = tmp_path / 'for_worker'
worker_dir.mkdir()
test_file = worker_dir / 'test_file.txt'
test_file.write_text('data\n')
with open(transmit_stream, 'rb') as f:
worker_args = ['worker', '--private-data-dir', str(worker_dir), '--delete']
r = cli(worker_args, stdin=f)
assert '{"eof": true}' in r.stdout
assert not worker_dir.exists()
assert not worker_dir.joinpath('project', 'debug.yml').exists()
def test_process_with_custom_ident(tmp_path, cli, worker_stream):
process_dir = tmp_path / 'for_process'
process_dir.mkdir()
with open(worker_stream, 'rb') as f:
process_args = ['process', str(process_dir), '--ident', 'custom_ident']
r = cli(process_args, stdin=f)
assert 'Hello world!' in r.stdout
assert (process_dir / 'artifacts').exists()
assert (process_dir / 'artifacts' / 'custom_ident').exists()
assert (process_dir / 'artifacts' / 'custom_ident' / 'job_events').exists()
def test_missing_private_dir_transmit(tmpdir):
outgoing_buffer = io.BytesIO()
# Transmit
with pytest.raises(ValueError) as excinfo:
run(
streamer='transmit',
_output=outgoing_buffer,
private_data_dir='/foo/bar/baz',
playbook='debug.yml',
)
assert "private_data_dir path is either invalid or does not exist" in str(excinfo.value)
def test_garbage_private_dir_worker(tmp_path):
worker_dir = tmp_path / 'for_worker'
worker_dir.mkdir()
incoming_buffer = io.BytesIO(
b'{"kwargs": {"playbook": "debug.yml"}}\n{"zipfile": 5}\n\x01\x02\x03\x04\x05{"eof": true}\n')
outgoing_buffer = io.BytesIO()
# Worker
run(
streamer='worker',
_input=incoming_buffer,
_output=outgoing_buffer,
private_data_dir=worker_dir,
)
sent = outgoing_buffer.getvalue()
assert b'"status": "error"' in sent
def test_unparsable_private_dir_worker(tmp_path):
worker_dir = tmp_path / 'for_worker'
worker_dir.mkdir()
incoming_buffer = io.BytesIO(b'')
outgoing_buffer = io.BytesIO()
# Worker
run(
streamer='worker',
_input=incoming_buffer,
_output=outgoing_buffer,
private_data_dir=worker_dir,
)
sent = outgoing_buffer.getvalue()
assert b'"status": "error"' in sent
def test_unparsable_private_dir_processor(tmp_path):
process_dir = tmp_path / 'for_process'
process_dir.mkdir()
incoming_buffer = io.BytesIO(b'')
processor = run(
streamer='process',
_input=incoming_buffer,
private_data_dir=process_dir,
)
assert processor.status == 'error'