CI: Add test rtdv3 GHA workflow
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / events / cmsubscription / CmSubscriptionNcmpInEventForwarder.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2023 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.cps.ncmp.api.impl.events.cmsubscription;
22
23 import com.hazelcast.map.IMap;
24 import io.cloudevents.CloudEvent;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Set;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.ScheduledExecutorService;
33 import java.util.concurrent.TimeUnit;
34 import java.util.stream.Collectors;
35 import lombok.RequiredArgsConstructor;
36 import lombok.extern.slf4j.Slf4j;
37 import org.onap.cps.ncmp.api.impl.config.embeddedcache.ForwardedSubscriptionEventCacheConfig;
38 import org.onap.cps.ncmp.api.impl.events.EventsPublisher;
39 import org.onap.cps.ncmp.api.impl.subscriptions.SubscriptionPersistence;
40 import org.onap.cps.ncmp.api.impl.subscriptions.SubscriptionStatus;
41 import org.onap.cps.ncmp.api.impl.utils.CmSubscriptionEventCloudMapper;
42 import org.onap.cps.ncmp.api.impl.utils.DmiServiceNameOrganizer;
43 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
44 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelSubscriptionEvent;
45 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
46 import org.onap.cps.ncmp.events.cmsubscription1_0_0.client_to_ncmp.CmSubscriptionNcmpInEvent;
47 import org.onap.cps.ncmp.events.cmsubscription1_0_0.dmi_to_ncmp.CmSubscriptionDmiOutEvent;
48 import org.onap.cps.ncmp.events.cmsubscription1_0_0.dmi_to_ncmp.Data;
49 import org.onap.cps.ncmp.events.cmsubscription1_0_0.ncmp_to_dmi.CmHandle;
50 import org.onap.cps.ncmp.events.cmsubscription1_0_0.ncmp_to_dmi.CmSubscriptionDmiInEvent;
51 import org.springframework.beans.factory.annotation.Value;
52 import org.springframework.stereotype.Component;
53
54
55 @Component
56 @Slf4j
57 @RequiredArgsConstructor
58 public class CmSubscriptionNcmpInEventForwarder {
59
60     private final InventoryPersistence inventoryPersistence;
61     private final EventsPublisher<CloudEvent> eventsPublisher;
62     private final IMap<String, Set<String>> forwardedSubscriptionEventCache;
63     private final CmSubscriptionNcmpOutEventPublisher cmSubscriptionNcmpOutEventPublisher;
64     private final CmSubscriptionNcmpInEventMapper cmSubscriptionNcmpInEventMapper;
65     private final CmSubscriptionEventCloudMapper cmSubscriptionEventCloudMapper;
66     private final CmSubscriptionNcmpInEventToCmSubscriptionDmiInEventMapper
67             cmSubscriptionNcmpInEventToCmSubscriptionDmiInEventMapper;
68     private final SubscriptionPersistence subscriptionPersistence;
69     private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
70     @Value("${app.ncmp.avc.subscription-forward-topic-prefix}")
71     private String dmiAvcSubscriptionTopicPrefix;
72
73     @Value("${ncmp.timers.subscription-forwarding.dmi-response-timeout-ms:30000}")
74     private int dmiResponseTimeoutInMs;
75
76     /**
77      * Forward subscription event.
78      *
79      * @param cmSubscriptionNcmpInEvent the event to be forwarded
80      */
81     public void forwardCreateSubscriptionEvent(final CmSubscriptionNcmpInEvent cmSubscriptionNcmpInEvent,
82             final String eventType) {
83         final List<String> cmHandleTargets = cmSubscriptionNcmpInEvent.getData().getPredicates().getTargets();
84         if (cmHandleTargets == null || cmHandleTargets.isEmpty() || cmHandleTargets.stream()
85                 .anyMatch(id -> (id).contains("*"))) {
86             throw new UnsupportedOperationException(
87                     "CMHandle targets are required. \"Wildcard\" operations are not yet supported");
88         }
89         final Collection<YangModelCmHandle> yangModelCmHandles =
90                 inventoryPersistence.getYangModelCmHandles(cmHandleTargets);
91         final Map<String, Map<String, Map<String, String>>> dmiPropertiesPerCmHandleIdPerServiceName =
92                 DmiServiceNameOrganizer.getDmiPropertiesPerCmHandleIdPerServiceName(yangModelCmHandles);
93         findDmisAndRespond(cmSubscriptionNcmpInEvent, eventType, cmHandleTargets,
94                 dmiPropertiesPerCmHandleIdPerServiceName);
95     }
96
97     private void findDmisAndRespond(final CmSubscriptionNcmpInEvent cmSubscriptionNcmpInEvent, final String eventType,
98             final List<String> cmHandleTargetsAsStrings,
99             final Map<String, Map<String, Map<String, String>>> dmiPropertiesPerCmHandleIdPerServiceName) {
100         final CmSubscriptionDmiOutEvent emptyCmSubscriptionDmiOutEvent =
101                 new CmSubscriptionDmiOutEvent().withData(new Data());
102         emptyCmSubscriptionDmiOutEvent.getData()
103                 .setSubscriptionName(cmSubscriptionNcmpInEvent.getData().getSubscription().getName());
104         emptyCmSubscriptionDmiOutEvent.getData()
105                 .setClientId(cmSubscriptionNcmpInEvent.getData().getSubscription().getClientID());
106         final List<String> cmHandlesThatExistsInDb =
107                 dmiPropertiesPerCmHandleIdPerServiceName.entrySet().stream().map(Map.Entry::getValue).map(Map::keySet)
108                         .flatMap(Set::stream).collect(Collectors.toList());
109
110         final List<String> targetCmHandlesDoesNotExistInDb = new ArrayList<>(cmHandleTargetsAsStrings);
111         targetCmHandlesDoesNotExistInDb.removeAll(cmHandlesThatExistsInDb);
112
113         final Set<String> dmisToRespond = new HashSet<>(dmiPropertiesPerCmHandleIdPerServiceName.keySet());
114
115         if (dmisToRespond.isEmpty() || !targetCmHandlesDoesNotExistInDb.isEmpty()) {
116             updatesCmHandlesToRejectedAndPersistSubscriptionEvent(cmSubscriptionNcmpInEvent,
117                     targetCmHandlesDoesNotExistInDb);
118         }
119         if (dmisToRespond.isEmpty()) {
120             cmSubscriptionNcmpOutEventPublisher.sendResponse(emptyCmSubscriptionDmiOutEvent,
121                     "subscriptionCreatedStatus");
122         } else {
123             startResponseTimeout(emptyCmSubscriptionDmiOutEvent, dmisToRespond);
124             final CmSubscriptionDmiInEvent cmSubscriptionDmiInEvent =
125                     cmSubscriptionNcmpInEventToCmSubscriptionDmiInEventMapper.toCmSubscriptionDmiInEvent(
126                             cmSubscriptionNcmpInEvent);
127             forwardEventToDmis(dmiPropertiesPerCmHandleIdPerServiceName, cmSubscriptionDmiInEvent, eventType);
128         }
129     }
130
131     private void startResponseTimeout(final CmSubscriptionDmiOutEvent emptyCmSubscriptionDmiOutEvent,
132                                       final Set<String> dmisToRespond) {
133         final String subscriptionClientId = emptyCmSubscriptionDmiOutEvent.getData().getClientId();
134         final String subscriptionName = emptyCmSubscriptionDmiOutEvent.getData().getSubscriptionName();
135         final String subscriptionEventId = subscriptionClientId + subscriptionName;
136
137         forwardedSubscriptionEventCache.put(subscriptionEventId, dmisToRespond,
138                 ForwardedSubscriptionEventCacheConfig.SUBSCRIPTION_FORWARD_STARTED_TTL_SECS, TimeUnit.SECONDS);
139         final ResponseTimeoutTask responseTimeoutTask =
140             new ResponseTimeoutTask(forwardedSubscriptionEventCache, cmSubscriptionNcmpOutEventPublisher,
141                     emptyCmSubscriptionDmiOutEvent);
142
143         executorService.schedule(responseTimeoutTask, dmiResponseTimeoutInMs, TimeUnit.MILLISECONDS);
144     }
145
146     private void forwardEventToDmis(final Map<String, Map<String, Map<String, String>>> dmiNameCmHandleMap,
147             final CmSubscriptionDmiInEvent cmSubscriptionDmiInEvent, final String eventType) {
148         dmiNameCmHandleMap.forEach((dmiName, cmHandlePropertiesMap) -> {
149             final List<CmHandle> cmHandleTargets = cmHandlePropertiesMap.entrySet().stream().map(
150                     cmHandleAndProperties -> {
151                         final CmHandle cmHandle = new CmHandle();
152                         cmHandle.setId(cmHandleAndProperties.getKey());
153                         cmHandle.setAdditionalProperties(cmHandleAndProperties.getValue());
154                         return cmHandle;
155                     }).collect(Collectors.toList());
156
157             cmSubscriptionDmiInEvent.getData().getPredicates().setTargets(cmHandleTargets);
158             final String eventKey = createEventKey(cmSubscriptionDmiInEvent, dmiName);
159             final String dmiAvcSubscriptionTopic = dmiAvcSubscriptionTopicPrefix + dmiName;
160
161             final CloudEvent cmSubscriptionDmiInCloudEvent =
162                     cmSubscriptionEventCloudMapper.toCloudEvent(cmSubscriptionDmiInEvent, eventKey, eventType);
163             eventsPublisher.publishCloudEvent(dmiAvcSubscriptionTopic, eventKey, cmSubscriptionDmiInCloudEvent);
164         });
165     }
166
167     private String createEventKey(final CmSubscriptionDmiInEvent cmSubscriptionDmiInEvent, final String dmiName) {
168         return cmSubscriptionDmiInEvent.getData().getSubscription().getClientID() + "-"
169                        + cmSubscriptionDmiInEvent.getData().getSubscription().getName() + "-" + dmiName;
170     }
171
172     private void updatesCmHandlesToRejectedAndPersistSubscriptionEvent(
173             final CmSubscriptionNcmpInEvent cmSubscriptionNcmpInEvent,
174             final List<String> targetCmHandlesDoesNotExistInDb) {
175         final YangModelSubscriptionEvent yangModelSubscriptionEvent =
176                 cmSubscriptionNcmpInEventMapper.toYangModelSubscriptionEvent(cmSubscriptionNcmpInEvent);
177         yangModelSubscriptionEvent.getPredicates()
178                 .setTargetCmHandles(findRejectedCmHandles(targetCmHandlesDoesNotExistInDb, yangModelSubscriptionEvent));
179         subscriptionPersistence.saveSubscriptionEvent(yangModelSubscriptionEvent);
180     }
181
182     private static List<YangModelSubscriptionEvent.TargetCmHandle> findRejectedCmHandles(
183             final List<String> targetCmHandlesDoesNotExistInDb,
184             final YangModelSubscriptionEvent yangModelSubscriptionEvent) {
185         return yangModelSubscriptionEvent.getPredicates().getTargetCmHandles().stream()
186                     .filter(targetCmHandle -> targetCmHandlesDoesNotExistInDb.contains(targetCmHandle.getCmHandleId()))
187                     .map(target -> new YangModelSubscriptionEvent.TargetCmHandle(target.getCmHandleId(),
188                                     SubscriptionStatus.REJECTED, "Targets not found"))
189                 .collect(Collectors.toList());
190     }
191 }