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