f3010a41387d21d4765b33309b9c45713270c7c1
[controller.git] / opendaylight / blueprint / src / main / java / org / opendaylight / controller / blueprint / BlueprintContainerRestartServiceImpl.java
1 /*
2  * Copyright (c) 2016 Brocade Communications 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.controller.blueprint;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Lists;
13 import com.google.common.util.concurrent.ThreadFactoryBuilder;
14 import java.lang.management.ManagementFactory;
15 import java.util.AbstractMap.SimpleEntry;
16 import java.util.ArrayDeque;
17 import java.util.ArrayList;
18 import java.util.Arrays;
19 import java.util.Collections;
20 import java.util.Deque;
21 import java.util.Dictionary;
22 import java.util.Hashtable;
23 import java.util.LinkedHashSet;
24 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.Set;
27 import java.util.concurrent.CountDownLatch;
28 import java.util.concurrent.ExecutorService;
29 import java.util.concurrent.Executors;
30 import java.util.concurrent.TimeUnit;
31 import javax.annotation.Nullable;
32 import javax.management.InstanceNotFoundException;
33 import javax.management.ObjectName;
34 import javax.xml.parsers.ParserConfigurationException;
35 import org.apache.aries.blueprint.services.BlueprintExtenderService;
36 import org.apache.aries.quiesce.participant.QuiesceParticipant;
37 import org.apache.aries.util.AriesFrameworkUtil;
38 import org.opendaylight.controller.config.api.ConfigRegistry;
39 import org.opendaylight.controller.config.api.ConflictingVersionException;
40 import org.opendaylight.controller.config.api.ModuleIdentifier;
41 import org.opendaylight.controller.config.api.ValidationException;
42 import org.opendaylight.controller.config.facade.xml.ConfigExecution;
43 import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
44 import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
45 import org.opendaylight.controller.config.facade.xml.TestOption;
46 import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
47 import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
48 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
49 import org.opendaylight.controller.config.util.xml.DocumentedException;
50 import org.opendaylight.controller.config.util.xml.XmlElement;
51 import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
52 import org.opendaylight.controller.config.util.xml.XmlUtil;
53 import org.osgi.framework.Bundle;
54 import org.osgi.framework.BundleContext;
55 import org.osgi.framework.ServiceReference;
56 import org.osgi.framework.ServiceRegistration;
57 import org.osgi.service.blueprint.container.EventConstants;
58 import org.osgi.service.event.EventHandler;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.w3c.dom.Document;
62 import org.w3c.dom.Element;
63
64 /**
65  * Implementation of the BlueprintContainerRestartService.
66  *
67  * @author Thomas Pantelis
68  */
69 class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintContainerRestartService {
70     private static final Logger LOG = LoggerFactory.getLogger(BlueprintContainerRestartServiceImpl.class);
71     private static final int CONTAINER_CREATE_TIMEOUT_IN_MINUTES = 5;
72     private static final String CONFIG_MODULE_NAMESPACE_PROP = "config-module-namespace";
73     private static final String CONFIG_MODULE_NAME_PROP = "config-module-name";
74     private static final String CONFIG_INSTANCE_NAME_PROP = "config-instance-name";
75
76     private final ExecutorService restartExecutor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder()
77             .setDaemon(true).setNameFormat("BlueprintContainerRestartService").build());
78
79     private BlueprintExtenderService blueprintExtenderService;
80     private QuiesceParticipant quiesceParticipant;
81
82     void setBlueprintExtenderService(final BlueprintExtenderService blueprintExtenderService) {
83         this.blueprintExtenderService = blueprintExtenderService;
84     }
85
86     void setQuiesceParticipant(final QuiesceParticipant quiesceParticipant) {
87         this.quiesceParticipant = quiesceParticipant;
88     }
89
90     public void restartContainer(final Bundle bundle, final List<Object> paths) {
91         if (restartExecutor.isShutdown()) {
92             return;
93         }
94
95         LOG.debug("restartContainer for bundle {}", bundle);
96
97         restartExecutor.execute(() -> {
98             blueprintExtenderService.destroyContainer(bundle, blueprintExtenderService.getContainer(bundle));
99             blueprintExtenderService.createContainer(bundle, paths);
100         });
101     }
102
103     @Override
104     public void restartContainerAndDependents(final Bundle bundle) {
105         if (restartExecutor.isShutdown()) {
106             return;
107         }
108
109         LOG.debug("restartContainerAndDependents for bundle {}", bundle);
110
111         restartExecutor.execute(() -> restartContainerAndDependentsInternal(bundle));
112     }
113
114     private void restartContainerAndDependentsInternal(Bundle forBundle) {
115         Preconditions.checkNotNull(blueprintExtenderService);
116         Preconditions.checkNotNull(quiesceParticipant);
117
118         // We use a LinkedHashSet to preserve insertion order as we walk the service usage hierarchy.
119         Set<Bundle> containerBundlesSet = new LinkedHashSet<>();
120         List<Entry<String, ModuleIdentifier>> configModules = new ArrayList<>();
121         findDependentContainersRecursively(forBundle, containerBundlesSet, configModules);
122
123         List<Bundle> containerBundles = new ArrayList<>(containerBundlesSet);
124
125         LOG.info("Restarting blueprint containers for bundle {} and its dependent bundles {}", forBundle,
126                 containerBundles.subList(1, containerBundles.size()));
127
128         // The blueprint containers are created asynchronously so we register a handler for blueprint events
129         // that are sent when a container is complete, successful or not. The CountDownLatch tells when all
130         // containers are complete. This is done to ensure all blueprint containers are finished before we
131         // restart config modules.
132         final CountDownLatch containerCreationComplete = new CountDownLatch(containerBundles.size());
133         ServiceRegistration<?> eventHandlerReg = registerEventHandler(forBundle.getBundleContext(), event -> {
134             LOG.debug("handleEvent {} for bundle {}", event.getTopic(), event.getProperty(EventConstants.BUNDLE));
135             if (containerBundles.contains(event.getProperty(EventConstants.BUNDLE))) {
136                 containerCreationComplete.countDown();
137             }
138         });
139
140         final Runnable createContainerCallback = () -> createContainers(containerBundles);
141
142         // Destroy the container down-top recursively and once done, restart the container top-down
143         destroyContainers(new ArrayDeque<>(Lists.reverse(containerBundles)), createContainerCallback);
144
145
146         try {
147             if (!containerCreationComplete.await(CONTAINER_CREATE_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES)) {
148                 LOG.warn("Failed to restart all blueprint containers within {} minutes. Attempted to restart {} {} "
149                         + "but only {} completed restart", CONTAINER_CREATE_TIMEOUT_IN_MINUTES, containerBundles.size(),
150                         containerBundles, containerBundles.size() - containerCreationComplete.getCount());
151                 return;
152             }
153         } catch (InterruptedException e) {
154             LOG.debug("CountDownLatch await was interrupted - returning");
155             return;
156         }
157
158         AriesFrameworkUtil.safeUnregisterService(eventHandlerReg);
159
160         // Now restart any associated config system Modules.
161         restartConfigModules(forBundle.getBundleContext(), configModules);
162     }
163
164     /**
165      * Recursively quiesce and destroy the bundles one by one in order to maintain synchronicity and ordering.
166      * @param remainingBundlesToDestroy the list of remaining bundles to destroy.
167      * @param createContainerCallback a {@link Runnable} to {@code run()} when the recursive function is completed.
168      */
169     private void destroyContainers(final Deque<Bundle> remainingBundlesToDestroy,
170             final Runnable createContainerCallback) {
171
172         final Bundle nextBundle;
173         synchronized (remainingBundlesToDestroy) {
174             if (remainingBundlesToDestroy.isEmpty()) {
175                 LOG.debug("All blueprint containers were quiesced and destroyed");
176                 createContainerCallback.run();
177                 return;
178             }
179
180             nextBundle = remainingBundlesToDestroy.poll();
181         }
182
183         // The Quiesce capability is a like a soft-stop, clean-stop. In the case of the Blueprint extender, in flight
184         // service calls are allowed to finish; they're counted in and counted out, and no new calls are allowed. When
185         // there are no in flight service calls, the bundle is told to stop. The Blueprint bundle itself doesn't know
186         // this is happening which is a key design point. In the case of Blueprint, the extender ensures no new Entity
187         // Managers(EMs) are created. Then when all those EMs are closed the quiesce operation reports that it is
188         // finished.
189         // To properly restart the blueprint containers, first we have to quiesce the list of bundles, and once done, it
190         // is safe to destroy their BlueprintContainer, so no reference is retained.
191         //
192         // Mail - thread explaining Quiesce API:
193         //      https://www.mail-archive.com/dev@aries.apache.org/msg08403.html
194
195         // Quiesced the bundle to unregister the associated BlueprintContainer
196         quiesceParticipant.quiesce(bundlesQuiesced -> {
197
198             // Destroy the container once Quiesced
199             Arrays.stream(bundlesQuiesced).forEach(quiescedBundle -> {
200                 LOG.debug("Quiesced bundle {}", quiescedBundle);
201                 blueprintExtenderService.destroyContainer(
202                         quiescedBundle, blueprintExtenderService.getContainer(quiescedBundle));
203             });
204
205             destroyContainers(remainingBundlesToDestroy, createContainerCallback);
206
207         }, Collections.singletonList(nextBundle));
208     }
209
210     private void createContainers(List<Bundle> containerBundles) {
211         containerBundles.forEach(bundle -> {
212             List<Object> paths = BlueprintBundleTracker.findBlueprintPaths(bundle);
213
214             LOG.info("Restarting blueprint container for bundle {} with paths {}", bundle, paths);
215
216             blueprintExtenderService.createContainer(bundle, paths);
217         });
218     }
219
220     private void restartConfigModules(BundleContext bundleContext, List<Entry<String,
221             ModuleIdentifier>> configModules) {
222         if (configModules.isEmpty()) {
223             return;
224         }
225
226         ServiceReference<ConfigSubsystemFacadeFactory> configFacadeFactoryRef = bundleContext
227                 .getServiceReference(ConfigSubsystemFacadeFactory.class);
228         if (configFacadeFactoryRef == null) {
229             LOG.debug("ConfigSubsystemFacadeFactory service reference not found");
230             return;
231         }
232
233         ConfigSubsystemFacadeFactory configFacadeFactory = bundleContext.getService(configFacadeFactoryRef);
234         if (configFacadeFactory == null) {
235             LOG.debug("ConfigSubsystemFacadeFactory service not found");
236             return;
237         }
238
239         try (ConfigSubsystemFacade configFacade = configFacadeFactory.createFacade(
240                 "BlueprintContainerRestartService")) {
241             restartConfigModules(configModules, configFacade);
242         } catch (ParserConfigurationException | DocumentedException | ValidationException
243                 | ConflictingVersionException e) {
244             LOG.error("Error restarting config modules", e);
245         } finally {
246             bundleContext.ungetService(configFacadeFactoryRef);
247         }
248
249     }
250
251     private void restartConfigModules(List<Entry<String, ModuleIdentifier>> configModules,
252             ConfigSubsystemFacade configFacade) throws ParserConfigurationException, DocumentedException,
253                     ValidationException, ConflictingVersionException {
254
255         Document document = XmlUtil.newDocument();
256         Element dataElement = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.<String>absent());
257         Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY,
258                 Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
259         dataElement.appendChild(modulesElement);
260
261         Config configMapping = configFacade.getConfigMapping();
262
263         ConfigRegistry configRegistryClient = new ConfigRegistryJMXClient(ManagementFactory.getPlatformMBeanServer());
264         for (Entry<String, ModuleIdentifier> entry : configModules) {
265             String moduleNamespace = entry.getKey();
266             ModuleIdentifier moduleId = entry.getValue();
267             try {
268                 ObjectName instanceON = configRegistryClient.lookupConfigBean(moduleId.getFactoryName(),
269                         moduleId.getInstanceName());
270
271                 LOG.debug("Found config module instance ObjectName: {}", instanceON);
272
273                 Element moduleElement = configMapping.moduleToXml(moduleNamespace, moduleId.getFactoryName(),
274                         moduleId.getInstanceName(), instanceON, document);
275                 modulesElement.appendChild(moduleElement);
276             } catch (InstanceNotFoundException e) {
277                 LOG.warn("Error looking up config module: namespace {}, module name {}, instance {}",
278                         moduleNamespace, moduleId.getFactoryName(), moduleId.getInstanceName(), e);
279             }
280         }
281
282         if (LOG.isDebugEnabled()) {
283             LOG.debug("Pushing config xml: {}", XmlUtil.toString(dataElement));
284         }
285
286         ConfigExecution execution = new ConfigExecution(configMapping, XmlElement.fromDomElement(dataElement),
287                 TestOption.testThenSet, EditStrategyType.recreate);
288         configFacade.executeConfigExecution(execution);
289         configFacade.commitSilentTransaction();
290     }
291
292     /**
293      * Recursively finds the services registered by the given bundle and the bundles using those services.
294      * User bundles that have an associated blueprint container are added to containerBundles. In addition,
295      * if a registered service has an associated config system Module, as determined via the presence of
296      * certain service properties, the ModuleIdentifier is added to the configModules list.
297      *
298      * @param bundle the bundle to traverse
299      * @param containerBundles the current set of bundles containing blueprint containers
300      * @param configModules the current set of bundles containing config modules
301      */
302     private void findDependentContainersRecursively(Bundle bundle, Set<Bundle> containerBundles,
303             List<Entry<String, ModuleIdentifier>> configModules) {
304         if (!containerBundles.add(bundle)) {
305             // Already seen this bundle...
306             return;
307         }
308
309         ServiceReference<?>[] references = bundle.getRegisteredServices();
310         if (references != null) {
311             for (ServiceReference<?> reference : references) {
312                 possiblyAddConfigModuleIdentifier(reference, configModules);
313
314                 Bundle[] usingBundles = reference.getUsingBundles();
315                 if (usingBundles != null) {
316                     for (Bundle usingBundle : usingBundles) {
317                         if (blueprintExtenderService.getContainer(usingBundle) != null) {
318                             findDependentContainersRecursively(usingBundle, containerBundles, configModules);
319                         }
320                     }
321                 }
322             }
323         }
324     }
325
326     private void possiblyAddConfigModuleIdentifier(ServiceReference<?> reference,
327             List<Entry<String, ModuleIdentifier>> configModules) {
328         Object moduleNamespace = reference.getProperty(CONFIG_MODULE_NAMESPACE_PROP);
329         if (moduleNamespace == null) {
330             return;
331         }
332
333         String moduleName = getRequiredConfigModuleProperty(CONFIG_MODULE_NAME_PROP, moduleNamespace,
334                 reference);
335         String instanceName = getRequiredConfigModuleProperty(CONFIG_INSTANCE_NAME_PROP, moduleNamespace,
336                 reference);
337         if (moduleName == null || instanceName == null) {
338             return;
339         }
340
341         LOG.debug("Found service with config module: namespace {}, module name {}, instance {}",
342                 moduleNamespace, moduleName, instanceName);
343
344         configModules.add(new SimpleEntry<>(moduleNamespace.toString(),
345                 new ModuleIdentifier(moduleName, instanceName)));
346     }
347
348     @Nullable
349     private String getRequiredConfigModuleProperty(String propName, Object moduleNamespace,
350             ServiceReference<?> reference) {
351         Object value = reference.getProperty(propName);
352         if (value == null) {
353             LOG.warn(
354                 "OSGi service with {} property is missing property {} therefore the config module can't be restarted",
355                 CONFIG_MODULE_NAMESPACE_PROP, propName);
356             return null;
357         }
358
359         return value.toString();
360     }
361
362     private ServiceRegistration<?> registerEventHandler(BundleContext bundleContext, EventHandler handler) {
363         Dictionary<String, Object> props = new Hashtable<>();
364         props.put(org.osgi.service.event.EventConstants.EVENT_TOPIC,
365                 new String[]{EventConstants.TOPIC_CREATED, EventConstants.TOPIC_FAILURE});
366         return bundleContext.registerService(EventHandler.class.getName(), handler, props);
367     }
368
369     @Override
370     public void close() {
371         restartExecutor.shutdownNow();
372     }
373 }