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