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