summaryrefslogtreecommitdiffstats
path: root/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainer.java
blob: 44bfed9010604b547f4f69df879d21a4e43ff001 (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
// Copyright 2019 Oath Inc. 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.NodeResources;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.OutOfCapacityException;
import com.yahoo.transaction.Mutex;
import com.yahoo.vespa.flags.FlagSource;
import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.flags.ListFlag;
import com.yahoo.vespa.flags.custom.HostCapacity;
import com.yahoo.vespa.hosted.provision.Node;
import com.yahoo.vespa.hosted.provision.NodeList;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.node.Agent;
import com.yahoo.vespa.hosted.provision.provisioning.FatalProvisioningException;
import com.yahoo.vespa.hosted.provision.provisioning.HostProvisioner;
import com.yahoo.vespa.hosted.provision.provisioning.NodeResourceComparator;
import com.yahoo.vespa.hosted.provision.provisioning.ProvisionedHost;
import com.yahoo.yolean.Exceptions;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author freva
 * @author mpolden
 */
public class DynamicProvisioningMaintainer extends NodeRepositoryMaintainer {

    private static final Logger log = Logger.getLogger(DynamicProvisioningMaintainer.class.getName());
    private static final ApplicationId preprovisionAppId = ApplicationId.from("hosted-vespa", "tenant-host", "preprovision");

    private final HostProvisioner hostProvisioner;
    private final ListFlag<HostCapacity> targetCapacityFlag;

    DynamicProvisioningMaintainer(NodeRepository nodeRepository,
                                  Duration interval,
                                  HostProvisioner hostProvisioner,
                                  FlagSource flagSource) {
        super(nodeRepository, interval);
        this.hostProvisioner = hostProvisioner;
        this.targetCapacityFlag = Flags.TARGET_CAPACITY.bindTo(flagSource);
    }

    @Override
    protected void maintain() {
        try (Mutex lock = nodeRepository().lockUnallocated()) {
            NodeList nodes = nodeRepository().list();
            resumeProvisioning(nodes, lock);
            convergeToCapacity(nodes);
        }
    }

    /** Resume provisioning of already provisioned hosts and their children */
    private void resumeProvisioning(NodeList nodes, Mutex lock) {
        Map<String, Set<Node>> nodesByProvisionedParentHostname = nodes.nodeType(NodeType.tenant).asList().stream()
                                                                       .filter(node -> node.parentHostname().isPresent())
                                                                       .collect(Collectors.groupingBy(
                                                                               node -> node.parentHostname().get(),
                                                                               Collectors.toSet()));

        nodes.state(Node.State.provisioned).nodeType(NodeType.host).forEach(host -> {
            Set<Node> children = nodesByProvisionedParentHostname.getOrDefault(host.hostname(), Set.of());
            try {
                List<Node> updatedNodes = hostProvisioner.provision(host, children);
                nodeRepository().write(updatedNodes, lock);
            } catch (IllegalArgumentException | IllegalStateException e) {
                log.log(Level.INFO, "Failed to provision " + host.hostname() + " with " + children.size() + " children: " +
                                    Exceptions.toMessageString(e));
            } catch (FatalProvisioningException e) {
                log.log(Level.SEVERE, "Failed to provision " + host.hostname() + " with " + children.size()  +
                                      " children, failing out the host recursively", e);
                // Fail out as operator to force a quick redeployment
                nodeRepository().failRecursively(
                        host.hostname(), Agent.operator, "Failed by HostProvisioner due to provisioning failure");
            } catch (RuntimeException e) {
                log.log(Level.WARNING, "Failed to provision " + host.hostname() + ", will retry in " + interval(), e);
            }
        });
    }

    /** Converge zone to wanted capacity */
    private void convergeToCapacity(NodeList nodes) {
        List<NodeResources> capacity = targetCapacity();
        List<Node> excessHosts = provision(capacity, nodes);
        excessHosts.forEach(host -> {
            try {
                hostProvisioner.deprovision(host);
                nodeRepository().removeRecursively(host, true);
            } catch (RuntimeException e) {
                log.log(Level.WARNING, "Failed to deprovision " + host.hostname() + ", will retry in " + interval(), e);
            }
        });
    }


    /**
     * Provision the nodes necessary to satisfy given capacity.
     *
     * @return Excess hosts that can safely be deprovisioned, if any.
     */
    private List<Node> provision(List<NodeResources> capacity, NodeList nodes) {
        List<Node> existingHosts = availableHostsOf(nodes);
        if (nodeRepository().zone().getCloud().dynamicProvisioning()) {
            existingHosts = removableHostsOf(existingHosts, nodes);
        } else if (capacity.isEmpty()) {
            return List.of();
        }
        List<Node> excessHosts = new ArrayList<>(existingHosts);
        for (Iterator<NodeResources> it = capacity.iterator(); it.hasNext() && !excessHosts.isEmpty(); ) {
            NodeResources resources = it.next();
            excessHosts.stream()
                       .filter(nodeRepository()::canAllocateTenantNodeTo)
                       .filter(host -> nodeRepository().resourcesCalculator()
                                                       .advertisedResourcesOf(host.flavor())
                                                       .satisfies(resources))
                       .min(Comparator.comparingInt(n -> n.flavor().cost()))
                       .ifPresent(host -> {
                           excessHosts.remove(host);
                           it.remove();
                       });
        }
        // Pre-provisioning is best effort, do one host at a time
        capacity.forEach(resources -> {
            try {
                Version osVersion = nodeRepository().osVersions().targetFor(NodeType.host).orElse(Version.emptyVersion);
                List<Node> hosts = hostProvisioner.provisionHosts(nodeRepository().database().getProvisionIndexes(1),
                                                                  resources, preprovisionAppId, osVersion)
                                                  .stream()
                                                  .map(ProvisionedHost::generateHost)
                                                  .collect(Collectors.toList());
                nodeRepository().addNodes(hosts, Agent.DynamicProvisioningMaintainer);
            } catch (OutOfCapacityException | IllegalArgumentException | IllegalStateException e) {
                log.log(Level.WARNING, "Failed to pre-provision " + resources + ": " + e.getMessage());
            } catch (RuntimeException e) {
                log.log(Level.WARNING, "Failed to pre-provision " + resources + ", will retry in " + interval(), e);
            }
        });
        return removableHostsOf(excessHosts, nodes);
    }


    /** Reads node resources declared by target capacity flag */
    private List<NodeResources> targetCapacity() {
        return targetCapacityFlag.value().stream()
                                 .flatMap(cap -> {
                                     NodeResources resources = new NodeResources(cap.getVcpu(), cap.getMemoryGb(),
                                                                                 cap.getDiskGb(), 1);
                                     return IntStream.range(0, cap.getCount()).mapToObj(i -> resources);
                                 })
                                 .sorted(NodeResourceComparator.memoryDiskCpuOrder().reversed())
                                 .collect(Collectors.toList());
    }

    /** Returns hosts that are considered available, i.e. not parked or flagged for deprovisioning */
    private static List<Node> availableHostsOf(NodeList nodes) {
        return nodes.nodeType(NodeType.host)
                    .matching(host -> host.state() != Node.State.parked || host.status().wantToDeprovision())
                    .asList();
    }

    /** Returns the subset of given hosts that have no containers and are thus removable */
    private static List<Node> removableHostsOf(List<Node> hosts, NodeList allNodes) {
        Map<String, Node> hostsByHostname = hosts.stream()
                                                 .collect(Collectors.toMap(Node::hostname,
                                                                           Function.identity()));

        allNodes.asList().stream()
                .filter(node -> node.allocation().isPresent())
                .flatMap(node -> node.parentHostname().stream())
                .distinct()
                .forEach(hostsByHostname::remove);

        return List.copyOf(hostsByHostname.values());
    }

}