Fix ModuleFactoryBundleTracker shutdown hang
[controller.git] / opendaylight / config / config-manager / src / main / java / org / opendaylight / controller / config / manager / impl / osgi / ModuleFactoryBundleTracker.java
1 /*
2  * Copyright (c) 2013 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.controller.config.manager.impl.osgi;
9
10 import static java.lang.String.format;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Charsets;
13 import com.google.common.base.Stopwatch;
14 import com.google.common.collect.HashMultimap;
15 import com.google.common.collect.Multimap;
16 import com.google.common.io.Resources;
17 import com.google.common.util.concurrent.Uninterruptibles;
18 import java.io.IOException;
19 import java.net.URL;
20 import java.util.AbstractMap;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.concurrent.GuardedBy;
27 import org.opendaylight.controller.config.spi.ModuleFactory;
28 import org.osgi.framework.Bundle;
29 import org.osgi.framework.BundleContext;
30 import org.osgi.framework.BundleEvent;
31 import org.osgi.util.tracker.BundleTrackerCustomizer;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * OSGi extender that listens for bundle activation events. Reads file
37  * META-INF/services/org.opendaylight.controller.config.spi.ModuleFactory, each
38  * line should contain an implementation of ModuleFactory interface. Creates new
39  * instance with default constructor and registers it into OSGi service
40  * registry. There is no need for listening for implementing removedBundle as
41  * the services are unregistered automatically.
42  * Code based on http://www.toedter.com/blog/?p=236
43  */
44 public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer<Object> {
45     private static final Logger LOG = LoggerFactory.getLogger(ModuleFactoryBundleTracker.class);
46     private static final long BUNDLE_CONTEXT_TIMEOUT = TimeUnit.MILLISECONDS.convert(60, TimeUnit.SECONDS);
47
48     private final BlankTransactionServiceTracker blankTransactionServiceTracker;
49
50     @GuardedBy(value = "bundleModuleFactoryMap")
51     private final Multimap<BundleKey, ModuleFactory> bundleModuleFactoryMap = HashMultimap.create();
52
53     public ModuleFactoryBundleTracker(BlankTransactionServiceTracker blankTransactionServiceTracker) {
54         this.blankTransactionServiceTracker = blankTransactionServiceTracker;
55     }
56
57     @Override
58     public Object addingBundle(Bundle bundle, BundleEvent event) {
59         if(event != null && (event.getType() == BundleEvent.STOPPED || event.getType() == BundleEvent.STOPPING)) {
60             // We're tracking RESOLVED, STARTING, and ACTIVE states but not STOPPING. So when a bundle transitions
61             // to STOPPING, removedBundle gets called and we remove the ModuleFactory entries. However the
62             // bundle will then transition to RESOLVED which will cause the tracker to notify addingBundle.
63             // In this case we don't want to re-add the ModuleFactory entries so we check if the BundleEvent
64             // is STOPPED.
65             return null;
66         }
67
68         URL resource = bundle.getEntry("META-INF/services/" + ModuleFactory.class.getName());
69         LOG.trace("Got addingBundle event of bundle {}, resource {}, event {}",
70                 bundle, resource, event);
71         if (resource != null) {
72             try {
73                 for (String factoryClassName : Resources.readLines(resource, Charsets.UTF_8)) {
74                     Entry<ModuleFactory, Bundle> moduleFactoryEntry = registerFactory(factoryClassName, bundle);
75                     synchronized (bundleModuleFactoryMap) {
76                         bundleModuleFactoryMap.put(new BundleKey(moduleFactoryEntry.getValue()),
77                                 moduleFactoryEntry.getKey());
78                     }
79                 }
80             } catch (IOException e) {
81                 LOG.error("Error while reading {}", resource, e);
82                 throw new RuntimeException(e);
83             }
84         }
85         return bundle;
86     }
87
88     @Override
89     public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
90         // NOOP
91     }
92
93     @Override
94     public void removedBundle(Bundle bundle, BundleEvent event, Object object) {
95         synchronized (bundleModuleFactoryMap) {
96             bundleModuleFactoryMap.removeAll(new BundleKey(bundle));
97         }
98
99         // workaround for service tracker not getting removed service event
100         blankTransactionServiceTracker.blankTransaction();
101     }
102
103     public Collection<Map.Entry<ModuleFactory, BundleContext>> getModuleFactoryEntries() {
104         Collection<Entry<BundleKey, ModuleFactory>> entries;
105         synchronized (bundleModuleFactoryMap) {
106             entries = new ArrayList<>(bundleModuleFactoryMap.entries());
107         }
108
109         Collection<Map.Entry<ModuleFactory, BundleContext>> result = new ArrayList<>(entries.size());
110         for(Entry<BundleKey, ModuleFactory> entry: entries) {
111             BundleContext context = entry.getKey().getBundleContext();
112             if(context == null) {
113                 LOG.warn("Bundle context for {} ModuleFactory not found", entry.getValue());
114             } else {
115                 result.add(new AbstractMap.SimpleImmutableEntry<>(entry.getValue(), context));
116             }
117         }
118
119         return result;
120     }
121
122     @VisibleForTesting
123     protected static Map.Entry<ModuleFactory, Bundle> registerFactory(String factoryClassName, Bundle bundle) {
124         String errorMessage;
125         Exception ex = null;
126         try {
127             Class<?> clazz = bundle.loadClass(factoryClassName);
128             if (ModuleFactory.class.isAssignableFrom(clazz)) {
129                 try {
130                     LOG.debug("Registering {} in bundle {}", clazz.getName(), bundle);
131
132                     return new AbstractMap.SimpleImmutableEntry<>((ModuleFactory)clazz.newInstance(), bundle);
133                 } catch (InstantiationException e) {
134                     errorMessage = logMessage(
135                             "Could not instantiate {} in bundle {}, reason {}",
136                             factoryClassName, bundle, e);
137                     ex = e;
138                 } catch (IllegalAccessException e) {
139                     errorMessage = logMessage(
140                             "Illegal access during instantiation of class {} in bundle {}, reason {}",
141                             factoryClassName, bundle, e);
142                     ex = e;
143                 } catch (RuntimeException e) {
144                     errorMessage = logMessage(
145                             "Unexpected exception during instantiation of class {} in bundle {}, reason {}",
146                             clazz, bundle.getBundleContext(), e);
147                     ex = e;
148                 }
149             } else {
150                 errorMessage = logMessage(
151                         "Class {} does not implement {} in bundle {}", clazz,
152                         ModuleFactory.class, bundle);
153             }
154         } catch (ClassNotFoundException e) {
155             errorMessage = logMessage(
156                     "Could not find class {} in bundle {}, reason {}",
157                     factoryClassName, bundle, e);
158             ex = e;
159         }
160
161         throw ex == null ? new IllegalStateException(errorMessage) : new IllegalStateException(errorMessage, ex);
162     }
163
164     public static String logMessage(String slfMessage, Object... params) {
165         LOG.info(slfMessage, params);
166         String formatMessage = slfMessage.replaceAll("\\{\\}", "%s");
167         return format(formatMessage, params);
168     }
169
170     private static class BundleKey {
171         Bundle bundle;
172         BundleContext bundleContext;
173
174         public BundleKey(Bundle bundle) {
175             this.bundle = bundle;
176         }
177
178         BundleContext getBundleContext() {
179             if(bundleContext != null) {
180                 return bundleContext;
181             }
182
183             // If the bundle isn't activated yet, it may not have a BundleContext yet so busy wait for it.
184             Stopwatch timer = Stopwatch.createStarted();
185             while(timer.elapsed(TimeUnit.MILLISECONDS) <= BUNDLE_CONTEXT_TIMEOUT) {
186                 bundleContext = bundle.getBundleContext();
187                 if(bundleContext != null) {
188                     return bundleContext;
189                 }
190
191                 Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
192             }
193
194             return null;
195         }
196
197         @Override
198         public int hashCode() {
199             return (int) bundle.getBundleId();
200         }
201
202         @Override
203         public boolean equals(Object obj) {
204             if (getClass() != obj.getClass()) {
205                 return false;
206             }
207             BundleKey other = (BundleKey) obj;
208             return bundle.getBundleId() == other.bundle.getBundleId();
209         }
210     }
211 }