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