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.TimerTask;
18 import java.util.Collections;
19 import java.util.Iterator;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentMap;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.ScheduledThreadPoolExecutor;
24 import java.util.concurrent.TimeUnit;
25 import javax.annotation.CheckForNull;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
28 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
29 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
30 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
31 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
32 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
33 import org.opendaylight.openflowplugin.api.openflow.OFPContext;
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.Nodes;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
51 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
58 public class DeviceManagerImpl implements DeviceManager, ExtensionConverterProviderKeeper {
60 private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
62 private final long globalNotificationQuota;
63 private final boolean switchFeaturesMandatory;
65 private final int spyRate = 10;
67 private final DataBroker dataBroker;
68 private TranslatorLibrary translatorLibrary;
69 private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
70 private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
72 private final ConcurrentMap<DeviceInfo, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
74 private final long barrierIntervalNanos;
75 private final int barrierCountLimit;
76 private ExtensionConverterProvider extensionConverterProvider;
77 private ScheduledThreadPoolExecutor spyPool;
79 private final LifecycleConductor conductor;
81 public DeviceManagerImpl(@Nonnull final DataBroker dataBroker,
82 final long globalNotificationQuota, final boolean switchFeaturesMandatory,
83 final long barrierInterval, final int barrierCountLimit,
84 final LifecycleConductor lifecycleConductor) {
85 this.switchFeaturesMandatory = switchFeaturesMandatory;
86 this.globalNotificationQuota = globalNotificationQuota;
87 this.dataBroker = Preconditions.checkNotNull(dataBroker);
88 /* merge empty nodes to oper DS to predict any problems with missing parent for Node */
89 final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
91 final NodesBuilder nodesBuilder = new NodesBuilder();
92 nodesBuilder.setNode(Collections.<Node>emptyList());
93 tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
96 } catch (ExecutionException | InterruptedException e) {
97 LOG.error("Creation of node failed.", e);
98 throw new IllegalStateException(e);
101 this.barrierIntervalNanos = TimeUnit.MILLISECONDS.toNanos(barrierInterval);
102 this.barrierCountLimit = barrierCountLimit;
104 this.conductor = lifecycleConductor;
105 spyPool = new ScheduledThreadPoolExecutor(1);
110 public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
111 this.deviceInitPhaseHandler = handler;
115 public void onDeviceContextLevelUp(@CheckForNull DeviceInfo deviceInfo) throws Exception {
116 // final phase - we have to add new Device to MD-SAL DataStore
117 LOG.debug("Final phase of DeviceContextLevelUp for Node: {} ", deviceInfo.getNodeId());
118 DeviceContext deviceContext = Preconditions.checkNotNull(deviceContexts.get(deviceInfo));
119 ((DeviceContextImpl) deviceContext).initialSubmitTransaction();
120 deviceContext.onPublished();
124 public boolean deviceConnected(@CheckForNull final ConnectionContext connectionContext) throws Exception {
125 Preconditions.checkArgument(connectionContext != null);
127 DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
129 * This part prevent destroy another device context. Throwing here an exception result to propagate close connection
130 * in {@link org.opendaylight.openflowplugin.impl.connection.org.opendaylight.openflowplugin.impl.connection.HandshakeContextImpl}
131 * If context already exist we are in state closing process (connection flapping) and we should not propagate connection close
133 if (deviceContexts.containsKey(deviceInfo)) {
134 LOG.warn("Rejecting connection from node which is already connected and there exist deviceContext for it: {}", connectionContext.getNodeId());
138 LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
139 connectionContext.getConnectionAdapter().getRemoteAddress(), deviceInfo.getNodeId());
141 // Add Disconnect handler
142 connectionContext.setDeviceDisconnectedHandler(DeviceManagerImpl.this);
143 // Cache this for clarity
144 final ConnectionAdapter connectionAdapter = connectionContext.getConnectionAdapter();
146 //FIXME: as soon as auxiliary connection are fully supported then this is needed only before device context published
147 connectionAdapter.setPacketInFiltering(true);
149 final Short version = connectionContext.getFeatures().getVersion();
150 final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(version);
152 connectionContext.setOutboundQueueProvider(outboundQueueProvider);
153 final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
154 connectionAdapter.registerOutboundQueueHandler(outboundQueueProvider, barrierCountLimit, barrierIntervalNanos);
155 connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
157 final DeviceState deviceState = new DeviceStateImpl();
158 final DeviceContext deviceContext = new DeviceContextImpl(connectionContext,
162 outboundQueueProvider,
164 switchFeaturesMandatory);
166 Verify.verify(deviceContexts.putIfAbsent(deviceInfo, deviceContext) == null, "DeviceCtx still not closed.");
168 ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
169 deviceContext.setNotificationPublishService(conductor.getNotificationPublishService());
171 updatePacketInRateLimiters();
173 final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
174 connectionAdapter, deviceContext);
175 connectionAdapter.setMessageListener(messageListener);
176 deviceState.setValid(true);
178 deviceInitPhaseHandler.onDeviceContextLevelUp(connectionContext.getDeviceInfo());
183 private void updatePacketInRateLimiters() {
184 synchronized (deviceContexts) {
185 final int deviceContextsSize = deviceContexts.size();
186 if (deviceContextsSize > 0) {
187 long freshNotificationLimit = globalNotificationQuota / deviceContextsSize;
188 if (freshNotificationLimit < 100) {
189 freshNotificationLimit = 100;
191 LOG.debug("fresh notification limit = {}", freshNotificationLimit);
192 for (final DeviceContext deviceContext : deviceContexts.values()) {
193 deviceContext.updatePacketInRateLimit(freshNotificationLimit);
200 public TranslatorLibrary oook() {
201 return translatorLibrary;
205 public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
206 this.translatorLibrary = translatorLibrary;
210 public void close() {
211 for (final Iterator<DeviceContext> iterator = Iterators.consumingIterator(deviceContexts.values().iterator());
212 iterator.hasNext();) {
213 final DeviceContext deviceCtx = iterator.next();
214 deviceCtx.shutdownConnection();
215 deviceCtx.shuttingDownDataStoreTransactions();
218 if (spyPool != null) {
219 spyPool.shutdownNow();
225 public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
226 LOG.debug("onDeviceContextClosed for Node {}", deviceInfo.getNodeId());
227 deviceContexts.remove(deviceInfo);
228 updatePacketInRateLimiters();
232 public void initialize() {
233 spyPool.scheduleAtFixedRate(conductor.getMessageIntelligenceAgency(), spyRate, spyRate, TimeUnit.SECONDS);
237 public DeviceContext getDeviceContextFromNodeId(DeviceInfo deviceInfo) {
238 return deviceContexts.get(deviceInfo);
242 public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
243 this.extensionConverterProvider = extensionConverterProvider;
247 public ExtensionConverterProvider getExtensionConverterProvider() {
248 return extensionConverterProvider;
252 public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
253 this.deviceTerminPhaseHandler = handler;
257 public void onDeviceDisconnected(final ConnectionContext connectionContext) {
258 LOG.trace("onDeviceDisconnected method call for Node: {}", connectionContext.getNodeId());
259 final DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
260 final DeviceContext deviceCtx = this.deviceContexts.get(deviceInfo.getNodeId());
262 if (null == deviceCtx) {
263 LOG.info("DeviceContext for Node {} was not found. Connection is terminated without OFP context suite.", deviceInfo.getNodeId());
267 if (!connectionContext.equals(deviceCtx.getPrimaryConnectionContext())) {
268 /* Connection is not PrimaryConnection so try to remove from Auxiliary Connections */
269 deviceCtx.removeAuxiliaryConnectionContext(connectionContext);
271 /* Device is disconnected and so we need to close TxManager */
272 final ListenableFuture<Void> future = deviceCtx.shuttingDownDataStoreTransactions();
273 Futures.addCallback(future, new FutureCallback<Void>() {
276 public void onSuccess(final Void result) {
277 LOG.debug("TxChainManager for device {} is closed successful.", deviceInfo.getNodeId());
278 deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
282 public void onFailure(final Throwable t) {
283 LOG.warn("TxChainManager for device {} failed by closing.", deviceInfo.getNodeId(), t);
284 deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
287 /* Add timer for Close TxManager because it could fain ind cluster without notification */
288 final TimerTask timerTask = timeout -> {
289 if (!future.isDone()) {
290 LOG.info("Shutting down TxChain for node {} not completed during 10 sec. Continue anyway.", deviceInfo.getNodeId());
291 future.cancel(false);
294 conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
299 void addDeviceContextToMap(final DeviceInfo deviceInfo, final DeviceContext deviceContext){
300 deviceContexts.put(deviceInfo, deviceContext);
304 public <T extends OFPContext> T gainContext(final DeviceInfo deviceInfo) {
305 return (T) deviceContexts.get(deviceInfo);