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