d7537e3d82469f233118e30e7deff96f918b9ae2
[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      * Get participants as a {@link Participant} class.
194      *
195      * @param name the participant name to get
196      * @param version the version of the participant to get
197      * @return the participant
198      */
199     public Participant getParticipant(String name, String version) {
200         if (participantId.getName().equals(name)) {
201             var participant = new Participant();
202             participant.setDefinition(participantId);
203             participant.setParticipantState(state);
204             participant.setHealthStatus(healthStatus);
205             return participant;
206         }
207         return null;
208     }
209
210     /**
211      * Get common properties of a controlloopelement.
212      *
213      * @param clElementDef the control loop element definition
214      * @return the common properties
215      */
216     public Map<String, ToscaProperty> getClElementDefinitionCommonProperties(ToscaConceptIdentifier clElementDef) {
217         Map<String, ToscaProperty> commonPropertiesMap = new HashMap<>();
218         clElementDefsOnThisParticipant.stream().forEach(definition -> {
219             if (definition.getClElementDefinitionId().equals(clElementDef)) {
220                 commonPropertiesMap.putAll(definition.getCommonPropertiesMap());
221             }
222         });
223         return commonPropertiesMap;
224     }
225
226     /**
227      * Check if a participant message applies to this participant handler.
228      *
229      * @param participantMsg the message to check
230      * @return true if it applies, false otherwise
231      */
232     public boolean appliesTo(ParticipantMessage participantMsg) {
233         return participantMsg.appliesTo(participantType, participantId);
234     }
235
236     /**
237      * Check if a participant message applies to this participant handler.
238      *
239      * @param participantMsg the message to check
240      * @return true if it applies, false otherwise
241      */
242     public boolean appliesTo(ParticipantAckMessage participantMsg) {
243         return participantMsg.appliesTo(participantType, participantId);
244     }
245
246     /**
247      * Method to send ParticipantRegister message to controlloop runtime.
248      */
249     public void sendParticipantRegister() {
250         var participantRegister = new ParticipantRegister();
251         participantRegister.setParticipantId(participantId);
252         participantRegister.setParticipantType(participantType);
253
254         publisher.sendParticipantRegister(participantRegister);
255     }
256
257     /**
258      * Handle a participantRegister Ack message.
259      *
260      * @param participantRegisterAckMsg the participantRegisterAck message
261      */
262     public void handleParticipantRegisterAck(ParticipantRegisterAck participantRegisterAckMsg) {
263         LOGGER.debug("ParticipantRegisterAck message received as responseTo {}",
264                 participantRegisterAckMsg.getResponseTo());
265         statusToPassive();
266         publisher.sendParticipantStatus(makeHeartbeat(false));
267     }
268
269     private void statusToPassive() {
270         if (ParticipantHealthStatus.UNKNOWN.equals(this.healthStatus)) {
271             this.healthStatus = ParticipantHealthStatus.HEALTHY;
272         }
273
274         if (ParticipantState.UNKNOWN.equals(this.state) || ParticipantState.TERMINATED.equals(this.state)) {
275             this.state = ParticipantState.PASSIVE;
276         }
277
278     }
279
280     /**
281      * Method to send ParticipantDeregister message to controlloop runtime.
282      */
283     public void sendParticipantDeregister() {
284         var participantDeregister = new ParticipantDeregister();
285         participantDeregister.setParticipantId(participantId);
286         participantDeregister.setParticipantType(participantType);
287
288         publisher.sendParticipantDeregister(participantDeregister);
289     }
290
291     /**
292      * Handle a participantDeregister Ack message.
293      *
294      * @param participantDeregisterAckMsg the participantDeregisterAck message
295      */
296     public void handleParticipantDeregisterAck(ParticipantDeregisterAck participantDeregisterAckMsg) {
297         LOGGER.debug("ParticipantDeregisterAck message received as responseTo {}",
298                 participantDeregisterAckMsg.getResponseTo());
299     }
300
301     /**
302      * Handle a ParticipantUpdate message.
303      *
304      * @param participantUpdateMsg the ParticipantUpdate message
305      */
306     public void handleParticipantUpdate(ParticipantUpdate participantUpdateMsg) {
307         LOGGER.debug("ParticipantUpdate message received for participantId {}",
308                 participantUpdateMsg.getParticipantId());
309
310         if (!participantUpdateMsg.getParticipantDefinitionUpdates().isEmpty()) {
311             statusToPassive();
312             // This message is to commission the controlloop
313             for (ParticipantDefinition participantDefinition : participantUpdateMsg.getParticipantDefinitionUpdates()) {
314                 if (participantDefinition.getParticipantType().equals(participantType)) {
315                     clElementDefsOnThisParticipant.addAll(participantDefinition.getControlLoopElementDefinitionList());
316                     break;
317                 }
318             }
319         } else {
320             // This message is to decommission the controlloop
321             clElementDefsOnThisParticipant.clear();
322             this.state = ParticipantState.TERMINATED;
323         }
324         sendParticipantUpdateAck(participantUpdateMsg.getMessageId());
325     }
326
327     /**
328      * Method to send ParticipantUpdateAck message to controlloop runtime.
329      */
330     public void sendParticipantUpdateAck(UUID messageId) {
331         var participantUpdateAck = new ParticipantUpdateAck();
332         participantUpdateAck.setResponseTo(messageId);
333         participantUpdateAck.setMessage("Participant Update Ack message");
334         participantUpdateAck.setResult(true);
335         participantUpdateAck.setParticipantId(participantId);
336         participantUpdateAck.setParticipantType(participantType);
337         participantUpdateAck.setState(state);
338         publisher.sendParticipantUpdateAck(participantUpdateAck);
339     }
340
341     /**
342      * Dispatch a heartbeat for this participant.
343      */
344     public void sendHeartbeat() {
345         publisher.sendHeartbeat(makeHeartbeat(false));
346     }
347
348     /**
349      * Method to send heartbeat to controlloop runtime.
350      */
351     public ParticipantStatus makeHeartbeat(boolean responseToParticipantStatusReq) {
352         if (!responseToParticipantStatusReq) {
353             var controlLoops = controlLoopHandler.getControlLoops();
354             for (var clElementListener : controlLoopHandler.getListeners()) {
355                 updateClElementStatistics(controlLoops, clElementListener);
356             }
357         }
358         this.participantStatistics.setState(state);
359         this.participantStatistics.setHealthStatus(healthStatus);
360         this.participantStatistics.setTimeStamp(Instant.now());
361
362         var heartbeat = new ParticipantStatus();
363         heartbeat.setParticipantId(participantId);
364         heartbeat.setParticipantStatistics(participantStatistics);
365         heartbeat.setParticipantType(participantType);
366         heartbeat.setHealthStatus(healthStatus);
367         heartbeat.setState(state);
368         heartbeat.setControlLoopInfoList(getControlLoopInfoList());
369
370         if (responseToParticipantStatusReq) {
371             ParticipantDefinition participantDefinition = new ParticipantDefinition();
372             participantDefinition.setParticipantId(participantId);
373             participantDefinition.setParticipantType(participantType);
374             participantDefinition.setControlLoopElementDefinitionList(clElementDefsOnThisParticipant);
375             heartbeat.setParticipantDefinitionUpdates(List.of(participantDefinition));
376         }
377
378         return heartbeat;
379     }
380
381     private List<ControlLoopInfo> getControlLoopInfoList() {
382         List<ControlLoopInfo> controlLoopInfoList = new ArrayList<>();
383         for (var entry : controlLoopHandler.getControlLoopMap().entrySet()) {
384             var clInfo = new ControlLoopInfo();
385             clInfo.setControlLoopId(entry.getKey());
386             var clStatitistics = new ControlLoopStatistics();
387             clStatitistics.setControlLoopId(entry.getKey());
388             var clElementStatisticsList = new ClElementStatisticsList();
389             clElementStatisticsList
390                     .setClElementStatistics(entry.getValue().getElements().values()
391                             .stream()
392                             .map(ControlLoopElement::getClElementStatistics)
393                             .filter(Objects::nonNull)
394                             .collect(Collectors.toList()));
395             clStatitistics.setClElementStatisticsList(clElementStatisticsList);
396             clInfo.setControlLoopStatistics(clStatitistics);
397             clInfo.setState(entry.getValue().getState());
398             controlLoopInfoList.add(clInfo);
399         }
400         return controlLoopInfoList;
401     }
402 }