Do not retain reference to DOMRpcRouter in registrations
[mdsal.git] / dom / mdsal-dom-broker / src / main / java / org / opendaylight / mdsal / dom / broker / DOMRpcRouter.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 package org.opendaylight.mdsal.dom.broker;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableList.Builder;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.MapDifference;
19 import com.google.common.collect.MapDifference.ValueDifference;
20 import com.google.common.collect.Maps;
21 import com.google.common.collect.Sets;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.ThreadFactoryBuilder;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Set;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.ThreadFactory;
33 import javax.annotation.concurrent.GuardedBy;
34 import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
35 import org.opendaylight.mdsal.dom.api.DOMRpcException;
36 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
37 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
38 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationRegistration;
39 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
40 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
41 import org.opendaylight.mdsal.dom.api.DOMRpcService;
42 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
43 import org.opendaylight.mdsal.dom.spi.AbstractDOMRpcImplementationRegistration;
44 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
45 import org.opendaylight.yangtools.concepts.ListenerRegistration;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51
52 public final class DOMRpcRouter implements AutoCloseable, DOMRpcService, DOMRpcProviderService, SchemaContextListener {
53     private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat(
54             "DOMRpcRouter-listener-%s").setDaemon(true).build();
55
56     private final ExecutorService listenerNotifier = Executors.newSingleThreadExecutor(THREAD_FACTORY);
57
58     @GuardedBy("this")
59     private Collection<Registration<?>> listeners = Collections.emptyList();
60
61     private volatile DOMRpcRoutingTable routingTable = DOMRpcRoutingTable.EMPTY;
62
63     private ListenerRegistration<?> listenerRegistration;
64
65     public static DOMRpcRouter newInstance(final DOMSchemaService schemaService) {
66         final DOMRpcRouter rpcRouter = new DOMRpcRouter();
67         rpcRouter.listenerRegistration = schemaService.registerSchemaContextListener(rpcRouter);
68         return rpcRouter;
69     }
70
71     @Override
72     public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(
73             final T implementation, final DOMRpcIdentifier... rpcs) {
74         return registerRpcImplementation(implementation, ImmutableSet.copyOf(rpcs));
75     }
76
77     @Override
78     public synchronized <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T>
79             registerRpcImplementation(final T implementation, final Set<DOMRpcIdentifier> rpcs) {
80         final DOMRpcRoutingTable oldTable = routingTable;
81         final DOMRpcRoutingTable newTable = oldTable.add(implementation, rpcs);
82         routingTable = newTable;
83
84         listenerNotifier.execute(() -> notifyAdded(newTable, implementation));
85
86         return new AbstractDOMRpcImplementationRegistration<T>(implementation) {
87             @Override
88             protected void removeRegistration() {
89                 removeRpcImplementation(getInstance(), rpcs);
90             }
91         };
92     }
93
94     private synchronized void removeRpcImplementation(final DOMRpcImplementation implementation,
95             final Set<DOMRpcIdentifier> rpcs) {
96         final DOMRpcRoutingTable oldTable = routingTable;
97         final DOMRpcRoutingTable newTable = oldTable.remove(implementation, rpcs);
98         routingTable = newTable;
99
100         listenerNotifier.execute(() -> notifyRemoved(newTable, implementation));
101     }
102
103     @Override
104     public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final SchemaPath type,
105             final NormalizedNode<?, ?> input) {
106         return routingTable.invokeRpc(type, input);
107     }
108
109     private synchronized void removeListener(final ListenerRegistration<? extends DOMRpcAvailabilityListener> reg) {
110         listeners = ImmutableList.copyOf(Collections2.filter(listeners, input -> !reg.equals(input)));
111     }
112
113     private synchronized void notifyAdded(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
114         for (Registration<?> l : listeners) {
115             l.addRpc(newTable, impl);
116         }
117     }
118
119     private synchronized void notifyRemoved(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
120         for (Registration<?> l : listeners) {
121             l.removeRpc(newTable, impl);
122         }
123     }
124
125     @Override
126     public synchronized <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
127             final T listener) {
128         final Registration<T> ret = new Registration<>(this, listener, routingTable.getRpcs(listener));
129         final Builder<Registration<?>> b = ImmutableList.builder();
130         b.addAll(listeners);
131         b.add(ret);
132         listeners = b.build();
133
134         listenerNotifier.execute(() -> ret.initialTable());
135         return ret;
136     }
137
138     @Override
139     public synchronized void onGlobalContextUpdated(final SchemaContext context) {
140         final DOMRpcRoutingTable oldTable = routingTable;
141         final DOMRpcRoutingTable newTable = oldTable.setSchemaContext(context);
142         routingTable = newTable;
143     }
144
145     @Override
146     public void close() {
147         listenerNotifier.shutdown();
148
149         if (listenerRegistration != null) {
150             listenerRegistration.close();
151         }
152     }
153
154     @VisibleForTesting
155     Collection<?> listeners() {
156         return listeners;
157     }
158
159     @VisibleForTesting
160     DOMRpcRoutingTable routingTable() {
161         return routingTable;
162     }
163
164     private static final class Registration<T extends DOMRpcAvailabilityListener>
165         extends AbstractListenerRegistration<T> {
166
167         private Map<SchemaPath, Set<YangInstanceIdentifier>> prevRpcs;
168         private DOMRpcRouter router;
169
170         Registration(final DOMRpcRouter router, final T listener,
171                 final Map<SchemaPath, Set<YangInstanceIdentifier>> rpcs) {
172             super(listener);
173             this.router = requireNonNull(router);
174             this.prevRpcs = requireNonNull(rpcs);
175         }
176
177         @Override
178         protected void removeRegistration() {
179             router.removeListener(this);
180             router = null;
181         }
182
183         void initialTable() {
184             final Collection<DOMRpcIdentifier> added = new ArrayList<>();
185             for (Entry<SchemaPath, Set<YangInstanceIdentifier>> e : prevRpcs.entrySet()) {
186                 added.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
187             }
188             if (!added.isEmpty()) {
189                 getInstance().onRpcAvailable(added);
190             }
191         }
192
193         void addRpc(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
194             final T l = getInstance();
195             if (!l.acceptsImplementation(impl)) {
196                 return;
197             }
198
199             final Map<SchemaPath, Set<YangInstanceIdentifier>> rpcs = verifyNotNull(newTable.getRpcs(l));
200             final MapDifference<SchemaPath, Set<YangInstanceIdentifier>> diff = Maps.difference(prevRpcs, rpcs);
201
202             final Collection<DOMRpcIdentifier> added = new ArrayList<>();
203             for (Entry<SchemaPath, Set<YangInstanceIdentifier>> e : diff.entriesOnlyOnRight().entrySet()) {
204                 added.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
205             }
206             for (Entry<SchemaPath, ValueDifference<Set<YangInstanceIdentifier>>> e :
207                     diff.entriesDiffering().entrySet()) {
208                 for (YangInstanceIdentifier i : Sets.difference(e.getValue().rightValue(), e.getValue().leftValue())) {
209                     added.add(DOMRpcIdentifier.create(e.getKey(), i));
210                 }
211             }
212
213             prevRpcs = rpcs;
214             if (!added.isEmpty()) {
215                 l.onRpcAvailable(added);
216             }
217         }
218
219         void removeRpc(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
220             final T l = getInstance();
221             if (!l.acceptsImplementation(impl)) {
222                 return;
223             }
224
225             final Map<SchemaPath, Set<YangInstanceIdentifier>> rpcs = verifyNotNull(newTable.getRpcs(l));
226             final MapDifference<SchemaPath, Set<YangInstanceIdentifier>> diff = Maps.difference(prevRpcs, rpcs);
227
228             final Collection<DOMRpcIdentifier> removed = new ArrayList<>();
229             for (Entry<SchemaPath, Set<YangInstanceIdentifier>> e : diff.entriesOnlyOnLeft().entrySet()) {
230                 removed.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
231             }
232             for (Entry<SchemaPath, ValueDifference<Set<YangInstanceIdentifier>>> e :
233                     diff.entriesDiffering().entrySet()) {
234                 for (YangInstanceIdentifier i : Sets.difference(e.getValue().leftValue(), e.getValue().rightValue())) {
235                     removed.add(DOMRpcIdentifier.create(e.getKey(), i));
236                 }
237             }
238
239             prevRpcs = rpcs;
240             if (!removed.isEmpty()) {
241                 l.onRpcUnavailable(removed);
242             }
243         }
244     }
245 }