/
client.go
314 lines (243 loc) · 6.63 KB
/
client.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package sidecar
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/go-resty/resty/v2"
"github.com/google/uuid"
"github.com/instaclustr/cassandra-operator/pkg/common/nodestate"
corev1 "k8s.io/api/core/v1"
logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
)
const (
accept = "Accept"
applicationJson = "application/json; charset=utf-8"
EndpointOperations = "operations"
EndpointStatus = "status"
)
var log = logf.Log.WithName("SidecarClient")
var DefaultSidecarClientOptions = ClientOptions{Port: 4567, Secure: false}
type Client struct {
Host string
Options *ClientOptions
restyClient *resty.Client
testResponse *resty.Response
testMode bool
}
type ClientOptions struct {
Secure bool
Port int32
Timeout time.Duration
}
func NewSidecarClient(host string, options *ClientOptions) *Client {
if options == nil {
options = &ClientOptions{
Secure: true,
}
}
if options.Timeout == 0 {
options.Timeout = 1 * time.Minute
}
client := &Client{}
client.Host = host
client.Options = options
restyClient := resty.New()
var protocol = "https"
if !client.Options.Secure {
protocol = "http"
}
var port = ""
if options.Port != 0 {
port = ":" + strconv.FormatInt(int64(options.Port), 10)
}
restyClient.SetHostURL(fmt.Sprintf("%s://%s%s", protocol, client.Host, port))
restyClient.SetTimeout(client.Options.Timeout)
client.restyClient = restyClient
return client
}
func SidecarClients(pods []corev1.Pod, clientOptions *ClientOptions) map[*corev1.Pod]*Client {
podClients := make(map[*corev1.Pod]*Client)
for i, pod := range pods {
podClients[&pods[i]] = NewSidecarClient(pod.Status.PodIP, clientOptions)
}
return podClients
}
func ClientFromPods(podsClients map[*corev1.Pod]*Client, pod corev1.Pod) *Client {
for key, value := range podsClients {
if key.Name == pod.Name {
return value
}
}
return nil
}
type HttpResponse struct {
status int
err error
responseBody string
}
func (e *HttpResponse) Error() string {
if e.status != 0 {
return fmt.Sprintf("Operation was not successful, response code %d", e.status)
}
return fmt.Sprintf("Operation was errorneous: %s", e.err)
}
func (client *Client) Status() (*nodestate.Status, error) {
if r, err := client.performRequest(EndpointStatus, http.MethodGet, nil); responseInvalid(r, err) {
return nil, err
} else {
body, err := readBody(r)
if err != nil {
return nil, err
}
if status, err := unmarshallBody(body, r, &nodestate.Status{}); err == nil {
return status.(*nodestate.Status), nil
} else {
return nil, err
}
}
}
func (client *Client) GetOperation(id uuid.UUID) (*OperationResponse, error) {
if id == uuid.Nil {
return nil, fmt.Errorf("getOperation must get a valid id")
}
endpoint := EndpointOperations + "/" + id.String()
if r, err := client.performRequest(endpoint, http.MethodGet, nil); responseInvalid(r, err) {
return nil, err
} else {
body, err := readBody(r)
if err != nil {
return nil, err
}
if status, err := unmarshallBody(body, r, &OperationResponse{}); err != nil {
return nil, err
} else {
return status.(*OperationResponse), nil
}
}
}
func (client *Client) GetOperations() (*Operations, error) {
return client.GetFilteredOperations(nil)
}
func (client *Client) GetFilteredOperations(filter *OperationsFilter) (*Operations, error) {
endpoint := EndpointOperations
if filter != nil {
endpoint = filter.buildFilteredEndpoint(endpoint)
}
if r, err := client.performRequest(endpoint, http.MethodGet, nil); responseInvalid(r, err) {
return nil, err
} else {
body, err := readBody(r)
if err != nil {
return nil, err
}
if response, err := unmarshallBody(body, r, &Operations{}); err == nil {
return response.(*Operations), nil
} else {
return nil, err
}
}
}
func FilterOperations(ops Operations, kind Kind) (result []interface{}, err error) {
result = make([]interface{}, 0)
var op interface{}
for _, item := range ops {
if op, err = ParseOperation(item, kind); err != nil {
log.Error(err, "Error parsing operation", &map[string]interface{}{"Operation": op})
continue
}
result = append(result, op)
}
return result, nil
}
func ParseOperation(operation OperationResponse, kind Kind) (interface{}, error) {
var op interface{}
if operation["progress"] == "NaN" {
operation["progress"] = 0.0
}
if operation["type"].(string) == _KindValueToName[kind] {
switch kind {
case cleanup:
op = &CleanupOperationResponse{}
case upgradesstables:
op = &UpgradeSSTablesResponse{}
case decommission:
op = &DecommissionOperationResponse{}
case backup:
op = &BackupResponse{}
case rebuild:
op = &RebuildResponse{}
case scrub:
op = &ScrubResponse{}
case noop:
return nil, fmt.Errorf("no op")
}
if body, err := json.Marshal(operation); err != nil {
return nil, err
} else if err := json.Unmarshal(body, op); err != nil {
return nil, err
}
}
return op, nil
}
func responseInvalid(r interface{}, err error) bool {
return r == nil || err != nil
}
func (client *Client) performRequest(endpoint string, verb string, requestBody interface{}) (response *resty.Response, err error) {
if client.testMode {
return client.testResponse, nil
}
request := client.restyClient.R().SetHeader(accept, applicationJson)
if verb == http.MethodPost {
response, err = request.SetBody(requestBody).Post(endpoint)
} else if verb == http.MethodGet {
response, err = request.Get(endpoint)
}
if err != nil {
return nil, &HttpResponse{
err: err,
}
}
return
}
func parseOperationId(response *resty.Response) (uuid.UUID, error) {
ids := strings.Split(response.Header().Get("Location"), "/")
location := ids[len(ids)-1]
id, err := uuid.Parse(location)
if err != nil {
return uuid.Nil, err
}
return id, nil
}
func readBody(response *resty.Response) (*[]byte, error) {
rawBody := response.Body()
return &rawBody, nil
}
func unmarshallBody(body *[]byte, response *resty.Response, responseEnvelope interface{}) (interface{}, error) {
if err := json.Unmarshal(*body, responseEnvelope); err != nil {
return nil, &HttpResponse{
err: err,
responseBody: string(*body),
}
}
if !response.IsSuccess() {
return nil, &HttpResponse{
status: response.StatusCode(),
}
}
return responseEnvelope, nil
}
func (client *Client) StartOperation(request OperationRequest) (uuid.UUID, error) {
request.Init()
if r, err := client.performRequest(EndpointOperations, http.MethodPost, request); responseInvalid(r, err) {
return uuid.Nil, err
} else {
operationId, err := parseOperationId(r)
if err != nil {
return uuid.Nil, err
}
return operationId, nil
}
}