This repository has been archived by the owner on Sep 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreator_host_health_check_fetcher.go
95 lines (77 loc) · 2.14 KB
/
creator_host_health_check_fetcher.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
85
86
87
88
89
90
91
92
93
94
95
package audiusclient
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/http/httptrace"
"time"
)
type creatorHostHealthCheckFetcher struct {
appName string
}
func NewCreatorHostHealthCheckFetcher(appName string) *creatorHostHealthCheckFetcher {
return &creatorHostHealthCheckFetcher{
appName: appName,
}
}
type creatorHostHealtcheckData struct {
ServiceProviderID int64 `json:"spID"`
ServiceProviderOwnerWallet string `json:"spOwnerWallet"`
IsRegisteredOnURSM bool `json:"isRegisteredOnURSM"`
SelectedDiscoveryProvider string `json:"selectedDiscoveryProvider"`
CreatorNodeEndpoint string `json:"creatorNodeEndpoint"`
Git string `json:"git"`
Service string `json:"service"`
Version string `json:"version"`
Healthy bool `json:"healthy"`
}
type fetchCreatorHostHealthCheckResponseType struct {
Data creatorHostHealtcheckData
}
func (f creatorHostHealthCheckFetcher) FetchHostHealthCheck(host string) (time.Duration, error) {
// Create the request:
req, err := http.NewRequest("GET", host, nil)
if err != nil {
return 0, err
}
// Add the health check path:
req.URL.Path = "/health_check"
// Add the trace to the request:
startTime := time.Now()
var endTime time.Time
trace := &httptrace.ClientTrace{
GotFirstResponseByte: func() {
endTime = time.Now()
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
// Make the request:
res, err := httpClient.Do(req)
if err != nil {
return 0, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
// Parse the error:
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return 0, err
}
err = errors.New(string(body))
return 0, err
}
// Calculate the time it took to receive the first byte:
duration := endTime.Sub(startTime)
// Decode the body:
var fetchCreatorHostHealthCheckResponse fetchCreatorHostHealthCheckResponseType
err = json.NewDecoder(res.Body).Decode(&fetchCreatorHostHealthCheckResponse)
if err != nil {
return 0, err
}
// Check if the host is healthy:
if !fetchCreatorHostHealthCheckResponse.Data.Healthy {
return 0, errors.New("host is unhealthy")
}
return duration, nil
}