Subscription Create Event Outcome Kafka Part
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / events / avcsubscription / SubscriptionEventForwarder.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.avcsubscription;
22
23 import com.hazelcast.map.IMap;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Objects;
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.apache.kafka.common.header.Headers;
38 import org.onap.cps.ncmp.api.impl.event.avc.ForwardedSubscriptionEventCacheConfig;
39 import org.onap.cps.ncmp.api.impl.event.avc.ResponseTimeoutTask;
40 import org.onap.cps.ncmp.api.impl.events.EventsPublisher;
41 import org.onap.cps.ncmp.api.impl.utils.DmiServiceNameOrganizer;
42 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
43 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
44 import org.onap.cps.ncmp.event.model.SubscriptionEvent;
45 import org.onap.cps.spi.exceptions.OperationNotYetSupportedException;
46 import org.springframework.beans.factory.annotation.Value;
47 import org.springframework.stereotype.Component;
48
49
50 @Component
51 @Slf4j
52 @RequiredArgsConstructor
53 public class SubscriptionEventForwarder {
54
55     private final InventoryPersistence inventoryPersistence;
56     private final EventsPublisher<SubscriptionEvent> eventsPublisher;
57     private final IMap<String, Set<String>> forwardedSubscriptionEventCache;
58     private final SubscriptionEventResponseOutcome subscriptionEventResponseOutcome;
59     private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
60     @Value("${app.ncmp.avc.subscription-forward-topic-prefix}")
61     private String dmiAvcSubscriptionTopicPrefix;
62
63     @Value("${ncmp.timers.subscription-forwarding.dmi-response-timeout-ms:30000}")
64     private int dmiResponseTimeoutInMs;
65
66     /**
67      * Forward subscription event.
68      *
69      * @param subscriptionEvent the event to be forwarded
70      */
71     public void forwardCreateSubscriptionEvent(final SubscriptionEvent subscriptionEvent,
72                                                final Headers eventHeaders) {
73         final List<Object> cmHandleTargets = subscriptionEvent.getEvent().getPredicates().getTargets();
74         if (cmHandleTargets == null || cmHandleTargets.isEmpty()
75                 || cmHandleTargets.stream().anyMatch(id -> ((String) id).contains("*"))) {
76             throw new OperationNotYetSupportedException(
77                     "CMHandle targets are required. \"Wildcard\" operations are not yet supported");
78         }
79         final List<String> cmHandleTargetsAsStrings = cmHandleTargets.stream().map(
80                 Objects::toString).collect(Collectors.toList());
81         final Collection<YangModelCmHandle> yangModelCmHandles =
82                 inventoryPersistence.getYangModelCmHandles(cmHandleTargetsAsStrings);
83
84         final Map<String, Map<String, Map<String, String>>> dmiPropertiesPerCmHandleIdPerServiceName
85                 = DmiServiceNameOrganizer.getDmiPropertiesPerCmHandleIdPerServiceName(yangModelCmHandles);
86
87         final Set<String> dmisToRespond = new HashSet<>(dmiPropertiesPerCmHandleIdPerServiceName.keySet());
88         if (dmisToRespond.isEmpty()) {
89             final String clientID = subscriptionEvent.getEvent().getSubscription().getClientID();
90             final String subscriptionName = subscriptionEvent.getEvent().getSubscription().getName();
91             subscriptionEventResponseOutcome.sendResponse(clientID, subscriptionName, true);
92         } else {
93             startResponseTimeout(subscriptionEvent, dmisToRespond);
94             forwardEventToDmis(dmiPropertiesPerCmHandleIdPerServiceName, subscriptionEvent, eventHeaders);
95         }
96     }
97
98     private void startResponseTimeout(final SubscriptionEvent subscriptionEvent, final Set<String> dmisToRespond) {
99         final String subscriptionClientId = subscriptionEvent.getEvent().getSubscription().getClientID();
100         final String subscriptionName = subscriptionEvent.getEvent().getSubscription().getName();
101         final String subscriptionEventId = subscriptionClientId + subscriptionName;
102
103         forwardedSubscriptionEventCache.put(subscriptionEventId, dmisToRespond,
104                 ForwardedSubscriptionEventCacheConfig.SUBSCRIPTION_FORWARD_STARTED_TTL_SECS, TimeUnit.SECONDS);
105         final ResponseTimeoutTask responseTimeoutTask =
106             new ResponseTimeoutTask(forwardedSubscriptionEventCache, subscriptionEventResponseOutcome,
107                     subscriptionClientId, subscriptionName);
108         try {
109             executorService.schedule(responseTimeoutTask, dmiResponseTimeoutInMs, TimeUnit.MILLISECONDS);
110         } catch (final RuntimeException ex) {
111             log.info("Caught exception in ScheduledExecutorService for ResponseTimeoutTask. StackTrace: {}",
112                     ex.toString());
113         }
114     }
115
116     private void forwardEventToDmis(final Map<String, Map<String, Map<String, String>>> dmiNameCmHandleMap,
117                                     final SubscriptionEvent subscriptionEvent,
118                                     final Headers eventHeaders) {
119         dmiNameCmHandleMap.forEach((dmiName, cmHandlePropertiesMap) -> {
120             subscriptionEvent.getEvent().getPredicates().setTargets(Collections.singletonList(cmHandlePropertiesMap));
121             final String eventKey = createEventKey(subscriptionEvent, dmiName);
122             final String dmiAvcSubscriptionTopic = dmiAvcSubscriptionTopicPrefix + dmiName;
123             eventsPublisher.publishEvent(dmiAvcSubscriptionTopic, eventKey, eventHeaders, subscriptionEvent);
124         });
125     }
126
127     private String createEventKey(final SubscriptionEvent subscriptionEvent, final String dmiName) {
128         return subscriptionEvent.getEvent().getSubscription().getClientID()
129             + "-"
130             + subscriptionEvent.getEvent().getSubscription().getName()
131             + "-"
132             + dmiName;
133     }
134 }