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