-
Notifications
You must be signed in to change notification settings - Fork 14.8k
/
Copy pathtest_batch_client.py
481 lines (424 loc) · 20.8 KB
/
test_batch_client.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import logging
import time
from unittest import mock
import botocore.exceptions
import pytest
from airflow.exceptions import AirflowException
from airflow.providers.amazon.aws.hooks.batch_client import BatchClientHook
from airflow.providers.amazon.aws.utils.task_log_fetcher import AwsTaskLogFetcher
# Use dummy AWS credentials
AWS_REGION = "eu-west-1"
AWS_ACCESS_KEY_ID = "airflow_dummy_key"
AWS_SECRET_ACCESS_KEY = "airflow_dummy_secret"
JOB_ID = "8ba9d676-4108-4474-9dca-8bbac1da9b19"
LOG_STREAM_NAME = "test/stream/d56a66bb98a14c4593defa1548686edf"
class TestBatchClient:
MAX_RETRIES = 2
STATUS_RETRIES = 3
@mock.patch.dict("os.environ", AWS_DEFAULT_REGION=AWS_REGION)
@mock.patch.dict("os.environ", AWS_ACCESS_KEY_ID=AWS_ACCESS_KEY_ID)
@mock.patch.dict("os.environ", AWS_SECRET_ACCESS_KEY=AWS_SECRET_ACCESS_KEY)
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type")
def setup_method(self, method, get_client_type_mock):
self.get_client_type_mock = get_client_type_mock
self.batch_client = BatchClientHook(
max_retries=self.MAX_RETRIES,
status_retries=self.STATUS_RETRIES,
aws_conn_id="airflow_test",
region_name=AWS_REGION,
)
# We're mocking all actual AWS calls and don't need a connection. This
# avoids an Airflow warning about connection cannot be found.
self.batch_client.get_connection = lambda _: None
self.client_mock = get_client_type_mock.return_value
assert self.batch_client.client == self.client_mock # setup client property
# don't pause in these unit tests
self.mock_delay = mock.Mock(return_value=None)
self.batch_client.delay = self.mock_delay
self.mock_exponential_delay = mock.Mock(return_value=0)
self.batch_client.exponential_delay = self.mock_exponential_delay
def test_init(self):
assert self.batch_client.max_retries == self.MAX_RETRIES
assert self.batch_client.status_retries == self.STATUS_RETRIES
assert self.batch_client.region_name == AWS_REGION
assert self.batch_client.aws_conn_id == "airflow_test"
assert self.batch_client.client == self.client_mock
self.get_client_type_mock.assert_called_once_with(region_name=AWS_REGION)
def test_wait_for_job_with_success(self):
self.client_mock.describe_jobs.return_value = {"jobs": [{"jobId": JOB_ID, "status": "SUCCEEDED"}]}
with mock.patch.object(
self.batch_client,
"poll_for_job_running",
wraps=self.batch_client.poll_for_job_running,
) as job_running:
self.batch_client.wait_for_job(JOB_ID)
job_running.assert_called_once_with(JOB_ID, None)
with mock.patch.object(
self.batch_client,
"poll_for_job_complete",
wraps=self.batch_client.poll_for_job_complete,
) as job_complete:
self.batch_client.wait_for_job(JOB_ID)
job_complete.assert_called_once_with(JOB_ID, None)
assert self.client_mock.describe_jobs.call_count == 4
def test_wait_for_job_with_failure(self):
self.client_mock.describe_jobs.return_value = {"jobs": [{"jobId": JOB_ID, "status": "FAILED"}]}
with mock.patch.object(
self.batch_client,
"poll_for_job_running",
wraps=self.batch_client.poll_for_job_running,
) as job_running:
self.batch_client.wait_for_job(JOB_ID)
job_running.assert_called_once_with(JOB_ID, None)
with mock.patch.object(
self.batch_client,
"poll_for_job_complete",
wraps=self.batch_client.poll_for_job_complete,
) as job_complete:
self.batch_client.wait_for_job(JOB_ID)
job_complete.assert_called_once_with(JOB_ID, None)
assert self.client_mock.describe_jobs.call_count == 4
def test_wait_for_job_with_logs(self):
self.client_mock.describe_jobs.return_value = {"jobs": [{"jobId": JOB_ID, "status": "SUCCEEDED"}]}
batch_log_fetcher = mock.Mock(spec=AwsTaskLogFetcher)
mock_get_batch_log_fetcher = mock.Mock(return_value=batch_log_fetcher)
thread_start = mock.Mock(side_effect=lambda: time.sleep(2))
thread_stop = mock.Mock(side_effect=lambda: time.sleep(2))
thread_join = mock.Mock(side_effect=lambda: time.sleep(2))
with mock.patch.object(
batch_log_fetcher, "start", thread_start
) as mock_fetcher_start, mock.patch.object(
batch_log_fetcher, "stop", thread_stop
) as mock_fetcher_stop, mock.patch.object(
batch_log_fetcher, "join", thread_join
) as mock_fetcher_join:
self.batch_client.wait_for_job(JOB_ID, get_batch_log_fetcher=mock_get_batch_log_fetcher)
mock_get_batch_log_fetcher.assert_called_with(JOB_ID)
mock_fetcher_start.assert_called_once()
mock_fetcher_stop.assert_called_once()
mock_fetcher_join.assert_called_once()
def test_poll_job_running_for_status_running(self):
self.client_mock.describe_jobs.return_value = {"jobs": [{"jobId": JOB_ID, "status": "RUNNING"}]}
self.batch_client.poll_for_job_running(JOB_ID)
self.client_mock.describe_jobs.assert_called_once_with(jobs=[JOB_ID])
def test_poll_job_complete_for_status_success(self):
self.client_mock.describe_jobs.return_value = {"jobs": [{"jobId": JOB_ID, "status": "SUCCEEDED"}]}
self.batch_client.poll_for_job_complete(JOB_ID)
self.client_mock.describe_jobs.assert_called_once_with(jobs=[JOB_ID])
def test_poll_job_complete_raises_for_max_retries(self):
self.client_mock.describe_jobs.return_value = {"jobs": [{"jobId": JOB_ID, "status": "RUNNING"}]}
with pytest.raises(AirflowException) as ctx:
self.batch_client.poll_for_job_complete(JOB_ID)
msg = f"AWS Batch job ({JOB_ID}) status checks exceed max_retries"
assert msg in str(ctx.value)
self.client_mock.describe_jobs.assert_called_with(jobs=[JOB_ID])
assert self.client_mock.describe_jobs.call_count == self.MAX_RETRIES + 1
def test_poll_job_status_hit_api_throttle(self, caplog):
self.client_mock.describe_jobs.side_effect = botocore.exceptions.ClientError(
error_response={"Error": {"Code": "TooManyRequestsException"}},
operation_name="get job description",
)
with pytest.raises(AirflowException) as ctx:
with caplog.at_level(level=logging.getLevelName("WARNING")):
self.batch_client.poll_for_job_complete(JOB_ID)
log_record = caplog.records[0]
assert "Ignored TooManyRequestsException error" in log_record.message
msg = f"AWS Batch job ({JOB_ID}) description error"
assert msg in str(ctx.value)
# It should retry when this client error occurs
self.client_mock.describe_jobs.assert_called_with(jobs=[JOB_ID])
assert self.client_mock.describe_jobs.call_count == self.STATUS_RETRIES
def test_poll_job_status_with_client_error(self):
self.client_mock.describe_jobs.side_effect = botocore.exceptions.ClientError(
error_response={"Error": {"Code": "InvalidClientTokenId"}},
operation_name="get job description",
)
with pytest.raises(botocore.exceptions.ClientError) as ctx:
self.batch_client.poll_for_job_complete(JOB_ID)
assert ctx.value.response["Error"]["Code"] == "InvalidClientTokenId"
# It will not retry when this client error occurs
self.client_mock.describe_jobs.assert_called_once_with(jobs=[JOB_ID])
def test_check_job_success(self):
self.client_mock.describe_jobs.return_value = {"jobs": [{"jobId": JOB_ID, "status": "SUCCEEDED"}]}
status = self.batch_client.check_job_success(JOB_ID)
assert status
self.client_mock.describe_jobs.assert_called_once_with(jobs=[JOB_ID])
def test_check_job_success_raises_failed(self):
self.client_mock.describe_jobs.return_value = {
"jobs": [
{
"jobId": JOB_ID,
"status": "FAILED",
"statusReason": "This is an error reason",
"attempts": [{"exitCode": 1}],
}
]
}
with pytest.raises(AirflowException) as ctx:
self.batch_client.check_job_success(JOB_ID)
self.client_mock.describe_jobs.assert_called_once_with(jobs=[JOB_ID])
msg = f"AWS Batch job ({JOB_ID}) failed"
assert msg in str(ctx.value)
def test_check_job_success_raises_failed_for_multiple_attempts(self):
self.client_mock.describe_jobs.return_value = {
"jobs": [
{
"jobId": JOB_ID,
"status": "FAILED",
"statusReason": "This is an error reason",
"attempts": [{"exitCode": 1}, {"exitCode": 10}],
}
]
}
with pytest.raises(AirflowException) as ctx:
self.batch_client.check_job_success(JOB_ID)
self.client_mock.describe_jobs.assert_called_once_with(jobs=[JOB_ID])
msg = f"AWS Batch job ({JOB_ID}) failed"
assert msg in str(ctx.value)
def test_check_job_success_raises_incomplete(self):
self.client_mock.describe_jobs.return_value = {"jobs": [{"jobId": JOB_ID, "status": "RUNNABLE"}]}
with pytest.raises(AirflowException) as ctx:
self.batch_client.check_job_success(JOB_ID)
self.client_mock.describe_jobs.assert_called_once_with(jobs=[JOB_ID])
msg = f"AWS Batch job ({JOB_ID}) is not complete"
assert msg in str(ctx.value)
def test_check_job_success_raises_unknown_status(self):
status = "STRANGE"
self.client_mock.describe_jobs.return_value = {"jobs": [{"jobId": JOB_ID, "status": status}]}
with pytest.raises(AirflowException) as ctx:
self.batch_client.check_job_success(JOB_ID)
self.client_mock.describe_jobs.assert_called_once_with(jobs=[JOB_ID])
msg = f"AWS Batch job ({JOB_ID}) has unknown status"
assert msg in str(ctx.value)
assert status in str(ctx.value)
def test_check_job_success_raises_without_jobs(self):
self.client_mock.describe_jobs.return_value = {"jobs": []}
with pytest.raises(AirflowException) as ctx:
self.batch_client.check_job_success(JOB_ID)
self.client_mock.describe_jobs.assert_called_once_with(jobs=[JOB_ID])
msg = f"AWS Batch job ({JOB_ID}) description error"
assert msg in str(ctx.value)
def test_terminate_job(self):
self.client_mock.terminate_job.return_value = {}
reason = "Task killed by the user"
response = self.batch_client.terminate_job(JOB_ID, reason)
self.client_mock.terminate_job.assert_called_once_with(jobId=JOB_ID, reason=reason)
assert response == {}
def test_job_awslogs_default(self):
self.client_mock.describe_jobs.return_value = {
"jobs": [
{
"jobId": JOB_ID,
"container": {"logStreamName": LOG_STREAM_NAME},
}
]
}
self.client_mock.meta.client.meta.region_name = AWS_REGION
awslogs = self.batch_client.get_job_awslogs_info(JOB_ID)
assert awslogs["awslogs_stream_name"] == LOG_STREAM_NAME
assert awslogs["awslogs_group"] == "/aws/batch/job"
assert awslogs["awslogs_region"] == AWS_REGION
def test_job_awslogs_user_defined(self):
self.client_mock.describe_jobs.return_value = {
"jobs": [
{
"jobId": JOB_ID,
"container": {
"logStreamName": LOG_STREAM_NAME,
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/test/batch/job",
"awslogs-region": "ap-southeast-2",
},
},
},
}
]
}
awslogs = self.batch_client.get_job_awslogs_info(JOB_ID)
assert awslogs["awslogs_stream_name"] == LOG_STREAM_NAME
assert awslogs["awslogs_group"] == "/test/batch/job"
assert awslogs["awslogs_region"] == "ap-southeast-2"
def test_job_no_awslogs_stream(self, caplog):
self.client_mock.describe_jobs.return_value = {
"jobs": [
{
"jobId": JOB_ID,
"container": {"logConfiguration": {}},
}
]
}
with caplog.at_level(level=logging.WARNING):
assert self.batch_client.get_job_awslogs_info(JOB_ID) is None
assert len(caplog.records) == 1
assert "doesn't have any AWS CloudWatch Stream" in caplog.messages[0]
def test_job_not_recognized_job(self):
self.client_mock.describe_jobs.return_value = {"jobs": [{"jobId": JOB_ID}]}
with pytest.raises(AirflowException) as ctx:
self.batch_client.get_job_awslogs_info(JOB_ID)
# It should not retry when this client error occurs
self.client_mock.describe_jobs.assert_called_once_with(jobs=[JOB_ID])
msg = "is not a supported job type"
assert msg in str(ctx.value)
def test_job_splunk_logs(self, caplog):
self.client_mock.describe_jobs.return_value = {
"jobs": [
{
"jobId": JOB_ID,
"logStreamName": LOG_STREAM_NAME,
"container": {
"logConfiguration": {
"logDriver": "splunk",
}
},
}
]
}
with caplog.at_level(level=logging.WARNING):
assert self.batch_client.get_job_awslogs_info(JOB_ID) is None
assert len(caplog.records) == 1
assert "uses non-aws log drivers. AWS CloudWatch logging disabled." in caplog.messages[0]
def test_job_awslogs_multinode_job(self):
self.client_mock.describe_jobs.return_value = {
"jobs": [
{
"jobId": JOB_ID,
"attempts": [
{"container": {"exitCode": 0, "logStreamName": "test/stream/attempt0"}},
{"container": {"exitCode": 0, "logStreamName": "test/stream/attempt1"}},
],
"nodeProperties": {
"mainNode": 0,
"nodeRangeProperties": [
{
"targetNodes": "0:",
"container": {
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/test/batch/job-a",
"awslogs-region": AWS_REGION,
},
}
},
},
{
"targetNodes": "1:",
"container": {
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/test/batch/job-b",
"awslogs-region": AWS_REGION,
},
}
},
},
],
},
}
]
}
awslogs = self.batch_client.get_job_all_awslogs_info(JOB_ID)
assert len(awslogs) == 4
assert all([log["awslogs_region"] == AWS_REGION for log in awslogs])
combinations = {
("test/stream/attempt0", "/test/batch/job-a"): False,
("test/stream/attempt0", "/test/batch/job-b"): False,
("test/stream/attempt1", "/test/batch/job-a"): False,
("test/stream/attempt1", "/test/batch/job-b"): False,
}
for log_info in awslogs:
# mark combinations that we see
combinations[(log_info["awslogs_stream_name"], log_info["awslogs_group"])] = True
assert len(combinations) == 4
# all combinations listed above should have been seen
assert all(combinations.values())
class TestBatchClientDelays:
@mock.patch.dict("os.environ", AWS_DEFAULT_REGION=AWS_REGION)
@mock.patch.dict("os.environ", AWS_ACCESS_KEY_ID=AWS_ACCESS_KEY_ID)
@mock.patch.dict("os.environ", AWS_SECRET_ACCESS_KEY=AWS_SECRET_ACCESS_KEY)
def setup_method(self, method):
self.batch_client = BatchClientHook(aws_conn_id="airflow_test", region_name=AWS_REGION)
# We're mocking all actual AWS calls and don't need a connection. This
# avoids an Airflow warning about connection cannot be found.
self.batch_client.get_connection = lambda _: None
def test_init(self):
assert self.batch_client.max_retries == self.batch_client.MAX_RETRIES
assert self.batch_client.status_retries == self.batch_client.STATUS_RETRIES
assert self.batch_client.region_name == AWS_REGION
assert self.batch_client.aws_conn_id == "airflow_test"
def test_add_jitter(self):
minima = 0
width = 5
result = self.batch_client.add_jitter(0, width=width, minima=minima)
assert result >= minima
assert result <= width
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.uniform")
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.sleep")
def test_delay_defaults(self, mock_sleep, mock_uniform):
assert BatchClientHook.DEFAULT_DELAY_MIN == 1
assert BatchClientHook.DEFAULT_DELAY_MAX == 10
mock_uniform.return_value = 0
self.batch_client.delay()
mock_uniform.assert_called_once_with(
BatchClientHook.DEFAULT_DELAY_MIN, BatchClientHook.DEFAULT_DELAY_MAX
)
mock_sleep.assert_called_once_with(0)
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.uniform")
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.sleep")
def test_delay_with_zero(self, mock_sleep, mock_uniform):
self.batch_client.delay(0)
mock_uniform.assert_called_once_with(0, 1) # in add_jitter
mock_sleep.assert_called_once_with(mock_uniform.return_value)
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.uniform")
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.sleep")
def test_delay_with_int(self, mock_sleep, mock_uniform):
self.batch_client.delay(5)
mock_uniform.assert_called_once_with(4, 6) # in add_jitter
mock_sleep.assert_called_once_with(mock_uniform.return_value)
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.uniform")
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.sleep")
def test_delay_with_float(self, mock_sleep, mock_uniform):
self.batch_client.delay(5.0)
mock_uniform.assert_called_once_with(4.0, 6.0) # in add_jitter
mock_sleep.assert_called_once_with(mock_uniform.return_value)
@pytest.mark.parametrize(
"tries, lower, upper",
[
(0, 0, 1),
(1, 0, 2),
(2, 0, 3),
(3, 1, 5),
(4, 2, 7),
(5, 3, 11),
(6, 4, 14),
(7, 6, 19),
(8, 8, 25),
(9, 10, 31),
(45, 200, 600), # > 40 tries invokes maximum delay allowed
],
)
def test_exponential_delay(self, tries, lower, upper):
result = self.batch_client.exponential_delay(tries)
assert result >= lower
assert result <= upper