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