-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathconftest.py
More file actions
2781 lines (2267 loc) · 91.5 KB
/
conftest.py
File metadata and controls
2781 lines (2267 loc) · 91.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
499
500
501
502
503
504
505
506
507
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
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
804
805
806
807
808
809
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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
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
"""
Pytest conftest file for CNV tests
"""
import copy
import ipaddress
import logging
import os
import os.path
import re
import shlex
import shutil
import subprocess
import tempfile
from bisect import bisect_left
from collections import defaultdict
from datetime import datetime, timezone
from signal import SIGINT, SIGTERM, getsignal, signal
from subprocess import check_output
import bcrypt
import bitmath
import paramiko
import pytest
import requests
import yaml
from bs4 import BeautifulSoup
from kubernetes.dynamic.exceptions import ResourceNotFoundError
from ocp_resources.application_aware_resource_quota import ApplicationAwareResourceQuota
from ocp_resources.catalog_source import CatalogSource
from ocp_resources.cdi import CDI
from ocp_resources.cdi_config import CDIConfig
from ocp_resources.cluster_role import ClusterRole
from ocp_resources.cluster_service_version import ClusterServiceVersion
from ocp_resources.config_map import ConfigMap
from ocp_resources.daemonset import DaemonSet
from ocp_resources.data_source import DataSource
from ocp_resources.datavolume import DataVolume
from ocp_resources.deployment import Deployment
from ocp_resources.hostpath_provisioner import HostPathProvisioner
from ocp_resources.infrastructure import Infrastructure
from ocp_resources.machine import Machine
from ocp_resources.migration_policy import MigrationPolicy
from ocp_resources.mutating_webhook_config import MutatingWebhookConfiguration
from ocp_resources.namespace import Namespace
from ocp_resources.network_addons_config import NetworkAddonsConfig
from ocp_resources.network_config_openshift_io import Network
from ocp_resources.node import Node
from ocp_resources.node_network_state import NodeNetworkState
from ocp_resources.oauth import OAuth
from ocp_resources.persistent_volume_claim import PersistentVolumeClaim
from ocp_resources.pod import Pod
from ocp_resources.resource import ResourceEditor, get_client
from ocp_resources.role_binding import RoleBinding
from ocp_resources.secret import Secret
from ocp_resources.service_account import ServiceAccount
from ocp_resources.sriov_network_node_policy import SriovNetworkNodePolicy
from ocp_resources.storage_class import StorageClass
from ocp_resources.virtual_machine_cluster_instancetype import (
VirtualMachineClusterInstancetype,
)
from ocp_resources.virtual_machine_cluster_preference import (
VirtualMachineClusterPreference,
)
from ocp_resources.virtual_machine_instance_migration import (
VirtualMachineInstanceMigration,
)
from ocp_resources.virtual_machine_instancetype import VirtualMachineInstancetype
from ocp_resources.virtual_machine_preference import VirtualMachinePreference
from ocp_utilities.monitoring import Prometheus
from packaging.version import Version, parse
from pytest_testconfig import config as py_config
from timeout_sampler import TimeoutSampler
import utilities.hco
from libs.net.ip import filter_link_local_addresses, random_ipv4_address, random_ipv6_address
from libs.net.vmspec import lookup_iface_status
from tests.utils import download_and_extract_tar
from utilities.artifactory import get_artifactory_header, get_http_image_url, get_test_artifact_server_url
from utilities.bitwarden import get_cnv_tests_secret_by_name
from utilities.cluster import cache_admin_client
from utilities.constants import (
AAQ_NAMESPACE_LABEL,
ARM_64,
ARQ_QUOTA_HARD_SPEC,
AUDIT_LOGS_PATH,
CDI_KUBEVIRT_HYPERCONVERGED,
CLUSTER,
CNV_TEST_SERVICE_ACCOUNT,
CNV_VM_SSH_KEY_PATH,
ES_NONE,
EXPECTED_CLUSTER_INSTANCE_TYPE_LABELS,
FEATURE_GATES,
HCO_SUBSCRIPTION,
HOTFIX_STR,
INSTANCE_TYPE_STR,
KMP_ENABLED_LABEL,
KMP_VM_ASSIGNMENT_LABEL,
KUBECONFIG,
KUBEMACPOOL_MAC_CONTROLLER_MANAGER,
KUBEMACPOOL_MAC_RANGE_CONFIG,
LINUX_BRIDGE,
MIGRATION_POLICY_VM_LABEL,
NODE_HUGE_PAGES_1GI_KEY,
NODE_ROLE_KUBERNETES_IO,
NODE_TYPE_WORKER_LABEL,
OC_ADM_LOGS_COMMAND,
OS_FLAVOR_RHEL,
OVS_BRIDGE,
POD_SECURITY_NAMESPACE_LABELS,
PREFERENCE_STR,
RHEL9_STR,
RHSM_SECRET_NAME,
S390X,
SSP_CR_COMMON_TEMPLATES_LIST_KEY_NAME,
TIMEOUT_3MIN,
TIMEOUT_4MIN,
TIMEOUT_5MIN,
UNPRIVILEGED_PASSWORD,
UNPRIVILEGED_USER,
UTILITY,
VIRTCTL_CLI_DOWNLOADS,
VIRTIO,
WORKER_NODE_LABEL_KEY,
WORKERS_TYPE,
Images,
NamespacesNames,
StorageClassNames,
UpgradeStreams,
)
from utilities.cpu import (
find_common_cpu_model_for_live_migration,
get_common_cpu_from_nodes,
get_host_model_cpu,
get_nodes_cpu_model,
)
from utilities.data_utils import base64_encode_str, name_prefix
from utilities.exceptions import MissingEnvironmentVariableError
from utilities.infra import (
ClusterHosts,
ExecCommandOnPod,
add_scc_to_service_account,
create_ns,
download_file_from_cluster,
generate_namespace_name,
generate_openshift_pull_secret_file,
get_cluster_platform,
get_clusterversion,
get_daemonset_yaml_file_with_image_hash,
get_deployment_by_name,
get_hyperconverged_resource,
get_infrastructure,
get_node_selector_dict,
get_nodes_with_label,
get_pods,
get_subscription,
get_utility_pods_from_nodes,
label_nodes,
label_project,
login_with_user_password,
run_virtctl_command,
scale_deployment_replicas,
wait_for_pods_deletion,
)
from utilities.network import (
EthernetNetworkConfigurationPolicy,
MacPool,
cloud_init_network_data,
enable_hyperconverged_ovs_annotations,
get_cluster_cni_type,
network_device,
network_nad,
wait_for_node_marked_by_bridge,
wait_for_ovs_daemonset_resource,
wait_for_ovs_status,
)
from utilities.operator import (
cluster_with_icsp,
disable_default_sources_in_operatorhub,
get_hco_csv_name_by_version,
get_machine_config_pool_by_name,
)
from utilities.pytest_utils import exit_pytest_execution
from utilities.sanity import cluster_sanity
from utilities.ssp import get_data_import_crons, get_ssp_resource
from utilities.storage import (
create_or_update_data_source,
data_volume,
get_default_storage_class,
get_storage_class_with_specified_volume_mode,
is_snapshot_supported_by_sc,
remove_default_storage_classes,
update_default_sc,
verify_boot_sources_reimported,
)
from utilities.virt import (
VirtualMachineForTests,
fedora_vm_body,
get_base_templates_list,
get_hyperconverged_kubevirt,
get_hyperconverged_ovs_annotations,
get_kubevirt_hyperconverged_spec,
kubernetes_taint_exists,
running_vm,
start_and_fetch_processid_on_linux_vm,
vm_instance_from_template,
wait_for_windows_vm,
)
LOGGER = logging.getLogger(__name__)
HTTP_SECRET_NAME = "htpass-secret-for-cnv-tests"
HTPASSWD_PROVIDER_DICT = {
"name": "htpasswd_provider",
"mappingMethod": "claim",
"type": "HTPasswd",
"htpasswd": {"fileData": {"name": HTTP_SECRET_NAME}},
}
ACCESS_TOKEN = {
"accessTokenMaxAgeSeconds": 604800,
"accessTokenInactivityTimeout": None,
}
CNV_NOT_INSTALLED = "CNV not yet installed."
RWX_FS_STORAGE_CLASS_NAMES_LIST = [
StorageClassNames.CEPHFS,
StorageClassNames.TRIDENT_CSI_FSX,
StorageClassNames.PORTWORX_CSI_DB_SHARED,
]
# Pre-compiled regex for audit log filename parsing: captures date and time components
AUDIT_LOG_PATTERN = re.compile(r"audit-(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2}\.\d{3})\.log")
@pytest.fixture(scope="session")
def junitxml_polarion(record_testsuite_property):
"""
Add polarion needed attributes to junit xml
export as os environment:
POLARION_CUSTOM_PLANNEDIN
POLARION_TESTRUN_ID
POLARION_TIER
"""
record_testsuite_property("polarion-custom-isautomated", "True")
record_testsuite_property("polarion-testrun-status-id", "inprogress")
record_testsuite_property("polarion-custom-plannedin", os.getenv("POLARION_CUSTOM_PLANNEDIN"))
record_testsuite_property("polarion-user-id", "cnvqe")
record_testsuite_property("polarion-project-id", "CNV")
record_testsuite_property("polarion-response-myproduct", "cnv-test-run")
record_testsuite_property("polarion-testrun-id", os.getenv("POLARION_TESTRUN_ID"))
record_testsuite_property("polarion-custom-env_tier", os.getenv("POLARION_TIER"))
record_testsuite_property("polarion-custom-env_os", os.getenv("POLARION_OS"))
@pytest.fixture(scope="session")
def kubeconfig_export_path():
return os.environ.get(KUBECONFIG)
@pytest.fixture(scope="session")
def session_start_time() -> datetime:
"""
Capture when test session started in UTC.
Uses UTC to match the timezone used in audit log file names.
Returns:
datetime: UTC timestamp when test session began (timezone-naive)
"""
return datetime.now(timezone.utc).replace(tzinfo=None)
@pytest.fixture(scope="session")
def exported_kubeconfig(unprivileged_secret, kubeconfig_export_path):
if not unprivileged_secret:
yield
else:
kube_config_path = os.path.join(os.path.expanduser("~"), ".kube/config")
if os.path.isfile(kube_config_path) and kubeconfig_export_path:
LOGGER.warning(
f"Both {KUBECONFIG} {kubeconfig_export_path} and {kube_config_path} exist. "
f"{kubeconfig_export_path} is used as kubeconfig source for this run."
)
orig_kubeconfig_file_path = kubeconfig_export_path or kube_config_path
tests_kubeconfig_dir_path = tempfile.mkdtemp(suffix="-cnv-tests-kubeconfig")
LOGGER.info(f"Setting {KUBECONFIG} dir for this run to point to: {tests_kubeconfig_dir_path}")
kubeconfig_file_dest_path = os.path.join(tests_kubeconfig_dir_path, KUBECONFIG.lower())
LOGGER.info(f"Copy {KUBECONFIG} to {kubeconfig_file_dest_path}")
shutil.copyfile(src=orig_kubeconfig_file_path, dst=kubeconfig_file_dest_path)
LOGGER.info(f"Set: {KUBECONFIG}={kubeconfig_file_dest_path}")
os.environ[KUBECONFIG] = kubeconfig_file_dest_path
yield kubeconfig_file_dest_path
LOGGER.info(f"Remove: {kubeconfig_file_dest_path}")
shutil.rmtree(tests_kubeconfig_dir_path, ignore_errors=True)
if kubeconfig_export_path:
LOGGER.info(f"Set: {KUBECONFIG}={kubeconfig_export_path}")
os.environ[KUBECONFIG] = kubeconfig_export_path
else:
del os.environ[KUBECONFIG]
@pytest.fixture(scope="session")
def admin_client():
"""
Get DynamicClient
"""
return cache_admin_client()
@pytest.fixture(scope="session")
def unprivileged_secret(admin_client, skip_unprivileged_client):
if skip_unprivileged_client:
yield
else:
password = UNPRIVILEGED_PASSWORD.encode()
enc_password = bcrypt.hashpw(password, bcrypt.gensalt(5, prefix=b"2a")).decode()
crypto_credentials = f"{UNPRIVILEGED_USER}:{enc_password}"
with Secret(
name=HTTP_SECRET_NAME,
namespace=NamespacesNames.OPENSHIFT_CONFIG,
htpasswd=base64_encode_str(text=crypto_credentials),
client=admin_client,
) as secret:
yield secret
# Wait for oauth-openshift deployment to update after removing htpass-secret
_wait_for_oauth_openshift_deployment(admin_client=admin_client)
def _wait_for_oauth_openshift_deployment(admin_client):
dp = get_deployment_by_name(
deployment_name="oauth-openshift",
namespace_name="openshift-authentication",
admin_client=admin_client,
)
_log = f"Wait for {dp.name} -> Type: Progressing -> Reason:"
def _wait_sampler(_reason):
sampler = TimeoutSampler(
wait_timeout=TIMEOUT_4MIN,
sleep=1,
func=lambda: dp.instance.status.conditions,
)
for sample in sampler:
for _spl in sample:
if _spl.type == "Progressing" and _spl.reason == _reason:
return
for reason in ("ReplicaSetUpdated", "NewReplicaSetAvailable"):
LOGGER.info(f"{_log} {reason}")
_wait_sampler(_reason=reason)
@pytest.fixture(scope="session")
def skip_unprivileged_client():
# To disable unprivileged_client pass --tc=no_unprivileged_client:True to pytest commandline.
return py_config.get("no_unprivileged_client")
@pytest.fixture(scope="session")
def identity_provider_config(skip_unprivileged_client, admin_client):
if skip_unprivileged_client:
return
return OAuth(client=admin_client, name=CLUSTER)
@pytest.fixture(scope="session")
def identity_provider_with_htpasswd(skip_unprivileged_client, admin_client, identity_provider_config):
if skip_unprivileged_client:
yield
else:
identity_provider_config_editor = ResourceEditor(
patches={
identity_provider_config: {
"metadata": {"name": identity_provider_config.name},
"spec": {
"identityProviders": [HTPASSWD_PROVIDER_DICT],
"tokenConfig": ACCESS_TOKEN,
},
}
}
)
identity_provider_config_editor.update(backup_resources=True)
_wait_for_oauth_openshift_deployment(admin_client=admin_client)
yield
identity_provider_config_editor.restore()
@pytest.fixture(scope="session")
def unprivileged_client(
skip_unprivileged_client,
admin_client,
unprivileged_secret,
identity_provider_with_htpasswd,
exported_kubeconfig,
):
"""
Provides none privilege API client
"""
if skip_unprivileged_client:
LOGGER.info("no_unprivileged_client was set, using admin_client")
yield admin_client
else:
current_user = check_output("oc whoami", shell=True).decode().strip() # Get the current admin account
if login_with_user_password(
api_address=admin_client.configuration.host,
user=UNPRIVILEGED_USER,
password=UNPRIVILEGED_PASSWORD,
): # Login to an unprivileged account
with open(exported_kubeconfig) as fd:
kubeconfig_content = yaml.safe_load(fd)
unprivileged_context = kubeconfig_content["current-context"]
# Get back to an admin account
login_with_user_password(
api_address=admin_client.configuration.host,
user=current_user.strip(),
)
yield get_client(config_file=exported_kubeconfig, context=unprivileged_context)
else:
yield admin_client
@pytest.fixture(scope="session")
def nodes(admin_client):
yield list(Node.get(client=admin_client))
@pytest.fixture(scope="session")
def schedulable_nodes(nodes):
"""Get nodes marked as schedulable by kubevirt"""
schedulable_label = "kubevirt.io/schedulable"
yield [
node
for node in nodes
if schedulable_label in node.labels.keys()
and node.labels[schedulable_label] == "true"
and not node.instance.spec.unschedulable
and not kubernetes_taint_exists(node)
and node.kubelet_ready
]
@pytest.fixture(scope="session")
def workers(nodes):
return get_nodes_with_label(nodes=nodes, label=WORKER_NODE_LABEL_KEY)
@pytest.fixture(scope="session")
def control_plane_nodes(nodes):
return get_nodes_with_label(nodes=nodes, label=f"{NODE_ROLE_KUBERNETES_IO}/control-plane")
@pytest.fixture(scope="session")
def cnv_tests_utilities_namespace(admin_client, installing_cnv):
if installing_cnv:
yield
else:
name = NamespacesNames.CNV_TESTS_UTILITIES
if Namespace(client=admin_client, name=name).exists:
exit_pytest_execution(
log_message=f"{name} namespace already exists."
f"\nAfter verifying no one else is performing tests against the cluster, run:"
f"\n'oc delete namespace {name}'",
return_code=100,
message=f"{name} namespace already exists.",
filename="cnv_tests_utilities_ns_failure.txt",
admin_client=admin_client,
)
else:
yield from create_ns(
admin_client=admin_client,
labels=POD_SECURITY_NAMESPACE_LABELS,
name=name,
)
@pytest.fixture(scope="session")
def cnv_tests_utilities_service_account(admin_client, cnv_tests_utilities_namespace, installing_cnv):
if installing_cnv:
yield
else:
with ServiceAccount(
client=admin_client,
name=CNV_TEST_SERVICE_ACCOUNT,
namespace=cnv_tests_utilities_namespace.name,
) as service_account:
add_scc_to_service_account(
namespace=cnv_tests_utilities_namespace.name,
scc_name="privileged",
sa_name=service_account.name,
)
yield service_account
@pytest.fixture(scope="session")
def utility_daemonset(
admin_client,
installing_cnv,
generated_pulled_secret,
cnv_tests_utilities_namespace,
cnv_tests_utilities_service_account,
):
"""
Deploy utility daemonset into the cnv-tests-utilities namespace.
This daemonset deploys a pod on every node with hostNetwork and the main usage is to run commands on the hosts.
For example to create linux bridge and other components related to the host configuration.
"""
if installing_cnv:
yield
else:
modified_ds_yaml_file = get_daemonset_yaml_file_with_image_hash(
generated_pulled_secret=generated_pulled_secret,
service_account=cnv_tests_utilities_service_account,
)
with DaemonSet(client=admin_client, yaml_file=modified_ds_yaml_file) as ds:
ds.wait_until_deployed()
yield ds
@pytest.fixture(scope="session")
def pull_secret_directory(tmpdir_factory):
yield tmpdir_factory.mktemp("pullsecret-folder")
@pytest.fixture(scope="session")
def generated_pulled_secret(
is_production_source,
installing_cnv,
admin_client,
):
if is_production_source and installing_cnv:
return
return generate_openshift_pull_secret_file()
@pytest.fixture(scope="session")
def workers_utility_pods(admin_client, workers, utility_daemonset, installing_cnv):
"""
Get utility pods from worker nodes.
When the tests start we deploy a pod on every worker node in the cluster using a daemonset.
These pods have a label of cnv-test=utility and they are privileged pods with hostnetwork=true
"""
if installing_cnv:
return
return get_utility_pods_from_nodes(
nodes=workers,
admin_client=admin_client,
label_selector="cnv-test=utility",
)
@pytest.fixture(scope="session")
def control_plane_utility_pods(admin_client, installing_cnv, control_plane_nodes, utility_daemonset):
"""
Get utility pods from control plane nodes.
When the tests start we deploy a pod on every control plane node in the cluster using a daemonset.
These pods have a label of cnv-test=utility and they are privileged pods with hostnetwork=true
"""
if installing_cnv:
return
return get_utility_pods_from_nodes(
nodes=control_plane_nodes,
admin_client=admin_client,
label_selector="cnv-test=utility",
)
@pytest.fixture(scope="session")
def node_physical_nics(workers_utility_pods):
interfaces = {}
for pod in workers_utility_pods:
node = pod.instance.spec.nodeName
output = pod.execute(
command=shlex.split("bash -c \"nmcli dev s | grep -v unmanaged | grep ethernet | awk '{print $1}'\"")
).split("\n")
interfaces[node] = list(filter(None, output)) # Filter out empty lines
LOGGER.info(f"Nodes physical NICs: {interfaces}")
return interfaces
@pytest.fixture(scope="session")
def nodes_active_nics(
nmstate_dependent_placeholder,
admin_client,
workers,
workers_utility_pods,
node_physical_nics,
):
# TODO: Add support for environments that do not have KNMstate installed. e.g: clouds
# TODO: Reduce cognitive complexity
def _bridge_ports(node_interface):
ports = set()
if node_interface["type"] in (OVS_BRIDGE, LINUX_BRIDGE) and node_interface["bridge"].get("port"):
for bridge_port in node_interface["bridge"]["port"]:
ports.add(bridge_port["name"])
elif node_interface["type"] == "bond" and node_interface["link-aggregation"].get("port"):
for bridge_port in node_interface["link-aggregation"]["port"]:
ports.add(bridge_port)
return ports
"""
Get nodes active NICs.
First NIC is management NIC
"""
nodes_nics = {}
for node in workers:
nodes_nics[node.name] = {"available": [], "occupied": []}
nns = NodeNetworkState(name=node.name, client=admin_client)
for node_iface in nns.interfaces:
iface_name = node_iface["name"]
# Exclude SR-IOV (VFs) interfaces.
if re.findall(r"v\d+$", iface_name):
continue
# If the interface is a bridge with physical ports, then these ports should be labeled as occupied.
for bridge_port in _bridge_ports(node_interface=node_iface):
if (
bridge_port in node_physical_nics[node.name]
and bridge_port not in nodes_nics[node.name]["occupied"]
):
node_iface_type = node_iface["type"]
LOGGER.warning(
f"{node.name}:{bridge_port} is a port of {iface_name} {node_iface_type} - adding it "
f"to the node's occupied interfaces list."
)
nodes_nics[node.name]["occupied"].append(bridge_port)
if bridge_port in nodes_nics[node.name]["available"]:
nodes_nics[node.name]["available"].remove(bridge_port)
if iface_name in nodes_nics[node.name]["occupied"]:
continue
if iface_name not in node_physical_nics[node.name]:
continue
physically_connected = (
ExecCommandOnPod(utility_pods=workers_utility_pods, node=node)
.exec(command=f"nmcli -g WIRED-PROPERTIES.CARRIER device show {iface_name}")
.lower()
)
if physically_connected != "on":
LOGGER.warning(f"{node.name} {iface_name} link is down")
continue
if node_iface["ipv4"].get("address"):
nodes_nics[node.name]["occupied"].append(iface_name)
else:
nodes_nics[node.name]["available"].append(iface_name)
LOGGER.info(f"Nodes active NICs: {nodes_nics}")
return nodes_nics
@pytest.fixture(scope="session")
def nodes_available_nics(nodes_active_nics):
return {node: nodes_active_nics[node]["available"] for node in nodes_active_nics.keys()}
@pytest.fixture(scope="module")
def namespace(request, admin_client, unprivileged_client):
"""
To create namespace using admin client, pass {"use_unprivileged_client": False} to request.param
(default for "use_unprivileged_client" is True)
"""
use_unprivileged_client = getattr(request, "param", {}).get("use_unprivileged_client", True)
teardown = getattr(request, "param", {}).get("teardown", True)
unprivileged_client = unprivileged_client if use_unprivileged_client else None
yield from create_ns(
unprivileged_client=unprivileged_client,
admin_client=admin_client,
name=generate_namespace_name(file_path=request.fspath.strpath.split(f"{os.path.dirname(__file__)}/")[1]),
teardown=teardown,
)
@pytest.fixture(scope="session")
def leftovers_cleanup(admin_client, cnv_tests_utilities_namespace, identity_provider_config):
LOGGER.info("Checking for leftover resources")
secret = Secret(
client=admin_client,
name=HTTP_SECRET_NAME,
namespace=NamespacesNames.OPENSHIFT_CONFIG,
)
ds = None
if cnv_tests_utilities_namespace:
ds = DaemonSet(
client=admin_client,
name=UTILITY,
namespace=cnv_tests_utilities_namespace.name,
)
# Delete Secret and DaemonSet created by us.
for resource_ in (secret, ds):
if resource_ and resource_.exists:
resource_.delete(wait=True)
# Remove leftovers from OAuth
if not identity_provider_config:
# When running CI (k8s) OAuth is not exists on the cluster.
LOGGER.warning("OAuth does not exist on the cluster")
return
identity_providers_spec = identity_provider_config.instance.to_dict()["spec"]
identity_providers_token = identity_providers_spec.get("tokenConfig")
identity_providers = identity_providers_spec.get("identityProviders", [])
if ACCESS_TOKEN == identity_providers_token:
identity_providers_spec["tokenConfig"] = None
if HTPASSWD_PROVIDER_DICT in identity_providers:
identity_providers.pop(identity_providers.index(HTPASSWD_PROVIDER_DICT))
identity_providers_spec["identityProviders"] = identity_providers or None
r_editor = ResourceEditor(
patches={
identity_provider_config: {
"metadata": {"name": identity_provider_config.name},
"spec": identity_providers_spec,
}
}
)
r_editor.update()
@pytest.fixture(scope="session")
def workers_type(workers_utility_pods, installing_cnv):
if installing_cnv:
return
physical = ClusterHosts.Type.PHYSICAL
virtual = ClusterHosts.Type.VIRTUAL
for pod in workers_utility_pods:
pod_exec = ExecCommandOnPod(utility_pods=workers_utility_pods, node=pod.node)
out = pod_exec.exec(command="systemd-detect-virt", ignore_rc=True)
if out == "none":
LOGGER.info(f"Cluster workers are: {physical}")
os.environ[WORKERS_TYPE] = physical
return physical
LOGGER.info(f"Cluster workers are: {virtual}")
os.environ[WORKERS_TYPE] = virtual
return virtual
@pytest.fixture()
def data_volume_multi_storage_scope_function(
request,
namespace,
storage_class_matrix__function__,
):
yield from data_volume(
request=request,
namespace=namespace,
storage_class_matrix=storage_class_matrix__function__,
client=namespace.client,
)
@pytest.fixture(scope="module")
def data_volume_multi_storage_scope_module(
request,
namespace,
storage_class_matrix__module__,
):
yield from data_volume(
request=request,
namespace=namespace,
storage_class_matrix=storage_class_matrix__module__,
client=namespace.client,
)
@pytest.fixture()
def golden_image_data_volume_multi_storage_scope_function(
admin_client,
request,
golden_images_namespace,
storage_class_matrix__function__,
):
yield from data_volume(
request=request,
namespace=golden_images_namespace,
storage_class_matrix=storage_class_matrix__function__,
check_dv_exists=True,
client=admin_client,
)
@pytest.fixture()
def golden_image_data_source_multi_storage_scope_function(
admin_client, golden_image_data_volume_multi_storage_scope_function
):
yield from create_or_update_data_source(
admin_client=admin_client,
dv=golden_image_data_volume_multi_storage_scope_function,
)
@pytest.fixture()
def data_volume_scope_function(request, namespace):
yield from data_volume(
request=request,
namespace=namespace,
storage_class=request.param["storage_class"],
client=namespace.client,
)
@pytest.fixture(scope="class")
def data_volume_scope_class(request, namespace):
yield from data_volume(
request=request,
namespace=namespace,
storage_class=request.param["storage_class"],
client=namespace.client,
)
@pytest.fixture(scope="module")
def golden_image_data_volume_scope_module(request, admin_client, golden_images_namespace):
yield from data_volume(
request=request,
namespace=golden_images_namespace,
storage_class=request.param["storage_class"],
check_dv_exists=True,
client=admin_client,
)
@pytest.fixture()
def golden_image_data_volume_scope_function(request, admin_client, golden_images_namespace):
yield from data_volume(
request=request,
namespace=golden_images_namespace,
storage_class=request.param["storage_class"],
check_dv_exists=True,
client=admin_client,
)
@pytest.fixture()
def golden_image_data_source_scope_function(admin_client, golden_image_data_volume_scope_function):
yield from create_or_update_data_source(admin_client=admin_client, dv=golden_image_data_volume_scope_function)
@pytest.fixture(scope="session")
def rhel9_data_source_scope_session(golden_images_namespace):
return DataSource(
client=golden_images_namespace.client,
name=RHEL9_STR,
namespace=golden_images_namespace.name,
ensure_exists=True,
)
@pytest.fixture(scope="session")
def rhel10_data_source_scope_session(golden_images_namespace):
return DataSource(
namespace=golden_images_namespace.name,
name="rhel10",
client=golden_images_namespace.client,
ensure_exists=True,
)
"""
VM creation from template
"""
@pytest.fixture()
def vm_instance_from_template_multi_storage_scope_function(
request,
unprivileged_client,
namespace,
data_volume_multi_storage_scope_function,
cpu_for_migration,
):
"""Calls vm_instance_from_template contextmanager
Creates a VM from template and starts it (if requested).
"""
with vm_instance_from_template(
request=request,
unprivileged_client=unprivileged_client,
namespace=namespace,
existing_data_volume=data_volume_multi_storage_scope_function,
vm_cpu_model=(cpu_for_migration if request.param.get("set_vm_common_cpu") else None),
) as vm:
yield vm
"""
Windows-specific fixtures
"""
@pytest.fixture()
def started_windows_vm(
request,
vm_instance_from_template_multi_storage_scope_function,
):
wait_for_windows_vm(
vm=vm_instance_from_template_multi_storage_scope_function,
version=request.param["os_version"],
)
@pytest.fixture(scope="session")
def worker_nodes_ipv4_false_secondary_nics(
admin_client,
nodes_available_nics,
schedulable_nodes,
):
"""
Function removes ipv4 from secondary nics.
"""
for worker_node in schedulable_nodes:
worker_nics = nodes_available_nics[worker_node.name]
with EthernetNetworkConfigurationPolicy(
name=f"disable-ipv4-{name_prefix(worker_node.name)}",
client=admin_client,
node_selector=get_node_selector_dict(node_selector=worker_node.hostname),
interfaces_name=worker_nics,
):
LOGGER.info(
f"selected worker node - {worker_node.name} under NNCP selected NIC information - {worker_nics} "
)
@pytest.fixture(scope="session")
def csv_scope_session(admin_client, hco_namespace, installing_cnv):
if not installing_cnv:
return utilities.hco.get_installed_hco_csv(admin_client=admin_client, hco_namespace=hco_namespace)
@pytest.fixture(scope="session")
def cnv_current_version(installing_cnv, csv_scope_session):
if installing_cnv:
return CNV_NOT_INSTALLED
if csv_scope_session:
version = csv_scope_session.instance.spec.version
if not version:
raise ValueError("CSV spec.version is missing (field is optional in schema).")
return version
@pytest.fixture(scope="session")
def hco_namespace(admin_client, installing_cnv):
if not installing_cnv:
return utilities.hco.get_hco_namespace(admin_client=admin_client, namespace=py_config["hco_namespace"])
@pytest.fixture(scope="session")
def worker_node1(schedulable_nodes):
# Get first worker nodes out of schedulable_nodes list
return schedulable_nodes[0]
@pytest.fixture(scope="session")
def worker_node2(schedulable_nodes):
# Get second worker nodes out of schedulable_nodes list
return schedulable_nodes[1]
@pytest.fixture(scope="session")
def worker_node3(schedulable_nodes):
# Get third worker nodes out of schedulable_nodes list
return schedulable_nodes[2]
@pytest.fixture(scope="session")
def sriov_namespace(admin_client):
return Namespace(name="openshift-sriov-network-operator", client=admin_client)
@pytest.fixture(scope="session")
def sriov_workers(schedulable_nodes):
sriov_worker_label = "feature.node.kubernetes.io/network-sriov.capable"
yield [node for node in schedulable_nodes if node.labels.get(sriov_worker_label) == "true"]