Repository navigation
Expand file tree
/
Copy pathtest_router_flavors_hook.py
More file actions
498 lines (399 loc) · 16.5 KB
/
Copy pathtest_router_flavors_hook.py
File metadata and controls
498 lines (399 loc) · 16.5 KB
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
"""Tests for the router flavor hook: how the plugin wires into the framework.
The generic driver is covered in ``test_framework.py``; these tests cover only
what is specific to this plugin, plus one end-to-end run through ``main()``.
"""
from __future__ import annotations
import importlib
import json
import types
from pathlib import Path
from typing import Any
from unittest import mock
import pytest
import openstack_sync.utils as utils
from openstack_sync.hooks import router_flavors as hook
from openstack_sync.hooks.framework import CleanupPolicy
from openstack_sync.hooks.framework import PruneRequest
from openstack_sync.hooks.framework import SyncPlan
from openstack_sync.hooks.framework import SyncResource
from openstack_sync.plugins.neutron.router_flavors import markers
from openstack_sync.plugins.neutron.router_flavors.config import BINDING_NAME
from openstack_sync.plugins.neutron.router_flavors.config import ENV_PREFIX
from openstack_sync.plugins.neutron.router_flavors.config import SERVICE_TYPE
from tests.conftest import CRD_API_VERSION
from tests.conftest import CRD_KIND
from tests.conftest import make_hook_config
ENV_NAMES = (
"BINDING_CONTEXT_PATH",
f"{ENV_PREFIX}_ENABLED",
f"{ENV_PREFIX}_SYNC_CRONTAB",
f"{ENV_PREFIX}_PRUNE",
f"{ENV_PREFIX}_STATUS_ENABLED",
f"{ENV_PREFIX}_READY_RETRIES",
f"{ENV_PREFIX}_READY_DELAY",
"POD_NAMESPACE",
)
FAKE_CLOUDS_YAML = """
clouds:
understack:
auth:
auth_url: https://keystone.example.com/v3
username: infrasetup
password: secret
project_name: baremetal
region_name: iad3
"""
def clear_env(monkeypatch: pytest.MonkeyPatch) -> None:
for name in ENV_NAMES:
monkeypatch.delenv(name, raising=False)
def router_flavor_object(name: str, spec: dict | None = None) -> dict:
flavor_spec: dict[str, Any] = {
"name": name,
"service_type": SERVICE_TYPE,
"description": f"{name} description",
"is_enabled": True,
"service_profiles": [
{
"driver": "neutron_understack.l3_router.vrf.Vrf",
"description": f"{name} profile",
"meta_info": {"vni_alloc": "auto"},
"is_enabled": True,
}
],
"cloudCredentialsRef": {
"secretName": "infrasetup",
"cloudName": "understack",
},
}
flavor_spec.update(spec or {})
return {
"apiVersion": CRD_API_VERSION,
"kind": CRD_KIND,
"metadata": {"name": name, "namespace": "openstack", "generation": 3},
"spec": flavor_spec,
}
def write_binding_context(path: Path, contexts: list[dict]) -> str:
context_path = path / "binding-context.json"
context_path.write_text(json.dumps(contexts), encoding="utf-8")
return str(context_path)
# ---------------------------------------------------------------------------
# Import safety
# ---------------------------------------------------------------------------
def test_module_import_is_safe_with_bad_runtime_env(monkeypatch):
"""Importing must not read runtime config.
Shell-operator imports the hook to ask for its config before the full
environment is guaranteed, so a malformed value must not break import.
"""
monkeypatch.setenv(f"{ENV_PREFIX}_READY_RETRIES", "not-a-number")
monkeypatch.setenv(f"{ENV_PREFIX}_ENABLED", "not-a-bool")
importlib.reload(hook)
def test_config_flag_prints_json(monkeypatch, capsys):
clear_env(monkeypatch)
monkeypatch.setattr(hook.sys, "argv", ["router_flavors.py", "--config"])
assert hook.main() == 0
assert json.loads(capsys.readouterr().out)["onStartup"] == 10
def test_enabled_config_flag_watches_this_crd(monkeypatch, capsys):
clear_env(monkeypatch)
monkeypatch.setenv(f"{ENV_PREFIX}_ENABLED", "true")
monkeypatch.setattr(hook.sys, "argv", ["router_flavors.py", "--config"])
assert hook.main() == 0
config = json.loads(capsys.readouterr().out)
(binding,) = config["kubernetes"]
assert binding["name"] == BINDING_NAME
assert binding["kind"] == CRD_KIND
# ---------------------------------------------------------------------------
# Plugin wiring
# ---------------------------------------------------------------------------
def test_plugin_reconcile_delegates_to_sync_flavor():
plugin = hook.RouterFlavorPlugin(make_hook_config())
conn = mock.MagicMock()
cache: dict[str, Any] = {}
spec = {"name": "flavor-a"}
with mock.patch.object(
hook.reconcile_module, "sync_flavor", return_value=["a note"]
) as sync_flavor:
result = plugin.reconcile(conn, spec, cache)
assert result.notes == ["a note"]
sync_flavor.assert_called_once_with(conn, spec, cache)
def test_plugin_wait_for_api_uses_configured_retry_budget():
plugin = hook.RouterFlavorPlugin(
make_hook_config(ready_retries=5, ready_delay=0.25)
)
conn = mock.MagicMock()
with mock.patch.object(hook, "wait_for_openstack_network") as wait:
plugin.wait_for_api(conn)
wait.assert_called_once_with(conn, retries=5, delay=0.25)
def test_plugin_prune_deletes_no_flavor_when_disabled():
plugin = hook.RouterFlavorPlugin(make_hook_config(prune=False))
conn = mock.MagicMock()
with (
mock.patch.object(hook.prune_module, "prune_removed_flavors") as prune,
mock.patch.object(hook.prune_module, "prune_orphaned_profiles") as sweep,
):
plugin.prune_resources(
conn,
PruneRequest(
credentials=("infrasetup", "understack"),
desired_specs=[{"name": "a"}],
authoritative_empty=False,
),
)
prune.assert_not_called()
sweep.assert_called_once_with(conn)
def test_plugin_prune_sweeps_orphaned_profiles_when_disabled():
"""PRUNE gates flavor deletion; an unattached owned profile is collected anyway."""
plugin = hook.RouterFlavorPlugin(make_hook_config(prune=False))
conn = mock.MagicMock()
with mock.patch.object(hook.prune_module, "prune_orphaned_profiles") as sweep:
plugin.prune_resources(
conn,
PruneRequest(
credentials=("infrasetup", "understack"),
desired_specs=[{"name": "a"}],
authoritative_empty=False,
),
)
sweep.assert_called_once_with(conn)
def test_plugin_prune_forwards_authoritative_empty_when_enabled():
plugin = hook.RouterFlavorPlugin(make_hook_config(prune=True))
conn = mock.MagicMock()
specs = [{"name": "a"}]
with mock.patch.object(hook.prune_module, "prune_removed_flavors") as prune:
plugin.prune_resources(
conn,
PruneRequest(
credentials=("infrasetup", "understack"),
desired_specs=specs,
authoritative_empty=True,
),
)
prune.assert_called_once_with(conn, specs, authoritative_empty=True)
def test_plugin_best_effort_prune_does_not_use_finalizers():
"""Router flavor orphan cleanup can run with PRUNE=false without wedging CRs."""
plugin = hook.RouterFlavorPlugin(make_hook_config(prune=False))
assert plugin.cleanup_policy() is CleanupPolicy.BEST_EFFORT_PRUNE
assert plugin.should_run_prune() is True
assert plugin.uses_finalizer() is False
def test_plugin_uses_finalized_prune_when_destructive_prune_is_enabled():
plugin = hook.RouterFlavorPlugin(make_hook_config(prune=True))
assert plugin.cleanup_policy() is CleanupPolicy.FINALIZED_PRUNE
assert plugin.should_run_prune() is True
assert plugin.uses_finalizer() is True
def test_plugin_cache_is_per_credential_group():
plugin = hook.RouterFlavorPlugin(make_hook_config())
assert plugin.new_cache() == {}
assert plugin.new_cache() is not plugin.new_cache()
# ---------------------------------------------------------------------------
# Integration through run_sync()
# ---------------------------------------------------------------------------
def test_run_sync_sweeps_orphaned_profile_on_deletion_when_prune_disabled():
"""Deletion-only input must still open a connection for safe orphan cleanup."""
plugin = hook.RouterFlavorPlugin(make_hook_config(prune=False))
deleted = SyncResource(
spec={"name": "pa1410"},
name="pa1410",
namespace="openstack",
generation=3,
secret_name="infrasetup",
cloud_name="understack",
)
conn = _neutron_conn()
orphan = types.SimpleNamespace(
id="orphan-profile-id",
driver="neutron_understack.l3_router.vrf.Vrf",
is_enabled=True,
description="pa1410 profile",
meta_info=markers.managed_meta_info({"vni_alloc": "auto"}),
)
conn.network.service_profiles.return_value = [
conn.network.service_profiles.return_value[0],
orphan,
]
inputs = SyncPlan(
resources_to_reconcile=[],
desired_resources_for_prune=[],
deleted_resources=[deleted],
prune_credentials=frozenset({deleted.credentials}),
unreadable_resources=frozenset(),
)
with (
mock.patch(
"openstack_sync.hooks.framework.get_openstack_connection",
return_value=conn,
) as connect,
mock.patch("openstack_sync.hooks.framework.patch_resource_status"),
mock.patch.object(hook, "wait_for_openstack_network") as wait,
):
code = hook.run_sync(plugin, inputs)
assert code == 0
connect.assert_called_once_with("infrasetup", "understack")
wait.assert_called_once_with(conn, retries=30, delay=10.0)
conn.network.delete_flavor.assert_not_called()
assert [
call.args[0] for call in conn.network.delete_service_profile.call_args_list
] == [orphan]
# ---------------------------------------------------------------------------
# End to end through main()
# ---------------------------------------------------------------------------
def _neutron_conn() -> Any:
"""A Neutron connection that already holds the desired flavor and profile."""
profile = types.SimpleNamespace(
id="profile-id",
driver="neutron_understack.l3_router.vrf.Vrf",
is_enabled=True,
description="pa1410 profile",
meta_info=markers.managed_meta_info({"vni_alloc": "auto"}),
)
flavor = types.SimpleNamespace(
id="flavor-id",
name="pa1410",
service_type=SERVICE_TYPE,
description=markers.managed_flavor_description("pa1410 description"),
is_enabled=True,
service_profile_ids=["profile-id"],
)
conn = mock.MagicMock()
conn.network.service_profiles.return_value = [profile]
conn.network.flavors.return_value = [flavor]
conn.network.get_flavor.return_value = flavor
return conn
def _run_main(monkeypatch, tmp_path, contexts: list[dict], conn: Any):
monkeypatch.setenv(
"BINDING_CONTEXT_PATH", write_binding_context(tmp_path, contexts)
)
with (
mock.patch.object(hook.sys, "argv", ["router_flavors.py"]),
mock.patch(
"openstack_sync.hooks.framework.get_openstack_connection",
return_value=conn,
),
mock.patch(
"openstack_sync.hooks.framework.patch_resource_status"
) as patch_status,
mock.patch(
"openstack_sync.hooks.framework.add_resource_finalizer",
return_value=True,
),
mock.patch(
"openstack_sync.hooks.framework.remove_resource_finalizer",
return_value=True,
),
mock.patch.object(hook, "wait_for_openstack_network"),
):
code = hook.main()
return code, patch_status
def _schedule_context(*names: str) -> list[dict]:
return [
{
"binding": BINDING_NAME,
"type": "Schedule",
"snapshots": {
BINDING_NAME: [{"object": router_flavor_object(n)} for n in names]
},
}
]
def test_main_returns_zero_when_hook_disabled(monkeypatch, tmp_path):
clear_env(monkeypatch)
conn = _neutron_conn()
code, patch_status = _run_main(
monkeypatch, tmp_path, _schedule_context("pa1410"), conn
)
assert code == 0
patch_status.assert_not_called()
conn.network.flavors.assert_not_called()
def test_main_reconciles_an_already_converged_flavor(monkeypatch, tmp_path):
clear_env(monkeypatch)
monkeypatch.setenv(f"{ENV_PREFIX}_ENABLED", "true")
monkeypatch.setenv("POD_NAMESPACE", "openstack")
conn = _neutron_conn()
code, patch_status = _run_main(
monkeypatch, tmp_path, _schedule_context("pa1410"), conn
)
assert code == 0
assert patch_status.call_args.kwargs["sync_status"] == "Synced"
assert patch_status.call_args.kwargs["message"] == (
"Successfully reconciled router flavor"
)
# Already converged: no writes to Neutron.
conn.network.create_flavor.assert_not_called()
conn.network.create_service_profile.assert_not_called()
conn.network.associate_flavor_with_service_profile.assert_not_called()
def test_main_reports_profile_drift_on_the_cr_status(monkeypatch, tmp_path):
"""A disabled profile keeps the flavor Synced but must show on the status."""
clear_env(monkeypatch)
monkeypatch.setenv(f"{ENV_PREFIX}_ENABLED", "true")
conn = _neutron_conn()
conn.network.service_profiles.return_value[0].is_enabled = False
code, patch_status = _run_main(
monkeypatch, tmp_path, _schedule_context("pa1410"), conn
)
assert code == 0
assert patch_status.call_args.kwargs["sync_status"] == "Synced"
message = patch_status.call_args.kwargs["message"]
assert "is_enabled" in message
assert "profile-id" in message
def test_main_reports_failure_and_skips_prune(monkeypatch, tmp_path):
clear_env(monkeypatch)
monkeypatch.setenv(f"{ENV_PREFIX}_ENABLED", "true")
monkeypatch.setenv(f"{ENV_PREFIX}_PRUNE", "true")
conn = _neutron_conn()
# An existing flavor whose service_type cannot be changed is a hard failure.
conn.network.flavors.return_value[0].service_type = "WRONG_TYPE"
with mock.patch.object(hook.prune_module, "prune_removed_flavors") as prune:
code, patch_status = _run_main(
monkeypatch, tmp_path, _schedule_context("pa1410"), conn
)
assert code == 1
assert patch_status.call_args.kwargs["sync_status"] == "Failed"
assert "service_type" in patch_status.call_args.kwargs["message"]
prune.assert_not_called()
def test_main_prunes_after_a_successful_reconcile(monkeypatch, tmp_path):
clear_env(monkeypatch)
monkeypatch.setenv(f"{ENV_PREFIX}_ENABLED", "true")
monkeypatch.setenv(f"{ENV_PREFIX}_PRUNE", "true")
conn = _neutron_conn()
with mock.patch.object(hook.prune_module, "prune_removed_flavors") as prune:
code, _ = _run_main(monkeypatch, tmp_path, _schedule_context("pa1410"), conn)
assert code == 0
prune.assert_called_once()
assert [spec["name"] for spec in prune.call_args.args[1]] == ["pa1410"]
def test_main_fails_loudly_on_a_cr_missing_cloud_credentials(monkeypatch, tmp_path):
"""A CR without credentials must fail the run, not be skipped.
The CRD marks cloudCredentialsRef required, so the API server should reject
it first; this guards the case where something bypasses that.
"""
clear_env(monkeypatch)
monkeypatch.setenv(f"{ENV_PREFIX}_ENABLED", "true")
obj = router_flavor_object("pa1410")
del obj["spec"]["cloudCredentialsRef"]
contexts = [
{
"binding": BINDING_NAME,
"type": "Schedule",
"snapshots": {BINDING_NAME: [{"object": obj}]},
}
]
code, _ = _run_main(monkeypatch, tmp_path, contexts, _neutron_conn())
assert code == 1
def test_main_uses_the_credentials_named_by_each_cr(monkeypatch, tmp_path):
clear_env(monkeypatch)
monkeypatch.setenv(f"{ENV_PREFIX}_ENABLED", "true")
monkeypatch.setattr(utils, "_connection_cache", {})
contexts = _schedule_context("pa1410")
contexts[0]["snapshots"][BINDING_NAME][0]["object"]["spec"][
"cloudCredentialsRef"
] = {"secretName": "other-secret", "cloudName": "other-cloud"}
monkeypatch.setenv(
"BINDING_CONTEXT_PATH", write_binding_context(tmp_path, contexts)
)
with (
mock.patch.object(hook.sys, "argv", ["router_flavors.py"]),
mock.patch(
"openstack_sync.hooks.framework.get_openstack_connection",
return_value=_neutron_conn(),
) as connect,
mock.patch("openstack_sync.hooks.framework.patch_resource_status"),
mock.patch.object(hook, "wait_for_openstack_network"),
):
assert hook.main() == 0
connect.assert_called_once_with("other-secret", "other-cloud")