-
Notifications
You must be signed in to change notification settings - Fork 239
/
base.py
508 lines (447 loc) · 17.4 KB
/
base.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
import json
import pathlib
import sys
import unittest.mock
from base64 import b64encode
from copy import deepcopy
from datetime import datetime, timezone
import deepdiff
from kubernetes import client
from kubernetes import client as k8s_client
from kubernetes.client import V1EnvVar
from mlrun.api.utils.singletons.k8s import get_k8s
from mlrun.config import config as mlconf
from mlrun.model import new_task
from mlrun.runtimes.constants import PodPhases
from mlrun.utils import create_logger
from mlrun.utils.azure_vault import AzureVaultStore
from mlrun.utils.vault import VaultStore
logger = create_logger(level="debug", name="test-runtime")
class TestRuntimeBase:
def setup_method(self, method):
self.namespace = mlconf.namespace = "test-namespace"
get_k8s().namespace = self.namespace
self._logger = logger
self.project = "test-project"
self.name = "test-function"
self.run_uid = "test_run_uid"
self.image_name = "mlrun/mlrun:latest"
self.artifact_path = "/tmp"
self.function_name_label = "mlrun/name"
self.code_filename = str(self.assets_path / "sample_function.py")
self.requirements_file = str(self.assets_path / "requirements.txt")
self.vault_secrets = ["secret1", "secret2", "AWS_KEY"]
self.vault_secret_value = "secret123!@"
self.vault_secret_name = "vault-secret"
self.azure_vault_secrets = ["azure_secret1", "azure_secret2"]
self.azure_secret_value = "azure-secret-123!@"
self.azure_vault_secret_name = "k8s-vault-secret"
self._logger.info(
f"Setting up test {self.__class__.__name__}::{method.__name__}"
)
self.custom_setup()
self._logger.info(
f"Finished setting up test {self.__class__.__name__}::{method.__name__}"
)
def teardown_method(self, method):
self._logger.info(
f"Tearing down test {self.__class__.__name__}::{method.__name__}"
)
self.custom_teardown()
self._logger.info(
f"Finished tearing down test {self.__class__.__name__}::{method.__name__}"
)
@property
def assets_path(self):
return (
pathlib.Path(sys.modules[self.__module__].__file__).absolute().parent
/ "assets"
)
def _generate_runtime(self):
pass
def custom_setup(self):
pass
def custom_teardown(self):
pass
def _generate_task(self):
return new_task(
name=self.name, project=self.project, artifact_path=self.artifact_path
)
def _generate_affinity(self):
return k8s_client.V1Affinity(
node_affinity=k8s_client.V1NodeAffinity(
preferred_during_scheduling_ignored_during_execution=[
k8s_client.V1PreferredSchedulingTerm(
weight=1,
preference=k8s_client.V1NodeSelectorTerm(
match_expressions=[
k8s_client.V1NodeSelectorRequirement(
key="some_node_label",
operator="In",
values=[
"possible-label-value-1",
"possible-label-value-2",
],
)
]
),
)
],
required_during_scheduling_ignored_during_execution=k8s_client.V1NodeSelector(
node_selector_terms=[
k8s_client.V1NodeSelectorTerm(
match_expressions=[
k8s_client.V1NodeSelectorRequirement(
key="some_node_label",
operator="In",
values=[
"required-label-value-1",
"required-label-value-2",
],
)
]
),
]
),
),
pod_affinity=k8s_client.V1PodAffinity(
required_during_scheduling_ignored_during_execution=[
k8s_client.V1PodAffinityTerm(
label_selector=k8s_client.V1LabelSelector(
match_labels={"some-pod-label-key": "some-pod-label-value"}
),
namespaces=["namespace-a", "namespace-b"],
topology_key="key-1",
)
]
),
pod_anti_affinity=k8s_client.V1PodAntiAffinity(
preferred_during_scheduling_ignored_during_execution=[
k8s_client.V1WeightedPodAffinityTerm(
weight=1,
pod_affinity_term=k8s_client.V1PodAffinityTerm(
label_selector=k8s_client.V1LabelSelector(
match_expressions=[
k8s_client.V1LabelSelectorRequirement(
key="some_pod_label",
operator="NotIn",
values=[
"forbidden-label-value-1",
"forbidden-label-value-2",
],
)
]
),
namespaces=["namespace-c"],
topology_key="key-2",
),
)
]
),
)
def _mock_create_namespaced_pod(self):
def _generate_pod(namespace, pod):
terminated_container_state = client.V1ContainerStateTerminated(
finished_at=datetime.now(timezone.utc), exit_code=0
)
container_state = client.V1ContainerState(
terminated=terminated_container_state
)
container_status = client.V1ContainerStatus(
state=container_state,
image=self.image_name,
image_id="must-provide-image-id",
name=self.name,
ready=True,
restart_count=0,
)
status = client.V1PodStatus(
phase=PodPhases.succeeded, container_statuses=[container_status]
)
response_pod = deepcopy(pod)
response_pod.status = status
response_pod.metadata.name = "test-pod"
response_pod.metadata.namespace = namespace
return response_pod
get_k8s().v1api.create_namespaced_pod = unittest.mock.Mock(
side_effect=_generate_pod
)
# Vault now supported in KubeJob and Serving, so moved to base.
def _mock_vault_functionality(self):
secret_dict = {key: self.vault_secret_value for key in self.vault_secrets}
VaultStore.get_secrets = unittest.mock.Mock(return_value=secret_dict)
azure_secret_dict = {
key: self.azure_secret_value for key in self.azure_vault_secrets
}
AzureVaultStore.get_secrets = unittest.mock.Mock(return_value=azure_secret_dict)
object_meta = client.V1ObjectMeta(
name="test-service-account", namespace=self.namespace
)
secret = client.V1ObjectReference(
name=self.vault_secret_name, namespace=self.namespace
)
service_account = client.V1ServiceAccount(
metadata=object_meta, secrets=[secret]
)
get_k8s().v1api.read_namespaced_service_account = unittest.mock.Mock(
return_value=service_account
)
def _execute_run(self, runtime, **kwargs):
# Reset the mock, so that when checking is create_pod was called, no leftovers are there (in case running
# multiple runs in the same test)
get_k8s().v1api.create_namespaced_pod.reset_mock()
runtime.run(
name=self.name,
project=self.project,
artifact_path=self.artifact_path,
**kwargs,
)
def _assert_labels(self, labels: dict, expected_class_name):
expected_labels = {
"mlrun/class": expected_class_name,
self.function_name_label: self.name,
"mlrun/project": self.project,
"mlrun/tag": "latest",
}
for key in expected_labels:
assert labels[key] == expected_labels[key]
def _assert_function_config(
self,
config,
expected_params,
expected_inputs,
expected_hyper_params,
expected_secrets,
expected_labels,
):
function_metadata = config["metadata"]
assert function_metadata["name"] == self.name
assert function_metadata["project"] == self.project
function_spec = config["spec"]
assert function_spec["output_path"] == self.artifact_path
if expected_params:
assert (
deepdiff.DeepDiff(
function_spec["parameters"], expected_params, ignore_order=True
)
== {}
)
if expected_inputs:
assert (
deepdiff.DeepDiff(
function_spec["inputs"], expected_inputs, ignore_order=True
)
== {}
)
if expected_hyper_params:
assert (
deepdiff.DeepDiff(
function_spec["hyperparams"],
expected_hyper_params,
ignore_order=True,
)
== {}
)
if expected_secrets:
assert (
deepdiff.DeepDiff(
function_spec["secret_sources"],
[expected_secrets],
ignore_order=True,
)
== {}
)
if expected_labels:
diff_result = deepdiff.DeepDiff(
function_metadata["labels"], expected_labels, ignore_order=True,
)
# We just care that the values we look for are fully there.
diff_result.pop("dictionary_item_removed", None)
assert diff_result == {}
@staticmethod
def _assert_pod_env(pod_env, expected_variables):
for env_variable in pod_env:
if isinstance(env_variable, V1EnvVar):
env_variable = dict(name=env_variable.name, value=env_variable.value)
name = env_variable["name"]
if name in expected_variables:
if expected_variables[name]:
assert expected_variables[name] == env_variable["value"]
expected_variables.pop(name)
# Make sure all variables were accounted for
assert len(expected_variables) == 0
def _get_pod_creation_args(self):
args, _ = get_k8s().v1api.create_namespaced_pod.call_args
return args[1]
def _get_namespace_arg(self):
args, _ = get_k8s().v1api.create_namespaced_pod.call_args
return args[0]
def _assert_v3io_mount_configured(self, v3io_user, v3io_access_key):
args = self._get_pod_creation_args()
pod_spec = args.spec
container_spec = pod_spec.containers[0]
pod_env = container_spec.env
self._assert_pod_env(
pod_env,
{
"V3IO_API": None,
"V3IO_USERNAME": v3io_user,
"V3IO_ACCESS_KEY": v3io_access_key,
},
)
expected_volume = {
"flexVolume": {
"driver": "v3io/fuse",
"options": {"accessKey": v3io_access_key},
},
"name": "v3io",
}
assert (
deepdiff.DeepDiff(pod_spec.volumes[0], expected_volume, ignore_order=True)
== {}
)
expected_volume_mounts = [
{"mountPath": "/v3io", "name": "v3io", "subPath": ""},
{"mountPath": "/User", "name": "v3io", "subPath": f"users/{v3io_user}"},
]
assert (
deepdiff.DeepDiff(
container_spec.volume_mounts, expected_volume_mounts, ignore_order=True
)
== {}
)
def _assert_pvc_mount_configured(self, pvc_name, pvc_mount_path, volume_name):
args = self._get_pod_creation_args()
pod_spec = args.spec
expected_volume = {
"name": volume_name,
"persistentVolumeClaim": {"claimName": pvc_name},
}
assert (
deepdiff.DeepDiff(pod_spec.volumes[0], expected_volume, ignore_order=True)
== {}
)
expected_volume_mounts = [
{"mountPath": pvc_mount_path, "name": volume_name},
]
container_spec = pod_spec.containers[0]
assert (
deepdiff.DeepDiff(
container_spec.volume_mounts, expected_volume_mounts, ignore_order=True
)
== {}
)
def _assert_secret_mount(self, volume_name, secret_name, default_mode, mount_path):
args = self._get_pod_creation_args()
pod_spec = args.spec
expected_volume = {
"name": volume_name,
"secret": {"defaultMode": default_mode, "secretName": secret_name},
}
assert (
deepdiff.DeepDiff(pod_spec.volumes[0], expected_volume, ignore_order=True)
== {}
)
expected_volume_mounts = [
{"mountPath": mount_path, "name": volume_name},
]
container_spec = pod_spec.containers[0]
assert (
deepdiff.DeepDiff(
container_spec.volume_mounts, expected_volume_mounts, ignore_order=True
)
== {}
)
def _assert_pod_creation_config(
self,
expected_runtime_class_name="job",
expected_params=None,
expected_inputs=None,
expected_hyper_params=None,
expected_secrets=None,
expected_limits=None,
expected_requests=None,
expected_code=None,
expected_env={},
expected_node_name=None,
expected_node_selector=None,
expected_affinity=None,
assert_create_pod_called=True,
assert_namespace_env_variable=True,
expected_labels=None,
):
if assert_create_pod_called:
create_pod_mock = get_k8s().v1api.create_namespaced_pod
create_pod_mock.assert_called_once()
assert self._get_namespace_arg() == self.namespace
pod = self._get_pod_creation_args()
self._assert_labels(pod.metadata.labels, expected_runtime_class_name)
container_spec = pod.spec.containers[0]
self._assert_container_resources(
container_spec, expected_limits, expected_requests
)
pod_env = container_spec.env
expected_code_found = False
if assert_namespace_env_variable:
expected_env["MLRUN_NAMESPACE"] = self.namespace
self._assert_pod_env(pod_env, expected_env)
for env_variable in pod_env:
if isinstance(env_variable, V1EnvVar):
env_variable = dict(name=env_variable.name, value=env_variable.value)
if env_variable["name"] == "MLRUN_EXEC_CONFIG":
function_config = json.loads(env_variable["value"])
self._assert_function_config(
function_config,
expected_params,
expected_inputs,
expected_hyper_params,
expected_secrets,
expected_labels,
)
if expected_code and env_variable["name"] == "MLRUN_EXEC_CODE":
assert env_variable["value"] == b64encode(
expected_code.encode("utf-8")
).decode("utf-8")
expected_code_found = True
if expected_code:
assert expected_code_found
if expected_node_name:
assert pod.spec.node_name == expected_node_name
if expected_node_selector:
assert (
deepdiff.DeepDiff(
pod.spec.node_selector, expected_node_selector, ignore_order=True,
)
== {}
)
if expected_affinity:
assert (
deepdiff.DeepDiff(
pod.spec.affinity.to_dict(),
expected_affinity.to_dict(),
ignore_order=True,
)
== {}
)
assert pod.spec.containers[0].image == self.image_name
def _assert_container_resources(
self, container_spec, expected_limits, expected_requests
):
if expected_limits:
assert (
deepdiff.DeepDiff(
container_spec.resources["limits"],
expected_limits,
ignore_order=True,
)
== {}
)
if expected_requests:
assert (
deepdiff.DeepDiff(
container_spec.resources["requests"],
expected_requests,
ignore_order=True,
)
== {}
)