Merge "DevCtx to DevMng"
[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.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.WriteTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
30 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
31 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
32 import org.opendaylight.openflowplugin.api.openflow.OFPContext;
33 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
34 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
35 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
36 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
37 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
38 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
39 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
40 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
41 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
42 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
43 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
44 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
45 import org.opendaylight.openflowplugin.impl.connection.OutboundQueueProviderImpl;
46 import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
51 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  *
57  */
58 public class DeviceManagerImpl implements DeviceManager, ExtensionConverterProviderKeeper {
59
60     private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
61
62     private final long globalNotificationQuota;
63     private final boolean switchFeaturesMandatory;
64
65     private final int spyRate = 10;
66
67     private final DataBroker dataBroker;
68     private TranslatorLibrary translatorLibrary;
69     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
70     private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
71
72     private final ConcurrentMap<DeviceInfo, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
73
74     private final long barrierIntervalNanos;
75     private final int barrierCountLimit;
76     private ExtensionConverterProvider extensionConverterProvider;
77     private ScheduledThreadPoolExecutor spyPool;
78
79     private final LifecycleConductor conductor;
80
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();
90
91         final NodesBuilder nodesBuilder = new NodesBuilder();
92         nodesBuilder.setNode(Collections.<Node>emptyList());
93         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
94         try {
95             tx.submit().get();
96         } catch (ExecutionException | InterruptedException e) {
97             LOG.error("Creation of node failed.", e);
98             throw new IllegalStateException(e);
99         }
100
101         this.barrierIntervalNanos = TimeUnit.MILLISECONDS.toNanos(barrierInterval);
102         this.barrierCountLimit = barrierCountLimit;
103
104         this.conductor = lifecycleConductor;
105         spyPool = new ScheduledThreadPoolExecutor(1);
106     }
107
108
109     @Override
110     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
111         this.deviceInitPhaseHandler = handler;
112     }
113
114     @Override
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();
121     }
122
123     @Override
124     public boolean deviceConnected(@CheckForNull final ConnectionContext connectionContext) throws Exception {
125         Preconditions.checkArgument(connectionContext != null);
126
127         DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
128         /**
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
132          */
133          if (deviceContexts.containsKey(deviceInfo)) {
134             LOG.warn("Rejecting connection from node which is already connected and there exist deviceContext for it: {}", connectionContext.getNodeId());
135              return false;
136          }
137
138         LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
139                 connectionContext.getConnectionAdapter().getRemoteAddress(), deviceInfo.getNodeId());
140
141         // Add Disconnect handler
142         connectionContext.setDeviceDisconnectedHandler(DeviceManagerImpl.this);
143         // Cache this for clarity
144         final ConnectionAdapter connectionAdapter = connectionContext.getConnectionAdapter();
145
146         //FIXME: as soon as auxiliary connection are fully supported then this is needed only before device context published
147         connectionAdapter.setPacketInFiltering(true);
148
149         final Short version = connectionContext.getFeatures().getVersion();
150         final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(version);
151
152         connectionContext.setOutboundQueueProvider(outboundQueueProvider);
153         final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
154                 connectionAdapter.registerOutboundQueueHandler(outboundQueueProvider, barrierCountLimit, barrierIntervalNanos);
155         connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
156
157         final DeviceState deviceState = new DeviceStateImpl();
158         final DeviceContext deviceContext = new DeviceContextImpl(connectionContext,
159                 deviceState,
160                 dataBroker,
161                 conductor,
162                 outboundQueueProvider,
163                 translatorLibrary,
164                 switchFeaturesMandatory);
165
166         Verify.verify(deviceContexts.putIfAbsent(deviceInfo, deviceContext) == null, "DeviceCtx still not closed.");
167
168         ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
169         deviceContext.setNotificationPublishService(conductor.getNotificationPublishService());
170
171         updatePacketInRateLimiters();
172
173         final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
174                 connectionAdapter, deviceContext);
175         connectionAdapter.setMessageListener(messageListener);
176         deviceState.setValid(true);
177
178         deviceInitPhaseHandler.onDeviceContextLevelUp(connectionContext.getDeviceInfo());
179
180         return true;
181     }
182
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;
190                 }
191                 LOG.debug("fresh notification limit = {}", freshNotificationLimit);
192                 for (final DeviceContext deviceContext : deviceContexts.values()) {
193                     deviceContext.updatePacketInRateLimit(freshNotificationLimit);
194                 }
195             }
196         }
197     }
198
199     @Override
200     public TranslatorLibrary oook() {
201         return translatorLibrary;
202     }
203
204     @Override
205     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
206         this.translatorLibrary = translatorLibrary;
207     }
208
209     @Override
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();
216         }
217
218         if (spyPool != null) {
219             spyPool.shutdownNow();
220             spyPool = null;
221         }
222     }
223
224     @Override
225     public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
226         LOG.debug("onDeviceContextClosed for Node {}", deviceInfo.getNodeId());
227         deviceContexts.remove(deviceInfo);
228         updatePacketInRateLimiters();
229     }
230
231     @Override
232     public void initialize() {
233         spyPool.scheduleAtFixedRate(conductor.getMessageIntelligenceAgency(), spyRate, spyRate, TimeUnit.SECONDS);
234     }
235
236     @Override
237     public DeviceContext getDeviceContextFromNodeId(DeviceInfo deviceInfo) {
238         return deviceContexts.get(deviceInfo);
239     }
240
241     @Override
242     public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
243         this.extensionConverterProvider = extensionConverterProvider;
244     }
245
246     @Override
247     public ExtensionConverterProvider getExtensionConverterProvider() {
248         return extensionConverterProvider;
249     }
250
251     @Override
252     public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
253         this.deviceTerminPhaseHandler = handler;
254     }
255
256     @Override
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);
261
262         if (null == deviceCtx) {
263             LOG.info("DeviceContext for Node {} was not found. Connection is terminated without OFP context suite.", deviceInfo.getNodeId());
264             return;
265         }
266
267         if (!connectionContext.equals(deviceCtx.getPrimaryConnectionContext())) {
268             /* Connection is not PrimaryConnection so try to remove from Auxiliary Connections */
269             deviceCtx.removeAuxiliaryConnectionContext(connectionContext);
270         } else {
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>() {
274
275                 @Override
276                 public void onSuccess(final Void result) {
277                     LOG.debug("TxChainManager for device {} is closed successful.", deviceInfo.getNodeId());
278                     deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
279                 }
280
281                 @Override
282                 public void onFailure(final Throwable t) {
283                     LOG.warn("TxChainManager for device {} failed by closing.", deviceInfo.getNodeId(), t);
284                     deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
285                 }
286             });
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);
292                 }
293             };
294             conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
295         }
296     }
297
298     @VisibleForTesting
299     void addDeviceContextToMap(final DeviceInfo deviceInfo, final DeviceContext deviceContext){
300         deviceContexts.put(deviceInfo, deviceContext);
301     }
302
303     @Override
304     public <T extends OFPContext> T gainContext(final DeviceInfo deviceInfo) {
305         return (T) deviceContexts.get(deviceInfo);
306     }
307
308     @Override
309     public ListenableFuture<Void> onClusterRoleChange(final DeviceInfo deviceInfo, final OfpRole role) {
310         DeviceContext deviceContext = conductor.getDeviceContext(deviceInfo);
311         LOG.trace("onClusterRoleChange {} for node:", role, deviceInfo.getNodeId());
312         if (OfpRole.BECOMEMASTER.equals(role)) {
313             return deviceContext.onDeviceTakeClusterLeadership();
314         }
315         return ((DeviceContextImpl)deviceContext).getTransactionChainManager().deactivateTransactionManager();
316     }
317
318 }