aboutsummaryrefslogtreecommitdiffstats
path: root/container-core/src/main/java/com/yahoo/osgi/OsgiImpl.java
blob: 4909f9a76eb01a11de49ed06c55310c8f97741fe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.osgi;

import com.yahoo.component.ComponentSpecification;
import com.yahoo.component.Version;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.jdisc.application.OsgiFramework;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.launch.Framework;

import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author Tony Vaagenes
 * @author bratseth
 * @author gjoranv
 */
public class OsgiImpl implements Osgi {

    private static final Logger log = Logger.getLogger(OsgiImpl.class.getName());

    private final OsgiFramework jdiscOsgi;

    // The initial bundles are never scheduled for uninstall
    private final List<Bundle> initialBundles;

    // An initial bundle that is not the framework, and can hence be used to look up current bundles
    private final Bundle alwaysCurrentBundle;

    public OsgiImpl(OsgiFramework jdiscOsgi) {
        this.jdiscOsgi = jdiscOsgi;

        this.initialBundles = jdiscOsgi.bundles();
        if (initialBundles.isEmpty())
            throw new IllegalStateException("No initial bundles!");

        alwaysCurrentBundle = firstNonFrameworkBundle(initialBundles);
        if (alwaysCurrentBundle == null)
            throw new IllegalStateException("The initial bundles only contained the framework bundle!");
        log.info("Using " + alwaysCurrentBundle + " to lookup current bundles.");
    }

    @Override
    public Bundle[] getBundles() {
        List<Bundle> bundles = jdiscOsgi.bundles();
        return bundles.toArray(new Bundle[bundles.size()]);
    }

    @Override
    public List<Bundle> getCurrentBundles() {
        return jdiscOsgi.getBundles(alwaysCurrentBundle);
    }

    public Class<Object> resolveClass(BundleInstantiationSpecification spec) {
        Bundle bundle = getBundle(spec.bundle);
        if (bundle != null) {
            return resolveFromBundle(spec, bundle);
        } else {
            return resolveFromClassPath(spec);
        }
    }

    @SuppressWarnings("unchecked")
    private static Class<Object> resolveFromClassPath(BundleInstantiationSpecification spec) {
        try {
            return (Class<Object>) Class.forName(spec.classId.getName());
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Could not create a component with id '" + spec.classId.getName() +
                    "'. Tried to load class directly, since no bundle was found for spec: " + spec.bundle +
                    ". If a bundle with the same name is installed, there is a either a version mismatch" +
                    " or the installed bundle's version contains a qualifier string.");
        }
    }

    @SuppressWarnings("unchecked")
    private static Class<Object> resolveFromBundle(BundleInstantiationSpecification spec, Bundle bundle) {
        try {
            ensureBundleActive(bundle);
            return (Class<Object>) bundle.loadClass(spec.classId.getName());
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Could not load class '" + spec.classId.getName() +
                                               "' from bundle " + bundle, e);
        }
    }

    private static void ensureBundleActive(Bundle bundle) throws IllegalStateException {
        int state = bundle.getState();
        Throwable cause = null;
        if (state != Bundle.ACTIVE) {
            try {
                // Get the reason why the bundle isn't active.
                // Do not change this method to not fail if start is successful without carefully analyzing
                // why there are non-active bundles.
                bundle.start();
            } catch (BundleException e) {
                cause = e;
            }
            throw new IllegalStateException("Bundle " + bundle + " is not active. State=" + state + ".", cause);
        }
    }

    /**
     * Returns the bundle of a given name having the highest matching version
     *
     * @param id the id of the component to return. May not include a version, or include
     *        an underspecified version, in which case the highest (matching) version which
     *        does not contain a qualifier is returned
     * @return the bundle match having the highest version, or null if there was no matches
     */
    public Bundle getBundle(ComponentSpecification id) {
        log.fine(() -> "Getting bundle for component " + id + ". Set of current bundles: " + getCurrentBundles());
        Bundle highestMatch = null;
        for (Bundle bundle : getCurrentBundles()) {
            assert bundle.getSymbolicName() != null : "ensureHasBundleSymbolicName not called during installation";

            if ( ! bundle.getSymbolicName().equals(id.getName())) continue;
            if ( ! id.getVersionSpecification().matches(versionOf(bundle))) continue;

            if (highestMatch == null || versionOf(highestMatch).compareTo(versionOf(bundle)) < 0)
                highestMatch = bundle;
        }
        return highestMatch;
    }

    /** Returns the version of a bundle, as specified by Bundle-Version in the manifest */
    private static Version versionOf(Bundle bundle) {
        Object bundleVersion = bundle.getHeaders().get("Bundle-Version");
        if (bundleVersion == null) return Version.emptyVersion;
        return new Version(bundleVersion.toString());
    }

    @Override
    public List<Bundle> install(String absolutePath) {
        try {
            return jdiscOsgi.installBundle(normalizeLocation(absolutePath));
        } catch (BundleException e) {
            throw new RuntimeException(e);
        }
    }

    private static String normalizeLocation(String location) {
        if (location.indexOf(':') < 0)
            location = "file:" + location;
        return location;
    }

    @Override
    public void allowDuplicateBundles(Collection<Bundle> bundles) {
        jdiscOsgi.allowDuplicateBundles(bundles);
    }

    @Override
    public boolean hasFelixFramework() {
        return jdiscOsgi.isFelixFramework();
    }

    private static Bundle firstNonFrameworkBundle(List<Bundle> bundles) {
        for (Bundle b : bundles) {
            if (! (b instanceof Framework))
                return b;
        }
        return null;
    }

}