2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.dom.broker;
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.ClassToInstanceMap;
15 import com.google.common.collect.Collections2;
16 import com.google.common.collect.ImmutableClassToInstanceMap;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.ImmutableList.Builder;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.MapDifference;
21 import com.google.common.collect.MapDifference.ValueDifference;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Sets;
24 import com.google.common.util.concurrent.Futures;
25 import com.google.common.util.concurrent.ListenableFuture;
26 import com.google.common.util.concurrent.ThreadFactoryBuilder;
27 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.HashSet;
32 import java.util.List;
34 import java.util.Map.Entry;
35 import java.util.Optional;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ThreadFactory;
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.DOMActionProviderServiceExtension;
52 import org.opendaylight.mdsal.dom.api.DOMActionResult;
53 import org.opendaylight.mdsal.dom.api.DOMActionService;
54 import org.opendaylight.mdsal.dom.api.DOMActionServiceExtension;
55 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
56 import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
57 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
58 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
59 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
60 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationRegistration;
61 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
62 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
63 import org.opendaylight.mdsal.dom.api.DOMRpcService;
64 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
65 import org.opendaylight.mdsal.dom.spi.AbstractDOMRpcImplementationRegistration;
66 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
67 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
68 import org.opendaylight.yangtools.concepts.AbstractRegistration;
69 import org.opendaylight.yangtools.concepts.ListenerRegistration;
70 import org.opendaylight.yangtools.concepts.ObjectRegistration;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
72 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
75 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
76 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
77 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
82 public final class DOMRpcRouter extends AbstractRegistration
83 implements DOMRpcRouterServices, EffectiveModelContextListener {
84 private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat(
85 "DOMRpcRouter-listener-%s").setDaemon(true).build();
87 private final ExecutorService listenerNotifier = Executors.newSingleThreadExecutor(THREAD_FACTORY);
88 private final @NonNull DOMActionProviderService actionProviderService = new ActionProviderServiceFacade();
89 private final @NonNull DOMActionService actionService = new ActionServiceFacade();
90 private final @NonNull DOMRpcProviderService rpcProviderService = new RpcProviderServiceFacade();
91 private final @NonNull DOMRpcService rpcService = new RpcServiceFacade();
94 private Collection<Registration<?>> listeners = Collections.emptyList();
97 private Collection<ActionRegistration<?>> actionListeners = Collections.emptyList();
99 private volatile DOMRpcRoutingTable routingTable = DOMRpcRoutingTable.EMPTY;
101 private volatile DOMActionRoutingTable actionRoutingTable = DOMActionRoutingTable.EMPTY;
103 private ListenerRegistration<?> listenerRegistration;
106 public static DOMRpcRouter newInstance(final DOMSchemaService schemaService) {
107 final DOMRpcRouter rpcRouter = new DOMRpcRouter();
108 rpcRouter.listenerRegistration = schemaService.registerSchemaContextListener(rpcRouter);
113 public DOMActionService getActionService() {
114 return actionService;
118 public DOMActionProviderService getActionProviderService() {
119 return actionProviderService;
123 public DOMRpcService getRpcService() {
128 public DOMRpcProviderService getRpcProviderService() {
129 return rpcProviderService;
132 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
133 justification = "https://github.com/spotbugs/spotbugs/issues/811")
134 private synchronized void removeRpcImplementation(final DOMRpcImplementation implementation,
135 final Set<DOMRpcIdentifier> rpcs) {
136 final DOMRpcRoutingTable oldTable = routingTable;
137 final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.remove(implementation, rpcs);
138 routingTable = newTable;
140 listenerNotifier.execute(() -> notifyRemoved(newTable, implementation));
143 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
144 justification = "https://github.com/spotbugs/spotbugs/issues/811")
145 private synchronized void removeActionImplementation(final DOMActionImplementation implementation,
146 final Set<DOMActionInstance> actions) {
147 final DOMActionRoutingTable oldTable = actionRoutingTable;
148 final DOMActionRoutingTable newTable = (DOMActionRoutingTable) oldTable.remove(implementation, actions);
149 actionRoutingTable = newTable;
151 listenerNotifier.execute(() -> notifyActionChanged(newTable, implementation));
154 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
155 justification = "https://github.com/spotbugs/spotbugs/issues/811")
156 private synchronized void removeListener(final ListenerRegistration<? extends DOMRpcAvailabilityListener> reg) {
157 listeners = ImmutableList.copyOf(Collections2.filter(listeners, input -> !reg.equals(input)));
160 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
161 justification = "https://github.com/spotbugs/spotbugs/issues/811")
162 private synchronized void removeActionListener(final ListenerRegistration<? extends AvailabilityListener> reg) {
163 actionListeners = ImmutableList.copyOf(Collections2.filter(actionListeners, input -> !reg.equals(input)));
166 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
167 justification = "https://github.com/spotbugs/spotbugs/issues/811")
168 private synchronized void notifyAdded(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
169 for (Registration<?> l : listeners) {
170 l.addRpc(newTable, impl);
174 private synchronized void notifyRemoved(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
175 for (Registration<?> l : listeners) {
176 l.removeRpc(newTable, impl);
180 private synchronized void notifyActionChanged(final DOMActionRoutingTable newTable,
181 final DOMActionImplementation impl) {
182 for (ActionRegistration<?> l : actionListeners) {
183 l.actionChanged(newTable, impl);
188 public synchronized void onModelContextUpdated(final EffectiveModelContext newModelContext) {
189 final DOMRpcRoutingTable oldTable = routingTable;
190 final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.setSchemaContext(newModelContext);
191 routingTable = newTable;
193 final DOMActionRoutingTable oldActionTable = actionRoutingTable;
194 final DOMActionRoutingTable newActionTable =
195 (DOMActionRoutingTable) oldActionTable.setSchemaContext(newModelContext);
196 actionRoutingTable = newActionTable;
200 protected void removeRegistration() {
201 if (listenerRegistration != null) {
202 listenerRegistration.close();
203 listenerRegistration = null;
205 listenerNotifier.shutdown();
209 synchronized Collection<?> listeners() {
214 DOMRpcRoutingTable routingTable() {
218 private static final class Registration<T extends DOMRpcAvailabilityListener>
219 extends AbstractListenerRegistration<T> {
221 private Map<SchemaPath, Set<YangInstanceIdentifier>> prevRpcs;
222 private DOMRpcRouter router;
224 Registration(final DOMRpcRouter router, final T listener,
225 final Map<SchemaPath, Set<YangInstanceIdentifier>> rpcs) {
227 this.router = requireNonNull(router);
228 this.prevRpcs = requireNonNull(rpcs);
232 protected void removeRegistration() {
233 router.removeListener(this);
237 void initialTable() {
238 final Collection<DOMRpcIdentifier> added = new ArrayList<>();
239 for (Entry<SchemaPath, Set<YangInstanceIdentifier>> e : prevRpcs.entrySet()) {
240 added.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
242 if (!added.isEmpty()) {
243 getInstance().onRpcAvailable(added);
247 void addRpc(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
248 final T l = getInstance();
249 if (!l.acceptsImplementation(impl)) {
253 final Map<SchemaPath, Set<YangInstanceIdentifier>> rpcs = verifyNotNull(newTable.getOperations(l));
254 final MapDifference<SchemaPath, Set<YangInstanceIdentifier>> diff = Maps.difference(prevRpcs, rpcs);
256 final Collection<DOMRpcIdentifier> added = new ArrayList<>();
257 for (Entry<SchemaPath, Set<YangInstanceIdentifier>> e : diff.entriesOnlyOnRight().entrySet()) {
258 added.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
260 for (Entry<SchemaPath, ValueDifference<Set<YangInstanceIdentifier>>> e :
261 diff.entriesDiffering().entrySet()) {
262 for (YangInstanceIdentifier i : Sets.difference(e.getValue().rightValue(), e.getValue().leftValue())) {
263 added.add(DOMRpcIdentifier.create(e.getKey(), i));
268 if (!added.isEmpty()) {
269 l.onRpcAvailable(added);
273 void removeRpc(final DOMRpcRoutingTable newTable, final DOMRpcImplementation impl) {
274 final T l = getInstance();
275 if (!l.acceptsImplementation(impl)) {
279 final Map<SchemaPath, Set<YangInstanceIdentifier>> rpcs = verifyNotNull(newTable.getOperations(l));
280 final MapDifference<SchemaPath, Set<YangInstanceIdentifier>> diff = Maps.difference(prevRpcs, rpcs);
282 final Collection<DOMRpcIdentifier> removed = new ArrayList<>();
283 for (Entry<SchemaPath, Set<YangInstanceIdentifier>> e : diff.entriesOnlyOnLeft().entrySet()) {
284 removed.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
286 for (Entry<SchemaPath, ValueDifference<Set<YangInstanceIdentifier>>> e :
287 diff.entriesDiffering().entrySet()) {
288 for (YangInstanceIdentifier i : Sets.difference(e.getValue().leftValue(), e.getValue().rightValue())) {
289 removed.add(DOMRpcIdentifier.create(e.getKey(), i));
294 if (!removed.isEmpty()) {
295 l.onRpcUnavailable(removed);
300 private static final class ActionRegistration<T extends AvailabilityListener>
301 extends AbstractListenerRegistration<T> {
303 private Map<SchemaPath, Set<DOMDataTreeIdentifier>> prevActions;
304 private DOMRpcRouter router;
306 ActionRegistration(final DOMRpcRouter router, final T listener,
307 final Map<SchemaPath, Set<DOMDataTreeIdentifier>> actions) {
309 this.router = requireNonNull(router);
310 this.prevActions = requireNonNull(actions);
314 protected void removeRegistration() {
315 router.removeActionListener(this);
319 void initialTable() {
320 final Collection<DOMActionInstance> added = new ArrayList<>();
321 for (Entry<SchemaPath, Set<DOMDataTreeIdentifier>> e : prevActions.entrySet()) {
322 added.addAll(Collections2.transform(e.getValue(), i -> DOMActionInstance.of(e.getKey(), i)));
324 if (!added.isEmpty()) {
325 getInstance().onActionsChanged(ImmutableSet.of(), ImmutableSet.copyOf(added));
329 void actionChanged(final DOMActionRoutingTable newTable, final DOMActionImplementation impl) {
330 final T l = getInstance();
331 if (!l.acceptsImplementation(impl)) {
335 final Map<SchemaPath, Set<DOMDataTreeIdentifier>> actions = verifyNotNull(newTable.getOperations(l));
336 final MapDifference<SchemaPath, Set<DOMDataTreeIdentifier>> diff = Maps.difference(prevActions, actions);
338 final Set<DOMActionInstance> removed = new HashSet<>();
339 final Set<DOMActionInstance> added = new HashSet<>();
341 for (Entry<SchemaPath, Set<DOMDataTreeIdentifier>> e : diff.entriesOnlyOnLeft().entrySet()) {
342 removed.addAll(Collections2.transform(e.getValue(), i -> DOMActionInstance.of(e.getKey(), i)));
345 for (Entry<SchemaPath, Set<DOMDataTreeIdentifier>> e : diff.entriesOnlyOnRight().entrySet()) {
346 added.addAll(Collections2.transform(e.getValue(), i -> DOMActionInstance.of(e.getKey(), i)));
349 for (Entry<SchemaPath, ValueDifference<Set<DOMDataTreeIdentifier>>> e :
350 diff.entriesDiffering().entrySet()) {
351 for (DOMDataTreeIdentifier i : Sets.difference(e.getValue().leftValue(), e.getValue().rightValue())) {
352 removed.add(DOMActionInstance.of(e.getKey(), i));
355 for (DOMDataTreeIdentifier i : Sets.difference(e.getValue().rightValue(), e.getValue().leftValue())) {
356 added.add(DOMActionInstance.of(e.getKey(), i));
360 prevActions = actions;
361 if (!removed.isEmpty() || !added.isEmpty()) {
362 l.onActionsChanged(removed, added);
368 private final class ActionAvailabilityFacade implements DOMActionAvailabilityExtension {
370 public <T extends AvailabilityListener> ListenerRegistration<T> registerAvailabilityListener(final T listener) {
371 synchronized (DOMRpcRouter.this) {
372 final ActionRegistration<T> ret = new ActionRegistration<>(DOMRpcRouter.this,
373 listener, actionRoutingTable.getOperations(listener));
374 final Builder<ActionRegistration<?>> b = ImmutableList.builder();
375 b.addAll(actionListeners);
377 actionListeners = b.build();
379 listenerNotifier.execute(ret::initialTable);
386 private final class ActionServiceFacade implements DOMActionService {
387 private final ClassToInstanceMap<DOMActionServiceExtension> extensions = ImmutableClassToInstanceMap.of(
388 DOMActionAvailabilityExtension.class, new ActionAvailabilityFacade());
391 public ClassToInstanceMap<DOMActionServiceExtension> getExtensions() {
396 public ListenableFuture<? extends DOMActionResult> invokeAction(final SchemaPath type,
397 final DOMDataTreeIdentifier path, final ContainerNode input) {
398 final DOMActionRoutingTableEntry entry = (DOMActionRoutingTableEntry) actionRoutingTable.getEntry(type);
400 return Futures.immediateFailedFuture(
401 new DOMActionNotAvailableException("No implementation of Action %s available", type));
404 return OperationInvocation.invoke(entry, type, path, requireNonNull(input));
409 private final class ActionProviderServiceFacade implements DOMActionProviderService {
411 public ClassToInstanceMap<DOMActionProviderServiceExtension> getExtensions() {
412 return ImmutableClassToInstanceMap.of();
416 public <T extends DOMActionImplementation> ObjectRegistration<T> registerActionImplementation(
417 final T implementation, final Set<DOMActionInstance> instances) {
419 synchronized (DOMRpcRouter.this) {
420 final DOMActionRoutingTable oldTable = actionRoutingTable;
421 final DOMActionRoutingTable newTable = (DOMActionRoutingTable) oldTable.add(implementation, instances);
422 actionRoutingTable = newTable;
424 listenerNotifier.execute(() -> notifyActionChanged(newTable, implementation));
427 return new AbstractObjectRegistration<>(implementation) {
429 protected void removeRegistration() {
430 removeActionImplementation(getInstance(), instances);
436 private final class RpcServiceFacade implements DOMRpcService {
438 public ListenableFuture<? extends DOMRpcResult> invokeRpc(final SchemaPath type, final ContainerNode input) {
439 final AbstractDOMRpcRoutingTableEntry entry = (AbstractDOMRpcRoutingTableEntry) routingTable.getEntry(type);
441 return Futures.immediateFailedFuture(
442 new DOMRpcImplementationNotAvailableException("No implementation of RPC %s available", type));
445 return OperationInvocation.invoke(entry, requireNonNull(input));
449 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(final T listener) {
450 synchronized (DOMRpcRouter.this) {
451 final Registration<T> ret = new Registration<>(DOMRpcRouter.this, listener,
452 routingTable.getOperations(listener));
453 final Builder<Registration<?>> b = ImmutableList.builder();
456 listeners = b.build();
458 listenerNotifier.execute(ret::initialTable);
464 private final class RpcProviderServiceFacade implements DOMRpcProviderService {
466 public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(
467 final T implementation, final DOMRpcIdentifier... rpcs) {
468 return registerRpcImplementation(implementation, ImmutableSet.copyOf(rpcs));
472 public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(
473 final T implementation, final Set<DOMRpcIdentifier> rpcs) {
475 synchronized (DOMRpcRouter.this) {
476 final DOMRpcRoutingTable oldTable = routingTable;
477 final DOMRpcRoutingTable newTable = (DOMRpcRoutingTable) oldTable.add(implementation, rpcs);
478 routingTable = newTable;
480 listenerNotifier.execute(() -> notifyAdded(newTable, implementation));
483 return new AbstractDOMRpcImplementationRegistration<>(implementation) {
485 protected void removeRegistration() {
486 removeRpcImplementation(getInstance(), rpcs);
492 static final class OperationInvocation {
493 private static final Logger LOG = LoggerFactory.getLogger(OperationInvocation.class);
495 static ListenableFuture<? extends DOMActionResult> invoke(final DOMActionRoutingTableEntry entry,
496 final SchemaPath type, final DOMDataTreeIdentifier path, final ContainerNode input) {
497 return entry.getImplementations(path).get(0).invokeAction(type, path, input);
500 static ListenableFuture<? extends DOMRpcResult> invoke(final AbstractDOMRpcRoutingTableEntry entry,
501 final ContainerNode input) {
502 if (entry instanceof UnknownDOMRpcRoutingTableEntry) {
503 return Futures.immediateFailedFuture(
504 new DOMRpcImplementationNotAvailableException("SchemaPath %s is not resolved to an RPC",
506 } else if (entry instanceof RoutedDOMRpcRoutingTableEntry) {
507 return invokeRoutedRpc((RoutedDOMRpcRoutingTableEntry) entry, input);
508 } else if (entry instanceof GlobalDOMRpcRoutingTableEntry) {
509 return invokeGlobalRpc((GlobalDOMRpcRoutingTableEntry) entry, input);
512 return Futures.immediateFailedFuture(
513 new DOMRpcImplementationNotAvailableException("Unsupported RPC entry."));
516 private static ListenableFuture<? extends DOMRpcResult> invokeRoutedRpc(
517 final RoutedDOMRpcRoutingTableEntry entry, final ContainerNode input) {
518 final Optional<NormalizedNode<?, ?>> maybeKey = NormalizedNodes.findNode(input,
519 entry.getRpcId().getContextReference());
521 // Routing key is present, attempt to deliver as a routed RPC
522 if (maybeKey.isPresent()) {
523 final NormalizedNode<?, ?> key = maybeKey.get();
524 final Object value = key.getValue();
525 if (value instanceof YangInstanceIdentifier) {
526 final YangInstanceIdentifier iid = (YangInstanceIdentifier) value;
528 // Find a DOMRpcImplementation for a specific iid
529 final List<DOMRpcImplementation> specificImpls = entry.getImplementations(iid);
530 if (specificImpls != null) {
531 return specificImpls.get(0)
532 .invokeRpc(DOMRpcIdentifier.create(entry.getType(), iid), input);
535 LOG.debug("No implementation for context {} found will now look for wildcard id", iid);
537 // Find a DOMRpcImplementation for a wild card. Usually remote-rpc-connector would register an
538 // implementation this way
539 final List<DOMRpcImplementation> mayBeRemoteImpls =
540 entry.getImplementations(YangInstanceIdentifier.empty());
542 if (mayBeRemoteImpls != null) {
543 return mayBeRemoteImpls.get(0)
544 .invokeRpc(DOMRpcIdentifier.create(entry.getType(), iid), input);
548 LOG.warn("Ignoring wrong context value {}", value);
552 final List<DOMRpcImplementation> impls = entry.getImplementations(null);
554 return impls.get(0).invokeRpc(entry.getRpcId(), input);
557 return Futures.immediateFailedFuture(
558 new DOMRpcImplementationNotAvailableException("No implementation of RPC %s available",
562 private static ListenableFuture<? extends DOMRpcResult> invokeGlobalRpc(
563 final GlobalDOMRpcRoutingTableEntry entry, final ContainerNode input) {
564 return entry.getImplementations(YangInstanceIdentifier.empty()).get(0).invokeRpc(entry.getRpcId(), input);