d4b09c923fbb657b6ae9d7a55619200ebf1359c6
[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.Map;
30 import java.util.UUID;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.Future;
36 import lombok.AccessLevel;
37 import lombok.Getter;
38 import org.apache.http.HttpStatus;
39 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
40 import org.onap.policy.clamp.acm.participant.intermediary.api.impl.AcElementListenerV1;
41 import org.onap.policy.clamp.acm.participant.kserve.exception.KserveException;
42 import org.onap.policy.clamp.acm.participant.kserve.k8s.InferenceServiceValidator;
43 import org.onap.policy.clamp.acm.participant.kserve.k8s.KserveClient;
44 import org.onap.policy.clamp.acm.participant.kserve.models.ConfigurationEntity;
45 import org.onap.policy.clamp.acm.participant.kserve.models.KserveInferenceEntity;
46 import org.onap.policy.clamp.models.acm.concepts.AcElementDeploy;
47 import org.onap.policy.clamp.models.acm.concepts.DeployState;
48 import org.onap.policy.clamp.models.acm.concepts.LockState;
49 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
50 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
51 import org.onap.policy.common.utils.coder.Coder;
52 import org.onap.policy.common.utils.coder.CoderException;
53 import org.onap.policy.common.utils.coder.StandardCoder;
54 import org.onap.policy.models.base.PfModelException;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.springframework.stereotype.Component;
58
59 /**
60  * This class handles implementation of automationCompositionElement updates.
61  */
62 @Component
63 public class AutomationCompositionElementHandler extends AcElementListenerV1 {
64
65     private static final Coder CODER = new StandardCoder();
66
67     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
68
69     private ExecutorService executor = Context.taskWrapping(
70             Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
71
72     private final KserveClient kserveClient;
73
74     @Getter(AccessLevel.PACKAGE)
75     private final Map<UUID, ConfigurationEntity> configRequestMap = new ConcurrentHashMap<>();
76
77     public AutomationCompositionElementHandler(ParticipantIntermediaryApi intermediaryApi, KserveClient kserveClient) {
78         super(intermediaryApi);
79         this.kserveClient = kserveClient;
80     }
81
82     private static class ThreadConfig {
83
84         private int uninitializedToPassiveTimeout = 60;
85         private int statusCheckInterval = 30;
86     }
87
88     @Override
89     public void undeploy(UUID automationCompositionId, UUID automationCompositionElementId) {
90         var configurationEntity = configRequestMap.get(automationCompositionElementId);
91         if (configurationEntity != null) {
92             try {
93                 for (KserveInferenceEntity kserveInferenceEntity : configurationEntity.getKserveInferenceEntities()) {
94                     kserveClient.undeployInferenceService(kserveInferenceEntity.getNamespace(),
95                             kserveInferenceEntity.getName());
96                 }
97                 configRequestMap.remove(automationCompositionElementId);
98                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
99                         automationCompositionElementId, DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR,
100                         "Undeployed");
101             } catch (IOException | ApiException exception) {
102                 LOGGER.warn("Deletion of Inference service failed", exception);
103             }
104         }
105     }
106
107     /**
108      * Callback method to handle an update on an automation composition element.
109      *
110      * @param automationCompositionId the ID of the automation composition
111      * @param element the information on the automation composition element
112      * @param properties properties Map
113      */
114     @Override
115     public void deploy(UUID automationCompositionId, AcElementDeploy element, Map<String, Object> properties)
116             throws PfModelException {
117         try {
118             var configurationEntity = CODER.convert(properties, ConfigurationEntity.class);
119             var violations = Validation.buildDefaultValidatorFactory().getValidator().validate(configurationEntity);
120             if (violations.isEmpty()) {
121                 boolean isAllInferenceSvcDeployed = true;
122                 var config = CODER.convert(properties, ThreadConfig.class);
123                 for (KserveInferenceEntity kserveInferenceEntity : configurationEntity.getKserveInferenceEntities()) {
124                     kserveClient.deployInferenceService(kserveInferenceEntity.getNamespace(),
125                             kserveInferenceEntity.getPayload());
126
127                     if (!checkInferenceServiceStatus(kserveInferenceEntity.getName(),
128                             kserveInferenceEntity.getNamespace(), config.uninitializedToPassiveTimeout,
129                             config.statusCheckInterval)) {
130                         isAllInferenceSvcDeployed = false;
131                         break;
132                     }
133                 }
134                 if (isAllInferenceSvcDeployed) {
135                     configRequestMap.put(element.getId(), configurationEntity);
136                     intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
137                             DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Deployed");
138                 } else {
139                     LOGGER.error("Inference Service deployment failed");
140                 }
141             } else {
142                 LOGGER.error("Violations found in the config request parameters: {}", violations);
143                 throw new ValidationException("Constraint violations in the config request");
144             }
145         } catch (CoderException e) {
146             throw new KserveException(HttpStatus.SC_BAD_REQUEST, "Invalid inference service configuration", e);
147         } catch (InterruptedException e) {
148             Thread.currentThread().interrupt();
149             throw new KserveException("Interrupt in configuring the inference service", e);
150         } catch (IOException | ExecutionException | ApiException e) {
151             throw new KserveException("Failed to configure the inference service", e);
152         }
153     }
154
155     /**
156      * Check the status of Inference Service.
157      *
158      * @param inferenceServiceName name of the inference service
159      * @param namespace kubernetes namespace
160      * @param timeout Inference service time check
161      * @param statusCheckInterval Status check time interval
162      * @return status of the inference service
163      * @throws ExecutionException Exception on execution
164      * @throws InterruptedException Exception on inference service status check
165      */
166     public boolean checkInferenceServiceStatus(String inferenceServiceName, String namespace, int timeout,
167             int statusCheckInterval) throws ExecutionException, InterruptedException {
168         // Invoke runnable thread to check pod status
169         Future<String> result = executor.submit(new InferenceServiceValidator(inferenceServiceName, namespace, timeout,
170                 statusCheckInterval, kserveClient), "Done");
171         return (!result.get().isEmpty()) && result.isDone();
172     }
173
174     @Override
175     public void handleRestartInstance(UUID automationCompositionId, AcElementDeploy element,
176             Map<String, Object> properties, DeployState deployState, LockState lockState) throws PfModelException {
177         if (DeployState.DEPLOYING.equals(deployState)) {
178             deploy(automationCompositionId, element, properties);
179             return;
180         }
181         if (DeployState.UNDEPLOYING.equals(deployState) || DeployState.DEPLOYED.equals(deployState)
182                 || DeployState.UPDATING.equals(deployState)) {
183             try {
184                 var configurationEntity = CODER.convert(properties, ConfigurationEntity.class);
185                 configRequestMap.put(element.getId(), configurationEntity);
186             } catch (CoderException e) {
187                 throw new KserveException(HttpStatus.SC_BAD_REQUEST, "Invalid inference service configuration", e);
188             }
189         }
190         if (DeployState.UNDEPLOYING.equals(deployState)) {
191             undeploy(automationCompositionId, element.getId());
192             return;
193         }
194         deployState = AcmUtils.deployCompleted(deployState);
195         lockState = AcmUtils.lockCompleted(deployState, lockState);
196         intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(), deployState,
197                 lockState, StateChangeResult.NO_ERROR, "Restarted");
198     }
199 }