aboutsummaryrefslogtreecommitdiffstats
path: root/container-core/src/test/java/com/yahoo/container/di/ContainerTest.java
blob: 30dc4f313e45a15bf36fd5ca88cfb980c346e79b (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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.di;

import com.google.inject.Guice;
import com.yahoo.component.AbstractComponent;
import com.yahoo.config.di.IntConfig;
import com.yahoo.config.test.TestConfig;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.container.di.componentgraph.core.ComponentGraph;
import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.SimpleComponent;
import com.yahoo.container.di.componentgraph.core.ComponentNode.ComponentConstructorException;
import org.junit.Ignore;
import org.junit.Test;
import org.osgi.framework.Bundle;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * @author Tony Vaagenes
 * @author gjoranv
 * @author ollivir
 */
public class ContainerTest extends ContainerTestBase {

    @Test
    public void components_can_be_created_from_config() {
        writeBootstrapConfigs();
        dirConfigSource.writeConfig("test", "stringVal \"myString\"");

        Container container = newContainer(dirConfigSource);

        ComponentTakingConfig component = createComponentTakingConfig(getNewComponentGraph(container));
        assertEquals("myString", component.config.stringVal());

        container.shutdownConfigRetriever();
    }

    @Test
    public void components_are_reconfigured_after_config_update_without_bootstrap_configs() {
        writeBootstrapConfigs();
        dirConfigSource.writeConfig("test", "stringVal \"original\"");

        Container container = newContainer(dirConfigSource);
        ComponentGraph componentGraph = getNewComponentGraph(container);
        ComponentTakingConfig component = createComponentTakingConfig(componentGraph);

        assertEquals("original", component.config.stringVal());

        // Reconfigure
        dirConfigSource.writeConfig("test", "stringVal \"reconfigured\"");
        container.reloadConfig(2);

        ComponentGraph newComponentGraph = getNewComponentGraph(container, componentGraph);
        ComponentTakingConfig component2 = createComponentTakingConfig(newComponentGraph);
        assertEquals("reconfigured", component2.config.stringVal());

        container.shutdownConfigRetriever();
    }

    @Test
    public void graph_is_updated_after_bootstrap_update() {
        dirConfigSource.writeConfig("test", "stringVal \"original\"");
        writeBootstrapConfigs("id1");

        Container container = newContainer(dirConfigSource);

        ComponentGraph graph = getNewComponentGraph(container);
        ComponentTakingConfig component = createComponentTakingConfig(graph);
        assertEquals("id1", component.getId().toString());

        writeBootstrapConfigs(
                new ComponentEntry("id1", ComponentTakingConfig.class),
                new ComponentEntry("id2", ComponentTakingConfig.class));

        container.reloadConfig(2);
        ComponentGraph newGraph = getNewComponentGraph(container, graph);

        assertNotNull(ComponentGraph.getNode(newGraph, "id1"));
        assertNotNull(ComponentGraph.getNode(newGraph, "id2"));

        container.shutdownConfigRetriever();
    }

    //@Test TODO
    public void deconstructor_is_given_guice_components() {
    }

    @Test
    public void component_is_deconstructed_when_not_reused() {
        writeBootstrapConfigs("id1", DestructableComponent.class);

        Container container = newContainer(dirConfigSource);

        ComponentGraph oldGraph = getNewComponentGraph(container);
        DestructableComponent componentToDestruct = oldGraph.getInstance(DestructableComponent.class);

        writeBootstrapConfigs("id2", DestructableComponent.class);
        container.reloadConfig(2);
        getNewComponentGraph(container, oldGraph);
        assertTrue(componentToDestruct.deconstructed);
    }

    @Ignore  // because logAndDie is impossible(?) to verify programmatically
    @Test
    public void manually_verify_what_happens_when_first_graph_contains_component_that_throws_exception_in_ctor() {
        writeBootstrapConfigs("thrower", ComponentThrowingExceptionInConstructor.class);
        Container container = newContainer(dirConfigSource);
        try {
            getNewComponentGraph(container);
            fail("Expected to log and die.");
        } catch (Throwable t) {
            fail("Expected to log and die");
        }
    }

    @Test
    public void previous_graph_is_retained_when_new_graph_contains_component_that_throws_exception_in_ctor() {
        ComponentEntry simpleComponentEntry = new ComponentEntry("simpleComponent", SimpleComponent.class);

        writeBootstrapConfigs(simpleComponentEntry);
        Container container = newContainer(dirConfigSource);
        ComponentGraph currentGraph = getNewComponentGraph(container);

        SimpleComponent simpleComponent = currentGraph.getInstance(SimpleComponent.class);

        writeBootstrapConfigs("thrower", ComponentThrowingExceptionInConstructor.class);
        container.reloadConfig(2);
        try {
            currentGraph = getNewComponentGraph(container, currentGraph);
            fail("Expected exception");
        } catch (ComponentConstructorException ignored) {
            // Expected, do nothing
        } catch (Throwable t) {
            fail("Expected ComponentConstructorException");
        }
        assertEquals(1, currentGraph.generation());

        // Also verify that next reconfig is successful
        ComponentEntry componentTakingConfigEntry = new ComponentEntry("componentTakingConfig", ComponentTakingConfig.class);
        dirConfigSource.writeConfig("test", "stringVal \"myString\"");
        writeBootstrapConfigs(simpleComponentEntry, componentTakingConfigEntry);
        container.reloadConfig(3);
        currentGraph = getNewComponentGraph(container, currentGraph);

        assertEquals(3, currentGraph.generation());
        assertSame(simpleComponent, currentGraph.getInstance(SimpleComponent.class));
        assertNotNull(currentGraph.getInstance(ComponentTakingConfig.class));
    }

    @Test
    public void previous_graph_is_retained_when_new_graph_throws_exception_for_missing_config() {
        ComponentEntry simpleComponentEntry = new ComponentEntry("simpleComponent", SimpleComponent.class);

        writeBootstrapConfigs(simpleComponentEntry);
        Container container = newContainer(dirConfigSource);
        ComponentGraph currentGraph = getNewComponentGraph(container);

        currentGraph.getInstance(SimpleComponent.class);

        writeBootstrapConfigs("thrower", ComponentThrowingExceptionForMissingConfig.class);
        dirConfigSource.writeConfig("test", "stringVal \"myString\"");
        container.reloadConfig(2);
        try {
            currentGraph = getNewComponentGraph(container, currentGraph);
            fail("Expected exception");
        } catch (IllegalArgumentException ignored) {
            // Expected, do nothing
        } catch (Throwable t) {
            fail("Expected IllegalArgumentException");
        }
        assertEquals(1, currentGraph.generation());
    }

    @Test
    public void getNewComponentGraph_hangs_waiting_for_valid_config_after_invalid_config() throws Exception {
        dirConfigSource.writeConfig("test", "stringVal \"original\"");
        writeBootstrapConfigs("myId", ComponentTakingConfig.class);

        Container container = newContainer(dirConfigSource);
        final ComponentGraph currentGraph = getNewComponentGraph(container);

        writeBootstrapConfigs("thrower", ComponentThrowingExceptionForMissingConfig.class);
        container.reloadConfig(2);

        assertThrows(IllegalArgumentException.class,
                     () -> getNewComponentGraph(container, currentGraph));

        ExecutorService exec = Executors.newFixedThreadPool(1);
        Future<ComponentGraph> newGraph = exec.submit(() -> getNewComponentGraph(container, currentGraph));

        try {
            newGraph.get(1, TimeUnit.SECONDS);
            fail("Expected waiting for new config.");
        } catch (Exception ignored) {
            // expect to time out
        }

        writeBootstrapConfigs("myId2", ComponentTakingConfig.class);
        container.reloadConfig(3);

        assertNotNull(newGraph.get(5, TimeUnit.MINUTES));
    }

    @Test
    public void providers_are_destructed() {
        writeBootstrapConfigs("id1", DestructableProvider.class);

        ComponentDeconstructor deconstructor = (generation, components, bundles) -> {
            components.forEach(component -> {
                if (component instanceof AbstractComponent) {
                    ((AbstractComponent) component).deconstruct();
                } else if (component instanceof Provider) {
                    ((Provider<?>) component).deconstruct();
                }
            });
            if (! bundles.isEmpty()) throw new IllegalArgumentException("This test should not use bundles");
        };

        Container container = newContainer(dirConfigSource, deconstructor);

        ComponentGraph oldGraph = getNewComponentGraph(container);
        DestructableEntity destructableEntity = oldGraph.getInstance(DestructableEntity.class);

        writeBootstrapConfigs("id2", DestructableProvider.class);
        container.reloadConfig(2);
        getNewComponentGraph(container, oldGraph);

        assertTrue(destructableEntity.deconstructed);
    }

    @Test
    public void providers_are_invoked_only_when_needed() {
        writeBootstrapConfigs("id1", FailOnGetProvider.class);

        Container container = newContainer(dirConfigSource);

        ComponentGraph oldGraph = getNewComponentGraph(container);
    }

    static class DestructableEntity {
        private boolean deconstructed = false;
    }

    public static class DestructableProvider implements Provider<DestructableEntity> {
        DestructableEntity instance = new DestructableEntity();

        public DestructableEntity get() {
            return instance;
        }

        public void deconstruct() {
            assertFalse(instance.deconstructed);
            instance.deconstructed = true;
        }
    }

    public static class FailOnGetProvider implements Provider<Integer> {

        public Integer get() {
            fail("Should never be called.");
            return null;
        }

        public void deconstruct() {
        }

    }

    public static class ComponentTakingConfig extends AbstractComponent {
        private final TestConfig config;

        public ComponentTakingConfig(TestConfig config) {
            assertNotNull(config);
            this.config = config;
        }
    }

    public static class ComponentThrowingExceptionInConstructor {
        public ComponentThrowingExceptionInConstructor() {
            throw new RuntimeException("This component fails upon construction.");
        }
    }

    public static class ComponentThrowingExceptionForMissingConfig extends AbstractComponent {
        public ComponentThrowingExceptionForMissingConfig(IntConfig intConfig) {
            fail("This component should never be created. Only used for tests where 'int' config is missing.");
        }
    }

    public static class DestructableComponent extends AbstractComponent {
        private boolean deconstructed = false;

        @Override
        public void deconstruct() {
            deconstructed = true;
        }
    }

    public static class TestDeconstructor implements ComponentDeconstructor {
        @Override
        public void deconstruct(long generation, List<Object> components, Collection<Bundle> bundles) {
            components.forEach(component -> {
                if (component instanceof DestructableComponent) {
                    DestructableComponent vespaComponent = (DestructableComponent) component;
                    vespaComponent.deconstruct();
                }
            });
            if (! bundles.isEmpty()) throw new IllegalArgumentException("This test should not use bundles");
        }
    }

    private static Container newContainer(DirConfigSource dirConfigSource,
                                          ComponentDeconstructor deconstructor) {
        return new Container(new CloudSubscriberFactory(dirConfigSource.configSource), dirConfigSource.configId(), deconstructor);
    }

    private static Container newContainer(DirConfigSource dirConfigSource) {
        return newContainer(dirConfigSource, new TestDeconstructor());
    }

    ComponentGraph getNewComponentGraph(Container container, ComponentGraph oldGraph) {
        Container.ComponentGraphResult result = container.waitForNextGraphGeneration(oldGraph, Guice.createInjector(), true);
        result.oldComponentsCleanupTask().run();
        return result.newGraph();
    }

    ComponentGraph getNewComponentGraph(Container container) {
        return container.waitForNextGraphGeneration(new ComponentGraph(), Guice.createInjector(), true).newGraph();
    }

    private ComponentTakingConfig createComponentTakingConfig(ComponentGraph componentGraph) {
        return componentGraph.getInstance(ComponentTakingConfig.class);
    }

}