5627bead2e513cacd848b4a7a58280bad6d44d4c
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2023-2025 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.acm.runtime.supervision;
22
23 import io.micrometer.core.annotation.Timed;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.UUID;
28 import java.util.function.UnaryOperator;
29 import java.util.stream.Collectors;
30 import lombok.AllArgsConstructor;
31 import org.apache.commons.collections4.MapUtils;
32 import org.onap.policy.clamp.acm.runtime.supervision.comm.ParticipantDeregisterAckPublisher;
33 import org.onap.policy.clamp.acm.runtime.supervision.comm.ParticipantRegisterAckPublisher;
34 import org.onap.policy.clamp.acm.runtime.supervision.comm.ParticipantSyncPublisher;
35 import org.onap.policy.clamp.models.acm.concepts.AcTypeState;
36 import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
37 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionDefinition;
38 import org.onap.policy.clamp.models.acm.concepts.NodeTemplateState;
39 import org.onap.policy.clamp.models.acm.concepts.Participant;
40 import org.onap.policy.clamp.models.acm.concepts.ParticipantReplica;
41 import org.onap.policy.clamp.models.acm.concepts.ParticipantState;
42 import org.onap.policy.clamp.models.acm.concepts.ParticipantSupportedElementType;
43 import org.onap.policy.clamp.models.acm.messages.kafka.participant.ParticipantDeregister;
44 import org.onap.policy.clamp.models.acm.messages.kafka.participant.ParticipantRegister;
45 import org.onap.policy.clamp.models.acm.messages.kafka.participant.ParticipantStatus;
46 import org.onap.policy.clamp.models.acm.persistence.provider.AcDefinitionProvider;
47 import org.onap.policy.clamp.models.acm.persistence.provider.AutomationCompositionProvider;
48 import org.onap.policy.clamp.models.acm.persistence.provider.MessageProvider;
49 import org.onap.policy.clamp.models.acm.persistence.provider.ParticipantProvider;
50 import org.onap.policy.clamp.models.acm.utils.TimestampHelper;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.stereotype.Component;
54
55 /**
56  * This class handles supervision of participant status.
57  */
58 @Component
59 @AllArgsConstructor
60 public class SupervisionParticipantHandler {
61     private static final Logger LOGGER = LoggerFactory.getLogger(SupervisionParticipantHandler.class);
62
63     private final ParticipantProvider participantProvider;
64     private final ParticipantRegisterAckPublisher participantRegisterAckPublisher;
65     private final ParticipantDeregisterAckPublisher participantDeregisterAckPublisher;
66     private final AutomationCompositionProvider automationCompositionProvider;
67     private final AcDefinitionProvider acDefinitionProvider;
68     private final ParticipantSyncPublisher participantSyncPublisher;
69     private final MessageProvider messageProvider;
70
71     /**
72      * Handle a ParticipantRegister message from a participant.
73      *
74      * @param participantRegisterMsg the ParticipantRegister message received from a participant
75      */
76     @Timed(value = "listener.participant_register", description = "PARTICIPANT_REGISTER messages received")
77     public void handleParticipantMessage(ParticipantRegister participantRegisterMsg) {
78         saveIfNotPresent(participantRegisterMsg.getReplicaId(),
79                 participantRegisterMsg.getParticipantId(),
80                 participantRegisterMsg.getParticipantSupportedElementType(), true);
81
82         participantRegisterAckPublisher.send(participantRegisterMsg.getMessageId(),
83                 participantRegisterMsg.getParticipantId(), participantRegisterMsg.getReplicaId());
84     }
85
86     /**
87      * Handle a ParticipantDeregister message from a participant.
88      *
89      * @param participantDeregisterMsg the ParticipantDeregister message received from a participant
90      */
91     @Timed(value = "listener.participant_deregister", description = "PARTICIPANT_DEREGISTER messages received")
92     public void handleParticipantMessage(ParticipantDeregister participantDeregisterMsg) {
93         var replicaId = participantDeregisterMsg.getReplicaId() != null
94                 ? participantDeregisterMsg.getReplicaId() : participantDeregisterMsg.getParticipantId();
95         var replicaOpt = participantProvider.findParticipantReplica(replicaId);
96         if (replicaOpt.isPresent()) {
97             participantProvider.deleteParticipantReplica(replicaId);
98         }
99
100         participantDeregisterAckPublisher.send(participantDeregisterMsg.getMessageId());
101     }
102
103     /**
104      * Handle a ParticipantStatus message from a participant.
105      *
106      * @param participantStatusMsg the ParticipantStatus message received from a participant
107      */
108     @MessageIntercept
109     @Timed(value = "listener.participant_status", description = "PARTICIPANT_STATUS messages received")
110     public void handleParticipantMessage(ParticipantStatus participantStatusMsg) {
111         saveIfNotPresent(participantStatusMsg.getReplicaId(), participantStatusMsg.getParticipantId(),
112                 participantStatusMsg.getParticipantSupportedElementType(), false);
113
114         if (!participantStatusMsg.getAutomationCompositionInfoList().isEmpty()) {
115             messageProvider.saveInstanceOutProperties(participantStatusMsg);
116         }
117         if (!participantStatusMsg.getParticipantDefinitionUpdates().isEmpty()
118                 && participantStatusMsg.getCompositionId() != null) {
119             var acDefinition = acDefinitionProvider.findAcDefinition(participantStatusMsg.getCompositionId());
120             if (acDefinition.isPresent()) {
121                 var map = acDefinition.get().getElementStateMap()
122                         .values().stream().collect(Collectors.toMap(NodeTemplateState::getNodeTemplateId,
123                                 UnaryOperator.identity()));
124                 messageProvider.saveCompositionOutProperties(participantStatusMsg, map);
125             } else {
126                 LOGGER.error("Not valid ParticipantStatus message");
127             }
128         }
129     }
130
131     private void saveIfNotPresent(UUID msgReplicaId, UUID participantId,
132             List<ParticipantSupportedElementType> participantSupportedElementType, boolean registration) {
133         var replicaId = msgReplicaId != null ? msgReplicaId : participantId;
134         var replicaOpt = participantProvider.findParticipantReplica(replicaId);
135         if (replicaOpt.isPresent()) {
136             var replica = replicaOpt.get();
137             checkOnline(replica);
138         } else {
139             var participant = getParticipant(participantId, listToMap(participantSupportedElementType));
140             participant.getReplicas().put(replicaId, createReplica(replicaId));
141             participantProvider.saveParticipant(participant);
142         }
143         if (registration) {
144             handleRestart(participantId, replicaId);
145         }
146     }
147
148     private Participant getParticipant(UUID participantId,
149             Map<UUID, ParticipantSupportedElementType> participantSupportedElementType) {
150         var participantOpt = participantProvider.findParticipant(participantId);
151         return participantOpt.orElseGet(() -> createParticipant(participantId, participantSupportedElementType));
152     }
153
154     private ParticipantReplica createReplica(UUID replicaId) {
155         var replica = new ParticipantReplica();
156         replica.setReplicaId(replicaId);
157         replica.setParticipantState(ParticipantState.ON_LINE);
158         replica.setLastMsg(TimestampHelper.now());
159         return replica;
160
161     }
162
163     private void checkOnline(ParticipantReplica replica) {
164         if (ParticipantState.OFF_LINE.equals(replica.getParticipantState())) {
165             replica.setParticipantState(ParticipantState.ON_LINE);
166         }
167         replica.setLastMsg(TimestampHelper.now());
168         participantProvider.saveParticipantReplica(replica);
169     }
170
171     private void handleRestart(UUID participantId, UUID replicaId) {
172         var compositionIds = participantProvider.getCompositionIds(participantId);
173         for (var compositionId : compositionIds) {
174             var acDefinition = acDefinitionProvider.getAcDefinition(compositionId);
175             LOGGER.debug("Scan Composition {} for restart", acDefinition.getCompositionId());
176             handleSyncRestart(participantId, replicaId, acDefinition);
177         }
178     }
179
180     private void handleSyncRestart(final UUID participantId, UUID replicaId,
181             AutomationCompositionDefinition acDefinition) {
182         if (AcTypeState.COMMISSIONED.equals(acDefinition.getState())) {
183             LOGGER.debug("Composition {} COMMISSIONED", acDefinition.getCompositionId());
184             return;
185         }
186         LOGGER.debug("Composition to be send in Restart message {}", acDefinition.getCompositionId());
187         var automationCompositionList =
188                 automationCompositionProvider.getAcInstancesByCompositionId(acDefinition.getCompositionId());
189         var automationCompositions = automationCompositionList.stream()
190                 .filter(ac -> isAcToBeSyncRestarted(participantId, ac)).toList();
191         participantSyncPublisher.sendRestartMsg(participantId, replicaId, acDefinition, automationCompositions);
192     }
193
194     private boolean isAcToBeSyncRestarted(UUID participantId, AutomationComposition automationComposition) {
195         for (var element : automationComposition.getElements().values()) {
196             if (participantId.equals(element.getParticipantId())) {
197                 return true;
198             }
199         }
200         return false;
201     }
202
203     private Participant createParticipant(UUID participantId,
204             Map<UUID, ParticipantSupportedElementType> participantSupportedElementType) {
205         var participant = new Participant();
206         participant.setParticipantId(participantId);
207         participant.setParticipantSupportedElementTypes(participantSupportedElementType);
208         return participant;
209     }
210
211     private Map<UUID, ParticipantSupportedElementType> listToMap(List<ParticipantSupportedElementType> elementList) {
212         Map<UUID, ParticipantSupportedElementType> map = new HashMap<>();
213         MapUtils.populateMap(map, elementList, ParticipantSupportedElementType::getId);
214         return map;
215     }
216 }