49ad6dab1f7a97eeb3a52e7e61076db66f78ae1b
[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.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65 import org.springframework.stereotype.Component;
66
67 /**
68  * This class is responsible for managing the state of a participant.
69  */
70 @Getter
71 @Component
72 public class ParticipantHandler {
73     private static final Logger LOGGER = LoggerFactory.getLogger(ParticipantHandler.class);
74
75     private final ToscaConceptIdentifier participantType;
76     private final ToscaConceptIdentifier participantId;
77     private final ControlLoopHandler controlLoopHandler;
78     private final ParticipantStatistics participantStatistics;
79     private final ParticipantMessagePublisher publisher;
80
81     @Setter
82     private ParticipantState state = ParticipantState.UNKNOWN;
83
84     @Setter
85     private ParticipantHealthStatus healthStatus = ParticipantHealthStatus.UNKNOWN;
86
87     private final List<ControlLoopElementDefinition> clElementDefsOnThisParticipant = new ArrayList<>();
88
89     private ToscaServiceTemplate toscaServiceTemplate = new ToscaServiceTemplate();
90
91     /**
92      * Constructor, set the participant ID and sender.
93      *
94      * @param parameters the parameters of the participant
95      * @param publisher the publisher for sending responses to messages
96      */
97     public ParticipantHandler(ParticipantParameters parameters, ParticipantMessagePublisher publisher,
98             ControlLoopHandler controlLoopHandler) {
99         this.participantType = parameters.getIntermediaryParameters().getParticipantType();
100         this.participantId = parameters.getIntermediaryParameters().getParticipantId();
101         this.publisher = publisher;
102         this.controlLoopHandler = controlLoopHandler;
103         this.participantStatistics = new ParticipantStatistics();
104         this.participantStatistics.setParticipantId(participantId);
105         this.participantStatistics.setState(state);
106         this.participantStatistics.setHealthStatus(healthStatus);
107         this.participantStatistics.setTimeStamp(Instant.now());
108     }
109
110     /**
111      * Method which handles a participant health check event from clamp.
112      *
113      * @param participantStatusReqMsg participant participantStatusReq message
114      */
115     public void handleParticipantStatusReq(final ParticipantStatusReq participantStatusReqMsg) {
116         var controlLoops = controlLoopHandler.getControlLoops();
117         for (ControlLoopElementListener clElementListener : controlLoopHandler.getListeners()) {
118             updateClElementStatistics(controlLoops, clElementListener);
119         }
120
121         var participantStatus = makeHeartbeat(true);
122         publisher.sendParticipantStatus(participantStatus);
123     }
124
125     /**
126      * Update ControlLoopElement statistics. The control loop elements listening will be
127      * notified to retrieve statistics from respective controlloop elements, and controlloopelements
128      * data on the handler will be updated.
129      *
130      * @param controlLoops the control loops
131      * @param clElementListener control loop element listener
132      */
133     private void updateClElementStatistics(ControlLoops controlLoops, ControlLoopElementListener clElementListener) {
134         for (ControlLoop controlLoop : controlLoops.getControlLoopList()) {
135             for (ControlLoopElement element : controlLoop.getElements().values()) {
136                 try {
137                     clElementListener.handleStatistics(element.getId());
138                 } catch (PfModelException e) {
139                     LOGGER.debug("Getting statistics for Control loop element failed for element ID {}",
140                             element.getId(), e);
141                 }
142             }
143         }
144     }
145
146     /**
147      * Handle a control loop update message.
148      *
149      * @param updateMsg the update message
150      */
151     public void handleControlLoopUpdate(ControlLoopUpdate updateMsg) {
152         controlLoopHandler.handleControlLoopUpdate(updateMsg, clElementDefsOnThisParticipant);
153     }
154
155     /**
156      * Handle a control loop state change message.
157      *
158      * @param stateChangeMsg the state change message
159      */
160     public void handleControlLoopStateChange(ControlLoopStateChange stateChangeMsg) {
161         controlLoopHandler.handleControlLoopStateChange(stateChangeMsg);
162     }
163
164     private void handleStateChange(ParticipantState newParticipantState, ParticipantUpdateAck response) {
165         if (state.equals(newParticipantState)) {
166             response.setResult(false);
167             response.setMessage("Participant already in state " + newParticipantState);
168         } else {
169             response.setResult(true);
170             response.setMessage("Participant state changed from " + state + " to " + newParticipantState);
171             state = newParticipantState;
172         }
173     }
174
175     /**
176      * Method to update participant state.
177      *
178      * @param definition participant definition
179      * @param participantState participant state
180      * @return the participant
181      */
182     public Participant updateParticipantState(ToscaConceptIdentifier definition, ParticipantState participantState) {
183         if (!Objects.equals(definition, participantId)) {
184             LOGGER.debug("No participant with this ID {}", definition.getName());
185             return null;
186         }
187
188         var participantUpdateAck = new ParticipantUpdateAck();
189         handleStateChange(participantState, participantUpdateAck);
190         publisher.sendParticipantUpdateAck(participantUpdateAck);
191         return getParticipant(definition.getName(), definition.getVersion());
192     }
193
194     /**
195      * Get participants as a {@link Participant} class.
196      *
197      * @param name the participant name to get
198      * @param version the version of the participant to get
199      * @return the participant
200      */
201     public Participant getParticipant(String name, String version) {
202         if (participantId.getName().equals(name)) {
203             var participant = new Participant();
204             participant.setDefinition(participantId);
205             participant.setParticipantState(state);
206             participant.setHealthStatus(healthStatus);
207             return participant;
208         }
209         return null;
210     }
211
212     /**
213      * Check if a participant message applies to this participant handler.
214      *
215      * @param participantMsg the message to check
216      * @return true if it applies, false otherwise
217      */
218     public boolean appliesTo(ParticipantMessage participantMsg) {
219         return participantMsg.appliesTo(participantType, participantId);
220     }
221
222     /**
223      * Check if a participant message applies to this participant handler.
224      *
225      * @param participantMsg the message to check
226      * @return true if it applies, false otherwise
227      */
228     public boolean appliesTo(ParticipantAckMessage participantMsg) {
229         return participantMsg.appliesTo(participantType, participantId);
230     }
231
232     /**
233      * Method to send ParticipantRegister message to controlloop runtime.
234      */
235     public void sendParticipantRegister() {
236         var participantRegister = new ParticipantRegister();
237         participantRegister.setParticipantId(participantId);
238         participantRegister.setParticipantType(participantType);
239
240         publisher.sendParticipantRegister(participantRegister);
241     }
242
243     /**
244      * Handle a participantRegister Ack message.
245      *
246      * @param participantRegisterAckMsg the participantRegisterAck message
247      */
248     public void handleParticipantRegisterAck(ParticipantRegisterAck participantRegisterAckMsg) {
249         LOGGER.debug("ParticipantRegisterAck message received as responseTo {}",
250                 participantRegisterAckMsg.getResponseTo());
251         if (ParticipantHealthStatus.UNKNOWN.equals(this.healthStatus)) {
252             this.healthStatus = ParticipantHealthStatus.HEALTHY;
253         }
254
255         if (ParticipantState.UNKNOWN.equals(this.state)) {
256             this.state = ParticipantState.PASSIVE;
257         }
258         publisher.sendParticipantStatus(makeHeartbeat(false));
259     }
260
261     /**
262      * Method to send ParticipantDeregister message to controlloop runtime.
263      */
264     public void sendParticipantDeregister() {
265         var participantDeregister = new ParticipantDeregister();
266         participantDeregister.setParticipantId(participantId);
267         participantDeregister.setParticipantType(participantType);
268
269         publisher.sendParticipantDeregister(participantDeregister);
270     }
271
272     /**
273      * Handle a participantDeregister Ack message.
274      *
275      * @param participantDeregisterAckMsg the participantDeregisterAck message
276      */
277     public void handleParticipantDeregisterAck(ParticipantDeregisterAck participantDeregisterAckMsg) {
278         LOGGER.debug("ParticipantDeregisterAck message received as responseTo {}",
279                 participantDeregisterAckMsg.getResponseTo());
280     }
281
282     /**
283      * Handle a ParticipantUpdate message.
284      *
285      * @param participantUpdateMsg the ParticipantUpdate message
286      */
287     public void handleParticipantUpdate(ParticipantUpdate participantUpdateMsg) {
288         LOGGER.debug("ParticipantUpdate message received for participantId {}",
289                 participantUpdateMsg.getParticipantId());
290
291         if (!participantUpdateMsg.appliesTo(participantType, participantId)) {
292             return;
293         }
294
295         toscaServiceTemplate = participantUpdateMsg.getToscaServiceTemplate();
296         if (toscaServiceTemplate != null) {
297             // This message is to commission the controlloop
298             for (ParticipantDefinition participantDefinition : participantUpdateMsg.getParticipantDefinitionUpdates()) {
299                 if (participantDefinition.getParticipantId().equals(participantType)) {
300                     clElementDefsOnThisParticipant.clear();
301                     clElementDefsOnThisParticipant.addAll(participantDefinition.getControlLoopElementDefinitionList());
302                     break;
303                 }
304             }
305         } else {
306             // This message is to decommision the controlloop
307             clElementDefsOnThisParticipant.clear();
308         }
309         sendParticipantUpdateAck(participantUpdateMsg.getMessageId());
310     }
311
312     /**
313      * Method to send ParticipantUpdateAck message to controlloop runtime.
314      */
315     public void sendParticipantUpdateAck(UUID messageId) {
316         var participantUpdateAck = new ParticipantUpdateAck();
317         participantUpdateAck.setResponseTo(messageId);
318         participantUpdateAck.setMessage("Participant Update Ack message");
319         participantUpdateAck.setResult(true);
320         participantUpdateAck.setParticipantId(participantId);
321         participantUpdateAck.setParticipantType(participantType);
322
323         publisher.sendParticipantUpdateAck(participantUpdateAck);
324     }
325
326     /**
327      * Dispatch a heartbeat for this participant.
328      */
329     public void sendHeartbeat() {
330         publisher.sendHeartbeat(makeHeartbeat(false));
331     }
332
333     /**
334      * Method to send heartbeat to controlloop runtime.
335      */
336     public ParticipantStatus makeHeartbeat(boolean responseToParticipantStatusReq) {
337         this.participantStatistics.setState(state);
338         this.participantStatistics.setHealthStatus(healthStatus);
339         this.participantStatistics.setTimeStamp(Instant.now());
340
341         var heartbeat = new ParticipantStatus();
342         heartbeat.setParticipantId(participantId);
343         heartbeat.setParticipantStatistics(participantStatistics);
344         heartbeat.setParticipantType(participantType);
345         heartbeat.setHealthStatus(healthStatus);
346         heartbeat.setState(state);
347         heartbeat.setControlLoopInfoList(getControlLoopInfoList());
348
349         if (responseToParticipantStatusReq) {
350             List<ParticipantDefinition> participantDefinitionUpdates = new ArrayList<>();
351             ParticipantDefinition participantDefinition = new ParticipantDefinition();
352             participantDefinition.setParticipantId(participantId);
353             participantDefinition.setControlLoopElementDefinitionList(clElementDefsOnThisParticipant);
354             participantDefinitionUpdates.add(participantDefinition);
355             heartbeat.setParticipantDefinitionUpdates(participantDefinitionUpdates);
356         }
357
358         return heartbeat;
359     }
360
361     private List<ControlLoopInfo> getControlLoopInfoList() {
362         List<ControlLoopInfo> controlLoopInfoList = new ArrayList<>();
363         for (Map.Entry<ToscaConceptIdentifier, ControlLoop> entry : controlLoopHandler.getControlLoopMap().entrySet()) {
364             ControlLoopInfo clInfo = new ControlLoopInfo();
365             clInfo.setControlLoopId(entry.getKey());
366             ControlLoopStatistics clStatitistics = new ControlLoopStatistics();
367             clStatitistics.setControlLoopId(entry.getKey());
368             ClElementStatisticsList clElementStatisticsList = new ClElementStatisticsList();
369             clElementStatisticsList
370                     .setClElementStatistics(entry.getValue().getControlLoopElementStatisticsList(entry.getValue()));
371             clStatitistics.setClElementStatisticsList(clElementStatisticsList);
372             clInfo.setControlLoopStatistics(clStatitistics);
373             clInfo.setState(entry.getValue().getState());
374         }
375         return controlLoopInfoList;
376     }
377 }