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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.clamp.acm.participant.kserve.handler;
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;
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;
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;
60 * This class handles implementation of automationCompositionElement updates.
63 public class AutomationCompositionElementHandler extends AcElementListenerV1 {
65 private static final Coder CODER = new StandardCoder();
67 private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
69 private ExecutorService executor = Context.taskWrapping(
70 Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
72 private final KserveClient kserveClient;
74 @Getter(AccessLevel.PACKAGE)
75 private final Map<UUID, ConfigurationEntity> configRequestMap = new ConcurrentHashMap<>();
77 public AutomationCompositionElementHandler(ParticipantIntermediaryApi intermediaryApi, KserveClient kserveClient) {
78 super(intermediaryApi);
79 this.kserveClient = kserveClient;
82 private static class ThreadConfig {
84 private int uninitializedToPassiveTimeout = 60;
85 private int statusCheckInterval = 30;
89 public void undeploy(UUID automationCompositionId, UUID automationCompositionElementId) {
90 var configurationEntity = configRequestMap.get(automationCompositionElementId);
91 if (configurationEntity != null) {
93 for (KserveInferenceEntity kserveInferenceEntity : configurationEntity.getKserveInferenceEntities()) {
94 kserveClient.undeployInferenceService(kserveInferenceEntity.getNamespace(),
95 kserveInferenceEntity.getName());
97 configRequestMap.remove(automationCompositionElementId);
98 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
99 automationCompositionElementId, DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR,
101 } catch (IOException | ApiException exception) {
102 LOGGER.warn("Deletion of Inference service failed", exception);
108 * Callback method to handle an update on an automation composition element.
110 * @param automationCompositionId the ID of the automation composition
111 * @param element the information on the automation composition element
112 * @param properties properties Map
115 public void deploy(UUID automationCompositionId, AcElementDeploy element, Map<String, Object> properties)
116 throws PfModelException {
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());
127 if (!checkInferenceServiceStatus(kserveInferenceEntity.getName(),
128 kserveInferenceEntity.getNamespace(), config.uninitializedToPassiveTimeout,
129 config.statusCheckInterval)) {
130 isAllInferenceSvcDeployed = false;
134 if (isAllInferenceSvcDeployed) {
135 configRequestMap.put(element.getId(), configurationEntity);
136 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
137 DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Deployed");
139 LOGGER.error("Inference Service deployment failed");
142 LOGGER.error("Violations found in the config request parameters: {}", violations);
143 throw new ValidationException("Constraint violations in the config request");
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);
156 * Check the status of Inference Service.
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
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();
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);
181 if (DeployState.UNDEPLOYING.equals(deployState) || DeployState.DEPLOYED.equals(deployState)
182 || DeployState.UPDATING.equals(deployState)) {
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);
190 if (DeployState.UNDEPLOYING.equals(deployState)) {
191 undeploy(automationCompositionId, element.getId());
194 deployState = AcmUtils.deployCompleted(deployState);
195 lockState = AcmUtils.lockCompleted(deployState, lockState);
196 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(), deployState,
197 lockState, StateChangeResult.NO_ERROR, "Restarted");