Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 22 additions & 51 deletions modules/python/clients/kubernetes_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1102,51 +1102,31 @@ def _apply_single_manifest(self, manifest, namespace=None):
Apply a single Kubernetes manifest using the appropriate API client.

:param manifest: Dictionary representing a Kubernetes resource
:param namespace: Optional namespace to override the manifest namespace
:param namespace: Optional namespace to override the manifest namespace.
Defaults to 'default' for namespaced resources if not specified.
:return: None
"""
try:
kind = manifest.get("kind")
# Use provided namespace or fall back to manifest namespace
namespace = namespace or manifest.get("metadata", {}).get("namespace")
# Use provided namespace or fall back to manifest namespace, then to "default"
namespace = namespace or manifest.get("metadata", {}).get("namespace") or "default"
Comment thread
anson627 marked this conversation as resolved.
Resolved
name = manifest.get("metadata", {}).get("name")
logger.info("Applying manifest %s %s in namespace %s", kind, name, namespace)
Comment thread
anson627 marked this conversation as resolved.
Resolved

if kind == "Deployment":
if namespace:
self.app.create_namespaced_deployment(namespace=namespace, body=manifest)
else:
raise ValueError("Deployment requires a namespace")
self.app.create_namespaced_deployment(namespace=namespace, body=manifest)
elif kind == "DaemonSet":
if namespace:
self.app.create_namespaced_daemon_set(namespace=namespace, body=manifest)
else:
raise ValueError("DaemonSet requires a namespace")
self.app.create_namespaced_daemon_set(namespace=namespace, body=manifest)
elif kind == "StatefulSet":
if namespace:
self.app.create_namespaced_stateful_set(namespace=namespace, body=manifest)
else:
raise ValueError("StatefulSet requires a namespace")
self.app.create_namespaced_stateful_set(namespace=namespace, body=manifest)
elif kind == "Service":
if namespace:
self.api.create_namespaced_service(namespace=namespace, body=manifest)
else:
raise ValueError("Service requires a namespace")
self.api.create_namespaced_service(namespace=namespace, body=manifest)
elif kind == "ConfigMap":
if namespace:
self.api.create_namespaced_config_map(namespace=namespace, body=manifest)
else:
raise ValueError("ConfigMap requires a namespace")
self.api.create_namespaced_config_map(namespace=namespace, body=manifest)
elif kind == "Secret":
if namespace:
self.api.create_namespaced_secret(namespace=namespace, body=manifest)
else:
raise ValueError("Secret requires a namespace")
self.api.create_namespaced_secret(namespace=namespace, body=manifest)
elif kind == "ServiceAccount":
if namespace:
self.api.create_namespaced_service_account(namespace=namespace, body=manifest)
else:
raise ValueError("ServiceAccount requires a namespace")
self.api.create_namespaced_service_account(namespace=namespace, body=manifest)
elif kind == "ClusterRole":
# ClusterRole is cluster-scoped
rbac_api = client.RbacAuthorizationV1Api()
Expand All @@ -1156,17 +1136,11 @@ def _apply_single_manifest(self, manifest, namespace=None):
rbac_api = client.RbacAuthorizationV1Api()
rbac_api.create_cluster_role_binding(body=manifest)
elif kind == "Role":
if namespace:
rbac_api = client.RbacAuthorizationV1Api()
rbac_api.create_namespaced_role(namespace=namespace, body=manifest)
else:
raise ValueError("Role requires a namespace")
rbac_api = client.RbacAuthorizationV1Api()
rbac_api.create_namespaced_role(namespace=namespace, body=manifest)
elif kind == "RoleBinding":
if namespace:
rbac_api = client.RbacAuthorizationV1Api()
rbac_api.create_namespaced_role_binding(namespace=namespace, body=manifest)
else:
raise ValueError("RoleBinding requires a namespace")
rbac_api = client.RbacAuthorizationV1Api()
rbac_api.create_namespaced_role_binding(namespace=namespace, body=manifest)
elif kind == "Namespace":
# Namespace is cluster-scoped
self.api.create_namespace(body=manifest)
Expand Down Expand Up @@ -1203,16 +1177,13 @@ def _apply_single_manifest(self, manifest, namespace=None):
api_version = manifest.get("apiVersion", "")
group, version = api_version.split("/") if "/" in api_version else ("", api_version)
custom_api = client.CustomObjectsApi()
if namespace:
custom_api.create_namespaced_custom_object(
group=group,
version=version,
namespace=namespace,
plural="mpijobs",
body=manifest
)
else:
raise ValueError("MPIJob requires a namespace")
custom_api.create_namespaced_custom_object(
group=group,
version=version,
namespace=namespace,
plural="mpijobs",
body=manifest
)
elif kind == "NodeFeatureRule":
# NodeFeatureRule is a custom resource from Node Feature Discovery (NFD)
api_version = manifest.get("apiVersion", "")
Expand Down
118 changes: 70 additions & 48 deletions modules/python/tests/clients/test_kubernetes_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2522,20 +2522,22 @@ def test_apply_single_manifest_deployment(self, mock_create_deployment):
mock_create_deployment.assert_called_once_with(
namespace="test-namespace", body=manifest)

def test_apply_single_manifest_deployment_no_namespace(self):
"""Test _apply_single_manifest with Deployment missing namespace."""
@patch('kubernetes.client.AppsV1Api.create_namespaced_deployment')
def test_apply_single_manifest_deployment_no_namespace(self, mock_create_deployment):
"""Test _apply_single_manifest with Deployment missing namespace uses 'default'."""
manifest = {
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {"name": "test-deployment"},
"spec": {}
}

with self.assertRaises(ValueError) as context:
# pylint: disable=protected-access
self.client._apply_single_manifest(manifest)
# pylint: disable=protected-access
self.client._apply_single_manifest(manifest)

self.assertEqual(str(context.exception), "Deployment requires a namespace")
# Should use "default" namespace when none is specified
mock_create_deployment.assert_called_once_with(
namespace="default", body=manifest)

@patch('kubernetes.client.AppsV1Api.create_namespaced_daemon_set')
def test_apply_single_manifest_daemonset(self, mock_create_daemonset):
Expand Down Expand Up @@ -2567,20 +2569,22 @@ def test_apply_single_manifest_statefulset(self, mock_create_statefulset):
mock_create_statefulset.assert_called_once_with(
namespace="test-namespace", body=manifest)

def test_apply_single_manifest_statefulset_no_namespace(self):
"""Test _apply_single_manifest with StatefulSet missing namespace."""
@patch('kubernetes.client.AppsV1Api.create_namespaced_stateful_set')
def test_apply_single_manifest_statefulset_no_namespace(self, mock_create_statefulset):
"""Test _apply_single_manifest with StatefulSet missing namespace uses 'default'."""
manifest = {
"apiVersion": "apps/v1",
"kind": "StatefulSet",
"metadata": {"name": "test-statefulset"},
"spec": {}
}

with self.assertRaises(ValueError) as context:
# pylint: disable=protected-access
self.client._apply_single_manifest(manifest)
# pylint: disable=protected-access
self.client._apply_single_manifest(manifest)

self.assertEqual(str(context.exception), "StatefulSet requires a namespace")
# Should use "default" namespace when none is specified
mock_create_statefulset.assert_called_once_with(
namespace="default", body=manifest)

@patch('kubernetes.client.CoreV1Api.create_namespaced_service')
def test_apply_single_manifest_service(self, mock_create_service):
Expand Down Expand Up @@ -2654,20 +2658,27 @@ def test_apply_single_manifest_mpi_job(self, mock_create_custom_object):
body=manifest
)

def test_apply_single_manifest_mpi_job_no_namespace(self):
"""Test _apply_single_manifest with MPIJob missing namespace."""
@patch('kubernetes.client.CustomObjectsApi.create_namespaced_custom_object')
def test_apply_single_manifest_mpi_job_no_namespace(self, mock_create_custom_object):
"""Test _apply_single_manifest with MPIJob missing namespace uses 'default'."""
manifest = {
"apiVersion": "kubeflow.org/v2beta1",
"kind": "MPIJob",
"metadata": {"name": "test-mpi-job"},
"spec": {}
}

with self.assertRaises(ValueError) as context:
# pylint: disable=protected-access
self.client._apply_single_manifest(manifest)
# pylint: disable=protected-access
self.client._apply_single_manifest(manifest)

self.assertEqual(str(context.exception), "MPIJob requires a namespace")
# Should use "default" namespace when none is specified
mock_create_custom_object.assert_called_once_with(
group="kubeflow.org",
version="v2beta1",
namespace="default",
plural="mpijobs",
body=manifest
)

@patch('kubernetes.client.CustomObjectsApi.create_cluster_custom_object')
def test_apply_single_manifest_node_feature_rule(self, mock_create_custom_object):
Expand Down Expand Up @@ -2741,12 +2752,12 @@ def test_apply_single_manifest_resource_already_exists(self, mock_update_single,
# pylint: disable=protected-access
self.client._apply_single_manifest(manifest)
expected_calls = [
mock.call("Applying manifest %s %s in namespace %s", "Namespace", "existing-namespace", None),
mock.call("Applying manifest %s %s in namespace %s", "Namespace", "existing-namespace", "default"),
Comment thread
anson627 marked this conversation as resolved.
Resolved
mock.call("Resource %s/%s already exists, updating it", "Namespace", "existing-namespace")
]
mock_logger.info.assert_has_calls(expected_calls)
# Verify that _update_single_manifest was called with the correct arguments
mock_update_single.assert_called_once_with(manifest, None)
mock_update_single.assert_called_once_with(manifest, "default")

@patch('kubernetes.client.CoreV1Api.create_namespace')
def test_apply_single_manifest_api_exception_non_409(self, mock_create_namespace):
Expand Down Expand Up @@ -3691,11 +3702,12 @@ def test_apply_manifest_from_file_combined_sources(self, _mock_open_file, mock_y
mock_api.create_namespaced_service.assert_called_once()
mock_api.create_namespaced_config_map.assert_called_once()

@patch('kubernetes.client.AppsV1Api.create_namespaced_deployment')
@patch('os.path.isfile')
@patch('yaml.safe_load_all')
@patch('builtins.open', new_callable=mock_open)
def test_apply_manifest_from_file_deployment_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile):
"""Test apply_manifest_from_file with deployment manifest missing namespace - should raise error"""
def test_apply_manifest_from_file_deployment_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile, mock_create_deployment):
Comment thread
anson627 marked this conversation as resolved.
Resolved
"""Test apply_manifest_from_file with deployment manifest missing namespace uses 'default'"""
# Mock file existence check
mock_isfile.return_value = True

Expand All @@ -3710,17 +3722,18 @@ def test_apply_manifest_from_file_deployment_missing_namespace_error(self, _mock

mock_yaml_load.return_value = [manifest_dict]

# Should raise ValueError for missing namespace
with self.assertRaises(ValueError) as context:
self.client.apply_manifest_from_file(manifest_path="/path/to/deployment.yaml")
# Should use "default" namespace when none is specified
self.client.apply_manifest_from_file(manifest_path="/path/to/deployment.yaml")

self.assertIn("Deployment requires a namespace", str(context.exception))
mock_create_deployment.assert_called_once_with(
namespace="default", body=manifest_dict)

@patch('kubernetes.client.CoreV1Api.create_namespaced_service')
@patch('os.path.isfile')
@patch('yaml.safe_load_all')
@patch('builtins.open', new_callable=mock_open)
def test_apply_manifest_from_file_service_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile):
"""Test apply_manifest_from_file with service manifest missing namespace - should raise error"""
def test_apply_manifest_from_file_service_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile, mock_create_service):
Comment thread
anson627 marked this conversation as resolved.
Resolved
"""Test apply_manifest_from_file with service manifest missing namespace uses 'default'"""
# Mock file existence check
mock_isfile.return_value = True

Expand All @@ -3735,17 +3748,18 @@ def test_apply_manifest_from_file_service_missing_namespace_error(self, _mock_op

mock_yaml_load.return_value = [manifest_dict]

# Should raise ValueError for missing namespace
with self.assertRaises(ValueError) as context:
self.client.apply_manifest_from_file(manifest_path="/path/to/service.yaml")
# Should use "default" namespace when none is specified
self.client.apply_manifest_from_file(manifest_path="/path/to/service.yaml")

self.assertIn("Service requires a namespace", str(context.exception))
mock_create_service.assert_called_once_with(
namespace="default", body=manifest_dict)

@patch('kubernetes.client.AppsV1Api.create_namespaced_stateful_set')
@patch('os.path.isfile')
@patch('yaml.safe_load_all')
@patch('builtins.open', new_callable=mock_open)
def test_apply_manifest_from_file_statefulset_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile):
"""Test apply_manifest_from_file with StatefulSet manifest missing namespace - should raise error"""
def test_apply_manifest_from_file_statefulset_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile, mock_create_statefulset):
Comment thread
anson627 marked this conversation as resolved.
Resolved
"""Test apply_manifest_from_file with StatefulSet manifest missing namespace uses 'default'"""
# Mock file existence check
mock_isfile.return_value = True

Expand All @@ -3760,17 +3774,18 @@ def test_apply_manifest_from_file_statefulset_missing_namespace_error(self, _moc

mock_yaml_load.return_value = [manifest_dict]

# Should raise ValueError for missing namespace
with self.assertRaises(ValueError) as context:
self.client.apply_manifest_from_file(manifest_path="/path/to/statefulset.yaml")
# Should use "default" namespace when none is specified
self.client.apply_manifest_from_file(manifest_path="/path/to/statefulset.yaml")

self.assertIn("StatefulSet requires a namespace", str(context.exception))
mock_create_statefulset.assert_called_once_with(
namespace="default", body=manifest_dict)

@patch('kubernetes.client.CoreV1Api.create_namespaced_config_map')
@patch('os.path.isfile')
@patch('yaml.safe_load_all')
@patch('builtins.open', new_callable=mock_open)
def test_apply_manifest_from_file_configmap_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile):
"""Test apply_manifest_from_file with ConfigMap manifest missing namespace - should raise error"""
def test_apply_manifest_from_file_configmap_missing_namespace_error(self, _mock_open_file, mock_yaml_load, mock_isfile, mock_create_configmap):
Comment thread
anson627 marked this conversation as resolved.
Resolved
"""Test apply_manifest_from_file with ConfigMap manifest missing namespace uses 'default'"""
# Mock file existence check
mock_isfile.return_value = True

Expand All @@ -3785,11 +3800,11 @@ def test_apply_manifest_from_file_configmap_missing_namespace_error(self, _mock_

mock_yaml_load.return_value = [manifest_dict]

# Should raise ValueError for missing namespace
with self.assertRaises(ValueError) as context:
self.client.apply_manifest_from_file(manifest_path="/path/to/configmap.yaml")
# Should use "default" namespace when none is specified
self.client.apply_manifest_from_file(manifest_path="/path/to/configmap.yaml")

self.assertIn("ConfigMap requires a namespace", str(context.exception))
mock_create_configmap.assert_called_once_with(
namespace="default", body=manifest_dict)

@patch('os.path.isfile')
@patch('builtins.open', new_callable=mock_open)
Expand Down Expand Up @@ -4763,7 +4778,7 @@ def test_apply_single_manifest_fallback_to_manifest_namespace(self):
)

def test_apply_single_manifest_no_namespace_anywhere_raises_error(self):
Comment thread
anson627 marked this conversation as resolved.
Resolved
"""Test _apply_single_manifest raises error when no namespace is provided anywhere."""
"""Test _apply_single_manifest uses 'default' when no namespace is provided anywhere."""
# Deployment manifest without namespace
manifest_dict = {
"apiVersion": "apps/v1",
Expand All @@ -4775,12 +4790,19 @@ def test_apply_single_manifest_no_namespace_anywhere_raises_error(self):
"spec": {"replicas": 1}
}

# Call _apply_single_manifest without namespace parameter
with self.assertRaises(ValueError) as context:
# Mock the app API client
with patch.object(self.client, 'app') as mock_app:
mock_app.create_namespaced_deployment.return_value = None

# Call _apply_single_manifest without namespace parameter
# pylint: disable=protected-access
self.client._apply_single_manifest(manifest_dict, namespace=None)

self.assertIn("Deployment requires a namespace", str(context.exception))
# Verify deployment was created with "default" namespace
mock_app.create_namespaced_deployment.assert_called_once_with(
namespace="default",
body=manifest_dict
)

# Tests for delete_manifest_from_file with namespace override functionality
@patch('os.path.isfile')
Expand Down