aboutsummaryrefslogtreecommitdiffstats
path: root/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java
blob: d669961e728d749fe7ec10359cc010dcb407bf1b (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;

import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.test.TestDriver;
import com.yahoo.test.ManualClock;
import org.junit.jupiter.api.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;

/**
 * @author bjorncs
 */
public class ContainerWatchdogTest {

    @Test
    void watchdog_counts_stale_container() {
        TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
        ManualClock clock = new ManualClock(Instant.EPOCH);
        DummyMetric metric = new DummyMetric();
        ContainerWatchdog watchdog = new ContainerWatchdog(mock(ScheduledExecutorService.class), clock);

        ActiveContainer containerWithoutRetainedResources = new ActiveContainer(driver.newContainerBuilder());

        watchdog.onContainerActivation(containerWithoutRetainedResources);
        assertEquals(0, runMonitorStepAndGetStaleContainerCount(watchdog, metric));

        clock.advance(Duration.ofHours(1));
        watchdog.onContainerActivation(null);
        assertEquals(0, runMonitorStepAndGetStaleContainerCount(watchdog, metric));

        clock.advance(ContainerWatchdog.GRACE_PERIOD);
        assertEquals(0, runMonitorStepAndGetStaleContainerCount(watchdog, metric));

        clock.advance(Duration.ofSeconds(1));
        assertEquals(1, runMonitorStepAndGetStaleContainerCount(watchdog, metric));

        containerWithoutRetainedResources.release();
        assertEquals(0, runMonitorStepAndGetStaleContainerCount(watchdog, metric));
    }

    private static int runMonitorStepAndGetStaleContainerCount(ContainerWatchdog watchdog, DummyMetric metric) {
        watchdog.monitorDeactivatedContainers();
        watchdog.emitMetrics(metric);
        return metric.value;
    }

    private static class DummyMetric implements Metric {
        int value;

        @Override
        public void set(String key, Number val, Context ctx) {
            this.value = val.intValue();
        }

        @Override
        public void add(String key, Number val, Context ctx) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Context createContext(Map<String, ?> properties) {
            throw new UnsupportedOperationException();
        }
    }
}