aboutsummaryrefslogtreecommitdiffstats
path: root/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/NodeRepositoryMock.java
blob: 5b70942bfd11d5524ecd46ebb105ec500fa7fdba (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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.integration;

import com.yahoo.collections.Pair;
import com.yahoo.component.Version;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.CloudAccount;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.HostName;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.TenantName;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.integration.archive.ArchiveUriUpdate;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Application;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationStats;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ArchiveUris;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Load;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeFilter;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeRepoStats;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeRepository;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.TargetVersions;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.ApplicationPatch;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;

/**
 * @author mpolden
 * @author jonmv
 */
public class NodeRepositoryMock implements NodeRepository {

    private final Map<ZoneId, Map<HostName, Node>> nodeRepository = new ConcurrentHashMap<>();
    private final Map<ZoneId, Map<ApplicationId, Application>> applications = new ConcurrentHashMap<>();
    private final Map<ZoneId, TargetVersions> targetVersions = new ConcurrentHashMap<>();
    private final Map<DeploymentId, Pair<Double, Double>> trafficFractions = new ConcurrentHashMap<>();
    private final Map<DeploymentClusterId, BcpGroupInfo> bcpGroupInfos = new ConcurrentHashMap<>();
    private final Map<ZoneId, ArchiveUris> archiveUris = new ConcurrentHashMap<>();

    private boolean allowPatching = true;
    private boolean hasSpareCapacity = false;

    @Override
    public void addNodes(ZoneId zone, List<Node> nodes) {
        Map<HostName, Node> existingNodes = nodeRepository.getOrDefault(zone, Map.of());
        for (var node : nodes) {
            if (existingNodes.containsKey(node.hostname())) {
                throw new IllegalArgumentException("Node " + node.hostname() + " already added in zone " + zone);
            }
        }
        putNodes(zone, nodes);
    }

    @Override
    public void deleteNode(ZoneId zone, String hostname) {
        require(zone, hostname);
        nodeRepository.get(zone).remove(HostName.of(hostname));
    }

    @Override
    public void setState(ZoneId zone, Node.State state, String hostname) {
        Node node = Node.builder(require(zone, hostname))
                        .state(Node.State.valueOf(state.name()))
                        .build();
        putNodes(zone, node);
    }

    @Override
    public Node getNode(ZoneId zone, String hostname) {
        return require(zone, hostname);
    }

    @Override
    public List<Node> list(ZoneId zone, NodeFilter filter) {
        return nodeRepository.getOrDefault(zone, Map.of()).values().stream()
                             .filter(node -> filter.includeDeprovisioned() || node.state() != Node.State.deprovisioned)
                             .filter(node -> filter.applications().isEmpty() ||
                                             (node.owner().isPresent() && filter.applications().contains(node.owner().get())))
                             .filter(node -> filter.hostnames().isEmpty() || filter.hostnames().contains(node.hostname()))
                             .filter(node -> filter.states().isEmpty() || filter.states().contains(node.state()))
                             .filter(node -> filter.clusterIds().isEmpty() || filter.clusterIds().contains(ClusterSpec.Id.from(node.clusterId())))
                             .filter(node -> filter.clusterTypes().isEmpty() || filter.clusterTypes().contains(node.clusterType()))
                             .toList();
    }

    @Override
    public Application getApplication(ZoneId zone, ApplicationId applicationId) {
        return applications.get(zone).get(applicationId);
    }

    @Override
    public void patchApplication(ZoneId zone, ApplicationId application, ApplicationPatch applicationPatch) {
        trafficFractions.put(new DeploymentId(application, zone),
                             new Pair<>(applicationPatch.currentReadShare, applicationPatch.maxReadShare));
        if (applicationPatch.clusters != null) {
            for (var cluster : applicationPatch.clusters.entrySet())
                bcpGroupInfos.put(new DeploymentClusterId(new DeploymentId(application, zone), new ClusterSpec.Id(cluster.getKey())),
                                  new BcpGroupInfo(cluster.getValue().bcpGroupInfo.queryRate,
                                                   cluster.getValue().bcpGroupInfo.growthRateHeadroom,
                                                   cluster.getValue().bcpGroupInfo.cpuCostPerQuery));
        }
    }

    @Override
    public NodeRepoStats getStats(ZoneId zone) {
        List<ApplicationStats> applicationStats =
                applications.containsKey(zone)
                        ? applications.get(zone).keySet().stream()
                                      .map(id -> new ApplicationStats(id, Load.zero(), 0, 0))
                                      .toList()
                        : List.of();

        return new NodeRepoStats(0.0, 0.0, Load.zero(), Load.zero(), applicationStats);
    }

    @Override
    public ArchiveUris getArchiveUris(ZoneId zone) {
        return archiveUris.getOrDefault(zone, ArchiveUris.EMPTY);
    }

    @Override
    public void updateArchiveUri(ZoneId zone, ArchiveUriUpdate update) {
        archiveUris.compute(zone, (z, prev) -> {
            prev = prev == null ? ArchiveUris.EMPTY : prev;
            if (update.tenantName().isPresent()) {
                Map<TenantName, URI> updated = new HashMap<>(prev.tenantArchiveUris());
                update.archiveUri().ifPresentOrElse(uri -> updated.put(update.tenantName().get(), uri),
                                                    () -> updated.remove(update.tenantName().get()));
                return new ArchiveUris(updated, prev.accountArchiveUris());
            } else {
                Map<CloudAccount, URI> updated = new HashMap<>(prev.accountArchiveUris());
                update.archiveUri().ifPresentOrElse(uri -> updated.put(update.cloudAccount().get(), uri),
                                                    () -> updated.remove(update.cloudAccount().get()));
                return new ArchiveUris(prev.tenantArchiveUris(), updated);
            }
        });
    }

    @Override
    public void upgrade(ZoneId zone, NodeType type, Version version, boolean allowDowngrade) {
        this.targetVersions.compute(zone, (ignored, targetVersions) -> {
            if (targetVersions == null) {
                targetVersions = TargetVersions.EMPTY;
            }
            Optional<Version> current = targetVersions.vespaVersion(type);
            if (current.isPresent() && version.isBefore(current.get()) && !allowDowngrade) {
                throw new IllegalArgumentException("Changing wanted version for " + type + " in " + zone + " from " +
                                                   current.get() + " to " + version +
                                                   ", but downgrade is not allowed");
            }
            return targetVersions.withVespaVersion(type, version);
        });
        // Bump wanted version of each node. This is done by InfrastructureProvisioner in a real node repository.
        nodeRepository.getOrDefault(zone, Map.of()).values()
                      .stream()
                      .filter(node -> node.type() == type)
                      .map(node -> Node.builder(node).wantedVersion(version).build())
                      .forEach(node -> putNodes(zone, node));
    }

    @Override
    public void upgradeOs(ZoneId zone, NodeType type, Version version, boolean downgrade) {
        this.targetVersions.compute(zone, (ignored, targetVersions) -> {
            if (targetVersions == null) {
                targetVersions = TargetVersions.EMPTY;
            }
            return targetVersions.withOsVersion(type, version);
        });
        // Bump wanted version of each node. This is done by OsUpgradeActivator in a real node repository.
        nodeRepository.getOrDefault(zone, Map.of()).values()
                      .stream()
                      .filter(node -> node.type() == type)
                      .map(node -> Node.builder(node).wantedOsVersion(version).build())
                      .forEach(node -> putNodes(zone, node));
    }

    @Override
    public TargetVersions targetVersionsOf(ZoneId zone) {
        return targetVersions.getOrDefault(zone, TargetVersions.EMPTY);
    }

    @Override
    public void requestFirmwareCheck(ZoneId zone) {
    }

    @Override
    public void cancelFirmwareCheck(ZoneId zone) {
    }

    @Override
    public void retire(ZoneId zone, String hostname, boolean wantToRetire, boolean wantToDeprovision) {
        patchNodes(zone, hostname, (node) -> Node.builder(node).wantToRetire(wantToRetire).wantToDeprovision(wantToDeprovision).build());
    }

    @Override
    public void dropDocuments(ZoneId zoneId, ApplicationId applicationId, Optional<ClusterSpec.Id> clusterId) {
    }

    @Override
    public void updateReports(ZoneId zone, String hostname, Map<String, String> reports) {
        Map<String, String> trimmedReports = reports.entrySet().stream()
                                                    // Null value clears a report
                                                    .filter(kv -> kv.getValue() != null)
                                                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        patchNodes(zone, hostname, (node) -> Node.builder(node).reports(trimmedReports).build());
    }

    @Override
    public void updateModel(ZoneId zone, String hostname, String modelName) {
        patchNodes(zone, hostname, (node) -> Node.builder(node).modelName(modelName).build());
    }

    @Override
    public void updateSwitchHostname(ZoneId zone, String hostname, String switchHostname) {
        patchNodes(zone, hostname, (node) -> Node.builder(node).switchHostname(switchHostname).build());
    }

    @Override
    public void reboot(ZoneId zone, String hostname) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isReplaceable(ZoneId zone, List<HostName> hostnames) {
        return hasSpareCapacity;
    }

    /** Add or update given nodes in zone */
    public void putNodes(ZoneId zone, List<Node> nodes) {
        Map<HostName, Node> zoneNodes = nodeRepository.computeIfAbsent(zone, (k) -> new ConcurrentHashMap<>());
        for (var node : nodes) {
            zoneNodes.put(node.hostname(), node);
        }
    }

    /** Add or update given node in zone */
    public void putNodes(ZoneId zone, Node node) {
        putNodes(zone, List.of(node));
    }

    public void putApplication(ZoneId zone, Application application) {
        applications.computeIfAbsent(zone, (k) -> new TreeMap<>())
                    .put(application.id(), application);
    }

    public Pair<Double, Double> getTrafficFraction(ApplicationId application, ZoneId zone) {
        return trafficFractions.get(new DeploymentId(application, zone));
    }

    public BcpGroupInfo getBcpGroupInfo(ApplicationId application, ZoneId zone, ClusterSpec.Id cluster) {
        return bcpGroupInfos.get(new DeploymentClusterId(new DeploymentId(application, zone), cluster));
    }

    /** Remove given nodes from zone */
    public void removeNodes(ZoneId zone, List<Node> nodes) {
        nodes.forEach(node -> nodeRepository.get(zone).remove(node.hostname()));
    }

    /** Remove all nodes in all zones */
    public void clear() {
        nodeRepository.clear();
    }

    /** Add a fixed set of nodes to given zone */
    public void addFixedNodes(ZoneId zone) {
        var nodeA = Node.builder()
                        .hostname(HostName.of("hostA"))
                        .parentHostname(HostName.of("parentHostA"))
                        .state(Node.State.active)
                        .type(NodeType.tenant)
                        .owner(ApplicationId.from("tenant1", "app1", "default"))
                        .currentVersion(Version.fromString("7.42"))
                        .wantedVersion(Version.fromString("7.42"))
                        .currentOsVersion(Version.fromString("7.6"))
                        .wantedOsVersion(Version.fromString("7.6"))
                        .serviceState(Node.ServiceState.expectedUp)
                        .resources(new NodeResources(24, 24, 500, 1))
                        .clusterId("clusterA")
                        .clusterType(Node.ClusterType.container)
                        .exclusiveTo(ApplicationId.from("t1", "a1", "i1"))
                        .build();
        var nodeB = Node.builder()
                        .hostname(HostName.of("hostB"))
                        .parentHostname(HostName.of("parentHostB"))
                        .state(Node.State.active)
                        .type(NodeType.tenant)
                        .owner(ApplicationId.from("tenant2", "app2", "default"))
                        .currentVersion(Version.fromString("7.42"))
                        .wantedVersion(Version.fromString("7.42"))
                        .currentOsVersion(Version.fromString("7.6"))
                        .wantedOsVersion(Version.fromString("7.6"))
                        .serviceState(Node.ServiceState.expectedUp)
                        .resources(new NodeResources(40, 24, 500, 1))
                        .cost(20)
                        .clusterId("clusterB")
                        .clusterType(Node.ClusterType.container)
                        .build();
        putNodes(zone, List.of(nodeA, nodeB));
    }

    public void doUpgrade(DeploymentId deployment, Optional<HostName> hostName, Version version) {
        patchNodes(deployment, hostName, node -> {
            return Node.builder(node)
                       .currentVersion(version)
                       .currentDockerImage(node.wantedDockerImage())
                       .build();
        });
    }

    public void requestRestart(DeploymentId deployment, Optional<HostName> hostname) {
        patchNodes(deployment, hostname, node -> Node.builder(node).wantedRestartGeneration(node.wantedRestartGeneration() + 1).build());
    }

    public void doRestart(DeploymentId deployment, Optional<HostName> hostname) {
        patchNodes(deployment, hostname, node -> Node.builder(node).restartGeneration(node.restartGeneration() + 1).build());
    }

    public void requestReboot(DeploymentId deployment, Optional<HostName> hostname) {
        patchNodes(deployment, hostname, node -> Node.builder(node).wantedRebootGeneration(node.wantedRebootGeneration() + 1).build());
    }

    public void doReboot(DeploymentId deployment, Optional<HostName> hostname) {
        patchNodes(deployment, hostname, node -> Node.builder(node).rebootGeneration(node.rebootGeneration() + 1).build());
    }

    public NodeRepositoryMock allowPatching(boolean allowPatching) {
        this.allowPatching = allowPatching;
        return this;
    }

    public void hasSpareCapacity(boolean hasSpareCapacity) {
        this.hasSpareCapacity = hasSpareCapacity;
    }

    private Node require(ZoneId zone, String hostname) {
        return require(zone, HostName.of(hostname));
    }

    private Node require(ZoneId zone, HostName hostname) {
        Node node = nodeRepository.getOrDefault(zone, Map.of()).get(hostname);
        if (node == null) throw new IllegalArgumentException("Node not found in " + zone + ": " + hostname);
        return node;
    }

    private void patchNodes(ZoneId zone, String hostname, UnaryOperator<Node> patcher) {
        patchNodes(zone, Optional.of(HostName.of(hostname)), patcher);
    }

    private void patchNodes(DeploymentId deployment, Optional<HostName> hostname, UnaryOperator<Node> patcher) {
        patchNodes(deployment.zoneId(), hostname, patcher);
    }

    private void patchNodes(ZoneId zone, Optional<HostName> hostname, UnaryOperator<Node> patcher) {
        if (!allowPatching) throw new UnsupportedOperationException("Patching is disabled in this mock");
        List<Node> nodes;
        if (hostname.isPresent()) {
            nodes = List.of(require(zone, hostname.get()));
        } else {
            nodes = list(zone, NodeFilter.all());
        }
        putNodes(zone, nodes.stream().map(patcher).toList());
    }

    public record DeploymentClusterId(DeploymentId deploymentId, ClusterSpec.Id clusterId) {}

    public record BcpGroupInfo(double queryRate, double growthRateHeadroom, double cpuCostPerQuery) {}

}