-
Notifications
You must be signed in to change notification settings - Fork 1
/
readiness_prober.go
84 lines (69 loc) · 2.16 KB
/
readiness_prober.go
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
package builder
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"time"
"github.com/rs/zerolog/log"
)
func WaitForReadinessHttpGet(ctx context.Context, scheme, host string, port int, path, hostname string, timeoutSeconds int) error {
if scheme == "" {
return fmt.Errorf("Scheme is empty, should be either http or https")
}
if host == "" {
return fmt.Errorf("Host is empty, should be the name (or alias) of the service")
}
if port <= 0 {
return fmt.Errorf("Port should be larger than zero")
}
if path == "" {
return fmt.Errorf("Path is empty, should be at least / or a path to a readiness endpoint")
}
if timeoutSeconds <= 0 {
return fmt.Errorf("Timeout should be larger than zero")
}
readinessURL := fmt.Sprintf("%v://%v:%v%v", scheme, host, port, path)
log.Info().Msgf("Running readiness probe against %v with host header %v", readinessURL, hostname)
// create http client and request
var httpClient = &http.Client{
Timeout: time.Second * 2,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
request, err := http.NewRequestWithContext(ctx, "GET", readinessURL, nil)
if err != nil {
return err
}
if hostname != "" && hostname != "host" && hostname != host {
request.Header.Add("Host", hostname)
}
ready := make(chan bool, 1)
quit := make(chan bool)
go func(request *http.Request) {
// perform request
resp, err := httpClient.Do(request)
// keep sending request until it succeeds or the total timeout has send a quit signal
for err != nil || resp.StatusCode != http.StatusOK {
log.Warn().Err(err).Msgf("Readiness probe against %v failed", request.URL)
time.Sleep(1 * time.Second)
select {
case <-quit:
return
default:
resp, err = httpClient.Do(request)
}
}
// successful request
ready <- true
}(request)
select {
case <-ready:
log.Info().Msgf("Readiness probe against %v with host header %v succeeded in time", readinessURL, hostname)
case <-time.After(time.Duration(timeoutSeconds) * time.Second):
quit <- true
return fmt.Errorf("Readiness probe against %v with host header %v did not succeed in %vs", readinessURL, hostname, timeoutSeconds)
}
return nil
}