42b26c6a417af13628ea65fcbc928bb90076afe2
[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.Map;
27 import java.util.UUID;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.stream.Collectors;
33 import javax.validation.Validation;
34 import javax.validation.ValidationException;
35 import lombok.Setter;
36 import org.apache.commons.lang3.tuple.Pair;
37 import org.onap.policy.clamp.acm.participant.http.main.models.ConfigRequest;
38 import org.onap.policy.clamp.acm.participant.http.main.webclient.AcHttpClient;
39 import org.onap.policy.clamp.acm.participant.intermediary.api.AutomationCompositionElementListener;
40 import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
41 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
42 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionOrderedState;
43 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionState;
44 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantMessageType;
45 import org.onap.policy.common.utils.coder.Coder;
46 import org.onap.policy.common.utils.coder.CoderException;
47 import org.onap.policy.common.utils.coder.StandardCoder;
48 import org.onap.policy.models.base.PfModelException;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.http.HttpStatus;
53 import org.springframework.stereotype.Component;
54
55 /**
56  * This class handles implementation of automationCompositionElement updates.
57  */
58 @Component
59 public class AutomationCompositionElementHandler implements AutomationCompositionElementListener, Closeable {
60
61     private static final Coder CODER = new StandardCoder();
62
63     private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
64
65     private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
66
67     private final Map<ToscaConceptIdentifier, Pair<Integer, String>> restResponseMap = new ConcurrentHashMap<>();
68
69     @Setter
70     private ParticipantIntermediaryApi intermediaryApi;
71
72     /**
73      * Handle a automation composition element state change.
74      *
75      * @param automationCompositionElementId the ID of the automation composition element
76      * @param currentState the current state of the automation composition element
77      * @param newState the state to which the automation composition element is changing to
78      * @throws PfModelException in case of a model exception
79      */
80     @Override
81     public void automationCompositionElementStateChange(UUID automationCompositionId,
82         UUID automationCompositionElementId, AutomationCompositionState currentState,
83         AutomationCompositionOrderedState newState) {
84         switch (newState) {
85             case UNINITIALISED:
86                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
87                     automationCompositionElementId, newState, AutomationCompositionState.UNINITIALISED,
88                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
89                 break;
90             case PASSIVE:
91                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
92                     automationCompositionElementId, newState, AutomationCompositionState.PASSIVE,
93                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
94                 break;
95             case RUNNING:
96                 intermediaryApi.updateAutomationCompositionElementState(automationCompositionId,
97                     automationCompositionElementId, newState, AutomationCompositionState.RUNNING,
98                     ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
99                 break;
100             default:
101                 LOGGER.warn("Cannot transition from state {} to state {}", currentState, newState);
102                 break;
103         }
104     }
105
106     /**
107      * Callback method to handle an update on a automation composition element.
108      *
109      * @param automationCompositionId the automationComposition Id
110      * @param element the information on the automation composition element
111      * @param properties properties Map
112      */
113     @Override
114     public void automationCompositionElementUpdate(UUID automationCompositionId,
115         AutomationCompositionElement element, Map<String, Object> properties) {
116         try {
117             var configRequest = CODER.convert(properties, ConfigRequest.class);
118             var violations =
119                 Validation.buildDefaultValidatorFactory().getValidator().validate(configRequest);
120             if (violations.isEmpty()) {
121                 invokeHttpClient(configRequest);
122                 var failedResponseStatus = restResponseMap.values().stream()
123                         .filter(response -> !HttpStatus.valueOf(response.getKey())
124                         .is2xxSuccessful()).collect(Collectors.toList());
125                 if (failedResponseStatus.isEmpty()) {
126                     intermediaryApi.updateAutomationCompositionElementState(automationCompositionId, element.getId(),
127                             AutomationCompositionOrderedState.PASSIVE, AutomationCompositionState.PASSIVE,
128                             ParticipantMessageType.AUTOMATION_COMPOSITION_STATE_CHANGE);
129                 } else {
130                     LOGGER.error("Error on Invoking the http request: {}", failedResponseStatus);
131                 }
132             } else {
133                 LOGGER.error("Violations found in the config request parameters: {}", violations);
134                 throw new ValidationException("Constraint violations in the config request");
135             }
136         } catch (CoderException | ValidationException | InterruptedException | ExecutionException e) {
137             LOGGER.error("Error invoking the http request for the config ", e);
138         }
139     }
140
141     /**
142      * Invoke a runnable thread to execute http requests.
143      *
144      * @param configRequest ConfigRequest
145      */
146     public void invokeHttpClient(ConfigRequest configRequest) throws ExecutionException, InterruptedException {
147         // Invoke runnable thread to execute https requests of all config entities
148         var result = executor.submit(new AcHttpClient(configRequest, restResponseMap), restResponseMap);
149         if (!result.get().isEmpty()) {
150             LOGGER.debug("Http Request Completed: {}", result.isDone());
151         }
152     }
153
154     /**
155      * Closes this stream and releases any system resources associated
156      * with it. If the stream is already closed then invoking this
157      * method has no effect.
158      *
159      * @throws IOException if an I/O error occurs
160      */
161     @Override
162     public void close() throws IOException {
163         executor.shutdown();
164     }
165 }