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