aboutsummaryrefslogtreecommitdiffstats
path: root/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/resource/ResourceDatabaseClientMock.java
blob: 81dfdf4656c0531bd326d6db553fff2e20ece743 (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.resource;

import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.TenantName;
import com.yahoo.vespa.hosted.controller.api.identifiers.ClusterId;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.integration.billing.Plan;
import com.yahoo.vespa.hosted.controller.api.integration.billing.PlanRegistry;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Cluster;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author olaa
 */
public class ResourceDatabaseClientMock implements ResourceDatabaseClient {

    PlanRegistry planRegistry;
    Map<TenantName, Plan> planMap = new HashMap<>();
    List<ResourceSnapshot> resourceSnapshots = new ArrayList<>();
    Map<ClusterId, List<Cluster.ScalingEvent>> scalingEvents = new HashMap<>();
    private boolean hasRefreshedMaterializedView = false;

    public ResourceDatabaseClientMock(PlanRegistry planRegistry) {
        this.planRegistry = planRegistry;
    }

    @Override
    public void writeResourceSnapshots(Collection<ResourceSnapshot> items) {
        this.resourceSnapshots.addAll(items);
    }

    @Override
    public Set<YearMonth> getMonthsWithSnapshotsForTenant(TenantName tenantName) {
        return Collections.emptySet();
    }

    @Override
    public List<ResourceSnapshot> getRawSnapshotHistoryForTenant(TenantName tenantName, YearMonth yearMonth) {
        return resourceSnapshots;
    }

    @Override
    public Set<TenantName> getTenants() {
        return resourceSnapshots.stream()
                .map(snapshot -> snapshot.getApplicationId().tenant())
                .collect(Collectors.toSet());
    }

    private List<ResourceUsage> resourceUsageFromSnapshots(Plan plan, List<ResourceSnapshot> snapshots) {
        snapshots.sort(Comparator.comparing(ResourceSnapshot::getTimestamp));

        return IntStream.range(0, snapshots.size())
                .mapToObj(idx -> {
                    var a = snapshots.get(idx);
                    var b = (idx + 1) < snapshots.size() ? snapshots.get(idx + 1) : null;
                    var start = a.getTimestamp();
                    var end   = Optional.ofNullable(b).map(ResourceSnapshot::getTimestamp).orElse(start.plusSeconds(120));
                    var d = BigDecimal.valueOf(Duration.between(start, end).toMillis());
                    return new ResourceUsage(
                            a.getApplicationId(),
                            a.getZoneId(),
                            plan,
                            a.resources().architecture(),
                            a.getMajorVersion(),
                            a.getAccount(),
                            BigDecimal.valueOf(a.resources().vcpu()).multiply(d),
                            BigDecimal.valueOf(a.resources().memoryGb()).multiply(d),
                            BigDecimal.valueOf(a.resources().diskGb()).multiply(d),
                            BigDecimal.valueOf(a.resources().gpuResources().count() * a.resources().gpuResources().memoryGb()).multiply(d));
                })
                .toList();
    }

    private ResourceUsage resourceUsageAdd(ResourceUsage a, ResourceUsage b) {
        assert a.getApplicationId().equals(b.getApplicationId());
        assert a.getZoneId().equals(b.getZoneId());
        assert a.getPlan().equals(b.getPlan());
        assert a.getArchitecture().equals(b.getArchitecture());
        assert a.getCloudAccount().equals(b.getCloudAccount());
        return new ResourceUsage(
                a.getApplicationId(),
                a.getZoneId(),
                a.getPlan(),
                a.getArchitecture(),
                a.getMajorVersion(),
                a.getCloudAccount(),
                a.getCpuMillis().add(b.getCpuMillis()),
                a.getMemoryMillis().add(b.getMemoryMillis()),
                a.getDiskMillis().add(b.getDiskMillis()),
                a.getGpuMillis().add(b.getGpuMillis()));
    }

    @Override
    public List<ResourceUsage> getResourceSnapshotsForPeriod(TenantName tenantName, long start, long end) {
        var tenantPlan = planMap.getOrDefault(tenantName, planRegistry.defaultPlan());

        return resourceSnapshots.stream()
                .filter(snapshot -> snapshot.getTimestamp().isAfter(Instant.ofEpochMilli(start)))
                .filter(snapshot -> snapshot.getTimestamp().isBefore(Instant.ofEpochMilli(end)))
                .filter(snapshot -> snapshot.getApplicationId().tenant().equals(tenantName))
                .collect(Collectors.groupingBy(
                        usage -> Objects.hash(usage.getApplicationId(), usage.getZoneId(), tenantPlan.id().value(), usage.resources().architecture(), usage.getMajorVersion())
                ))
                .values().stream()
                .map(snapshots -> resourceUsageFromSnapshots(tenantPlan, snapshots))
                .map(usages -> usages.stream().reduce(this::resourceUsageAdd))
                .filter(Optional::isPresent)
                .map(Optional::get)
                .toList();
    }

    @Override
    public void refreshMaterializedView() {
        hasRefreshedMaterializedView = true;
    }

    @Override
    public Instant getOldestSnapshotTimestamp(Set<DeploymentId> deployments) {
        return Instant.ofEpochMilli(987654L);
    }

    @Override
    public void writeScalingEvents(ClusterId clusterId, Collection<Cluster.ScalingEvent> scalingEvents) {
        this.scalingEvents.put(clusterId, List.copyOf(scalingEvents));
    }

    @Override
    public Map<ClusterId, List<Cluster.ScalingEvent>> scalingEvents(Instant from, Instant to, DeploymentId deploymentId) {
        return Map.of();
    }

    public void setPlan(TenantName tenant, Plan plan) {
        planMap.put(tenant, plan);
    }

    public boolean hasRefreshedMaterializedView() {
        return hasRefreshedMaterializedView;
    }

    public List<ResourceSnapshot> resourceSnapshots() {
        return resourceSnapshots;
    }

}