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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.clamp.controlloop.participant.http.main.handler;
23 import java.io.Closeable;
24 import java.io.IOException;
25 import java.lang.invoke.MethodHandles;
26 import java.util.List;
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;
40 import org.apache.commons.lang3.tuple.Pair;
41 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement;
42 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState;
43 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState;
44 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantMessageType;
45 import org.onap.policy.clamp.controlloop.participant.http.main.models.ConfigRequest;
46 import org.onap.policy.clamp.controlloop.participant.http.main.webclient.ClHttpClient;
47 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ControlLoopElementListener;
48 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryApi;
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;
61 * This class handles implementation of controlLoopElement updates.
64 public class ControlLoopElementHandler implements ControlLoopElementListener, Closeable {
66 private static final Coder CODER = new StandardCoder();
68 private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
70 private ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
72 private Map<ToscaConceptIdentifier, Pair<Integer, String>> restResponseMap = new ConcurrentHashMap<>();
75 private ParticipantIntermediaryApi intermediaryApi;
78 * Handle controlLoopElement statistics.
80 * @param controlLoopElementId controlloop element id
83 public void handleStatistics(UUID controlLoopElementId) throws PfModelException {
84 // Implementation not needed for http participant
89 * Handle a control loop element state change.
91 * @param controlLoopElementId the ID of the control loop element
92 * @param currentState the current state of the control loop element
93 * @param newState the state to which the control loop element is changing to
94 * @throws PfModelException in case of a model exception
97 public void controlLoopElementStateChange(ToscaConceptIdentifier controlLoopId, UUID controlLoopElementId,
98 ControlLoopState currentState, ControlLoopOrderedState newState) throws PfModelException {
101 intermediaryApi.updateControlLoopElementState(controlLoopId,
102 controlLoopElementId, newState, ControlLoopState.UNINITIALISED,
103 ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
106 intermediaryApi.updateControlLoopElementState(controlLoopId,
107 controlLoopElementId, newState, ControlLoopState.PASSIVE,
108 ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
111 intermediaryApi.updateControlLoopElementState(controlLoopId,
112 controlLoopElementId, newState, ControlLoopState.RUNNING,
113 ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
116 LOGGER.warn("Cannot transition from state {} to state {}", currentState, newState);
122 * Callback method to handle an update on a control loop element.
124 * @param element the information on the control loop element
125 * @param nodeTemplate toscaNodeTemplate
128 public void controlLoopElementUpdate(ToscaConceptIdentifier controlLoopId, ControlLoopElement element,
129 ToscaNodeTemplate nodeTemplate) {
131 var configRequest = CODER.convert(nodeTemplate.getProperties(), ConfigRequest.class);
132 Set<ConstraintViolation<ConfigRequest>> violations = Validation.buildDefaultValidatorFactory()
133 .getValidator().validate(configRequest);
134 if (violations.isEmpty()) {
135 invokeHttpClient(configRequest);
136 List<Pair<Integer, String>> failedResponseStatus = restResponseMap.values().stream()
137 .filter(response -> !HttpStatus.valueOf(response.getKey())
138 .is2xxSuccessful()).collect(Collectors.toList());
139 if (failedResponseStatus.isEmpty()) {
140 intermediaryApi.updateControlLoopElementState(controlLoopId, element.getId(),
141 ControlLoopOrderedState.PASSIVE, ControlLoopState.PASSIVE,
142 ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
144 LOGGER.error("Error on Invoking the http request: {}", failedResponseStatus);
147 LOGGER.error("Violations found in the config request parameters: {}", violations);
148 throw new ValidationException("Constraint violations in the config request");
150 } catch (CoderException | ValidationException | InterruptedException | ExecutionException e) {
151 LOGGER.error("Error invoking the http request for the config ", e);
156 * Invoke a runnable thread to execute http requests.
157 * @param configRequest ConfigRequest
159 public void invokeHttpClient(ConfigRequest configRequest) throws ExecutionException, InterruptedException {
160 // Invoke runnable thread to execute https requests of all config entities
161 Future<Map> result = executor.submit(new ClHttpClient(configRequest, restResponseMap), restResponseMap);
162 if (!result.get().isEmpty()) {
163 LOGGER.debug("Http Request Completed: {}", result.isDone());
168 * Closes this stream and releases any system resources associated
169 * with it. If the stream is already closed then invoking this
170 * method has no effect.
172 * @throws IOException if an I/O error occurs
175 public void close() throws IOException {