Skip to content

Commit 4f43814

Browse files
authored
Fix doc-link checker to retry with back-off after a 429 response (#741)
1 parent 6883628 commit 4f43814

File tree

1 file changed

+54
-3
lines changed

1 file changed

+54
-3
lines changed

utils/linkcheck/main.go

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
ctrl "sigs.k8s.io/controller-runtime"
2020
logf "sigs.k8s.io/controller-runtime/pkg/log"
2121
"sort"
22+
"strconv"
2223
"strings"
2324
"time"
2425
)
@@ -277,15 +278,65 @@ func checkURL(urlToGet *url.URL, fragments []string) int {
277278
Timeout: time.Minute * 1,
278279
}
279280

280-
if resp, err = netClient.Get(urlToGet.String()); err != nil {
281+
urlStr := urlToGet.String()
282+
283+
// Create a new request using http
284+
req, err := http.NewRequest("GET", urlStr, nil)
285+
if err != nil {
286+
fmt.Printf(" FAILED error: %v\n", err)
287+
return 1
288+
}
289+
290+
if strings.HasPrefix(urlStr, "https://github.com") {
291+
if token, found := os.LookupEnv("GH_TOKEN"); found && token != "" {
292+
// Create a Bearer string by appending string access token
293+
var bearer = "Bearer " + token
294+
// add authorization header to the req
295+
req.Header.Add("Authorization", bearer)
296+
fmt.Print(" (URL is GitHub, GH_TOKEN is set)")
297+
} else {
298+
fmt.Print(" (URL is GitHub, but no auth token in GH_TOKEN)")
299+
}
300+
}
301+
302+
if resp, err = netClient.Do(req); err != nil {
281303
fmt.Printf(" FAILED error: %v\n", err)
282304
return 1
283305
}
306+
307+
retryCount := 10
308+
if retryCountStr, found := os.LookupEnv("LINK_CHECK_RETRY_COUNT"); found {
309+
if c, err := strconv.Atoi(retryCountStr); err == nil {
310+
retryCount = c
311+
}
312+
}
313+
314+
if resp.StatusCode == 429 {
315+
for i := 0; i < retryCount; i++ {
316+
_ = resp.Body.Close()
317+
fmt.Println(" received 429 status waiting for one minute")
318+
time.Sleep(1 * time.Minute)
319+
320+
if resp, err = netClient.Do(req); err != nil {
321+
fmt.Printf(" FAILED error: %v\n", err)
322+
return 1
323+
}
324+
325+
if resp.StatusCode != 429 {
326+
break
327+
}
328+
}
329+
}
330+
284331
defer resp.Body.Close()
285332

286-
// Check if request was successful
333+
// Check if the request was successful
287334
if resp.StatusCode != 200 {
288-
fmt.Printf(" FAILED response: %d\n", resp.StatusCode)
335+
body := ""
336+
if content, err = io.ReadAll(resp.Body); err == nil {
337+
body = string(content)
338+
}
339+
fmt.Printf(" FAILED response: %d\n%v\n%s\n", resp.StatusCode, body, resp.Header)
289340
return 1
290341
}
291342

0 commit comments

Comments
 (0)