|
| 1 | +# |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | + |
| 14 | +"""KServe sklearn prediction test. |
| 15 | +
|
| 16 | +Deploys an sklearn InferenceService via the KServe Python SDK, |
| 17 | +waits for Ready, runs a prediction via host-based routing, |
| 18 | +asserts the output, and cleans up. |
| 19 | +
|
| 20 | +This test is fully independent - it does not rely on any |
| 21 | +external deployment from kserve_test.sh. |
| 22 | +
|
| 23 | +Because of the mesh-wide global-deny-all AuthorizationPolicy |
| 24 | +(common/istio/istio-install/base/deny_all_authorizationpolicy.yaml), |
| 25 | +the predictor pod's sidecar blocks all traffic by default. |
| 26 | +We create a permissive ALLOW AuthorizationPolicy (rules: [{}]) on the |
| 27 | +predictor pod. Security is enforced at the ingress gateway, which |
| 28 | +validates the JWT via RequestAuthentication before forwarding. |
| 29 | +""" |
| 30 | + |
| 31 | +import os |
| 32 | +import sys |
| 33 | + |
| 34 | +os.system( |
| 35 | + f"{sys.executable} -m pip install -q" |
| 36 | + " pytest>=7.0.0 kserve>=0.16.0 kubernetes>=18.20.0 requests>=2.18.4" |
| 37 | +) |
| 38 | + |
| 39 | +import json |
| 40 | +import logging |
| 41 | +import time |
| 42 | + |
| 43 | +import requests |
| 44 | +from kubernetes import client |
| 45 | +from kubernetes.client import V1ResourceRequirements |
| 46 | + |
| 47 | +from kserve import ( |
| 48 | + KServeClient, |
| 49 | + V1beta1InferenceService, |
| 50 | + V1beta1InferenceServiceSpec, |
| 51 | + V1beta1PredictorSpec, |
| 52 | + V1beta1SKLearnSpec, |
| 53 | + constants, |
| 54 | +) |
| 55 | + |
| 56 | +logging.basicConfig(level=logging.INFO) |
| 57 | + |
| 58 | +AUTHORIZATION_POLICY_NAME = "allow-isvc-sklearn" |
| 59 | +SERVICE_NAME = "isvc-sklearn" |
| 60 | +KSERVE_TEST_NAMESPACE = os.environ.get( |
| 61 | + "KSERVE_TEST_NAMESPACE", "kubeflow-user-example-com" |
| 62 | +) |
| 63 | + |
| 64 | +IRIS_INPUT = {"instances": [[6.8, 2.8, 4.8, 1.4], [6.0, 3.4, 4.5, 1.6]]} |
| 65 | + |
| 66 | + |
| 67 | +class M2mTokenNotAvailable(Exception): |
| 68 | + pass |
| 69 | + |
| 70 | + |
| 71 | +def get_cluster_ip(name="istio-ingressgateway", namespace="istio-system"): |
| 72 | + api_instance = client.CoreV1Api(client.ApiClient()) |
| 73 | + service = api_instance.read_namespaced_service(name, namespace) |
| 74 | + if service.status.load_balancer.ingress is None: |
| 75 | + cluster_ip = service.spec.cluster_ip |
| 76 | + else: |
| 77 | + if service.status.load_balancer.ingress[0].hostname: |
| 78 | + cluster_ip = service.status.load_balancer.ingress[0].hostname |
| 79 | + else: |
| 80 | + cluster_ip = service.status.load_balancer.ingress[0].ip |
| 81 | + return os.environ.get("KSERVE_INGRESS_HOST_PORT", cluster_ip) |
| 82 | + |
| 83 | + |
| 84 | +def get_m2m_auth_token(env_name="KSERVE_M2M_TOKEN"): |
| 85 | + try: |
| 86 | + return os.environ[env_name] |
| 87 | + except KeyError: |
| 88 | + raise M2mTokenNotAvailable(env_name) |
| 89 | + |
| 90 | + |
| 91 | +def predict(service_name, input_data): |
| 92 | + """Send a prediction request using host-based routing.""" |
| 93 | + kfs_client = KServeClient( |
| 94 | + config_file=os.environ.get("KUBECONFIG", "~/.kube/config") |
| 95 | + ) |
| 96 | + kfs_client.get( |
| 97 | + service_name, |
| 98 | + namespace=KSERVE_TEST_NAMESPACE, |
| 99 | + version=constants.KSERVE_V1BETA1_VERSION, |
| 100 | + ) |
| 101 | + time.sleep(10) |
| 102 | + cluster_ip = get_cluster_ip() |
| 103 | + |
| 104 | + host = f"{service_name}.{KSERVE_TEST_NAMESPACE}.example.com" |
| 105 | + headers = { |
| 106 | + "Host": host, |
| 107 | + "Content-Type": "application/json", |
| 108 | + } |
| 109 | + |
| 110 | + try: |
| 111 | + token = get_m2m_auth_token() |
| 112 | + headers["Authorization"] = f"Bearer {token}" |
| 113 | + logging.info("M2M Token Found.") |
| 114 | + except M2mTokenNotAvailable: |
| 115 | + logging.warning("M2M Token Not found, client authentication disabled.") |
| 116 | + |
| 117 | + url = f"http://{cluster_ip}/v1/models/{service_name}:predict" |
| 118 | + |
| 119 | + logging.info("Sending Header = %s", headers) |
| 120 | + logging.info("Sending url = %s", url) |
| 121 | + logging.info("Sending request data: %s", input_data) |
| 122 | + response = requests.post(url, json.dumps(input_data), headers=headers) |
| 123 | + logging.info( |
| 124 | + "Got response code %s, content %s", response.status_code, response.content |
| 125 | + ) |
| 126 | + if response.status_code == 200: |
| 127 | + return json.loads(response.content.decode("utf-8")) |
| 128 | + response.raise_for_status() |
| 129 | + |
| 130 | + |
| 131 | +def create_predictor_authorization_policy(namespace): |
| 132 | + """Create an AuthorizationPolicy allowing traffic to the predictor pod.""" |
| 133 | + api = client.CustomObjectsApi() |
| 134 | + ap_body = { |
| 135 | + "apiVersion": "security.istio.io/v1beta1", |
| 136 | + "kind": "AuthorizationPolicy", |
| 137 | + "metadata": { |
| 138 | + "name": AUTHORIZATION_POLICY_NAME, |
| 139 | + "namespace": namespace, |
| 140 | + }, |
| 141 | + "spec": { |
| 142 | + "action": "ALLOW", |
| 143 | + "rules": [{}], |
| 144 | + "selector": { |
| 145 | + "matchLabels": { |
| 146 | + "serving.knative.dev/service": f"{SERVICE_NAME}-predictor", |
| 147 | + } |
| 148 | + }, |
| 149 | + }, |
| 150 | + } |
| 151 | + api.create_namespaced_custom_object( |
| 152 | + group="security.istio.io", |
| 153 | + version="v1beta1", |
| 154 | + namespace=namespace, |
| 155 | + plural="authorizationpolicies", |
| 156 | + body=ap_body, |
| 157 | + ) |
| 158 | + logging.info( |
| 159 | + "Created AuthorizationPolicy %s in %s", |
| 160 | + AUTHORIZATION_POLICY_NAME, |
| 161 | + namespace, |
| 162 | + ) |
| 163 | + |
| 164 | + |
| 165 | +def delete_predictor_authorization_policy(namespace): |
| 166 | + """Delete the predictor AuthorizationPolicy.""" |
| 167 | + api = client.CustomObjectsApi() |
| 168 | + try: |
| 169 | + api.delete_namespaced_custom_object( |
| 170 | + group="security.istio.io", |
| 171 | + version="v1beta1", |
| 172 | + namespace=namespace, |
| 173 | + plural="authorizationpolicies", |
| 174 | + name=AUTHORIZATION_POLICY_NAME, |
| 175 | + ) |
| 176 | + logging.info( |
| 177 | + "Deleted AuthorizationPolicy %s in %s", |
| 178 | + AUTHORIZATION_POLICY_NAME, |
| 179 | + namespace, |
| 180 | + ) |
| 181 | + except client.exceptions.ApiException as exc: |
| 182 | + if exc.status != 404: |
| 183 | + raise |
| 184 | + |
| 185 | + |
| 186 | +def test_sklearn_kserve(): |
| 187 | + predictor = V1beta1PredictorSpec( |
| 188 | + min_replicas=1, |
| 189 | + sklearn=V1beta1SKLearnSpec( |
| 190 | + storage_uri="gs://kfserving-examples/models/sklearn/1.0/model", |
| 191 | + resources=V1ResourceRequirements( |
| 192 | + requests={"cpu": "50m", "memory": "128Mi"}, |
| 193 | + limits={"cpu": "100m", "memory": "256Mi"}, |
| 194 | + ), |
| 195 | + ), |
| 196 | + ) |
| 197 | + |
| 198 | + isvc = V1beta1InferenceService( |
| 199 | + api_version=constants.KSERVE_V1BETA1, |
| 200 | + kind="InferenceService", |
| 201 | + metadata=client.V1ObjectMeta( |
| 202 | + name=SERVICE_NAME, namespace=KSERVE_TEST_NAMESPACE |
| 203 | + ), |
| 204 | + spec=V1beta1InferenceServiceSpec(predictor=predictor), |
| 205 | + ) |
| 206 | + |
| 207 | + kserve_client = KServeClient( |
| 208 | + config_file=os.environ.get("KUBECONFIG", "~/.kube/config") |
| 209 | + ) |
| 210 | + |
| 211 | + try: |
| 212 | + create_predictor_authorization_policy(KSERVE_TEST_NAMESPACE) |
| 213 | + |
| 214 | + kserve_client.create(isvc) |
| 215 | + kserve_client.wait_isvc_ready( |
| 216 | + SERVICE_NAME, namespace=KSERVE_TEST_NAMESPACE |
| 217 | + ) |
| 218 | + |
| 219 | + response = predict(SERVICE_NAME, IRIS_INPUT) |
| 220 | + assert response["predictions"] == [1, 1] |
| 221 | + logging.info( |
| 222 | + "Python SDK prediction passed for %s in %s", |
| 223 | + SERVICE_NAME, |
| 224 | + KSERVE_TEST_NAMESPACE, |
| 225 | + ) |
| 226 | + finally: |
| 227 | + kserve_client.delete(SERVICE_NAME, KSERVE_TEST_NAMESPACE) |
| 228 | + delete_predictor_authorization_policy(KSERVE_TEST_NAMESPACE) |
0 commit comments