summaryrefslogtreecommitdiffstats
path: root/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiHandler.java
blob: 1815628a1eefb2111c9b36abed0fbdcee70eddd9 (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
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.restapi.routing;

import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.zone.RoutingMethod;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.restapi.ErrorResponse;
import com.yahoo.restapi.MessageResponse;
import com.yahoo.restapi.Path;
import com.yahoo.restapi.SlimeJsonResponse;
import com.yahoo.slime.Cursor;
import com.yahoo.slime.Slime;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.Instance;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.EndpointStatus;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLoggingRequestHandler;
import com.yahoo.vespa.hosted.controller.routing.GlobalRouting;
import com.yahoo.vespa.hosted.controller.routing.RoutingPolicy;
import com.yahoo.yolean.Exceptions;

import java.time.Instant;
import java.util.Objects;
import java.util.logging.Level;

/**
 * This implements the /routing/v1 API, which provides operator with global routing control at both zone- and
 * deployment-level.
 *
 * @author mpolden
 */
public class RoutingApiHandler extends AuditLoggingRequestHandler {

    private final Controller controller;

    public RoutingApiHandler(Context ctx, Controller controller) {
        super(ctx, controller.auditLogger());
        this.controller = Objects.requireNonNull(controller, "controller must be non-null");
    }

    @Override
    public HttpResponse auditAndHandle(HttpRequest request) {
        try {
            var path = new Path(request.getUri());
            switch (request.getMethod()) {
                case GET: return get(path);
                case POST: return post(path);
                case DELETE: return delete(path);
                default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
            }
        } catch (IllegalArgumentException e) {
            return ErrorResponse.badRequest(Exceptions.toMessageString(e));
        } catch (RuntimeException e) {
            log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
            return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
        }
    }

    private HttpResponse delete(Path path) {
        if (path.matches("/routing/v1/inactive/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return setDeploymentStatus(path, true);
        if (path.matches("/routing/v1/inactive/environment/{environment}/region/{region}")) return setZoneStatus(path, true);
        return ErrorResponse.notFoundError("Nothing at " + path);
    }

    private HttpResponse post(Path path) {
        if (path.matches("/routing/v1/inactive/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return setDeploymentStatus(path, false);
        if (path.matches("/routing/v1/inactive/environment/{environment}/region/{region}")) return setZoneStatus(path, false);
        return ErrorResponse.notFoundError("Nothing at " + path);
    }

    private HttpResponse get(Path path) {
        if (path.matches("/routing/v1/status/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploymentStatus(path);
        if (path.matches("/routing/v1/status/environment/{environment}/region/{region}")) return zoneStatus(path);
        return ErrorResponse.notFoundError("Nothing at " + path);
    }

    private HttpResponse setZoneStatus(Path path, boolean in) {
        var zone = zoneFrom(path);
        if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
            var status = in ? GlobalRouting.Status.in : GlobalRouting.Status.out;
            controller.routingController().policies().setGlobalRoutingStatus(zone, status);
        } else {
            controller.serviceRegistry().configServer().setGlobalRotationStatus(zone, in);
        }
        return new MessageResponse("Set global routing status for deployments in " + zone + " to " +
                                   (in ? "IN" : "OUT"));
    }

    private HttpResponse zoneStatus(Path path) {
        var zone = zoneFrom(path);
        var slime = new Slime();
        var root = slime.setObject();
        if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
            var zonePolicy = controller.routingController().policies().get(zone);
            zoneStatusToSlime(root, zonePolicy.zone(), zonePolicy.globalRouting(), RoutingMethod.exclusive);
        } else {
            // Rotation status per zone only exposes in/out status, no agent or time of change.
            var in = controller.serviceRegistry().configServer().getGlobalRotationStatus(zone);
            var globalRouting = new GlobalRouting(in ? GlobalRouting.Status.in : GlobalRouting.Status.out,
                                                  GlobalRouting.Agent.operator, Instant.EPOCH);
            zoneStatusToSlime(root, zone, globalRouting, RoutingMethod.shared);
        }
        return new SlimeJsonResponse(slime);
    }

    private HttpResponse setDeploymentStatus(Path path, boolean in) {
        var deployment = deploymentFrom(path);
        var instance = controller.applications().requireInstance(deployment.applicationId());
        var status = in ? GlobalRouting.Status.in : GlobalRouting.Status.out;
        var agent = GlobalRouting.Agent.operator; // Always operator as this is an operator API

        // Set rotation status, if any assigned
        if (rotationCanRouteTo(deployment.zoneId(), instance)) {
            var endpointStatus = new EndpointStatus(in ? EndpointStatus.Status.in : EndpointStatus.Status.out, "",
                                                    agent.name(),
                                                    controller.clock().instant().getEpochSecond());
            controller.routingController().setGlobalRotationStatus(deployment, endpointStatus);
        }

        // Set policy status
        controller.routingController().policies().setGlobalRoutingStatus(deployment, status, agent);
        return new MessageResponse("Set global routing status for " + deployment + " to " + (in ? "IN" : "OUT"));
    }

    private HttpResponse deploymentStatus(Path path) {
        var deployment = deploymentFrom(path);
        var instance = controller.applications().requireInstance(deployment.applicationId());
        var slime = new Slime();
        var deploymentsObject = slime.setObject().setArray("deployments");

        // Include status from rotation
        if (rotationCanRouteTo(deployment.zoneId(), instance)) {
            var rotationStatus = controller.routingController().globalRotationStatus(deployment);
            // Status is equal across all global endpoints, as the status is per deployment, not per endpoint.
            var endpointStatus = rotationStatus.values().stream().findFirst();
            if (endpointStatus.isPresent()) {
                var changedAt = Instant.ofEpochSecond(endpointStatus.get().getEpoch());
                GlobalRouting.Agent agent;
                try {
                    agent = GlobalRouting.Agent.valueOf(endpointStatus.get().getAgent());
                } catch (IllegalArgumentException e) {
                    agent = GlobalRouting.Agent.unknown;
                }
                var status = endpointStatus.get().getStatus() == EndpointStatus.Status.in
                        ? GlobalRouting.Status.in
                        : GlobalRouting.Status.out;
                deploymentStatusToSlime(deploymentsObject.addObject(), deployment,
                                        new GlobalRouting(status, agent, changedAt),
                                        RoutingMethod.shared);
            }
        }

        // Include status from routing policies
        var routingPolicies = controller.routingController().policies().get(deployment);
        for (var policy : routingPolicies.values()) {
            deploymentStatusToSlime(deploymentsObject.addObject(), policy);
        }

        return new SlimeJsonResponse(slime);
    }

    /** Returns whether instance has an assigned rotation and a deployment in given zone */
    private static boolean rotationCanRouteTo(ZoneId zone, Instance instance) {
        return !instance.rotations().isEmpty() && instance.deployments().containsKey(zone);
    }

    private static void zoneStatusToSlime(Cursor object, ZoneId zone, GlobalRouting globalRouting, RoutingMethod method) {
        object.setString("routingMethod", asString(method));
        object.setString("environment", zone.environment().value());
        object.setString("region", zone.region().value());
        object.setString("status", asString(globalRouting.status()));
        object.setString("agent", asString(globalRouting.agent()));
        object.setLong("changedAt", globalRouting.changedAt().toEpochMilli());
    }

    private static void deploymentStatusToSlime(Cursor object, DeploymentId deployment, GlobalRouting globalRouting, RoutingMethod method) {
        object.setString("routingMethod", asString(method));
        object.setString("instance", deployment.applicationId().serializedForm());
        object.setString("environment", deployment.zoneId().environment().value());
        object.setString("region", deployment.zoneId().region().value());
        object.setString("status", asString(globalRouting.status()));
        object.setString("agent", asString(globalRouting.agent()));
        object.setLong("changedAt", globalRouting.changedAt().toEpochMilli());
    }

    private static void deploymentStatusToSlime(Cursor object, RoutingPolicy policy) {
        deploymentStatusToSlime(object, new DeploymentId(policy.id().owner(), policy.id().zone()),
                                policy.status().globalRouting(), RoutingMethod.exclusive);
    }

    private DeploymentId deploymentFrom(Path path) {
        return new DeploymentId(ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance")),
                                zoneFrom(path));
    }

    private ZoneId zoneFrom(Path path) {
        var zone = ZoneId.from(path.get("environment"), path.get("region"));
        if (!controller.zoneRegistry().hasZone(zone)) {
            throw new IllegalArgumentException("No such zone: " + zone);
        }
        return zone;
    }

    private static String asString(GlobalRouting.Status status) {
        switch (status) {
            case in: return "in";
            case out: return "out";
            default: return "unknown";
        }
    }

    private static String asString(GlobalRouting.Agent agent) {
        switch (agent) {
            case operator: return "operator";
            case system: return "system";
            case tenant: return "tenant";
            default: return "unknown";
        }
    }

    private static String asString(RoutingMethod method) {
        switch (method) {
            case shared: return "shared";
            case exclusive: return "exclusive";
            default: return "unknonwn";
        }
    }

}