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.Function;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Verify;
14 import com.google.common.collect.Iterators;
15 import com.google.common.util.concurrent.AsyncFunction;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import io.netty.util.TimerTask;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.ScheduledThreadPoolExecutor;
26 import java.util.concurrent.TimeUnit;
27 import javax.annotation.CheckForNull;
28 import javax.annotation.Nonnull;
29 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
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.OFPContext;
35 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
36 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
37 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
38 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
39 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
40 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
41 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
42 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
43 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
44 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
45 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
46 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
47 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
48 import org.opendaylight.openflowplugin.impl.connection.OutboundQueueProviderImpl;
49 import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
50 import org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtils;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
55 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
62 public class DeviceManagerImpl implements DeviceManager, ExtensionConverterProviderKeeper {
64 private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
66 private final long globalNotificationQuota;
67 private final boolean switchFeaturesMandatory;
69 private final int spyRate = 10;
71 private final DataBroker dataBroker;
72 private TranslatorLibrary translatorLibrary;
73 private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
74 private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
76 private final ConcurrentMap<DeviceInfo, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
78 private final long barrierIntervalNanos;
79 private final int barrierCountLimit;
80 private ExtensionConverterProvider extensionConverterProvider;
81 private ScheduledThreadPoolExecutor spyPool;
83 private final LifecycleConductor conductor;
85 public DeviceManagerImpl(@Nonnull final DataBroker dataBroker,
86 final long globalNotificationQuota, final boolean switchFeaturesMandatory,
87 final long barrierInterval, final int barrierCountLimit,
88 final LifecycleConductor lifecycleConductor) {
89 this.switchFeaturesMandatory = switchFeaturesMandatory;
90 this.globalNotificationQuota = globalNotificationQuota;
91 this.dataBroker = Preconditions.checkNotNull(dataBroker);
92 /* merge empty nodes to oper DS to predict any problems with missing parent for Node */
93 final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
95 final NodesBuilder nodesBuilder = new NodesBuilder();
96 nodesBuilder.setNode(Collections.<Node>emptyList());
97 tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
100 } catch (ExecutionException | InterruptedException e) {
101 LOG.error("Creation of node failed.", e);
102 throw new IllegalStateException(e);
105 this.barrierIntervalNanos = TimeUnit.MILLISECONDS.toNanos(barrierInterval);
106 this.barrierCountLimit = barrierCountLimit;
108 this.conductor = lifecycleConductor;
109 spyPool = new ScheduledThreadPoolExecutor(1);
114 public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
115 this.deviceInitPhaseHandler = handler;
119 public void onDeviceContextLevelUp(@CheckForNull DeviceInfo deviceInfo) throws Exception {
120 // final phase - we have to add new Device to MD-SAL DataStore
121 LOG.debug("Final phase of DeviceContextLevelUp for Node: {} ", deviceInfo.getNodeId());
122 DeviceContext deviceContext = Preconditions.checkNotNull(deviceContexts.get(deviceInfo));
123 ((DeviceContextImpl) deviceContext).initialSubmitTransaction();
124 deviceContext.onPublished();
128 public boolean deviceConnected(@CheckForNull final ConnectionContext connectionContext) throws Exception {
129 Preconditions.checkArgument(connectionContext != null);
131 DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
133 * This part prevent destroy another device context. Throwing here an exception result to propagate close connection
134 * in {@link org.opendaylight.openflowplugin.impl.connection.org.opendaylight.openflowplugin.impl.connection.HandshakeContextImpl}
135 * If context already exist we are in state closing process (connection flapping) and we should not propagate connection close
137 if (deviceContexts.containsKey(deviceInfo)) {
138 LOG.warn("Rejecting connection from node which is already connected and there exist deviceContext for it: {}", connectionContext.getNodeId());
142 LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
143 connectionContext.getConnectionAdapter().getRemoteAddress(), deviceInfo.getNodeId());
145 // Add Disconnect handler
146 connectionContext.setDeviceDisconnectedHandler(DeviceManagerImpl.this);
147 // Cache this for clarity
148 final ConnectionAdapter connectionAdapter = connectionContext.getConnectionAdapter();
150 //FIXME: as soon as auxiliary connection are fully supported then this is needed only before device context published
151 connectionAdapter.setPacketInFiltering(true);
153 final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(deviceInfo.getVersion());
155 connectionContext.setOutboundQueueProvider(outboundQueueProvider);
156 final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
157 connectionAdapter.registerOutboundQueueHandler(outboundQueueProvider, barrierCountLimit, barrierIntervalNanos);
158 connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
160 final DeviceState deviceState = new DeviceStateImpl();
161 final DeviceContext deviceContext = new DeviceContextImpl(connectionContext,
165 outboundQueueProvider,
168 Verify.verify(deviceContexts.putIfAbsent(deviceInfo, deviceContext) == null, "DeviceCtx still not closed.");
170 ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
171 deviceContext.setNotificationPublishService(conductor.getNotificationPublishService());
173 updatePacketInRateLimiters();
175 final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
176 connectionAdapter, deviceContext);
177 connectionAdapter.setMessageListener(messageListener);
178 deviceState.setValid(true);
180 deviceInitPhaseHandler.onDeviceContextLevelUp(connectionContext.getDeviceInfo());
185 private void updatePacketInRateLimiters() {
186 synchronized (deviceContexts) {
187 final int deviceContextsSize = deviceContexts.size();
188 if (deviceContextsSize > 0) {
189 long freshNotificationLimit = globalNotificationQuota / deviceContextsSize;
190 if (freshNotificationLimit < 100) {
191 freshNotificationLimit = 100;
193 LOG.debug("fresh notification limit = {}", freshNotificationLimit);
194 for (final DeviceContext deviceContext : deviceContexts.values()) {
195 deviceContext.updatePacketInRateLimit(freshNotificationLimit);
202 public TranslatorLibrary oook() {
203 return translatorLibrary;
207 public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
208 this.translatorLibrary = translatorLibrary;
212 public void close() {
213 for (final Iterator<DeviceContext> iterator = Iterators.consumingIterator(deviceContexts.values().iterator());
214 iterator.hasNext();) {
215 final DeviceContext deviceCtx = iterator.next();
216 deviceCtx.shutdownConnection();
217 deviceCtx.shuttingDownDataStoreTransactions();
220 if (spyPool != null) {
221 spyPool.shutdownNow();
227 public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
228 LOG.debug("onDeviceContextClosed for Node {}", deviceInfo.getNodeId());
229 deviceContexts.remove(deviceInfo);
230 updatePacketInRateLimiters();
234 public void initialize() {
235 spyPool.scheduleAtFixedRate(conductor.getMessageIntelligenceAgency(), spyRate, spyRate, TimeUnit.SECONDS);
239 public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
240 this.extensionConverterProvider = extensionConverterProvider;
244 public ExtensionConverterProvider getExtensionConverterProvider() {
245 return extensionConverterProvider;
249 public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
250 this.deviceTerminPhaseHandler = handler;
254 public void onDeviceDisconnected(final ConnectionContext connectionContext) {
255 LOG.trace("onDeviceDisconnected method call for Node: {}", connectionContext.getNodeId());
256 final DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
257 final DeviceContext deviceCtx = this.deviceContexts.get(deviceInfo);
259 if (null == deviceCtx) {
260 LOG.info("DeviceContext for Node {} was not found. Connection is terminated without OFP context suite.", deviceInfo.getNodeId());
264 if (!connectionContext.equals(deviceCtx.getPrimaryConnectionContext())) {
265 /* Connection is not PrimaryConnection so try to remove from Auxiliary Connections */
266 deviceCtx.removeAuxiliaryConnectionContext(connectionContext);
268 /* Device is disconnected and so we need to close TxManager */
269 final ListenableFuture<Void> future = deviceCtx.shuttingDownDataStoreTransactions();
270 Futures.addCallback(future, new FutureCallback<Void>() {
273 public void onSuccess(final Void result) {
274 LOG.debug("TxChainManager for device {} is closed successful.", deviceInfo.getNodeId());
275 deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
279 public void onFailure(final Throwable t) {
280 LOG.warn("TxChainManager for device {} failed by closing.", deviceInfo.getNodeId(), t);
281 deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
284 /* Add timer for Close TxManager because it could fain ind cluster without notification */
285 final TimerTask timerTask = timeout -> {
286 if (!future.isDone()) {
287 LOG.info("Shutting down TxChain for node {} not completed during 10 sec. Continue anyway.", deviceInfo.getNodeId());
288 future.cancel(false);
291 conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
296 void addDeviceContextToMap(final DeviceInfo deviceInfo, final DeviceContext deviceContext){
297 deviceContexts.put(deviceInfo, deviceContext);
301 public <T extends OFPContext> T gainContext(final DeviceInfo deviceInfo) {
302 return (T) deviceContexts.get(deviceInfo);
306 public ListenableFuture<Void> onClusterRoleChange(final DeviceInfo deviceInfo, final OfpRole role) {
307 DeviceContext deviceContext = conductor.getDeviceContext(deviceInfo);
308 LOG.trace("onClusterRoleChange {} for node:", role, deviceInfo.getNodeId());
309 if (OfpRole.BECOMEMASTER.equals(role)) {
310 return onDeviceTakeClusterLeadership(deviceInfo);
312 return ((DeviceContextImpl)deviceContext).getTransactionChainManager().deactivateTransactionManager();
315 private ListenableFuture<Void> onDeviceTakeClusterLeadership(final DeviceInfo deviceInfo) {
316 LOG.trace("onDeviceTakeClusterLeadership for node: {}", deviceInfo.getNodeId());
318 StatisticsContext statisticsContext = conductor.getStatisticsContext(deviceInfo);
319 if (statisticsContext == null) {
320 final String errMsg = String.format("DeviceCtx %s is up but we are missing StatisticsContext", deviceInfo.getDatapathId());
322 return Futures.immediateFailedFuture(new IllegalStateException(errMsg));
324 DeviceContext deviceContext = conductor.getDeviceContext(deviceInfo);
325 /* Prepare init info collecting */
326 deviceContext.getDeviceState().setDeviceSynchronized(false);
327 ((DeviceContextImpl)deviceContext).getTransactionChainManager().activateTransactionManager();
328 /* Init Collecting NodeInfo */
329 final ListenableFuture<Void> initCollectingDeviceInfo = DeviceInitializationUtils.initializeNodeInformation(
330 deviceContext, switchFeaturesMandatory);
331 /* Init Collecting StatInfo */
332 final ListenableFuture<Boolean> statPollFuture = Futures.transform(initCollectingDeviceInfo,
333 new AsyncFunction<Void, Boolean>() {
336 public ListenableFuture<Boolean> apply(@Nonnull final Void input) throws Exception {
337 statisticsContext.statListForCollectingInitialization();
338 return statisticsContext.gatherDynamicData();
342 return Futures.transform(statPollFuture, new Function<Boolean, Void>() {
345 public Void apply(final Boolean input) {
346 if (ConnectionContext.CONNECTION_STATE.RIP.equals(conductor.gainConnectionStateSafely(deviceInfo))) {
347 final String errMsg = String.format("We lost connection for Device %s, context has to be closed.",
348 deviceInfo.getNodeId());
350 throw new IllegalStateException(errMsg);
353 final String errMsg = String.format("Get Initial Device %s information fails",
354 deviceInfo.getNodeId());
356 throw new IllegalStateException(errMsg);
358 LOG.debug("Get Initial Device {} information is successful", deviceInfo.getNodeId());
359 deviceContext.getDeviceState().setDeviceSynchronized(true);
360 ((DeviceContextImpl)deviceContext).getTransactionChainManager().initialSubmitWriteTransaction();
361 deviceContext.getDeviceState().setStatisticsPollingEnabledProp(true);