2 * Copyright (c) 2014 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.controller.sal.dom.broker.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
14 import java.util.concurrent.ConcurrentHashMap;
15 import java.util.concurrent.ConcurrentMap;
17 import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
18 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
19 import org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils;
20 import org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration;
21 import org.opendaylight.controller.sal.core.api.Broker.RpcRegistration;
22 import org.opendaylight.controller.sal.core.api.RoutedRpcDefaultImplementation;
23 import org.opendaylight.controller.sal.core.api.RpcImplementation;
24 import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
25 import org.opendaylight.controller.sal.core.api.RpcRoutingContext;
26 import org.opendaylight.controller.sal.dom.broker.spi.RpcRouter;
27 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
28 import org.opendaylight.yangtools.concepts.Identifiable;
29 import org.opendaylight.yangtools.concepts.ListenerRegistration;
30 import org.opendaylight.yangtools.concepts.util.ListenerRegistry;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.RpcResult;
33 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
34 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
36 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.Module;
39 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 import com.google.common.base.Optional;
46 import com.google.common.collect.FluentIterable;
47 import com.google.common.collect.ImmutableMap;
48 import com.google.common.collect.ImmutableSet;
49 import com.google.common.util.concurrent.ListenableFuture;
51 public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, RoutedRpcDefaultImplementation {
53 private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareRpcBroker.class);
55 private static final QName CONTEXT_REFERENCE = QName.create("urn:opendaylight:yang:extension:yang-ext",
56 "2013-07-09", "context-reference");
57 private final ListenerRegistry<RpcRegistrationListener> rpcRegistrationListeners = new ListenerRegistry<>();
58 private final ListenerRegistry<RouteChangeListener<RpcRoutingContext, InstanceIdentifier>> routeChangeListeners = new ListenerRegistry<>();
61 private final String identifier;
62 private final ConcurrentMap<QName, RpcImplementation> implementations = new ConcurrentHashMap<>();
63 private RpcImplementation defaultImplementation;
64 private SchemaContextProvider schemaProvider;
65 private RoutedRpcDefaultImplementation defaultDelegate;
67 public SchemaAwareRpcBroker(String identifier, SchemaContextProvider schemaProvider) {
69 this.identifier = identifier;
70 this.schemaProvider = schemaProvider;
73 public RpcImplementation getDefaultImplementation() {
74 return defaultImplementation;
77 public void setDefaultImplementation(RpcImplementation defaultImplementation) {
78 this.defaultImplementation = defaultImplementation;
81 public SchemaContextProvider getSchemaProvider() {
82 return schemaProvider;
85 public void setSchemaProvider(SchemaContextProvider schemaProvider) {
86 this.schemaProvider = schemaProvider;
89 public RoutedRpcDefaultImplementation getRoutedRpcDefaultDelegate() {
90 return defaultDelegate;
94 public void setRoutedRpcDefaultDelegate(RoutedRpcDefaultImplementation defaultDelegate) {
95 this.defaultDelegate = defaultDelegate;
99 public RoutedRpcRegistration addRoutedRpcImplementation(QName rpcType, RpcImplementation implementation) {
100 checkArgument(rpcType != null, "RPC Type should not be null");
101 checkArgument(implementation != null, "RPC Implementatoin should not be null");
102 return getOrCreateRoutedRpcRouter(rpcType).addRoutedRpcImplementation(rpcType, implementation);
105 private RoutedRpcSelector getOrCreateRoutedRpcRouter(QName rpcType) {
106 RoutedRpcSelector potential = getRoutedRpcRouter(rpcType);
107 if (potential != null) {
110 synchronized (implementations) {
111 potential = getRoutedRpcRouter(rpcType);
112 if (potential != null) {
115 RpcDefinition definition = findRpcDefinition(rpcType);
116 RoutingStrategy strategy = getRoutingStrategy(definition);
117 checkState(strategy instanceof RoutedRpcStrategy, "Rpc %s is not routed.", rpcType);
118 potential = new RoutedRpcSelector((RoutedRpcStrategy) strategy, this);
119 implementations.put(rpcType, potential);
124 private RoutedRpcSelector getRoutedRpcRouter(QName rpcType) {
125 RpcImplementation potential = implementations.get(rpcType);
126 if (potential != null) {
127 checkState(potential instanceof RoutedRpcSelector, "Rpc %s is not routed.", rpcType);
128 return (RoutedRpcSelector) potential;
135 public RpcRegistration addRpcImplementation(QName rpcType, RpcImplementation implementation)
136 throws IllegalArgumentException {
137 checkArgument(rpcType != null, "RPC Type should not be null");
138 checkArgument(implementation != null, "RPC Implementatoin should not be null");
139 checkState(!hasRpcImplementation(rpcType), "Implementation already registered");
140 RpcDefinition definition = findRpcDefinition(rpcType);
141 checkArgument(!isRoutedRpc(definition), "RPC Type must not be routed.");
142 GlobalRpcRegistration reg = new GlobalRpcRegistration(rpcType, implementation, this);
143 implementations.putIfAbsent(rpcType, implementation);
147 private boolean isRoutedRpc(RpcDefinition definition) {
148 return getRoutingStrategy(definition) instanceof RoutedRpcStrategy;
152 public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(RpcRegistrationListener listener) {
153 return rpcRegistrationListeners.register(listener);
157 public String getIdentifier() {
162 public Set<QName> getSupportedRpcs() {
163 return ImmutableSet.copyOf(implementations.keySet());
167 public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, CompositeNode input) {
168 return findRpcImplemention(rpc).invokeRpc(rpc, input);
171 private RpcImplementation findRpcImplemention(QName rpc) {
172 checkArgument(rpc != null, "Rpc name should not be null");
173 RpcImplementation potentialImpl = implementations.get(rpc);
174 if (potentialImpl != null) {
175 return potentialImpl;
178 potentialImpl = defaultImplementation;
179 if( potentialImpl == null ) {
180 throw new UnsupportedOperationException( "No implementation for this operation is available." );
183 return potentialImpl;
186 private boolean hasRpcImplementation(QName rpc) {
187 return implementations.containsKey(rpc);
190 private RpcDefinition findRpcDefinition(QName rpcType) {
191 checkArgument(rpcType != null, "Rpc name must be supplied.");
192 checkState(schemaProvider != null, "Schema Provider is not available.");
193 SchemaContext ctx = schemaProvider.getSchemaContext();
194 checkState(ctx != null, "YANG Schema Context is not available.");
195 Module module = ctx.findModuleByNamespaceAndRevision(rpcType.getNamespace(), rpcType.getRevision());
196 checkState(module != null, "YANG Module is not available.");
197 return findRpcDefinition(rpcType, module.getRpcs());
200 static private RpcDefinition findRpcDefinition(QName rpcType, Set<RpcDefinition> rpcs) {
201 checkState(rpcs != null, "Rpc schema is not available.");
202 for (RpcDefinition rpc : rpcs) {
203 if (rpcType.equals(rpc.getQName())) {
207 throw new IllegalArgumentException("Supplied Rpc Type is not defined.");
210 private RoutingStrategy getRoutingStrategy(RpcDefinition rpc) {
211 ContainerSchemaNode input = rpc.getInput();
213 for (DataSchemaNode schemaNode : input.getChildNodes()) {
214 Optional<QName> context = getRoutingContext(schemaNode);
215 if (context.isPresent()) {
216 return createRoutedStrategy(rpc, context.get(), schemaNode.getQName());
220 return createGlobalStrategy(rpc);
223 private static RoutingStrategy createRoutedStrategy(RpcDefinition rpc, QName context, QName leafNode) {
224 return new RoutedRpcStrategy(rpc.getQName(), context, leafNode);
227 private Optional<QName> getRoutingContext(DataSchemaNode schemaNode) {
228 for (UnknownSchemaNode extension : schemaNode.getUnknownSchemaNodes()) {
229 if (CONTEXT_REFERENCE.equals(extension.getNodeType())) {
230 return Optional.fromNullable(extension.getQName());
233 return Optional.absent();
236 private static RoutingStrategy createGlobalStrategy(RpcDefinition rpc) {
237 GlobalRpcStrategy ret = new GlobalRpcStrategy(rpc.getQName());
242 public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, InstanceIdentifier identifier, CompositeNode input) {
243 checkState(defaultDelegate != null);
244 return defaultDelegate.invokeRpc(rpc, identifier, input);
247 private static abstract class RoutingStrategy implements Identifiable<QName> {
249 private final QName identifier;
251 public RoutingStrategy(QName identifier) {
253 this.identifier = identifier;
257 public QName getIdentifier() {
262 private static class GlobalRpcStrategy extends RoutingStrategy {
264 public GlobalRpcStrategy(QName identifier) {
269 private static class RoutedRpcStrategy extends RoutingStrategy {
271 private final QName context;
272 private final QName leaf;
274 public RoutedRpcStrategy(QName identifier, QName ctx, QName leaf) {
280 public QName getContext() {
284 public QName getLeaf() {
289 private static class RoutedRpcSelector implements RpcImplementation, AutoCloseable, Identifiable<RpcRoutingContext> {
291 private final RoutedRpcStrategy strategy;
292 private final Set<QName> supportedRpcs;
293 private final RpcRoutingContext identifier;
294 private RpcImplementation defaultDelegate;
295 private final ConcurrentMap<InstanceIdentifier, RoutedRpcRegImpl> implementations = new ConcurrentHashMap<>();
296 private final SchemaAwareRpcBroker router;
298 public RoutedRpcSelector(RoutedRpcStrategy strategy, SchemaAwareRpcBroker router) {
300 this.strategy = strategy;
301 supportedRpcs = ImmutableSet.of(strategy.getIdentifier());
302 identifier = RpcRoutingContext.create(strategy.context, strategy.getIdentifier());
303 this.router = router;
307 public RpcRoutingContext getIdentifier() {
312 public void close() throws Exception {
317 public Set<QName> getSupportedRpcs() {
318 return supportedRpcs;
321 public RoutedRpcRegistration addRoutedRpcImplementation(QName rpcType, RpcImplementation implementation) {
322 return new RoutedRpcRegImpl(rpcType, implementation, this);
326 public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, CompositeNode input) {
327 CompositeNode inputContainer = input.getFirstCompositeByName(QName.create(rpc,"input"));
328 checkArgument(inputContainer != null, "Rpc payload must contain input element");
329 SimpleNode<?> routeContainer = inputContainer.getFirstSimpleByName(strategy.getLeaf());
330 checkArgument(routeContainer != null, "Leaf %s must be set with value", strategy.getLeaf());
331 Object route = routeContainer.getValue();
332 checkArgument(route instanceof InstanceIdentifier,
333 "The routed node %s is not an instance identifier", route);
334 RpcImplementation potential = null;
336 RoutedRpcRegImpl potentialReg = implementations.get(route);
337 if (potentialReg != null) {
338 potential = potentialReg.getInstance();
341 if (potential == null) {
342 return router.invokeRpc(rpc, (InstanceIdentifier) route, input);
344 checkState(potential != null, "No implementation is available for rpc:%s path:%s", rpc, route);
345 return potential.invokeRpc(rpc, input);
348 public void addPath(QName context, InstanceIdentifier path, RoutedRpcRegImpl routedRpcRegImpl) {
349 //checkArgument(strategy.getContext().equals(context),"Supplied context is not supported.");
350 RoutedRpcRegImpl previous = implementations.put(path, routedRpcRegImpl);
351 if (previous == null) {
352 router.notifyPathAnnouncement(context,strategy.getIdentifier(), path);
357 public void removePath(QName context, InstanceIdentifier path, RoutedRpcRegImpl routedRpcRegImpl) {
358 boolean removed = implementations.remove(path, routedRpcRegImpl);
360 router.notifyPathWithdrawal(context, strategy.getIdentifier(), path);
365 private static class GlobalRpcRegistration extends AbstractObjectRegistration<RpcImplementation> implements
367 private final QName type;
368 private SchemaAwareRpcBroker router;
370 public GlobalRpcRegistration(QName type, RpcImplementation instance, SchemaAwareRpcBroker router) {
373 this.router = router;
377 public QName getType() {
382 protected void removeRegistration() {
383 if (router != null) {
390 private static class RoutedRpcRegImpl extends AbstractObjectRegistration<RpcImplementation> implements
391 RoutedRpcRegistration {
393 private final QName type;
394 private final RoutedRpcSelector router;
396 public RoutedRpcRegImpl(QName rpcType, RpcImplementation implementation, RoutedRpcSelector routedRpcSelector) {
397 super(implementation);
399 router = routedRpcSelector;
403 public void registerPath(QName context, InstanceIdentifier path) {
404 router.addPath(context, path, this);
408 public void unregisterPath(QName context, InstanceIdentifier path) {
409 router.removePath(context, path, this);
413 protected void removeRegistration() {
418 public QName getType() {
424 private void remove(GlobalRpcRegistration registration) {
425 implementations.remove(registration.getType(), registration);
428 private void notifyPathAnnouncement(QName context, QName identifier, InstanceIdentifier path) {
429 RpcRoutingContext contextWrapped = RpcRoutingContext.create(context, identifier);
430 RouteChange<RpcRoutingContext, InstanceIdentifier> change = RoutingUtils.announcementChange(contextWrapped , path);
431 for(ListenerRegistration<RouteChangeListener<RpcRoutingContext, InstanceIdentifier>> routeListener : routeChangeListeners) {
433 routeListener.getInstance().onRouteChange(change);
434 } catch (Exception e) {
435 LOG.error("Unhandled exception during invoking onRouteChange for {}",routeListener.getInstance(),e);
444 private void notifyPathWithdrawal(QName context,QName identifier, InstanceIdentifier path) {
445 RpcRoutingContext contextWrapped = RpcRoutingContext.create(context, identifier);
446 RouteChange<RpcRoutingContext, InstanceIdentifier> change = RoutingUtils.removalChange(contextWrapped , path);
447 for(ListenerRegistration<RouteChangeListener<RpcRoutingContext, InstanceIdentifier>> routeListener : routeChangeListeners) {
449 routeListener.getInstance().onRouteChange(change);
450 } catch (Exception e) {
451 LOG.error("Unhandled exception during invoking onRouteChange for {}",routeListener.getInstance(),e);
457 public <L extends RouteChangeListener<RpcRoutingContext, InstanceIdentifier>> ListenerRegistration<L> registerRouteChangeListener(
459 ListenerRegistration<L> reg = routeChangeListeners.registerWithType(listener);
460 RouteChange<RpcRoutingContext, InstanceIdentifier> initial = createInitialRouteChange();
462 listener.onRouteChange(initial);
463 } catch (Exception e) {
464 LOG.error("Unhandled exception during sending initial route change event {} to {}",initial,listener, e);
469 private RouteChange<RpcRoutingContext, InstanceIdentifier> createInitialRouteChange() {
470 FluentIterable<RoutedRpcSelector> rpcSelectors = FluentIterable.from(implementations.values()).filter(RoutedRpcSelector.class);
473 ImmutableMap.Builder<RpcRoutingContext, Set<InstanceIdentifier>> announcements = ImmutableMap.builder();
474 ImmutableMap.Builder<RpcRoutingContext, Set<InstanceIdentifier>> removals = ImmutableMap.builder();
475 for (RoutedRpcSelector routedRpcSelector : rpcSelectors) {
476 final RpcRoutingContext context = routedRpcSelector.getIdentifier();
477 final Set<InstanceIdentifier> paths = ImmutableSet.copyOf(routedRpcSelector.implementations.keySet());
478 announcements.put(context, paths);
480 return RoutingUtils.change(announcements.build(), removals.build());