8036eb4146ffe28fb8386eef41e20f4e36450426
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2023 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 jakarta.validation.Validation;
25 import jakarta.validation.ValidationException;
26 import java.io.IOException;
27 import java.lang.invoke.MethodHandles;
28 import java.util.List;
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 lombok.RequiredArgsConstructor;
39 import org.apache.http.HttpStatus;
40 import org.onap.policy.clamp.acm.participant.intermediary.api.AutomationCompositionElementListener;
41 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
42 import org.onap.policy.clamp.acm.participant.kserve.exception.KserveException;
43 import org.onap.policy.clamp.acm.participant.kserve.k8s.InferenceServiceValidator;
44 import org.onap.policy.clamp.acm.participant.kserve.k8s.KserveClient;
45 import org.onap.policy.clamp.acm.participant.kserve.models.ConfigurationEntity;
46 import org.onap.policy.clamp.acm.participant.kserve.models.KserveInferenceEntity;
47 import org.onap.policy.clamp.models.acm.concepts.AcElementDeploy;
48 import org.onap.policy.clamp.models.acm.concepts.AcTypeState;
49 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElementDefinition;
50 import org.onap.policy.clamp.models.acm.concepts.DeployState;
51 import org.onap.policy.clamp.models.acm.concepts.LockState;
52 import org.onap.policy.clamp.models.acm.concepts.StateChangeResult;
53 import org.onap.policy.clamp.models.acm.utils.AcmUtils;
54 import org.onap.policy.common.utils.coder.Coder;
55 import org.onap.policy.common.utils.coder.CoderException;
56 import org.onap.policy.common.utils.coder.StandardCoder;
57 import org.onap.policy.models.base.PfModelException;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60 import org.springframework.stereotype.Component;
61
62 /**
63  * This class handles implementation of automationCompositionElement updates.
64  */
65 @Component
66 @RequiredArgsConstructor
67 public class AutomationCompositionElementHandler implements AutomationCompositionElementListener {
68
69     private static final Coder CODER = new StandardCoder();
70
71     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
72
73     private ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
74
75     private final ParticipantIntermediaryApi intermediaryApi;
76
77     private final KserveClient kserveClient;
78
79     @Getter(AccessLevel.PACKAGE)
80     private final Map<UUID, ConfigurationEntity> configRequestMap = new ConcurrentHashMap<>();
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 lock(UUID instanceId, UUID elementId) throws PfModelException {
176         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, null, LockState.LOCKED,
177                 StateChangeResult.NO_ERROR, "Locked");
178     }
179
180     @Override
181     public void unlock(UUID instanceId, UUID elementId) throws PfModelException {
182         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, null, LockState.UNLOCKED,
183                 StateChangeResult.NO_ERROR, "Unlocked");
184     }
185
186     @Override
187     public void delete(UUID instanceId, UUID elementId) throws PfModelException {
188         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, DeployState.DELETED, null,
189                 StateChangeResult.NO_ERROR, "Deleted");
190     }
191
192     @Override
193     public void update(UUID instanceId, AcElementDeploy element, Map<String, Object> properties)
194             throws PfModelException {
195         intermediaryApi.updateAutomationCompositionElementState(instanceId, element.getId(), DeployState.DEPLOYED, null,
196                 StateChangeResult.NO_ERROR, "Update not supported");
197     }
198
199     @Override
200     public void prime(UUID compositionId, List<AutomationCompositionElementDefinition> elementDefinitionList)
201             throws PfModelException {
202         intermediaryApi.updateCompositionState(compositionId, AcTypeState.PRIMED, StateChangeResult.NO_ERROR, "Primed");
203     }
204
205     @Override
206     public void deprime(UUID compositionId) throws PfModelException {
207         intermediaryApi.updateCompositionState(compositionId, AcTypeState.COMMISSIONED, StateChangeResult.NO_ERROR,
208                 "Deprimed");
209     }
210
211     @Override
212     public void handleRestartComposition(UUID compositionId,
213             List<AutomationCompositionElementDefinition> elementDefinitionList, AcTypeState state)
214             throws PfModelException {
215         var finalState = AcTypeState.PRIMED.equals(state) || AcTypeState.PRIMING.equals(state) ? AcTypeState.PRIMED
216                 : AcTypeState.COMMISSIONED;
217         intermediaryApi.updateCompositionState(compositionId, finalState, StateChangeResult.NO_ERROR, "Restarted");
218     }
219
220     @Override
221     public void handleRestartInstance(UUID automationCompositionId, AcElementDeploy element,
222             Map<String, Object> properties, DeployState deployState, LockState lockState) throws PfModelException {
223         if (DeployState.DEPLOYING.equals(deployState)) {
224             deploy(automationCompositionId, element, properties);
225             return;
226         }
227         if (DeployState.UNDEPLOYING.equals(deployState) || DeployState.DEPLOYED.equals(deployState)
228                 || DeployState.UPDATING.equals(deployState)) {
229             try {
230                 var configurationEntity = CODER.convert(properties, ConfigurationEntity.class);
231                 configRequestMap.put(element.getId(), configurationEntity);
232             } catch (CoderException e) {
233                 throw new KserveException(HttpStatus.SC_BAD_REQUEST, "Invalid inference service configuration", e);
234             }
235         }
236         if (DeployState.UNDEPLOYING.equals(deployState)) {
237             undeploy(automationCompositionId, element.getId());
238             return;
239         }
240         deployState = AcmUtils.deployCompleted(deployState);
241         lockState = AcmUtils.lockCompleted(deployState, lockState);
242         intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(), deployState,
243                 lockState, StateChangeResult.NO_ERROR, "Restarted");
244     }
245 }