-
Notifications
You must be signed in to change notification settings - Fork 0
/
profitbricks.go
516 lines (433 loc) · 12 KB
/
profitbricks.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
package profitbricks
import (
"errors"
"fmt"
"time"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnflag"
"github.com/docker/machine/libmachine/ssh"
"github.com/docker/machine/libmachine/state"
"github.com/profitbricks/profitbricks-sdk-go"
"io/ioutil"
"strings"
)
type Driver struct {
*drivers.BaseDriver
URL string
Username string
Password string
ServerId string
Ram int
Cores int
SSHKey string
DatacenterId string
DiskSize int
DiskType string
Image string
Size int
Location string
}
const (
defaultImage = "Ubuntu-15.10-server-2016-04-01"
defaultRegion = "us/lasdev"
defaultSize = 10
waitCount = 5
)
func (d *Driver) GetCreateFlags() []mcnflag.Flag {
return []mcnflag.Flag{
mcnflag.StringFlag{
EnvVar: "PROFITBRICKS_ENDPOINT",
Name: "profitbricks-endpoint",
Value: "https://api.profitbricks.com/rest/v2",
Usage: "profitbricks API endpoint",
},
mcnflag.StringFlag{
EnvVar: "PROFITBRICKS_USERNAME",
Name: "profitbricks-username",
Usage: "profitbricks username",
},
mcnflag.StringFlag{
EnvVar: "PROFITBRICKS_PASSWORD",
Name: "profitbricks-password",
Usage: "profitbricks password",
},
mcnflag.IntFlag{
EnvVar: "PROFITBRICKS_CORES",
Name: "profitbricks-cores",
Value: 4,
Usage: "profitbricks cores (2, 3, 4, 5, 6, etc.)",
},
mcnflag.IntFlag{
EnvVar: "PROFITBRICKS_RAM",
Name: "profitbricks-ram",
Value: 2048,
Usage: "profitbricks ram (1024, 2048, 3072, 4096, etc.)",
},
mcnflag.IntFlag{
EnvVar: "PROFITBRICKS_DISK_SIZE",
Name: "profitbricks-disk-size",
Value: 50,
Usage: "profitbricks disk size (10, 50, 100, 200, 400)",
},
mcnflag.StringFlag{
EnvVar: "PROFITBRICKS_IMAGE",
Name: "profitbricks-image",
Value: "Ubuntu-15.10-server-2016-04-01",
Usage: "profitbricks image",
},
mcnflag.StringFlag{
EnvVar: "PROFITBRICKS_LOCATION",
Name: "profitbricks-location",
Value: "us/las",
Usage: "profitbricks location",
},
mcnflag.StringFlag{
EnvVar: "PROFITBRICKS_DISK_TYPE",
Name: "profitbricks-disk-type",
Value: "HDD",
Usage: "profitbricks disk type (HDD, SSD)",
},
}
}
func NewDriver(hostName, storePath string) drivers.Driver {
return &Driver{
Image: defaultImage,
Size: defaultSize,
Location: defaultRegion,
BaseDriver: &drivers.BaseDriver{
MachineName: hostName,
StorePath: storePath,
},
}
}
func (d *Driver) GetSSHHostname() (string, error) {
return d.GetIP()
}
func (d *Driver) DriverName() string {
return "profitbricks"
}
func (d *Driver) SetConfigFromFlags(flags drivers.DriverOptions) error {
d.URL = flags.String("profitbricks-endpoint")
d.Username = flags.String("profitbricks-username")
d.Password = flags.String("profitbricks-password")
d.DiskSize = flags.Int("profitbricks-disk-size")
d.Image = flags.String("profitbricks-image")
d.Cores = flags.Int("profitbricks-cores")
d.Ram = flags.Int("profitbricks-ram")
d.Location = flags.String("profitbricks-location")
d.DiskType = flags.String("profitbricks-disk-type")
d.SwarmMaster = flags.Bool("swarm-master")
d.SwarmHost = flags.String("swarm-host")
d.SwarmDiscovery = flags.String("swarm-discovery")
d.SetSwarmConfigFromFlags(flags)
if d.URL == "" {
d.URL = "https://api.profitbricks.com/rest/v2"
}
return nil
}
func (d *Driver) PreCreateCheck() error {
if d.Username == "" {
return fmt.Errorf("Please provide username as paramter --profitbricks-username or as environment variable $PROFITBRICKS_USERNAME")
}
if d.getImageId(d.Image) == "" {
return fmt.Errorf("The image %s %s %s", d.Image, d.Location, "does not exist.")
}
return nil
}
func (d *Driver) Create() error {
d.setPB()
var err error
if d.SSHKey == "" {
d.SSHKey, err = d.createSSHKey()
if err != nil {
return err
}
}
//Create a PB Datacenter
dcrequest := profitbricks.CreateDatacenterRequest{
DCProperties: profitbricks.DCProperties{
Name: d.MachineName,
Location: d.Location,
},
}
dc := profitbricks.CreateDatacenter(dcrequest)
if dc.Resp.StatusCode == 202 {
log.Info("Datacenter Created")
} else {
return errors.New("Error while creating DC: " + string(dc.Resp.Body))
}
d.DatacenterId = dc.Id
d.waitTillProvisioned(strings.Join(dc.Resp.Headers["Location"], ""))
//Create a PB Sever
serverrequest := profitbricks.CreateServerRequest{
ServerProperties: profitbricks.ServerProperties{
Name: d.MachineName,
Ram: d.Ram,
Cores: d.Cores,
},
}
server := profitbricks.CreateServer(dc.Id, serverrequest)
if server.Resp.StatusCode == 202 {
log.Info("Server Created")
} else {
log.Error("Error while creating Server: " + string(server.Resp.Body))
d.Remove()
return errors.New("Rolling back...")
}
d.waitTillProvisioned(strings.Join(server.Resp.Headers["Location"], ""))
d.Image = d.getImageId(d.Image)
if d.Image == "" {
return errors.New("Image is not provided. Exiting...")
}
volumerequest := profitbricks.CreateVolumeRequest{
VolumeProperties: profitbricks.VolumeProperties{
Size: d.DiskSize,
Name: d.MachineName,
Image: d.Image,
Type: d.DiskType,
SshKey: []string{d.SSHKey},
},
}
volume := profitbricks.CreateVolume(dc.Id, volumerequest)
if volume.Resp.StatusCode == 202 {
log.Info("Volume Created")
} else {
log.Error("Error while creating Volume: " + string(volume.Resp.Body))
d.Remove()
return errors.New("Rolling back...")
}
d.waitTillProvisioned(strings.Join(volume.Resp.Headers["Location"], ""))
attachresponse := profitbricks.AttachVolume(dc.Id, server.Id, volume.Id)
if attachresponse.Resp.StatusCode == 202 {
log.Info("Attached a volume to a server.")
} else {
log.Error("Error while attaching Volume: " + string(attachresponse.Resp.Body))
d.Remove()
return errors.New("Rolling back...")
}
d.waitTillProvisioned(strings.Join(attachresponse.Resp.Headers["Location"], ""))
lanrequest := profitbricks.CreateLanRequest{
LanProperties: profitbricks.LanProperties{
Public: true,
Name: d.MachineName,
},
}
lan := profitbricks.CreateLan(dc.Id, lanrequest)
if lan.Resp.StatusCode == 202 {
log.Info("LAN Created")
} else {
log.Error("Error while creating a LAN " + string(lan.Resp.Body))
d.Remove()
return errors.New("Rolling back...")
}
d.waitTillProvisioned(strings.Join(lan.Resp.Headers["Location"], ""))
d.ServerId = server.Id
ipblockreq := profitbricks.IPBlockReserveRequest{
IPBlockProperties: profitbricks.IPBlockProperties{
Size: 1,
Location: d.Location,
},
}
ipblockresp := profitbricks.ReserveIpBlock(ipblockreq)
if lan.Resp.StatusCode == 202 {
log.Info("IP Block Reserved")
} else {
log.Error("Error while reserving an IP Block " + string(lan.Resp.Body))
d.Remove()
return errors.New("Rolling back...")
}
d.waitTillProvisioned(strings.Join(ipblockresp.Resp.Headers["Location"], ""))
ip := ipblockresp.Properties["ips"].([]interface{})[0].(string)
if ip == "" {
log.Error("IP Address could not be assigned")
d.Remove()
return errors.New("Rolling back...")
}
nicrequest := profitbricks.NicCreateRequest{
NicProperties: profitbricks.NicProperties{
Name: d.MachineName,
Lan: lan.Id,
Ips: []string{ip},
},
}
nic := profitbricks.CreateNic(dc.Id, server.Id, nicrequest)
if nic.Resp.StatusCode == 202 {
log.Info("NIC created")
} else {
log.Error("Error while creating a NIC " + string(nic.Resp.Body))
d.Remove()
return errors.New("Rolling back...")
}
d.waitTillProvisioned(strings.Join(nic.Resp.Headers["Location"], ""))
bootVolume := profitbricks.Instance{
Properties: nil,
Entities: nil,
MetaData: nil,
}
bootVolume.Id = volume.Id
serverprops := profitbricks.ServerProperties{
BootVolume: &bootVolume,
}
serverpatchresponse := profitbricks.PatchServer(dc.Id, server.Id, serverprops)
if serverpatchresponse.Resp.StatusCode == 202 {
log.Info("Updated server's boot image")
} else {
log.Error("Error while setting Boot Volume to Server: " + string(serverpatchresponse.Resp.Body))
d.Remove()
return errors.New("Rolling back...")
}
d.waitTillProvisioned(strings.Join(serverpatchresponse.Resp.Headers["Location"], ""))
//Get server data
server = profitbricks.GetServer(dc.Id, server.Id)
d.IPAddress = server.Entities["nics"].Items[0].Properties["ips"].([]interface{})[0].(string)
return nil
}
func (d *Driver) Restart() error {
d.setPB()
resp := profitbricks.RebootServer(d.DatacenterId, d.ServerId)
if resp.StatusCode != 202 {
return errors.New(string(resp.Body))
}
return nil
}
func (d *Driver) Remove() error {
d.setPB()
resp := profitbricks.DeleteDatacenter(d.DatacenterId)
d.waitTillProvisioned(strings.Join(resp.Headers["Location"], ""))
ipblocks := profitbricks.ListIpBlocks()
for i := 0; i < len(ipblocks.Items); i++ {
for _, v := range ipblocks.Items[i].Properties["ips"].([]interface{}) {
if d.IPAddress == v.(string) {
resp := profitbricks.ReleaseIpBlock(ipblocks.Items[i].Id)
if resp.StatusCode > 299 {
return errors.New(string(resp.Body))
}
}
}
}
if resp.StatusCode > 299 {
return errors.New(string(resp.Body))
}
return nil
}
func (d *Driver) GetURL() (string, error) {
if err := drivers.MustBeRunning(d); err != nil {
return "", err
}
ip, err := d.GetIP()
if err != nil {
return "", err
}
return fmt.Sprintf("tcp://%s:2376", ip), nil
}
func (d *Driver) Start() error {
serverstate, err := d.GetState()
d.setPB()
if err != nil {
return err
}
if serverstate != state.Running {
profitbricks.StartServer(d.DatacenterId, d.ServerId)
} else {
log.Info("Host is already running or starting")
}
return nil
}
func (d *Driver) Stop() error {
vmstate, err := d.GetState()
if err != nil {
return err
}
if vmstate == state.Stopped {
log.Infof("Host is already stopped")
return nil
}
d.setPB()
profitbricks.StopServer(d.DatacenterId, d.ServerId)
if err != nil {
return err
}
return nil
}
func (d *Driver) Kill() error {
resp := profitbricks.StopServer(d.DatacenterId, d.ServerId)
if resp.StatusCode != 202 {
return errors.New(string(resp.Body))
}
return nil
}
func (d *Driver) GetIP() (string, error) {
d.setPB()
server := profitbricks.GetServer(d.DatacenterId, d.ServerId)
d.IPAddress = server.Entities["nics"].Items[0].Properties["ips"].([]interface{})[0].(string)
if d.IPAddress == "" {
return "", fmt.Errorf("IP address is not set")
}
return d.IPAddress, nil
}
func (d *Driver) GetState() (state.State, error) {
d.setPB()
server := profitbricks.GetServer(d.DatacenterId, d.ServerId)
switch server.MetaData["state"] {
case "NOSTATE":
return state.None, nil
case "AVAILABLE":
return state.Running, nil
case "PAUSED":
return state.Paused, nil
case "BLOCKED":
return state.Stopped, nil
case "SHUTDOWN":
return state.Stopped, nil
case "SHUTOFF":
return state.Stopped, nil
case "CHRASHED":
return state.Error, nil
case "INACTIVE":
return state.Stopped, nil
}
return state.None, nil
}
//Private helper functions
func (d *Driver) setPB() {
profitbricks.SetAuth(d.Username, d.Password)
profitbricks.SetEndpoint(d.URL)
}
func (d *Driver) publicSSHKeyPath() string {
return d.GetSSHKeyPath() + ".pub"
}
func (d *Driver) createSSHKey() (string, error) {
if err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {
return "", err
}
publicKey, err := ioutil.ReadFile(d.publicSSHKeyPath())
if err != nil {
return "", err
}
return string(publicKey), nil
}
func (d *Driver) isSwarmMaster() bool {
return d.SwarmMaster
}
func (d *Driver) waitTillProvisioned(path string) {
d.setPB()
for i := 0; i < waitCount; i++ {
request := profitbricks.GetRequestStatus(path)
if request.MetaData["status"] == "DONE" {
break
}
time.Sleep(10 * time.Second)
i++
}
}
func (d *Driver) getImageId(imageName string) string {
d.setPB()
images := profitbricks.ListImages()
for i := 0; i < len(images.Items); i++ {
if images.Items[i].Properties["name"] == imageName && images.Items[i].Properties["imageType"] == d.DiskType && images.Items[i].Properties["location"] == d.Location {
return images.Items[i].Id
}
}
return ""
}