13
13
import java .nio .file .Paths ;
14
14
import java .nio .file .StandardOpenOption ;
15
15
import java .util .Optional ;
16
+ import java .time .Duration ;
16
17
import okhttp3 .OkHttpClient ;
17
18
import okhttp3 .Request ;
18
19
import okhttp3 .Response ;
@@ -30,6 +31,11 @@ public class LatestAgentSnapshotResolver {
30
31
"https://oss.sonatype.org/content/repositories/snapshots/io/opentelemetry/javaagent/opentelemetry-javaagent" ;
31
32
static final String LATEST_SNAPSHOT_META = BASE_URL + "/maven-metadata.xml" ;
32
33
34
+ private static final OkHttpClient client = new OkHttpClient .Builder ()
35
+ .connectTimeout (Duration .ofMinutes (1 ))
36
+ .readTimeout (Duration .ofMinutes (1 ))
37
+ .build ();
38
+
33
39
Optional <Path > resolve () throws IOException {
34
40
String version = fetchLatestSnapshotVersion ();
35
41
logger .info ("Latest snapshot version is {}" , version );
@@ -81,11 +87,33 @@ private byte[] fetchBodyBytesFrom(String url) throws IOException {
81
87
return fetchBodyFrom (url ).bytes ();
82
88
}
83
89
90
+ // The sonatype repository can be very unreliable, so we retry a few times
84
91
private ResponseBody fetchBodyFrom (String url ) throws IOException {
85
92
Request request = new Request .Builder ().url (url ).build ();
86
- OkHttpClient client = new OkHttpClient ();
87
- Response response = client .newCall (request ).execute ();
88
- ResponseBody body = response .body ();
89
- return body ;
93
+ IOException lastException = null ;
94
+
95
+ for (int attempt = 0 ; attempt < 3 ; attempt ++) {
96
+ try {
97
+ try (Response response = client .newCall (request ).execute ()) {
98
+ if (!response .isSuccessful ()) {
99
+ throw new IOException ("Unexpected HTTP code " + response .code () + " for " + url );
100
+ }
101
+ ResponseBody body = response .body ();
102
+ if (body != null ) {
103
+ byte [] data = body .bytes ();
104
+ return ResponseBody .create (data , body .contentType ());
105
+ } else {
106
+ throw new IOException ("Response body is null" );
107
+ }
108
+ }
109
+ } catch (IOException e ) {
110
+ lastException = e ;
111
+ if (attempt < 2 ) {
112
+ logger .warn ("Attempt {} to fetch {} failed: {}. Retrying..." , attempt + 1 , url , e .getMessage ());
113
+ }
114
+ }
115
+ }
116
+ throw lastException ;
90
117
}
91
118
}
119
+
0 commit comments