2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.openflowplugin.impl;
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;
76 public class OpenFlowPluginProviderImpl implements
77 OpenFlowPluginProvider,
78 OpenFlowPluginExtensionRegistratorProvider {
80 private static final Logger LOG = LoggerFactory.getLogger(OpenFlowPluginProviderImpl.class);
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";
86 private static final MessageIntelligenceAgency MESSAGE_INTELLIGENCE_AGENCY = new MessageIntelligenceAgencyImpl();
87 private static final String MESSAGE_INTELLIGENCE_AGENCY_MX_BEAN_NAME = String
89 MessageIntelligenceAgencyMXBean.class.getPackage().getName(),
90 MessageIntelligenceAgencyMXBean.class.getSimpleName());
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;
112 public static MessageIntelligenceAgency getMessageIntelligenceAgency() {
113 return MESSAGE_INTELLIGENCE_AGENCY;
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;
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);
145 DeserializerInjector.revertDeserializers(switchConnectionProvider);
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>>() {
153 public void onSuccess(final List<Boolean> result) {
154 LOG.info("All switchConnectionProviders are up and running ({}).", result.size());
158 public void onFailure(@Nonnull final Throwable throwable) {
159 LOG.warn("Some switchConnectionProviders failed to start.", throwable);
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);
171 // Shutdown switch connection provider
172 return switchConnectionProvider.shutdown();
173 }).collect(Collectors.toSet()));
175 Futures.addCallback(listListenableFuture, new FutureCallback<List<Boolean>>() {
177 public void onSuccess(final List<Boolean> result) {
178 LOG.info("All switchConnectionProviders were successfully shut down ({}).", result.size());
182 public void onFailure(@Nonnull final Throwable throwable) {
183 LOG.warn("Some switchConnectionProviders failed to shutdown.", throwable);
187 return listListenableFuture;
191 public void initialize() {
192 registerMXBean(MESSAGE_INTELLIGENCE_AGENCY, MESSAGE_INTELLIGENCE_AGENCY_MX_BEAN_NAME);
194 // TODO: copied from OpenFlowPluginProvider (Helium) misusesing the old way of distributing extension converters
195 // TODO: rewrite later!
196 OFSessionUtil.getSessionManager().setExtensionConverterProvider(extensionConverterManager);
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);
207 deviceManager = new DeviceManagerImpl(
210 getMessageIntelligenceAgency(),
211 notificationPublishService,
214 deviceInitializerProvider);
216 TranslatorLibraryUtil.injectBasicTranslatorLibrary(deviceManager, convertorManager);
217 ((ExtensionConverterProviderKeeper) deviceManager).setExtensionConverterProvider(extensionConverterManager);
219 rpcManager = new RpcManagerImpl(
222 extensionConverterManager,
224 notificationPublishService);
226 statisticsManager = new StatisticsManagerImpl(
231 roleManager = new RoleManagerImpl(hashedWheelTimer);
233 contextChainHolder = new ContextChainHolderImpl(
235 singletonServicesProvider,
236 entityOwnershipService,
237 mastershipChangeServiceManager);
239 contextChainHolder.addManager(deviceManager);
240 contextChainHolder.addManager(statisticsManager);
241 contextChainHolder.addManager(rpcManager);
242 contextChainHolder.addManager(roleManager);
244 connectionManager = new ConnectionManagerImpl(config, threadPool);
245 connectionManager.setDeviceConnectedHandler(contextChainHolder);
246 connectionManager.setDeviceDisconnectedHandler(contextChainHolder);
248 deviceManager.initialize();
249 startSwitchConnections();
253 public ExtensionConverterRegistrator getExtensionConverterRegistrator() {
254 return extensionConverterManager;
258 public void close() {
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);
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);
275 private static void gracefulShutdown(final AutoCloseable closeable) {
276 if (Objects.isNull(closeable)) {
282 } catch (Exception e) {
283 LOG.warn("Failed to shutdown {} gracefully.", closeable);
287 private static void gracefulShutdown(final Timer timer) {
288 if (Objects.isNull(timer)) {
294 } catch (Exception e) {
295 LOG.warn("Failed to shutdown {} gracefully.", timer);
299 private static void gracefulShutdown(final ThreadPoolExecutor threadPoolExecutor) {
300 if (Objects.isNull(threadPoolExecutor)) {
305 threadPoolExecutor.shutdownNow();
306 } catch (Exception e) {
307 LOG.warn("Failed to shutdown {} gracefully.", threadPoolExecutor);
311 private static void registerMXBean(final Object bean, final String beanName) {
312 final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
315 mbs.registerMBean(bean, new ObjectName(beanName));
316 } catch (MalformedObjectNameException
317 | NotCompliantMBeanException
318 | MBeanRegistrationException
319 | InstanceAlreadyExistsException e) {
320 LOG.warn("Error registering MBean {}", e);
324 private static void unregisterMXBean(final String beanName) {
325 final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
328 mbs.unregisterMBean(new ObjectName(beanName));
329 } catch (InstanceNotFoundException
330 | MBeanRegistrationException
331 | MalformedObjectNameException e) {
332 LOG.warn("Error unregistering MBean {}", e);