Merge "BUG-2288: DOMNotification API"
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / impl / RpcProviderRegistryImpl.java
1 /*
2  * Copyright (c) 2013 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.controller.sal.binding.impl;
9
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;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Set;
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;
47
48 public class RpcProviderRegistryImpl implements RpcProviderRegistry, RouteChangePublisher<RpcContextIdentifier, InstanceIdentifier<?>> {
49
50     private RuntimeCodeGenerator rpcFactory = SingletonHolder.RPC_GENERATOR_IMPL;
51
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>() {
55                 @Override
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);
59                     return proxy;
60                 }
61             });
62
63     private final Cache<Class<? extends RpcService>, RpcRouter<?>> rpcRouters = CacheBuilder.newBuilder().weakKeys()
64             .build();
65
66     private final ListenerRegistry<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> routeChangeListeners = ListenerRegistry
67             .create();
68     private final ListenerRegistry<RouterInstantiationListener> routerInstantiationListener = ListenerRegistry.create();
69
70     private final static Logger LOG = LoggerFactory.getLogger(RpcProviderRegistryImpl.class);
71
72     private final String name;
73
74     private final ListenerRegistry<GlobalRpcRegistrationListener> globalRpcListeners = ListenerRegistry.create();
75
76     public String getName() {
77         return name;
78     }
79
80     public RpcProviderRegistryImpl(final String name) {
81         super();
82         this.name = name;
83     }
84
85     @Override
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);
89     }
90
91     @Override
92     public final <T extends RpcService> RpcRegistration<T> addRpcImplementation(final Class<T> type, final T implementation) {
93
94         // FIXME: This should be well documented - addRpcImplementation for
95         // routed RPCs
96         try {
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);
107         }
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);
115     }
116
117     @SuppressWarnings("unchecked")
118     @Override
119     public final <T extends RpcService> T getRpcService(final Class<T> type) {
120         return (T) publicProxies.getUnchecked(type);
121     }
122
123
124     public <T extends RpcService> RpcRouter<T> getRpcRouter(final Class<T> type) {
125         try {
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<?>>() {
133
134                 @Override
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());
140                     created.set(true);
141                     return router;
142                 }
143             });
144             if(created.get()) {
145                 notifyListenersRoutedCreated(router);
146             }
147             return 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);
154         }
155     }
156
157     private void notifyGlobalRpcAdded(final Class<? extends RpcService> type) {
158         for(ListenerRegistration<GlobalRpcRegistrationListener> listener : globalRpcListeners) {
159             try {
160                 listener.getInstance().onGlobalRpcRegistered(type);
161             } catch (Exception e) {
162                 LOG.error("Unhandled exception during invoking listener {}", e);
163             }
164         }
165
166     }
167
168     private void notifyListenersRoutedCreated(final RpcRouter<?> router) {
169
170         for (ListenerRegistration<RouterInstantiationListener> listener : routerInstantiationListener) {
171             try {
172                 listener.getInstance().onRpcRouterCreated(router);
173             } catch (Exception e) {
174                 LOG.error("Unhandled exception during invoking listener {}", e);
175             }
176         }
177
178     }
179
180     public ListenerRegistration<RouterInstantiationListener> registerRouterInstantiationListener(
181             final RouterInstantiationListener listener) {
182         ListenerRegistration<RouterInstantiationListener> reg = routerInstantiationListener.register(listener);
183         try {
184             for (RpcRouter<?> router : rpcRouters.asMap().values()) {
185                 listener.onRpcRouterCreated(router);
186             }
187         } catch (Exception e) {
188             LOG.error("Unhandled exception during invoking listener {}", e);
189         }
190         return reg;
191     }
192
193     @SuppressWarnings("unchecked")
194     @Override
195     public <L extends RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> ListenerRegistration<L> registerRouteChangeListener(
196             final L listener) {
197         return (ListenerRegistration<L>) routeChangeListeners.register(listener);
198     }
199
200     public RuntimeCodeGenerator getRpcFactory() {
201         return rpcFactory;
202     }
203
204     public void setRpcFactory(final RuntimeCodeGenerator rpcFactory) {
205         this.rpcFactory = rpcFactory;
206     }
207
208     public interface RouterInstantiationListener extends EventListener {
209         void onRpcRouterCreated(RpcRouter<?> router);
210     }
211
212     public ListenerRegistration<GlobalRpcRegistrationListener> registerGlobalRpcRegistrationListener(final GlobalRpcRegistrationListener listener) {
213         return globalRpcListeners.register(listener);
214     }
215
216     public interface GlobalRpcRegistrationListener extends EventListener {
217         void onGlobalRpcRegistered(Class<? extends RpcService> cls);
218         void onGlobalRpcUnregistered(Class<? extends RpcService> cls);
219
220     }
221
222     private final class RouteChangeForwarder<T extends RpcService> implements RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
223         private final Class<T> type;
224
225         RouteChangeForwarder(final Class<T> type) {
226             this.type = type;
227         }
228
229         @Override
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()
233                     .entrySet()) {
234                 RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
235                 announcements.put(key, entry.getValue());
236             }
237             Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> removals = new HashMap<>();
238             for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getRemovals()
239                     .entrySet()) {
240                 RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
241                 removals.put(key, entry.getValue());
242             }
243             RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> toPublish = RoutingUtils
244                     .<RpcContextIdentifier, InstanceIdentifier<?>> change(announcements, removals);
245             for (ListenerRegistration<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> listener : routeChangeListeners) {
246                 try {
247                     listener.getInstance().onRouteChange(toPublish);
248                 } catch (Exception e) {
249                     LOG.error("Unhandled exception during invoking listener",listener.getInstance(),e);
250                 }
251             }
252         }
253     }
254
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;
258
259         RpcProxyRegistration(final Class<T> type, final T service, final RpcProviderRegistryImpl registry) {
260             super(service);
261             this.registry =  Preconditions.checkNotNull(registry);
262             this.serviceType = type;
263         }
264
265         @Override
266         public Class<T> getServiceType() {
267             return serviceType;
268         }
269
270         @Override
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);
276             }
277         }
278     }
279 }