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