aboutsummaryrefslogtreecommitdiffstats
path: root/container-core/src/main/java/com/yahoo/container/core/config/HandlersConfigurerDi.java
blob: eec4e4d9bb6b23a3c200331d2964bae24caceaf4 (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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.core.config;

import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.yahoo.component.AbstractComponent;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.component.annotation.Inject;
import com.yahoo.component.provider.ComponentRegistry;
import com.yahoo.concurrent.ThreadFactoryFactory;
import com.yahoo.config.FileReference;
import com.yahoo.container.di.ComponentDeconstructor;
import com.yahoo.container.di.Container;
import com.yahoo.container.di.componentgraph.core.ComponentGraph;
import com.yahoo.container.di.config.SubscriberFactory;
import com.yahoo.container.logging.AccessLog;
import com.yahoo.filedistribution.fileacquirer.FileAcquirer;
import com.yahoo.jdisc.application.BsnVersion;
import com.yahoo.jdisc.application.OsgiFramework;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.service.ClientProvider;
import com.yahoo.jdisc.service.ServerProvider;
import com.yahoo.osgi.OsgiImpl;
import com.yahoo.osgi.OsgiWrapper;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * For internal use only.
 *
 * @author Tony Vaagenes
 * @author gjoranv
 */
//TODO: rename
public class HandlersConfigurerDi {

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

    private static final Executor fallbackExecutor = Executors.newCachedThreadPool(
            ThreadFactoryFactory.getThreadFactory("HandlersConfigurerDI"));

    private final com.yahoo.container.Container vespaContainer;
    private final Container container;

    private volatile ComponentGraph currentGraph = new ComponentGraph(0);

    public HandlersConfigurerDi(SubscriberFactory subscriberFactory,
                                com.yahoo.container.Container vespaContainer,
                                String configId,
                                ComponentDeconstructor deconstructor,
                                Injector discInjector,
                                OsgiFramework osgiFramework) {

        this(subscriberFactory, vespaContainer, configId, deconstructor, discInjector,
             new ContainerAndDiOsgi(osgiFramework, vespaContainer.getFileAcquirer()));
    }

    // Only public for testing
    public HandlersConfigurerDi(SubscriberFactory subscriberFactory,
                                com.yahoo.container.Container vespaContainer,
                                String configId,
                                ComponentDeconstructor deconstructor,
                                Injector discInjector,
                                OsgiWrapper osgiWrapper) {

        this.vespaContainer = vespaContainer;
        container = new Container(subscriberFactory, configId, deconstructor, osgiWrapper);
        Runnable cleanupTask = waitForNextGraphGeneration(discInjector, true);
        cleanupTask.run();
    }

    private static class ContainerAndDiOsgi extends OsgiImpl implements OsgiWrapper {

        private final OsgiFramework osgiFramework;
        private final ApplicationBundleLoader applicationBundleLoader;
        private final PlatformBundleLoader platformBundleLoader;

        public ContainerAndDiOsgi(OsgiFramework osgiFramework, FileAcquirer fileAcquirer) {
            super(osgiFramework);
            this.osgiFramework = osgiFramework;

            applicationBundleLoader = new ApplicationBundleLoader(this, new FileAcquirerBundleInstaller(fileAcquirer));
            platformBundleLoader = new PlatformBundleLoader(this);
        }

        @Override
        public void installPlatformBundles(Collection<String> bundlePaths) {
            // Don't install physical bundles for test frameworks, where all platform bundles are on the classpath.
            if (osgiFramework.isFelixFramework()) {
                log.fine("Installing platform bundles.");
                platformBundleLoader.useBundles(new ArrayList<>(bundlePaths));
            }
        }

        @Override
        public void useApplicationBundles(Collection<FileReference> bundles, long generation) {
            if (! bundles.isEmpty()) log.info("Installing bundles for application generation " + generation);
            applicationBundleLoader.useBundles(new ArrayList<>(bundles));
        }

        @Override
        public Set<Bundle> completeBundleGeneration(GenerationStatus status) {
            return applicationBundleLoader.completeGeneration(status);
        }

        @Override
        protected String bundleResolutionErrorMessage(ComponentSpecification bundleSpec) {
            List<BsnVersion> activeBundles = applicationBundleLoader.activeBundlesBsnVersion();
            List<Version> activeVersions = activeVersionsOfBundle(bundleSpec, activeBundles);

            String versionsMessage = "";
            if (activeVersions.size() == 1) {
                versionsMessage = "There is an installed bundle with the same name with version: " + activeVersions.get(0) + " ";
            } else if (activeVersions.size() > 1) {
                versionsMessage = "There are installed bundles with the same name with versions: " + activeVersions + " ";
            }
            if (qualifierIsUsed(bundleSpec, activeVersions)) {
                versionsMessage += " Note that qualifier strings must be matched exactly. ";
            }
            return String.format("%sInstalled application bundles: [%s]",
                                 versionsMessage,
                                 activeBundles.stream()
                                         .map(BsnVersion::toReadableString)
                                         .collect(Collectors.joining(", ")));
        }

        private static boolean qualifierIsUsed(ComponentSpecification bundleSpec, List<Version> activeVersions) {
            return ! bundleSpec.getVersionSpecification().getQualifier().isEmpty() ||
                    activeVersions.stream().anyMatch(version -> ! version.getQualifier().isEmpty());
        }

        private static List<Version> activeVersionsOfBundle(ComponentSpecification bundleSpec, List<BsnVersion> activeBundles) {
            return activeBundles.stream()
                    .filter(bundle -> bundle.symbolicName().equals(bundleSpec.getName()))
                    .map(BsnVersion::version)
                    .toList();
        }
    }

    /**
     * Wait for new config to arrive and produce the new graph
     * @return Task for deconstructing previous component graph and bundles
     */
    public Runnable waitForNextGraphGeneration(Injector discInjector, boolean isInitializing) {
        Container.ComponentGraphResult result = container.waitForNextGraphGeneration(
                this.currentGraph,
                createFallbackInjector(vespaContainer, discInjector),
                isInitializing);
        this.currentGraph = result.newGraph();
        return result.oldComponentsCleanupTask();
    }

    private Injector createFallbackInjector(com.yahoo.container.Container vespaContainer, Injector discInjector) {
        return discInjector.createChildInjector(new AbstractModule() {
            @Override
            protected void configure() {
                // Provide a singleton instance for all component fallbacks,
                // otherwise fallback injection may lead to a cascade of components requiring reconstruction.
                bind(com.yahoo.container.Container.class).toInstance(vespaContainer);
                bind(AccessLog.class).toInstance(AccessLog.NONE_INSTANCE);
                bind(Executor.class).toInstance(fallbackExecutor);
                if (vespaContainer.getFileAcquirer() != null)
                    bind(com.yahoo.filedistribution.fileacquirer.FileAcquirer.class).toInstance(vespaContainer.getFileAcquirer());
            }
        });
    }

    public void reloadConfig(long generation) {
        container.reloadConfig(generation);
    }

    public <T> T getComponent(Class<T> componentClass) {
        return currentGraph.getInstance(componentClass);
    }

    public void shutdown() { container.shutdown(currentGraph); }

    public void shutdownConfigRetriever() { container.shutdownConfigRetriever(); }

    /** Returns the currently active application configuration generation */
    public long generation() { return currentGraph.generation(); }

    public static class RegistriesHack {

        @Inject
        public RegistriesHack(com.yahoo.container.Container vespaContainer,
                              ComponentRegistry<AbstractComponent> allComponents,
                              ComponentRegistry<RequestHandler> requestHandlerRegistry,
                              ComponentRegistry<ClientProvider> clientProviderRegistry,
                              ComponentRegistry<ServerProvider> serverProviderRegistry) {
            log.log(Level.FINE, () -> "RegistriesHack.init " + System.identityHashCode(this));

            vespaContainer.setComponentRegistry(allComponents);
            vespaContainer.setRequestHandlerRegistry(requestHandlerRegistry);
            vespaContainer.setClientProviderRegistry(clientProviderRegistry);
            vespaContainer.setServerProviderRegistry(serverProviderRegistry);
        }

    }

}