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