More defensive RPC handling in DOM Broker
[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 java.util.EventListener;
11 import java.util.Map;
12 import java.util.Map.Entry;
13 import java.util.HashMap;
14 import java.util.Set;
15 import java.util.WeakHashMap;
16
17 import javax.swing.tree.ExpandVetoException;
18
19 import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
20 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
21 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangePublisher;
22 import org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils;
23 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
24 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
25 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
26 import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
27 import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeGenerator;
28 import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeHelper;
29 import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
30 import org.opendaylight.controller.sal.binding.api.rpc.RpcContextIdentifier;
31 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
32 import org.opendaylight.yangtools.concepts.Identifiable;
33 import org.opendaylight.yangtools.concepts.ListenerRegistration;
34 import org.opendaylight.yangtools.concepts.util.ListenerRegistry;
35 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.binding.RpcService;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 import static com.google.common.base.Preconditions.*;
42
43 public class RpcProviderRegistryImpl implements //
44         RpcProviderRegistry, //
45         RouteChangePublisher<RpcContextIdentifier, InstanceIdentifier<?>> {
46
47     private RuntimeCodeGenerator rpcFactory = SingletonHolder.RPC_GENERATOR_IMPL;
48
49     private final Map<Class<? extends RpcService>, RpcService> publicProxies = new WeakHashMap<>();
50     private final Map<Class<? extends RpcService>, RpcRouter<?>> rpcRouters = new WeakHashMap<>();
51     private final ListenerRegistry<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> routeChangeListeners = ListenerRegistry
52             .create();
53     private final ListenerRegistry<RouterInstantiationListener> routerInstantiationListener = ListenerRegistry.create();
54
55     private final static Logger LOG = LoggerFactory.getLogger(RpcProviderRegistryImpl.class);
56
57     private final String name;
58
59     public String getName() {
60         return name;
61     }
62
63     public RpcProviderRegistryImpl(String name) {
64         super();
65         this.name = name;
66     }
67
68     @Override
69     public final <T extends RpcService> RoutedRpcRegistration<T> addRoutedRpcImplementation(Class<T> type,
70             T implementation) throws IllegalStateException {
71         return getRpcRouter(type).addRoutedRpcImplementation(implementation);
72     }
73
74     @Override
75     public final <T extends RpcService> RpcRegistration<T> addRpcImplementation(Class<T> type, T implementation)
76             throws IllegalStateException {
77         @SuppressWarnings("unchecked")
78         RpcRouter<T> potentialRouter = (RpcRouter<T>) rpcRouters.get(type);
79         if (potentialRouter != null) {
80             checkState(potentialRouter.getDefaultService() == null,
81                     "Default service for routed RPC already registered.");
82             return potentialRouter.registerDefaultService(implementation);
83         }
84         T publicProxy = getRpcService(type);
85         RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
86         checkState(currentDelegate == null, "Rpc service is already registered");
87         LOG.debug("Registering {} as global implementation of {} in {}", implementation, type.getSimpleName(), this);
88         RuntimeCodeHelper.setDelegate(publicProxy, implementation);
89         return new RpcProxyRegistration<T>(type, implementation, this);
90     }
91
92     @SuppressWarnings("unchecked")
93     @Override
94     public final <T extends RpcService> T getRpcService(Class<T> type) {
95
96         @SuppressWarnings("unchecked")
97         T potentialProxy = (T) publicProxies.get(type);
98         if (potentialProxy != null) {
99             return potentialProxy;
100         }
101         synchronized (this) {
102             /**
103              * Potential proxy could be instantiated by other thread while we
104              * were waiting for the lock.
105              */
106
107             potentialProxy = (T) publicProxies.get(type);
108             if (potentialProxy != null) {
109                 return (T) potentialProxy;
110             }
111             T proxy = rpcFactory.getDirectProxyFor(type);
112             LOG.debug("Created {} as public proxy for {} in {}", proxy, type.getSimpleName(), this);
113             publicProxies.put(type, proxy);
114             return proxy;
115         }
116     }
117
118     @SuppressWarnings("unchecked")
119     public <T extends RpcService> RpcRouter<T> getRpcRouter(Class<T> type) {
120         RpcRouter<?> potentialRouter = rpcRouters.get(type);
121         if (potentialRouter != null) {
122             return (RpcRouter<T>) potentialRouter;
123         }
124         synchronized (this) {
125             /**
126              * Potential Router could be instantiated by other thread while we
127              * were waiting for the lock.
128              */
129             potentialRouter = rpcRouters.get(type);
130             if (potentialRouter != null) {
131                 return (RpcRouter<T>) potentialRouter;
132             }
133             RpcRouter<T> router = rpcFactory.getRouterFor(type, name);
134             router.registerRouteChangeListener(new RouteChangeForwarder(type));
135             LOG.debug("Registering router {} as global implementation of {} in {}", router, type.getSimpleName(), this);
136             RuntimeCodeHelper.setDelegate(getRpcService(type), router.getInvocationProxy());
137             rpcRouters.put(type, router);
138             notifyListenersRoutedCreated(router);
139             return router;
140         }
141     }
142
143     private void notifyListenersRoutedCreated(RpcRouter router) {
144
145         for (ListenerRegistration<RouterInstantiationListener> listener : routerInstantiationListener) {
146             try {
147                 listener.getInstance().onRpcRouterCreated(router);
148             } catch (Exception e) {
149                 LOG.error("Unhandled exception during invoking listener {}", e);
150             }
151         }
152
153     }
154
155     public ListenerRegistration<RouterInstantiationListener> registerRouterInstantiationListener(
156             RouterInstantiationListener listener) {
157         ListenerRegistration<RouterInstantiationListener> reg = routerInstantiationListener.register(listener);
158         try {
159             for (RpcRouter<?> router : rpcRouters.values()) {
160                 listener.onRpcRouterCreated(router);
161             }
162         } catch (Exception e) {
163             LOG.error("Unhandled exception during invoking listener {}", e);
164         }
165         return reg;
166     }
167
168     @Override
169     public <L extends RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> ListenerRegistration<L> registerRouteChangeListener(
170             L listener) {
171         return (ListenerRegistration<L>) routeChangeListeners.register(listener);
172     }
173
174     public RuntimeCodeGenerator getRpcFactory() {
175         return rpcFactory;
176     }
177
178     public void setRpcFactory(RuntimeCodeGenerator rpcFactory) {
179         this.rpcFactory = rpcFactory;
180     }
181
182     public interface RouterInstantiationListener extends EventListener {
183         void onRpcRouterCreated(RpcRouter<?> router);
184     }
185
186     private class RouteChangeForwarder<T extends RpcService> implements
187             RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
188
189         private final Class<T> type;
190
191         public RouteChangeForwarder(Class<T> type) {
192             this.type = type;
193         }
194
195         @Override
196         public void onRouteChange(RouteChange<Class<? extends BaseIdentity>, InstanceIdentifier<?>> change) {
197             Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> announcements = new HashMap<>();
198             for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getAnnouncements()
199                     .entrySet()) {
200                 RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
201                 announcements.put(key, entry.getValue());
202             }
203             Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> removals = new HashMap<>();
204             for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getRemovals()
205                     .entrySet()) {
206                 RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
207                 removals.put(key, entry.getValue());
208             }
209             RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> toPublish = RoutingUtils
210                     .<RpcContextIdentifier, InstanceIdentifier<?>> change(announcements, removals);
211             for (ListenerRegistration<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> listener : routeChangeListeners) {
212                 try {
213                     listener.getInstance().onRouteChange(toPublish);
214                 } catch (Exception e) {
215                     e.printStackTrace();
216                 }
217             }
218         }
219     }
220
221     public static class RpcProxyRegistration<T extends RpcService> extends AbstractObjectRegistration<T> implements
222             RpcRegistration<T> {
223
224         private final Class<T> serviceType;
225         private RpcProviderRegistryImpl registry;
226
227         public RpcProxyRegistration(Class<T> type, T service, RpcProviderRegistryImpl registry) {
228             super(service);
229             serviceType = type;
230         }
231
232         @Override
233         public Class<T> getServiceType() {
234             return serviceType;
235         }
236
237         @Override
238         protected void removeRegistration() {
239             if (registry != null) {
240                 T publicProxy = registry.getRpcService(serviceType);
241                 RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
242                 if (currentDelegate == getInstance()) {
243                     RuntimeCodeHelper.setDelegate(publicProxy, null);
244                 }
245                 registry = null;
246             }
247         }
248     }
249 }