Abstract service
[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.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;
58
59 /**
60  *
61  */
62 public class DeviceManagerImpl implements DeviceManager, ExtensionConverterProviderKeeper {
63
64     private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
65
66     private final long globalNotificationQuota;
67     private final boolean switchFeaturesMandatory;
68
69     private final int spyRate = 10;
70
71     private final DataBroker dataBroker;
72     private TranslatorLibrary translatorLibrary;
73     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
74     private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
75
76     private final ConcurrentMap<DeviceInfo, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
77
78     private final long barrierIntervalNanos;
79     private final int barrierCountLimit;
80     private ExtensionConverterProvider extensionConverterProvider;
81     private ScheduledThreadPoolExecutor spyPool;
82
83     private final LifecycleConductor conductor;
84
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();
94
95         final NodesBuilder nodesBuilder = new NodesBuilder();
96         nodesBuilder.setNode(Collections.<Node>emptyList());
97         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
98         try {
99             tx.submit().get();
100         } catch (ExecutionException | InterruptedException e) {
101             LOG.error("Creation of node failed.", e);
102             throw new IllegalStateException(e);
103         }
104
105         this.barrierIntervalNanos = TimeUnit.MILLISECONDS.toNanos(barrierInterval);
106         this.barrierCountLimit = barrierCountLimit;
107
108         this.conductor = lifecycleConductor;
109         spyPool = new ScheduledThreadPoolExecutor(1);
110     }
111
112
113     @Override
114     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
115         this.deviceInitPhaseHandler = handler;
116     }
117
118     @Override
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();
125     }
126
127     @Override
128     public boolean deviceConnected(@CheckForNull final ConnectionContext connectionContext) throws Exception {
129         Preconditions.checkArgument(connectionContext != null);
130
131         DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
132         /**
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
136          */
137          if (deviceContexts.containsKey(deviceInfo)) {
138             LOG.warn("Rejecting connection from node which is already connected and there exist deviceContext for it: {}", connectionContext.getNodeId());
139              return false;
140          }
141
142         LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
143                 connectionContext.getConnectionAdapter().getRemoteAddress(), deviceInfo.getNodeId());
144
145         // Add Disconnect handler
146         connectionContext.setDeviceDisconnectedHandler(DeviceManagerImpl.this);
147         // Cache this for clarity
148         final ConnectionAdapter connectionAdapter = connectionContext.getConnectionAdapter();
149
150         //FIXME: as soon as auxiliary connection are fully supported then this is needed only before device context published
151         connectionAdapter.setPacketInFiltering(true);
152
153         final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(deviceInfo.getVersion());
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 = new DeviceStateImpl();
161         final DeviceContext deviceContext = new DeviceContextImpl(connectionContext,
162                 deviceState,
163                 dataBroker,
164                 conductor,
165                 outboundQueueProvider,
166                 translatorLibrary);
167
168         Verify.verify(deviceContexts.putIfAbsent(deviceInfo, deviceContext) == null, "DeviceCtx still not closed.");
169
170         ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
171         deviceContext.setNotificationPublishService(conductor.getNotificationPublishService());
172
173         updatePacketInRateLimiters();
174
175         final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
176                 connectionAdapter, deviceContext);
177         connectionAdapter.setMessageListener(messageListener);
178         deviceState.setValid(true);
179
180         deviceInitPhaseHandler.onDeviceContextLevelUp(connectionContext.getDeviceInfo());
181
182         return true;
183     }
184
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;
192                 }
193                 LOG.debug("fresh notification limit = {}", freshNotificationLimit);
194                 for (final DeviceContext deviceContext : deviceContexts.values()) {
195                     deviceContext.updatePacketInRateLimit(freshNotificationLimit);
196                 }
197             }
198         }
199     }
200
201     @Override
202     public TranslatorLibrary oook() {
203         return translatorLibrary;
204     }
205
206     @Override
207     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
208         this.translatorLibrary = translatorLibrary;
209     }
210
211     @Override
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();
218         }
219
220         if (spyPool != null) {
221             spyPool.shutdownNow();
222             spyPool = null;
223         }
224     }
225
226     @Override
227     public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
228         LOG.debug("onDeviceContextClosed for Node {}", deviceInfo.getNodeId());
229         deviceContexts.remove(deviceInfo);
230         updatePacketInRateLimiters();
231     }
232
233     @Override
234     public void initialize() {
235         spyPool.scheduleAtFixedRate(conductor.getMessageIntelligenceAgency(), spyRate, spyRate, TimeUnit.SECONDS);
236     }
237
238     @Override
239     public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
240         this.extensionConverterProvider = extensionConverterProvider;
241     }
242
243     @Override
244     public ExtensionConverterProvider getExtensionConverterProvider() {
245         return extensionConverterProvider;
246     }
247
248     @Override
249     public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
250         this.deviceTerminPhaseHandler = handler;
251     }
252
253     @Override
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);
258
259         if (null == deviceCtx) {
260             LOG.info("DeviceContext for Node {} was not found. Connection is terminated without OFP context suite.", deviceInfo.getNodeId());
261             return;
262         }
263
264         if (!connectionContext.equals(deviceCtx.getPrimaryConnectionContext())) {
265             /* Connection is not PrimaryConnection so try to remove from Auxiliary Connections */
266             deviceCtx.removeAuxiliaryConnectionContext(connectionContext);
267         } else {
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>() {
271
272                 @Override
273                 public void onSuccess(final Void result) {
274                     LOG.debug("TxChainManager for device {} is closed successful.", deviceInfo.getNodeId());
275                     deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
276                 }
277
278                 @Override
279                 public void onFailure(final Throwable t) {
280                     LOG.warn("TxChainManager for device {} failed by closing.", deviceInfo.getNodeId(), t);
281                     deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
282                 }
283             });
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);
289                 }
290             };
291             conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
292         }
293     }
294
295     @VisibleForTesting
296     void addDeviceContextToMap(final DeviceInfo deviceInfo, final DeviceContext deviceContext){
297         deviceContexts.put(deviceInfo, deviceContext);
298     }
299
300     @Override
301     public <T extends OFPContext> T gainContext(final DeviceInfo deviceInfo) {
302         return (T) deviceContexts.get(deviceInfo);
303     }
304
305     @Override
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);
311         }
312         return ((DeviceContextImpl)deviceContext).getTransactionChainManager().deactivateTransactionManager();
313     }
314
315     private ListenableFuture<Void> onDeviceTakeClusterLeadership(final DeviceInfo deviceInfo) {
316         LOG.trace("onDeviceTakeClusterLeadership for node: {}", deviceInfo.getNodeId());
317         /* validation */
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());
321             LOG.warn(errMsg);
322             return Futures.immediateFailedFuture(new IllegalStateException(errMsg));
323         }
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>() {
334
335                     @Override
336                     public ListenableFuture<Boolean> apply(@Nonnull final Void input) throws Exception {
337                         statisticsContext.statListForCollectingInitialization();
338                         return statisticsContext.gatherDynamicData();
339                     }
340                 });
341
342         return Futures.transform(statPollFuture, new Function<Boolean, Void>() {
343
344             @Override
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());
349                     LOG.warn(errMsg);
350                     throw new IllegalStateException(errMsg);
351                 }
352                 if (!input) {
353                     final String errMsg = String.format("Get Initial Device %s information fails",
354                             deviceInfo.getNodeId());
355                     LOG.warn(errMsg);
356                     throw new IllegalStateException(errMsg);
357                 }
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);
362                 return null;
363             }
364         });
365     }
366
367 }