Adjust to yangtools-2.0.0/odlparent-3.0.0 changes
[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 java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Set;
27 import java.util.concurrent.Future;
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.config.util.xml.XmlUtil;
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.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.JoinTopicInput;
47 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutput;
48 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutputBuilder;
49 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicStatus;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
51 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.RpcResult;
54 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
58 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
59 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
60 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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 = Preconditions.checkNotNull(streamMap);
108         this.domPublish = Preconditions.checkNotNull(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 (String urnPrefix : this.urnPrefixToStreamMap.keySet()) {
126             final String streamName = this.urnPrefixToStreamMap.get(urnPrefix);
127             LOG.debug("urnPrefix: {} streamName: {}", urnPrefix, streamName);
128             if (availableStreams.containsKey(streamName)) {
129                 LOG.debug("Stream containig on device");
130                 notificationTopicRegistrations
131                         .put(urnPrefix, new StreamNotificationTopicRegistration(availableStreams.get(streamName),
132                                 urnPrefix, this));
133             }
134         }
135     }
136
137     private Map<String, Stream> getAvailableStreams() {
138         Map<String, Stream> streamMap = new HashMap<>();
139         final List<Stream> availableStreams;
140         try {
141             availableStreams = mount.getAvailableStreams();
142             streamMap = Maps.uniqueIndex(availableStreams, input -> input.getName().getValue());
143         } catch (ReadFailedException e) {
144             LOG.warn("Can not read streams for node {}", mount.getNodeId());
145         }
146         return streamMap;
147     }
148
149     @Override
150     public Future<RpcResult<JoinTopicOutput>> joinTopic(final JoinTopicInput input) {
151         LOG.debug("Join topic {} on {}", input.getTopicId().getValue(), mount.getNodeId());
152         final NotificationPattern notificationPattern = input.getNotificationPattern();
153         final List<SchemaPath> matchingNotifications = getMatchingNotifications(notificationPattern);
154         return registerTopic(input.getTopicId(), matchingNotifications);
155
156     }
157
158     @Override
159     public Future<RpcResult<Void>> disJoinTopic(final DisJoinTopicInput input) {
160         for (NotificationTopicRegistration reg : notificationTopicRegistrations.values()) {
161             reg.unRegisterNotificationTopic(input.getTopicId());
162         }
163         return Util.resultRpcSuccessFor((Void) null);
164     }
165
166     private synchronized Future<RpcResult<JoinTopicOutput>> registerTopic(
167             final TopicId topicId,
168             final List<SchemaPath> notificationsToSubscribe) {
169         Preconditions.checkNotNull(notificationsToSubscribe);
170         LOG.debug("Join topic {} - register", topicId);
171         JoinTopicStatus joinTopicStatus = JoinTopicStatus.Down;
172
173         LOG.debug("Notifications to subscribe has found - count {}", notificationsToSubscribe.size());
174         int registeredNotificationCount = 0;
175         for (SchemaPath schemaPath : notificationsToSubscribe) {
176             final Collection<NotificationTopicRegistration> topicRegistrations =
177                     notificationTopicRegistrations.get(schemaPath.getLastComponent().getNamespace().toString());
178             for (NotificationTopicRegistration reg : topicRegistrations) {
179                 LOG.info("Source of notification {} is activating, TopicId {}", reg.getSourceName(),
180                         topicId.getValue());
181                 boolean regSuccess = reg.registerNotificationTopic(schemaPath, topicId);
182                 if (regSuccess) {
183                     registeredNotificationCount = registeredNotificationCount + 1;
184                 }
185             }
186         }
187         if (registeredNotificationCount > 0) {
188             joinTopicStatus = JoinTopicStatus.Up;
189         }
190         final JoinTopicOutput output = new JoinTopicOutputBuilder().setStatus(joinTopicStatus).build();
191         return immediateFuture(RpcResultBuilder.success(output).build());
192
193     }
194
195     public void reActivateStreams() {
196         for (NotificationTopicRegistration reg : notificationTopicRegistrations.values()) {
197             LOG.info("Source of notification {} is reactivating on node {}", reg.getSourceName(), mount.getNodeId());
198             reg.reActivateNotificationSource();
199         }
200     }
201
202     public void deActivateStreams() {
203         for (NotificationTopicRegistration reg : notificationTopicRegistrations.values()) {
204             LOG.info("Source of notification {} is deactivating on node {}", reg.getSourceName(), mount.getNodeId());
205             reg.deActivateNotificationSource();
206         }
207     }
208
209     @Override
210     public void onNotification(final DOMNotification notification) {
211         SchemaPath notificationPath = notification.getType();
212         Date notificationEventTime = null;
213         if (notification instanceof DOMEvent) {
214             notificationEventTime = ((DOMEvent) notification).getEventTime();
215         }
216         final String namespace = notification.getType().getLastComponent().getNamespace().toString();
217         for (NotificationTopicRegistration notifReg : notificationTopicRegistrations.get(namespace)) {
218             notifReg.setLastEventTime(notificationEventTime);
219             Set<TopicId> topicIdsForNotification = notifReg.getTopicsForNotification(notificationPath);
220             for (TopicId topicId : topicIdsForNotification) {
221                 publishNotification(notification, topicId);
222                 LOG.debug("Notification {} has been published for TopicId {}", notification.getType(),
223                         topicId.getValue());
224             }
225         }
226     }
227
228     private void publishNotification(final DOMNotification notification, final TopicId topicId) {
229         final ContainerNode topicNotification = Builders.containerBuilder().withNodeIdentifier(TOPIC_NOTIFICATION_ARG)
230                 .withChild(ImmutableNodes.leafNode(TOPIC_ID_ARG, topicId))
231                 .withChild(ImmutableNodes.leafNode(EVENT_SOURCE_ARG, mount.getNodeId()))
232                 .withChild(encapsulate(notification))
233                 .build();
234         try {
235             domPublish.putNotification(new TopicDOMNotification(topicNotification));
236         } catch (final InterruptedException e) {
237             throw new RuntimeException(e);
238         }
239     }
240
241     private AnyXmlNode encapsulate(final DOMNotification body) {
242         // FIXME: Introduce something like YangModeledAnyXmlNode in Yangtools
243         final Document doc = XmlUtil.newDocument();
244         final Optional<String> namespace = Optional.of(PAYLOAD_ARG.getNodeType().getNamespace().toString());
245         final Element element = XmlUtil.createElement(doc, "payload", namespace);
246
247         final DOMResult result = new DOMResult(element);
248
249         final SchemaContext context = mount.getSchemaContext();
250         final SchemaPath schemaPath = body.getType();
251         try {
252             NetconfUtil.writeNormalizedNode(body.getBody(), result, schemaPath, context);
253             return Builders.anyXmlBuilder().withNodeIdentifier(PAYLOAD_ARG).withValue(new DOMSource(element)).build();
254         } catch (IOException | XMLStreamException e) {
255             LOG.error("Unable to encapsulate notification.", e);
256             throw new RuntimeException(e);
257         }
258     }
259
260     /**
261      * Returns all available notification paths that matches given pattern.
262      *
263      * @param notificationPattern pattern
264      * @return notification paths
265      */
266     private List<SchemaPath> getMatchingNotifications(final NotificationPattern notificationPattern) {
267         final String regex = notificationPattern.getValue();
268
269         final Pattern pattern = Pattern.compile(regex);
270         List<SchemaPath> availableNotifications = getAvailableNotifications();
271         return Util.expandQname(availableNotifications, pattern);
272     }
273
274     @Override
275     public void close() throws Exception {
276         for (NotificationTopicRegistration streamReg : notificationTopicRegistrations.values()) {
277             streamReg.close();
278         }
279     }
280
281     @Override
282     public NodeKey getSourceNodeKey() {
283         return mount.getNode().getKey();
284     }
285
286     @Override
287     public List<SchemaPath> getAvailableNotifications() {
288
289         final List<SchemaPath> availNotifList = new ArrayList<>();
290         // add Event Source Connection status notification
291         availNotifList.add(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
292
293         final Set<NotificationDefinition> availableNotifications = mount.getSchemaContext()
294                 .getNotifications();
295         // add all known notifications from netconf device
296         for (final NotificationDefinition nd : availableNotifications) {
297             availNotifList.add(nd.getPath());
298         }
299         return availNotifList;
300     }
301
302     NetconfEventSourceMount getMount() {
303         return mount;
304     }
305
306 }