Fix context chain closing
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / rpc / RpcContextImpl.java
1 /**
2  * Copyright (c) 2015 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.openflowplugin.impl.rpc;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Function;
12 import com.google.common.collect.Iterators;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import java.util.Iterator;
16 import java.util.Map.Entry;
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.ConcurrentMap;
19 import java.util.concurrent.Semaphore;
20 import javax.annotation.Nonnull;
21 import javax.annotation.Nullable;
22 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
23 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
24 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
25 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
26 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
27 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
28 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
29 import org.opendaylight.openflowplugin.api.openflow.lifecycle.ContextChainMastershipState;
30 import org.opendaylight.openflowplugin.api.openflow.lifecycle.MastershipChangeListener;
31 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
32 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
33 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
34 import org.opendaylight.openflowplugin.impl.util.MdSalRegistrationUtils;
35 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContext;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
39 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.binding.RpcService;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 class RpcContextImpl implements RpcContext {
45     private static final Logger LOG = LoggerFactory.getLogger(RpcContextImpl.class);
46     private final RpcProviderRegistry rpcProviderRegistry;
47     private final MessageSpy messageSpy;
48     private final Semaphore tracker;
49     private boolean isStatisticsRpcEnabled;
50
51     // TODO: add private Sal salBroker
52     private final ConcurrentMap<Class<?>, RoutedRpcRegistration<?>> rpcRegistrations = new ConcurrentHashMap<>();
53     private final KeyedInstanceIdentifier<Node, NodeKey> nodeInstanceIdentifier;
54     private volatile ContextState state = ContextState.INITIALIZATION;
55     private final DeviceInfo deviceInfo;
56     private final DeviceContext deviceContext;
57     private final ExtensionConverterProvider extensionConverterProvider;
58     private final ConvertorExecutor convertorExecutor;
59     private final NotificationPublishService notificationPublishService;
60
61     RpcContextImpl(@Nonnull final RpcProviderRegistry rpcProviderRegistry,
62                    final int maxRequests,
63                    @Nonnull final DeviceContext deviceContext,
64                    @Nonnull final ExtensionConverterProvider extensionConverterProvider,
65                    @Nonnull final ConvertorExecutor convertorExecutor,
66                    @Nonnull final NotificationPublishService notificationPublishService,
67                    boolean statisticsRpcEnabled) {
68         this.deviceContext = deviceContext;
69         this.deviceInfo = deviceContext.getDeviceInfo();
70         this.nodeInstanceIdentifier = deviceContext.getDeviceInfo().getNodeInstanceIdentifier();
71         this.messageSpy = deviceContext.getMessageSpy();
72         this.rpcProviderRegistry = rpcProviderRegistry;
73         this.extensionConverterProvider = extensionConverterProvider;
74         this.notificationPublishService = notificationPublishService;
75         this.convertorExecutor = convertorExecutor;
76         this.isStatisticsRpcEnabled = statisticsRpcEnabled;
77         this.tracker = new Semaphore(maxRequests, true);
78     }
79
80     /**
81      * @see org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext#registerRpcServiceImplementation(java.lang.Class,
82      * org.opendaylight.yangtools.yang.binding.RpcService)
83      */
84     @Override
85     public <S extends RpcService> void registerRpcServiceImplementation(final Class<S> serviceClass,
86                                                                         final S serviceInstance) {
87         if (! rpcRegistrations.containsKey(serviceClass)) {
88             final RoutedRpcRegistration<S> routedRpcReg = rpcProviderRegistry.addRoutedRpcImplementation(serviceClass, serviceInstance);
89             routedRpcReg.registerPath(NodeContext.class, nodeInstanceIdentifier);
90             rpcRegistrations.put(serviceClass, routedRpcReg);
91             if (LOG.isDebugEnabled()) {
92                 LOG.debug("Registration of service {} for device {}.",
93                         serviceClass.getSimpleName(),
94                         nodeInstanceIdentifier.getKey().getId().getValue());
95             }
96         }
97     }
98
99     @Override
100     public <S extends RpcService> S lookupRpcService(final Class<S> serviceClass) {
101         RoutedRpcRegistration<?> registration = rpcRegistrations.get(serviceClass);
102         final RpcService rpcService = registration.getInstance();
103         return (S) rpcService;
104     }
105
106     /**
107      * Unregisters all services.
108      *
109      * @see java.lang.AutoCloseable#close()
110      */
111     @Override
112     public void close() {
113         if (ContextState.TERMINATION.equals(state)) {
114             if (LOG.isDebugEnabled()) {
115                 LOG.debug("RpcContext for node {} is already in TERMINATION state.", getDeviceInfo().getLOGValue());
116             }
117         } else {
118             this.state = ContextState.TERMINATION;
119             unregisterRPCs();
120         }
121     }
122
123     private void unregisterRPCs() {
124         for (final Iterator<Entry<Class<?>, RoutedRpcRegistration<?>>> iterator = Iterators
125                 .consumingIterator(rpcRegistrations.entrySet().iterator()); iterator.hasNext(); ) {
126             final RoutedRpcRegistration<?> rpcRegistration = iterator.next().getValue();
127             rpcRegistration.unregisterPath(NodeContext.class, nodeInstanceIdentifier);
128             rpcRegistration.close();
129
130             if (LOG.isDebugEnabled()) {
131                 LOG.debug("Closing RPC Registration of service {} for device {}.", rpcRegistration.getServiceType().getSimpleName(),
132                         nodeInstanceIdentifier.getKey().getId().getValue());
133             }
134         }
135     }
136
137     @Override
138     public <T> RequestContext<T> createRequestContext() {
139         if (!tracker.tryAcquire()) {
140             LOG.trace("Device queue {} at capacity", this);
141             return null;
142         } else {
143             LOG.trace("Acquired semaphore for {}, available permits:{} ", nodeInstanceIdentifier.getKey().getId().getValue(), tracker.availablePermits());
144         }
145
146         final Long xid = deviceInfo.reserveXidForDeviceMessage();
147         if (xid == null) {
148             LOG.warn("Xid cannot be reserved for new RequestContext, node:{}", nodeInstanceIdentifier.getKey().getId().getValue());
149             tracker.release();
150             return null;
151         }
152
153         return new AbstractRequestContext<T>(xid) {
154             @Override
155             public void close() {
156                 tracker.release();
157                 final long xid = getXid().getValue();
158                 LOG.trace("Removed request context with xid {}", xid);
159                 messageSpy.spyMessage(RpcContextImpl.class, MessageSpy.StatisticsGroup.REQUEST_STACK_FREED);
160             }
161         };
162     }
163
164     @Override
165     public <S extends RpcService> void unregisterRpcServiceImplementation(final Class<S> serviceClass) {
166         LOG.trace("Try to unregister serviceClass {} for Node {}", serviceClass, nodeInstanceIdentifier.getKey().getId());
167         final RoutedRpcRegistration<?> rpcRegistration = rpcRegistrations.remove(serviceClass);
168         if (rpcRegistration != null) {
169             rpcRegistration.unregisterPath(NodeContext.class, nodeInstanceIdentifier);
170             rpcRegistration.close();
171             LOG.debug("Un-registration serviceClass {} for Node {}", serviceClass.getSimpleName(), nodeInstanceIdentifier.getKey().getId().getValue());
172         }
173     }
174
175     @VisibleForTesting
176     boolean isEmptyRpcRegistrations() {
177         return this.rpcRegistrations.isEmpty();
178     }
179
180     @Override
181     public ServiceGroupIdentifier getServiceIdentifier() {
182         return this.deviceInfo.getServiceIdentifier();
183     }
184
185     @Override
186     public DeviceInfo getDeviceInfo() {
187         return this.deviceInfo;
188     }
189
190     @Override
191     public ListenableFuture<Void> stopClusterServices() {
192         if (ContextState.TERMINATION.equals(this.state)) {
193             return Futures.immediateCancelledFuture();
194         }
195
196         return Futures.transform(Futures.immediateFuture(null), new Function<Object, Void>() {
197             @Nullable
198             @Override
199             public Void apply(@Nullable Object input) {
200                 unregisterRPCs();
201                 return null;
202             }
203         });
204     }
205
206     @Override
207     public boolean onContextInstantiateService(final MastershipChangeListener mastershipChangeListener) {
208         LOG.info("Starting rpc context cluster services for node {}", deviceInfo.getLOGValue());
209         MdSalRegistrationUtils.registerServices(this, deviceContext, extensionConverterProvider, convertorExecutor);
210
211         if (isStatisticsRpcEnabled && !deviceContext.canUseSingleLayerSerialization()) {
212             MdSalRegistrationUtils.registerStatCompatibilityServices(
213                     this,
214                     deviceContext,
215                     notificationPublishService,
216                     convertorExecutor);
217         }
218
219         mastershipChangeListener.onMasterRoleAcquired(deviceInfo, ContextChainMastershipState.RPC_REGISTRATION);
220         return true;
221     }
222 }