37713fd58cc2512e45ca0840f70c717254d93942
[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.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.collect.ClassToInstanceMap;
16 import com.google.common.collect.Collections2;
17 import com.google.common.collect.ImmutableClassToInstanceMap;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.ImmutableSet;
21 import com.google.common.collect.MapDifference;
22 import com.google.common.collect.MapDifference.ValueDifference;
23 import com.google.common.collect.Maps;
24 import com.google.common.collect.Sets;
25 import com.google.common.util.concurrent.Futures;
26 import com.google.common.util.concurrent.ListenableFuture;
27 import com.google.common.util.concurrent.ThreadFactoryBuilder;
28 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Optional;
37 import java.util.Set;
38 import java.util.concurrent.ExecutorService;
39 import java.util.concurrent.Executors;
40 import java.util.concurrent.ThreadFactory;
41 import javax.annotation.PreDestroy;
42 import javax.inject.Inject;
43 import javax.inject.Singleton;
44 import org.checkerframework.checker.lock.qual.GuardedBy;
45 import org.eclipse.jdt.annotation.NonNull;
46 import org.eclipse.jdt.annotation.NonNullByDefault;
47 import org.opendaylight.mdsal.dom.api.DOMActionAvailabilityExtension;
48 import org.opendaylight.mdsal.dom.api.DOMActionAvailabilityExtension.AvailabilityListener;
49 import org.opendaylight.mdsal.dom.api.DOMActionImplementation;
50 import org.opendaylight.mdsal.dom.api.DOMActionInstance;
51 import org.opendaylight.mdsal.dom.api.DOMActionNotAvailableException;
52 import org.opendaylight.mdsal.dom.api.DOMActionProviderService;
53 import org.opendaylight.mdsal.dom.api.DOMActionResult;
54 import org.opendaylight.mdsal.dom.api.DOMActionService;
55 import org.opendaylight.mdsal.dom.api.DOMActionServiceExtension;
56 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
57 import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
58 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
59 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
60 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
61 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationRegistration;
62 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
63 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
64 import org.opendaylight.mdsal.dom.api.DOMRpcService;
65 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
66 import org.opendaylight.mdsal.dom.spi.AbstractDOMRpcImplementationRegistration;
67 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
68 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
69 import org.opendaylight.yangtools.concepts.AbstractRegistration;
70 import org.opendaylight.yangtools.concepts.ListenerRegistration;
71 import org.opendaylight.yangtools.concepts.ObjectRegistration;
72 import org.opendaylight.yangtools.yang.common.QName;
73 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
74 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
77 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
78 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
79 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
80 import org.osgi.service.component.annotations.Activate;
81 import org.osgi.service.component.annotations.Component;
82 import org.osgi.service.component.annotations.Deactivate;
83 import org.osgi.service.component.annotations.Reference;
84 import org.osgi.service.component.annotations.RequireServiceComponentRuntime;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87
88 @Singleton
89 @Component(immediate = true, service = DOMRpcRouterServices.class)
90 @RequireServiceComponentRuntime
91 public final class DOMRpcRouter extends AbstractRegistration
92         implements DOMRpcRouterServices, EffectiveModelContextListener {
93     private static final Logger LOG = LoggerFactory.getLogger(DOMRpcRouter.class);
94     private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat(
95             "DOMRpcRouter-listener-%s").setDaemon(true).build();
96
97     private final ExecutorService listenerNotifier = Executors.newSingleThreadExecutor(THREAD_FACTORY);
98     private final @NonNull DOMActionProviderService actionProviderService = new ActionProviderServiceFacade();
99     private final @NonNull DOMActionService actionService = new ActionServiceFacade();
100     private final @NonNull DOMRpcProviderService rpcProviderService = new RpcProviderServiceFacade();
101     private final @NonNull DOMRpcService rpcService = new RpcServiceFacade();
102
103     @GuardedBy("this")
104     private Collection<Registration<?>> listeners = Collections.emptyList();
105
106     @GuardedBy("this")
107     private Collection<ActionRegistration<?>> actionListeners = Collections.emptyList();
108
109     private volatile DOMRpcRoutingTable routingTable = DOMRpcRoutingTable.EMPTY;
110
111     private volatile DOMActionRoutingTable actionRoutingTable = DOMActionRoutingTable.EMPTY;
112
113     private ListenerRegistration<?> listenerRegistration;
114
115     @Deprecated
116     @VisibleForTesting
117     // FIXME: 9.0.0: make this constructor package-private
118     public DOMRpcRouter() {
119
120     }
121
122     @Inject
123     @Activate
124     public DOMRpcRouter(@Reference final DOMSchemaService schemaService) {
125         listenerRegistration = schemaService.registerSchemaContextListener(this);
126         LOG.info("DOM RPC/Action router started");
127     }
128
129     @Deprecated(forRemoval = true)
130     public static DOMRpcRouter newInstance(final DOMSchemaService schemaService) {
131         return new DOMRpcRouter(schemaService);
132     }
133
134     @PreDestroy
135     @Deactivate
136     public void shutdown() {
137         close();
138     }
139
140     @Override
141     public DOMActionService getActionService() {
142         return actionService;
143     }
144
145     @Override
146     public DOMActionProviderService getActionProviderService() {
147         return actionProviderService;
148     }
149
150     @Override
151     public DOMRpcService getRpcService() {
152         return rpcService;
153     }
154
155     @Override
156     public DOMRpcProviderService getRpcProviderService() {
157         return rpcProviderService;
158     }
159
160     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
161             justification = "https://github.com/spotbugs/spotbugs/issues/811")
162     private synchronized void removeRpcImplementation(final DOMRpcImplementation implementation,
163             final Set<DOMRpcIdentifier> rpcs) {
164         final DOMRpcRoutingTable oldTable = routingTable;
165         final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.remove(implementation, rpcs);
166         routingTable = newTable;
167
168         listenerNotifier.execute(() -> notifyRemoved(newTable, implementation));
169     }
170
171     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
172             justification = "https://github.com/spotbugs/spotbugs/issues/811")
173     private synchronized void removeRpcImplementations(final Map<DOMRpcIdentifier, DOMRpcImplementation> map) {
174         final DOMRpcRoutingTable oldTable = routingTable;
175         final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.removeAll(map);
176         routingTable = newTable;
177
178         listenerNotifier.execute(() -> notifyRemoved(newTable, map.values()));
179     }
180
181     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
182             justification = "https://github.com/spotbugs/spotbugs/issues/811")
183     private synchronized void removeActionImplementation(final DOMActionImplementation implementation,
184             final Set<DOMActionInstance> actions) {
185         final DOMActionRoutingTable oldTable = actionRoutingTable;
186         final DOMActionRoutingTable newTable = (DOMActionRoutingTable) oldTable.remove(implementation, actions);
187         actionRoutingTable = newTable;
188
189         listenerNotifier.execute(() -> notifyActionChanged(newTable, implementation));
190     }
191
192     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
193             justification = "https://github.com/spotbugs/spotbugs/issues/811")
194     private synchronized void removeListener(final ListenerRegistration<? extends DOMRpcAvailabilityListener> reg) {
195         listeners = ImmutableList.copyOf(Collections2.filter(listeners, input -> !reg.equals(input)));
196     }
197
198     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
199             justification = "https://github.com/spotbugs/spotbugs/issues/811")
200     private synchronized void removeActionListener(final ListenerRegistration<? extends AvailabilityListener> reg) {
201         actionListeners = ImmutableList.copyOf(Collections2.filter(actionListeners, input -> !reg.equals(input)));
202     }
203
204     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
205             justification = "https://github.com/spotbugs/spotbugs/issues/811")
206     private synchronized void notifyAdded(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
207         for (Registration<?> l : listeners) {
208             l.addRpc(newTable, impl);
209         }
210     }
211
212     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
213             justification = "https://github.com/spotbugs/spotbugs/issues/811")
214     private synchronized void notifyAdded(final DOMRpcRoutingTable newTable,
215             final Collection<? extends DOMRpcImplementation> impls) {
216         for (Registration<?> l : listeners) {
217             for (DOMRpcImplementation impl : impls) {
218                 l.addRpc(newTable, impl);
219             }
220         }
221     }
222
223     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
224             justification = "https://github.com/spotbugs/spotbugs/issues/811")
225     private synchronized void notifyRemoved(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
226         for (Registration<?> l : listeners) {
227             l.removeRpc(newTable, impl);
228         }
229     }
230
231     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
232             justification = "https://github.com/spotbugs/spotbugs/issues/811")
233     private synchronized void notifyRemoved(final DOMRpcRoutingTable newTable,
234             final Collection<? extends DOMRpcImplementation> impls) {
235         for (Registration<?> l : listeners) {
236             for (DOMRpcImplementation impl : impls) {
237                 l.removeRpc(newTable, impl);
238             }
239         }
240     }
241
242     private synchronized void notifyActionChanged(final DOMActionRoutingTable newTable,
243             final DOMActionImplementation impl) {
244         for (ActionRegistration<?> l : actionListeners) {
245             l.actionChanged(newTable, impl);
246         }
247     }
248
249     @Override
250     public synchronized void onModelContextUpdated(final EffectiveModelContext newModelContext) {
251         final DOMRpcRoutingTable oldTable = routingTable;
252         final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.setSchemaContext(newModelContext);
253         routingTable = newTable;
254
255         final DOMActionRoutingTable oldActionTable = actionRoutingTable;
256         final DOMActionRoutingTable newActionTable =
257                 (DOMActionRoutingTable) oldActionTable.setSchemaContext(newModelContext);
258         actionRoutingTable = newActionTable;
259     }
260
261     @Override
262     protected void removeRegistration() {
263         if (listenerRegistration != null) {
264             listenerRegistration.close();
265             listenerRegistration = null;
266         }
267         listenerNotifier.shutdown();
268         LOG.info("DOM RPC/Action router stopped");
269     }
270
271     @VisibleForTesting
272     synchronized Collection<?> listeners() {
273         return listeners;
274     }
275
276     @VisibleForTesting
277     DOMRpcRoutingTable routingTable() {
278         return routingTable;
279     }
280
281     private static final class Registration<T extends DOMRpcAvailabilityListener>
282         extends AbstractListenerRegistration<T> {
283
284         private Map<QName, Set<YangInstanceIdentifier>> prevRpcs;
285         private DOMRpcRouter router;
286
287         Registration(final DOMRpcRouter router, final T listener, final Map<QName, Set<YangInstanceIdentifier>> rpcs) {
288             super(listener);
289             this.router = requireNonNull(router);
290             this.prevRpcs = requireNonNull(rpcs);
291         }
292
293         @Override
294         protected void removeRegistration() {
295             router.removeListener(this);
296             router = null;
297         }
298
299         void initialTable() {
300             final Collection<DOMRpcIdentifier> added = new ArrayList<>();
301             for (Entry<QName, Set<YangInstanceIdentifier>> e : prevRpcs.entrySet()) {
302                 added.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
303             }
304             if (!added.isEmpty()) {
305                 getInstance().onRpcAvailable(added);
306             }
307         }
308
309         void addRpc(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
310             final T l = getInstance();
311             if (!l.acceptsImplementation(impl)) {
312                 return;
313             }
314
315             final Map<QName, Set<YangInstanceIdentifier>> rpcs = verifyNotNull(newTable.getOperations(l));
316             final MapDifference<QName, Set<YangInstanceIdentifier>> diff = Maps.difference(prevRpcs, rpcs);
317
318             final Collection<DOMRpcIdentifier> added = new ArrayList<>();
319             for (Entry<QName, Set<YangInstanceIdentifier>> e : diff.entriesOnlyOnRight().entrySet()) {
320                 added.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
321             }
322             for (Entry<QName, ValueDifference<Set<YangInstanceIdentifier>>> e : diff.entriesDiffering().entrySet()) {
323                 for (YangInstanceIdentifier i : Sets.difference(e.getValue().rightValue(), e.getValue().leftValue())) {
324                     added.add(DOMRpcIdentifier.create(e.getKey(), i));
325                 }
326             }
327
328             prevRpcs = rpcs;
329             if (!added.isEmpty()) {
330                 l.onRpcAvailable(added);
331             }
332         }
333
334         void removeRpc(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
335             final T l = getInstance();
336             if (!l.acceptsImplementation(impl)) {
337                 return;
338             }
339
340             final Map<QName, Set<YangInstanceIdentifier>> rpcs = verifyNotNull(newTable.getOperations(l));
341             final MapDifference<QName, Set<YangInstanceIdentifier>> diff = Maps.difference(prevRpcs, rpcs);
342
343             final Collection<DOMRpcIdentifier> removed = new ArrayList<>();
344             for (Entry<QName, Set<YangInstanceIdentifier>> e : diff.entriesOnlyOnLeft().entrySet()) {
345                 removed.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
346             }
347             for (Entry<QName, ValueDifference<Set<YangInstanceIdentifier>>> e : diff.entriesDiffering().entrySet()) {
348                 for (YangInstanceIdentifier i : Sets.difference(e.getValue().leftValue(), e.getValue().rightValue())) {
349                     removed.add(DOMRpcIdentifier.create(e.getKey(), i));
350                 }
351             }
352
353             prevRpcs = rpcs;
354             if (!removed.isEmpty()) {
355                 l.onRpcUnavailable(removed);
356             }
357         }
358     }
359
360     private static final class ActionRegistration<T extends AvailabilityListener>
361         extends AbstractListenerRegistration<T> {
362
363         private Map<Absolute, Set<DOMDataTreeIdentifier>> prevActions;
364         private DOMRpcRouter router;
365
366         ActionRegistration(final DOMRpcRouter router, final T listener,
367                 final Map<Absolute, Set<DOMDataTreeIdentifier>> actions) {
368             super(listener);
369             this.router = requireNonNull(router);
370             this.prevActions = requireNonNull(actions);
371         }
372
373         @Override
374         protected void removeRegistration() {
375             router.removeActionListener(this);
376             router = null;
377         }
378
379         void initialTable() {
380             final Collection<DOMActionInstance> added = new ArrayList<>();
381             for (Entry<Absolute, Set<DOMDataTreeIdentifier>> e : prevActions.entrySet()) {
382                 added.addAll(Collections2.transform(e.getValue(), i -> DOMActionInstance.of(e.getKey(), i)));
383             }
384             if (!added.isEmpty()) {
385                 getInstance().onActionsChanged(ImmutableSet.of(), ImmutableSet.copyOf(added));
386             }
387         }
388
389         void actionChanged(final DOMActionRoutingTable newTable, final DOMActionImplementation impl) {
390             final T l = getInstance();
391             if (!l.acceptsImplementation(impl)) {
392                 return;
393             }
394
395             final Map<Absolute, Set<DOMDataTreeIdentifier>> actions = verifyNotNull(newTable.getOperations(l));
396             final MapDifference<Absolute, Set<DOMDataTreeIdentifier>> diff = Maps.difference(prevActions, actions);
397
398             final Set<DOMActionInstance> removed = new HashSet<>();
399             final Set<DOMActionInstance> added = new HashSet<>();
400
401             for (Entry<Absolute, Set<DOMDataTreeIdentifier>> e : diff.entriesOnlyOnLeft().entrySet()) {
402                 removed.addAll(Collections2.transform(e.getValue(), i -> DOMActionInstance.of(e.getKey(), i)));
403             }
404
405             for (Entry<Absolute, Set<DOMDataTreeIdentifier>> e : diff.entriesOnlyOnRight().entrySet()) {
406                 added.addAll(Collections2.transform(e.getValue(), i -> DOMActionInstance.of(e.getKey(), i)));
407             }
408
409             for (Entry<Absolute, ValueDifference<Set<DOMDataTreeIdentifier>>> e : diff.entriesDiffering().entrySet()) {
410                 for (DOMDataTreeIdentifier i : Sets.difference(e.getValue().leftValue(), e.getValue().rightValue())) {
411                     removed.add(DOMActionInstance.of(e.getKey(), i));
412                 }
413
414                 for (DOMDataTreeIdentifier i : Sets.difference(e.getValue().rightValue(), e.getValue().leftValue())) {
415                     added.add(DOMActionInstance.of(e.getKey(), i));
416                 }
417             }
418
419             prevActions = actions;
420             if (!removed.isEmpty() || !added.isEmpty()) {
421                 l.onActionsChanged(removed, added);
422             }
423         }
424     }
425
426     @NonNullByDefault
427     private final class ActionAvailabilityFacade implements DOMActionAvailabilityExtension {
428         @Override
429         public <T extends AvailabilityListener> ListenerRegistration<T> registerAvailabilityListener(final T listener) {
430             synchronized (DOMRpcRouter.this) {
431                 final ActionRegistration<T> ret = new ActionRegistration<>(DOMRpcRouter.this, listener,
432                     actionRoutingTable.getOperations(listener));
433                 actionListeners = ImmutableList.<ActionRegistration<?>>builder()
434                     .addAll(actionListeners)
435                     .add(ret)
436                     .build();
437
438                 listenerNotifier.execute(ret::initialTable);
439                 return ret;
440             }
441         }
442     }
443
444     @NonNullByDefault
445     private final class ActionServiceFacade implements DOMActionService {
446         private final ClassToInstanceMap<DOMActionServiceExtension> extensions = ImmutableClassToInstanceMap.of(
447             DOMActionAvailabilityExtension.class, new ActionAvailabilityFacade());
448
449         @Override
450         public ClassToInstanceMap<DOMActionServiceExtension> getExtensions() {
451             return extensions;
452         }
453
454         @Override
455         public ListenableFuture<? extends DOMActionResult> invokeAction(final Absolute type,
456                 final DOMDataTreeIdentifier path, final ContainerNode input) {
457             final YangInstanceIdentifier pathRoot = path.getRootIdentifier();
458             checkArgument(!pathRoot.isEmpty(), "Action path must not be empty");
459
460             final DOMActionRoutingTableEntry entry = (DOMActionRoutingTableEntry) actionRoutingTable.getEntry(type);
461             return entry != null ? OperationInvocation.invoke(entry, type, path, requireNonNull(input))
462                 : Futures.immediateFailedFuture(
463                     new DOMActionNotAvailableException("No implementation of Action %s available", type));
464         }
465     }
466
467     @NonNullByDefault
468     private final class ActionProviderServiceFacade implements DOMActionProviderService {
469         @Override
470         public <T extends DOMActionImplementation> ObjectRegistration<T> registerActionImplementation(
471                 final T implementation, final Set<DOMActionInstance> instances) {
472
473             synchronized (DOMRpcRouter.this) {
474                 final DOMActionRoutingTable oldTable = actionRoutingTable;
475                 final DOMActionRoutingTable newTable = (DOMActionRoutingTable) oldTable.add(implementation, instances);
476                 actionRoutingTable = newTable;
477
478                 listenerNotifier.execute(() -> notifyActionChanged(newTable, implementation));
479             }
480
481             return new AbstractObjectRegistration<>(implementation) {
482                 @Override
483                 protected void removeRegistration() {
484                     removeActionImplementation(getInstance(), instances);
485                 }
486             };
487         }
488     }
489
490     private final class RpcServiceFacade implements DOMRpcService {
491         @Override
492         public ListenableFuture<? extends DOMRpcResult> invokeRpc(final QName type, final NormalizedNode input) {
493             final AbstractDOMRpcRoutingTableEntry entry = (AbstractDOMRpcRoutingTableEntry) routingTable.getEntry(type);
494             if (entry == null) {
495                 return Futures.immediateFailedFuture(
496                     new DOMRpcImplementationNotAvailableException("No implementation of RPC %s available", type));
497             }
498
499             return OperationInvocation.invoke(entry, requireNonNull(input));
500         }
501
502         @Override
503         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(final T listener) {
504             synchronized (DOMRpcRouter.this) {
505                 final Registration<T> ret = new Registration<>(DOMRpcRouter.this, listener,
506                     routingTable.getOperations(listener));
507                 listeners = ImmutableList.<Registration<?>>builder().addAll(listeners).add(ret).build();
508
509                 listenerNotifier.execute(ret::initialTable);
510                 return ret;
511             }
512         }
513     }
514
515     private final class RpcProviderServiceFacade implements DOMRpcProviderService {
516         @Override
517         public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(
518                 final T implementation, final DOMRpcIdentifier... rpcs) {
519             return registerRpcImplementation(implementation, ImmutableSet.copyOf(rpcs));
520         }
521
522         @Override
523         public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(
524                 final T implementation, final Set<DOMRpcIdentifier> rpcs) {
525
526             synchronized (DOMRpcRouter.this) {
527                 final DOMRpcRoutingTable oldTable = routingTable;
528                 final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.add(implementation, rpcs);
529                 routingTable = newTable;
530
531                 listenerNotifier.execute(() -> notifyAdded(newTable, implementation));
532             }
533
534             return new AbstractDOMRpcImplementationRegistration<>(implementation) {
535                 @Override
536                 protected void removeRegistration() {
537                     removeRpcImplementation(getInstance(), rpcs);
538                 }
539             };
540         }
541
542         @Override
543         public org.opendaylight.yangtools.concepts.Registration registerRpcImplementations(
544                 final Map<DOMRpcIdentifier, DOMRpcImplementation> map) {
545             final ImmutableMap<DOMRpcIdentifier, DOMRpcImplementation> defensive = ImmutableMap.copyOf(map);
546             checkArgument(!map.isEmpty());
547
548             synchronized (DOMRpcRouter.this) {
549                 final DOMRpcRoutingTable oldTable = routingTable;
550                 final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.addAll(defensive);
551                 routingTable = newTable;
552
553                 listenerNotifier.execute(() -> notifyAdded(newTable, defensive.values()));
554             }
555
556             return new AbstractRegistration() {
557                 @Override
558                 protected void removeRegistration() {
559                     removeRpcImplementations(defensive);
560                 }
561             };
562         }
563     }
564
565     static final class OperationInvocation {
566         private static final Logger LOG = LoggerFactory.getLogger(OperationInvocation.class);
567
568         static ListenableFuture<? extends DOMActionResult> invoke(final DOMActionRoutingTableEntry entry,
569                 final Absolute type, final DOMDataTreeIdentifier path, final ContainerNode input) {
570             List<DOMActionImplementation> impls = entry.getImplementations(path);
571             if (impls == null) {
572                 impls = entry.getImplementations(
573                     new DOMDataTreeIdentifier(path.getDatastoreType(), YangInstanceIdentifier.empty()));
574                 if (impls == null) {
575                     return Futures.immediateFailedFuture(new DOMActionNotAvailableException(
576                         "No implementation of Action %s available for %s", type, path));
577                 }
578             }
579
580             return impls.get(0).invokeAction(type, path, input);
581         }
582
583         static ListenableFuture<? extends DOMRpcResult> invoke(final AbstractDOMRpcRoutingTableEntry entry,
584                 final NormalizedNode input) {
585             if (entry instanceof UnknownDOMRpcRoutingTableEntry) {
586                 return Futures.immediateFailedFuture(
587                     new DOMRpcImplementationNotAvailableException("%s is not resolved to an RPC", entry.getType()));
588             } else if (entry instanceof RoutedDOMRpcRoutingTableEntry) {
589                 return invokeRoutedRpc((RoutedDOMRpcRoutingTableEntry) entry, input);
590             } else if (entry instanceof GlobalDOMRpcRoutingTableEntry) {
591                 return invokeGlobalRpc((GlobalDOMRpcRoutingTableEntry) entry, input);
592             }
593
594             return Futures.immediateFailedFuture(
595                 new DOMRpcImplementationNotAvailableException("Unsupported RPC entry."));
596         }
597
598         private static ListenableFuture<? extends DOMRpcResult> invokeRoutedRpc(
599                 final RoutedDOMRpcRoutingTableEntry entry, final NormalizedNode input) {
600             final Optional<NormalizedNode> maybeKey = NormalizedNodes.findNode(input,
601                 entry.getRpcId().getContextReference());
602
603             // Routing key is present, attempt to deliver as a routed RPC
604             if (maybeKey.isPresent()) {
605                 final NormalizedNode key = maybeKey.get();
606                 final Object value = key.body();
607                 if (value instanceof YangInstanceIdentifier) {
608                     final YangInstanceIdentifier iid = (YangInstanceIdentifier) value;
609
610                     // Find a DOMRpcImplementation for a specific iid
611                     final List<DOMRpcImplementation> specificImpls = entry.getImplementations(iid);
612                     if (specificImpls != null) {
613                         return specificImpls.get(0)
614                             .invokeRpc(DOMRpcIdentifier.create(entry.getType(), iid), input);
615                     }
616
617                     LOG.debug("No implementation for context {} found will now look for wildcard id", iid);
618
619                     // Find a DOMRpcImplementation for a wild card. Usually remote-rpc-connector would register an
620                     // implementation this way
621                     final List<DOMRpcImplementation> mayBeRemoteImpls =
622                         entry.getImplementations(YangInstanceIdentifier.empty());
623
624                     if (mayBeRemoteImpls != null) {
625                         return mayBeRemoteImpls.get(0)
626                             .invokeRpc(DOMRpcIdentifier.create(entry.getType(), iid), input);
627                     }
628
629                 } else {
630                     LOG.warn("Ignoring wrong context value {}", value);
631                 }
632             }
633
634             final List<DOMRpcImplementation> impls = entry.getImplementations(null);
635             if (impls != null) {
636                 return impls.get(0).invokeRpc(entry.getRpcId(), input);
637             }
638
639             return Futures.immediateFailedFuture(
640                 new DOMRpcImplementationNotAvailableException("No implementation of RPC %s available",
641                     entry.getType()));
642         }
643
644         private static ListenableFuture<? extends DOMRpcResult> invokeGlobalRpc(
645                 final GlobalDOMRpcRoutingTableEntry entry, final NormalizedNode input) {
646             return entry.getImplementations(YangInstanceIdentifier.empty()).get(0).invokeRpc(entry.getRpcId(), input);
647         }
648     }
649 }