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.HashSet;
22 import java.util.Iterator;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ScheduledThreadPoolExecutor;
28 import java.util.concurrent.TimeUnit;
29 import javax.annotation.CheckForNull;
30 import javax.annotation.Nonnull;
31 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
32 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
33 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
34 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
35 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
36 import org.opendaylight.openflowplugin.api.openflow.OFPContext;
37 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
38 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
39 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
40 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
41 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
42 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
43 import org.opendaylight.openflowplugin.api.openflow.device.DeviceSynchronizeListener;
44 import org.opendaylight.openflowplugin.api.openflow.device.DeviceValidListener;
45 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
46 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
47 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
48 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
49 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
50 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
51 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
52 import org.opendaylight.openflowplugin.impl.connection.OutboundQueueProviderImpl;
53 import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
54 import org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtils;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
59 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
66 public class DeviceManagerImpl implements DeviceManager, ExtensionConverterProviderKeeper {
68 private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
70 private final long globalNotificationQuota;
71 private final boolean switchFeaturesMandatory;
73 private final int spyRate = 10;
75 private final DataBroker dataBroker;
76 private TranslatorLibrary translatorLibrary;
77 private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
78 private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
80 private final ConcurrentMap<DeviceInfo, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
82 private final long barrierIntervalNanos;
83 private final int barrierCountLimit;
84 private ExtensionConverterProvider extensionConverterProvider;
85 private ScheduledThreadPoolExecutor spyPool;
86 private Set<DeviceSynchronizeListener> deviceSynchronizedListeners;
87 private Set<DeviceValidListener> deviceValidListeners;
89 private final LifecycleConductor conductor;
91 public DeviceManagerImpl(@Nonnull final DataBroker dataBroker,
92 final long globalNotificationQuota, final boolean switchFeaturesMandatory,
93 final long barrierInterval, final int barrierCountLimit,
94 final LifecycleConductor lifecycleConductor) {
95 this.switchFeaturesMandatory = switchFeaturesMandatory;
96 this.globalNotificationQuota = globalNotificationQuota;
97 this.dataBroker = Preconditions.checkNotNull(dataBroker);
98 /* merge empty nodes to oper DS to predict any problems with missing parent for Node */
99 final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
101 final NodesBuilder nodesBuilder = new NodesBuilder();
102 nodesBuilder.setNode(Collections.<Node>emptyList());
103 tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
106 } catch (ExecutionException | InterruptedException e) {
107 LOG.error("Creation of node failed.", e);
108 throw new IllegalStateException(e);
111 this.barrierIntervalNanos = TimeUnit.MILLISECONDS.toNanos(barrierInterval);
112 this.barrierCountLimit = barrierCountLimit;
114 this.conductor = lifecycleConductor;
115 spyPool = new ScheduledThreadPoolExecutor(1);
116 this.deviceSynchronizedListeners = new HashSet<>();
117 this.deviceValidListeners = new HashSet<>();
122 public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
123 this.deviceInitPhaseHandler = handler;
127 public void onDeviceContextLevelUp(@CheckForNull DeviceInfo deviceInfo) throws Exception {
128 // final phase - we have to add new Device to MD-SAL DataStore
129 LOG.debug("Final phase of DeviceContextLevelUp for Node: {} ", deviceInfo.getNodeId());
130 DeviceContext deviceContext = Preconditions.checkNotNull(deviceContexts.get(deviceInfo));
131 ((DeviceContextImpl) deviceContext).initialSubmitTransaction();
132 deviceContext.onPublished();
136 public boolean deviceConnected(@CheckForNull final ConnectionContext connectionContext) throws Exception {
137 Preconditions.checkArgument(connectionContext != null);
139 DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
141 * This part prevent destroy another device context. Throwing here an exception result to propagate close connection
142 * in {@link org.opendaylight.openflowplugin.impl.connection.org.opendaylight.openflowplugin.impl.connection.HandshakeContextImpl}
143 * If context already exist we are in state closing process (connection flapping) and we should not propagate connection close
145 if (deviceContexts.containsKey(deviceInfo)) {
146 LOG.warn("Rejecting connection from node which is already connected and there exist deviceContext for it: {}", connectionContext.getNodeId());
150 LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
151 connectionContext.getConnectionAdapter().getRemoteAddress(), deviceInfo.getNodeId());
153 // Add Disconnect handler
154 connectionContext.setDeviceDisconnectedHandler(DeviceManagerImpl.this);
155 // Cache this for clarity
156 final ConnectionAdapter connectionAdapter = connectionContext.getConnectionAdapter();
158 //FIXME: as soon as auxiliary connection are fully supported then this is needed only before device context published
159 connectionAdapter.setPacketInFiltering(true);
161 final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(deviceInfo.getVersion());
163 connectionContext.setOutboundQueueProvider(outboundQueueProvider);
164 final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
165 connectionAdapter.registerOutboundQueueHandler(outboundQueueProvider, barrierCountLimit, barrierIntervalNanos);
166 connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
168 final DeviceState deviceState = new DeviceStateImpl(deviceInfo);
169 this.addDeviceSynchronizeListener(deviceState);
170 this.addDeviceValidListener(deviceState);
172 final DeviceContext deviceContext = new DeviceContextImpl(connectionContext,
176 outboundQueueProvider,
179 Verify.verify(deviceContexts.putIfAbsent(deviceInfo, deviceContext) == null, "DeviceCtx still not closed.");
181 ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
182 deviceContext.setNotificationPublishService(conductor.getNotificationPublishService());
184 updatePacketInRateLimiters();
186 final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
187 connectionAdapter, deviceContext);
188 connectionAdapter.setMessageListener(messageListener);
189 notifyDeviceValidListeners(deviceInfo, true);
191 deviceInitPhaseHandler.onDeviceContextLevelUp(connectionContext.getDeviceInfo());
193 notifyDeviceSynchronizeListeners(deviceInfo, true);
198 private void updatePacketInRateLimiters() {
199 synchronized (deviceContexts) {
200 final int deviceContextsSize = deviceContexts.size();
201 if (deviceContextsSize > 0) {
202 long freshNotificationLimit = globalNotificationQuota / deviceContextsSize;
203 if (freshNotificationLimit < 100) {
204 freshNotificationLimit = 100;
206 LOG.debug("fresh notification limit = {}", freshNotificationLimit);
207 for (final DeviceContext deviceContext : deviceContexts.values()) {
208 deviceContext.updatePacketInRateLimit(freshNotificationLimit);
215 public TranslatorLibrary oook() {
216 return translatorLibrary;
220 public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
221 this.translatorLibrary = translatorLibrary;
225 public void close() {
226 for (final Iterator<DeviceContext> iterator = Iterators.consumingIterator(deviceContexts.values().iterator());
227 iterator.hasNext();) {
228 final DeviceContext deviceCtx = iterator.next();
229 notifyDeviceValidListeners(deviceCtx.getDeviceInfo(), false);
230 deviceCtx.shutdownConnection();
231 deviceCtx.shuttingDownDataStoreTransactions();
234 if (spyPool != null) {
235 spyPool.shutdownNow();
241 public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
242 LOG.debug("onDeviceContextClosed for Node {}", deviceInfo.getNodeId());
243 deviceContexts.remove(deviceInfo);
244 updatePacketInRateLimiters();
248 public void initialize() {
249 spyPool.scheduleAtFixedRate(conductor.getMessageIntelligenceAgency(), spyRate, spyRate, TimeUnit.SECONDS);
253 public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
254 this.extensionConverterProvider = extensionConverterProvider;
258 public ExtensionConverterProvider getExtensionConverterProvider() {
259 return extensionConverterProvider;
263 public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
264 this.deviceTerminPhaseHandler = handler;
268 public void onDeviceDisconnected(final ConnectionContext connectionContext) {
269 LOG.trace("onDeviceDisconnected method call for Node: {}", connectionContext.getNodeId());
270 final DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
271 final DeviceContext deviceCtx = this.deviceContexts.get(deviceInfo);
273 if (null == deviceCtx) {
274 LOG.info("DeviceContext for Node {} was not found. Connection is terminated without OFP context suite.", deviceInfo.getNodeId());
278 if (!connectionContext.equals(deviceCtx.getPrimaryConnectionContext())) {
279 /* Connection is not PrimaryConnection so try to remove from Auxiliary Connections */
280 deviceCtx.removeAuxiliaryConnectionContext(connectionContext);
282 notifyDeviceValidListeners(deviceInfo, false);
283 /* Device is disconnected and so we need to close TxManager */
284 final ListenableFuture<Void> future = deviceCtx.shuttingDownDataStoreTransactions();
285 Futures.addCallback(future, new FutureCallback<Void>() {
288 public void onSuccess(final Void result) {
289 LOG.debug("TxChainManager for device {} is closed successful.", deviceInfo.getNodeId());
290 deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
294 public void onFailure(final Throwable t) {
295 LOG.warn("TxChainManager for device {} failed by closing.", deviceInfo.getNodeId(), t);
296 deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
299 /* Add timer for Close TxManager because it could fain ind cluster without notification */
300 final TimerTask timerTask = timeout -> {
301 if (!future.isDone()) {
302 LOG.info("Shutting down TxChain for node {} not completed during 10 sec. Continue anyway.", deviceInfo.getNodeId());
303 future.cancel(false);
306 conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
311 void addDeviceContextToMap(final DeviceInfo deviceInfo, final DeviceContext deviceContext){
312 deviceContexts.put(deviceInfo, deviceContext);
316 public <T extends OFPContext> T gainContext(final DeviceInfo deviceInfo) {
317 return (T) deviceContexts.get(deviceInfo);
321 public ListenableFuture<Void> onClusterRoleChange(final DeviceInfo deviceInfo, final OfpRole role) {
322 DeviceContext deviceContext = conductor.getDeviceContext(deviceInfo);
323 LOG.trace("onClusterRoleChange {} for node:", role, deviceInfo.getNodeId());
324 if (OfpRole.BECOMEMASTER.equals(role)) {
325 return onDeviceTakeClusterLeadership(deviceInfo);
327 return ((DeviceContextImpl)deviceContext).getTransactionChainManager().deactivateTransactionManager();
331 public void addDeviceSynchronizeListener(final DeviceSynchronizeListener deviceSynchronizeListener) {
332 this.deviceSynchronizedListeners.add(deviceSynchronizeListener);
336 public void notifyDeviceSynchronizeListeners(final DeviceInfo deviceInfo, final boolean deviceSynchronized) {
337 for (DeviceSynchronizeListener listener : deviceSynchronizedListeners) {
338 listener.deviceIsSynchronized(deviceInfo, deviceSynchronized);
343 public void addDeviceValidListener(final DeviceValidListener deviceValidListener) {
344 this.deviceValidListeners.add(deviceValidListener);
348 public void notifyDeviceValidListeners(final DeviceInfo deviceInfo, final boolean deviceValid) {
349 for (DeviceValidListener listener : deviceValidListeners) {
350 listener.deviceIsValid(deviceInfo, deviceValid);
354 private ListenableFuture<Void> onDeviceTakeClusterLeadership(final DeviceInfo deviceInfo) {
355 LOG.trace("onDeviceTakeClusterLeadership for node: {}", deviceInfo.getNodeId());
357 StatisticsContext statisticsContext = conductor.getStatisticsContext(deviceInfo);
358 if (statisticsContext == null) {
359 final String errMsg = String.format("DeviceCtx %s is up but we are missing StatisticsContext", deviceInfo.getDatapathId());
361 return Futures.immediateFailedFuture(new IllegalStateException(errMsg));
363 DeviceContext deviceContext = conductor.getDeviceContext(deviceInfo);
364 /* Prepare init info collecting */
365 notifyDeviceSynchronizeListeners(deviceInfo, false);
366 ((DeviceContextImpl)deviceContext).getTransactionChainManager().activateTransactionManager();
367 /* Init Collecting NodeInfo */
368 final ListenableFuture<Void> initCollectingDeviceInfo = DeviceInitializationUtils.initializeNodeInformation(
369 deviceContext, switchFeaturesMandatory);
370 /* Init Collecting StatInfo */
371 final ListenableFuture<Boolean> statPollFuture = Futures.transform(initCollectingDeviceInfo,
372 new AsyncFunction<Void, Boolean>() {
375 public ListenableFuture<Boolean> apply(@Nonnull final Void input) throws Exception {
376 statisticsContext.statListForCollectingInitialization();
377 return statisticsContext.initialGatherDynamicData();
381 return Futures.transform(statPollFuture, new Function<Boolean, Void>() {
384 public Void apply(final Boolean input) {
385 if (ConnectionContext.CONNECTION_STATE.RIP.equals(conductor.gainConnectionStateSafely(deviceInfo))) {
386 final String errMsg = String.format("We lost connection for Device %s, context has to be closed.",
387 deviceInfo.getNodeId());
389 throw new IllegalStateException(errMsg);
392 final String errMsg = String.format("Get Initial Device %s information fails",
393 deviceInfo.getNodeId());
395 throw new IllegalStateException(errMsg);
397 LOG.debug("Get Initial Device {} information is successful", deviceInfo.getNodeId());
398 notifyDeviceSynchronizeListeners(deviceInfo, true);
399 ((DeviceContextImpl)deviceContext).getTransactionChainManager().initialSubmitWriteTransaction();
400 deviceContext.getDeviceState().setStatisticsPollingEnabledProp(true);