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 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
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) {
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());
80 } catch (IOException e) {
81 LOG.error("Error while reading {}", resource, e);
82 throw new RuntimeException(e);
89 public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
94 public void removedBundle(Bundle bundle, BundleEvent event, Object object) {
95 synchronized (bundleModuleFactoryMap) {
96 bundleModuleFactoryMap.removeAll(new BundleKey(bundle));
99 // workaround for service tracker not getting removed service event
100 blankTransactionServiceTracker.blankTransaction();
103 public Collection<Map.Entry<ModuleFactory, BundleContext>> getModuleFactoryEntries() {
104 Collection<Entry<BundleKey, ModuleFactory>> entries;
105 synchronized (bundleModuleFactoryMap) {
106 entries = new ArrayList<>(bundleModuleFactoryMap.entries());
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());
115 result.add(new AbstractMap.SimpleImmutableEntry<>(entry.getValue(), context));
123 protected static Map.Entry<ModuleFactory, Bundle> registerFactory(String factoryClassName, Bundle bundle) {
127 Class<?> clazz = bundle.loadClass(factoryClassName);
128 if (ModuleFactory.class.isAssignableFrom(clazz)) {
130 LOG.debug("Registering {} in bundle {}", clazz.getName(), bundle);
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);
138 } catch (IllegalAccessException e) {
139 errorMessage = logMessage(
140 "Illegal access during instantiation of class {} in bundle {}, reason {}",
141 factoryClassName, bundle, e);
143 } catch (RuntimeException e) {
144 errorMessage = logMessage(
145 "Unexpected exception during instantiation of class {} in bundle {}, reason {}",
146 clazz, bundle.getBundleContext(), e);
150 errorMessage = logMessage(
151 "Class {} does not implement {} in bundle {}", clazz,
152 ModuleFactory.class, bundle);
154 } catch (ClassNotFoundException e) {
155 errorMessage = logMessage(
156 "Could not find class {} in bundle {}, reason {}",
157 factoryClassName, bundle, e);
161 throw ex == null ? new IllegalStateException(errorMessage) : new IllegalStateException(errorMessage, ex);
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);
170 private static class BundleKey {
172 BundleContext bundleContext;
174 public BundleKey(Bundle bundle) {
175 this.bundle = bundle;
178 BundleContext getBundleContext() {
179 if(bundleContext != null) {
180 return bundleContext;
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;
191 Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
198 public int hashCode() {
199 return (int) bundle.getBundleId();
203 public boolean equals(Object obj) {
204 if (getClass() != obj.getClass()) {
207 BundleKey other = (BundleKey) obj;
208 return bundle.getBundleId() == other.bundle.getBundleId();