Skip to content
Open
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
34 changes: 34 additions & 0 deletions kubeflow/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,46 @@
from kubernetes import config

from kubeflow.common import constants
from kubeflow.common.types import KubernetesBackendConfig


def is_running_in_k8s() -> bool:
return os.path.isdir("/var/run/secrets/kubernetes.io/")


def load_kube_config(cfg: KubernetesBackendConfig) -> None:
"""Load the Kubernetes client configuration for a backend.

Trainer, Optimizer and Spark share this so that a given KubernetesBackendConfig
resolves to the same cluster in every client.

Precedence:
1. ``client_configuration`` is set: nothing is loaded, the caller builds its
API client from it.
2. ``config_file`` is set, or the SDK runs outside a pod: kube-config is loaded
with ``config_file`` and ``context``.
3. Otherwise in-cluster config is loaded. If that fails, kube-config is tried
so a pod with a mounted kube-config still works.

Args:
cfg: Kubernetes backend configuration.

Raises:
kubernetes.config.ConfigException: If no configuration can be loaded.
"""
if cfg.client_configuration is not None:
return

if cfg.config_file or not is_running_in_k8s():
config.load_kube_config(config_file=cfg.config_file, context=cfg.context)
return

try:
config.load_incluster_config()
except config.ConfigException:
config.load_kube_config(context=cfg.context)


def get_default_target_namespace(context: str | None = None) -> str:
if not is_running_in_k8s():
try:
Expand Down
133 changes: 132 additions & 1 deletion kubeflow/common/utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,14 @@
# 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 unittest.mock import call, patch

from kubernetes import client, config
import pytest

from kubeflow.common import utils
from kubeflow.test.common import SUCCESS, TestCase
from kubeflow.common.types import KubernetesBackendConfig
from kubeflow.test.common import FAILED, SUCCESS, TestCase

# --------------------------
# Test Helpers
Expand Down Expand Up @@ -99,6 +103,133 @@ def test_validate_wait_for_job_status(test_case):
utils.validate_wait_for_job_status(polling_interval, timeout)


@pytest.mark.parametrize(
"test_case",
[
TestCase(
name="client_configuration set, nothing loaded",
expected_status=SUCCESS,
config={
"backend_config": KubernetesBackendConfig(
client_configuration=client.Configuration(),
config_file="/tmp/kubeconfig",
context="ctx",
),
"in_cluster": True,
},
expected_output={"load_kube_config": [], "load_incluster_config": []},
),
TestCase(
name="config_file and context are both passed through",
expected_status=SUCCESS,
config={
"backend_config": KubernetesBackendConfig(
config_file="/tmp/kubeconfig", context="ctx"
),
"in_cluster": False,
},
expected_output={
"load_kube_config": [call(config_file="/tmp/kubeconfig", context="ctx")],
"load_incluster_config": [],
},
),
TestCase(
name="config_file wins over in-cluster config",
expected_status=SUCCESS,
config={
"backend_config": KubernetesBackendConfig(
config_file="/tmp/kubeconfig", context="ctx"
),
"in_cluster": True,
},
expected_output={
"load_kube_config": [call(config_file="/tmp/kubeconfig", context="ctx")],
"load_incluster_config": [],
},
),
TestCase(
name="context outside a pod loads kube-config with that context",
expected_status=SUCCESS,
config={"backend_config": KubernetesBackendConfig(context="ctx"), "in_cluster": False},
expected_output={
"load_kube_config": [call(config_file=None, context="ctx")],
"load_incluster_config": [],
},
),
TestCase(
name="nothing set outside a pod loads the default kube-config",
expected_status=SUCCESS,
config={"backend_config": KubernetesBackendConfig(), "in_cluster": False},
expected_output={
"load_kube_config": [call(config_file=None, context=None)],
"load_incluster_config": [],
},
),
TestCase(
name="inside a pod loads in-cluster config",
expected_status=SUCCESS,
config={"backend_config": KubernetesBackendConfig(context="ctx"), "in_cluster": True},
expected_output={"load_kube_config": [], "load_incluster_config": [call()]},
),
TestCase(
name="in-cluster config failure falls back to kube-config",
expected_status=SUCCESS,
config={
"backend_config": KubernetesBackendConfig(context="ctx"),
"in_cluster": True,
"incluster_error": config.ConfigException("Service host/port is not set."),
},
expected_output={
"load_kube_config": [call(context="ctx")],
"load_incluster_config": [call()],
},
),
TestCase(
name="error is raised when neither config can be loaded",
expected_status=FAILED,
config={
"backend_config": KubernetesBackendConfig(),
"in_cluster": True,
"incluster_error": config.ConfigException("Service host/port is not set."),
"load_error": config.ConfigException("Invalid kube-config file."),
},
expected_error=config.ConfigException,
),
],
)
def test_load_kube_config(test_case):
"""Test load_kube_config picks one config source per KubernetesBackendConfig."""
print("Executing test:", test_case.name)

with (
patch(
"kubeflow.common.utils.is_running_in_k8s",
return_value=test_case.config["in_cluster"],
),
patch(
"kubernetes.config.load_kube_config",
side_effect=test_case.config.get("load_error"),
) as mock_load_kube_config,
patch(
"kubernetes.config.load_incluster_config",
side_effect=test_case.config.get("incluster_error"),
) as mock_load_incluster_config,
):
if test_case.expected_error:
with pytest.raises(test_case.expected_error, match="Invalid kube-config file"):
utils.load_kube_config(test_case.config["backend_config"])
return

utils.load_kube_config(test_case.config["backend_config"])

assert test_case.expected_status == SUCCESS
assert mock_load_kube_config.call_args_list == test_case.expected_output["load_kube_config"]
assert (
mock_load_incluster_config.call_args_list
== test_case.expected_output["load_incluster_config"]
)


