summaryrefslogtreecommitdiffstats
path: root/configserver/src/main/java/com/yahoo/vespa/serviceview/StateResource.java
blob: 138e6c8798c57df8f222b7006c01c0001df1fcb2 (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.serviceview;

import ai.vespa.util.http.VespaClientBuilderFactory;
import com.yahoo.container.jaxrs.annotation.Component;
import com.yahoo.vespa.serviceview.bindings.ApplicationView;
import com.yahoo.vespa.serviceview.bindings.ConfigClient;
import com.yahoo.vespa.serviceview.bindings.HealthClient;
import com.yahoo.vespa.serviceview.bindings.ModelResponse;
import com.yahoo.vespa.serviceview.bindings.StateClient;
import org.glassfish.jersey.client.proxy.WebResourceFactory;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;


/**
 * A web service to discover and proxy Vespa service state info.
 *
 * @author Steinar Knutsen
 */
@Path("/")
public class StateResource implements StateClient {

    private static final String USER_AGENT = "service-view-config-server-client";
    private static final String SINGLE_API_LINK = "url";

    @SuppressWarnings("removal")
    private final VespaClientBuilderFactory clientBuilderFactory;
    private final int restApiPort;
    private final String host;
    private final UriInfo uriInfo;

    @SuppressWarnings("serial")
    private static class GiveUpLinkRetargetingException extends Exception {
        public GiveUpLinkRetargetingException(Throwable reason) {
            super(reason);
        }

        public GiveUpLinkRetargetingException(String message) {
            super(message);
        }
    }

    public StateResource(@Component ConfigServerLocation configServer, @Context UriInfo ui) {
        this.clientBuilderFactory = configServer.clientBuilderFactory;
        this.restApiPort = configServer.restApiPort;
        this.host = "localhost";
        this.uriInfo = ui;
    }

    @Override
    @GET
    @Path("v1/")
    @Produces(MediaType.APPLICATION_JSON)
    public ApplicationView getDefaultUserInfo() {
        return getUserInfo("default", "default", "default", "default", "default");
    }

    @Override
    @GET
    @Path("v1/tenant/{tenantName}/application/{applicationName}/environment/{environmentName}/region/{regionName}/instance/{instanceName}")
    @Produces(MediaType.APPLICATION_JSON)
    public ApplicationView getUserInfo(@PathParam("tenantName") String tenantName,
                                @PathParam("applicationName") String applicationName,
                                @PathParam("environmentName") String environmentName,
                                @PathParam("regionName") String regionName,
                                @PathParam("instanceName") String instanceName) {
        ServiceModel model = new ServiceModel(
                getModelConfig(tenantName, applicationName, environmentName, regionName, instanceName));
        return model.showAllClusters(
                getBaseUri() + "v1/",
                        applicationIdentifier(tenantName, applicationName, environmentName, regionName, instanceName));
    }

    private String getBaseUri() {
        String baseUri = uriInfo.getBaseUri().toString();
        if (baseUri.endsWith("/")) {
            return baseUri;
        } else {
            return baseUri + "/";
        }
    }

    protected ModelResponse getModelConfig(String tenant, String application, String environment, String region, String instance) {
        Client client = client();
        try {
            WebTarget target = client.target("http://" + host + ":" + restApiPort + "/");
            ConfigClient resource = WebResourceFactory.newResource(ConfigClient.class, target);
            return resource.getServiceModel(tenant, application, environment, region, instance);
        } finally {
            client.close();
        }
    }

    @SuppressWarnings("rawtypes")
    @Override
    @GET
    @Path("v1/tenant/{tenantName}/application/{applicationName}/environment/{environmentName}/region/{regionName}/instance/{instanceName}/service/{serviceIdentifier}/{apiParams: .*}")
    @Produces(MediaType.APPLICATION_JSON)
    public HashMap singleService(@PathParam("tenantName") String tenantName,
            @PathParam("applicationName") String applicationName,
            @PathParam("environmentName") String environmentName,
            @PathParam("regionName") String regionName,
            @PathParam("instanceName") String instanceName,
            @PathParam("serviceIdentifier") String identifier,
            @PathParam("apiParams") String apiParams) {
        ServiceModel model = new ServiceModel(getModelConfig(tenantName, applicationName, environmentName, regionName, instanceName));
        Service s = model.getService(identifier);
        int requestedPort = s.matchIdentifierWithPort(identifier);
        Client client = client();
        try {
            HealthClient resource = getHealthClient(apiParams, s, requestedPort, client);
            HashMap<?, ?> apiResult = resource.getHealthInfo();
            rewriteResourceLinks(apiResult, model, s, applicationIdentifier(tenantName, applicationName, environmentName, regionName, instanceName), identifier);
            return apiResult;
        } finally {
            client.close();
        }
    }

    protected HealthClient getHealthClient(String apiParams, Service s, int requestedPort, Client client) {
        final StringBuilder uriBuffer = new StringBuilder("http://").append(s.host).append(':').append(requestedPort).append('/')
                .append(apiParams);
        addQuery(uriBuffer);
        WebTarget target = client.target(uriBuffer.toString());
        return WebResourceFactory.newResource(HealthClient.class, target);
    }

    private String applicationIdentifier(String tenant, String application, String environment, String region, String instance) {
        return "tenant/" + tenant
               + "/application/" + application
               + "/environment/" + environment
               + "/region/" + region
               + "/instance/" + instance;
    }

    private void rewriteResourceLinks(Object apiResult,
            ServiceModel model,
            Service self,
            String applicationIdentifier,
            String incomingIdentifier) {
        if (apiResult instanceof List) {
            for (@SuppressWarnings("unchecked") ListIterator<Object> i = ((List<Object>) apiResult).listIterator(); i.hasNext();) {
                Object resource = i.next();
                if (resource instanceof String) {
                    try {
                        StringBuilder buffer = linkBuffer(applicationIdentifier);
                        // if it points to a port and host not part of the application, rewriting will not occur, so this is kind of safe
                        retarget(model, self, buffer, (String) resource);
                        i.set(buffer.toString());
                    } catch (GiveUpLinkRetargetingException e) {
                        break; // assume relatively homogenous lists when doing rewrites to avoid freezing up on scanning long lists
                    }
                } else {
                    rewriteResourceLinks(resource, model, self, applicationIdentifier, incomingIdentifier);
                }
            }
        } else if (apiResult instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<Object, Object> api = (Map<Object, Object>) apiResult;
            for (Map.Entry<Object, Object> entry : api.entrySet()) {
                if (SINGLE_API_LINK.equals(entry.getKey()) && entry.getValue() instanceof String) {
                    try {
                        rewriteSingleLink(entry, model, self, linkBuffer(applicationIdentifier));
                    } catch (GiveUpLinkRetargetingException e) {
                        // NOP
                    }
                } else if ("link".equals(entry.getKey()) && entry.getValue() instanceof String) {
                    buildSingleLink(entry, linkBuffer(applicationIdentifier), incomingIdentifier);
                } else {
                    rewriteResourceLinks(entry.getValue(), model, self, applicationIdentifier, incomingIdentifier);
                }
            }
        }
    }

    private void buildSingleLink(Map.Entry<Object, Object> entry,
                                 StringBuilder newUri,
                                 String incomingIdentifier) {
        newUri.append("/service/")
                .append(incomingIdentifier);
        newUri.append(entry.getValue());
        entry.setValue(newUri.toString());
    }

    private void addQuery(StringBuilder newUri) {
        String query = uriInfo.getRequestUri().getRawQuery();
        if (query != null && query.length() > 0) {
            newUri.append('?').append(query);
        }
    }

    private StringBuilder linkBuffer(String applicationIdentifier) {
        StringBuilder newUri = new StringBuilder(getBaseUri());
        newUri.append("v1/").append(applicationIdentifier);
        return newUri;
    }

    private void rewriteSingleLink(Map.Entry<Object, Object> entry,
            ServiceModel model,
            Service self,
            StringBuilder newUri) throws GiveUpLinkRetargetingException {
        String url = (String) entry.getValue();
        retarget(model, self, newUri, url);
        entry.setValue(newUri.toString());
    }

    private void retarget(ServiceModel model, Service self, StringBuilder newUri, String url) throws GiveUpLinkRetargetingException {
        URI link;
        try {
            link = new URI(url);
        } catch (URISyntaxException e) {
            throw new GiveUpLinkRetargetingException(e);
        }
        if (!link.isAbsolute()) {
            throw new GiveUpLinkRetargetingException("This rewriting only supports absolute URIs.");
        }
        int linkPort = link.getPort();
        if (linkPort == -1) {
            linkPort = 80;
        }
        Service s;
        try {
            s = model.resolve(link.getHost(), linkPort, self);
        } catch (IllegalArgumentException e) {
            throw new GiveUpLinkRetargetingException(e);
        }
        newUri.append("/service/").append(s.getIdentifier(linkPort));
        newUri.append(link.getRawPath());
    }

    private Client client() {
        return clientBuilderFactory.newBuilder()
                            .register((ClientRequestFilter) ctx -> ctx.getHeaders().put(HttpHeaders.USER_AGENT, List.of(USER_AGENT)))
                            .build();
    }
}