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

©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.