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