Bump upstreams for Silicon
[netconf.git] / netconf / messagebus-netconf / src / main / java / org / opendaylight / netconf / messagebus / eventsources / netconf / NetconfEventSource.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netconf.messagebus.eventsources.netconf;
9
10 import static com.google.common.util.concurrent.Futures.immediateFuture;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.collect.ArrayListMultimap;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.Maps;
16 import com.google.common.collect.Multimap;
17 import com.google.common.collect.Multimaps;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import java.io.IOException;
20 import java.time.Instant;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Optional;
27 import java.util.concurrent.ExecutionException;
28 import java.util.regex.Pattern;
29 import javax.xml.stream.XMLStreamException;
30 import javax.xml.transform.dom.DOMResult;
31 import javax.xml.transform.dom.DOMSource;
32 import org.opendaylight.controller.messagebus.app.util.TopicDOMNotification;
33 import org.opendaylight.controller.messagebus.app.util.Util;
34 import org.opendaylight.controller.messagebus.spi.EventSource;
35 import org.opendaylight.mdsal.dom.api.DOMEvent;
36 import org.opendaylight.mdsal.dom.api.DOMNotification;
37 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
38 import org.opendaylight.mdsal.dom.api.DOMNotificationPublishService;
39 import org.opendaylight.netconf.api.xml.XmlUtil;
40 import org.opendaylight.netconf.util.NetconfUtil;
41 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.NotificationPattern;
42 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
43 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicNotification;
44 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.DisJoinTopicInput;
45 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.DisJoinTopicOutput;
46 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.DisJoinTopicOutputBuilder;
47 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicInput;
48 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutput;
49 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutputBuilder;
50 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicStatus;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
52 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.common.RpcResult;
55 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
59 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
60 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
61 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
62 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65 import org.w3c.dom.Document;
66 import org.w3c.dom.Element;
67
68 /**
69  * NetconfEventSource serves as proxy between nodes and messagebus. Subscribers can join topic stream from this source.
70  * Then they will receive notifications from device that matches pattern specified by topic.
71  */
72 public class NetconfEventSource implements EventSource, DOMNotificationListener {
73
74     private static final Logger LOG = LoggerFactory.getLogger(NetconfEventSource.class);
75
76     private static final NodeIdentifier TOPIC_NOTIFICATION_ARG = NodeIdentifier.create(TopicNotification.QNAME);
77     private static final NodeIdentifier EVENT_SOURCE_ARG = NodeIdentifier.create(
78             QName.create(TopicNotification.QNAME, "node-id"));
79     private static final NodeIdentifier TOPIC_ID_ARG = NodeIdentifier.create(
80             QName.create(TopicNotification.QNAME, "topic-id"));
81     private static final NodeIdentifier PAYLOAD_ARG = NodeIdentifier.create(
82             QName.create(TopicNotification.QNAME, "payload"));
83     private static final String CONNECTION_NOTIFICATION_SOURCE_NAME = "ConnectionNotificationSource";
84
85     private final DOMNotificationPublishService domPublish;
86
87     private final Map<String, String> urnPrefixToStreamMap; // key = urnPrefix, value = StreamName
88
89     /**
90      * Map notification uri -> registrations.
91      */
92     private final Multimap<String, NotificationTopicRegistration>
93             notificationTopicRegistrations = Multimaps.synchronizedListMultimap(ArrayListMultimap.create());
94     private final NetconfEventSourceMount mount;
95
96     /**
97      * Creates new NetconfEventSource for node. Topic notifications will be published via provided
98      * {@link DOMNotificationPublishService}
99      *
100      * @param streamMap      netconf streams from device
101      * @param publishService publish service
102      */
103     public NetconfEventSource(final Map<String, String> streamMap,
104                               final NetconfEventSourceMount mount,
105                               final DOMNotificationPublishService publishService) {
106         this.mount = mount;
107         this.urnPrefixToStreamMap = requireNonNull(streamMap);
108         this.domPublish = requireNonNull(publishService);
109         this.initializeNotificationTopicRegistrationList();
110
111         LOG.info("NetconfEventSource [{}] created.", mount.getNodeId());
112     }
113
114     /**
115      * Creates {@link ConnectionNotificationTopicRegistration} for connection. Also creates
116      * {@link StreamNotificationTopicRegistration} for every prefix and available stream as defined in config file.
117      */
118     private void initializeNotificationTopicRegistrationList() {
119         final ConnectionNotificationTopicRegistration cntr =
120                 new ConnectionNotificationTopicRegistration(CONNECTION_NOTIFICATION_SOURCE_NAME, this);
121         notificationTopicRegistrations
122                 .put(cntr.getNotificationUrnPrefix(), cntr);
123         Map<String, Stream> availableStreams = getAvailableStreams();
124         LOG.debug("Stream configuration compare...");
125         for (Entry<String, String> entry : this.urnPrefixToStreamMap.entrySet()) {
126             String urnPrefix = entry.getKey();
127             final String streamName = entry.getValue();
128             LOG.debug("urnPrefix: {} streamName: {}", urnPrefix, streamName);
129             if (availableStreams.containsKey(streamName)) {
130                 LOG.debug("Stream containig on device");
131                 notificationTopicRegistrations
132                         .put(urnPrefix, new StreamNotificationTopicRegistration(availableStreams.get(streamName),
133                                 urnPrefix, this));
134             }
135         }
136     }
137
138     private Map<String, Stream> getAvailableStreams() {
139         final Collection<Stream> availableStreams;
140         try {
141             availableStreams = mount.getAvailableStreams();
142         } catch (InterruptedException | ExecutionException e) {
143             LOG.warn("Can not read streams for node {}", mount.getNodeId(), e);
144             return ImmutableMap.of();
145         }
146
147         return Maps.uniqueIndex(availableStreams, input -> input.getName().getValue());
148     }
149
150     @Override
151     public ListenableFuture<RpcResult<JoinTopicOutput>> joinTopic(final JoinTopicInput input) {
152         LOG.debug("Join topic {} on {}", input.getTopicId().getValue(), mount.getNodeId());
153         final NotificationPattern notificationPattern = input.getNotificationPattern();
154         final List<SchemaPath> matchingNotifications = getMatchingNotifications(notificationPattern);
155         return registerTopic(input.getTopicId(), matchingNotifications);
156
157     }
158
159     @Override
160     public ListenableFuture<RpcResult<DisJoinTopicOutput>> disJoinTopic(final DisJoinTopicInput input) {
161         for (NotificationTopicRegistration reg : notificationTopicRegistrations.values()) {
162             reg.unRegisterNotificationTopic(input.getTopicId());
163         }
164         return Util.resultRpcSuccessFor(new DisJoinTopicOutputBuilder().build());
165     }
166
167     private synchronized ListenableFuture<RpcResult<JoinTopicOutput>> registerTopic(
168             final TopicId topicId,
169             final List<SchemaPath> notificationsToSubscribe) {
170         requireNonNull(notificationsToSubscribe);
171         LOG.debug("Join topic {} - register", topicId);
172         JoinTopicStatus joinTopicStatus = JoinTopicStatus.Down;
173
174         LOG.debug("Notifications to subscribe has found - count {}", notificationsToSubscribe.size());
175         int registeredNotificationCount = 0;
176         for (SchemaPath schemaPath : notificationsToSubscribe) {
177             final Collection<NotificationTopicRegistration> topicRegistrations =
178                     notificationTopicRegistrations.get(schemaPath.getLastComponent().getNamespace().toString());
179             for (NotificationTopicRegistration reg : topicRegistrations) {
180                 LOG.info("Source of notification {} is activating, TopicId {}", reg.getSourceName(),
181                         topicId.getValue());
182                 boolean regSuccess = reg.registerNotificationTopic(schemaPath, topicId);
183                 if (regSuccess) {
184                     registeredNotificationCount = registeredNotificationCount + 1;
185                 }
186             }
187         }
188         if (registeredNotificationCount > 0) {
189             joinTopicStatus = JoinTopicStatus.Up;
190         }
191         final JoinTopicOutput output = new JoinTopicOutputBuilder().setStatus(joinTopicStatus).build();
192         return immediateFuture(RpcResultBuilder.success(output).build());
193
194     }
195
196     public void reActivateStreams() {
197         for (NotificationTopicRegistration reg : notificationTopicRegistrations.values()) {
198             LOG.info("Source of notification {} is reactivating on node {}", reg.getSourceName(), mount.getNodeId());
199             reg.reActivateNotificationSource();
200         }
201     }
202
203     public void deActivateStreams() {
204         for (NotificationTopicRegistration reg : notificationTopicRegistrations.values()) {
205             LOG.info("Source of notification {} is deactivating on node {}", reg.getSourceName(), mount.getNodeId());
206             reg.deActivateNotificationSource();
207         }
208     }
209
210     @Override
211     public void onNotification(final DOMNotification notification) {
212         Instant notificationEventTime = null;
213         if (notification instanceof DOMEvent) {
214             notificationEventTime = ((DOMEvent) notification).getEventInstant();
215         }
216         final String namespace = notification.getType().lastNodeIdentifier().getNamespace().toString();
217         for (NotificationTopicRegistration notifReg : notificationTopicRegistrations.get(namespace)) {
218             notifReg.setLastEventTime(notificationEventTime);
219             for (TopicId topicId : notifReg.getTopicsForNotification(notification.getType().asSchemaPath())) {
220                 publishNotification(notification, topicId);
221                 LOG.debug("Notification {} has been published for TopicId {}", notification.getType(),
222                         topicId.getValue());
223             }
224         }
225     }
226
227     private void publishNotification(final DOMNotification notification, final TopicId topicId) {
228         final ContainerNode topicNotification = Builders.containerBuilder().withNodeIdentifier(TOPIC_NOTIFICATION_ARG)
229                 .withChild(ImmutableNodes.leafNode(TOPIC_ID_ARG, topicId))
230                 .withChild(ImmutableNodes.leafNode(EVENT_SOURCE_ARG, mount.getNodeId()))
231                 .withChild(encapsulate(notification))
232                 .build();
233         try {
234             domPublish.putNotification(new TopicDOMNotification(topicNotification));
235         } catch (final InterruptedException e) {
236             throw new RuntimeException(e);
237         }
238     }
239
240     private DOMSourceAnyxmlNode encapsulate(final DOMNotification body) {
241         // FIXME: Introduce something like YangModeledAnyXmlNode in Yangtools
242         final Document doc = XmlUtil.newDocument();
243         final Optional<String> namespace = Optional.of(PAYLOAD_ARG.getNodeType().getNamespace().toString());
244         final Element element = XmlUtil.createElement(doc, "payload", namespace);
245
246         final DOMResult result = new DOMResult(element);
247
248         try {
249             NetconfUtil.writeNormalizedNode(body.getBody(), result, body.getType().asSchemaPath(),
250                 mount.getSchemaContext());
251             return Builders.anyXmlBuilder().withNodeIdentifier(PAYLOAD_ARG).withValue(new DOMSource(element)).build();
252         } catch (IOException | XMLStreamException e) {
253             LOG.error("Unable to encapsulate notification.", e);
254             throw new RuntimeException(e);
255         }
256     }
257
258     /**
259      * Returns all available notification paths that matches given pattern.
260      *
261      * @param notificationPattern pattern
262      * @return notification paths
263      */
264     private List<SchemaPath> getMatchingNotifications(final NotificationPattern notificationPattern) {
265         final String regex = notificationPattern.getValue();
266
267         final Pattern pattern = Pattern.compile(regex);
268         List<SchemaPath> availableNotifications = getAvailableNotifications();
269         return Util.expandQname(availableNotifications, pattern);
270     }
271
272     @Override
273     public void close() throws Exception {
274         for (NotificationTopicRegistration streamReg : notificationTopicRegistrations.values()) {
275             streamReg.close();
276         }
277     }
278
279     @Override
280     public NodeKey getSourceNodeKey() {
281         return mount.getNode().key();
282     }
283
284     @Override
285     public List<SchemaPath> getAvailableNotifications() {
286
287         final List<SchemaPath> availNotifList = new ArrayList<>();
288         // add Event Source Connection status notification
289         availNotifList.add(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH.asSchemaPath());
290
291         // add all known notifications from netconf device
292         for (final NotificationDefinition nd : mount.getSchemaContext().getNotifications()) {
293             availNotifList.add(nd.getPath());
294         }
295         return availNotifList;
296     }
297
298     NetconfEventSourceMount getMount() {
299         return mount;
300     }
301
302 }