/
exoscale.go
711 lines (634 loc) · 18 KB
/
exoscale.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
package exoscale
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"net"
"os"
"os/user"
"path/filepath"
"regexp"
"strings"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnflag"
"github.com/docker/machine/libmachine/mcnutils"
"github.com/docker/machine/libmachine/state"
"github.com/exoscale/egoscale"
)
// Driver is the struct compatible with github.com/docker/machine/libmachine/drivers.Driver interface
type Driver struct {
*drivers.BaseDriver
URL string
APIKey string `json:"ApiKey"`
APISecretKey string `json:"ApiSecretKey"`
InstanceProfile string
DiskSize int64
Image string
SecurityGroups []string
AffinityGroups []string
AvailabilityZone string
SSHKey string
KeyPair string
Password string
PublicKey string
UserDataFile string
UserData []byte
ID string `json:"Id"`
}
const (
defaultAPIEndpoint = "https://api.exoscale.ch/compute"
defaultInstanceProfile = "Small"
defaultDiskSize = 50
defaultImage = "Linux Ubuntu 16.04 LTS 64-bit"
defaultAvailabilityZone = "CH-DK-2"
defaultSSHUser = "root"
defaultSecurityGroup = "docker-machine"
defaultAffinityGroupType = "host anti-affinity"
defaultCloudInit = `#cloud-config
manage_etc_hosts: localhost
`
)
// GetCreateFlags registers the flags this driver adds to
// "docker hosts create"
func (d *Driver) GetCreateFlags() []mcnflag.Flag {
return []mcnflag.Flag{
mcnflag.StringFlag{
EnvVar: "EXOSCALE_ENDPOINT",
Name: "exoscale-url",
Usage: "exoscale API endpoint",
},
mcnflag.StringFlag{
EnvVar: "EXOSCALE_API_KEY",
Name: "exoscale-api-key",
Usage: "exoscale API key",
},
mcnflag.StringFlag{
EnvVar: "EXOSCALE_API_SECRET",
Name: "exoscale-api-secret-key",
Usage: "exoscale API secret key",
},
mcnflag.StringFlag{
EnvVar: "EXOSCALE_INSTANCE_PROFILE",
Name: "exoscale-instance-profile",
Value: defaultInstanceProfile,
Usage: "exoscale instance profile (Small, Medium, Large, ...)",
},
mcnflag.IntFlag{
EnvVar: "EXOSCALE_DISK_SIZE",
Name: "exoscale-disk-size",
Value: defaultDiskSize,
Usage: "exoscale disk size (10, 50, 100, 200, 400)",
},
mcnflag.StringFlag{
EnvVar: "EXOSCALE_IMAGE",
Name: "exoscale-image",
Value: defaultImage,
Usage: "exoscale image template",
},
mcnflag.StringSliceFlag{
EnvVar: "EXOSCALE_SECURITY_GROUP",
Name: "exoscale-security-group",
Value: []string{defaultSecurityGroup},
Usage: "exoscale security group",
},
mcnflag.StringFlag{
EnvVar: "EXOSCALE_AVAILABILITY_ZONE",
Name: "exoscale-availability-zone",
Value: defaultAvailabilityZone,
Usage: "exoscale availability zone",
},
mcnflag.StringFlag{
EnvVar: "EXOSCALE_SSH_USER",
Name: "exoscale-ssh-user",
Value: "",
Usage: "name of the ssh user",
},
mcnflag.StringFlag{
EnvVar: "EXOSCALE_SSH_KEY",
Name: "exoscale-ssh-key",
Value: "",
Usage: "path to the SSH user private key",
},
mcnflag.StringFlag{
EnvVar: "EXOSCALE_USERDATA",
Name: "exoscale-userdata",
Usage: "path to file with cloud-init user-data",
},
mcnflag.StringSliceFlag{
EnvVar: "EXOSCALE_AFFINITY_GROUP",
Name: "exoscale-affinity-group",
Value: []string{},
Usage: "exoscale affinity group",
},
}
}
// NewDriver creates a Driver with the specified machineName and storePath.
func NewDriver(machineName, storePath string) drivers.Driver {
return &Driver{
InstanceProfile: defaultInstanceProfile,
DiskSize: defaultDiskSize,
Image: defaultImage,
AvailabilityZone: defaultAvailabilityZone,
BaseDriver: &drivers.BaseDriver{
MachineName: machineName,
StorePath: storePath,
},
}
}
// GetSSHHostname returns the hostname to use with SSH
func (d *Driver) GetSSHHostname() (string, error) {
return d.GetIP()
}
// GetSSHUsername returns the username to use with SSH
func (d *Driver) GetSSHUsername() string {
if d.SSHUser == "" {
name := strings.ToLower(d.Image)
if strings.Contains(name, "ubuntu") {
return "ubuntu"
}
if strings.Contains(name, "centos") {
return "centos"
}
if strings.Contains(name, "redhat") {
return "cloud-user"
}
if strings.Contains(name, "fedora") {
return "fedora"
}
if strings.Contains(name, "coreos") {
return "core"
}
if strings.Contains(name, "debian") {
return "debian"
}
return defaultSSHUser
}
return d.SSHUser
}
// DriverName returns the name of the driver
func (d *Driver) DriverName() string {
return "exoscale"
}
// SetConfigFromFlags configures the driver with the object that was returned
// by RegisterCreateFlags
func (d *Driver) SetConfigFromFlags(flags drivers.DriverOptions) error {
d.URL = flags.String("exoscale-url")
d.APIKey = flags.String("exoscale-api-key")
d.APISecretKey = flags.String("exoscale-api-secret-key")
d.InstanceProfile = flags.String("exoscale-instance-profile")
d.DiskSize = int64(flags.Int("exoscale-disk-size"))
d.Image = flags.String("exoscale-image")
d.SecurityGroups = flags.StringSlice("exoscale-security-group")
d.AffinityGroups = flags.StringSlice("exoscale-affinity-group")
d.AvailabilityZone = flags.String("exoscale-availability-zone")
d.SSHUser = flags.String("exoscale-ssh-user")
d.SSHKey = flags.String("exoscale-ssh-key")
d.UserDataFile = flags.String("exoscale-userdata")
d.UserData = []byte(defaultCloudInit)
d.SetSwarmConfigFromFlags(flags)
if d.URL == "" {
d.URL = defaultAPIEndpoint
}
if d.APIKey == "" || d.APISecretKey == "" {
return errors.New("missing an API key (--exoscale-api-key) or API secret key (--exoscale-api-secret-key)")
}
return nil
}
// PreCreateCheck allows for pre-create operations to make sure a driver is
// ready for creation
func (d *Driver) PreCreateCheck() error {
if d.UserDataFile != "" {
if _, err := os.Stat(d.UserDataFile); os.IsNotExist(err) {
return fmt.Errorf("user-data file %s could not be found", d.UserDataFile)
}
}
return nil
}
// GetURL returns a Docker compatible host URL for connecting to this host
// e.g tcp://10.1.2.3:2376
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", net.JoinHostPort(ip, "2376")), nil
}
func (d *Driver) client() *egoscale.Client {
return egoscale.NewClient(d.URL, d.APIKey, d.APISecretKey)
}
func (d *Driver) virtualMachine() (*egoscale.VirtualMachine, error) {
cs := d.client()
virtualMachine := &egoscale.VirtualMachine{
ID: d.ID,
}
if err := cs.GetWithContext(context.TODO(), virtualMachine); err != nil {
return nil, err
}
return virtualMachine, nil
}
// GetState returns a github.com/machine/libmachine/state.State representing the state of the host (running, stopped, etc.)
func (d *Driver) GetState() (state.State, error) {
vm, err := d.virtualMachine()
if err != nil {
return state.Error, err
}
switch vm.State {
case "Starting":
return state.Starting, nil
case "Running":
return state.Running, nil
case "Stopping":
return state.Running, nil
case "Stopped":
return state.Stopped, nil
case "Destroyed":
return state.Stopped, nil
case "Expunging":
return state.Stopped, nil
case "Migrating":
return state.Paused, nil
case "Error":
return state.Error, nil
case "Unknown":
return state.Error, nil
case "Shutdowned":
return state.Stopped, nil
}
return state.None, nil
}
func (d *Driver) createDefaultSecurityGroup(group string) (*egoscale.SecurityGroup, error) {
cs := d.client()
resp, err := cs.RequestWithContext(context.TODO(), &egoscale.CreateSecurityGroup{
Name: group,
Description: "created by docker-machine",
})
if err != nil {
return nil, err
}
sg := resp.(*egoscale.CreateSecurityGroupResponse).SecurityGroup
requests := []egoscale.AuthorizeSecurityGroupIngress{
{
SecurityGroupID: sg.ID,
Description: "SSH",
CidrList: []string{"0.0.0.0/0"},
Protocol: "TCP",
StartPort: 22,
EndPort: 22,
},
{
SecurityGroupID: sg.ID,
Description: "Ping",
CidrList: []string{"0.0.0.0/0"},
Protocol: "ICMP",
IcmpType: 8,
IcmpCode: 0,
},
{
SecurityGroupID: sg.ID,
Description: "Docker",
CidrList: []string{"0.0.0.0/0"},
Protocol: "TCP",
StartPort: 2376,
EndPort: 2377,
},
{
SecurityGroupID: sg.ID,
Description: "Legacy Standalone Swarm",
CidrList: []string{"0.0.0.0/0"},
Protocol: "TCP",
StartPort: 3376,
EndPort: 3377,
},
{
SecurityGroupID: sg.ID,
Description: "Communication among nodes",
Protocol: "TCP",
StartPort: 7946,
EndPort: 7946,
UserSecurityGroupList: []egoscale.UserSecurityGroup{{
Group: sg.Name,
Account: sg.Account,
}},
},
{
SecurityGroupID: sg.ID,
Description: "Communication among nodes",
Protocol: "UDP",
StartPort: 7946,
EndPort: 7946,
UserSecurityGroupList: []egoscale.UserSecurityGroup{{
Group: sg.Name,
Account: sg.Account,
}},
},
{
SecurityGroupID: sg.ID,
Description: "Overlay network traffic",
Protocol: "UDP",
StartPort: 4789,
EndPort: 4789,
UserSecurityGroupList: []egoscale.UserSecurityGroup{{
Group: sg.Name,
Account: sg.Account,
}},
},
}
for _, req := range requests {
_, err := cs.RequestWithContext(context.TODO(), &req)
if err != nil {
return nil, err
}
}
return &sg, nil
}
func (d *Driver) createDefaultAffinityGroup(group string) (*egoscale.AffinityGroup, error) {
cs := d.client()
resp, err := cs.RequestWithContext(context.TODO(), &egoscale.CreateAffinityGroup{
Name: group,
Type: defaultAffinityGroupType,
Description: "created by docker-machine",
})
if err != nil {
return nil, err
}
affinityGroup := resp.(*egoscale.CreateAffinityGroupResponse).AffinityGroup
return &affinityGroup, nil
}
// Create creates the VM instance acting as the docker host
func (d *Driver) Create() error {
cloudInit, err := d.getCloudInit()
if err != nil {
return err
}
log.Infof("Querying exoscale for the requested parameters...")
client := egoscale.NewClient(d.URL, d.APIKey, d.APISecretKey)
resp, err := client.RequestWithContext(context.TODO(), &egoscale.ListZones{
Name: d.AvailabilityZone,
})
if err != nil {
return err
}
zones := resp.(*egoscale.ListZonesResponse)
if len(zones.Zone) != 1 {
return fmt.Errorf("Availability zone %v doesn't exist",
d.AvailabilityZone)
}
zone := zones.Zone[0].ID
log.Debugf("Availability zone %v = %s", d.AvailabilityZone, zone)
// Image
template := egoscale.Template{
IsFeatured: true,
ZoneID: "1", // GVA2
}
templates, err := client.ListWithContext(context.TODO(), &template)
if err != nil {
return err
}
image := strings.ToLower(d.Image)
re := regexp.MustCompile(`^Linux (?P<name>.+?) (?P<version>[0-9.]+)\b`)
for _, t := range templates {
tpl := t.(*egoscale.Template)
// Keep only 10GiB images
if tpl.Size>>30 != 10 {
continue
}
fullname := strings.ToLower(tpl.Name)
if image == fullname {
template = *tpl
break
}
submatch := re.FindStringSubmatch(tpl.Name)
if len(submatch) > 0 {
name := strings.Replace(strings.ToLower(submatch[1]), " ", "-", -1)
version := submatch[2]
shortname := fmt.Sprintf("%s-%s", name, version)
if image == shortname {
template = *tpl
break
}
}
}
if template.ID == "" {
return fmt.Errorf("Unable to find image %v", d.Image)
}
// Reading the username from the template
if name, ok := template.Details["username"]; ok {
d.SSHUser = name
}
log.Debugf("Image %v(10) = %s (%s)", d.Image, template.ID, d.SSHUser)
// Profile UUID
resp, err = client.RequestWithContext(context.TODO(), &egoscale.ListServiceOfferings{
Name: d.InstanceProfile,
})
if err != nil {
return err
}
profiles := resp.(*egoscale.ListServiceOfferingsResponse)
if len(profiles.ServiceOffering) != 1 {
return fmt.Errorf("Unable to find the %s profile",
d.InstanceProfile)
}
profile := profiles.ServiceOffering[0].ID
log.Debugf("Profile %v = %s", d.InstanceProfile, profile)
// Security groups
sgs := make([]string, 0, len(d.SecurityGroups))
for _, group := range d.SecurityGroups {
if group == "" {
continue
}
sg := &egoscale.SecurityGroup{Name: group}
if err := client.Get(sg); err != nil {
if _, ok := err.(*egoscale.ErrorResponse); !ok {
return err
}
log.Infof("Security group %v does not exist. Creating it...", group)
securityGroup, err := d.createDefaultSecurityGroup(group)
if err != nil {
return err
}
sg.ID = securityGroup.ID
}
log.Debugf("Security group %v = %s", group, sg.ID)
sgs = append(sgs, sg.ID)
}
// Affinity Groups
ags := make([]string, 0, len(d.AffinityGroups))
for _, group := range d.AffinityGroups {
if group == "" {
continue
}
ag := &egoscale.AffinityGroup{Name: group}
if err := client.Get(ag); err != nil {
if _, ok := err.(*egoscale.ErrorResponse); !ok {
return err
}
log.Infof("Affinity Group %v does not exist, create it", group)
affinityGroup, err := d.createDefaultAffinityGroup(group)
if err != nil {
return err
}
ag.ID = affinityGroup.ID
}
log.Debugf("Affinity group %v = %s", group, ag.ID)
ags = append(ags, ag.ID)
}
// SSH key pair
if d.SSHKey == "" {
var keyPairName string
keyPairName = fmt.Sprintf("docker-machine-%s", d.MachineName)
log.Infof("Generate an SSH keypair...")
resp, err := client.RequestWithContext(context.TODO(), &egoscale.CreateSSHKeyPair{
Name: keyPairName,
})
if err != nil {
return fmt.Errorf("SSH Key pair creation failed %s", err)
}
keyPair := resp.(*egoscale.CreateSSHKeyPairResponse).KeyPair
if err = os.MkdirAll(filepath.Dir(d.GetSSHKeyPath()), 0750); err != nil {
return fmt.Errorf("Cannot create the folder to store the SSH private key. %s", err)
}
if err = ioutil.WriteFile(d.GetSSHKeyPath(), []byte(keyPair.PrivateKey), 0600); err != nil {
return fmt.Errorf("SSH private key could not be written. %s", err)
}
d.KeyPair = keyPairName
} else {
log.Infof("Importing SSH key from %s", d.SSHKey)
sshKey := d.SSHKey
if strings.HasPrefix(sshKey, "~/") {
usr, _ := user.Current()
sshKey = filepath.Join(usr.HomeDir, sshKey[2:])
} else {
var err error
if sshKey, err = filepath.Abs(sshKey); err != nil {
return err
}
}
// Sending the SSH public key through the cloud-init config
pubKey, err := ioutil.ReadFile(sshKey + ".pub")
if err != nil {
return fmt.Errorf("Cannot read SSH public key %s", err)
}
sshAuthorizedKeys := `
ssh_authorized_keys:
- `
cloudInit = bytes.Join([][]byte{cloudInit, []byte(sshAuthorizedKeys), pubKey}, []byte(""))
// Copying the private key into docker-machine
if err := mcnutils.CopyFile(sshKey, d.GetSSHKeyPath()); err != nil {
return fmt.Errorf("Unable to copy SSH file: %s", err)
}
if err := os.Chmod(d.GetSSHKeyPath(), 0600); err != nil {
return fmt.Errorf("Unable to set permissions on the SSH file: %s", err)
}
}
log.Infof("Spawn exoscale host...")
log.Debugf("Using the following cloud-init file:")
log.Debugf("%s", string(cloudInit))
// Base64 encode the userdata
d.UserData = cloudInit
encodedUserData := base64.StdEncoding.EncodeToString(d.UserData)
req := &egoscale.DeployVirtualMachine{
TemplateID: template.ID,
ServiceOfferingID: profile,
UserData: encodedUserData,
ZoneID: zone,
Name: d.MachineName,
KeyPair: d.KeyPair,
DisplayName: d.MachineName,
RootDiskSize: d.DiskSize,
SecurityGroupIDs: sgs,
AffinityGroupIDs: ags,
}
log.Infof("Deploy %#v", req)
resp, err = client.RequestWithContext(context.TODO(), req)
if err != nil {
return err
}
vm := resp.(*egoscale.DeployVirtualMachineResponse).VirtualMachine
IPAddress := vm.Nic[0].IPAddress
if IPAddress != nil {
d.IPAddress = IPAddress.String()
}
d.ID = vm.ID
log.Infof("IP Address: %v, SSH User: %v", d.IPAddress, d.GetSSHUsername())
if vm.PasswordEnabled {
d.Password = vm.Password
}
// Destroy the SSH key from CloudStack
if d.KeyPair != "" {
if err := drivers.WaitForSSH(d); err != nil {
return err
}
key := &egoscale.SSHKeyPair{
Name: d.KeyPair,
}
if err := client.DeleteWithContext(context.TODO(), key); err != nil {
return err
}
d.KeyPair = ""
}
return nil
}
// Start starts the existing VM instance.
func (d *Driver) Start() error {
cs := d.client()
_, err := cs.RequestWithContext(context.TODO(), &egoscale.StartVirtualMachine{
ID: d.ID,
})
return err
}
// Stop stops the existing VM instance.
func (d *Driver) Stop() error {
cs := d.client()
_, err := cs.RequestWithContext(context.TODO(), &egoscale.StopVirtualMachine{
ID: d.ID,
})
return err
}
// Restart reboots the existing VM instance.
func (d *Driver) Restart() error {
cs := d.client()
_, err := cs.RequestWithContext(context.TODO(), &egoscale.RebootVirtualMachine{
ID: d.ID,
})
return err
}
// Kill stops a host forcefully (same as Stop)
func (d *Driver) Kill() error {
return d.Stop()
}
// Remove destroys the VM instance and the associated SSH key.
func (d *Driver) Remove() error {
client := d.client()
// Destroy the SSH key from CloudStack
if d.KeyPair != "" {
key := &egoscale.SSHKeyPair{Name: d.KeyPair}
if err := client.DeleteWithContext(context.TODO(), key); err != nil {
return err
}
}
// Destroy the virtual machine
if d.ID != "" {
vm := &egoscale.VirtualMachine{ID: d.ID}
if err := client.DeleteWithContext(context.TODO(), vm); err != nil {
return err
}
}
log.Infof("The Anti-Affinity group and Security group were not removed")
return nil
}
// Build a cloud-init user data string that will install and run
// docker.
func (d *Driver) getCloudInit() ([]byte, error) {
var err error
if d.UserDataFile != "" {
d.UserData, err = ioutil.ReadFile(d.UserDataFile)
}
return d.UserData, err
}