86a864efc69726daf7073cd640a606c849c8b68c
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 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.controlloop.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.Set;
28 import java.util.UUID;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import javax.validation.ConstraintViolation;
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.controlloop.models.controlloop.concepts.ControlLoopElement;
38 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState;
39 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState;
40 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantMessageType;
41 import org.onap.policy.clamp.controlloop.participant.http.main.models.ConfigRequest;
42 import org.onap.policy.clamp.controlloop.participant.http.main.webclient.ClHttpClient;
43 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ControlLoopElementListener;
44 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryApi;
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.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.stereotype.Component;
54
55 /**
56  * This class handles implementation of controlLoopElement updates.
57  */
58 @Component
59 public class ControlLoopElementHandler implements ControlLoopElementListener, 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 ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
66
67     private Map<ToscaConceptIdentifier, Pair<Integer, String>> restResponseMap = new ConcurrentHashMap<>();
68
69     @Setter
70     private ParticipantIntermediaryApi intermediaryApi;
71
72     /**
73      * Handle controlLoopElement statistics.
74      *
75      * @param controlLoopElementId controlloop element id
76      */
77     @Override
78     public void handleStatistics(UUID controlLoopElementId) throws PfModelException {
79         // Implementation not needed for http participant
80
81     }
82
83     /**
84      * Handle a control loop element state change.
85      *
86      * @param controlLoopElementId the ID of the control loop element
87      * @param currentState         the current state of the control loop element
88      * @param newState             the state to which the control loop element is changing to
89      * @throws PfModelException in case of a model exception
90      */
91     @Override
92     public void controlLoopElementStateChange(ToscaConceptIdentifier controlLoopId, UUID controlLoopElementId,
93             ControlLoopState currentState, ControlLoopOrderedState newState) throws PfModelException {
94         switch (newState) {
95             case UNINITIALISED:
96                 intermediaryApi.updateControlLoopElementState(controlLoopId,
97                         controlLoopElementId, newState, ControlLoopState.UNINITIALISED,
98                         ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
99                 break;
100             case PASSIVE:
101                 intermediaryApi.updateControlLoopElementState(controlLoopId,
102                         controlLoopElementId, newState, ControlLoopState.PASSIVE,
103                         ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
104                 break;
105             case RUNNING:
106                 intermediaryApi.updateControlLoopElementState(controlLoopId,
107                         controlLoopElementId, newState, ControlLoopState.RUNNING,
108                         ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
109                 break;
110             default:
111                 LOGGER.warn("Cannot transition from state {} to state {}", currentState, newState);
112                 break;
113         }
114     }
115
116     /**
117      * Callback method to handle an update on a control loop element.
118      *
119      * @param element the information on the control loop element
120      * @param nodeTemplate toscaNodeTemplate
121      */
122     @Override
123     public void controlLoopElementUpdate(ToscaConceptIdentifier controlLoopId, ControlLoopElement element,
124             ToscaNodeTemplate nodeTemplate) {
125         try {
126             var configRequest = CODER.convert(nodeTemplate.getProperties(), ConfigRequest.class);
127             Set<ConstraintViolation<ConfigRequest>> violations = Validation.buildDefaultValidatorFactory()
128                 .getValidator().validate(configRequest);
129             if (violations.isEmpty()) {
130                 invokeHttpClient(configRequest);
131                 intermediaryApi.updateControlLoopElementState(controlLoopId, element.getId(),
132                         ControlLoopOrderedState.PASSIVE, ControlLoopState.PASSIVE,
133                         ParticipantMessageType.CONTROL_LOOP_STATE_CHANGE);
134             } else {
135                 LOGGER.error("Violations found in the config request parameters: {}", violations);
136                 throw new ValidationException("Constraint violations in the config request");
137             }
138         } catch (CoderException | ValidationException e) {
139             LOGGER.error("Error invoking the http request for the config ", e);
140         }
141     }
142
143     /**
144      * Invoke a runnable thread to execute http requests.
145      * @param configRequest ConfigRequest
146      */
147     public void invokeHttpClient(ConfigRequest configRequest) {
148         // Invoke runnable thread to execute https requests of all config entities
149         executor.execute(new ClHttpClient(configRequest, restResponseMap));
150     }
151
152     /**
153      * Closes this stream and releases any system resources associated
154      * with it. If the stream is already closed then invoking this
155      * method has no effect.
156      *
157      * @throws IOException if an I/O error occurs
158      */
159     @Override
160     public void close() throws IOException {
161         executor.shutdown();
162     }
163 }