Bug 5596 Created lifecycle service
[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.Preconditions;
12 import com.google.common.collect.Iterators;
13 import java.util.Iterator;
14 import java.util.Map.Entry;
15 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.concurrent.ConcurrentMap;
17 import java.util.concurrent.Semaphore;
18 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
19 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
20 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
21 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
22 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
23 import org.opendaylight.openflowplugin.api.openflow.device.XidSequencer;
24 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
25 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContext;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
29 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.binding.RpcService;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 class RpcContextImpl implements RpcContext {
35     private static final Logger LOG = LoggerFactory.getLogger(RpcContextImpl.class);
36     private final RpcProviderRegistry rpcProviderRegistry;
37     private final MessageSpy messageSpy;
38     private final Semaphore tracker;
39     private final XidSequencer xidSequencer;
40     private boolean isStatisticsRpcEnabled;
41
42     // TODO: add private Sal salBroker
43     private final ConcurrentMap<Class<?>, RoutedRpcRegistration<?>> rpcRegistrations = new ConcurrentHashMap<>();
44     private final KeyedInstanceIdentifier<Node, NodeKey> nodeInstanceIdentifier;
45     private CONTEXT_STATE state;
46     private final DeviceInfo deviceInfo;
47
48     RpcContextImpl(final DeviceInfo deviceInfo,
49                    final RpcProviderRegistry rpcProviderRegistry,
50                    final XidSequencer xidSequencer,
51                    final MessageSpy messageSpy,
52                    final int maxRequests,
53                    final KeyedInstanceIdentifier<Node, NodeKey> nodeInstanceIdentifier) {
54         this.xidSequencer = Preconditions.checkNotNull(xidSequencer);
55         this.messageSpy = Preconditions.checkNotNull(messageSpy);
56         this.rpcProviderRegistry = Preconditions.checkNotNull(rpcProviderRegistry);
57         this.nodeInstanceIdentifier = nodeInstanceIdentifier;
58
59         tracker = new Semaphore(maxRequests, true);
60         setState(CONTEXT_STATE.WORKING);
61         this.deviceInfo = deviceInfo;
62     }
63
64     /**
65      * @see org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext#registerRpcServiceImplementation(java.lang.Class,
66      * org.opendaylight.yangtools.yang.binding.RpcService)
67      */
68     @Override
69     public <S extends RpcService> void registerRpcServiceImplementation(final Class<S> serviceClass,
70                                                                         final S serviceInstance) {
71         LOG.trace("Try to register service {} for device {}.", serviceClass, nodeInstanceIdentifier);
72         if (! rpcRegistrations.containsKey(serviceClass)) {
73             final RoutedRpcRegistration<S> routedRpcReg = rpcProviderRegistry.addRoutedRpcImplementation(serviceClass, serviceInstance);
74             routedRpcReg.registerPath(NodeContext.class, nodeInstanceIdentifier);
75             rpcRegistrations.put(serviceClass, routedRpcReg);
76             LOG.debug("Registration of service {} for device {}.", serviceClass, nodeInstanceIdentifier);
77         }
78     }
79
80     @Override
81     public <S extends RpcService> S lookupRpcService(final Class<S> serviceClass) {
82         RoutedRpcRegistration<?> registration = rpcRegistrations.get(serviceClass);
83         final RpcService rpcService = registration.getInstance();
84         return (S) rpcService;
85     }
86
87     /**
88      * Unregisters all services.
89      *
90      * @see java.lang.AutoCloseable#close()
91      */
92     @Override
93     public void close() {
94         if (CONTEXT_STATE.TERMINATION.equals(getState())){
95             if (LOG.isDebugEnabled()) {
96                 LOG.debug("RpcContext is already in TERMINATION state.");
97             }
98         } else {
99             setState(CONTEXT_STATE.TERMINATION);
100             for (final Iterator<Entry<Class<?>, RoutedRpcRegistration<?>>> iterator = Iterators
101                     .consumingIterator(rpcRegistrations.entrySet().iterator()); iterator.hasNext(); ) {
102                 final RoutedRpcRegistration<?> rpcRegistration = iterator.next().getValue();
103                 rpcRegistration.unregisterPath(NodeContext.class, nodeInstanceIdentifier);
104                 rpcRegistration.close();
105                 LOG.debug("Closing RPC Registration of service {} for device {}.", rpcRegistration.getServiceType(),
106                         nodeInstanceIdentifier);
107             }
108         }
109     }
110
111     @Override
112     public <T> RequestContext<T> createRequestContext() {
113         if (!tracker.tryAcquire()) {
114             LOG.trace("Device queue {} at capacity", this);
115             return null;
116         } else {
117             LOG.trace("Acquired semaphore for {}, available permits:{} ", nodeInstanceIdentifier.getKey().getId(), tracker.availablePermits());
118         }
119
120         final Long xid = xidSequencer.reserveXidForDeviceMessage();
121         if (xid == null) {
122             LOG.warn("Xid cannot be reserved for new RequestContext, node:{}", nodeInstanceIdentifier.getKey().getId());
123             tracker.release();
124             return null;
125         }
126
127         return new AbstractRequestContext<T>(xid) {
128             @Override
129             public void close() {
130                 tracker.release();
131                 final long xid = getXid().getValue();
132                 LOG.trace("Removed request context with xid {}", xid);
133                 messageSpy.spyMessage(RpcContextImpl.class, MessageSpy.STATISTIC_GROUP.REQUEST_STACK_FREED);
134             }
135         };
136     }
137
138     @Override
139     public <S extends RpcService> void unregisterRpcServiceImplementation(final Class<S> serviceClass) {
140         LOG.trace("Try to unregister serviceClass {} for Node {}", serviceClass, nodeInstanceIdentifier.getKey().getId());
141         final RoutedRpcRegistration<?> rpcRegistration = rpcRegistrations.remove(serviceClass);
142         if (rpcRegistration != null) {
143             rpcRegistration.unregisterPath(NodeContext.class, nodeInstanceIdentifier);
144             rpcRegistration.close();
145             LOG.debug("Unregistration serviceClass {} for Node {}", serviceClass, nodeInstanceIdentifier.getKey().getId());
146         }
147     }
148
149     @VisibleForTesting
150     boolean isEmptyRpcRegistrations() {
151         return this.rpcRegistrations.isEmpty();
152     }
153
154     @Override
155     public void setStatisticsRpcEnabled(boolean isStatisticsRpcEnabled) {
156         this.isStatisticsRpcEnabled = isStatisticsRpcEnabled;
157     }
158
159     @Override
160     public boolean isStatisticsRpcEnabled() {
161         return isStatisticsRpcEnabled;
162     }
163
164     @Override
165     public CONTEXT_STATE getState() {
166         return this.state;
167     }
168
169     @Override
170     public void setState(CONTEXT_STATE state) {
171         this.state = state;
172     }
173
174     @Override
175     public ServiceGroupIdentifier getServiceIdentifier() {
176         return this.deviceInfo.getServiceIdentifier();
177     }
178
179     @Override
180     public DeviceInfo getDeviceInfo() {
181         return this.deviceInfo;
182     }
183 }