Post "Clustering optimization" updates
[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.base.Preconditions;
11 import com.google.common.collect.Iterators;
12 import java.util.Iterator;
13 import java.util.Map.Entry;
14 import java.util.concurrent.ConcurrentHashMap;
15 import java.util.concurrent.ConcurrentMap;
16 import java.util.concurrent.Semaphore;
17 import java.util.concurrent.atomic.AtomicLong;
18 import com.google.common.base.Preconditions;
19 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
20 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
21 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
22 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
23 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
24 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
25 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
26 import org.opendaylight.openflowplugin.impl.util.MdSalRegistrationUtils;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContext;
28 import org.opendaylight.yangtools.yang.binding.RpcService;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 public class RpcContextImpl implements RpcContext {
33     private static final Logger LOG = LoggerFactory.getLogger(RpcContextImpl.class);
34     private final RpcProviderRegistry rpcProviderRegistry;
35     private final DeviceContext deviceContext;
36     private final MessageSpy messageSpy;
37     private final Semaphore tracker;
38
39     // TODO: add private Sal salBroker
40     private final ConcurrentMap<Class<?>, RoutedRpcRegistration<?>> rpcRegistrations = new ConcurrentHashMap<>();
41     private final boolean isStatisticsRpcEnabled;
42     private final NotificationPublishService notificationPublishService;
43
44     public RpcContextImpl(final MessageSpy messageSpy, final RpcProviderRegistry rpcProviderRegistry, final DeviceContext deviceContext,
45             final int maxRequests, final boolean isStatisticsRpcEnabled,
46             final NotificationPublishService notificationPublishService) {
47         this.deviceContext = Preconditions.checkNotNull(deviceContext);
48         this.messageSpy = Preconditions.checkNotNull(messageSpy);
49         this.rpcProviderRegistry = Preconditions.checkNotNull(rpcProviderRegistry);
50         this.isStatisticsRpcEnabled = isStatisticsRpcEnabled;
51         this.notificationPublishService = notificationPublishService;
52         tracker = new Semaphore(maxRequests, true);
53         deviceContext.setRpcContext(RpcContextImpl.this);
54     }
55
56     /**
57      * @see org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext#registerRpcServiceImplementation(java.lang.Class,
58      * org.opendaylight.yangtools.yang.binding.RpcService)
59      */
60     @Override
61     public <S extends RpcService> void registerRpcServiceImplementation(final Class<S> serviceClass,
62                                                                         final S serviceInstance) {
63         LOG.trace("Try to register service {} for device {}.", serviceClass, deviceContext.getDeviceState().getNodeInstanceIdentifier());
64         if (! rpcRegistrations.containsKey(serviceClass)) {
65             final RoutedRpcRegistration<S> routedRpcReg = rpcProviderRegistry.addRoutedRpcImplementation(serviceClass, serviceInstance);
66             routedRpcReg.registerPath(NodeContext.class, deviceContext.getDeviceState().getNodeInstanceIdentifier());
67             rpcRegistrations.put(serviceClass, routedRpcReg);
68             LOG.debug("Registration of service {} for device {}.", serviceClass, deviceContext.getDeviceState().getNodeInstanceIdentifier());
69         }
70     }
71
72     @Override
73     public void registerStatCompatibilityServices() {
74         if (isStatisticsRpcEnabled) {
75             MdSalRegistrationUtils.registerStatCompatibilityServices(RpcContextImpl.this, deviceContext,
76                     notificationPublishService, new AtomicLong());
77         }
78     }
79
80     @Override
81     public <S extends RpcService> S lookupRpcService(final Class<S> serviceClass) {
82         final RpcService rpcService = rpcRegistrations.get(serviceClass).getInstance();
83         return (S) rpcService;
84     }
85     /**
86      * Unregisters all services.
87      *
88      * @see java.lang.AutoCloseable#close()
89      */
90     @Override
91     public void close() {
92         for (final Iterator<Entry<Class<?>, RoutedRpcRegistration<?>>> iterator = Iterators
93                 .consumingIterator(rpcRegistrations.entrySet().iterator()); iterator.hasNext();) {
94             final RoutedRpcRegistration<?> rpcRegistration = iterator.next().getValue();
95             rpcRegistration.unregisterPath(NodeContext.class, deviceContext.getDeviceState().getNodeInstanceIdentifier());
96             rpcRegistration.close();
97             LOG.debug("Closing RPC Registration of service {} for device {}.", rpcRegistration.getServiceType(),
98                     deviceContext.getDeviceState().getNodeInstanceIdentifier());
99         }
100     }
101
102     @Override
103     public <T> RequestContext<T> createRequestContext() {
104         if (!tracker.tryAcquire()) {
105             LOG.trace("Device queue {} at capacity", this);
106             return null;
107         } else {
108             LOG.info("Acquired semaphore for {}, available permits:{} ", deviceContext.getDeviceState().getNodeId(), tracker.availablePermits());
109         }
110
111         final Long xid = deviceContext.reservedXidForDeviceMessage();
112         if (xid == null) {
113             LOG.warn("Xid cannot be reserved for new RequestContext, node:{}", deviceContext.getDeviceState().getNodeId());
114             tracker.release();
115             return null;
116         }
117
118         return new AbstractRequestContext<T>(xid) {
119             @Override
120             public void close() {
121                 tracker.release();
122                 final long xid = getXid().getValue();
123                 LOG.trace("Removed request context with xid {}", xid);
124                 messageSpy.spyMessage(RpcContextImpl.class, MessageSpy.STATISTIC_GROUP.REQUEST_STACK_FREED);
125             }
126         };
127     }
128
129     @Override
130     public <S extends RpcService> void unregisterRpcServiceImplementation(final Class<S> serviceClass) {
131         LOG.trace("Try to unregister serviceClass {} for Node {}", serviceClass, deviceContext.getDeviceState().getNodeId());
132         final RoutedRpcRegistration<?> rpcRegistration = rpcRegistrations.remove(serviceClass);
133         if (rpcRegistration != null) {
134             rpcRegistration.unregisterPath(NodeContext.class, deviceContext.getDeviceState().getNodeInstanceIdentifier());
135             rpcRegistration.close();
136             LOG.debug("Unregistration serviceClass {} for Node {}", serviceClass, deviceContext.getDeviceState().getNodeId());
137         }
138     }
139 }