Modify ModuleInfoBundleTracker to track RESOLVED bundles
[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         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) {
63             try {
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());
69                     }
70                 }
71             } catch (IOException e) {
72                 LOG.error("Error while reading {}", resource, e);
73                 throw new RuntimeException(e);
74             }
75         }
76         return bundle;
77     }
78
79     @Override
80     public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
81         // NOOP
82     }
83
84     @Override
85     public void removedBundle(Bundle bundle, BundleEvent event, Object object) {
86         bundleModuleFactoryMap.removeAll(new BundleKey(bundle));
87
88         // workaround for service tracker not getting removed service event
89         blankTransactionServiceTracker.blankTransaction();
90     }
91
92     public Collection<Map.Entry<ModuleFactory, BundleContext>> getModuleFactoryEntries() {
93         Collection<Entry<BundleKey, ModuleFactory>> entries;
94         synchronized (bundleModuleFactoryMap) {
95             entries = new ArrayList<>(bundleModuleFactoryMap.entries());
96         }
97
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());
103             } else {
104                 result.add(new AbstractMap.SimpleImmutableEntry<>(entry.getValue(), context));
105             }
106         }
107
108         return result;
109     }
110
111     @VisibleForTesting
112     protected static Map.Entry<ModuleFactory, Bundle> registerFactory(String factoryClassName, Bundle bundle) {
113         String errorMessage;
114         Exception ex = null;
115         try {
116             Class<?> clazz = bundle.loadClass(factoryClassName);
117             if (ModuleFactory.class.isAssignableFrom(clazz)) {
118                 try {
119                     LOG.debug("Registering {} in bundle {}", clazz.getName(), bundle);
120
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);
126                     ex = e;
127                 } catch (IllegalAccessException e) {
128                     errorMessage = logMessage(
129                             "Illegal access during instantiation of class {} in bundle {}, reason {}",
130                             factoryClassName, bundle, e);
131                     ex = e;
132                 } catch (RuntimeException e) {
133                     errorMessage = logMessage(
134                             "Unexpected exception during instantiation of class {} in bundle {}, reason {}",
135                             clazz, bundle.getBundleContext(), e);
136                     ex = e;
137                 }
138             } else {
139                 errorMessage = logMessage(
140                         "Class {} does not implement {} in bundle {}", clazz,
141                         ModuleFactory.class, bundle);
142             }
143         } catch (ClassNotFoundException e) {
144             errorMessage = logMessage(
145                     "Could not find class {} in bundle {}, reason {}",
146                     factoryClassName, bundle, e);
147             ex = e;
148         }
149
150         throw ex == null ? new IllegalStateException(errorMessage) : new IllegalStateException(errorMessage, ex);
151     }
152
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);
157     }
158
159     private static class BundleKey {
160         Bundle bundle;
161         BundleContext bundleContext;
162
163         public BundleKey(Bundle bundle) {
164             this.bundle = bundle;
165         }
166
167         BundleContext getBundleContext() {
168             if(bundleContext != null) {
169                 return bundleContext;
170             }
171
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;
178                 }
179
180                 Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
181             }
182
183             return null;
184         }
185
186         @Override
187         public int hashCode() {
188             return (int) bundle.getBundleId();
189         }
190
191         @Override
192         public boolean equals(Object obj) {
193             if (getClass() != obj.getClass()) {
194                 return false;
195             }
196             BundleKey other = (BundleKey) obj;
197             return bundle.getBundleId() == other.bundle.getBundleId();
198         }
199     }
200 }