2 * Copyright (c) 2013 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
8 package org.opendaylight.controller.config.manager.impl.osgi;
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;
20 import java.util.AbstractMap;
21 import java.util.ArrayList;
22 import java.util.Collection;
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;
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
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);
48 private final BlankTransactionServiceTracker blankTransactionServiceTracker;
50 @GuardedBy(value = "bundleModuleFactoryMap")
51 private final Multimap<BundleKey, ModuleFactory> bundleModuleFactoryMap = HashMultimap.create();
53 public ModuleFactoryBundleTracker(BlankTransactionServiceTracker blankTransactionServiceTracker) {
54 this.blankTransactionServiceTracker = blankTransactionServiceTracker;
58 public Object addingBundle(Bundle bundle, BundleEvent event) {
59 URL resource = bundle.getEntry("META-INF/services/" + ModuleFactory.class.getName());
60 LOG.trace("Got addingBundle event of bundle {}, resource {}, event {}",
61 bundle, resource, event);
62 if (resource != null) {
64 for (String factoryClassName : Resources.readLines(resource, Charsets.UTF_8)) {
65 Entry<ModuleFactory, Bundle> moduleFactoryEntry = registerFactory(factoryClassName, bundle);
66 synchronized (bundleModuleFactoryMap) {
67 bundleModuleFactoryMap.put(new BundleKey(moduleFactoryEntry.getValue()),
68 moduleFactoryEntry.getKey());
71 } catch (IOException e) {
72 LOG.error("Error while reading {}", resource, e);
73 throw new RuntimeException(e);
80 public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
85 public void removedBundle(Bundle bundle, BundleEvent event, Object object) {
86 bundleModuleFactoryMap.removeAll(new BundleKey(bundle));
88 // workaround for service tracker not getting removed service event
89 blankTransactionServiceTracker.blankTransaction();
92 public Collection<Map.Entry<ModuleFactory, BundleContext>> getModuleFactoryEntries() {
93 Collection<Entry<BundleKey, ModuleFactory>> entries;
94 synchronized (bundleModuleFactoryMap) {
95 entries = new ArrayList<>(bundleModuleFactoryMap.entries());
98 Collection<Map.Entry<ModuleFactory, BundleContext>> result = new ArrayList<>(entries.size());
99 for(Entry<BundleKey, ModuleFactory> entry: entries) {
100 BundleContext context = entry.getKey().getBundleContext();
101 if(context == null) {
102 LOG.warn("Bundle context for {} ModuleFactory not found", entry.getValue());
104 result.add(new AbstractMap.SimpleImmutableEntry<>(entry.getValue(), context));
112 protected static Map.Entry<ModuleFactory, Bundle> registerFactory(String factoryClassName, Bundle bundle) {
116 Class<?> clazz = bundle.loadClass(factoryClassName);
117 if (ModuleFactory.class.isAssignableFrom(clazz)) {
119 LOG.debug("Registering {} in bundle {}", clazz.getName(), bundle);
121 return new AbstractMap.SimpleImmutableEntry<>((ModuleFactory)clazz.newInstance(), bundle);
122 } catch (InstantiationException e) {
123 errorMessage = logMessage(
124 "Could not instantiate {} in bundle {}, reason {}",
125 factoryClassName, bundle, e);
127 } catch (IllegalAccessException e) {
128 errorMessage = logMessage(
129 "Illegal access during instantiation of class {} in bundle {}, reason {}",
130 factoryClassName, bundle, e);
132 } catch (RuntimeException e) {
133 errorMessage = logMessage(
134 "Unexpected exception during instantiation of class {} in bundle {}, reason {}",
135 clazz, bundle.getBundleContext(), e);
139 errorMessage = logMessage(
140 "Class {} does not implement {} in bundle {}", clazz,
141 ModuleFactory.class, bundle);
143 } catch (ClassNotFoundException e) {
144 errorMessage = logMessage(
145 "Could not find class {} in bundle {}, reason {}",
146 factoryClassName, bundle, e);
150 throw ex == null ? new IllegalStateException(errorMessage) : new IllegalStateException(errorMessage, ex);
153 public static String logMessage(String slfMessage, Object... params) {
154 LOG.info(slfMessage, params);
155 String formatMessage = slfMessage.replaceAll("\\{\\}", "%s");
156 return format(formatMessage, params);
159 private static class BundleKey {
161 BundleContext bundleContext;
163 public BundleKey(Bundle bundle) {
164 this.bundle = bundle;
167 BundleContext getBundleContext() {
168 if(bundleContext != null) {
169 return bundleContext;
172 // If the bundle isn't activated yet, it may not have a BundleContext yet so busy wait for it.
173 Stopwatch timer = Stopwatch.createStarted();
174 while(timer.elapsed(TimeUnit.MILLISECONDS) <= BUNDLE_CONTEXT_TIMEOUT) {
175 bundleContext = bundle.getBundleContext();
176 if(bundleContext != null) {
177 return bundleContext;
180 Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
187 public int hashCode() {
188 return (int) bundle.getBundleId();
192 public boolean equals(Object obj) {
193 if (getClass() != obj.getClass()) {
196 BundleKey other = (BundleKey) obj;
197 return bundle.getBundleId() == other.bundle.getBundleId();