a6e1c9cbcea679f1f5b1a1e1f2efcac1b000dbcd
[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.Map;
28 import java.util.UUID;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.Future;
33 import javax.validation.Validation;
34 import javax.validation.ValidationException;
35 import lombok.AccessLevel;
36 import lombok.Getter;
37 import lombok.RequiredArgsConstructor;
38 import lombok.Setter;
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.DeployState;
49 import org.onap.policy.clamp.models.acm.concepts.LockState;
50 import org.onap.policy.common.utils.coder.Coder;
51 import org.onap.policy.common.utils.coder.CoderException;
52 import org.onap.policy.common.utils.coder.StandardCoder;
53 import org.onap.policy.models.base.PfModelException;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.springframework.stereotype.Component;
57
58 /**
59  * This class handles implementation of automationCompositionElement updates.
60  */
61 @Component
62 @RequiredArgsConstructor
63 public class AutomationCompositionElementHandler implements AutomationCompositionElementListener {
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 = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
70
71     @Setter
72     private ParticipantIntermediaryApi intermediaryApi;
73
74     private final KserveClient kserveClient;
75
76     @Getter(AccessLevel.PACKAGE)
77     private final Map<UUID, ConfigurationEntity> configRequestMap = new HashMap<>();
78
79
80     private static class ThreadConfig {
81
82         private int uninitializedToPassiveTimeout = 60;
83         private int statusCheckInterval = 30;
84     }
85
86     @Override
87     public void undeploy(UUID automationCompositionId, UUID automationCompositionElementId) {
88         var configurationEntity = configRequestMap.get(automationCompositionElementId);
89         if (configurationEntity != null) {
90             try {
91                 for (KserveInferenceEntity kserveInferenceEntity : configurationEntity.getKserveInferenceEntities()) {
92                     kserveClient.undeployInferenceService(kserveInferenceEntity.getNamespace(),
93                             kserveInferenceEntity.getName());
94                 }
95                 configRequestMap.remove(automationCompositionElementId);
96                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
97                         automationCompositionElementId, DeployState.UNDEPLOYED, LockState.NONE);
98             } catch (IOException | ApiException exception) {
99                 LOGGER.warn("Deletion of Inference service failed", exception);
100             }
101         }
102     }
103
104     /**
105      * Callback method to handle an update on an automation composition element.
106      *
107      * @param automationCompositionId the ID of the automation composition
108      * @param element the information on the automation composition element
109      * @param properties properties Map
110      */
111     @Override
112     public void deploy(UUID automationCompositionId, AcElementDeploy element, Map<String, Object> properties)
113             throws PfModelException {
114         try {
115             var configurationEntity = CODER.convert(properties, ConfigurationEntity.class);
116             var violations = Validation.buildDefaultValidatorFactory().getValidator().validate(configurationEntity);
117             if (violations.isEmpty()) {
118                 boolean isAllInferenceSvcDeployed = true;
119                 var config = CODER.convert(properties, ThreadConfig.class);
120                 for (KserveInferenceEntity kserveInferenceEntity : configurationEntity.getKserveInferenceEntities()) {
121                     kserveClient.deployInferenceService(kserveInferenceEntity.getNamespace(),
122                             kserveInferenceEntity.getPayload());
123
124                     if (!checkInferenceServiceStatus(kserveInferenceEntity.getName(),
125                             kserveInferenceEntity.getNamespace(), config.uninitializedToPassiveTimeout,
126                             config.statusCheckInterval)) {
127                         isAllInferenceSvcDeployed = false;
128                         break;
129                     }
130                 }
131                 if (isAllInferenceSvcDeployed) {
132                     configRequestMap.put(element.getId(), configurationEntity);
133                     intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
134                             DeployState.DEPLOYED, LockState.LOCKED);
135                 } else {
136                     LOGGER.error("Inference Service deployment failed");
137                 }
138             } else {
139                 LOGGER.error("Violations found in the config request parameters: {}", violations);
140                 throw new ValidationException("Constraint violations in the config request");
141             }
142         } catch (CoderException e) {
143             throw new KserveException(HttpStatus.SC_BAD_REQUEST, "Invalid inference service configuration", e);
144         } catch (InterruptedException e) {
145             Thread.currentThread().interrupt();
146             throw new KserveException("Interrupt in configuring the inference service", e);
147         } catch (IOException | ExecutionException | ApiException e) {
148             throw new KserveException("Failed to configure the inference service", e);
149         }
150     }
151
152     /**
153      * Check the status of Inference Service.
154      *
155      * @param inferenceServiceName name of the inference service
156      * @param namespace            kubernetes namespace
157      * @param timeout              Inference service time check
158      * @param statusCheckInterval  Status check time interval
159      * @return status of the inference service
160      * @throws ExecutionException   Exception on execution
161      * @throws InterruptedException Exception on inference service status check
162      */
163     public boolean checkInferenceServiceStatus(String inferenceServiceName, String namespace, int timeout,
164             int statusCheckInterval) throws ExecutionException, InterruptedException {
165         // Invoke runnable thread to check pod status
166         Future<String> result = executor.submit(
167                 new InferenceServiceValidator(inferenceServiceName, namespace, timeout, statusCheckInterval,
168                         kserveClient), "Done");
169         return (!result.get().isEmpty()) && result.isDone();
170     }
171 }