4d556579d5ca54c9e01546b47e7baa2a4cc26623
[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 java.io.IOException;
25 import java.lang.invoke.MethodHandles;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.UUID;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.Executors;
33 import java.util.concurrent.Future;
34 import javax.validation.Validation;
35 import javax.validation.ValidationException;
36 import lombok.AccessLevel;
37 import lombok.Getter;
38 import lombok.RequiredArgsConstructor;
39 import lombok.Setter;
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.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     @Setter
76     private ParticipantIntermediaryApi intermediaryApi;
77
78     private final KserveClient kserveClient;
79
80     @Getter(AccessLevel.PACKAGE)
81     private final Map<UUID, ConfigurationEntity> configRequestMap = new HashMap<>();
82
83     private static class ThreadConfig {
84
85         private int uninitializedToPassiveTimeout = 60;
86         private int statusCheckInterval = 30;
87     }
88
89     @Override
90     public void undeploy(UUID automationCompositionId, UUID automationCompositionElementId) {
91         var configurationEntity = configRequestMap.get(automationCompositionElementId);
92         if (configurationEntity != null) {
93             try {
94                 for (KserveInferenceEntity kserveInferenceEntity : configurationEntity.getKserveInferenceEntities()) {
95                     kserveClient.undeployInferenceService(kserveInferenceEntity.getNamespace(),
96                             kserveInferenceEntity.getName());
97                 }
98                 configRequestMap.remove(automationCompositionElementId);
99                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
100                         automationCompositionElementId, DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR,
101                         "Undeployed");
102             } catch (IOException | ApiException exception) {
103                 LOGGER.warn("Deletion of Inference service failed", exception);
104             }
105         }
106     }
107
108     /**
109      * Callback method to handle an update on an automation composition element.
110      *
111      * @param automationCompositionId the ID of the automation composition
112      * @param element the information on the automation composition element
113      * @param properties properties Map
114      */
115     @Override
116     public void deploy(UUID automationCompositionId, AcElementDeploy element, Map<String, Object> properties)
117             throws PfModelException {
118         try {
119             var configurationEntity = CODER.convert(properties, ConfigurationEntity.class);
120             var violations = Validation.buildDefaultValidatorFactory().getValidator().validate(configurationEntity);
121             if (violations.isEmpty()) {
122                 boolean isAllInferenceSvcDeployed = true;
123                 var config = CODER.convert(properties, ThreadConfig.class);
124                 for (KserveInferenceEntity kserveInferenceEntity : configurationEntity.getKserveInferenceEntities()) {
125                     kserveClient.deployInferenceService(kserveInferenceEntity.getNamespace(),
126                             kserveInferenceEntity.getPayload());
127
128                     if (!checkInferenceServiceStatus(kserveInferenceEntity.getName(),
129                             kserveInferenceEntity.getNamespace(), config.uninitializedToPassiveTimeout,
130                             config.statusCheckInterval)) {
131                         isAllInferenceSvcDeployed = false;
132                         break;
133                     }
134                 }
135                 if (isAllInferenceSvcDeployed) {
136                     configRequestMap.put(element.getId(), configurationEntity);
137                     intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
138                             DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Deployed");
139                 } else {
140                     LOGGER.error("Inference Service deployment failed");
141                 }
142             } else {
143                 LOGGER.error("Violations found in the config request parameters: {}", violations);
144                 throw new ValidationException("Constraint violations in the config request");
145             }
146         } catch (CoderException e) {
147             throw new KserveException(HttpStatus.SC_BAD_REQUEST, "Invalid inference service configuration", e);
148         } catch (InterruptedException e) {
149             Thread.currentThread().interrupt();
150             throw new KserveException("Interrupt in configuring the inference service", e);
151         } catch (IOException | ExecutionException | ApiException e) {
152             throw new KserveException("Failed to configure the inference service", e);
153         }
154     }
155
156     /**
157      * Check the status of Inference Service.
158      *
159      * @param inferenceServiceName name of the inference service
160      * @param namespace kubernetes namespace
161      * @param timeout Inference service time check
162      * @param statusCheckInterval Status check time interval
163      * @return status of the inference service
164      * @throws ExecutionException Exception on execution
165      * @throws InterruptedException Exception on inference service status check
166      */
167     public boolean checkInferenceServiceStatus(String inferenceServiceName, String namespace, int timeout,
168             int statusCheckInterval) throws ExecutionException, InterruptedException {
169         // Invoke runnable thread to check pod status
170         Future<String> result = executor.submit(new InferenceServiceValidator(inferenceServiceName, namespace, timeout,
171                 statusCheckInterval, kserveClient), "Done");
172         return (!result.get().isEmpty()) && result.isDone();
173     }
174
175     @Override
176     public void lock(UUID instanceId, UUID elementId) throws PfModelException {
177         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, null, LockState.LOCKED,
178                 StateChangeResult.NO_ERROR, "Locked");
179     }
180
181     @Override
182     public void unlock(UUID instanceId, UUID elementId) throws PfModelException {
183         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, null, LockState.UNLOCKED,
184                 StateChangeResult.NO_ERROR, "Unlocked");
185     }
186
187     @Override
188     public void delete(UUID instanceId, UUID elementId) throws PfModelException {
189         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, DeployState.DELETED, null,
190                 StateChangeResult.NO_ERROR, "Deleted");
191     }
192
193     @Override
194     public void update(UUID instanceId, AcElementDeploy element, Map<String, Object> properties)
195             throws PfModelException {
196         intermediaryApi.updateAutomationCompositionElementState(instanceId, element.getId(), DeployState.DEPLOYED, null,
197                 StateChangeResult.NO_ERROR, "Update not supported");
198     }
199
200     @Override
201     public void prime(UUID compositionId, List<AutomationCompositionElementDefinition> elementDefinitionList)
202             throws PfModelException {
203         intermediaryApi.updateCompositionState(compositionId, AcTypeState.PRIMED, StateChangeResult.NO_ERROR, "Primed");
204     }
205
206     @Override
207     public void deprime(UUID compositionId) throws PfModelException {
208         intermediaryApi.updateCompositionState(compositionId, AcTypeState.COMMISSIONED, StateChangeResult.NO_ERROR,
209                 "Deprimed");
210     }
211 }