Merge "Bug 6050 - TcpSrcCodec is not maskable"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / device / DeviceManagerImpl.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.device;
9
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;
23 import java.util.Set;
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;
62
63 /**
64  *
65  */
66 public class DeviceManagerImpl implements DeviceManager, ExtensionConverterProviderKeeper {
67
68     private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
69
70     private final long globalNotificationQuota;
71     private final boolean switchFeaturesMandatory;
72
73     private final int spyRate = 10;
74
75     private final DataBroker dataBroker;
76     private TranslatorLibrary translatorLibrary;
77     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
78     private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
79
80     private final ConcurrentMap<DeviceInfo, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
81
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;
88
89     private final LifecycleConductor conductor;
90
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();
100
101         final NodesBuilder nodesBuilder = new NodesBuilder();
102         nodesBuilder.setNode(Collections.<Node>emptyList());
103         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
104         try {
105             tx.submit().get();
106         } catch (ExecutionException | InterruptedException e) {
107             LOG.error("Creation of node failed.", e);
108             throw new IllegalStateException(e);
109         }
110
111         this.barrierIntervalNanos = TimeUnit.MILLISECONDS.toNanos(barrierInterval);
112         this.barrierCountLimit = barrierCountLimit;
113
114         this.conductor = lifecycleConductor;
115         spyPool = new ScheduledThreadPoolExecutor(1);
116         this.deviceSynchronizedListeners = new HashSet<>();
117         this.deviceValidListeners = new HashSet<>();
118     }
119
120
121     @Override
122     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
123         this.deviceInitPhaseHandler = handler;
124     }
125
126     @Override
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();
133     }
134
135     @Override
136     public boolean deviceConnected(@CheckForNull final ConnectionContext connectionContext) throws Exception {
137         Preconditions.checkArgument(connectionContext != null);
138
139         DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
140         /**
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
144          */
145          if (deviceContexts.containsKey(deviceInfo)) {
146             LOG.warn("Rejecting connection from node which is already connected and there exist deviceContext for it: {}", connectionContext.getNodeId());
147              return false;
148          }
149
150         LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
151                 connectionContext.getConnectionAdapter().getRemoteAddress(), deviceInfo.getNodeId());
152
153         // Add Disconnect handler
154         connectionContext.setDeviceDisconnectedHandler(DeviceManagerImpl.this);
155         // Cache this for clarity
156         final ConnectionAdapter connectionAdapter = connectionContext.getConnectionAdapter();
157
158         //FIXME: as soon as auxiliary connection are fully supported then this is needed only before device context published
159         connectionAdapter.setPacketInFiltering(true);
160
161         final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(deviceInfo.getVersion());
162
163         connectionContext.setOutboundQueueProvider(outboundQueueProvider);
164         final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
165                 connectionAdapter.registerOutboundQueueHandler(outboundQueueProvider, barrierCountLimit, barrierIntervalNanos);
166         connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
167
168         final DeviceState deviceState = new DeviceStateImpl(deviceInfo);
169         this.addDeviceSynchronizeListener(deviceState);
170         this.addDeviceValidListener(deviceState);
171
172         final DeviceContext deviceContext = new DeviceContextImpl(connectionContext,
173                 deviceState,
174                 dataBroker,
175                 conductor,
176                 outboundQueueProvider,
177                 translatorLibrary);
178
179         Verify.verify(deviceContexts.putIfAbsent(deviceInfo, deviceContext) == null, "DeviceCtx still not closed.");
180
181         ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
182         deviceContext.setNotificationPublishService(conductor.getNotificationPublishService());
183
184         updatePacketInRateLimiters();
185
186         final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
187                 connectionAdapter, deviceContext);
188         connectionAdapter.setMessageListener(messageListener);
189         notifyDeviceValidListeners(deviceInfo, true);
190
191         deviceInitPhaseHandler.onDeviceContextLevelUp(connectionContext.getDeviceInfo());
192
193         notifyDeviceSynchronizeListeners(deviceInfo, true);
194
195         return true;
196     }
197
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;
205                 }
206                 LOG.debug("fresh notification limit = {}", freshNotificationLimit);
207                 for (final DeviceContext deviceContext : deviceContexts.values()) {
208                     deviceContext.updatePacketInRateLimit(freshNotificationLimit);
209                 }
210             }
211         }
212     }
213
214     @Override
215     public TranslatorLibrary oook() {
216         return translatorLibrary;
217     }
218
219     @Override
220     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
221         this.translatorLibrary = translatorLibrary;
222     }
223
224     @Override
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();
232         }
233
234         if (spyPool != null) {
235             spyPool.shutdownNow();
236             spyPool = null;
237         }
238     }
239
240     @Override
241     public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
242         LOG.debug("onDeviceContextClosed for Node {}", deviceInfo.getNodeId());
243         deviceContexts.remove(deviceInfo);
244         updatePacketInRateLimiters();
245     }
246
247     @Override
248     public void initialize() {
249         spyPool.scheduleAtFixedRate(conductor.getMessageIntelligenceAgency(), spyRate, spyRate, TimeUnit.SECONDS);
250     }
251
252     @Override
253     public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
254         this.extensionConverterProvider = extensionConverterProvider;
255     }
256
257     @Override
258     public ExtensionConverterProvider getExtensionConverterProvider() {
259         return extensionConverterProvider;
260     }
261
262     @Override
263     public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
264         this.deviceTerminPhaseHandler = handler;
265     }
266
267     @Override
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);
272
273         if (null == deviceCtx) {
274             LOG.info("DeviceContext for Node {} was not found. Connection is terminated without OFP context suite.", deviceInfo.getNodeId());
275             return;
276         }
277
278         if (!connectionContext.equals(deviceCtx.getPrimaryConnectionContext())) {
279             /* Connection is not PrimaryConnection so try to remove from Auxiliary Connections */
280             deviceCtx.removeAuxiliaryConnectionContext(connectionContext);
281         } else {
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>() {
286
287                 @Override
288                 public void onSuccess(final Void result) {
289                     LOG.debug("TxChainManager for device {} is closed successful.", deviceInfo.getNodeId());
290                     deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
291                 }
292
293                 @Override
294                 public void onFailure(final Throwable t) {
295                     LOG.warn("TxChainManager for device {} failed by closing.", deviceInfo.getNodeId(), t);
296                     deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
297                 }
298             });
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);
304                 }
305             };
306             conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
307         }
308     }
309
310     @VisibleForTesting
311     void addDeviceContextToMap(final DeviceInfo deviceInfo, final DeviceContext deviceContext){
312         deviceContexts.put(deviceInfo, deviceContext);
313     }
314
315     @Override
316     public <T extends OFPContext> T gainContext(final DeviceInfo deviceInfo) {
317         return (T) deviceContexts.get(deviceInfo);
318     }
319
320     @Override
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);
326         }
327         return ((DeviceContextImpl)deviceContext).getTransactionChainManager().deactivateTransactionManager();
328     }
329
330     @Override
331     public void addDeviceSynchronizeListener(final DeviceSynchronizeListener deviceSynchronizeListener) {
332         this.deviceSynchronizedListeners.add(deviceSynchronizeListener);
333     }
334
335     @Override
336     public void notifyDeviceSynchronizeListeners(final DeviceInfo deviceInfo, final boolean deviceSynchronized) {
337         for (DeviceSynchronizeListener listener : deviceSynchronizedListeners) {
338             listener.deviceIsSynchronized(deviceInfo, deviceSynchronized);
339         }
340     }
341
342     @Override
343     public void addDeviceValidListener(final DeviceValidListener deviceValidListener) {
344         this.deviceValidListeners.add(deviceValidListener);
345     }
346
347     @Override
348     public void notifyDeviceValidListeners(final DeviceInfo deviceInfo, final boolean deviceValid) {
349         for (DeviceValidListener listener : deviceValidListeners) {
350             listener.deviceIsValid(deviceInfo, deviceValid);
351         }
352     }
353
354     private ListenableFuture<Void> onDeviceTakeClusterLeadership(final DeviceInfo deviceInfo) {
355         LOG.trace("onDeviceTakeClusterLeadership for node: {}", deviceInfo.getNodeId());
356         /* validation */
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());
360             LOG.warn(errMsg);
361             return Futures.immediateFailedFuture(new IllegalStateException(errMsg));
362         }
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>() {
373
374                     @Override
375                     public ListenableFuture<Boolean> apply(@Nonnull final Void input) throws Exception {
376                         statisticsContext.statListForCollectingInitialization();
377                         return statisticsContext.initialGatherDynamicData();
378                     }
379                 });
380
381         return Futures.transform(statPollFuture, new Function<Boolean, Void>() {
382
383             @Override
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());
388                     LOG.warn(errMsg);
389                     throw new IllegalStateException(errMsg);
390                 }
391                 if (!input) {
392                     final String errMsg = String.format("Get Initial Device %s information fails",
393                             deviceInfo.getNodeId());
394                     LOG.warn(errMsg);
395                     throw new IllegalStateException(errMsg);
396                 }
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);
401                 return null;
402             }
403         });
404     }
405
406 }