Move used code from openflowplugin to impl
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / OpenFlowPluginProviderImpl.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
9 package org.opendaylight.openflowplugin.impl;
10
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import io.netty.util.HashedWheelTimer;
15 import io.netty.util.Timer;
16 import java.lang.management.ManagementFactory;
17 import java.util.Collection;
18 import java.util.List;
19 import java.util.Objects;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.SynchronousQueue;
22 import java.util.concurrent.ThreadPoolExecutor;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.TimeoutException;
25 import java.util.stream.Collectors;
26 import javax.annotation.Nonnull;
27 import javax.management.InstanceAlreadyExistsException;
28 import javax.management.InstanceNotFoundException;
29 import javax.management.MBeanRegistrationException;
30 import javax.management.MBeanServer;
31 import javax.management.MalformedObjectNameException;
32 import javax.management.NotCompliantMBeanException;
33 import javax.management.ObjectName;
34 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
35 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
36 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
37 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
38 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
39 import org.opendaylight.openflowjava.protocol.spi.connection.SwitchConnectionProvider;
40 import org.opendaylight.openflowplugin.api.openflow.OpenFlowPluginProvider;
41 import org.opendaylight.openflowplugin.api.openflow.configuration.ConfigurationService;
42 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionManager;
43 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
44 import org.opendaylight.openflowplugin.api.openflow.mastership.MastershipChangeServiceManager;
45 import org.opendaylight.openflowplugin.api.openflow.role.RoleManager;
46 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcManager;
47 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
48 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
49 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
50 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterRegistrator;
51 import org.opendaylight.openflowplugin.extension.api.OpenFlowPluginExtensionRegistratorProvider;
52 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterManager;
53 import org.opendaylight.openflowplugin.impl.configuration.OpenFlowProviderConfigImpl;
54 import org.opendaylight.openflowplugin.impl.connection.ConnectionManagerImpl;
55 import org.opendaylight.openflowplugin.impl.device.DeviceManagerImpl;
56 import org.opendaylight.openflowplugin.impl.device.initialization.DeviceInitializerProvider;
57 import org.opendaylight.openflowplugin.impl.device.initialization.DeviceInitializerProviderFactory;
58 import org.opendaylight.openflowplugin.impl.lifecycle.ContextChainHolderImpl;
59 import org.opendaylight.openflowplugin.impl.protocol.deserialization.DeserializerInjector;
60 import org.opendaylight.openflowplugin.impl.protocol.serialization.SerializerInjector;
61 import org.opendaylight.openflowplugin.impl.role.RoleManagerImpl;
62 import org.opendaylight.openflowplugin.impl.rpc.RpcManagerImpl;
63 import org.opendaylight.openflowplugin.impl.statistics.StatisticsManagerImpl;
64 import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyImpl;
65 import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyMXBean;
66 import org.opendaylight.openflowplugin.impl.util.TranslatorLibraryUtil;
67 import org.opendaylight.openflowplugin.impl.util.ThreadPoolLoggingExecutor;
68 import org.opendaylight.openflowplugin.openflow.md.core.extension.ExtensionConverterManagerImpl;
69 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
70 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
71 import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.provider.config.rev160510.OpenflowProviderConfig;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75
76 public class OpenFlowPluginProviderImpl implements
77         OpenFlowPluginProvider,
78         OpenFlowPluginExtensionRegistratorProvider {
79
80     private static final Logger LOG = LoggerFactory.getLogger(OpenFlowPluginProviderImpl.class);
81
82     private static final int TICKS_PER_WHEEL = 500; // 0.5 sec.
83     private static final long TICK_DURATION = 10;
84     private static final String POOL_NAME = "ofppool";
85
86     private static final MessageIntelligenceAgency MESSAGE_INTELLIGENCE_AGENCY = new MessageIntelligenceAgencyImpl();
87     private static final String MESSAGE_INTELLIGENCE_AGENCY_MX_BEAN_NAME = String
88             .format("%s:type=%s",
89                     MessageIntelligenceAgencyMXBean.class.getPackage().getName(),
90                     MessageIntelligenceAgencyMXBean.class.getSimpleName());
91
92     private final HashedWheelTimer hashedWheelTimer = new HashedWheelTimer(TICK_DURATION, TimeUnit.MILLISECONDS, TICKS_PER_WHEEL);
93     private final NotificationPublishService notificationPublishService;
94     private final ExtensionConverterManager extensionConverterManager;
95     private final DataBroker dataBroker;
96     private final Collection<SwitchConnectionProvider> switchConnectionProviders;
97     private final DeviceInitializerProvider deviceInitializerProvider;
98     private final ConvertorManager convertorManager;
99     private final RpcProviderRegistry rpcProviderRegistry;
100     private final ClusterSingletonServiceProvider singletonServicesProvider;
101     private final OpenflowProviderConfig config;
102     private final EntityOwnershipService entityOwnershipService;
103     private final MastershipChangeServiceManager mastershipChangeServiceManager;
104     private DeviceManager deviceManager;
105     private RpcManager rpcManager;
106     private StatisticsManager statisticsManager;
107     private RoleManager roleManager;
108     private ConnectionManager connectionManager;
109     private ThreadPoolExecutor threadPool;
110     private ContextChainHolderImpl contextChainHolder;
111
112     public static MessageIntelligenceAgency getMessageIntelligenceAgency() {
113         return MESSAGE_INTELLIGENCE_AGENCY;
114     }
115
116     OpenFlowPluginProviderImpl(final ConfigurationService configurationService,
117                                final List<SwitchConnectionProvider> switchConnectionProviders,
118                                final DataBroker dataBroker,
119                                final RpcProviderRegistry rpcProviderRegistry,
120                                final NotificationPublishService notificationPublishService,
121                                final ClusterSingletonServiceProvider singletonServiceProvider,
122                                final EntityOwnershipService entityOwnershipService,
123                                final MastershipChangeServiceManager mastershipChangeServiceManager) {
124         this.switchConnectionProviders = switchConnectionProviders;
125         this.dataBroker = dataBroker;
126         this.rpcProviderRegistry = rpcProviderRegistry;
127         this.notificationPublishService = notificationPublishService;
128         this.singletonServicesProvider = singletonServiceProvider;
129         this.entityOwnershipService = entityOwnershipService;
130         convertorManager = ConvertorManagerFactory.createDefaultManager();
131         extensionConverterManager = new ExtensionConverterManagerImpl();
132         deviceInitializerProvider = DeviceInitializerProviderFactory.createDefaultProvider();
133         config = new OpenFlowProviderConfigImpl(configurationService);
134         this.mastershipChangeServiceManager = mastershipChangeServiceManager;
135     }
136
137
138     private void startSwitchConnections() {
139         Futures.addCallback(Futures.allAsList(switchConnectionProviders.stream().map(switchConnectionProvider -> {
140             // Inject OpenFlowPlugin custom serializers and deserializers into OpenFlowJava
141             if (config.isUseSingleLayerSerialization()) {
142                 SerializerInjector.injectSerializers(switchConnectionProvider);
143                 DeserializerInjector.injectDeserializers(switchConnectionProvider);
144             } else {
145                 DeserializerInjector.revertDeserializers(switchConnectionProvider);
146             }
147
148             // Set handler of incoming connections and start switch connection provider
149             switchConnectionProvider.setSwitchConnectionHandler(connectionManager);
150             return switchConnectionProvider.startup();
151         }).collect(Collectors.toSet())), new FutureCallback<List<Boolean>>() {
152             @Override
153             public void onSuccess(final List<Boolean> result) {
154                 LOG.info("All switchConnectionProviders are up and running ({}).", result.size());
155             }
156
157             @Override
158             public void onFailure(@Nonnull final Throwable throwable) {
159                 LOG.warn("Some switchConnectionProviders failed to start.", throwable);
160             }
161         });
162     }
163
164     private ListenableFuture<List<Boolean>> shutdownSwitchConnections() {
165         final ListenableFuture<List<Boolean>> listListenableFuture = Futures.allAsList(switchConnectionProviders.stream().map(switchConnectionProvider -> {
166             // Revert deserializers to their original state
167             if (config.isUseSingleLayerSerialization()) {
168                 DeserializerInjector.revertDeserializers(switchConnectionProvider);
169             }
170
171             // Shutdown switch connection provider
172             return switchConnectionProvider.shutdown();
173         }).collect(Collectors.toSet()));
174
175         Futures.addCallback(listListenableFuture, new FutureCallback<List<Boolean>>() {
176             @Override
177             public void onSuccess(final List<Boolean> result) {
178                 LOG.info("All switchConnectionProviders were successfully shut down ({}).", result.size());
179             }
180
181             @Override
182             public void onFailure(@Nonnull final Throwable throwable) {
183                 LOG.warn("Some switchConnectionProviders failed to shutdown.", throwable);
184             }
185         });
186
187         return listListenableFuture;
188     }
189
190     @Override
191     public void initialize() {
192         registerMXBean(MESSAGE_INTELLIGENCE_AGENCY, MESSAGE_INTELLIGENCE_AGENCY_MX_BEAN_NAME);
193
194         // TODO: copied from OpenFlowPluginProvider (Helium) misusesing the old way of distributing extension converters
195         // TODO: rewrite later!
196         OFSessionUtil.getSessionManager().setExtensionConverterProvider(extensionConverterManager);
197
198         // Creates a thread pool that creates new threads as needed, but will reuse previously
199         // constructed threads when they are available.
200         // Threads that have not been used for x seconds are terminated and removed from the cache.
201         threadPool = new ThreadPoolLoggingExecutor(
202                 config.getThreadPoolMinThreads(),
203                 config.getThreadPoolMaxThreads().getValue(),
204                 config.getThreadPoolTimeout(),
205                 TimeUnit.SECONDS, new SynchronousQueue<>(), POOL_NAME);
206
207         deviceManager = new DeviceManagerImpl(
208                 config,
209                 dataBroker,
210                 getMessageIntelligenceAgency(),
211                 notificationPublishService,
212                 hashedWheelTimer,
213                 convertorManager,
214                 deviceInitializerProvider);
215
216         TranslatorLibraryUtil.injectBasicTranslatorLibrary(deviceManager, convertorManager);
217         ((ExtensionConverterProviderKeeper) deviceManager).setExtensionConverterProvider(extensionConverterManager);
218
219         rpcManager = new RpcManagerImpl(
220                 config,
221                 rpcProviderRegistry,
222                 extensionConverterManager,
223                 convertorManager,
224                 notificationPublishService);
225
226         statisticsManager = new StatisticsManagerImpl(
227                 config,
228                 rpcProviderRegistry,
229                 convertorManager);
230
231         roleManager = new RoleManagerImpl(hashedWheelTimer);
232
233         contextChainHolder = new ContextChainHolderImpl(
234                 threadPool,
235                 singletonServicesProvider,
236                 entityOwnershipService,
237                 mastershipChangeServiceManager);
238
239         contextChainHolder.addManager(deviceManager);
240         contextChainHolder.addManager(statisticsManager);
241         contextChainHolder.addManager(rpcManager);
242         contextChainHolder.addManager(roleManager);
243
244         connectionManager = new ConnectionManagerImpl(config, threadPool);
245         connectionManager.setDeviceConnectedHandler(contextChainHolder);
246         connectionManager.setDeviceDisconnectedHandler(contextChainHolder);
247
248         deviceManager.initialize();
249         startSwitchConnections();
250     }
251
252     @Override
253     public ExtensionConverterRegistrator getExtensionConverterRegistrator() {
254         return extensionConverterManager;
255     }
256
257     @Override
258     public void close() {
259         try {
260             shutdownSwitchConnections().get(10, TimeUnit.SECONDS);
261         } catch (InterruptedException | ExecutionException | TimeoutException e) {
262             LOG.warn("Failed to shut down switch connections in time {}s, error: {}", 10, e);
263         }
264
265         gracefulShutdown(contextChainHolder);
266         gracefulShutdown(deviceManager);
267         gracefulShutdown(rpcManager);
268         gracefulShutdown(statisticsManager);
269         gracefulShutdown(roleManager);
270         gracefulShutdown(threadPool);
271         gracefulShutdown(hashedWheelTimer);
272         unregisterMXBean(MESSAGE_INTELLIGENCE_AGENCY_MX_BEAN_NAME);
273     }
274
275     private static void gracefulShutdown(final AutoCloseable closeable) {
276         if (Objects.isNull(closeable)) {
277             return;
278         }
279
280         try {
281             closeable.close();
282         } catch (Exception e) {
283             LOG.warn("Failed to shutdown {} gracefully.", closeable);
284         }
285     }
286
287     private static void gracefulShutdown(final Timer timer) {
288         if (Objects.isNull(timer)) {
289             return;
290         }
291
292         try {
293             timer.stop();
294         } catch (Exception e) {
295             LOG.warn("Failed to shutdown {} gracefully.", timer);
296         }
297     }
298
299     private static void gracefulShutdown(final ThreadPoolExecutor threadPoolExecutor) {
300         if (Objects.isNull(threadPoolExecutor)) {
301             return;
302         }
303
304         try {
305             threadPoolExecutor.shutdownNow();
306         } catch (Exception e) {
307             LOG.warn("Failed to shutdown {} gracefully.", threadPoolExecutor);
308         }
309     }
310
311     private static void registerMXBean(final Object bean, final String beanName) {
312         final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
313
314         try {
315             mbs.registerMBean(bean, new ObjectName(beanName));
316         } catch (MalformedObjectNameException
317                 | NotCompliantMBeanException
318                 | MBeanRegistrationException
319                 | InstanceAlreadyExistsException e) {
320             LOG.warn("Error registering MBean {}", e);
321         }
322     }
323
324     private static void unregisterMXBean(final String beanName) {
325         final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
326
327         try {
328             mbs.unregisterMBean(new ObjectName(beanName));
329         } catch (InstanceNotFoundException
330                 | MBeanRegistrationException
331                 | MalformedObjectNameException e) {
332             LOG.warn("Error unregistering MBean {}", e);
333         }
334     }
335 }