072a2ebc101a630ea5bd39148fb264503b747cb5
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
4  * ================================================================================
5  * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.clamp.controlloop.participant.intermediary.handler;
24
25 import java.time.Instant;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Objects;
30 import java.util.UUID;
31 import lombok.Getter;
32 import lombok.Setter;
33 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatisticsList;
34 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop;
35 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement;
36 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElementDefinition;
37 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopInfo;
38 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopStatistics;
39 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops;
40 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant;
41 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantDefinition;
42 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantHealthStatus;
43 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantState;
44 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantStatistics;
45 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ControlLoopStateChange;
46 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ControlLoopUpdate;
47 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantAckMessage;
48 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantDeregister;
49 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantDeregisterAck;
50 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantMessage;
51 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantRegister;
52 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantRegisterAck;
53 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantStatus;
54 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantStatusReq;
55 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantUpdate;
56 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantUpdateAck;
57 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ControlLoopElementListener;
58 import org.onap.policy.clamp.controlloop.participant.intermediary.comm.ParticipantMessagePublisher;
59 import org.onap.policy.clamp.controlloop.participant.intermediary.parameters.ParticipantParameters;
60 import org.onap.policy.models.base.PfModelException;
61 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64 import org.springframework.stereotype.Component;
65
66 /**
67  * This class is responsible for managing the state of a participant.
68  */
69 @Getter
70 @Component
71 public class ParticipantHandler {
72     private static final Logger LOGGER = LoggerFactory.getLogger(ParticipantHandler.class);
73
74     private final ToscaConceptIdentifier participantType;
75     private final ToscaConceptIdentifier participantId;
76     private final ControlLoopHandler controlLoopHandler;
77     private final ParticipantStatistics participantStatistics;
78     private final ParticipantMessagePublisher publisher;
79
80     @Setter
81     private ParticipantState state = ParticipantState.UNKNOWN;
82
83     @Setter
84     private ParticipantHealthStatus healthStatus = ParticipantHealthStatus.UNKNOWN;
85
86     private final List<ControlLoopElementDefinition> clElementDefsOnThisParticipant = new ArrayList<>();
87
88     /**
89      * Constructor, set the participant ID and sender.
90      *
91      * @param parameters the parameters of the participant
92      * @param publisher the publisher for sending responses to messages
93      */
94     public ParticipantHandler(ParticipantParameters parameters, ParticipantMessagePublisher publisher,
95             ControlLoopHandler controlLoopHandler) {
96         this.participantType = parameters.getIntermediaryParameters().getParticipantType();
97         this.participantId = parameters.getIntermediaryParameters().getParticipantId();
98         this.publisher = publisher;
99         this.controlLoopHandler = controlLoopHandler;
100         this.participantStatistics = new ParticipantStatistics();
101         this.participantStatistics.setParticipantId(participantId);
102         this.participantStatistics.setState(state);
103         this.participantStatistics.setHealthStatus(healthStatus);
104         this.participantStatistics.setTimeStamp(Instant.now());
105     }
106
107     /**
108      * Method which handles a participant health check event from clamp.
109      *
110      * @param participantStatusReqMsg participant participantStatusReq message
111      */
112     public void handleParticipantStatusReq(final ParticipantStatusReq participantStatusReqMsg) {
113         var controlLoops = controlLoopHandler.getControlLoops();
114         for (ControlLoopElementListener clElementListener : controlLoopHandler.getListeners()) {
115             updateClElementStatistics(controlLoops, clElementListener);
116         }
117
118         var participantStatus = makeHeartbeat(true);
119         publisher.sendParticipantStatus(participantStatus);
120     }
121
122     /**
123      * Update ControlLoopElement statistics. The control loop elements listening will be
124      * notified to retrieve statistics from respective controlloop elements, and controlloopelements
125      * data on the handler will be updated.
126      *
127      * @param controlLoops the control loops
128      * @param clElementListener control loop element listener
129      */
130     private void updateClElementStatistics(ControlLoops controlLoops, ControlLoopElementListener clElementListener) {
131         for (ControlLoop controlLoop : controlLoops.getControlLoopList()) {
132             for (ControlLoopElement element : controlLoop.getElements().values()) {
133                 try {
134                     clElementListener.handleStatistics(element.getId());
135                 } catch (PfModelException e) {
136                     LOGGER.debug("Getting statistics for Control loop element failed for element ID {}",
137                             element.getId(), e);
138                 }
139             }
140         }
141     }
142
143     /**
144      * Handle a control loop update message.
145      *
146      * @param updateMsg the update message
147      */
148     public void handleControlLoopUpdate(ControlLoopUpdate updateMsg) {
149         controlLoopHandler.handleControlLoopUpdate(updateMsg, clElementDefsOnThisParticipant);
150     }
151
152     /**
153      * Handle a control loop state change message.
154      *
155      * @param stateChangeMsg the state change message
156      */
157     public void handleControlLoopStateChange(ControlLoopStateChange stateChangeMsg) {
158         controlLoopHandler.handleControlLoopStateChange(stateChangeMsg);
159     }
160
161     private void handleStateChange(ParticipantState newParticipantState, ParticipantUpdateAck response) {
162         if (state.equals(newParticipantState)) {
163             response.setResult(false);
164             response.setMessage("Participant already in state " + newParticipantState);
165         } else {
166             response.setResult(true);
167             response.setMessage("Participant state changed from " + state + " to " + newParticipantState);
168             state = newParticipantState;
169         }
170     }
171
172     /**
173      * Method to update participant state.
174      *
175      * @param definition participant definition
176      * @param participantState participant state
177      * @return the participant
178      */
179     public Participant updateParticipantState(ToscaConceptIdentifier definition, ParticipantState participantState) {
180         if (!Objects.equals(definition, participantId)) {
181             LOGGER.debug("No participant with this ID {}", definition.getName());
182             return null;
183         }
184
185         var participantUpdateAck = new ParticipantUpdateAck();
186         handleStateChange(participantState, participantUpdateAck);
187         publisher.sendParticipantUpdateAck(participantUpdateAck);
188         return getParticipant(definition.getName(), definition.getVersion());
189     }
190
191     /**
192      * Get participants as a {@link Participant} class.
193      *
194      * @param name the participant name to get
195      * @param version the version of the participant to get
196      * @return the participant
197      */
198     public Participant getParticipant(String name, String version) {
199         if (participantId.getName().equals(name)) {
200             var participant = new Participant();
201             participant.setDefinition(participantId);
202             participant.setParticipantState(state);
203             participant.setHealthStatus(healthStatus);
204             return participant;
205         }
206         return null;
207     }
208
209     /**
210      * Check if a participant message applies to this participant handler.
211      *
212      * @param participantMsg the message to check
213      * @return true if it applies, false otherwise
214      */
215     public boolean appliesTo(ParticipantMessage participantMsg) {
216         return participantMsg.appliesTo(participantType, participantId);
217     }
218
219     /**
220      * Check if a participant message applies to this participant handler.
221      *
222      * @param participantMsg the message to check
223      * @return true if it applies, false otherwise
224      */
225     public boolean appliesTo(ParticipantAckMessage participantMsg) {
226         return participantMsg.appliesTo(participantType, participantId);
227     }
228
229     /**
230      * Method to send ParticipantRegister message to controlloop runtime.
231      */
232     public void sendParticipantRegister() {
233         var participantRegister = new ParticipantRegister();
234         participantRegister.setParticipantId(participantId);
235         participantRegister.setParticipantType(participantType);
236
237         publisher.sendParticipantRegister(participantRegister);
238     }
239
240     /**
241      * Handle a participantRegister Ack message.
242      *
243      * @param participantRegisterAckMsg the participantRegisterAck message
244      */
245     public void handleParticipantRegisterAck(ParticipantRegisterAck participantRegisterAckMsg) {
246         LOGGER.debug("ParticipantRegisterAck message received as responseTo {}",
247                 participantRegisterAckMsg.getResponseTo());
248         if (ParticipantHealthStatus.UNKNOWN.equals(this.healthStatus)) {
249             this.healthStatus = ParticipantHealthStatus.HEALTHY;
250         }
251
252         if (ParticipantState.UNKNOWN.equals(this.state)) {
253             this.state = ParticipantState.PASSIVE;
254         }
255         publisher.sendParticipantStatus(makeHeartbeat(false));
256     }
257
258     /**
259      * Method to send ParticipantDeregister message to controlloop runtime.
260      */
261     public void sendParticipantDeregister() {
262         var participantDeregister = new ParticipantDeregister();
263         participantDeregister.setParticipantId(participantId);
264         participantDeregister.setParticipantType(participantType);
265
266         publisher.sendParticipantDeregister(participantDeregister);
267     }
268
269     /**
270      * Handle a participantDeregister Ack message.
271      *
272      * @param participantDeregisterAckMsg the participantDeregisterAck message
273      */
274     public void handleParticipantDeregisterAck(ParticipantDeregisterAck participantDeregisterAckMsg) {
275         LOGGER.debug("ParticipantDeregisterAck message received as responseTo {}",
276                 participantDeregisterAckMsg.getResponseTo());
277     }
278
279     /**
280      * Handle a ParticipantUpdate message.
281      *
282      * @param participantUpdateMsg the ParticipantUpdate message
283      */
284     public void handleParticipantUpdate(ParticipantUpdate participantUpdateMsg) {
285         LOGGER.debug("ParticipantUpdate message received for participantId {}",
286                 participantUpdateMsg.getParticipantId());
287
288         if (!participantUpdateMsg.appliesTo(participantType, participantId)) {
289             return;
290         }
291
292         if (!participantUpdateMsg.getParticipantDefinitionUpdates().isEmpty()) {
293             // This message is to commission the controlloop
294             for (ParticipantDefinition participantDefinition : participantUpdateMsg.getParticipantDefinitionUpdates()) {
295                 if (participantDefinition.getParticipantType().equals(participantType)) {
296                     clElementDefsOnThisParticipant.clear();
297                     clElementDefsOnThisParticipant.addAll(participantDefinition.getControlLoopElementDefinitionList());
298                     break;
299                 }
300             }
301         } else {
302             // This message is to decommision the controlloop
303             clElementDefsOnThisParticipant.clear();
304         }
305         sendParticipantUpdateAck(participantUpdateMsg.getMessageId());
306     }
307
308     /**
309      * Method to send ParticipantUpdateAck message to controlloop runtime.
310      */
311     public void sendParticipantUpdateAck(UUID messageId) {
312         var participantUpdateAck = new ParticipantUpdateAck();
313         participantUpdateAck.setResponseTo(messageId);
314         participantUpdateAck.setMessage("Participant Update Ack message");
315         participantUpdateAck.setResult(true);
316         participantUpdateAck.setParticipantId(participantId);
317         participantUpdateAck.setParticipantType(participantType);
318
319         publisher.sendParticipantUpdateAck(participantUpdateAck);
320     }
321
322     /**
323      * Dispatch a heartbeat for this participant.
324      */
325     public void sendHeartbeat() {
326         publisher.sendHeartbeat(makeHeartbeat(false));
327     }
328
329     /**
330      * Method to send heartbeat to controlloop runtime.
331      */
332     public ParticipantStatus makeHeartbeat(boolean responseToParticipantStatusReq) {
333         this.participantStatistics.setState(state);
334         this.participantStatistics.setHealthStatus(healthStatus);
335         this.participantStatistics.setTimeStamp(Instant.now());
336
337         var heartbeat = new ParticipantStatus();
338         heartbeat.setParticipantId(participantId);
339         heartbeat.setParticipantStatistics(participantStatistics);
340         heartbeat.setParticipantType(participantType);
341         heartbeat.setHealthStatus(healthStatus);
342         heartbeat.setState(state);
343         heartbeat.setControlLoopInfoList(getControlLoopInfoList());
344
345         if (responseToParticipantStatusReq) {
346             ParticipantDefinition participantDefinition = new ParticipantDefinition();
347             participantDefinition.setParticipantId(participantId);
348             participantDefinition.setParticipantType(participantType);
349             participantDefinition.setControlLoopElementDefinitionList(clElementDefsOnThisParticipant);
350             heartbeat.setParticipantDefinitionUpdates(List.of(participantDefinition));
351         }
352
353         return heartbeat;
354     }
355
356     private List<ControlLoopInfo> getControlLoopInfoList() {
357         List<ControlLoopInfo> controlLoopInfoList = new ArrayList<>();
358         for (Map.Entry<ToscaConceptIdentifier, ControlLoop> entry : controlLoopHandler.getControlLoopMap().entrySet()) {
359             ControlLoopInfo clInfo = new ControlLoopInfo();
360             clInfo.setControlLoopId(entry.getKey());
361             ControlLoopStatistics clStatitistics = new ControlLoopStatistics();
362             clStatitistics.setControlLoopId(entry.getKey());
363             ClElementStatisticsList clElementStatisticsList = new ClElementStatisticsList();
364             clElementStatisticsList
365                     .setClElementStatistics(entry.getValue().getControlLoopElementStatisticsList(entry.getValue()));
366             clStatitistics.setClElementStatisticsList(clElementStatisticsList);
367             clInfo.setControlLoopStatistics(clStatitistics);
368             clInfo.setState(entry.getValue().getState());
369         }
370         return controlLoopInfoList;
371     }
372 }