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