966aee971b9a133eca803a11a0d5900f2d4e8bc2
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-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.http.main.handler;
22
23 import java.io.Closeable;
24 import java.io.IOException;
25 import java.lang.invoke.MethodHandles;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.UUID;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.Executors;
33 import java.util.stream.Collectors;
34 import javax.validation.Validation;
35 import javax.ws.rs.core.Response.Status;
36 import lombok.RequiredArgsConstructor;
37 import lombok.Setter;
38 import org.apache.commons.lang3.tuple.Pair;
39 import org.onap.policy.clamp.acm.participant.http.main.models.ConfigRequest;
40 import org.onap.policy.clamp.acm.participant.http.main.webclient.AcHttpClient;
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.common.acm.exception.AutomationCompositionException;
44 import org.onap.policy.clamp.models.acm.concepts.AcElementDeploy;
45 import org.onap.policy.clamp.models.acm.concepts.AcTypeState;
46 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElementDefinition;
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.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.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.springframework.http.HttpStatus;
58 import org.springframework.stereotype.Component;
59
60 /**
61  * This class handles implementation of automationCompositionElement updates.
62  */
63 @Component
64 @RequiredArgsConstructor
65 public class AutomationCompositionElementHandler implements AutomationCompositionElementListener, Closeable {
66
67     private static final Coder CODER = new StandardCoder();
68
69     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
70
71     private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
72
73     @Setter
74     private ParticipantIntermediaryApi intermediaryApi;
75
76     private final AcHttpClient acHttpClient;
77
78     /**
79      * Handle a automation composition element state change.
80      *
81      * @param automationCompositionElementId the ID of the automation composition element
82      */
83     @Override
84     public void undeploy(UUID automationCompositionId, UUID automationCompositionElementId) {
85         intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, automationCompositionElementId,
86                 DeployState.UNDEPLOYED, null, StateChangeResult.NO_ERROR, "");
87     }
88
89     /**
90      * Callback method to handle an update on a automation composition element.
91      *
92      * @param automationCompositionId the automationComposition Id
93      * @param element the information on the automation composition element
94      * @param properties properties Map
95      * @throws PfModelException in case of a exception
96      */
97     @Override
98     public void deploy(UUID automationCompositionId, AcElementDeploy element, Map<String, Object> properties)
99             throws PfModelException {
100         try {
101             var configRequest = getConfigRequest(properties);
102             var restResponseMap = invokeHttpClient(configRequest);
103             var failedResponseStatus = restResponseMap.values().stream()
104                     .filter(response -> !HttpStatus.valueOf(response.getKey()).is2xxSuccessful())
105                     .collect(Collectors.toList());
106             if (failedResponseStatus.isEmpty()) {
107                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
108                         DeployState.DEPLOYED, null, StateChangeResult.NO_ERROR, "Deployed");
109             } else {
110                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
111                         DeployState.UNDEPLOYED, null, StateChangeResult.FAILED,
112                         "Error on Invoking the http request: " + failedResponseStatus);
113             }
114         } catch (AutomationCompositionException e) {
115             intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
116                     DeployState.UNDEPLOYED, null, StateChangeResult.FAILED, e.getMessage());
117         }
118     }
119
120     private ConfigRequest getConfigRequest(Map<String, Object> properties) throws AutomationCompositionException {
121         try {
122             var configRequest = CODER.convert(properties, ConfigRequest.class);
123             var violations = Validation.buildDefaultValidatorFactory().getValidator().validate(configRequest);
124             if (!violations.isEmpty()) {
125                 LOGGER.error("Violations found in the config request parameters: {}", violations);
126                 throw new AutomationCompositionException(Status.BAD_REQUEST,
127                         "Constraint violations in the config request");
128             }
129             return configRequest;
130         } catch (CoderException e) {
131             throw new AutomationCompositionException(Status.BAD_REQUEST, "Error extracting ConfigRequest ", e);
132         }
133     }
134
135     /**
136      * Invoke a runnable thread to execute http requests.
137      *
138      * @param configRequest ConfigRequest
139      */
140     private Map<ToscaConceptIdentifier, Pair<Integer, String>> invokeHttpClient(ConfigRequest configRequest)
141             throws PfModelException {
142         try {
143             Map<ToscaConceptIdentifier, Pair<Integer, String>> restResponseMap = new ConcurrentHashMap<>();
144             // Invoke runnable thread to execute https requests of all config entities
145             var result = executor.submit(() -> acHttpClient.run(configRequest, restResponseMap), restResponseMap);
146             if (!result.get().isEmpty()) {
147                 LOGGER.debug("Http Request Completed: {}", result.isDone());
148             }
149             return restResponseMap;
150         } catch (InterruptedException e) {
151             Thread.currentThread().interrupt();
152             throw new PfModelException(Status.BAD_REQUEST, "Error invoking ExecutorService ", e);
153         } catch (ExecutionException e) {
154             throw new PfModelException(Status.BAD_REQUEST, "Error invoking the http request for the config ", e);
155         }
156     }
157
158     @Override
159     public void lock(UUID instanceId, UUID elementId) throws PfModelException {
160         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, null, LockState.LOCKED,
161                 StateChangeResult.NO_ERROR, "Locked");
162     }
163
164     @Override
165     public void unlock(UUID instanceId, UUID elementId) throws PfModelException {
166         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, null, LockState.UNLOCKED,
167                 StateChangeResult.NO_ERROR, "Unlocked");
168     }
169
170     @Override
171     public void delete(UUID instanceId, UUID elementId) throws PfModelException {
172         intermediaryApi.updateAutomationCompositionElementState(instanceId, elementId, DeployState.DELETED, null,
173                 StateChangeResult.NO_ERROR, "Deleted");
174     }
175
176     @Override
177     public void update(UUID instanceId, AcElementDeploy element, Map<String, Object> properties)
178             throws PfModelException {
179         intermediaryApi.updateAutomationCompositionElementState(instanceId, element.getId(), DeployState.DEPLOYED, null,
180                 StateChangeResult.NO_ERROR, "Update not supported");
181     }
182
183     @Override
184     public void prime(UUID compositionId, List<AutomationCompositionElementDefinition> elementDefinitionList)
185             throws PfModelException {
186         intermediaryApi.updateCompositionState(compositionId, AcTypeState.PRIMED, StateChangeResult.NO_ERROR, "Primed");
187     }
188
189     @Override
190     public void deprime(UUID compositionId) throws PfModelException {
191         intermediaryApi.updateCompositionState(compositionId, AcTypeState.COMMISSIONED, StateChangeResult.NO_ERROR,
192                 "Deprimed");
193     }
194
195     /**
196      * Closes this stream and releases any system resources associated
197      * with it. If the stream is already closed then invoking this
198      * method has no effect.
199      *
200      * @throws IOException if an I/O error occurs
201      */
202     @Override
203     public void close() throws IOException {
204         executor.shutdown();
205     }
206 }