summaryrefslogtreecommitdiffstats
path: root/service-monitor/src/main/java/com/yahoo/vespa/service/monitor/internal/health/HealthClient.java
blob: 1ecdf432ada3c2e3538f3580756802270b2d2b85 (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
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.service.monitor.internal.health;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.config.provision.HostName;
import com.yahoo.vespa.athenz.api.AthenzService;
import com.yahoo.vespa.athenz.identity.ServiceIdentityProvider;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.net.URL;

import static com.yahoo.yolean.Exceptions.uncheck;

/**
 * @author hakon
 */
public class HealthClient implements AutoCloseable, ServiceIdentityProvider.Listener {
    private static final ObjectMapper mapper = new ObjectMapper();
    private static final long MAX_CONTENT_LENGTH = 1L << 20; // 1 MB
    private static final int DEFAULT_TIMEOUT_MILLIS = 1_000;

    private static final ConnectionKeepAliveStrategy KEEP_ALIVE_STRATEGY =
            new DefaultConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    long keepAlive = super.getKeepAliveDuration(response, context);
                    if (keepAlive == -1) {
                        // Keep connections alive 60 seconds if a keep-alive value
                        // has not be explicitly set by the server
                        keepAlive = 60000;
                    }
                    return keepAlive;
                }
            };

    private final URL url;
    private final ServiceIdentityProvider serviceIdentityProvider;
    private final HostnameVerifier hostnameVerifier;

    private volatile CloseableHttpClient httpClient;

    public HealthClient(HostName hostname,
                        int port,
                        ServiceIdentityProvider identityProvider,
                        HostnameVerifier hostnameVerifier) {
        this(uncheck(() -> new URL("https", hostname.value(), port, "/state/v1/health")),
                identityProvider,
                hostnameVerifier);
    }

    public HealthClient(URL stateV1HealthEndpoint,
                        ServiceIdentityProvider serviceIdentityProvider,
                        HostnameVerifier hostnameVerifier) {
        this.url = stateV1HealthEndpoint;
        this.serviceIdentityProvider = serviceIdentityProvider;
        this.hostnameVerifier = hostnameVerifier;

        onCredentialsUpdate(serviceIdentityProvider.getIdentitySslContext(), null);
        serviceIdentityProvider.addIdentityListener(this);
    }

    @Override
    public void onCredentialsUpdate(SSLContext sslContext, AthenzService ignored) {
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", socketFactory)
                .build();

        HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(DEFAULT_TIMEOUT_MILLIS) // establishment of connection
                .setConnectionRequestTimeout(DEFAULT_TIMEOUT_MILLIS)  // connection from connection manager
                .setSocketTimeout(DEFAULT_TIMEOUT_MILLIS) // waiting for data
                .build();

        this.httpClient = HttpClients.custom()
                .setKeepAliveStrategy(KEEP_ALIVE_STRATEGY)
                .setConnectionManager(connectionManager)
                .disableAutomaticRetries()
                .setDefaultRequestConfig(requestConfig)
                .build();
    }

    public HealthInfo getHealthInfo() {
        try {
            return probeHealth();
        } catch (Exception e) {
            return HealthInfo.fromException(e);
        }
    }

    @Override
    public void close() {
        serviceIdentityProvider.removeIdentityListener(this);

        try {
            httpClient.close();
        } catch (Exception e) {
            // ignore
        }
        httpClient = null;
    }

    private HealthInfo probeHealth() throws Exception {
        HttpGet httpget = new HttpGet(url.toString());
        CloseableHttpResponse httpResponse;

        CloseableHttpClient httpClient = this.httpClient;
        if (httpClient == null) {
            throw new IllegalStateException("HTTP client has closed");
        }

        httpResponse = httpClient.execute(httpget);

        int httpStatusCode = httpResponse.getStatusLine().getStatusCode();
        if (httpStatusCode < 200 || httpStatusCode >= 300) {
            return HealthInfo.fromBadHttpStatusCode(httpStatusCode);
        }

        HttpEntity bodyEntity = httpResponse.getEntity();
        long contentLength = bodyEntity.getContentLength();
        if (contentLength > MAX_CONTENT_LENGTH) {
            throw new IllegalArgumentException("Content too long: " + contentLength + " bytes");
        }
        String body = EntityUtils.toString(bodyEntity);
        HealthResponse healthResponse = mapper.readValue(body, HealthResponse.class);

        if (healthResponse.status == null || healthResponse.status.code == null) {
            return HealthInfo.fromHealthStatusCode(HealthResponse.Status.DEFAULT_STATUS);
        } else {
            return HealthInfo.fromHealthStatusCode(healthResponse.status.code);
        }
    }
}