Merge "Device Info"
[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.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;
55
56 /**
57  *
58  */
59 public class DeviceManagerImpl implements DeviceManager, ExtensionConverterProviderKeeper {
60
61     private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
62
63     private final long globalNotificationQuota;
64     private final boolean switchFeaturesMandatory;
65
66     private final int spyRate = 10;
67
68     private final DataBroker dataBroker;
69     private TranslatorLibrary translatorLibrary;
70     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
71     private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
72     private NotificationPublishService notificationPublishService;
73
74     private final ConcurrentMap<NodeId, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
75
76     private final long barrierIntervalNanos;
77     private final int barrierCountLimit;
78     private ExtensionConverterProvider extensionConverterProvider;
79     private ScheduledThreadPoolExecutor spyPool;
80
81     private final LifecycleConductor conductor;
82     private boolean isStatisticsRpcEnabled;
83
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();
93
94         final NodesBuilder nodesBuilder = new NodesBuilder();
95         nodesBuilder.setNode(Collections.<Node>emptyList());
96         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
97         try {
98             tx.submit().get();
99         } catch (ExecutionException | InterruptedException e) {
100             LOG.error("Creation of node failed.", e);
101             throw new IllegalStateException(e);
102         }
103
104         this.barrierIntervalNanos = TimeUnit.MILLISECONDS.toNanos(barrierInterval);
105         this.barrierCountLimit = barrierCountLimit;
106
107         this.conductor = lifecycleConductor;
108         spyPool = new ScheduledThreadPoolExecutor(1);
109     }
110
111
112     @Override
113     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
114         this.deviceInitPhaseHandler = handler;
115     }
116
117     @Override
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();
124     }
125
126     @Override
127     public boolean deviceConnected(@CheckForNull final ConnectionContext connectionContext) throws Exception {
128         Preconditions.checkArgument(connectionContext != null);
129
130         NodeId nodeId = connectionContext.getNodeId();
131         /**
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
135          */
136          if (deviceContexts.containsKey(nodeId)) {
137             LOG.warn("Rejecting connection from node which is already connected and there exist deviceContext for it: {}", connectionContext.getNodeId());
138              return false;
139          }
140
141         LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
142                 connectionContext.getConnectionAdapter().getRemoteAddress(), nodeId);
143
144         // Add Disconnect handler
145         connectionContext.setDeviceDisconnectedHandler(DeviceManagerImpl.this);
146         // Cache this for clarity
147         final ConnectionAdapter connectionAdapter = connectionContext.getConnectionAdapter();
148
149         //FIXME: as soon as auxiliary connection are fully supported then this is needed only before device context published
150         connectionAdapter.setPacketInFiltering(true);
151
152         final Short version = connectionContext.getFeatures().getVersion();
153         final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(version);
154
155         connectionContext.setOutboundQueueProvider(outboundQueueProvider);
156         final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
157                 connectionAdapter.registerOutboundQueueHandler(outboundQueueProvider, barrierCountLimit, barrierIntervalNanos);
158         connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
159
160         final DeviceState deviceState = createDeviceState(connectionContext);
161         final DeviceContext deviceContext = new DeviceContextImpl(connectionContext,
162                 deviceState,
163                 dataBroker,
164                 conductor,
165                 outboundQueueProvider,
166                 translatorLibrary,
167                 switchFeaturesMandatory);
168
169         Verify.verify(deviceContexts.putIfAbsent(nodeId, deviceContext) == null, "DeviceCtx still not closed.");
170
171         ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
172         deviceContext.setStatisticsRpcEnabled(isStatisticsRpcEnabled);
173         deviceContext.setNotificationPublishService(notificationPublishService);
174
175         updatePacketInRateLimiters();
176
177         final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
178                 connectionAdapter, deviceContext);
179         connectionAdapter.setMessageListener(messageListener);
180         deviceState.setValid(true);
181
182         deviceInitPhaseHandler.onDeviceContextLevelUp(connectionContext.gainDeviceInfo());
183
184         return true;
185     }
186
187     private static DeviceStateImpl createDeviceState(final @Nonnull ConnectionContext connectionContext) {
188         return new DeviceStateImpl(connectionContext.getFeatures(), connectionContext.getNodeId());
189     }
190
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;
198                 }
199                 LOG.debug("fresh notification limit = {}", freshNotificationLimit);
200                 for (final DeviceContext deviceContext : deviceContexts.values()) {
201                     deviceContext.updatePacketInRateLimit(freshNotificationLimit);
202                 }
203             }
204         }
205     }
206
207     @Override
208     public TranslatorLibrary oook() {
209         return translatorLibrary;
210     }
211
212     @Override
213     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
214         this.translatorLibrary = translatorLibrary;
215     }
216
217     @Override
218     public void setNotificationPublishService(final NotificationPublishService notificationService) {
219         notificationPublishService = notificationService;
220     }
221
222     @Override
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();
229         }
230
231         if (spyPool != null) {
232             spyPool.shutdownNow();
233             spyPool = null;
234         }
235     }
236
237     @Override
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();
242     }
243
244     @Override
245     public void initialize() {
246         spyPool.scheduleAtFixedRate(conductor.getMessageIntelligenceAgency(), spyRate, spyRate, TimeUnit.SECONDS);
247     }
248
249     @Override
250     public DeviceContext getDeviceContextFromNodeId(final NodeId nodeId) {
251         return deviceContexts.get(nodeId);
252     }
253
254     @Override
255     public void setStatisticsRpcEnabled(boolean isStatisticsRpcEnabled) {
256         this.isStatisticsRpcEnabled = isStatisticsRpcEnabled;
257     }
258
259     @Override
260     public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
261         this.extensionConverterProvider = extensionConverterProvider;
262     }
263
264     @Override
265     public ExtensionConverterProvider getExtensionConverterProvider() {
266         return extensionConverterProvider;
267     }
268
269     @Override
270     public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
271         this.deviceTerminPhaseHandler = handler;
272     }
273
274     @Override
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);
279
280         if (null == deviceCtx) {
281             LOG.info("DeviceContext for Node {} was not found. Connection is terminated without OFP context suite.", nodeId);
282             return;
283         }
284
285         if (!connectionContext.equals(deviceCtx.getPrimaryConnectionContext())) {
286             /* Connection is not PrimaryConnection so try to remove from Auxiliary Connections */
287             deviceCtx.removeAuxiliaryConnectionContext(connectionContext);
288         } else {
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>() {
292
293                 @Override
294                 public void onSuccess(final Void result) {
295                     LOG.debug("TxChainManager for device {} is closed successful.", nodeId);
296                     deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceCtx);
297                 }
298
299                 @Override
300                 public void onFailure(final Throwable t) {
301                     LOG.warn("TxChainManager for device {} failed by closing.", nodeId, t);
302                     deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceCtx);
303                 }
304             });
305             /* Add timer for Close TxManager because it could fain ind cluster without notification */
306             final TimerTask timerTask = new TimerTask() {
307
308                 @Override
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);
313                     }
314                 }
315             };
316             conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
317         }
318     }
319
320     @VisibleForTesting
321     void addDeviceContextToMap(final NodeId nodeId, final DeviceContext deviceContext){
322         deviceContexts.put(nodeId, deviceContext);
323     }
324 }