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