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