-
Notifications
You must be signed in to change notification settings - Fork 0
/
drove.go
255 lines (227 loc) · 6.59 KB
/
drove.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package drovedns
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
const (
FETCH_APP_TIMEOUT time.Duration = time.Duration(5) * time.Second
FETCH_EVENTS_TIMEOUT time.Duration = time.Duration(5) * time.Second
PING_TIMEOUT time.Duration = time.Duration(5) * time.Second
)
type IDroveClient interface {
FetchApps() (*DroveAppsResponse, error)
FetchRecentEvents(syncPoint *CurrSyncPoint) (*DroveEventSummary, error)
PollEvents(callback func(event *DroveEventSummary))
}
type DroveClient struct {
EndpointMutex sync.RWMutex
Endpoint []EndpointStatus
Leader *LeaderController
AuthConfig *DroveAuthConfig
client *http.Client
}
func NewDroveClient(config DroveConfig) DroveClient {
controllerEndpoints := strings.Split(config.Endpoint, ",")
endpoints := make([]EndpointStatus, len(controllerEndpoints))
for i, e := range controllerEndpoints {
endpoints[i] = EndpointStatus{e, true, ""}
}
tr := &http.Transport{MaxIdleConnsPerHost: 10, TLSClientConfig: &tls.Config{InsecureSkipVerify: config.SkipSSL}}
httpClient := &http.Client{
Timeout: 0 * time.Second,
Transport: tr,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
return DroveClient{Endpoint: endpoints, AuthConfig: &config.AuthConfig, client: httpClient}
}
func (c *DroveClient) Init() error {
c.updateHealth()
c.endpointHealth()
_, err := c.endpoint()
return err
}
func (c *DroveClient) getRequest(path string, timeout time.Duration, obj any) error {
host, err := c.endpoint()
if err != nil {
return err
}
endpoint := host + path
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", endpoint, nil)
if err != nil {
return err
}
setHeaders(*c.AuthConfig, req)
resp, err := c.client.Do(req)
if err != nil {
DroveApiRequests.WithLabelValues("err", "GET", host).Inc()
return err
}
DroveApiRequests.WithLabelValues(strconv.Itoa(resp.StatusCode), "GET", host).Inc()
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(obj)
if err != nil {
return err
}
return nil
}
func (c *DroveClient) FetchApps() (*DroveAppsResponse, error) {
jsonapps := &DroveAppsResponse{}
err := c.getRequest("/apis/v1/endpoints", FETCH_APP_TIMEOUT, jsonapps)
return jsonapps, err
}
func (c *DroveClient) FetchRecentEvents(syncPoint *CurrSyncPoint) (*DroveEventSummary, error) {
var newEventsApiResponse = DroveEventsApiResponse{}
err := c.getRequest("/apis/v1/cluster/events/summary?lastSyncTime="+fmt.Sprint(syncPoint.LastSyncTime), FETCH_EVENTS_TIMEOUT, &newEventsApiResponse)
if err != nil {
return nil, err
}
log.Debugf("events response %+v", newEventsApiResponse)
if newEventsApiResponse.Status != "SUCCESS" {
return nil, errors.New("Events api call failed. Message: " + newEventsApiResponse.Message)
}
syncPoint.LastSyncTime = newEventsApiResponse.EventSummary.LastSyncTime
return &(newEventsApiResponse.EventSummary), nil
}
func (c *DroveClient) PollEvents(callback func(event *DroveEventSummary)) {
go func() {
syncData := CurrSyncPoint{}
refreshInterval := 2
ticker := time.NewTicker(time.Duration(refreshInterval) * time.Second)
for range ticker.C {
func() {
log.Debugf("Syncing... at %d", time.Now().UnixMilli())
syncData.Lock()
defer syncData.Unlock()
eventSummary, err := c.FetchRecentEvents(&syncData)
if err != nil {
log.Errorf("unable to sync events from drove %s", err.Error())
} else {
callback(eventSummary)
}
}()
}
}()
}
func setHeaders(config DroveAuthConfig, req *http.Request) {
req.Header.Set("Accept", "application/json")
if config.User != "" {
req.SetBasicAuth(config.User, config.Pass)
}
if config.AccessToken != "" {
req.Header.Add("Authorization", config.AccessToken)
}
}
func leaderController(endpoint string) (*LeaderController, error) {
if endpoint == "" {
return nil, fmt.Errorf("Empty leader endpoint")
}
parsedUrl, err := url.Parse(endpoint)
if err != nil {
return nil, err
}
host, port, splitErr := net.SplitHostPort(parsedUrl.Host)
if splitErr != nil {
return nil, splitErr
}
iPort, _ := strconv.Atoi(port)
return &LeaderController{
Endpoint: endpoint,
Host: host,
Port: int32(iPort),
}, nil
}
func (c *DroveClient) endpoint() (string, error) {
c.EndpointMutex.RLock()
defer c.EndpointMutex.RUnlock()
var err error = nil
if c.Leader == nil || c.Leader.Endpoint == "" {
return "", errors.New("all endpoints are down")
}
return c.Leader.Endpoint, err
}
func (c *DroveClient) refreshLeaderData() {
var endpoint string
for _, es := range c.Endpoint {
DroveControllerHealth.WithLabelValues(es.Endpoint).Set(boolToDouble(es.Healthy))
if es.Healthy {
endpoint = es.Endpoint
}
}
if c.Leader == nil || endpoint != c.Leader.Endpoint {
log.Infof("Looks like master shifted. Will resync app new [%s] old[%+v]", endpoint, c.Leader)
newLeader, err := leaderController(endpoint)
if err != nil {
log.Errorf("Leader struct generation failed %+v", err)
return
}
c.EndpointMutex.Lock()
defer c.EndpointMutex.Unlock()
c.Leader = newLeader
log.Infof("New leader being set leader %+v", c.Leader)
}
}
func (c *DroveClient) endpointHealth() {
go func() {
ticker := time.NewTicker(2 * time.Second)
for {
select {
case <-ticker.C:
shouldReturn := c.updateHealth()
if shouldReturn {
return
}
}
}
}()
}
func (c *DroveClient) updateHealth() bool {
log.Debugf("Updating health %+v", c.Endpoint)
for i, es := range c.Endpoint {
ctx, cancel := context.WithTimeout(context.Background(), PING_TIMEOUT)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", es.Endpoint+"/apis/v1/ping", nil)
if err != nil {
log.Errorf("an error occurred creating endpoint health request %s %s", es.Endpoint, err.Error())
c.Endpoint[i].Healthy = false
c.Endpoint[i].Message = err.Error()
continue
}
setHeaders(*c.AuthConfig, req)
resp, err := c.client.Do(req)
if err != nil {
log.Errorf("endpoint is down %s %s", es.Endpoint, err)
c.Endpoint[i].Healthy = false
c.Endpoint[i].Message = err.Error()
continue
}
resp.Body.Close()
if resp.StatusCode != 200 {
if resp.StatusCode != 400 {
log.Errorf("Unknown responsecode from drove %d %+v", resp.StatusCode, resp)
}
c.Endpoint[i].Healthy = false
c.Endpoint[i].Message = resp.Status
continue
}
c.Endpoint[i].Healthy = true
c.Endpoint[i].Message = "OK"
log.Debugf("Endpoint is healthy host %s", es.Endpoint)
}
c.refreshLeaderData()
return false
}