@pytest.mark.parametrize(
"test_case",
[
Expand Down
10 changes: 2 additions & 8 deletions kubeflow/optimizer/backends/kubernetes/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import uuid

from kubeflow_katib_api import models
from kubernetes import client, config
from kubernetes import client

import kubeflow.common.constants as common_constants
from kubeflow.common.types import KubernetesBackendConfig
Expand Down Expand Up @@ -52,13 +52,7 @@ def __init__(self, cfg: KubernetesBackendConfig):
if cfg.namespace is None:
cfg.namespace = common_utils.get_default_target_namespace(cfg.context)

# If client configuration is not set, use kube-config to access Kubernetes APIs.
if cfg.client_configuration is None:
# Load kube-config or in-cluster config.
if cfg.config_file or not common_utils.is_running_in_k8s():
config.load_kube_config(config_file=cfg.config_file, context=cfg.context)
else:
config.load_incluster_config()
common_utils.load_kube_config(cfg)

k8s_client = client.ApiClient(cfg.client_configuration)
self.custom_api = client.CustomObjectsApi(k8s_client)
Expand Down
19 changes: 6 additions & 13 deletions kubeflow/spark/backends/kubernetes/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@
from typing import Any

from kubeflow_spark_api import models
from kubernetes import client, config
from kubernetes import client
from pyspark.sql import SparkSession

from kubeflow.common import constants as common_constants
from kubeflow.common.types import KubernetesBackendConfig
from kubeflow.common.utils import validate_python_function
from kubeflow.common.utils import load_kube_config, validate_python_function
from kubeflow.spark.backends.base import RuntimeBackend
from kubeflow.spark.backends.kubernetes import constants
from kubeflow.spark.backends.kubernetes.utils import (
Expand Down Expand Up @@ -101,18 +101,11 @@ def __init__(self, backend_config: KubernetesBackendConfig):
"""
self.namespace = backend_config.namespace or "default"

if backend_config.config_file:
config.load_kube_config(config_file=backend_config.config_file)
elif backend_config.context:
config.load_kube_config(context=backend_config.context)
else:
try:
config.load_incluster_config()
except config.ConfigException:
config.load_kube_config()
load_kube_config(backend_config)

self.custom_api = client.CustomObjectsApi()
self.core_api = client.CoreV1Api()
k8s_client = client.ApiClient(backend_config.client_configuration)
self.custom_api = client.CustomObjectsApi(k8s_client)
self.core_api = client.CoreV1Api(k8s_client)

# ------------------------------------------------------------------
# Spark Connect sessions
Expand Down
53 changes: 52 additions & 1 deletion kubeflow/spark/backends/kubernetes/backend_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from datetime import datetime
import multiprocessing
from unittest.mock import MagicMock, Mock, patch
from unittest.mock import MagicMock, Mock, call, patch

from kubeflow_spark_api import models
from kubernetes import client
Expand Down Expand Up @@ -80,6 +80,57 @@ def kubernetes_backend():
yield KubernetesBackend(KubernetesBackendConfig())


@pytest.mark.parametrize(
"test_case",
[
TestCase(
name="config_file and context are both passed to kube-config",
expected_status=SUCCESS,
config={
"backend_config": KubernetesBackendConfig(
config_file="/tmp/kubeconfig", context="ctx"
),
},
expected_output=[call(config_file="/tmp/kubeconfig", context="ctx")],
),
TestCase(
name="client_configuration is used and kube-config is not loaded",
expected_status=SUCCESS,
config={
"backend_config": KubernetesBackendConfig(
client_configuration=client.Configuration(host="https://custom-k8s:6443"),
),
},
expected_output=[],
),
],
)
def test_backend_config_loading(test_case):
"""Test KubernetesBackend loads its client config through the common loader."""
print("Executing test:", test_case.name)

backend_config = test_case.config["backend_config"]
with (
patch("kubernetes.config.load_kube_config") as mock_load_kube_config,
patch("kubernetes.config.load_incluster_config") as mock_load_incluster_config,
):
backend = KubernetesBackend(backend_config)

assert test_case.expected_status == SUCCESS
assert mock_load_kube_config.call_args_list == test_case.expected_output
mock_load_incluster_config.assert_not_called()

expected_host = (
backend_config.client_configuration.host
if backend_config.client_configuration
else client.Configuration.get_default_copy().host
)
assert backend.custom_api.api_client.configuration.host == expected_host
assert backend.core_api.api_client is backend.custom_api.api_client

print("test execution complete")


# --------------------------
# Mock Helpers
# --------------------------
Expand Down
10 changes: 2 additions & 8 deletions kubeflow/trainer/backends/kubernetes/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import uuid

from kubeflow_trainer_api import models
from kubernetes import client, config, watch
from kubernetes import client, watch

import kubeflow.common.constants as common_constants
from kubeflow.common.types import KubernetesBackendConfig
Expand All @@ -43,13 +43,7 @@ def __init__(self, cfg: KubernetesBackendConfig):
if cfg.namespace is None:
cfg.namespace = common_utils.get_default_target_namespace(cfg.context)

# If client configuration is not set, use kube-config to access Kubernetes APIs.
if cfg.client_configuration is None:
# Load kube-config or in-cluster config.
if cfg.config_file or not common_utils.is_running_in_k8s():
config.load_kube_config(config_file=cfg.config_file, context=cfg.context)
else:
config.load_incluster_config()
common_utils.load_kube_config(cfg)

k8s_client = client.ApiClient(cfg.client_configuration)
self.custom_api = client.CustomObjectsApi(k8s_client)
Expand Down
Loading