89c98400e800c84429d9590eda2a2b03af324ddb
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2022 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.Set;
29 import java.util.UUID;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.Future;
35 import java.util.stream.Collectors;
36 import javax.validation.ConstraintViolation;
37 import javax.validation.Validation;
38 import javax.validation.ValidationException;
39 import lombok.Setter;
40 import org.apache.commons.lang3.tuple.Pair;
41 import org.onap.policy.clamp.acm.participant.http.main.models.ConfigRequest;
42 import org.onap.policy.clamp.acm.participant.http.main.webclient.AcHttpClient;
43 import org.onap.policy.clamp.acm.participant.intermediary.api.AutomationCompositionElementListener;
44 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
45 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
46 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionOrderedState;
47 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState;
48 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantMessageType;
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.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
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 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 Map<ToscaConceptIdentifier, Pair<Integer, String>> restResponseMap = new ConcurrentHashMap<>();
73
74     @Setter
75     private ParticipantIntermediaryApi intermediaryApi;
76
77     /**
78      * Handle automationCompositionElement statistics.
79      *
80      * @param automationCompositionElementId automation composition element id
81      */
82     @Override
83     public void handleStatistics(UUID automationCompositionElementId) {
84         // Implementation not needed for http participant
85
86     }
87
88     /**
89      * Handle a automation composition element state change.
90      *
91      * @param automationCompositionElementId the ID of the automation composition element
92      * @param currentState the current state of the automation composition element
93      * @param newState the state to which the automation composition element is changing to
94      * @throws PfModelException in case of a model exception
95      */
96     @Override
97     public void automationCompositionElementStateChange(ToscaConceptIdentifier automationCompositionId,
98         UUID automationCompositionElementId, AutomationCompositionState currentState,
99         AutomationCompositionOrderedState newState) {
100         switch (newState) {
101             case UNINITIALISED:
102                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
103                     automationCompositionElementId, newState, AutomationCompositionState.UNINITIALISED,
104                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
105                 break;
106             case PASSIVE:
107                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
108                     automationCompositionElementId, newState, AutomationCompositionState.PASSIVE,
109                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
110                 break;
111             case RUNNING:
112                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
113                     automationCompositionElementId, newState, AutomationCompositionState.RUNNING,
114                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
115                 break;
116             default:
117                 LOGGER.warn("Cannot transition from state {} to state {}", currentState, newState);
118                 break;
119         }
120     }
121
122     /**
123      * Callback method to handle an update on a automation composition element.
124      *
125      * @param element the information on the automation composition element
126      * @param nodeTemplate toscaNodeTemplate
127      */
128     @Override
129     public void automationCompositionElementUpdate(ToscaConceptIdentifier automationCompositionId,
130         AutomationCompositionElement element, ToscaNodeTemplate nodeTemplate) {
131         try {
132             var configRequest = CODER.convert(nodeTemplate.getProperties(), ConfigRequest.class);
133             Set<ConstraintViolation<ConfigRequest>> violations =
134                 Validation.buildDefaultValidatorFactory().getValidator().validate(configRequest);
135             if (violations.isEmpty()) {
136                 invokeHttpClient(configRequest);
137                 List<Pair<Integer, String>> failedResponseStatus = restResponseMap.values().stream()
138                         .filter(response -> !HttpStatus.valueOf(response.getKey())
139                         .is2xxSuccessful()).collect(Collectors.toList());
140                 if (failedResponseStatus.isEmpty()) {
141                     intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
142                             AutomationCompositionOrderedState.PASSIVE, AutomationCompositionState.PASSIVE,
143                             ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
144                 } else {
145                     LOGGER.error("Error on Invoking the http request: {}", failedResponseStatus);
146                 }
147             } else {
148                 LOGGER.error("Violations found in the config request parameters: {}", violations);
149                 throw new ValidationException("Constraint violations in the config request");
150             }
151         } catch (CoderException | ValidationException | InterruptedException | ExecutionException e) {
152             LOGGER.error("Error invoking the http request for the config ", e);
153         }
154     }
155
156     /**
157      * Invoke a runnable thread to execute http requests.
158      *
159      * @param configRequest ConfigRequest
160      */
161     public void invokeHttpClient(ConfigRequest configRequest) throws ExecutionException, InterruptedException {
162         // Invoke runnable thread to execute https requests of all config entities
163         Future<Map> result = executor.submit(new AcHttpClient(configRequest, restResponseMap), restResponseMap);
164         if (!result.get().isEmpty()) {
165             LOGGER.debug("Http Request Completed: {}", result.isDone());
166         }
167     }
168
169     /**
170      * Closes this stream and releases any system resources associated
171      * with it. If the stream is already closed then invoking this
172      * method has no effect.
173      *
174      * @throws IOException if an I/O error occurs
175      */
176     @Override
177     public void close() throws IOException {
178         executor.shutdown();
179     }
180 }