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