Improve config system shutdown
[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.io.Resources;
14 import java.io.IOException;
15 import java.net.URL;
16 import org.opendaylight.controller.config.spi.ModuleFactory;
17 import org.osgi.framework.Bundle;
18 import org.osgi.framework.BundleEvent;
19 import org.osgi.framework.ServiceRegistration;
20 import org.osgi.util.tracker.BundleTrackerCustomizer;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 /**
25  * OSGi extender that listens for bundle activation events. Reads file
26  * META-INF/services/org.opendaylight.controller.config.spi.ModuleFactory, each
27  * line should contain an implementation of ModuleFactory interface. Creates new
28  * instance with default constructor and registers it into OSGi service
29  * registry. There is no need for listening for implementing removedBundle as
30  * the services are unregistered automatically.
31  * Code based on http://www.toedter.com/blog/?p=236
32  */
33 public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer<Boolean> {
34     private final BlankTransactionServiceTracker blankTransactionServiceTracker;
35     private static final Logger LOG = LoggerFactory.getLogger(ModuleFactoryBundleTracker.class);
36
37     public ModuleFactoryBundleTracker(BlankTransactionServiceTracker blankTransactionServiceTracker) {
38         this.blankTransactionServiceTracker = blankTransactionServiceTracker;
39     }
40
41     @Override
42     public Boolean addingBundle(Bundle bundle, BundleEvent event) {
43         URL resource = bundle.getEntry("META-INF/services/" + ModuleFactory.class.getName());
44         LOG.trace("Got addingBundle event of bundle {}, resource {}, event {}",
45                 bundle, resource, event);
46         if (resource != null) {
47             try {
48                 for (String factoryClassName : Resources.readLines(resource, Charsets.UTF_8)) {
49                     registerFactory(factoryClassName, bundle);
50                 }
51
52                 return Boolean.TRUE;
53             } catch (IOException e) {
54                 LOG.error("Error while reading {}", resource, e);
55                 throw new RuntimeException(e);
56             }
57         }
58
59         return Boolean.FALSE;
60     }
61
62     @Override
63     public void modifiedBundle(Bundle bundle, BundleEvent event, Boolean hasFactory) {
64         // NOOP
65     }
66
67     @Override
68     public void removedBundle(Bundle bundle, BundleEvent event, Boolean hasFactory) {
69         if(hasFactory) {
70             // workaround for service tracker not getting removed service event
71             blankTransactionServiceTracker.blankTransactionSync();
72         }
73     }
74
75     @VisibleForTesting
76     protected static ServiceRegistration<?> registerFactory(String factoryClassName, Bundle bundle) {
77         String errorMessage;
78         Exception ex = null;
79         try {
80             Class<?> clazz = bundle.loadClass(factoryClassName);
81             if (ModuleFactory.class.isAssignableFrom(clazz)) {
82                 try {
83                     LOG.debug("Registering {} in bundle {}",
84                             clazz.getName(), bundle);
85                     return bundle.getBundleContext().registerService(
86                             ModuleFactory.class.getName(), clazz.newInstance(),
87                             null);
88                 } catch (InstantiationException e) {
89                     errorMessage = logMessage(
90                             "Could not instantiate {} in bundle {}, reason {}",
91                             factoryClassName, bundle, e);
92                     ex = e;
93                 } catch (IllegalAccessException e) {
94                     errorMessage = logMessage(
95                             "Illegal access during instantiation of class {} in bundle {}, reason {}",
96                             factoryClassName, bundle, e);
97                     ex = e;
98                 }
99             } else {
100                 errorMessage = logMessage(
101                         "Class {} does not implement {} in bundle {}", clazz,
102                         ModuleFactory.class, bundle);
103             }
104         } catch (ClassNotFoundException e) {
105             errorMessage = logMessage(
106                     "Could not find class {} in bundle {}, reason {}",
107                     factoryClassName, bundle, e);
108             ex = e;
109         }
110
111         throw ex == null ? new IllegalStateException(errorMessage) : new IllegalStateException(errorMessage, ex);
112     }
113
114     public static String logMessage(String slfMessage, Object... params) {
115         LOG.info(slfMessage, params);
116         String formatMessage = slfMessage.replaceAll("\\{\\}", "%s");
117         return format(formatMessage, params);
118     }
119 }