407a5943d70e937e53f9d3053555b8d9424857b9
[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.CheckedFuture;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import io.netty.util.HashedWheelTimer;
14 import io.netty.util.internal.ConcurrentSet;
15 import java.util.Collections;
16 import java.util.Optional;
17 import java.util.Set;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ConcurrentMap;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.ScheduledThreadPoolExecutor;
22 import java.util.concurrent.TimeUnit;
23 import javax.annotation.Nonnull;
24 import javax.annotation.Nullable;
25 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
26 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
27 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
28 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
29 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
30 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
31 import org.opendaylight.openflowplugin.api.openflow.OFPContext;
32 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
33 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
34 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
35 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
36 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
37 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
38 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
39 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
40 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
41 import org.opendaylight.openflowplugin.impl.connection.OutboundQueueProviderImpl;
42 import org.opendaylight.openflowplugin.impl.device.initialization.DeviceInitializerProvider;
43 import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
44 import org.opendaylight.openflowplugin.impl.services.sal.SalRoleServiceImpl;
45 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRemovedBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdatedBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
54 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
55 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
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 long globalNotificationQuota;
67     private boolean switchFeaturesMandatory;
68     private boolean isFlowRemovedNotificationOn;
69     private boolean skipTableFeatures;
70     private static final int SPY_RATE = 10;
71
72     private final DataBroker dataBroker;
73     private final DeviceInitializerProvider deviceInitializerProvider;
74     private final ConvertorExecutor convertorExecutor;
75     private TranslatorLibrary translatorLibrary;
76
77     private final ConcurrentMap<DeviceInfo, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
78     private final Set<KeyedInstanceIdentifier<Node, NodeKey>> notificationCreateNodeSend = new ConcurrentSet<>();
79
80     private long barrierIntervalNanos;
81     private int barrierCountLimit;
82
83     private ExtensionConverterProvider extensionConverterProvider;
84     private ScheduledThreadPoolExecutor spyPool;
85     private final NotificationPublishService notificationPublishService;
86     private final MessageSpy messageSpy;
87     private final HashedWheelTimer hashedWheelTimer;
88     private final boolean useSingleLayerSerialization;
89
90     public DeviceManagerImpl(@Nonnull final DataBroker dataBroker,
91                              @Nonnull final MessageSpy messageSpy,
92                              @Nullable final NotificationPublishService notificationPublishService,
93                              @Nonnull final HashedWheelTimer hashedWheelTimer,
94                              @Nonnull final ConvertorExecutor convertorExecutor,
95                              @Nonnull final DeviceInitializerProvider deviceInitializerProvider,
96                              final boolean useSingleLayerSerialization) {
97
98         this.dataBroker = dataBroker;
99         this.deviceInitializerProvider = deviceInitializerProvider;
100         this.useSingleLayerSerialization = useSingleLayerSerialization;
101
102         /* merge empty nodes to oper DS to predict any problems with missing parent for Node */
103         final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
104         final NodesBuilder nodesBuilder = new NodesBuilder();
105         nodesBuilder.setNode(Collections.<Node>emptyList());
106         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
107         try {
108             tx.submit().get();
109         } catch (ExecutionException | InterruptedException e) {
110             LOG.error("Creation of node failed.", e);
111             throw new IllegalStateException(e);
112         }
113
114         this.convertorExecutor = convertorExecutor;
115         this.hashedWheelTimer = hashedWheelTimer;
116         this.spyPool = new ScheduledThreadPoolExecutor(1);
117         this.notificationPublishService = notificationPublishService;
118         this.messageSpy = messageSpy;
119     }
120
121     @Override
122     public TranslatorLibrary oook() {
123         return translatorLibrary;
124     }
125
126     @Override
127     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
128         this.translatorLibrary = translatorLibrary;
129     }
130
131     @Override
132     public void close() {
133         deviceContexts.values().forEach(OFPContext::close);
134         deviceContexts.clear();
135         Optional.ofNullable(spyPool).ifPresent(ScheduledThreadPoolExecutor::shutdownNow);
136         spyPool = null;
137
138     }
139
140     @Override
141     public void initialize() {
142         spyPool.scheduleAtFixedRate(messageSpy, SPY_RATE, SPY_RATE, TimeUnit.SECONDS);
143     }
144
145     @Override
146     public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
147         this.extensionConverterProvider = extensionConverterProvider;
148     }
149
150     @Override
151     public ExtensionConverterProvider getExtensionConverterProvider() {
152         return extensionConverterProvider;
153     }
154
155     @Override
156     public void setFlowRemovedNotificationOn(boolean isNotificationFlowRemovedOff) {
157         this.isFlowRemovedNotificationOn = isNotificationFlowRemovedOff;
158     }
159
160     @Override
161     public boolean isFlowRemovedNotificationOn() {
162         return this.isFlowRemovedNotificationOn;
163     }
164
165     @Override
166     public void setGlobalNotificationQuota(final long globalNotificationQuota) {
167         this.globalNotificationQuota = globalNotificationQuota;
168     }
169
170     @Override
171     public void setSwitchFeaturesMandatory(final boolean switchFeaturesMandatory) {
172         this.switchFeaturesMandatory = switchFeaturesMandatory;
173     }
174
175     @Override
176     public void setSkipTableFeatures(boolean skipTableFeaturesValue) {
177         skipTableFeatures = skipTableFeaturesValue;
178     }
179
180     @Override
181     public void setBarrierCountLimit(final int barrierCountLimit) {
182         this.barrierCountLimit = barrierCountLimit;
183     }
184
185     @Override
186     public void setBarrierInterval(final long barrierTimeoutLimit) {
187         this.barrierIntervalNanos = TimeUnit.MILLISECONDS.toNanos(barrierTimeoutLimit);
188     }
189
190     @Override
191     public CheckedFuture<Void, TransactionCommitFailedException> removeDeviceFromOperationalDS(@Nonnull final KeyedInstanceIdentifier<Node, NodeKey> ii) {
192         final WriteTransaction delWtx = dataBroker.newWriteOnlyTransaction();
193         delWtx.delete(LogicalDatastoreType.OPERATIONAL, ii);
194         final CheckedFuture<Void, TransactionCommitFailedException> delFuture = delWtx.submit();
195
196         Futures.addCallback(delFuture, new FutureCallback<Void>() {
197             @Override
198             public void onSuccess(final Void result) {
199                 if (LOG.isDebugEnabled()) {
200                     LOG.debug("Delete Node {} was successful", ii);
201                 }
202             }
203
204             @Override
205             public void onFailure(@Nonnull final Throwable t) {
206                 LOG.warn("Delete node {} failed with exception {}", ii, t);
207             }
208         });
209
210         return delFuture;
211     }
212
213     public DeviceContext createContext(@Nonnull final ConnectionContext connectionContext) {
214
215         LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
216                 connectionContext.getConnectionAdapter().getRemoteAddress(),
217                 connectionContext.getDeviceInfo().getNodeId());
218
219         connectionContext.getConnectionAdapter().setPacketInFiltering(true);
220
221         final OutboundQueueProvider outboundQueueProvider
222                 = new OutboundQueueProviderImpl(connectionContext.getDeviceInfo().getVersion());
223
224         connectionContext.setOutboundQueueProvider(outboundQueueProvider);
225         final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
226                 connectionContext.getConnectionAdapter().registerOutboundQueueHandler(
227                         outboundQueueProvider,
228                         barrierCountLimit,
229                         barrierIntervalNanos);
230         connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
231
232
233         final DeviceContext deviceContext = new DeviceContextImpl(
234                 connectionContext,
235                 dataBroker,
236                 messageSpy,
237                 translatorLibrary,
238                 this,
239                 convertorExecutor,
240                 skipTableFeatures,
241                 hashedWheelTimer,
242                 useSingleLayerSerialization,
243                 deviceInitializerProvider);
244
245         deviceContext.setSalRoleService(new SalRoleServiceImpl(deviceContext, deviceContext));
246         deviceContext.setSwitchFeaturesMandatory(switchFeaturesMandatory);
247         ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
248         deviceContext.setNotificationPublishService(notificationPublishService);
249
250         deviceContexts.put(connectionContext.getDeviceInfo(), deviceContext);
251         updatePacketInRateLimiters();
252
253         final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
254                 connectionContext.getConnectionAdapter(), deviceContext);
255
256         connectionContext.getConnectionAdapter().setMessageListener(messageListener);
257
258         return deviceContext;
259     }
260
261     private void updatePacketInRateLimiters() {
262         synchronized (deviceContexts) {
263             final int deviceContextsSize = deviceContexts.size();
264             if (deviceContextsSize > 0) {
265                 long freshNotificationLimit = globalNotificationQuota / deviceContextsSize;
266                 if (freshNotificationLimit < 100) {
267                     freshNotificationLimit = 100;
268                 }
269                 if (LOG.isDebugEnabled()) {
270                     LOG.debug("fresh notification limit = {}", freshNotificationLimit);
271                 }
272                 for (final DeviceContext deviceContext : deviceContexts.values()) {
273                     deviceContext.updatePacketInRateLimit(freshNotificationLimit);
274                 }
275             }
276         }
277     }
278
279     @Override
280     public void onDeviceRemoved(final DeviceInfo deviceInfo) {
281         deviceContexts.remove(deviceInfo);
282         if (LOG.isDebugEnabled()) {
283             LOG.debug("Device context removed for node {}", deviceInfo.getLOGValue());
284         }
285         if (deviceContexts.size() > 0) {
286             this.updatePacketInRateLimiters();
287         }
288     }
289
290     @Override
291     public void sendNodeRemovedNotification(@Nonnull final KeyedInstanceIdentifier<Node, NodeKey> instanceIdentifier) {
292         if (notificationCreateNodeSend.remove(instanceIdentifier)) {
293             NodeRemovedBuilder builder = new NodeRemovedBuilder();
294             builder.setNodeRef(new NodeRef(instanceIdentifier));
295             LOG.info("Publishing node removed notification for {}", instanceIdentifier.firstKeyOf(Node.class).getId());
296             notificationPublishService.offerNotification(builder.build());
297         }
298     }
299
300     @Override
301     public void sendNodeAddedNotification(@Nonnull final KeyedInstanceIdentifier<Node, NodeKey> instanceIdentifier) {
302         if (!notificationCreateNodeSend.contains(instanceIdentifier)) {
303             notificationCreateNodeSend.add(instanceIdentifier);
304             final NodeId id = instanceIdentifier.firstKeyOf(Node.class).getId();
305             NodeUpdatedBuilder builder = new NodeUpdatedBuilder();
306             builder.setId(id);
307             builder.setNodeRef(new NodeRef(instanceIdentifier));
308             LOG.info("Publishing node added notification for {}", id);
309             notificationPublishService.offerNotification(builder.build());
310         }
311     }
312 }