Merge "BUG-4099: Groups pointing to ports"
[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 javax.annotation.CheckForNull;
11 import javax.annotation.Nonnull;
12 import java.util.Collections;
13 import java.util.concurrent.ConcurrentHashMap;
14 import java.util.concurrent.ConcurrentMap;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.ScheduledThreadPoolExecutor;
17 import java.util.concurrent.TimeUnit;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Verify;
21 import io.netty.util.HashedWheelTimer;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
24 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
25 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
28 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
29 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
30 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
31 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
32 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
33 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
34 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
35 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
36 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
37 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
38 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
39 import org.opendaylight.openflowplugin.impl.connection.OutboundQueueProviderImpl;
40 import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  *
51  */
52 public class DeviceManagerImpl implements DeviceManager, ExtensionConverterProviderKeeper {
53
54     private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
55
56     private static final long TICK_DURATION = 10; // 0.5 sec.
57     private final long globalNotificationQuota;
58     private ScheduledThreadPoolExecutor spyPool;
59     private final int spyRate = 10;
60
61     private final DataBroker dataBroker;
62     private final HashedWheelTimer hashedWheelTimer;
63     private TranslatorLibrary translatorLibrary;
64     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
65     private NotificationService notificationService;
66     private NotificationPublishService notificationPublishService;
67
68     private final ConcurrentMap<NodeId, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
69     private final MessageIntelligenceAgency messageIntelligenceAgency;
70
71     private final long barrierNanos = TimeUnit.MILLISECONDS.toNanos(500);
72     private final int maxQueueDepth = 25600;
73     private ExtensionConverterProvider extensionConverterProvider;
74
75     public DeviceManagerImpl(@Nonnull final DataBroker dataBroker,
76                              @Nonnull final MessageIntelligenceAgency messageIntelligenceAgency,
77                              final long globalNotificationQuota) {
78         this.globalNotificationQuota = globalNotificationQuota;
79         this.dataBroker = Preconditions.checkNotNull(dataBroker);
80         hashedWheelTimer = new HashedWheelTimer(TICK_DURATION, TimeUnit.MILLISECONDS, 500);
81         /* merge empty nodes to oper DS to predict any problems with missing parent for Node */
82         final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
83
84         final NodesBuilder nodesBuilder = new NodesBuilder();
85         nodesBuilder.setNode(Collections.<Node>emptyList());
86         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
87         try {
88             tx.submit().get();
89         } catch (ExecutionException | InterruptedException e) {
90             LOG.error("Creation of node failed.", e);
91             throw new IllegalStateException(e);
92         }
93
94         this.messageIntelligenceAgency = messageIntelligenceAgency;
95     }
96
97
98     @Override
99     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
100         deviceInitPhaseHandler = handler;
101     }
102
103     @Override
104     public void onDeviceContextLevelUp(final DeviceContext deviceContext) {
105         // final phase - we have to add new Device to MD-SAL DataStore
106         Preconditions.checkNotNull(deviceContext);
107         try {
108             ((DeviceContextImpl) deviceContext).initialSubmitTransaction();
109             deviceContext.onPublished();
110
111         } catch (final Exception e) {
112             LOG.warn("Node {} can not be add to OPERATIONAL DataStore yet because {} ", deviceContext.getDeviceState().getNodeId(), e.getMessage());
113             LOG.trace("Problem with add node {} to OPERATIONAL DataStore", deviceContext.getDeviceState().getNodeId(), e);
114             try {
115                 deviceContext.close();
116             } catch (Exception e1) {
117                 LOG.warn("Exception on device context close. ", e);
118             }
119         }
120
121     }
122
123     @Override
124     public void deviceConnected(@CheckForNull final ConnectionContext connectionContext) throws Exception {
125         Preconditions.checkArgument(connectionContext != null);
126         Preconditions.checkState(!deviceContexts.containsKey(connectionContext.getNodeId()),
127                 "Rejecting connection from node which is already connected and there exist deviceContext for it: {}",
128                 connectionContext.getNodeId()
129         );
130         LOG.info("Initializing New Connection DeviceContext for node:{}", connectionContext.getNodeId());
131
132         // Cache this for clarity
133         final ConnectionAdapter connectionAdapter = connectionContext.getConnectionAdapter();
134
135         //FIXME: as soon as auxiliary connection are fully supported then this is needed only before device context published
136         connectionAdapter.setPacketInFiltering(true);
137
138         final Short version = connectionContext.getFeatures().getVersion();
139         final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(version);
140
141         connectionContext.setOutboundQueueProvider(outboundQueueProvider);
142         final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
143                 connectionAdapter.registerOutboundQueueHandler(outboundQueueProvider, maxQueueDepth, barrierNanos);
144         connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
145
146         final DeviceState deviceState = createDeviceState(connectionContext);
147         final DeviceContext deviceContext = new DeviceContextImpl(connectionContext, deviceState, dataBroker,
148                 hashedWheelTimer, messageIntelligenceAgency, outboundQueueProvider, translatorLibrary);
149
150         deviceContext.addDeviceContextClosedHandler(this);
151         Verify.verify(deviceContexts.putIfAbsent(connectionContext.getNodeId(), deviceContext) == null);
152
153         ((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
154         deviceContext.setNotificationService(notificationService);
155         deviceContext.setNotificationPublishService(notificationPublishService);
156
157         updatePacketInRateLimiters();
158
159         final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
160                 connectionAdapter, deviceContext);
161         connectionAdapter.setMessageListener(messageListener);
162
163         deviceCtxLevelUp(deviceContext);
164     }
165
166     private static DeviceStateImpl createDeviceState(final @Nonnull ConnectionContext connectionContext) {
167         return new DeviceStateImpl(connectionContext.getFeatures(), connectionContext.getNodeId());
168     }
169
170     private void updatePacketInRateLimiters() {
171         synchronized (deviceContexts) {
172             final int deviceContextsSize = deviceContexts.size();
173             if (deviceContextsSize > 0) {
174                 long freshNotificationLimit = globalNotificationQuota / deviceContextsSize;
175                 if (freshNotificationLimit < 100) {
176                     freshNotificationLimit = 100;
177                 }
178                 LOG.debug("fresh notification limit = {}", freshNotificationLimit);
179                 for (final DeviceContext deviceContext : deviceContexts.values()) {
180                     deviceContext.updatePacketInRateLimit(freshNotificationLimit);
181                 }
182             }
183         }
184     }
185
186     void deviceCtxLevelUp(final DeviceContext deviceContext) {
187         deviceContext.getDeviceState().setValid(true);
188         LOG.trace("Device context level up called.");
189         deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
190     }
191
192     @Override
193     public TranslatorLibrary oook() {
194         return translatorLibrary;
195     }
196
197     @Override
198     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
199         this.translatorLibrary = translatorLibrary;
200     }
201
202     @Override
203     public void setNotificationService(final NotificationService notificationServiceParam) {
204         notificationService = notificationServiceParam;
205     }
206
207     @Override
208     public void setNotificationPublishService(final NotificationPublishService notificationService) {
209         notificationPublishService = notificationService;
210     }
211
212     @Override
213     public void close() throws Exception {
214         for (final DeviceContext deviceContext : deviceContexts.values()) {
215             deviceContext.close();
216         }
217     }
218
219     @Override
220     public void onDeviceContextClosed(final DeviceContext deviceContext) {
221         LOG.trace("onDeviceContextClosed for Node {}", deviceContext.getDeviceState().getNodeId());
222         deviceContexts.remove(deviceContext.getPrimaryConnectionContext().getNodeId());
223         updatePacketInRateLimiters();
224     }
225
226     @Override
227     public void initialize() {
228         spyPool = new ScheduledThreadPoolExecutor(1);
229         spyPool.scheduleAtFixedRate(messageIntelligenceAgency, spyRate, spyRate, TimeUnit.SECONDS);
230     }
231
232     @Override
233     public void setExtensionConverterProvider(ExtensionConverterProvider extensionConverterProvider) {
234         this.extensionConverterProvider = extensionConverterProvider;
235     }
236
237     @Override
238     public ExtensionConverterProvider getExtensionConverterProvider() {
239         return extensionConverterProvider;
240     }
241 }