Adjust for Binding RPC codegen changes
[controller.git] / opendaylight / md-sal / messagebus-impl / src / main / java / org / opendaylight / controller / messagebus / app / impl / EventSourceTopic.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.controller.messagebus.app.impl;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import java.util.Collection;
18 import java.util.List;
19 import java.util.UUID;
20 import java.util.concurrent.CopyOnWriteArraySet;
21 import java.util.concurrent.ExecutionException;
22 import java.util.regex.Pattern;
23 import javax.annotation.Nonnull;
24 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
25 import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
26 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
27 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
28 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
30 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.NotificationPattern;
31 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
32 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.DisJoinTopicInput;
33 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.DisJoinTopicInputBuilder;
34 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.DisJoinTopicOutput;
35 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.EventSourceService;
36 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicInput;
37 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicInputBuilder;
38 import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutput;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
42 import org.opendaylight.yangtools.concepts.ListenerRegistration;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
44 import org.opendaylight.yangtools.yang.common.RpcError;
45 import org.opendaylight.yangtools.yang.common.RpcResult;
46 import org.slf4j.LoggerFactory;
47
48 public final class EventSourceTopic implements DataTreeChangeListener<Node>, AutoCloseable {
49     private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(EventSourceTopic.class);
50     private final NotificationPattern notificationPattern;
51     private final EventSourceService sourceService;
52     private final Pattern nodeIdPattern;
53     private final TopicId topicId;
54     private ListenerRegistration<?> listenerRegistration;
55     private final CopyOnWriteArraySet<InstanceIdentifier<?>> joinedEventSources = new CopyOnWriteArraySet<>();
56
57     public static EventSourceTopic create(final NotificationPattern notificationPattern,
58             final String nodeIdRegexPattern, final EventSourceTopology eventSourceTopology) {
59         final EventSourceTopic est = new EventSourceTopic(notificationPattern, nodeIdRegexPattern,
60                 eventSourceTopology.getEventSourceService());
61         est.registerListner(eventSourceTopology);
62         est.notifyExistingNodes(eventSourceTopology);
63         return est;
64     }
65
66     private EventSourceTopic(final NotificationPattern notificationPattern, final String nodeIdRegexPattern,
67             final EventSourceService sourceService) {
68         this.notificationPattern = Preconditions.checkNotNull(notificationPattern);
69         this.sourceService = Preconditions.checkNotNull(sourceService);
70         this.nodeIdPattern = Pattern.compile(nodeIdRegexPattern);
71         this.topicId = new TopicId(getUUIDIdent());
72         this.listenerRegistration = null;
73         LOG.info("EventSourceTopic created - topicId {}", topicId.getValue());
74     }
75
76     public TopicId getTopicId() {
77         return topicId;
78     }
79
80     @Override
81     public void onDataTreeChanged(final Collection<DataTreeModification<Node>> changes) {
82         for (DataTreeModification<Node> change: changes) {
83             final DataObjectModification<Node> rootNode = change.getRootNode();
84             switch (rootNode.getModificationType()) {
85                 case WRITE:
86                 case SUBTREE_MODIFIED:
87                     final Node node = rootNode.getDataAfter();
88                     if (getNodeIdRegexPattern().matcher(node.getNodeId().getValue()).matches()) {
89                         notifyNode(change.getRootPath().getRootIdentifier());
90                     }
91                     break;
92                 default:
93                     break;
94             }
95         }
96     }
97
98     public void notifyNode(final InstanceIdentifier<?> nodeId) {
99         LOG.debug("Notify node: {}", nodeId);
100         try {
101             final RpcResult<JoinTopicOutput> rpcResultJoinTopic =
102                     sourceService.joinTopic(getJoinTopicInputArgument(nodeId)).get();
103             if (!rpcResultJoinTopic.isSuccessful()) {
104                 for (final RpcError err : rpcResultJoinTopic.getErrors()) {
105                     LOG.error("Can not join topic: [{}] on node: [{}]. Error: {}", getTopicId().getValue(),
106                             nodeId.toString(), err.toString());
107                 }
108             } else {
109                 joinedEventSources.add(nodeId);
110             }
111         } catch (InterruptedException | ExecutionException e) {
112             LOG.error("Could not invoke join topic for node {}", nodeId);
113         }
114     }
115
116     private void notifyExistingNodes(final EventSourceTopology eventSourceTopology) {
117         LOG.debug("Notify existing nodes");
118         final Pattern nodeRegex = this.nodeIdPattern;
119
120         final ReadOnlyTransaction tx = eventSourceTopology.getDataBroker().newReadOnlyTransaction();
121         final ListenableFuture<Optional<Topology>> future =
122                 tx.read(LogicalDatastoreType.OPERATIONAL, EventSourceTopology.EVENT_SOURCE_TOPOLOGY_PATH);
123
124         Futures.addCallback(future, new FutureCallback<Optional<Topology>>() {
125             @Override
126             public void onSuccess(@Nonnull final Optional<Topology> data) {
127                 if (data.isPresent()) {
128                     final List<Node> nodes = data.get().getNode();
129                     if (nodes != null) {
130                         for (final Node node : nodes) {
131                             if (nodeRegex.matcher(node.getNodeId().getValue()).matches()) {
132                                 notifyNode(EventSourceTopology.EVENT_SOURCE_TOPOLOGY_PATH.child(Node.class,
133                                         node.getKey()));
134                             }
135                         }
136                     }
137                 }
138                 tx.close();
139             }
140
141             @Override
142             public void onFailure(final Throwable ex) {
143                 LOG.error("Can not notify existing nodes", ex);
144                 tx.close();
145             }
146         }, MoreExecutors.directExecutor());
147     }
148
149     private JoinTopicInput getJoinTopicInputArgument(final InstanceIdentifier<?> path) {
150         final NodeRef nodeRef = new NodeRef(path);
151         final JoinTopicInput jti =
152                 new JoinTopicInputBuilder()
153                         .setNode(nodeRef.getValue())
154                         .setTopicId(topicId)
155                         .setNotificationPattern(notificationPattern)
156                         .build();
157         return jti;
158     }
159
160     public Pattern getNodeIdRegexPattern() {
161         return nodeIdPattern;
162     }
163
164     private DisJoinTopicInput getDisJoinTopicInputArgument(final InstanceIdentifier<?> eventSourceNodeId) {
165         final NodeRef nodeRef = new NodeRef(eventSourceNodeId);
166         final DisJoinTopicInput dji = new DisJoinTopicInputBuilder()
167                 .setNode(nodeRef.getValue())
168                 .setTopicId(topicId)
169                 .build();
170         return dji;
171     }
172
173     private void registerListner(final EventSourceTopology eventSourceTopology) {
174         this.listenerRegistration =
175                 eventSourceTopology.getDataBroker().registerDataTreeChangeListener(new DataTreeIdentifier<>(
176                         LogicalDatastoreType.OPERATIONAL,
177                         EventSourceTopology.EVENT_SOURCE_TOPOLOGY_PATH.child(Node.class)),
178                         this);
179     }
180
181     @Override
182     public void close() {
183         if (this.listenerRegistration != null) {
184             this.listenerRegistration.close();
185         }
186         for (final InstanceIdentifier<?> eventSourceNodeId : joinedEventSources) {
187             try {
188                 final RpcResult<DisJoinTopicOutput> result = sourceService
189                         .disJoinTopic(getDisJoinTopicInputArgument(eventSourceNodeId)).get();
190                 if (result.isSuccessful() == false) {
191                     for (final RpcError err : result.getErrors()) {
192                         LOG.error("Can not destroy topic: [{}] on node: [{}]. Error: {}", getTopicId().getValue(),
193                                 eventSourceNodeId, err.toString());
194                     }
195                 }
196             } catch (InterruptedException | ExecutionException ex) {
197                 LOG.error("Can not close event source topic / destroy topic {} on node {}.", this.topicId.getValue(),
198                         eventSourceNodeId, ex);
199             }
200         }
201         joinedEventSources.clear();
202     }
203
204     private static String getUUIDIdent() {
205         final UUID uuid = UUID.randomUUID();
206         return uuid.toString();
207     }
208 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.