d9c932efd4fd146f711efdfadccacc1032eea091
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2023-2024 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.acm.participant.kserve.handler;
22
23 import io.kubernetes.client.openapi.ApiException;
24 import io.opentelemetry.context.Context;
25 import jakarta.validation.Validation;
26 import jakarta.validation.ValidationException;
27 import java.io.IOException;
28 import java.lang.invoke.MethodHandles;
29 import java.util.HashMap;
30 import java.util.Map;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import org.apache.http.HttpStatus;
35 import org.onap.policy.clamp.acm.participant.intermediary.api.CompositionElementDto;
36 import org.onap.policy.clamp.acm.participant.intermediary.api.InstanceElementDto;
37 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
38 import org.onap.policy.clamp.acm.participant.intermediary.api.impl.AcElementListenerV2;
39 import org.onap.policy.clamp.acm.participant.kserve.exception.KserveException;
40 import org.onap.policy.clamp.acm.participant.kserve.k8s.InferenceServiceValidator;
41 import org.onap.policy.clamp.acm.participant.kserve.k8s.KserveClient;
42 import org.onap.policy.clamp.acm.participant.kserve.models.ConfigurationEntity;
43 import org.onap.policy.clamp.acm.participant.kserve.models.KserveInferenceEntity;
44 import org.onap.policy.clamp.models.acm.concepts.DeployState;
45 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
46 import org.onap.policy.common.utils.coder.Coder;
47 import org.onap.policy.common.utils.coder.CoderException;
48 import org.onap.policy.common.utils.coder.StandardCoder;
49 import org.onap.policy.models.base.PfModelException;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.stereotype.Component;
53
54 /**
55  * This class handles implementation of automationCompositionElement updates.
56  */
57 @Component
58 public class AutomationCompositionElementHandler extends AcElementListenerV2 {
59
60     private static final Coder CODER = new StandardCoder();
61
62     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
63
64     private final ExecutorService executor = Context.taskWrapping(
65             Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
66
67     private final KserveClient kserveClient;
68
69     public AutomationCompositionElementHandler(ParticipantIntermediaryApi intermediaryApi, KserveClient kserveClient) {
70         super(intermediaryApi);
71         this.kserveClient = kserveClient;
72     }
73
74     private static class ThreadConfig {
75
76         private int uninitializedToPassiveTimeout = 60;
77         private int statusCheckInterval = 30;
78     }
79
80     @Override
81     public void undeploy(CompositionElementDto compositionElement, InstanceElementDto instanceElement)
82             throws PfModelException {
83         Map<String, Object> properties = new HashMap<>(compositionElement.inProperties());
84         properties.putAll(instanceElement.inProperties());
85         var configurationEntity = getConfigurationEntity(properties);
86         if (configurationEntity != null) {
87             try {
88                 for (KserveInferenceEntity kserveInferenceEntity : configurationEntity.getKserveInferenceEntities()) {
89                     kserveClient.undeployInferenceService(kserveInferenceEntity.getNamespace(),
90                             kserveInferenceEntity.getName());
91                 }
92                 intermediaryApi.updateAutomationCompositionElementState(instanceElement.instanceId(),
93                         instanceElement.elementId(), DeployState.UNDEPLOYED, null,
94                         StateChangeResult.NO_ERROR, "Undeployed");
95             } catch (IOException | ApiException exception) {
96                 LOGGER.warn("Deletion of Inference service failed", exception);
97                 intermediaryApi.updateAutomationCompositionElementState(instanceElement.instanceId(),
98                         instanceElement.elementId(), DeployState.DEPLOYED, null,
99                         StateChangeResult.FAILED, "Undeploy Failed");
100             }
101         }
102     }
103
104     /**
105      * Callback method to handle an update on an automation composition element.
106      *
107      * @param compositionElement the information of the Automation Composition Definition Element
108      * @param instanceElement the information of the Automation Composition Instance Element
109      * @throws PfModelException if error occurs
110      */
111     @Override
112     public void deploy(CompositionElementDto compositionElement, InstanceElementDto instanceElement)
113             throws PfModelException {
114         Map<String, Object> properties = new HashMap<>(compositionElement.inProperties());
115         properties.putAll(instanceElement.inProperties());
116         try {
117             var configurationEntity = getConfigurationEntity(properties);
118             boolean isAllInferenceSvcDeployed = true;
119             var config = getThreadConfig(properties);
120             for (var kserveInferenceEntity : configurationEntity.getKserveInferenceEntities()) {
121                 kserveClient.deployInferenceService(kserveInferenceEntity.getNamespace(),
122                         kserveInferenceEntity.getPayload());
123
124                 if (!checkInferenceServiceStatus(kserveInferenceEntity.getName(),
125                         kserveInferenceEntity.getNamespace(), config.uninitializedToPassiveTimeout,
126                         config.statusCheckInterval)) {
127                     isAllInferenceSvcDeployed = false;
128                     break;
129                 }
130             }
131             if (isAllInferenceSvcDeployed) {
132                 intermediaryApi.updateAutomationCompositionElementState(instanceElement.instanceId(),
133                         instanceElement.elementId(), DeployState.DEPLOYED, null,
134                         StateChangeResult.NO_ERROR, "Deployed");
135             } else {
136                 LOGGER.error("Inference Service deployment failed");
137                 intermediaryApi.updateAutomationCompositionElementState(instanceElement.instanceId(),
138                         instanceElement.elementId(), DeployState.UNDEPLOYED, null,
139                         StateChangeResult.FAILED, "Deploy Failed");
140             }
141         } catch (InterruptedException e) {
142             Thread.currentThread().interrupt();
143             throw new KserveException("Interrupt in configuring the inference service", e);
144         } catch (IOException | ExecutionException | ApiException e) {
145             throw new KserveException("Failed to configure the inference service", e);
146         }
147
148     }
149
150     private ConfigurationEntity getConfigurationEntity(Map<String, Object> properties) throws KserveException {
151         try {
152             var configurationEntity = CODER.convert(properties, ConfigurationEntity.class);
153             try (var validatorFactory = Validation.buildDefaultValidatorFactory()) {
154                 var violations = validatorFactory.getValidator().validate(configurationEntity);
155                 if (!violations.isEmpty()) {
156                     LOGGER.error("Violations found in the config request parameters: {}", violations);
157                     throw new ValidationException("Constraint violations in the config request");
158                 }
159             }
160             return  configurationEntity;
161         } catch (CoderException e) {
162             throw new KserveException(HttpStatus.SC_BAD_REQUEST, "Invalid inference service configuration", e);
163         }
164     }
165
166     private ThreadConfig getThreadConfig(Map<String, Object> properties) throws KserveException {
167         try {
168             return CODER.convert(properties, ThreadConfig.class);
169         } catch (CoderException e) {
170             throw new KserveException(HttpStatus.SC_BAD_REQUEST, "Invalid inference service configuration", e);
171         }
172     }
173
174     /**
175      * Check the status of Inference Service.
176      *
177      * @param inferenceServiceName name of the inference service
178      * @param namespace kubernetes namespace
179      * @param timeout Inference service time check
180      * @param statusCheckInterval Status check time interval
181      * @return status of the inference service
182      * @throws ExecutionException Exception on execution
183      * @throws InterruptedException Exception on inference service status check
184      */
185     public boolean checkInferenceServiceStatus(String inferenceServiceName, String namespace, int timeout,
186             int statusCheckInterval) throws ExecutionException, InterruptedException {
187         // Invoke runnable thread to check pod status
188         var result = executor.submit(new InferenceServiceValidator(inferenceServiceName, namespace, timeout,
189                 statusCheckInterval, kserveClient), "Done");
190         return (!result.get().isEmpty()) && result.isDone();
191     }
192 }