-
Notifications
You must be signed in to change notification settings - Fork 44
/
server_utils.go
409 lines (340 loc) · 10.5 KB
/
server_utils.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package instance
import (
"bytes"
"fmt"
"io"
"net/http"
"time"
"github.com/scaleway/scaleway-sdk-go/api/marketplace/v1"
"github.com/scaleway/scaleway-sdk-go/internal/async"
"github.com/scaleway/scaleway-sdk-go/internal/errors"
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/scaleway/scaleway-sdk-go/validation"
)
const (
defaultTimeout = 5 * time.Minute
defaultRetryInterval = 5 * time.Second
)
// CreateServer creates a server.
func (s *API) CreateServer(req *CreateServerRequest, opts ...scw.RequestOption) (*CreateServerResponse, error) {
// If image is not a UUID we try to fetch it from marketplace.
if req.Image != "" && !validation.IsUUID(req.Image) {
apiMarketplace := marketplace.NewAPI(s.client)
imageID, err := apiMarketplace.GetLocalImageIDByLabel(&marketplace.GetLocalImageIDByLabelRequest{
ImageLabel: req.Image,
Zone: req.Zone,
CommercialType: req.CommercialType,
})
if err != nil {
return nil, err
}
req.Image = imageID
}
return s.createServer(req, opts...)
}
// UpdateServer updates a server.
//
// Note: Implementation is thread-safe.
func (s *API) UpdateServer(req *UpdateServerRequest, opts ...scw.RequestOption) (*UpdateServerResponse, error) {
defer lockServer(req.Zone, req.ServerID).Unlock()
return s.updateServer(req, opts...)
}
// WaitForServerRequest is used by WaitForServer method.
type WaitForServerRequest struct {
ServerID string
Zone scw.Zone
Timeout *time.Duration
RetryInterval *time.Duration
}
// WaitForServer wait for the server to be in a "terminal state" before returning.
// This function can be used to wait for a server to be started for example.
func (s *API) WaitForServer(req *WaitForServerRequest, opts ...scw.RequestOption) (*Server, error) {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
terminalStatus := map[ServerState]struct{}{
ServerStateStopped: {},
ServerStateStoppedInPlace: {},
ServerStateLocked: {},
ServerStateRunning: {},
}
server, err := async.WaitSync(&async.WaitSyncConfig{
Get: func() (interface{}, bool, error) {
res, err := s.GetServer(&GetServerRequest{
ServerID: req.ServerID,
Zone: req.Zone,
}, opts...)
if err != nil {
return nil, false, err
}
_, isTerminal := terminalStatus[res.Server.State]
return res.Server, isTerminal, err
},
Timeout: timeout,
IntervalStrategy: async.LinearIntervalStrategy(retryInterval),
})
if err != nil {
return nil, errors.Wrap(err, "waiting for server failed")
}
return server.(*Server), nil
}
// ServerActionAndWaitRequest is used by ServerActionAndWait method.
type ServerActionAndWaitRequest struct {
ServerID string
Zone scw.Zone
Action ServerAction
// Timeout: maximum time to wait before (default: 5 minutes)
Timeout *time.Duration
RetryInterval *time.Duration
}
// ServerActionAndWait start an action and wait for the server to be in the correct "terminal state"
// expected by this action.
func (s *API) ServerActionAndWait(req *ServerActionAndWaitRequest, opts ...scw.RequestOption) error {
timeout := defaultTimeout
if req.Timeout != nil {
timeout = *req.Timeout
}
retryInterval := defaultRetryInterval
if req.RetryInterval != nil {
retryInterval = *req.RetryInterval
}
_, err := s.ServerAction(&ServerActionRequest{
Zone: req.Zone,
ServerID: req.ServerID,
Action: req.Action,
}, opts...)
if err != nil {
return err
}
finalServer, err := s.WaitForServer(&WaitForServerRequest{
Zone: req.Zone,
ServerID: req.ServerID,
Timeout: &timeout,
RetryInterval: &retryInterval,
}, opts...)
if err != nil {
return err
}
// check the action was properly executed
expectedState := ServerState("unknown")
switch req.Action {
case ServerActionPoweron, ServerActionReboot:
expectedState = ServerStateRunning
case ServerActionPoweroff:
expectedState = ServerStateStopped
case ServerActionStopInPlace:
expectedState = ServerStateStoppedInPlace
}
// backup can be performed from any state
if expectedState != ServerState("unknown") && finalServer.State != expectedState {
return errors.New("expected state %s but found %s: %s", expectedState, finalServer.State, finalServer.StateDetail)
}
return nil
}
// GetServerTypeRequest is used by GetServerType.
type GetServerTypeRequest struct {
Zone scw.Zone
Name string
}
// GetServerType get server type info by it's name.
func (s *API) GetServerType(req *GetServerTypeRequest) (*ServerType, error) {
res, err := s.ListServersTypes(&ListServersTypesRequest{
Zone: req.Zone,
}, scw.WithAllPages())
if err != nil {
return nil, err
}
if serverType, exist := res.Servers[req.Name]; exist {
return serverType, nil
}
return nil, errors.New("could not find server type %q", req.Name)
}
// GetServerUserDataRequest is used by GetServerUserData method.
type GetServerUserDataRequest struct {
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
// Key defines the user data key to get.
Key string `json:"-"`
}
// GetServerUserData gets the content of a user data on a server for the given key.
func (s *API) GetServerUserData(req *GetServerUserDataRequest, opts ...scw.RequestOption) (io.Reader, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.Key) == "" {
return nil, errors.New("field Key cannot be empty in request")
}
scwReq := &scw.ScalewayRequest{
Method: "GET",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/user_data/" + fmt.Sprint(req.Key),
Headers: http.Header{},
}
res := &bytes.Buffer{}
err = s.client.Do(scwReq, res, opts...)
if err != nil {
return nil, err
}
return res, nil
}
// SetServerUserDataRequest is used by SetServerUserData method.
type SetServerUserDataRequest struct {
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
// Key defines the user data key to set.
Key string `json:"-"`
// Content defines the data to set.
Content io.Reader
}
// SetServerUserData sets the content of a user data on a server for the given key.
func (s *API) SetServerUserData(req *SetServerUserDataRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
if fmt.Sprint(req.Key) == "" {
return errors.New("field Key cannot be empty in request")
}
if req.Content == nil {
return errors.New("field Content cannot be nil in request")
}
scwReq := &scw.ScalewayRequest{
Method: "PATCH",
Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/user_data/" + fmt.Sprint(req.Key),
Headers: http.Header{},
}
err = scwReq.SetBody(req.Content)
if err != nil {
return err
}
err = s.client.Do(scwReq, nil, opts...)
if err != nil {
return err
}
return nil
}
// GetAllServerUserDataRequest is used by GetAllServerUserData method.
type GetAllServerUserDataRequest struct {
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
}
// GetAllServerUserDataResponse is used by GetAllServerUserData method.
type GetAllServerUserDataResponse struct {
UserData map[string]io.Reader `json:"-"`
}
// GetAllServerUserData gets all user data on a server.
func (s *API) GetAllServerUserData(req *GetAllServerUserDataRequest, opts ...scw.RequestOption) (*GetAllServerUserDataResponse, error) {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return nil, errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return nil, errors.New("field ServerID cannot be empty in request")
}
// get all user data keys
allUserDataRes, err := s.ListServerUserData(&ListServerUserDataRequest{
Zone: req.Zone,
ServerID: req.ServerID,
})
if err != nil {
return nil, err
}
res := &GetAllServerUserDataResponse{
UserData: make(map[string]io.Reader, len(allUserDataRes.UserData)),
}
// build a map with all user data
for _, key := range allUserDataRes.UserData {
value, err := s.GetServerUserData(&GetServerUserDataRequest{
Zone: req.Zone,
ServerID: req.ServerID,
Key: key,
})
if err != nil {
return nil, err
}
res.UserData[key] = value
}
return res, nil
}
// SetAllServerUserDataRequest is used by SetAllServerUserData method.
type SetAllServerUserDataRequest struct {
Zone scw.Zone `json:"-"`
ServerID string `json:"-"`
// UserData defines all user data that will be set to the server.
// This map is idempotent, it means that all the current data will be overwritten and
// all keys not present in this map will be deleted.. All data will be removed if this map is nil.
UserData map[string]io.Reader `json:"-"`
}
// SetAllServerUserData sets all user data on a server.
func (s *API) SetAllServerUserData(req *SetAllServerUserDataRequest, opts ...scw.RequestOption) error {
var err error
if req.Zone == "" {
defaultZone, _ := s.client.GetDefaultZone()
req.Zone = defaultZone
}
if fmt.Sprint(req.Zone) == "" {
return errors.New("field Zone cannot be empty in request")
}
if fmt.Sprint(req.ServerID) == "" {
return errors.New("field ServerID cannot be empty in request")
}
// get all current user data keys
allUserDataRes, err := s.ListServerUserData(&ListServerUserDataRequest{
Zone: req.Zone,
ServerID: req.ServerID,
})
if err != nil {
return err
}
// delete all current user data
for _, key := range allUserDataRes.UserData {
_, exist := req.UserData[key]
if exist {
continue
}
err := s.DeleteServerUserData(&DeleteServerUserDataRequest{
Zone: req.Zone,
ServerID: req.ServerID,
Key: key,
})
if err != nil {
return err
}
}
// set all new user data
for key, value := range req.UserData {
err := s.SetServerUserData(&SetServerUserDataRequest{
Zone: req.Zone,
ServerID: req.ServerID,
Key: key,
Content: value,
})
if err != nil {
return err
}
}
return nil
}