summaryrefslogtreecommitdiffstats
path: root/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporterTest.java
blob: 8747dc4eb6fbbe4554cda5f8a224f9e5c8ef2429 (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
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.maintenance;

import com.yahoo.component.Version;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ClusterMembership;
import com.yahoo.config.provision.DockerImage;
import com.yahoo.config.provision.NodeFlavors;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.Zone;
import com.yahoo.jdisc.Metric;
import com.yahoo.test.ManualClock;
import com.yahoo.transaction.Mutex;
import com.yahoo.transaction.NestedTransaction;
import com.yahoo.vespa.applicationmodel.ApplicationInstance;
import com.yahoo.vespa.applicationmodel.ApplicationInstanceReference;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.curator.mock.MockCurator;
import com.yahoo.vespa.curator.stats.LockStats;
import com.yahoo.vespa.flags.InMemoryFlagSource;
import com.yahoo.vespa.hosted.provision.LockedNodeList;
import com.yahoo.vespa.hosted.provision.Node;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.node.Agent;
import com.yahoo.vespa.hosted.provision.node.Allocation;
import com.yahoo.vespa.hosted.provision.node.Generation;
import com.yahoo.vespa.hosted.provision.node.IP;
import com.yahoo.vespa.hosted.provision.provisioning.EmptyProvisionServiceProvider;
import com.yahoo.vespa.hosted.provision.provisioning.FlavorConfigBuilder;
import com.yahoo.vespa.hosted.provision.testutils.MockNameResolver;
import com.yahoo.vespa.orchestrator.Orchestrator;
import com.yahoo.vespa.orchestrator.status.HostInfo;
import com.yahoo.vespa.orchestrator.status.HostStatus;
import com.yahoo.vespa.service.monitor.ServiceModel;
import com.yahoo.vespa.service.monitor.ServiceMonitor;
import org.junit.Before;
import org.junit.Test;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author oyving
 * @author smorgrav
 */
public class MetricsReporterTest {

    private final ServiceMonitor serviceMonitor = mock(ServiceMonitor.class);
    private final ApplicationInstanceReference reference = mock(ApplicationInstanceReference.class);

    @Before
    public void setUp() {
        // On the serviceModel returned by serviceMonitor.getServiceModelSnapshot(),
        // 2 methods should be used by MetricsReporter:
        //  - getServiceInstancesByHostName() -> empty Map
        //  - getApplication() which is mapped to a dummy ApplicationInstanceReference and
        //    used for lookup.
        ServiceModel serviceModel = mock(ServiceModel.class);
        when(serviceMonitor.getServiceModelSnapshot()).thenReturn(serviceModel);
        when(serviceModel.getServiceInstancesByHostName()).thenReturn(Map.of());
        ApplicationInstance applicationInstance = mock(ApplicationInstance.class);
        when(serviceModel.getApplication(any())).thenReturn(Optional.of(applicationInstance));
        when(applicationInstance.reference()).thenReturn(reference);
        LockStats.clearForTesting();
    }

    @Test
    public void test_registered_metric() {
        NodeFlavors nodeFlavors = FlavorConfigBuilder.createDummies("default");
        Curator curator = new MockCurator();
        NodeRepository nodeRepository = new NodeRepository(nodeFlavors,
                                                           new EmptyProvisionServiceProvider().getHostResourcesCalculator(),
                                                           curator,
                                                           Clock.systemUTC(),
                                                           Zone.defaultZone(),
                                                           new MockNameResolver().mockAnyLookup(),
                                                           DockerImage.fromString("docker-registry.domain.tld:8080/dist/vespa"),
                                                           new InMemoryFlagSource(),
                                                           true,
                                                           false,
                                                           0, 1000);
        Node node = nodeRepository.createNode("openStackId", "hostname", Optional.empty(), nodeFlavors.getFlavorOrThrow("default"), NodeType.tenant);
        nodeRepository.addNodes(List.of(node), Agent.system);
        Node hostNode = nodeRepository.createNode("openStackId2", "parent", Optional.empty(), nodeFlavors.getFlavorOrThrow("default"), NodeType.proxy);
        nodeRepository.addNodes(List.of(hostNode), Agent.system);

        Map<String, Number> expectedMetrics = new TreeMap<>();
        expectedMetrics.put("hostedVespa.provisionedHosts", 1);
        expectedMetrics.put("hostedVespa.parkedHosts", 0);
        expectedMetrics.put("hostedVespa.readyHosts", 0);
        expectedMetrics.put("hostedVespa.reservedHosts", 0);
        expectedMetrics.put("hostedVespa.activeHosts", 0);
        expectedMetrics.put("hostedVespa.inactiveHosts", 0);
        expectedMetrics.put("hostedVespa.dirtyHosts", 0);
        expectedMetrics.put("hostedVespa.failedHosts", 0);
        expectedMetrics.put("hostedVespa.deprovisionedHosts", 0);
        expectedMetrics.put("hostedVespa.pendingRedeployments", 42);
        expectedMetrics.put("hostedVespa.docker.totalCapacityDisk", 0.0);
        expectedMetrics.put("hostedVespa.docker.totalCapacityMem", 0.0);
        expectedMetrics.put("hostedVespa.docker.totalCapacityCpu", 0.0);
        expectedMetrics.put("hostedVespa.docker.freeCapacityDisk", 0.0);
        expectedMetrics.put("hostedVespa.docker.freeCapacityMem", 0.0);
        expectedMetrics.put("hostedVespa.docker.freeCapacityCpu", 0.0);

        expectedMetrics.put("wantedRebootGeneration", 0L);
        expectedMetrics.put("currentRebootGeneration", 0L);
        expectedMetrics.put("wantToReboot", 0);
        expectedMetrics.put("wantToRetire", 0);
        expectedMetrics.put("wantToDeprovision", 0);
        expectedMetrics.put("failReport", 0);
        expectedMetrics.put("allowedToBeDown", 1);
        expectedMetrics.put("suspended", 1);
        expectedMetrics.put("suspendedSeconds", 123L);
        expectedMetrics.put("numberOfServices", 0L);

        expectedMetrics.put("cache.nodeObject.hitRate", 0.6D);
        expectedMetrics.put("cache.nodeObject.evictionCount", 0L);
        expectedMetrics.put("cache.nodeObject.size", 2L);

        nodeRepository.list();
        expectedMetrics.put("cache.curator.hitRate", 0.5D);
        expectedMetrics.put("cache.curator.evictionCount", 0L);
        expectedMetrics.put("cache.curator.size", 11L);

        ManualClock clock = new ManualClock(Instant.ofEpochSecond(124));

        Orchestrator orchestrator = mock(Orchestrator.class);
        when(orchestrator.getHostInfo(eq(reference), any())).thenReturn(
                HostInfo.createSuspended(HostStatus.ALLOWED_TO_BE_DOWN, Instant.ofEpochSecond(1)));

        TestMetric metric = new TestMetric();
        MetricsReporter metricsReporter = new MetricsReporter(
                nodeRepository,
                metric,
                orchestrator,
                serviceMonitor,
                () -> 42,
                Duration.ofMinutes(1),
                clock);
        metricsReporter.maintain();

        // Verify sum of values across dimensions, and remove these metrics to avoid checking against
        // metric.values below, which is not sensitive to dimensions.
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.acquire", 3);
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.acquireFailed", 0);
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.acquireTimedOut", 0);
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.locked", 3);
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.release", 3);
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.releaseFailed", 0);
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.reentry", 0);
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.deadlock", 0);
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.nakedRelease", 0);
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.acquireWithoutRelease", 0);
        verifyAndRemoveIntegerMetricSum(metric, "lockAttempt.foreignRelease", 0);
        metric.remove("lockAttempt.acquireLatency");
        metric.remove("lockAttempt.acquireMaxActiveLatency");
        metric.remove("lockAttempt.acquireHz");
        metric.remove("lockAttempt.acquireLoad");
        metric.remove("lockAttempt.lockedLatency");
        metric.remove("lockAttempt.lockedMaxActiveLatency");
        metric.remove("lockAttempt.lockedHz");
        metric.remove("lockAttempt.lockedLoad");

        assertEquals(expectedMetrics, new TreeMap<>(metric.values));
    }

    private void verifyAndRemoveIntegerMetricSum(TestMetric metric, String key, int expected) {
        assertEquals(expected, (int) metric.sumNumberValues(key));
        metric.remove(key);
    }

    @Test
    public void docker_metrics() {
        NodeFlavors nodeFlavors = FlavorConfigBuilder.createDummies("host", "docker", "docker2");
        Curator curator = new MockCurator();
        NodeRepository nodeRepository = new NodeRepository(nodeFlavors,
                                                           new EmptyProvisionServiceProvider().getHostResourcesCalculator(),
                                                           curator,
                                                           Clock.systemUTC(),
                                                           Zone.defaultZone(),
                                                           new MockNameResolver().mockAnyLookup(),
                                                           DockerImage.fromString("docker-registry.domain.tld:8080/dist/vespa"),
                                                           new InMemoryFlagSource(),
                                                           true,
                                                           false,
                                                           0, 1000);

        // Allow 4 containers
        Set<String> ipAddressPool = Set.of("::2", "::3", "::4", "::5");

        Node dockerHost = Node.create("openStackId1", new IP.Config(Set.of("::1"), ipAddressPool), "dockerHost",
                                      Optional.empty(), Optional.empty(), nodeFlavors.getFlavorOrThrow("host"), Optional.empty(), NodeType.host, Optional.empty());
        nodeRepository.addNodes(List.of(dockerHost), Agent.system);
        nodeRepository.dirtyRecursively("dockerHost", Agent.system, getClass().getSimpleName());
        nodeRepository.setReady("dockerHost", Agent.system, getClass().getSimpleName());

        Node container1 = Node.createDockerNode(Set.of("::2"), "container1",
                                                "dockerHost", new NodeResources(1, 3, 2, 1), NodeType.tenant);
        container1 = container1.with(allocation(Optional.of("app1"), container1).get());
        try (Mutex lock = nodeRepository.lockUnallocated()) {
            nodeRepository.addDockerNodes(new LockedNodeList(List.of(container1), lock));
        }

        Node container2 = Node.createDockerNode(Set.of("::3"), "container2",
                                                "dockerHost", new NodeResources(2, 4, 4, 1), NodeType.tenant);
        container2 = container2.with(allocation(Optional.of("app2"), container2).get());
        try (Mutex lock = nodeRepository.lockUnallocated()) {
            nodeRepository.addDockerNodes(new LockedNodeList(List.of(container2), lock));
        }

        NestedTransaction transaction = new NestedTransaction();
        nodeRepository.activate(nodeRepository.getNodes(NodeType.host), transaction);
        transaction.commit();

        Orchestrator orchestrator = mock(Orchestrator.class);
        when(orchestrator.getHostInfo(eq(reference), any())).thenReturn(HostInfo.createNoRemarks());

        TestMetric metric = new TestMetric();
        ManualClock clock = new ManualClock();
        MetricsReporter metricsReporter = new MetricsReporter(
                nodeRepository,
                metric,
                orchestrator,
                serviceMonitor,
                () -> 42,
                Duration.ofMinutes(1),
                clock);
        metricsReporter.maintain();

        assertEquals(0, metric.values.get("hostedVespa.readyHosts")); // Only tenants counts
        assertEquals(2, metric.values.get("hostedVespa.reservedHosts"));

        assertEquals(120.0, metric.values.get("hostedVespa.docker.totalCapacityDisk"));
        assertEquals(100.0, metric.values.get("hostedVespa.docker.totalCapacityMem"));
        assertEquals(  7.0, metric.values.get("hostedVespa.docker.totalCapacityCpu"));

        assertEquals(114.0, metric.values.get("hostedVespa.docker.freeCapacityDisk"));
        assertEquals( 93.0, metric.values.get("hostedVespa.docker.freeCapacityMem"));
        assertEquals(  4.0, metric.values.get("hostedVespa.docker.freeCapacityCpu"));

        Metric.Context app1context = metric.createContext(Map.of("app", "test.default", "tenantName", "app1", "applicationId", "app1.test.default"));
        assertEquals(2.0, metric.sumDoubleValues("hostedVespa.docker.allocatedCapacityDisk", app1context), 0.01d);
        assertEquals(3.0, metric.sumDoubleValues("hostedVespa.docker.allocatedCapacityMem", app1context), 0.01d);
        assertEquals(1.0, metric.sumDoubleValues("hostedVespa.docker.allocatedCapacityCpu", app1context), 0.01d);

        Metric.Context app2context = metric.createContext(Map.of("app", "test.default", "tenantName", "app2", "applicationId", "app2.test.default"));
        assertEquals(4.0, metric.sumDoubleValues("hostedVespa.docker.allocatedCapacityDisk", app2context), 0.01d);
        assertEquals(4.0, metric.sumDoubleValues("hostedVespa.docker.allocatedCapacityMem", app2context), 0.01d);
        assertEquals(2.0, metric.sumDoubleValues("hostedVespa.docker.allocatedCapacityCpu", app2context), 0.01d);
    }

    private ApplicationId app(String tenant) {
        return new ApplicationId.Builder()
                .tenant(tenant)
                .applicationName("test")
                .instanceName("default").build();
    }

    private Optional<Allocation> allocation(Optional<String> tenant, Node owner) {
        if (tenant.isPresent()) {
            Allocation allocation = new Allocation(app(tenant.get()),
                                                   ClusterMembership.from("container/id1/0/3", new Version(), Optional.empty()),
                                                   owner.resources(),
                                                   Generation.initial(),
                                                   false);
            return Optional.of(allocation);
        }
        return Optional.empty();
    }

}