2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.openflowplugin.impl.device;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import com.google.common.collect.Iterators;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import io.netty.util.Timeout;
18 import io.netty.util.TimerTask;
19 import java.util.Collections;
20 import java.util.Iterator;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ConcurrentMap;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.ScheduledThreadPoolExecutor;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.CheckForNull;
27 import javax.annotation.Nonnull;
28 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
29 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
30 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
31 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
32 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
33 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
34 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
35 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
36 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
37 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
38 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
39 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
40 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
41 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
42 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
43 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
44 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
45 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
46 import org.opendaylight.openflowplugin.impl.connection.OutboundQueueProviderImpl;
47 import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
52 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
59 public class DeviceManagerImpl implements DeviceManager, ExtensionConverterProviderKeeper {
61 private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
63 private final long globalNotificationQuota;
64 private final boolean switchFeaturesMandatory;
66 private final int spyRate = 10;
68 private final DataBroker dataBroker;
69 private TranslatorLibrary translatorLibrary;
70 private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
71 private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
72 private NotificationPublishService notificationPublishService;
74 private final ConcurrentMap<NodeId, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
76 private final long barrierIntervalNanos;
77 private final int barrierCountLimit;
78 private ExtensionConverterProvider extensionConverterProvider;
79 private ScheduledThreadPoolExecutor spyPool;
81 private final LifecycleConductor conductor;
82 private boolean isStatisticsRpcEnabled;
84 public DeviceManagerImpl(@Nonnull final DataBroker dataBroker,
85 final long globalNotificationQuota, final boolean switchFeaturesMandatory,
86 final long barrierInterval, final int barrierCountLimit,
87 final LifecycleConductor lifecycleConductor) {
88 this.switchFeaturesMandatory = switchFeaturesMandatory;
89 this.globalNotificationQuota = globalNotificationQuota;
90 this.dataBroker = Preconditions.checkNotNull(dataBroker);
91 /* merge empty nodes to oper DS to predict any problems with missing parent for Node */
92 final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
94 final NodesBuilder nodesBuilder = new NodesBuilder();
95 nodesBuilder.setNode(Collections.<Node>emptyList());
96 tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
99 } catch (ExecutionException | InterruptedException e) {
100 LOG.error("Creation of node failed.", e);
101 throw new IllegalStateException(e);
104 this.barrierIntervalNanos = TimeUnit.MILLISECONDS.toNanos(barrierInterval);
105 this.barrierCountLimit = barrierCountLimit;
107 this.conductor = lifecycleConductor;
108 spyPool = new ScheduledThreadPoolExecutor(1);
113 public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
114 this.deviceInitPhaseHandler = handler;
118 public void onDeviceContextLevelUp(@CheckForNull DeviceInfo deviceInfo) throws Exception {
119 // final phase - we have to add new Device to MD-SAL DataStore
120 LOG.debug("Final phase of DeviceContextLevelUp for Node: {} ", deviceInfo.getNodeId());
121 DeviceContext deviceContext = Preconditions.checkNotNull(deviceContexts.get(deviceInfo.getNodeId()));
122 ((DeviceContextImpl) deviceContext).initialSubmitTransaction();
123 deviceContext.onPublished();
127 public boolean deviceConnected(@CheckForNull final ConnectionContext connectionContext) throws Exception {
128 Preconditions.checkArgument(connectionContext != null);
130 NodeId nodeId = connectionContext.getNodeId();
132 * This part prevent destroy another device context. Throwing here an exception result to propagate close connection
133 * in {@link org.opendaylight.openflowplugin.impl.connection.org.opendaylight.openflowplugin.impl.connection.HandshakeContextImpl}
134 * If context already exist we are in state closing process (connection flapping) and we should not propagate connection close
136 if (deviceContexts.containsKey(nodeId)) {
137 LOG.warn("Rejecting connection from node which is already connected and there exist deviceContext for it: {}", connectionContext.getNodeId());
141 LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
142 connectionContext.getConnectionAdapter().getRemoteAddress(), nodeId);
144 // Add Disconnect handler
145 connectionContext.setDeviceDisconnectedHandler(DeviceManagerImpl.this);
146 // Cache this for clarity
147 final ConnectionAdapter connectionAdapter = connectionContext.getConnectionAdapter();
149 //FIXME: as soon as auxiliary connection are fully supported then this is needed only before device context published
150 connectionAdapter.setPacketInFiltering(true);
152 final Short version = connectionContext.getFeatures().getVersion();
153 final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(version);
155 connectionContext.setOutboundQueueProvider(outboundQueueProvider);
156 final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
157 connectionAdapter.registerOutboundQueueHandler(outboundQueueProvider, barrierCountLimit, barrierIntervalNanos);
158 connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
160 final DeviceState deviceState = createDeviceState(connectionContext);
161 final DeviceContext deviceContext = new DeviceContextImpl(connectionContext,
165 outboundQueueProvider,
167 switchFeaturesMandatory);
169 Verify.verify(deviceContexts.putIfAbsent(nodeId, deviceContext) == null, "DeviceCtx still not closed.");
171 ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
172 deviceContext.setStatisticsRpcEnabled(isStatisticsRpcEnabled);
173 deviceContext.setNotificationPublishService(notificationPublishService);
175 updatePacketInRateLimiters();
177 final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
178 connectionAdapter, deviceContext);
179 connectionAdapter.setMessageListener(messageListener);
180 deviceState.setValid(true);
182 deviceInitPhaseHandler.onDeviceContextLevelUp(connectionContext.getDeviceInfo());
187 private static DeviceStateImpl createDeviceState(final @Nonnull ConnectionContext connectionContext) {
188 return new DeviceStateImpl(connectionContext.getFeatures(), connectionContext.getNodeId());
191 private void updatePacketInRateLimiters() {
192 synchronized (deviceContexts) {
193 final int deviceContextsSize = deviceContexts.size();
194 if (deviceContextsSize > 0) {
195 long freshNotificationLimit = globalNotificationQuota / deviceContextsSize;
196 if (freshNotificationLimit < 100) {
197 freshNotificationLimit = 100;
199 LOG.debug("fresh notification limit = {}", freshNotificationLimit);
200 for (final DeviceContext deviceContext : deviceContexts.values()) {
201 deviceContext.updatePacketInRateLimit(freshNotificationLimit);
208 public TranslatorLibrary oook() {
209 return translatorLibrary;
213 public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
214 this.translatorLibrary = translatorLibrary;
218 public void setNotificationPublishService(final NotificationPublishService notificationService) {
219 notificationPublishService = notificationService;
223 public void close() {
224 for (final Iterator<DeviceContext> iterator = Iterators.consumingIterator(deviceContexts.values().iterator());
225 iterator.hasNext();) {
226 final DeviceContext deviceCtx = iterator.next();
227 deviceCtx.shutdownConnection();
228 deviceCtx.shuttingDownDataStoreTransactions();
231 if (spyPool != null) {
232 spyPool.shutdownNow();
238 public void onDeviceContextLevelDown(final DeviceContext deviceContext) {
239 LOG.debug("onDeviceContextClosed for Node {}", deviceContext.getDeviceState().getNodeId());
240 deviceContexts.remove(deviceContext.getPrimaryConnectionContext().getNodeId(), deviceContext);
241 updatePacketInRateLimiters();
245 public void initialize() {
246 spyPool.scheduleAtFixedRate(conductor.getMessageIntelligenceAgency(), spyRate, spyRate, TimeUnit.SECONDS);
250 public DeviceContext getDeviceContextFromNodeId(final NodeId nodeId) {
251 return deviceContexts.get(nodeId);
255 public void setStatisticsRpcEnabled(boolean isStatisticsRpcEnabled) {
256 this.isStatisticsRpcEnabled = isStatisticsRpcEnabled;
260 public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
261 this.extensionConverterProvider = extensionConverterProvider;
265 public ExtensionConverterProvider getExtensionConverterProvider() {
266 return extensionConverterProvider;
270 public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
271 this.deviceTerminPhaseHandler = handler;
275 public void onDeviceDisconnected(final ConnectionContext connectionContext) {
276 LOG.trace("onDeviceDisconnected method call for Node: {}", connectionContext.getNodeId());
277 final NodeId nodeId = connectionContext.getNodeId();
278 final DeviceContext deviceCtx = this.deviceContexts.get(nodeId);
280 if (null == deviceCtx) {
281 LOG.info("DeviceContext for Node {} was not found. Connection is terminated without OFP context suite.", nodeId);
285 if (!connectionContext.equals(deviceCtx.getPrimaryConnectionContext())) {
286 /* Connection is not PrimaryConnection so try to remove from Auxiliary Connections */
287 deviceCtx.removeAuxiliaryConnectionContext(connectionContext);
289 /* Device is disconnected and so we need to close TxManager */
290 final ListenableFuture<Void> future = deviceCtx.shuttingDownDataStoreTransactions();
291 Futures.addCallback(future, new FutureCallback<Void>() {
294 public void onSuccess(final Void result) {
295 LOG.debug("TxChainManager for device {} is closed successful.", nodeId);
296 deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceCtx);
300 public void onFailure(final Throwable t) {
301 LOG.warn("TxChainManager for device {} failed by closing.", nodeId, t);
302 deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceCtx);
305 /* Add timer for Close TxManager because it could fain ind cluster without notification */
306 final TimerTask timerTask = new TimerTask() {
309 public void run(final Timeout timeout) throws Exception {
310 if (!future.isDone()) {
311 LOG.info("Shutting down TxChain for node {} not completed during 10 sec. Continue anyway.", nodeId);
312 future.cancel(false);
316 conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
321 void addDeviceContextToMap(final NodeId nodeId, final DeviceContext deviceContext){
322 deviceContexts.put(nodeId, deviceContext);