fa02f3dcf71137cb8fd0fafd7107b79573d8f2d9
[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.acm.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.acm.participant.intermediary.api.AutomationCompositionElementListener;
36 import org.onap.policy.clamp.acm.participant.intermediary.comm.ParticipantMessagePublisher;
37 import org.onap.policy.clamp.acm.participant.intermediary.parameters.ParticipantParameters;
38 import org.onap.policy.clamp.models.acm.concepts.AcElementStatisticsList;
39 import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
40 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
41 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElementDefinition;
42 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionInfo;
43 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionStatistics;
44 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositions;
45 import org.onap.policy.clamp.models.acm.concepts.Participant;
46 import org.onap.policy.clamp.models.acm.concepts.ParticipantDefinition;
47 import org.onap.policy.clamp.models.acm.concepts.ParticipantHealthStatus;
48 import org.onap.policy.clamp.models.acm.concepts.ParticipantState;
49 import org.onap.policy.clamp.models.acm.concepts.ParticipantStatistics;
50 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.AutomationCompositionStateChange;
51 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.AutomationCompositionUpdate;
52 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantAckMessage;
53 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantDeregister;
54 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantDeregisterAck;
55 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantMessage;
56 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantRegister;
57 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantRegisterAck;
58 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantStatus;
59 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantStatusReq;
60 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantUpdate;
61 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.ParticipantUpdateAck;
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 AutomationCompositionHandler automationCompositionHandler;
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<AutomationCompositionElementDefinition> acElementDefsOnThisParticipant = 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         AutomationCompositionHandler automationCompositionHandler) {
102         this.participantType = parameters.getIntermediaryParameters().getParticipantType();
103         this.participantId = parameters.getIntermediaryParameters().getParticipantId();
104         this.publisher = publisher;
105         this.automationCompositionHandler = automationCompositionHandler;
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 AutomationCompositionElement statistics. The automation composition elements listening will be
125      * notified to retrieve statistics from respective automation composition elements, and automation
126      * compositionelements
127      * data on the handler will be updated.
128      *
129      * @param automationCompositions the automation compositions
130      * @param acElementListener automation composition element listener
131      */
132     private void updateAcElementStatistics(AutomationCompositions automationCompositions,
133         AutomationCompositionElementListener acElementListener) {
134         for (AutomationComposition automationComposition : automationCompositions.getAutomationCompositionList()) {
135             for (AutomationCompositionElement element : automationComposition.getElements().values()) {
136                 try {
137                     acElementListener.handleStatistics(element.getId());
138                 } catch (PfModelException e) {
139                     LOGGER.debug("Getting statistics for automation composition element failed for element ID {}",
140                         element.getId(), e);
141                 }
142             }
143         }
144     }
145
146     /**
147      * Handle a automation composition update message.
148      *
149      * @param updateMsg the update message
150      */
151     public void handleAutomationCompositionUpdate(AutomationCompositionUpdate updateMsg) {
152         automationCompositionHandler.handleAutomationCompositionUpdate(updateMsg, acElementDefsOnThisParticipant);
153     }
154
155     /**
156      * Handle a automation composition state change message.
157      *
158      * @param stateChangeMsg the state change message
159      */
160     public void handleAutomationCompositionStateChange(AutomationCompositionStateChange stateChangeMsg) {
161         automationCompositionHandler.handleAutomationCompositionStateChange(stateChangeMsg,
162             acElementDefsOnThisParticipant);
163     }
164
165     private void handleStateChange(ParticipantState newParticipantState, ParticipantUpdateAck response) {
166         if (state.equals(newParticipantState)) {
167             response.setResult(false);
168             response.setMessage("Participant already in state " + newParticipantState);
169         } else {
170             response.setResult(true);
171             response.setMessage("Participant state changed from " + state + " to " + newParticipantState);
172             state = newParticipantState;
173         }
174     }
175
176     /**
177      * Method to update participant state.
178      *
179      * @param definition participant definition
180      * @param participantState participant state
181      * @return the participant
182      */
183     public Participant updateParticipantState(ToscaConceptIdentifier definition, ParticipantState participantState) {
184         if (!Objects.equals(definition, participantId)) {
185             LOGGER.debug("No participant with this ID {}", definition.getName());
186             return null;
187         }
188
189         var participantUpdateAck = new ParticipantUpdateAck();
190         handleStateChange(participantState, participantUpdateAck);
191         publisher.sendParticipantUpdateAck(participantUpdateAck);
192         return getParticipant(definition.getName(), definition.getVersion());
193     }
194
195     /**
196      * Method to update participant statistics.
197      *
198      * @param statistics participant statistics
199      */
200     public void updateParticipantStatistics(ParticipantStatistics statistics) {
201         participantStatistics.setState(statistics.getState());
202         participantStatistics.setHealthStatus(statistics.getHealthStatus());
203         participantStatistics.setTimeStamp(statistics.getTimeStamp());
204         participantStatistics.setAverageExecutionTime(statistics.getAverageExecutionTime());
205         participantStatistics.setEventCount(statistics.getEventCount());
206     }
207
208     /**
209      * Get participants as a {@link Participant} class.
210      *
211      * @param name the participant name to get
212      * @param version the version of the participant to get
213      * @return the participant
214      */
215     public Participant getParticipant(String name, String version) {
216         if (participantId.getName().equals(name)) {
217             var participant = new Participant();
218             participant.setDefinition(participantId);
219             participant.setParticipantState(state);
220             participant.setHealthStatus(healthStatus);
221             return participant;
222         }
223         return null;
224     }
225
226     /**
227      * Get common properties of a automation composition element.
228      *
229      * @param acElementDef the automation composition element definition
230      * @return the common properties
231      */
232     public Map<String, ToscaProperty> getAcElementDefinitionCommonProperties(ToscaConceptIdentifier acElementDef) {
233         Map<String, ToscaProperty> commonPropertiesMap = new HashMap<>();
234         acElementDefsOnThisParticipant.stream().forEach(definition -> {
235             if (definition.getAcElementDefinitionId().equals(acElementDef)) {
236                 commonPropertiesMap.putAll(definition.getCommonPropertiesMap());
237             }
238         });
239         return commonPropertiesMap;
240     }
241
242     /**
243      * Check if a participant message applies to this participant handler.
244      *
245      * @param participantMsg the message to check
246      * @return true if it applies, false otherwise
247      */
248     public boolean appliesTo(ParticipantMessage participantMsg) {
249         return participantMsg.appliesTo(participantType, participantId);
250     }
251
252     /**
253      * Check if a participant message applies to this participant handler.
254      *
255      * @param participantMsg the message to check
256      * @return true if it applies, false otherwise
257      */
258     public boolean appliesTo(ParticipantAckMessage participantMsg) {
259         return participantMsg.appliesTo(participantType, participantId);
260     }
261
262     /**
263      * Method to send ParticipantRegister message to automation composition runtime.
264      */
265     public void sendParticipantRegister() {
266         var participantRegister = new ParticipantRegister();
267         participantRegister.setParticipantId(participantId);
268         participantRegister.setParticipantType(participantType);
269
270         publisher.sendParticipantRegister(participantRegister);
271     }
272
273     /**
274      * Handle a participantRegister Ack message.
275      *
276      * @param participantRegisterAckMsg the participantRegisterAck message
277      */
278     public void handleParticipantRegisterAck(ParticipantRegisterAck participantRegisterAckMsg) {
279         LOGGER.debug("ParticipantRegisterAck message received as responseTo {}",
280             participantRegisterAckMsg.getResponseTo());
281         statusToPassive();
282         publisher.sendParticipantStatus(makeHeartbeat(false));
283     }
284
285     private void statusToPassive() {
286         if (ParticipantHealthStatus.UNKNOWN.equals(this.healthStatus)) {
287             this.healthStatus = ParticipantHealthStatus.HEALTHY;
288         }
289
290         if (ParticipantState.UNKNOWN.equals(this.state) || ParticipantState.TERMINATED.equals(this.state)) {
291             this.state = ParticipantState.PASSIVE;
292         }
293
294     }
295
296     /**
297      * Method to send ParticipantDeregister message to automation composition runtime.
298      */
299     public void sendParticipantDeregister() {
300         var participantDeregister = new ParticipantDeregister();
301         participantDeregister.setParticipantId(participantId);
302         participantDeregister.setParticipantType(participantType);
303
304         publisher.sendParticipantDeregister(participantDeregister);
305     }
306
307     /**
308      * Handle a participantDeregister Ack message.
309      *
310      * @param participantDeregisterAckMsg the participantDeregisterAck message
311      */
312     public void handleParticipantDeregisterAck(ParticipantDeregisterAck participantDeregisterAckMsg) {
313         LOGGER.debug("ParticipantDeregisterAck message received as responseTo {}",
314             participantDeregisterAckMsg.getResponseTo());
315     }
316
317     /**
318      * Handle a ParticipantUpdate message.
319      *
320      * @param participantUpdateMsg the ParticipantUpdate message
321      */
322     public void handleParticipantUpdate(ParticipantUpdate participantUpdateMsg) {
323         LOGGER.debug("ParticipantUpdate message received for participantId {}",
324             participantUpdateMsg.getParticipantId());
325
326         if (!participantUpdateMsg.getParticipantDefinitionUpdates().isEmpty()) {
327             statusToPassive();
328             // This message is to commission the automation composition
329             for (ParticipantDefinition participantDefinition : participantUpdateMsg.getParticipantDefinitionUpdates()) {
330                 if (participantDefinition.getParticipantType().equals(participantType)) {
331                     acElementDefsOnThisParticipant
332                         .addAll(participantDefinition.getAutomationCompositionElementDefinitionList());
333                     break;
334                 }
335             }
336         } else {
337             // This message is to decommission the automation composition
338             acElementDefsOnThisParticipant.clear();
339             this.state = ParticipantState.TERMINATED;
340         }
341         sendParticipantUpdateAck(participantUpdateMsg.getMessageId());
342     }
343
344     /**
345      * Method to send ParticipantUpdateAck message to automation composition runtime.
346      */
347     public void sendParticipantUpdateAck(UUID messageId) {
348         var participantUpdateAck = new ParticipantUpdateAck();
349         participantUpdateAck.setResponseTo(messageId);
350         participantUpdateAck.setMessage("Participant Update Ack message");
351         participantUpdateAck.setResult(true);
352         participantUpdateAck.setParticipantId(participantId);
353         participantUpdateAck.setParticipantType(participantType);
354         participantUpdateAck.setState(state);
355         publisher.sendParticipantUpdateAck(participantUpdateAck);
356     }
357
358     /**
359      * Dispatch a heartbeat for this participant.
360      */
361     public void sendHeartbeat() {
362         publisher.sendHeartbeat(makeHeartbeat(false));
363     }
364
365     /**
366      * Method to send heartbeat to automation composition runtime.
367      */
368     public ParticipantStatus makeHeartbeat(boolean responseToParticipantStatusReq) {
369         if (!responseToParticipantStatusReq) {
370             var automationCompositions = automationCompositionHandler.getAutomationCompositions();
371             for (var acElementListener : automationCompositionHandler.getListeners()) {
372                 updateAcElementStatistics(automationCompositions, acElementListener);
373             }
374         }
375         this.participantStatistics.setState(state);
376         this.participantStatistics.setHealthStatus(healthStatus);
377         this.participantStatistics.setTimeStamp(Instant.now());
378
379         var heartbeat = new ParticipantStatus();
380         heartbeat.setParticipantId(participantId);
381         heartbeat.setParticipantStatistics(participantStatistics);
382         heartbeat.setParticipantType(participantType);
383         heartbeat.setHealthStatus(healthStatus);
384         heartbeat.setState(state);
385         heartbeat.setAutomationCompositionInfoList(getAutomationCompositionInfoList());
386
387         if (responseToParticipantStatusReq) {
388             ParticipantDefinition participantDefinition = new ParticipantDefinition();
389             participantDefinition.setParticipantId(participantId);
390             participantDefinition.setParticipantType(participantType);
391             participantDefinition.setAutomationCompositionElementDefinitionList(acElementDefsOnThisParticipant);
392             heartbeat.setParticipantDefinitionUpdates(List.of(participantDefinition));
393         }
394
395         return heartbeat;
396     }
397
398     private List<AutomationCompositionInfo> getAutomationCompositionInfoList() {
399         List<AutomationCompositionInfo> automationCompositionInfoList = new ArrayList<>();
400         for (var entry : automationCompositionHandler.getAutomationCompositionMap().entrySet()) {
401             var acInfo = new AutomationCompositionInfo();
402             acInfo.setAutomationCompositionId(entry.getKey());
403             var acStatitistics = new AutomationCompositionStatistics();
404             acStatitistics.setAutomationCompositionId(entry.getKey());
405             var acElementStatisticsList = new AcElementStatisticsList();
406             acElementStatisticsList.setAcElementStatistics(entry.getValue().getElements().values().stream()
407                 .map(AutomationCompositionElement::getAcElementStatistics).filter(Objects::nonNull)
408                 .collect(Collectors.toList()));
409             acStatitistics.setAcElementStatisticsList(acElementStatisticsList);
410             acInfo.setAutomationCompositionStatistics(acStatitistics);
411             acInfo.setState(entry.getValue().getState());
412             automationCompositionInfoList.add(acInfo);
413         }
414         return automationCompositionInfoList;
415     }
416 }