aboutsummaryrefslogtreecommitdiffstats
path: root/jaxrs_client_utils/src/main/java/com/yahoo/vespa/jaxrs/client/RetryingJaxRsStrategy.java
blob: c964dfce2c755f009a958a382088b10f44e3530e (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.jaxrs.client;

import com.yahoo.vespa.applicationmodel.HostName;

import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A {@link JaxRsStrategy} that will retry on failures, looping twice over all available server hosts before giving up.
 *
 * @author bakksjo
 */
public class RetryingJaxRsStrategy<T> implements JaxRsStrategy<T> {
    private static final Logger logger = Logger.getLogger(RetryingJaxRsStrategy.class.getName());

    private final List<HostName> hostNames;
    private final int port;
    private final JaxRsClientFactory jaxRsClientFactory;
    private final Class<T> apiClass;
    private String pathPrefix;
    private final String scheme;

    private int maxIterations = 2;

    public RetryingJaxRsStrategy(
            final Set<HostName> hostNames,
            final int port,
            final JaxRsClientFactory jaxRsClientFactory,
            final Class<T> apiClass,
            final String pathPrefix,
            String scheme) {
        if (hostNames.isEmpty()) {
            throw new IllegalArgumentException("hostNames argument must not be empty");
        }
        Objects.requireNonNull(jaxRsClientFactory, "jaxRsClientFactory argument may not be null");
        Objects.requireNonNull(apiClass, "apiClass argument may not be null");
        Objects.requireNonNull(pathPrefix, "pathPrefix argument may not be null");
        this.hostNames = new ArrayList<>(hostNames);
        Collections.shuffle(this.hostNames);
        this.port = port;
        this.jaxRsClientFactory = jaxRsClientFactory;
        this.apiClass = apiClass;
        this.pathPrefix = pathPrefix;
        this.scheme = scheme;
    }

    /**
     * The the max number of times the hostnames should be iterated over, before giving up.
     *
     * <p>By default, maxIterations is 2.
     */
    public RetryingJaxRsStrategy<T> setMaxIterations(int maxIterations) {
        this.maxIterations = maxIterations;
        return this;
    }

    @Override
    public <R> R apply(final Function<T, R> function) throws IOException {
        return apply(function, new LegacyJaxRsTimeouts());
    }


    @Override
    public <R> R apply(final Function<T, R> function, JaxRsTimeouts timeouts) throws IOException {
        ProcessingException sampleException = null;

        for (int i = 0; i < maxIterations; ++i) {
            for (final HostName hostName : hostNames) {
                URI uri = UriBuilder.fromPath(pathPrefix).port(port).scheme(scheme).host(hostName.s()).build();
                JaxRsClientFactory.Params<T> params = new JaxRsClientFactory.Params<>(apiClass, uri);
                params.setConnectTimeout(timeouts.getConnectTimeoutOrThrow());
                params.setReadTimeout(timeouts.getReadTimeoutOrThrow());
                final T jaxRsClient = jaxRsClientFactory.createClient(params);
                try {
                    return function.apply(jaxRsClient);
                } catch (ProcessingException e) {
                    // E.g. java.net.SocketTimeoutException thrown on read timeout is wrapped as a ProcessingException
                    sampleException = e;
                    logger.log(Level.INFO, "Failed REST API call to "
                            + hostName + ":" + port + pathPrefix + " (in retry loop): "
                            + e.getMessage());
                }
            }
        }

        final String message = String.format(
                "Giving up invoking REST API after %d tries against hosts %s.%s",
                maxIterations,
                hostNames,
                sampleException == null ? "" : ", sample error: " + sampleException.getMessage());

        assert sampleException != null;
        throw new IOException(message, sampleException);
    }
}