forked from ClusterHQ/flocker-go
-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
376 lines (314 loc) · 10.5 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
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(options *CreateDatasetOptions) (*DatasetState, error)
DeleteDataset(datasetID string) error
GetDatasetState(datasetID string) (*DatasetState, error)
GetDatasetID(metaName string) (datasetID string, err error)
GetPrimaryUUID() (primaryUUID string, err error)
ListNodes() (nodes []NodeState, 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
}
var _ Clientable = &Client{}
// 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)
}
// delete performs a delete request with the indicated payload
func (c Client) delete(url string, payload interface{}) (*http.Response, error) {
return c.request("DELETE", 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 {
Deleted bool `json:"deleted"`
Primary string `json:"primary"`
DatasetID string `json:"dataset_id,omitempty"`
MaximumSize json.Number `json:"maximum_size,omitempty"`
Metadata metadataPayload `json:"metadata,omitempty"`
}
type CreateDatasetOptions struct {
Primary string `json:"primary"`
DatasetID string `json:"dataset_id,omitempty"`
MaximumSize int64 `json:"maximum_size,omitempty"`
Metadata map[string]string `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 NodeState 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
}
// ListNodes returns a list of dataset agent nodes from Flocker Control Service
func (c *Client) ListNodes() (nodes []NodeState, err error) {
resp, err := c.get(c.getURL("state/nodes"))
if err != nil {
return []NodeState{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return []NodeState{}, fmt.Errorf("Expected: {1,2}xx listing nodes, got: %d", resp.StatusCode)
}
err = json.NewDecoder(resp.Body).Decode(&nodes)
if err != nil {
return []NodeState{}, err
}
return nodes, err
}
// GetPrimaryUUID returns the UUID of the primary Flocker Control Service for
// the given host.
func (c Client) GetPrimaryUUID() (uuid string, err error) {
states, err := c.ListNodes()
if err != nil {
return "", err
}
for _, s := range states {
if s.Host == c.clientIP {
return s.UUID, nil
}
}
return "", fmt.Errorf("No node found with IP '%s', available nodes %+v", c.clientIP, states)
}
// DeleteDataset performs a delete request to the given datasetID
func (c *Client) DeleteDataset(datasetID string) error {
url := c.getURL(fmt.Sprintf("configuration/datasets/%s", datasetID))
resp, err := c.delete(url, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("Expected: {1,2}xx deleting the dataset %s, got: %d", datasetID, resp.StatusCode)
}
return nil
}
// 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. If it already exists an error is returned
3. If it didn't previously exist, wait for it to be ready
*/
func (c *Client) CreateDataset(options *CreateDatasetOptions) (datasetState *DatasetState, err error) {
// 1) Find the primary Flocker UUID
// Note: it could be cached, but doing this query we health check it
if options.Primary == "" {
options.Primary, err = c.GetPrimaryUUID()
if err != nil {
return nil, err
}
}
if options.MaximumSize == 0 {
options.MaximumSize, _ = c.maximumSize.Int64()
}
resp, err := c.post(c.getURL("configuration/datasets"), options)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// 2) 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
}
// 3) 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 {
var strErrDel string
s, err := c.GetDatasetState(p.DatasetID)
if err == nil {
return s, nil
} else if err != errStateNotFound {
errDel := c.DeleteDataset(p.DatasetID)
if errDel != nil {
strErrDel = fmt.Sprintf(", deletion of dataset failed with %s", errDel)
}
return nil, fmt.Errorf("Flocker API error during dataset creation (datasetID %s): %s%s", p.DatasetID, err, strErrDel)
}
select {
case <-timeoutChan:
errDel := c.DeleteDataset(p.DatasetID)
if errDel != nil {
strErrDel = fmt.Sprintf(", deletion of dataset failed with %s", errDel)
}
return nil, fmt.Errorf("Flocker API timeout during dataset creation (datasetID %s): %s%s", p.DatasetID, err, strErrDel)
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 && c.Deleted == false {
return c.DatasetID, nil
}
}
return "", errConfigurationNotFound
}
return "", err
}