-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
client.go
323 lines (270 loc) · 8.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
315
316
317
318
319
320
321
322
323
package flocker
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
// From https://github.com/ClusterHQ/flocker-docker-plugin/blob/master/flockerdockerplugin/adapter.py#L18
const defaultVolumeSize = json.Number("107374182400")
var (
// A volume can take a long time to be available, if we don't want
// Kubernetes to wait forever we need to stop trying after some time, that
// time is defined here
timeoutWaitingForVolume = 2 * time.Minute
tickerWaitingForVolume = 5 * time.Second
errStateNotFound = errors.New("State not found by Dataset ID")
errConfigurationNotFound = errors.New("Configuration not found by Name")
errFlockerControlServiceHost = errors.New("The volume config must have a key CONTROL_SERVICE_HOST defined in the OtherAttributes field")
errFlockerControlServicePort = errors.New("The volume config must have a key CONTROL_SERVICE_PORT defined in the OtherAttributes field")
errVolumeAlreadyExists = errors.New("The volume already exists")
errVolumeDoesNotExist = errors.New("The volume does not exist")
errUpdatingDataset = errors.New("It was impossible to update the dataset")
)
// Clientable exposes the needed methods to implement your own Flocker Client.
type Clientable interface {
CreateDataset(metaName string) (*DatasetState, error)
GetDatasetState(datasetID string) (*DatasetState, error)
GetDatasetID(metaName string) (datasetID string, err error)
GetPrimaryUUID() (primaryUUID string, err error)
UpdatePrimaryForDataset(primaryUUID, datasetID string) (*DatasetState, error)
}
// Client is a default Flocker Client.
type Client struct {
*http.Client
schema string
host string
port int
version string
clientIP string
maximumSize json.Number
}
// NewClient creates a wrapper over http.Client to communicate with the flocker control service.
func NewClient(host string, port int, clientIP string, caCertPath, keyPath, certPath string) (*Client, error) {
client, err := newTLSClient(caCertPath, keyPath, certPath)
if err != nil {
return nil, err
}
return &Client{
Client: client,
schema: "https",
host: host,
port: port,
version: "v1",
maximumSize: defaultVolumeSize,
clientIP: clientIP,
}, nil
}
/*
request do a request using the http.Client embedded to the control service
and returns the response or an error in case it happens.
Note: you will need to deal with the response body call to Close if you
don't want to deal with problems later.
*/
func (c Client) request(method, url string, payload interface{}) (*http.Response, error) {
var (
b []byte
err error
)
if method == "POST" { // Just allow payload on POST
b, err = json.Marshal(payload)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, url, bytes.NewBuffer(b))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
// REMEMBER TO CLOSE THE BODY IN THE OUTSIDE FUNCTION
return c.Do(req)
}
// post performs a post request with the indicated payload
func (c Client) post(url string, payload interface{}) (*http.Response, error) {
return c.request("POST", url, payload)
}
// get performs a get request
func (c Client) get(url string) (*http.Response, error) {
return c.request("GET", url, nil)
}
// getURL returns a full URI to the control service
func (c Client) getURL(path string) string {
return fmt.Sprintf("%s://%s:%d/%s/%s", c.schema, c.host, c.port, c.version, path)
}
type configurationPayload struct {
Primary string `json:"primary"`
DatasetID string `json:"dataset_id,omitempty"`
MaximumSize json.Number `json:"maximum_size,omitempty"`
Metadata metadataPayload `json:"metadata,omitempty"`
}
type metadataPayload struct {
Name string `json:"name,omitempty"`
}
type DatasetState struct {
Path string `json:"path"`
DatasetID string `json:"dataset_id"`
Primary string `json:"primary,omitempty"`
MaximumSize json.Number `json:"maximum_size,omitempty"`
}
type datasetStatePayload struct {
*DatasetState
}
type nodeStatePayload struct {
UUID string `json:"uuid"`
Host string `json:"host"`
}
// findIDInConfigurationsPayload returns the datasetID if it was found in the
// configurations payload, otherwise it will return an error.
func (c Client) findIDInConfigurationsPayload(body io.ReadCloser, name string) (datasetID string, err error) {
var configurations []configurationPayload
if err = json.NewDecoder(body).Decode(&configurations); err == nil {
for _, r := range configurations {
if r.Metadata.Name == name {
return r.DatasetID, nil
}
}
return "", errConfigurationNotFound
}
return "", err
}
// GetPrimaryUUID returns the UUID of the primary Flocker Control Service for
// the given host.
func (c Client) GetPrimaryUUID() (uuid string, err error) {
resp, err := c.get(c.getURL("state/nodes"))
if err != nil {
return "", err
}
defer resp.Body.Close()
var states []nodeStatePayload
if err = json.NewDecoder(resp.Body).Decode(&states); err == nil {
for _, s := range states {
if s.Host == c.clientIP {
return s.UUID, nil
}
}
return "", errStateNotFound
}
return "", err
}
// GetDatasetState performs a get request to get the state of the given datasetID, if
// something goes wrong or the datasetID was not found it returns an error.
func (c Client) GetDatasetState(datasetID string) (*DatasetState, error) {
resp, err := c.get(c.getURL("state/datasets"))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var states []datasetStatePayload
if err = json.NewDecoder(resp.Body).Decode(&states); err == nil {
for _, s := range states {
if s.DatasetID == datasetID {
return s.DatasetState, nil
}
}
return nil, errStateNotFound
}
return nil, err
}
/*
CreateDataset creates a volume in Flocker, waits for it to be ready and
returns the dataset id.
This process is a little bit complex but follows this flow:
1. Find the Flocker Control Service UUID
2. Try to create the dataset
3. If it already exists an error is returned
4. If it didn't previously exist, wait for it to be ready
*/
func (c Client) CreateDataset(metaName string) (*DatasetState, error) {
// 1) Find the primary Flocker UUID
// Note: it could be cached, but doing this query we health check it
primary, err := c.GetPrimaryUUID()
if err != nil {
return nil, err
}
// 2) Try to create the dataset in the given Primary
payload := configurationPayload{
Primary: primary,
MaximumSize: json.Number(c.maximumSize),
Metadata: metadataPayload{
Name: metaName,
},
}
resp, err := c.post(c.getURL("configuration/datasets"), payload)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// 3) Return if the dataset was previously created
if resp.StatusCode == http.StatusConflict {
return nil, errVolumeAlreadyExists
}
if resp.StatusCode >= 300 {
return nil, fmt.Errorf("Expected: {1,2}xx creating the volume, got: %d", resp.StatusCode)
}
var p configurationPayload
if err := json.NewDecoder(resp.Body).Decode(&p); err != nil {
return nil, err
}
// 4) Wait until the dataset is ready for usage. In case it never gets
// ready there is a timeoutChan that will return an error
timeoutChan := time.NewTimer(timeoutWaitingForVolume).C
tickChan := time.NewTicker(tickerWaitingForVolume).C
for {
if s, err := c.GetDatasetState(p.DatasetID); err == nil {
return s, nil
} else if err != errStateNotFound {
return nil, err
}
select {
case <-timeoutChan:
return nil, err
case <-tickChan:
break
}
}
}
// UpdatePrimaryForDataset will update the Primary for the given dataset
// returning the current DatasetState.
func (c Client) UpdatePrimaryForDataset(newPrimaryUUID, datasetID string) (*DatasetState, error) {
payload := struct {
Primary string `json:"primary"`
}{
Primary: newPrimaryUUID,
}
url := c.getURL(fmt.Sprintf("configuration/datasets/%s", datasetID))
resp, err := c.post(url, payload)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return nil, errUpdatingDataset
}
var s DatasetState
if err := json.NewDecoder(resp.Body).Decode(&s); err != nil {
return nil, err
}
return &s, nil
}
// GetDatasetID will return the DatasetID found for the given metadata name.
func (c Client) GetDatasetID(metaName string) (datasetID string, err error) {
resp, err := c.get(c.getURL("configuration/datasets"))
if err != nil {
return "", err
}
defer resp.Body.Close()
var configurations []configurationPayload
if err = json.NewDecoder(resp.Body).Decode(&configurations); err == nil {
for _, c := range configurations {
if c.Metadata.Name == metaName {
return c.DatasetID, nil
}
}
return "", errConfigurationNotFound
}
return "", err
}