BUG-8360: add mdsal-binding-dom-codec-osgi
[mdsal.git] / binding / mdsal-binding-dom-codec-osgi / src / main / java / org / opendaylight / mdsal / binding / dom / codec / osgi / impl / ModuleInfoBundleTracker.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. 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.mdsal.binding.dom.codec.osgi.impl;
9
10 import static com.google.common.base.Preconditions.checkNotNull;
11
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.io.Resources;
14 import java.io.IOException;
15 import java.net.URL;
16 import java.nio.charset.StandardCharsets;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
20 import java.util.regex.Pattern;
21 import org.opendaylight.yangtools.concepts.ObjectRegistration;
22 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
23 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
24 import org.osgi.framework.Bundle;
25 import org.osgi.framework.BundleEvent;
26 import org.osgi.util.tracker.BundleTrackerCustomizer;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * Tracks bundles and attempts to retrieve YangModuleInfo, which is then fed into ModuleInfoRegistry
32  */
33 final class ModuleInfoBundleTracker implements BundleTrackerCustomizer<Collection<ObjectRegistration<YangModuleInfo>>> {
34     private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBundleTracker.class);
35     // FIXME: this should be in a place shared with maven-sal-api-gen-plugin
36     private static final String MODULE_INFO_PROVIDER_PATH_PREFIX = "META-INF/services/";
37
38     private static final String YANG_MODLE_BINDING_PROVIDER_SERVICE = MODULE_INFO_PROVIDER_PATH_PREFIX
39             + YangModelBindingProvider.class.getName();
40
41     private static final Pattern BRACE_PATTERN = Pattern.compile("{}", Pattern.LITERAL);
42
43     private final OsgiModuleInfoRegistry moduleInfoRegistry;
44
45     private volatile boolean starting = true;
46
47     ModuleInfoBundleTracker(final OsgiModuleInfoRegistry moduleInfoRegistry) {
48         this.moduleInfoRegistry = checkNotNull(moduleInfoRegistry);
49     }
50
51     void finishStart() {
52         starting = false;
53         moduleInfoRegistry.updateService();
54     }
55
56     @Override
57     public Collection<ObjectRegistration<YangModuleInfo>> addingBundle(final Bundle bundle, final BundleEvent event) {
58         final URL resource = bundle.getEntry(YANG_MODLE_BINDING_PROVIDER_SERVICE);
59         if (resource == null) {
60             LOG.debug("Bundle {} does not have an entry for {}", bundle, YANG_MODLE_BINDING_PROVIDER_SERVICE);
61             return ImmutableList.of();
62         }
63
64         LOG.debug("Got addingBundle({}) with YangModelBindingProvider resource {}", bundle, resource);
65         final List<String> lines;
66         try {
67             lines = Resources.readLines(resource, StandardCharsets.UTF_8);
68         } catch (IOException e) {
69             LOG.error("Error while reading {} from bundle {}", resource, bundle, e);
70             return ImmutableList.of();
71         }
72
73         if (lines.isEmpty()) {
74             LOG.debug("Bundle {} has empty services for {}", bundle, YANG_MODLE_BINDING_PROVIDER_SERVICE);
75             return ImmutableList.of();
76         }
77
78         final List<ObjectRegistration<YangModuleInfo>> registrations = new ArrayList<>(lines.size());
79         for (String moduleInfoName : lines) {
80             LOG.trace("Retrieve ModuleInfo({}, {})", moduleInfoName, bundle);
81             final YangModuleInfo moduleInfo;
82             try {
83                 moduleInfo = retrieveModuleInfo(moduleInfoName, bundle);
84             } catch (RuntimeException e) {
85                 LOG.warn("Failed to acquire {} from bundle {}, ignoring it", moduleInfoName, bundle, e);
86                 continue;
87             }
88
89             registrations.add(moduleInfoRegistry.registerModuleInfo(moduleInfo));
90         }
91
92         if (!starting) {
93             moduleInfoRegistry.updateService();
94         }
95
96         LOG.trace("Bundle {} resultend in registrations {}", registrations);
97         return registrations;
98     }
99
100     @Override
101     public void modifiedBundle(final Bundle bundle, final BundleEvent event,
102             final Collection<ObjectRegistration<YangModuleInfo>> object) {
103         // No-op
104     }
105
106     @Override
107     public void removedBundle(final Bundle bundle, final BundleEvent event,
108             final Collection<ObjectRegistration<YangModuleInfo>> regs) {
109         if (regs == null) {
110             return;
111         }
112
113         for (ObjectRegistration<YangModuleInfo> reg : regs) {
114             try {
115                 reg.close();
116             } catch (Exception e) {
117                 LOG.warn("Unable to unregister YangModuleInfo {}", reg.getInstance(), e);
118             }
119         }
120     }
121
122     private static YangModuleInfo retrieveModuleInfo(final String moduleInfoClass, final Bundle bundle) {
123         final Class<?> clazz = loadClass(moduleInfoClass, bundle);
124         if (!YangModelBindingProvider.class.isAssignableFrom(clazz)) {
125             String errorMessage = logMessage("Class {} does not implement {} in bundle {}", clazz,
126                 YangModelBindingProvider.class, bundle);
127             throw new IllegalStateException(errorMessage);
128         }
129
130         final YangModelBindingProvider instance;
131         try {
132             Object instanceObj = clazz.newInstance();
133             instance = YangModelBindingProvider.class.cast(instanceObj);
134         } catch (InstantiationException e) {
135             String errorMessage = logMessage("Could not instantiate {} in bundle {}, reason {}", moduleInfoClass,
136                 bundle, e);
137             throw new IllegalStateException(errorMessage, e);
138         } catch (IllegalAccessException e) {
139             String errorMessage = logMessage("Illegal access during instantiation of class {} in bundle {}, reason {}",
140                     moduleInfoClass, bundle, e);
141             throw new IllegalStateException(errorMessage, e);
142         }
143
144         try {
145             return instance.getModuleInfo();
146         } catch (NoClassDefFoundError | ExceptionInInitializerError e) {
147             throw new IllegalStateException("Error while executing getModuleInfo on " + instance, e);
148         }
149     }
150
151     private static Class<?> loadClass(final String moduleInfoClass, final Bundle bundle) {
152         try {
153             return bundle.loadClass(moduleInfoClass);
154         } catch (ClassNotFoundException e) {
155             String errorMessage = logMessage("Could not find class {} in bundle {}, reason {}", moduleInfoClass, bundle,
156                 e);
157             throw new IllegalStateException(errorMessage);
158         }
159     }
160
161     private static String logMessage(final String slfMessage, final Object... params) {
162         LOG.info(slfMessage, params);
163         return String.format(BRACE_PATTERN.matcher(slfMessage).replaceAll("%s"), params);
164     }
165 }