2 * Copyright (c) 2013 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.binding.impl;
10 import static com.google.common.base.Preconditions.checkState;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Throwables;
13 import com.google.common.cache.Cache;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import com.google.common.util.concurrent.UncheckedExecutionException;
18 import java.util.EventListener;
19 import java.util.HashMap;
21 import java.util.Map.Entry;
23 import java.util.concurrent.Callable;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.atomic.AtomicBoolean;
26 import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
27 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
28 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangePublisher;
29 import org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils;
30 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
31 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
32 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
33 import org.opendaylight.controller.sal.binding.api.rpc.RpcContextIdentifier;
34 import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
35 import org.opendaylight.controller.sal.binding.codegen.RpcIsNotRoutedException;
36 import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeGenerator;
37 import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeHelper;
38 import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
39 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
40 import org.opendaylight.yangtools.concepts.ListenerRegistration;
41 import org.opendaylight.yangtools.util.ListenerRegistry;
42 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
44 import org.opendaylight.yangtools.yang.binding.RpcService;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 public class RpcProviderRegistryImpl implements RpcProviderRegistry, RouteChangePublisher<RpcContextIdentifier, InstanceIdentifier<?>> {
50 private RuntimeCodeGenerator rpcFactory = SingletonHolder.RPC_GENERATOR_IMPL;
52 // cache of proxy objects where each value in the map corresponds to a specific RpcService
53 private final LoadingCache<Class<? extends RpcService>, RpcService> publicProxies = CacheBuilder.newBuilder().weakKeys().
54 build(new CacheLoader<Class<? extends RpcService>, RpcService>() {
56 public RpcService load(final Class<? extends RpcService> type) {
57 final RpcService proxy = rpcFactory.getDirectProxyFor(type);
58 LOG.debug("Created {} as public proxy for {} in {}", proxy, type.getSimpleName(), this);
63 private final Cache<Class<? extends RpcService>, RpcRouter<?>> rpcRouters = CacheBuilder.newBuilder().weakKeys()
66 private final ListenerRegistry<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> routeChangeListeners = ListenerRegistry
68 private final ListenerRegistry<RouterInstantiationListener> routerInstantiationListener = ListenerRegistry.create();
70 private final static Logger LOG = LoggerFactory.getLogger(RpcProviderRegistryImpl.class);
72 private final String name;
74 private final ListenerRegistry<GlobalRpcRegistrationListener> globalRpcListeners = ListenerRegistry.create();
76 public String getName() {
80 public RpcProviderRegistryImpl(final String name) {
86 public final <T extends RpcService> RoutedRpcRegistration<T> addRoutedRpcImplementation(final Class<T> type,
87 final T implementation) throws IllegalStateException {
88 return getRpcRouter(type).addRoutedRpcImplementation(implementation);
92 public final <T extends RpcService> RpcRegistration<T> addRpcImplementation(final Class<T> type, final T implementation) {
94 // FIXME: This should be well documented - addRpcImplementation for
97 // Note: If RPC is really global, expected count of registrations
98 // of this method is really low.
99 RpcRouter<T> potentialRouter = getRpcRouter(type);
100 checkState(potentialRouter.getDefaultService() == null,
101 "Default service for routed RPC already registered.");
102 return potentialRouter.registerDefaultService(implementation);
103 } catch (RpcIsNotRoutedException e) {
104 // NOOP - we could safely continue, since RPC is not routed
105 // so we fallback to global routing.
106 LOG.debug("RPC is not routed. Using global registration.",e);
108 T publicProxy = getRpcService(type);
109 RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
110 checkState(currentDelegate == null, "Rpc service is already registered");
111 LOG.debug("Registering {} as global implementation of {} in {}", implementation, type.getSimpleName(), this);
112 RuntimeCodeHelper.setDelegate(publicProxy, implementation);
113 notifyGlobalRpcAdded(type);
114 return new RpcProxyRegistration<T>(type, implementation, this);
117 @SuppressWarnings("unchecked")
119 public final <T extends RpcService> T getRpcService(final Class<T> type) {
120 return (T) publicProxies.getUnchecked(type);
124 public <T extends RpcService> RpcRouter<T> getRpcRouter(final Class<T> type) {
126 final AtomicBoolean created = new AtomicBoolean(false);
127 @SuppressWarnings( "unchecked")
128 // LoadingCache is unsuitable for RpcRouter since we need to distinguish
129 // first creation of RPC Router, so that is why
130 // we are using normal cache with load API and shared AtomicBoolean
131 // for this call, which will be set to true if router was created.
132 RpcRouter<T> router = (RpcRouter<T>) rpcRouters.get(type,new Callable<RpcRouter<?>>() {
135 public org.opendaylight.controller.sal.binding.api.rpc.RpcRouter<?> call() {
136 RpcRouter<?> router = rpcFactory.getRouterFor(type, name);
137 router.registerRouteChangeListener(new RouteChangeForwarder<T>(type));
138 LOG.debug("Registering router {} as global implementation of {} in {}", router, type.getSimpleName(), this);
139 RuntimeCodeHelper.setDelegate(getRpcService(type), router.getInvocationProxy());
145 notifyListenersRoutedCreated(router);
148 } catch (ExecutionException | UncheckedExecutionException e) {
149 // We rethrow Runtime Exceptions which were wrapped by
150 // Execution Exceptions
151 // otherwise we throw IllegalStateException with original
152 Throwables.propagateIfPossible(e.getCause());
153 throw new IllegalStateException("Could not load RPC Router for "+type.getName(),e);
157 private void notifyGlobalRpcAdded(final Class<? extends RpcService> type) {
158 for(ListenerRegistration<GlobalRpcRegistrationListener> listener : globalRpcListeners) {
160 listener.getInstance().onGlobalRpcRegistered(type);
161 } catch (Exception e) {
162 LOG.error("Unhandled exception during invoking listener {}", e);
168 private void notifyListenersRoutedCreated(final RpcRouter<?> router) {
170 for (ListenerRegistration<RouterInstantiationListener> listener : routerInstantiationListener) {
172 listener.getInstance().onRpcRouterCreated(router);
173 } catch (Exception e) {
174 LOG.error("Unhandled exception during invoking listener {}", e);
180 public ListenerRegistration<RouterInstantiationListener> registerRouterInstantiationListener(
181 final RouterInstantiationListener listener) {
182 ListenerRegistration<RouterInstantiationListener> reg = routerInstantiationListener.register(listener);
184 for (RpcRouter<?> router : rpcRouters.asMap().values()) {
185 listener.onRpcRouterCreated(router);
187 } catch (Exception e) {
188 LOG.error("Unhandled exception during invoking listener {}", e);
193 @SuppressWarnings("unchecked")
195 public <L extends RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> ListenerRegistration<L> registerRouteChangeListener(
197 return (ListenerRegistration<L>) routeChangeListeners.register(listener);
200 public RuntimeCodeGenerator getRpcFactory() {
204 public void setRpcFactory(final RuntimeCodeGenerator rpcFactory) {
205 this.rpcFactory = rpcFactory;
208 public interface RouterInstantiationListener extends EventListener {
209 void onRpcRouterCreated(RpcRouter<?> router);
212 public ListenerRegistration<GlobalRpcRegistrationListener> registerGlobalRpcRegistrationListener(final GlobalRpcRegistrationListener listener) {
213 return globalRpcListeners.register(listener);
216 public interface GlobalRpcRegistrationListener extends EventListener {
217 void onGlobalRpcRegistered(Class<? extends RpcService> cls);
218 void onGlobalRpcUnregistered(Class<? extends RpcService> cls);
222 private final class RouteChangeForwarder<T extends RpcService> implements RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
223 private final Class<T> type;
225 RouteChangeForwarder(final Class<T> type) {
230 public void onRouteChange(final RouteChange<Class<? extends BaseIdentity>, InstanceIdentifier<?>> change) {
231 Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> announcements = new HashMap<>();
232 for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getAnnouncements()
234 RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
235 announcements.put(key, entry.getValue());
237 Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> removals = new HashMap<>();
238 for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getRemovals()
240 RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
241 removals.put(key, entry.getValue());
243 RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> toPublish = RoutingUtils
244 .<RpcContextIdentifier, InstanceIdentifier<?>> change(announcements, removals);
245 for (ListenerRegistration<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> listener : routeChangeListeners) {
247 listener.getInstance().onRouteChange(toPublish);
248 } catch (Exception e) {
249 LOG.error("Unhandled exception during invoking listener",listener.getInstance(),e);
255 private static final class RpcProxyRegistration<T extends RpcService> extends AbstractObjectRegistration<T> implements RpcRegistration<T> {
256 private final RpcProviderRegistryImpl registry;
257 private final Class<T> serviceType;
259 RpcProxyRegistration(final Class<T> type, final T service, final RpcProviderRegistryImpl registry) {
261 this.registry = Preconditions.checkNotNull(registry);
262 this.serviceType = type;
266 public Class<T> getServiceType() {
271 protected void removeRegistration() {
272 T publicProxy = registry.getRpcService(serviceType);
273 RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
274 if (currentDelegate == getInstance()) {
275 RuntimeCodeHelper.setDelegate(publicProxy, null);