Bump odlparent to 5.0.0
[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.ImmutableSet;
13 import com.google.common.collect.Iterators;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import java.util.Iterator;
18 import java.util.Map.Entry;
19 import java.util.concurrent.ConcurrentHashMap;
20 import java.util.concurrent.ConcurrentMap;
21 import java.util.concurrent.Semaphore;
22 import javax.annotation.Nonnull;
23 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
24 import org.opendaylight.mdsal.binding.api.RpcProviderService;
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.ContextChainMastershipWatcher;
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.nodes.Node;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
38 import org.opendaylight.yangtools.concepts.ObjectRegistration;
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 RpcProviderService rpcProviderRegistry;
47     private final MessageSpy messageSpy;
48     private final Semaphore tracker;
49     private final boolean isStatisticsRpcEnabled;
50
51     // TODO: add private Sal salBroker
52     private final ConcurrentMap<Class<?>, ObjectRegistration<? extends RpcService>> rpcRegistrations =
53             new ConcurrentHashMap<>();
54     private final KeyedInstanceIdentifier<Node, NodeKey> nodeInstanceIdentifier;
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     private ContextChainMastershipWatcher contextChainMastershipWatcher;
61
62     RpcContextImpl(@Nonnull final RpcProviderService rpcProviderRegistry,
63                    final int maxRequests,
64                    @Nonnull final DeviceContext deviceContext,
65                    @Nonnull final ExtensionConverterProvider extensionConverterProvider,
66                    @Nonnull final ConvertorExecutor convertorExecutor,
67                    @Nonnull final NotificationPublishService notificationPublishService,
68                    boolean statisticsRpcEnabled) {
69         this.deviceContext = deviceContext;
70         this.deviceInfo = deviceContext.getDeviceInfo();
71         this.nodeInstanceIdentifier = deviceContext.getDeviceInfo().getNodeInstanceIdentifier();
72         this.messageSpy = deviceContext.getMessageSpy();
73         this.rpcProviderRegistry = rpcProviderRegistry;
74         this.extensionConverterProvider = extensionConverterProvider;
75         this.notificationPublishService = notificationPublishService;
76         this.convertorExecutor = convertorExecutor;
77         this.isStatisticsRpcEnabled = statisticsRpcEnabled;
78         this.tracker = new Semaphore(maxRequests, true);
79     }
80
81     @Override
82     public <S extends RpcService> void registerRpcServiceImplementation(final Class<S> serviceClass,
83                                                                         final S serviceInstance) {
84         if (!rpcRegistrations.containsKey(serviceClass)) {
85             final ObjectRegistration<S> routedRpcReg = rpcProviderRegistry.registerRpcImplementation(serviceClass,
86                 serviceInstance, ImmutableSet.of(nodeInstanceIdentifier));
87             rpcRegistrations.put(serviceClass, routedRpcReg);
88             if (LOG.isDebugEnabled()) {
89                 LOG.debug("Registration of service {} for device {}.",
90                         serviceClass.getSimpleName(),
91                         nodeInstanceIdentifier.getKey().getId().getValue());
92             }
93         }
94     }
95
96     @Override
97     public <S extends RpcService> S lookupRpcService(final Class<S> serviceClass) {
98         ObjectRegistration<? extends RpcService> registration = rpcRegistrations.get(serviceClass);
99         final RpcService rpcService = registration.getInstance();
100         return serviceClass.cast(rpcService);
101     }
102
103     @Override
104     public void close() {
105         unregisterRPCs();
106     }
107
108     private void unregisterRPCs() {
109         for (final Iterator<Entry<Class<?>, ObjectRegistration<? extends RpcService>>> iterator = Iterators
110                 .consumingIterator(rpcRegistrations.entrySet().iterator()); iterator.hasNext(); ) {
111             final ObjectRegistration<? extends RpcService> rpcRegistration = iterator.next().getValue();
112             rpcRegistration.close();
113
114             if (LOG.isDebugEnabled()) {
115                 LOG.debug("Closing RPC Registration of service {} for device {}.",
116                         rpcRegistration.getInstance().getClass().getSimpleName(),
117                         nodeInstanceIdentifier.getKey().getId().getValue());
118             }
119         }
120     }
121
122     @Override
123     public <T> RequestContext<T> createRequestContext() {
124         if (!tracker.tryAcquire()) {
125             LOG.trace("Device queue {} at capacity", this);
126             return null;
127         } else {
128             LOG.trace("Acquired semaphore for {}, available permits:{} ",
129                     nodeInstanceIdentifier.getKey().getId().getValue(), tracker.availablePermits());
130         }
131
132         final Long xid = deviceInfo.reserveXidForDeviceMessage();
133         if (xid == null) {
134             LOG.warn("Xid cannot be reserved for new RequestContext, node:{}",
135                     nodeInstanceIdentifier.getKey().getId().getValue());
136             tracker.release();
137             return null;
138         }
139
140         return new AbstractRequestContext<T>(xid) {
141             @Override
142             public void close() {
143                 tracker.release();
144                 final long xid = getXid().getValue();
145                 LOG.trace("Removed request context with xid {}", xid);
146                 messageSpy.spyMessage(RpcContextImpl.class, MessageSpy.StatisticsGroup.REQUEST_STACK_FREED);
147             }
148         };
149     }
150
151     @Override
152     public <S extends RpcService> void unregisterRpcServiceImplementation(final Class<S> serviceClass) {
153         LOG.trace("Try to unregister serviceClass {} for Node {}",
154                 serviceClass, nodeInstanceIdentifier.getKey().getId());
155         final ObjectRegistration<? extends RpcService> rpcRegistration = rpcRegistrations.remove(serviceClass);
156         if (rpcRegistration != null) {
157             rpcRegistration.close();
158             LOG.debug("Un-registration serviceClass {} for Node {}", serviceClass.getSimpleName(),
159                     nodeInstanceIdentifier.getKey().getId().getValue());
160         }
161     }
162
163     @VisibleForTesting
164     boolean isEmptyRpcRegistrations() {
165         return this.rpcRegistrations.isEmpty();
166     }
167
168     @Override
169     public DeviceInfo getDeviceInfo() {
170         return this.deviceInfo;
171     }
172
173     @Override
174     public void registerMastershipWatcher(@Nonnull final ContextChainMastershipWatcher newWatcher) {
175         this.contextChainMastershipWatcher = newWatcher;
176     }
177
178     @Override
179     public ListenableFuture<Void> closeServiceInstance() {
180         return Futures.transform(Futures.immediateFuture(null), new Function<Void, Void>() {
181             @Override
182             public Void apply(final Void input) {
183                 unregisterRPCs();
184                 return null;
185             }
186         }, MoreExecutors.directExecutor());
187     }
188
189     @Override
190     public void instantiateServiceInstance() {
191         MdSalRegistrationUtils.registerServices(this, deviceContext, extensionConverterProvider, convertorExecutor);
192
193         if (isStatisticsRpcEnabled && !deviceContext.canUseSingleLayerSerialization()) {
194             MdSalRegistrationUtils.registerStatCompatibilityServices(
195                     this,
196                     deviceContext,
197                     notificationPublishService,
198                     convertorExecutor);
199         }
200
201         contextChainMastershipWatcher.onMasterRoleAcquired(deviceInfo, ContextChainMastershipState.RPC_REGISTRATION);
202     }
203
204     @Nonnull
205     @Override
206     public ServiceGroupIdentifier getIdentifier() {
207         return deviceInfo.getServiceIdentifier();
208     }
209 }