Solves issue with two connections from one device.
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / device / DeviceManagerImpl.java
1 /**
2  * Copyright (c) 2015, 2017 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.util.concurrent.ListenableFuture;
11 import io.netty.util.HashedWheelTimer;
12 import io.netty.util.internal.ConcurrentSet;
13 import java.util.Optional;
14 import java.util.Set;
15 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.concurrent.ConcurrentMap;
17 import java.util.concurrent.ScheduledThreadPoolExecutor;
18 import java.util.concurrent.TimeUnit;
19 import javax.annotation.Nonnull;
20 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
21 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
22 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
25 import org.opendaylight.openflowplugin.api.openflow.OFPContext;
26 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
27 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
28 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
29 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
30 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
31 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
32 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
33 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
34 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
35 import org.opendaylight.openflowplugin.impl.connection.OutboundQueueProviderImpl;
36 import org.opendaylight.openflowplugin.impl.device.initialization.DeviceInitializerProvider;
37 import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
38 import org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtil;
39 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRemovedBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdatedBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.provider.config.rev160510.OpenflowProviderConfig;
47 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  *
53  */
54 public class DeviceManagerImpl implements DeviceManager, ExtensionConverterProviderKeeper {
55
56     private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
57     private static final int SPY_RATE = 10;
58
59     private final OpenflowProviderConfig config;
60     private final DataBroker dataBroker;
61     private final DeviceInitializerProvider deviceInitializerProvider;
62     private final ConvertorExecutor convertorExecutor;
63     private final ConcurrentMap<DeviceInfo, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
64     private final Set<KeyedInstanceIdentifier<Node, NodeKey>> notificationCreateNodeSend = new ConcurrentSet<>();
65     private final NotificationPublishService notificationPublishService;
66     private final MessageSpy messageSpy;
67     private final HashedWheelTimer hashedWheelTimer;
68     private TranslatorLibrary translatorLibrary;
69     private ExtensionConverterProvider extensionConverterProvider;
70     private ScheduledThreadPoolExecutor spyPool;
71
72     public DeviceManagerImpl(@Nonnull final OpenflowProviderConfig config,
73                              @Nonnull final DataBroker dataBroker,
74                              @Nonnull final MessageSpy messageSpy,
75                              @Nonnull final NotificationPublishService notificationPublishService,
76                              @Nonnull final HashedWheelTimer hashedWheelTimer,
77                              @Nonnull final ConvertorExecutor convertorExecutor,
78                              @Nonnull final DeviceInitializerProvider deviceInitializerProvider) {
79         this.config = config;
80         this.dataBroker = dataBroker;
81         this.deviceInitializerProvider = deviceInitializerProvider;
82         this.convertorExecutor = convertorExecutor;
83         this.hashedWheelTimer = hashedWheelTimer;
84         this.spyPool = new ScheduledThreadPoolExecutor(1);
85         this.notificationPublishService = notificationPublishService;
86         this.messageSpy = messageSpy;
87         DeviceInitializationUtil.makeEmptyNodes(dataBroker);
88     }
89
90     @Override
91     public TranslatorLibrary oook() {
92         return translatorLibrary;
93     }
94
95     @Override
96     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
97         this.translatorLibrary = translatorLibrary;
98     }
99
100     @Override
101     public void close() {
102         deviceContexts.values().forEach(OFPContext::close);
103         deviceContexts.clear();
104         Optional.ofNullable(spyPool).ifPresent(ScheduledThreadPoolExecutor::shutdownNow);
105         spyPool = null;
106
107     }
108
109     @Override
110     public void initialize() {
111         spyPool.scheduleAtFixedRate(messageSpy, SPY_RATE, SPY_RATE, TimeUnit.SECONDS);
112     }
113
114     @Override
115     public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
116         this.extensionConverterProvider = extensionConverterProvider;
117     }
118
119     @Override
120     public ExtensionConverterProvider getExtensionConverterProvider() {
121         return extensionConverterProvider;
122     }
123
124     @Override
125     public ListenableFuture<Void> removeDeviceFromOperationalDS(
126             @Nonnull final KeyedInstanceIdentifier<Node, NodeKey> ii) {
127
128         final WriteTransaction delWtx = dataBroker.newWriteOnlyTransaction();
129         delWtx.delete(LogicalDatastoreType.OPERATIONAL, ii);
130         return delWtx.submit();
131
132     }
133
134     public DeviceContext createContext(@Nonnull final ConnectionContext connectionContext) {
135
136         LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
137                 connectionContext.getConnectionAdapter().getRemoteAddress(),
138                 connectionContext.getDeviceInfo().getNodeId());
139
140         connectionContext.getConnectionAdapter().setPacketInFiltering(true);
141
142         final OutboundQueueProvider outboundQueueProvider
143                 = new OutboundQueueProviderImpl(connectionContext.getDeviceInfo().getVersion());
144
145         connectionContext.setOutboundQueueProvider(outboundQueueProvider);
146         final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
147                 connectionContext.getConnectionAdapter().registerOutboundQueueHandler(
148                         outboundQueueProvider,
149                         config.getBarrierCountLimit().getValue(),
150                         TimeUnit.MILLISECONDS.toNanos(config.getBarrierIntervalTimeoutLimit().getValue()));
151         connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
152
153
154         final DeviceContext deviceContext = new DeviceContextImpl(
155                 connectionContext,
156                 dataBroker,
157                 messageSpy,
158                 translatorLibrary,
159                 convertorExecutor,
160                 config.isSkipTableFeatures(),
161                 hashedWheelTimer,
162                 config.isUseSingleLayerSerialization(),
163                 deviceInitializerProvider,
164                 config.isEnableFlowRemovedNotification(),
165                 config.isSwitchFeaturesMandatory());
166
167         ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
168         deviceContext.setNotificationPublishService(notificationPublishService);
169
170         deviceContexts.put(connectionContext.getDeviceInfo(), deviceContext);
171         updatePacketInRateLimiters();
172
173         final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
174                 connectionContext.getConnectionAdapter(), deviceContext);
175
176         connectionContext.getConnectionAdapter().setMessageListener(messageListener);
177         connectionContext.getConnectionAdapter().setAlienMessageListener(messageListener);
178
179         return deviceContext;
180     }
181
182     private void updatePacketInRateLimiters() {
183         synchronized (deviceContexts) {
184             final int deviceContextsSize = deviceContexts.size();
185             if (deviceContextsSize > 0) {
186                 long freshNotificationLimit = config.getGlobalNotificationQuota() / deviceContextsSize;
187                 if (freshNotificationLimit < 100) {
188                     freshNotificationLimit = 100;
189                 }
190                 if (LOG.isDebugEnabled()) {
191                     LOG.debug("fresh notification limit = {}", freshNotificationLimit);
192                 }
193                 for (final DeviceContext deviceContext : deviceContexts.values()) {
194                     deviceContext.updatePacketInRateLimit(freshNotificationLimit);
195                 }
196             }
197         }
198     }
199
200     @Override
201     public void onDeviceRemoved(final DeviceInfo deviceInfo) {
202         deviceContexts.remove(deviceInfo);
203         if (LOG.isDebugEnabled()) {
204             LOG.debug("Device context removed for node {}", deviceInfo);
205         }
206         if (deviceContexts.size() > 0) {
207             this.updatePacketInRateLimiters();
208         }
209     }
210
211     @Override
212     public void sendNodeRemovedNotification(@Nonnull final KeyedInstanceIdentifier<Node, NodeKey> instanceIdentifier) {
213         if (notificationCreateNodeSend.remove(instanceIdentifier)) {
214             NodeRemovedBuilder builder = new NodeRemovedBuilder();
215             builder.setNodeRef(new NodeRef(instanceIdentifier));
216             LOG.info("Publishing node removed notification for {}", instanceIdentifier.firstKeyOf(Node.class).getId());
217             notificationPublishService.offerNotification(builder.build());
218         }
219     }
220
221     @Override
222     public void sendNodeAddedNotification(@Nonnull final KeyedInstanceIdentifier<Node, NodeKey> instanceIdentifier) {
223         if (!notificationCreateNodeSend.contains(instanceIdentifier)) {
224             notificationCreateNodeSend.add(instanceIdentifier);
225             final NodeId id = instanceIdentifier.firstKeyOf(Node.class).getId();
226             NodeUpdatedBuilder builder = new NodeUpdatedBuilder();
227             builder.setId(id);
228             builder.setNodeRef(new NodeRef(instanceIdentifier));
229             LOG.info("Publishing node added notification for {}", id);
230             notificationPublishService.offerNotification(builder.build());
231         }
232     }
233 }