aboutsummaryrefslogtreecommitdiffstats
path: root/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/ConfigServerMock.java
blob: 0e5308fcef56f40c6ad613c3a1eec0aedca1c5a5 (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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
// 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 ai.vespa.http.DomainName;
import ai.vespa.http.HttpURL.Path;
import ai.vespa.http.HttpURL.Query;
import com.yahoo.component.AbstractComponent;
import com.yahoo.component.Version;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.CloudAccount;
import com.yahoo.config.provision.ClusterResources;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.DockerImage;
import com.yahoo.config.provision.EndpointsChecker.Availability;
import com.yahoo.config.provision.EndpointsChecker.Endpoint;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.HostName;
import com.yahoo.config.provision.IntRange;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.ZoneEndpoint.AllowedUrn;
import com.yahoo.config.provision.ZoneEndpoint.AccessType;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.ClusterMetrics;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.DeploymentData;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.EndpointStatus;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.SearchNodeMetrics;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.integration.LogEntry;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing.Status;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Cluster;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ConfigServer;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ContainerEndpoint;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.DeploymentResult;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Load;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.LoadBalancer;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.LoadBalancer.PrivateServiceInfo;
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.ProxyResponse;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.QuotaUsage;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ServiceConvergence;
import com.yahoo.vespa.hosted.controller.api.integration.dataplanetoken.FingerPrint;
import com.yahoo.vespa.hosted.controller.api.integration.dataplanetoken.TokenId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.TestReport;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.TesterCloud;
import com.yahoo.vespa.hosted.controller.api.integration.dns.NameService;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.RestartFilter;
import com.yahoo.vespa.hosted.controller.api.integration.secrets.TenantSecretStore;
import com.yahoo.vespa.hosted.controller.api.integration.stubs.MockTesterCloud;
import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.URI;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.yahoo.config.provision.NodeResources.DiskSpeed.slow;
import static com.yahoo.config.provision.NodeResources.StorageType.remote;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * @author mortent
 * @author jonmv
 */
public class ConfigServerMock extends AbstractComponent implements ConfigServer {

    private final MockTesterCloud mockTesterCloud;
    private final Map<DeploymentId, Application> applications = new LinkedHashMap<>();
    private final Set<ZoneId> inactiveZones = new HashSet<>();
    private final Map<DeploymentId, EndpointStatus> endpoints = new HashMap<>();
    private final NodeRepositoryMock nodeRepository = new NodeRepositoryMock();
    private final Map<DeploymentId, ServiceConvergence> serviceStatus = new HashMap<>();
    private final Set<ApplicationId> disallowConvergenceCheckApplications = new HashSet<>();
    private final Version initialVersion = new Version(6, 1, 0);
    private final DockerImage initialDockerImage = DockerImage.fromString("registry.example.com/vespa/vespa:6.1.0");
    private final Set<DeploymentId> suspendedApplications = new HashSet<>();
    private final Map<ZoneId, Set<LoadBalancer>> loadBalancers = new HashMap<>();
    private final Set<Environment> deferLoadBalancerProvisioning = new HashSet<>();
    private final Map<DeploymentId, List<DeploymentResult.LogEntry>> warnings = new HashMap<>();
    private final Map<DeploymentId, Set<ContainerEndpoint>> containerEndpoints = new HashMap<>();
    private final Map<DeploymentId, List<ClusterMetrics>> clusterMetrics = new HashMap<>();
    private final Map<DeploymentId, TestReport> testReport = new HashMap<>();
    private final Map<DeploymentId, CloudAccount> cloudAccounts = new HashMap<>();
    private final Map<DeploymentId, List<X509Certificate>> additionalCertificates = new HashMap<>();
    private final Map<HostName, Map<TokenId, List<FingerPrint>>> activeTokenFingerprints = new HashMap<>();
    private List<SearchNodeMetrics> searchNodeMetrics;

    private Version lastPrepareVersion = null;
    private Consumer<ApplicationId> prepareException = null;
    private Supplier<String> log = () -> "INFO - All good";

    public ConfigServerMock(ZoneRegistryMock zoneRegistry, NameService nameService) {
        bootstrap(zoneRegistry.zones().all().ids(), SystemApplication.notController());
        this.mockTesterCloud = new MockTesterCloud(nameService);
    }

    /** Assigns a reserved tenant node to the given deployment, with initial versions. */
    public void provision(ZoneId zone, ApplicationId application, ClusterSpec.Id clusterId) {
        var current = new ClusterResources(2, 1, new NodeResources(2,  8, 50, 1, slow, remote));
        Cluster cluster = new Cluster(clusterId,
                                      ClusterSpec.Type.container,
                                      new ClusterResources(2, 1, new NodeResources(1,  4, 20, 1, slow, remote)),
                                      new ClusterResources(2, 1, new NodeResources(4, 16, 90, 1, slow, remote)),
                                      IntRange.to(3),
                                      current,
                                      new Cluster.Autoscaling("ideal",
                                                              "Cluster is ideally scaled",
                                                              Optional.of(new ClusterResources(2, 1, new NodeResources(3, 8, 50, 1, slow, remote))),
                                                              Instant.ofEpochMilli(123),
                                                              new Load(0.35, 0.65, 1.0),
                                                              new Load(0.2,  0.5,  0.8),
                                                              new Cluster.Autoscaling.Metrics(0.1, 0.2, 0.3)),
                                      Cluster.Autoscaling.empty(),
                                      List.of(new Cluster.ScalingEvent(new ClusterResources(0, 0, NodeResources.unspecified()),
                                                                       current,
                                                                       Instant.ofEpochMilli(1234),
                                                                       Optional.of(Instant.ofEpochMilli(2234)))),
                                      Duration.ofMinutes(6));
        nodeRepository.putApplication(zone,
                                      new com.yahoo.vespa.hosted.controller.api.integration.configserver.Application(application,
                                                                                                                     List.of(cluster)));

        Node parent = nodeRepository().list(zone, NodeFilter.all().applications(SystemApplication.tenantHost.id())).stream().findAny()
                                      .orElseThrow(() -> new IllegalStateException("No parent hosts in " + zone));
        nodeRepository().putNodes(zone, Node.builder().hostname(hostFor(application, zone))
                                            .state(Node.State.reserved)
                                            .type(NodeType.tenant)
                                            .owner(application)
                                            .parentHostname(parent.hostname())
                                            .currentVersion(initialVersion)
                                            .wantedVersion(initialVersion)
                                            .currentDockerImage(initialDockerImage)
                                            .wantedDockerImage(initialDockerImage)
                                            .currentOsVersion(Version.emptyVersion)
                                            .wantedOsVersion(Version.emptyVersion)
                                            .resources(new NodeResources(2, 8, 50, 1, slow, remote))
                                            .serviceState(Node.ServiceState.unorchestrated)
                                            .flavor("d-2-8-50")
                                            .clusterId(clusterId.value())
                                            .clusterType(Node.ClusterType.container)
                                            .build());
    }

    public HostName hostFor(ApplicationId application, ZoneId zone) {
        return HostName.of("host-" + application.toFullString() + "-" + zone.value());
    }

    public void bootstrap(List<ZoneId> zones, SystemApplication... applications) {
        bootstrap(zones, List.of(applications));
    }

    public void bootstrap(List<ZoneId> zones, List<SystemApplication> applications) {
        nodeRepository().clear();
        addNodes(zones, applications);
    }

    public void addNodes(List<ZoneId> zones, List<SystemApplication> applications) {
        for (ZoneId zone : zones) {
            for (SystemApplication application : applications) {
                for (int i = 1; i <= 3; i++) {
                    Node node = Node.builder()
                                    .hostname(HostName.of("node-" + i + "-" + application.id().application()
                                                                                         .value() + "-" + zone.value()))
                                    .state(Node.State.active)
                                    .type(application.nodeType())
                                    .owner(application.id())
                                    .currentVersion(initialVersion).wantedVersion(initialVersion)
                                    .currentOsVersion(Version.emptyVersion).wantedOsVersion(Version.emptyVersion)
                                    .build();
                    nodeRepository().putNodes(zone, node);
                }
                convergeServices(application.id(), zone);
            }
        }
    }

    /** Converge all services belonging to the given application */
    public void convergeServices(ApplicationId application, ZoneId zone) {
        List<Node> nodes = nodeRepository.list(zone, NodeFilter.all().applications(application));
        serviceStatus.put(new DeploymentId(application, zone), new ServiceConvergence(application,
                                                                                      zone,
                                                                                      true,
                                                                                      2,
                                                                                      nodes.stream()
                                                                                           .map(node -> new ServiceConvergence.Status(node.hostname(),
                                                                                                                                      43,
                                                                                                                                      "container",
                                                                                                                                      2))
                                                                                           .toList()));
    }

    /** The version given in the previous prepare call, or empty if no call has been made */
    public Optional<Version> lastPrepareVersion() {
        return Optional.ofNullable(lastPrepareVersion);
    }

    /** Sets a function that may throw, determined by app id. */
    public void throwOnPrepare(Consumer<ApplicationId> prepareThrower) {
        this.prepareException = prepareThrower;
    }

    /** The exception to throw on the next prepare run, or null to continue normally */
    public void throwOnNextPrepare(RuntimeException prepareException) {
        this.prepareException = prepareException == null ? null : id -> { this.prepareException = null; throw prepareException; };
    }

    /** Set version for an application in a given zone */
    public void setVersion(Version version, ApplicationId application, ZoneId zone) {
        setVersion(zone, nodeRepository.list(zone, NodeFilter.all().applications(application)), version, false);
    }

    /** Set version for nodeCount number of nodes in application in a given zone */
    public void setVersion(Version version, List<Node> nodes, ZoneId zone) {
        setVersion(zone, nodes, version, false);
    }

    /** Set OS version for an application in a given zone */
    public void setOsVersion(Version version, ApplicationId application, ZoneId zone) {
        setVersion(zone, nodeRepository.list(zone, NodeFilter.all().applications(application)), version, true);
    }

    /** Set OS version for an application in a given zone */
    public void setOsVersion(Version version, List<Node> nodes, ZoneId zone) {
        setVersion(zone, nodes, version, true);
    }

    private void setVersion(ZoneId zone, List<Node> nodes, Version version, boolean osVersion) {
        for (var node : nodes) {
            Node newNode;
            if (osVersion) {
                newNode = Node.builder(node).currentOsVersion(version).wantedOsVersion(version).build();
            } else {
                newNode = Node.builder(node).currentVersion(version).wantedVersion(version).build();
            }
            nodeRepository().putNodes(zone, newNode);
        }
    }

    /** The initial version of this config server */
    public Version initialVersion() {
        return initialVersion;
    }

    /** Get deployed application by ID */
    public Optional<Application> application(ApplicationId id, ZoneId zone) {
        return Optional.ofNullable(applications.get(new DeploymentId(id, zone)));
    }

    @Override
    public void setSuspension(DeploymentId deployment, boolean suspend) {
        if (suspend)
            suspendedApplications.add(deployment);
        else
            suspendedApplications.remove(deployment);
    }

    public void generateWarnings(DeploymentId deployment, int count) {
        warnings.put(deployment,
                     IntStream.rangeClosed(1, count)
                              .mapToObj(i -> new DeploymentResult.LogEntry(Instant.now().toEpochMilli(),
                                                                           "log message " + i + " generated by unit test",
                                                                           Level.WARNING,
                                                                           false))
                              .toList());
    }

    public Map<DeploymentId, Set<ContainerEndpoint>> containerEndpoints() {
        return Collections.unmodifiableMap(containerEndpoints);
    }

    public Optional<CloudAccount> cloudAccount(DeploymentId deployment) {
        return Optional.ofNullable(cloudAccounts.get(deployment));
    }

    public Set<String> containerEndpointNames(DeploymentId deployment) {
        return containerEndpoints.getOrDefault(deployment, Set.of()).stream()
                                 .map(ContainerEndpoint::names)
                                 .flatMap(Collection::stream)
                                 .collect(Collectors.toUnmodifiableSet());
    }

    public void setMetrics(DeploymentId deployment, ClusterMetrics clusterMetrics) {
        setMetrics(deployment, List.of(clusterMetrics));
    }

    public void setMetrics(DeploymentId deployment, List<ClusterMetrics> clusterMetrics) {
        this.clusterMetrics.put(deployment, clusterMetrics);
    }

    public void setProtonMetrics(List<SearchNodeMetrics> searchnodeMetrics) {
        this.searchNodeMetrics = searchnodeMetrics;
    }

    public void deferLoadBalancerProvisioningIn(Set<Environment> environments) {
        deferLoadBalancerProvisioning.addAll(environments);
    }

    public List<X509Certificate> additionalCertificates(DeploymentId deployment) {
        return additionalCertificates.getOrDefault(deployment, List.of());
    }

    public void setActiveTokenFingerprints(HostName hostname, Map<TokenId, List<FingerPrint>> tokens) {
        activeTokenFingerprints.put(hostname, tokens);
    }

    @Override
    public NodeRepositoryMock nodeRepository() {
        return nodeRepository;
    }

    @Override
    public Optional<ServiceConvergence> serviceConvergence(DeploymentId deployment, Optional<Version> version) {
        if (disallowConvergenceCheckApplications.contains(deployment.applicationId()))
            throw new IllegalStateException(deployment.applicationId() + " should not ask for service convergence");

        return Optional.ofNullable(serviceStatus.get(deployment));
    }

    public void disallowConvergenceCheck(ApplicationId applicationId) {
        disallowConvergenceCheckApplications.add(applicationId);
    }

    private Set<LoadBalancer> getLoadBalancers(ZoneId zone) {
        return loadBalancers.getOrDefault(zone, new LinkedHashSet<>());
    }

    @Override
    public List<LoadBalancer> getLoadBalancers(ApplicationId application, ZoneId zone) {
        return getLoadBalancers(zone).stream()
                                     .filter(lb -> lb.application().equals(application))
                                     .toList();
    }

    @Override
    public List<FlagData> listFlagData(ZoneId zone) {
        return List.of();
    }

    @Override
    public TesterCloud.Status getTesterStatus(DeploymentId deployment) {
        return TesterCloud.Status.SUCCESS;
    }

    @Override
    public String startTests(DeploymentId deployment, TesterCloud.Suite suite, byte[] config) {
        return "Tests started";
    }

    @Override
    public List<LogEntry> getTesterLog(DeploymentId deployment, long after) {
        return List.of();
    }

    @Override
    public boolean isTesterReady(DeploymentId deployment) {
        return false;
    }

    @Override
    public Optional<TestReport> getTestReport(DeploymentId deployment) {
        return Optional.ofNullable(testReport.get(deployment));
    }

    @Override
    public Availability verifyEndpoints(DeploymentId deploymentId, List<Endpoint> zoneEndpoints) {
        return mockTesterCloud.verifyEndpoints(deploymentId, zoneEndpoints); // Wraps the same name service mock, which is updated by test harness.
    }

    /** Add any of given loadBalancers that do not already exist to the load balancers in zone */
    public void putLoadBalancers(ZoneId zone, List<LoadBalancer> loadBalancers) {
        this.loadBalancers.computeIfAbsent(zone, __ -> new LinkedHashSet<>()).addAll(loadBalancers);
    }

    public void removeLoadBalancers(ApplicationId application, ZoneId zone) {
        getLoadBalancers(zone).removeIf(lb -> lb.application().equals(application));
    }

    @Override
    public PreparedApplication deploy(DeploymentData deployment) {
        byte[] appPackage;
        try (InputStream in = deployment.applicationPackage()) {
            appPackage = in.readAllBytes();
        }
        catch (IOException e) {
            throw new UncheckedIOException(e);
        }
        deployment.cloudAccount(); // Supplier with side effects >_<
        lastPrepareVersion = deployment.platform();
        if (prepareException != null)
            prepareException.accept(ApplicationId.from(deployment.instance().tenant(),
                                                       deployment.instance().application(),
                                                       deployment.instance().instance()));
        DeploymentId id = new DeploymentId(deployment.instance(), deployment.zone());

        applications.put(id, new Application(id.applicationId(), lastPrepareVersion, appPackage));
        ClusterSpec.Id cluster = ClusterSpec.Id.from("default");
        deployment.endpoints(); // Supplier with side effects >_<

        if (nodeRepository().list(id.zoneId(), NodeFilter.all().applications(id.applicationId())).isEmpty())
            provision(id.zoneId(), id.applicationId(), cluster);

        this.containerEndpoints.put(id, deployment.endpoints().get().endpoints());
        deployment.cloudAccount().ifPresent(account -> this.cloudAccounts.put(id, account));

        if (!deferLoadBalancerProvisioning.contains(id.zoneId().environment())) {
            putLoadBalancers(id.zoneId(), List.of(new LoadBalancer(id.dottedString() + "." + cluster,
                                                                   id.applicationId(),
                                                                   cluster,
                                                                   Optional.of(HostName.of("lb-0--" + id.applicationId().toFullString() + "--" + id.zoneId().toString())),
                                                                   Optional.empty(),
                                                                   LoadBalancer.State.active,
                                                                   Optional.of("dns-zone-1"),
                                                                   Optional.empty(),
                                                                   Optional.of(new PrivateServiceInfo("service", List.of(new AllowedUrn(AccessType.awsPrivateLink, "arne")))),
                                                                   true)));
        }

        Application application = applications.get(id);
        application.activate();
        List<Node> nodes = nodeRepository.list(id.zoneId(), NodeFilter.all().applications(id.applicationId()));
        for (Node node : nodes) {
            nodeRepository.putNodes(id.zoneId(), Node.builder(node)
                                                     .state(Node.State.active)
                                                     .wantedVersion(application.version().get())
                                                     .build());
        }
        serviceStatus.put(id, new ServiceConvergence(id.applicationId(),
                                                     id.zoneId(),
                                                     false,
                                                     2,
                                                     nodes.stream()
                                                          .map(node -> new ServiceConvergence.Status(node.hostname(),
                                                                                                     43,
                                                                                                     "container",
                                                                                                     1))
                                                          .toList()));

        additionalCertificates.put(id, deployment.operatorCertificates());
        DeploymentResult result = new DeploymentResult("foo", warnings.getOrDefault(id, List.of()));
        return () -> result;
    }

    @Override
    public void reindex(DeploymentId deployment, List<String> clusterNames, List<String> documentTypes, boolean indexedOnly, Double speed, String cause) { }

    @Override
    public ApplicationReindexing getReindexing(DeploymentId deployment) {
        return new ApplicationReindexing(true,
                                         Map.of("cluster",
                                                new ApplicationReindexing.Cluster(Map.of("type", 100L),
                                                                                  Map.of("type", new Status(Instant.ofEpochMilli(345),
                                                                                                            Instant.ofEpochMilli(456),
                                                                                                            Instant.ofEpochMilli(567),
                                                                                                            ApplicationReindexing.State.FAILED,
                                                                                                            "(#`д´)ノ",
                                                                                                            0.1,
                                                                                                            1.0,
                                                                                                            "test reindexing")))));
    }

    @Override
    public void disableReindexing(DeploymentId deployment) { }

    @Override
    public void enableReindexing(DeploymentId deployment) { }

    @Override
    public boolean isSuspended(DeploymentId deployment) {
        return suspendedApplications.contains(deployment);
    }

    @Override
    public void restart(DeploymentId deployment, RestartFilter restartFilter) {
        nodeRepository().requestRestart(deployment, restartFilter.getHostName());
    }

    @Override
    public void deactivate(DeploymentId deployment) {
        ApplicationId applicationId = deployment.applicationId();
        nodeRepository().removeNodes(deployment.zoneId(),
                                     nodeRepository().list(deployment.zoneId(), NodeFilter.all().applications(applicationId)));
        if ( ! applications.containsKey(deployment))
            return;

        applications.remove(deployment);
        serviceStatus.remove(deployment);

        // This simulates what a real config server does: It deactivates the LB. Actual removal happens in the background
        loadBalancers.computeIfPresent(deployment.zoneId(), (k, old) ->
                old.stream().map(lb -> lb.application().equals(deployment.applicationId())
                           ? new LoadBalancer(lb.id(), lb.application(), lb.cluster(), lb.hostname(), lb.ipAddress(),
                                              LoadBalancer.State.inactive, lb.dnsZone(), lb.cloudAccount(),
                                              lb.service(), lb.isPublic())
                           : lb)
                   .collect(Collectors.toCollection(LinkedHashSet::new)));
    }

    @Override
    public List<ClusterMetrics> getDeploymentMetrics(DeploymentId deployment) {
        return Collections.unmodifiableList(clusterMetrics.getOrDefault(deployment, List.of()));
    }

    @Override
    public List<SearchNodeMetrics> getSearchNodeMetrics(DeploymentId deployment) {
        return this.searchNodeMetrics;
    }

    @Override
    public ProxyResponse getServiceNodePage(DeploymentId deployment, String serviceName, DomainName node, Path subPath, Query query) {
        return new ProxyResponse((subPath + " and " + query).getBytes(UTF_8), "text/html", 200);
    }

    @Override
    public ProxyResponse getServiceNodes(DeploymentId deployment) {
        return new ProxyResponse("{\"json\":\"thank you very much\"}".getBytes(UTF_8), "application.json", 200);
    }

    @Override
    public void setGlobalRotationStatus(DeploymentId deployment, List<String> upstreamNames, EndpointStatus status) {
        endpoints.put(deployment, status);
    }

    @Override
    public void setGlobalRotationStatus(ZoneId zone, boolean in) {
        if (in) {
            inactiveZones.remove(zone);
        } else {
            inactiveZones.add(zone);
        }
    }

    @Override
    public EndpointStatus getGlobalRotationStatus(DeploymentId deployment, String upstreamName) {
        EndpointStatus status = new EndpointStatus(EndpointStatus.Status.in, "", Instant.ofEpochSecond(1497618757L));
        return endpoints.getOrDefault(deployment, status);
    }

    @Override
    public boolean getGlobalRotationStatus(ZoneId zone) {
        return !inactiveZones.contains(zone);
    }

    @Override
    public InputStream getLogs(DeploymentId deployment, Map<String, String> queryParameters) {
        return new ByteArrayInputStream(log.get().getBytes(UTF_8));
    }

    @Override
    public ProxyResponse getApplicationPackageContent(DeploymentId deployment, Path path, URI requestUri) {
        return new ProxyResponse(("{\"path\":\"/" + String.join("/", path.segments()) + "\"}").getBytes(UTF_8), "application/json", 200);
    }

    public void setLogStream(Supplier<String> log) {
        this.log = log;
    }

    @Override
    public List<String> getContentClusters(DeploymentId deployment) {
        return Collections.singletonList("music");
    }

    @Override
    public QuotaUsage getQuotaUsage(DeploymentId deploymentId) {
        return new QuotaUsage(42);
    }

    @Override
    public String validateSecretStore(DeploymentId deployment, TenantSecretStore tenantSecretStore, String region, String parameterName) {
        return "{\"settings\":{\"name\":\"foo\",\"role\":\"vespa-secretstore-access\",\"awsId\":\"892075328880\",\"externalId\":\"*****\",\"region\":\"us-east-1\"},\"status\":\"ok\"}";
    }

    @Override
    public Map<HostName, Map<TokenId, List<FingerPrint>>> activeTokenFingerprints(DeploymentId deploymentId) {
        return activeTokenFingerprints;
    }

    public static class Application {

        private final ApplicationId id;
        private final Version version;
        private boolean activated;
        private final byte[] applicationPackage;

        private Application(ApplicationId id, Version version, byte[] applicationPackage) {
            this.id = id;
            this.version = version;
            this.applicationPackage = applicationPackage;
        }

        public ApplicationId id() {
            return id;
        }

        public Optional<Version> version() {
            return Optional.ofNullable(version);
        }

        public boolean activated() {
            return activated;
        }

        public ApplicationPackage applicationPackage() {
            return new ApplicationPackage(applicationPackage);
        }

        private void activate() {
            this.activated = true;
        }

    }

}