-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
785 lines (619 loc) · 20 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
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
package main
/*
* Driver support for the CloudControl API client
* ----------------------------------------------
*/
import (
"errors"
"fmt"
"strings"
"time"
"github.com/DimensionDataResearch/go-dd-cloud-compute/compute"
"github.com/docker/machine/libmachine/log"
)
// CloudControl client retry
const (
// The maximum number of times the client will retry in the case of a network error connecting to the CloudContron API.
clientMaxRetry = 5
// The period of time between retries against the CloudControl API.
clientRetryPeriod = 5 * time.Second
)
// Timeouts
const (
// CloudControl server deployment timeout.
serverCreateTimeout = 15 * time.Minute
// CloudControl resource deletion timeout.
serverDeleteTimeout = 10 * time.Minute
// CloudControl server startup timeout.
serverStartTimeout = 3 * time.Minute
// CloudControl server shutdown timeout.
serverStopTimeout = 3 * time.Minute
// CloudControl server power-off timeout.
serverPowerOffTimeout = 2 * time.Minute
)
// Get the CloudControl API client used by the driver.
func (driver *Driver) getCloudControlClient() (client *compute.Client, err error) {
client = driver.client
if client != nil {
return
}
if driver.CloudControlUser == "" {
err = errors.New("Cannot connect to CloudControl API (user name has not been configured)")
return
}
if driver.CloudControlPassword == "" {
err = errors.New("Cannot connect to CloudControl API (password has not been configured)")
return
}
if driver.CloudControlRegion != "" {
client = compute.NewClient(driver.CloudControlRegion, driver.CloudControlUser, driver.CloudControlPassword)
} else if driver.CloudControlEndPointURI != "" {
client = compute.NewClientWithBaseAddress(driver.CloudControlEndPointURI, driver.CloudControlUser, driver.CloudControlPassword)
} else {
err = errors.New("Cannot connect to CloudControl API (neither region nor custom end-point URI have been configured)")
return
}
client.ConfigureRetry(clientMaxRetry, clientRetryPeriod)
driver.client = client
return
}
// Determine whether the target server has been created.
func (driver *Driver) isServerCreated() bool {
return driver.ServerID != ""
}
// Retrieve the target server (must have been created, or an error is returned).
func (driver *Driver) getServer() (*compute.Server, error) {
if !driver.isServerCreated() {
return nil, fmt.Errorf("Server '%s' has not been created", driver.MachineName)
}
client, err := driver.getCloudControlClient()
if err != nil {
return nil, err
}
return client.GetServer(driver.ServerID)
}
// Retrieve the target network domain.
func (driver *Driver) getNetworkDomain() (*compute.NetworkDomain, error) {
if driver.NetworkDomainID == "" {
return nil, errors.New("Network domain Id has not been configured")
}
client, err := driver.getCloudControlClient()
if err != nil {
return nil, err
}
return client.GetNetworkDomain(driver.ServerID)
}
// Resolve (find) the target network domain by name and data centre Id.
func (driver *Driver) resolveNetworkDomain() error {
driver.NetworkDomainID = ""
if driver.NetworkDomainName == "" {
return errors.New("Network domain name has not been configured")
}
if driver.DataCenterID == "" {
return errors.New("Data centre Id has not been configured")
}
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
networkDomain, err := client.GetNetworkDomainByName(driver.NetworkDomainName, driver.DataCenterID)
if err != nil {
return err
}
if networkDomain == nil {
return fmt.Errorf("No network domain named '%s' was found in data centre '%s'", driver.NetworkDomainName, driver.DataCenterID)
}
driver.NetworkDomainID = networkDomain.ID
return nil
}
// Retrieve the target VLAN.
func (driver *Driver) getVLAN() (*compute.VLAN, error) {
if driver.VLANID == "" {
return nil, errors.New("VLAN Id has not been configured")
}
client, err := driver.getCloudControlClient()
if err != nil {
return nil, err
}
return client.GetVLAN(driver.VLANID)
}
// Resolve (find) the target network domain by name and data centre Id.
func (driver *Driver) resolveVLAN() error {
driver.VLANID = ""
if driver.VLANName == "" {
return errors.New("VLAN name has not been configured")
}
var err error
if driver.NetworkDomainID == "" {
err = driver.resolveNetworkDomain()
if err != nil {
return err
}
}
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
vlan, err := client.GetVLANByName(driver.VLANName, driver.NetworkDomainID)
if err != nil {
return err
}
if vlan == nil {
return fmt.Errorf("No VLAN named '%s' was found in network domain '%s' ('%s')", driver.VLANName, driver.NetworkDomainName, driver.NetworkDomainID)
}
driver.VLANID = vlan.ID
return nil
}
// Retrieve the target image.
func (driver *Driver) getImage() (image compute.Image, err error) {
if driver.ImageID == "" {
return nil, errors.New("Image Id has not been resolved")
}
var client *compute.Client
client, err = driver.getCloudControlClient()
if err != nil {
return nil, err
}
image, err = client.GetOSImage(driver.ImageID)
if err != nil {
return
}
if image == nil {
image, err = client.GetCustomerImage(driver.ImageID)
if err != nil {
return
}
}
return
}
// Resolve (find) the target image.
func (driver *Driver) resolveImage() error {
driver.ImageID = ""
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
var image compute.Image
image, err = client.FindOSImage(driver.ImageName, driver.DataCenterID)
if err != nil {
return err
}
if image == nil {
image, err = client.FindCustomerImage(driver.ImageName, driver.DataCenterID)
if err != nil {
return err
}
}
if image == nil {
log.Errorf("Image '%s' was not found in data centre '%s'.", driver.ImageName, driver.DataCenterID)
return fmt.Errorf("Image '%s' was not found in data centre '%s'", driver.ImageName, driver.DataCenterID)
}
if image.GetOS().Family != "UNIX" {
return fmt.Errorf("Image '%s' in data centre '%s' is not from a supported OS family (expected 'UNIX', but found '%s')",
driver.ImageName,
driver.DataCenterID,
image.GetOS().Family,
)
}
driver.ImageID = image.GetID()
driver.ImageType = image.GetType()
driver.ImageOSType = image.GetOS().ID
return nil
}
func (driver *Driver) deployServer() (*compute.Server, error) {
if driver.isServerCreated() {
return nil, fmt.Errorf("Server '%s' already exists (Id = '%s')", driver.MachineName, driver.ServerID)
}
serverConfiguration, err := driver.buildDeploymentConfiguration()
if err != nil {
return nil, err
}
client, err := driver.getCloudControlClient()
if err != nil {
return nil, err
}
driver.ServerID, err = client.DeployServer(serverConfiguration)
if err != nil {
return nil, err
}
log.Debugf("Deploying server '%s' ('%s')...", driver.ServerID, driver.MachineName)
resource, err := client.WaitForDeploy(compute.ResourceTypeServer, driver.ServerID, serverCreateTimeout)
if err != nil {
return nil, err
}
server := resource.(*compute.Server)
log.Debugf("Server '%s' ('%s') has been successfully deployed...", driver.ServerID, server.Name)
driver.PrivateIPAddress = *server.Network.PrimaryAdapter.PrivateIPv4Address
driver.IPAddress = driver.PrivateIPAddress // NAT rule not created yet.
return server, nil
}
// Build a deployment configuration for the target server.
func (driver *Driver) buildDeploymentConfiguration() (deploymentConfiguration compute.ServerDeploymentConfiguration, err error) {
var image compute.Image
image, err = driver.getImage()
if err != nil {
return
}
if image == nil {
err = fmt.Errorf("OS image '%s' not found", driver.ImageID)
return
}
// Specify private IPv4 address or VLAN Id.
var (
vlanID *string
privateIPv4Address *string
)
if driver.PrivateIPAddress != "" {
privateIPv4Address = &driver.PrivateIPAddress
} else {
vlanID = &driver.VLANID
}
deploymentConfiguration = compute.ServerDeploymentConfiguration{
Name: driver.MachineName,
Description: fmt.Sprintf("%s (created by Docker Machine).", driver.MachineName),
AdministratorPassword: driver.SSHBootstrapPassword,
Network: compute.VirtualMachineNetwork{
NetworkDomainID: driver.NetworkDomainID,
PrimaryAdapter: compute.VirtualMachineNetworkAdapter{
VLANID: vlanID,
PrivateIPv4Address: privateIPv4Address,
},
},
PrimaryDNS: "8.8.8.8",
SecondaryDNS: "8.8.4.4",
Start: true,
}
image.ApplyTo(&deploymentConfiguration)
// Customise memory and / or CPU (if required).
if driver.MemoryGB != -1 {
deploymentConfiguration.MemoryGB = driver.MemoryGB
}
if driver.CPUCount != -1 {
deploymentConfiguration.CPU.Count = driver.CPUCount
}
if driver.CoresPerSocket != -1 {
deploymentConfiguration.CPU.CoresPerSocket = driver.CoresPerSocket
}
return
}
// Start the target server.
func (driver *Driver) startServer() error {
server, err := driver.getServer()
if err != nil {
return err
}
if server == nil {
return fmt.Errorf("server '%s' not found", driver.ServerID)
}
if !server.Started {
return nil
}
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
err = client.StartServer(driver.ServerID)
if err != nil {
return err
}
_, err = client.WaitForChange(compute.ResourceTypeServer, driver.ServerID, "Start server", serverStartTimeout)
return err
}
// Stop the target server.
func (driver *Driver) stopServer() error {
server, err := driver.getServer()
if err != nil {
return err
}
if server == nil {
return fmt.Errorf("server '%s' not found", driver.ServerID)
}
if !server.Started {
return nil
}
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
err = client.ShutdownServer(driver.ServerID)
if err != nil {
return err
}
_, err = client.WaitForChange(compute.ResourceTypeServer, driver.ServerID, "Shut down server", serverStopTimeout)
return err
}
// Stop the target server.
func (driver *Driver) powerOffServer() error {
server, err := driver.getServer()
if err != nil {
return err
}
if server == nil {
return fmt.Errorf("server '%s' not found", driver.ServerID)
}
if !server.Started {
return nil
}
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
err = client.PowerOffServer(driver.ServerID)
if err != nil {
return err
}
_, err = client.WaitForChange(compute.ResourceTypeServer, driver.ServerID, "Power off server", serverPowerOffTimeout)
return err
}
// Has a NAT rule been created for the server?
func (driver *Driver) isNATRuleCreated() bool {
return driver.NATRuleID != ""
}
// Create a NAT rule to expose the server.
func (driver *Driver) createNATRuleForServer() error {
if !driver.isServerCreated() {
return fmt.Errorf("Server '%s' has not been created", driver.MachineName)
}
if driver.isNATRuleCreated() {
return fmt.Errorf("NAT rule '%s' has already been created for server '%s'", driver.NATRuleID, driver.MachineName)
}
log.Debugf("Creating NAT rule for server '%s' ('%s')...", driver.MachineName, driver.PrivateIPAddress)
natRule, err := driver.getExistingNATRuleByInternalIP(driver.PrivateIPAddress)
if natRule == nil {
err = driver.ensurePublicIPAvailable()
if err != nil {
return err
}
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
driver.NATRuleID, err = client.AddNATRule(driver.NetworkDomainID, driver.PrivateIPAddress, nil)
if err != nil {
return err
}
natRule, err = client.GetNATRule(driver.NATRuleID)
if err != nil {
return err
}
if natRule == nil {
return fmt.Errorf("Failed to retrieve newly-created NAT rule '%s' for server '%s'", driver.NATRuleID, driver.MachineName)
}
log.Debugf("Created NAT rule '%s' for server '%s'", driver.NATRuleID)
} else {
driver.NATRuleID = natRule.ID
log.Debugf("NAT rule already exists (Id = '%s').", driver.NATRuleID)
}
driver.IPAddress = natRule.ExternalIPAddress
log.Debugf("Created NAT rule '%s' for server '%s' (Ext:'%s' -> Int:'%s').",
driver.NATRuleID,
driver.MachineName,
driver.IPAddress,
driver.PrivateIPAddress,
)
return nil
}
// Delete the the server's NAT rule (if any).
func (driver *Driver) deleteNATRuleForServer() error {
if !driver.isServerCreated() {
return fmt.Errorf("Server '%s' has not been created", driver.MachineName)
}
if !driver.isNATRuleCreated() {
log.Debugf("Not deleting NAT rule for server '%s' (no NAT rule was created for it).")
return nil
}
log.Debugf("Deleting NAT rule '%s' for server '%s' (Ext:'%s' -> Int:'%s')...", driver.NATRuleID, driver.MachineName, driver.IPAddress, driver.PrivateIPAddress)
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
natRule, err := client.GetNATRule(driver.NATRuleID)
if err != nil {
return err
}
if natRule == nil {
log.Debugf("NAT rule '%s' not found; will treat it as already deleted.")
driver.NATRuleID = ""
return nil
}
err = client.DeleteNATRule(driver.NATRuleID)
if err != nil {
return err
}
log.Debugf("Deleted NAT rule '%s'.", driver.NATRuleID)
driver.NATRuleID = ""
driver.IPAddress = driver.PrivateIPAddress
return nil
}
// Find the existing NAT rule (if any) that forwards IPv4 traffic to specified internal address.
func (driver *Driver) getExistingNATRuleByInternalIP(internalIPAddress string) (*compute.NATRule, error) {
if driver.NetworkDomainID == "" {
return nil, errors.New("network domain has not been resolved")
}
client, err := driver.getCloudControlClient()
if err != nil {
return nil, err
}
page := compute.DefaultPaging()
for {
var rules *compute.NATRules
rules, err = client.ListNATRules(driver.NetworkDomainID, page)
if err != nil {
return nil, err
}
if rules.IsEmpty() {
break // We're done
}
for _, rule := range rules.Rules {
if rule.InternalIPAddress == internalIPAddress {
return &rule, nil
}
}
page.Next()
}
return nil, nil
}
// Ensure that at least one public IP address is available in the target network domain.
func (driver *Driver) ensurePublicIPAvailable() error {
if driver.NetworkDomainID == "" {
return errors.New("network domain has not been resolved")
}
log.Debugf("Verifying that network domain '%s' has a public IP available for server '%s'...", driver.NetworkDomainName, driver.MachineName)
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
availableIPs, err := client.GetAvailablePublicIPAddresses(driver.NetworkDomainID)
if err != nil {
return err
}
if len(availableIPs) == 0 {
log.Debugf("There are no available public IPs in network domain '%s'; a new block of public IPs will be allocated.", driver.NetworkDomainID)
blockID, err := client.AddPublicIPBlock(driver.NetworkDomainID)
if err != nil {
return err
}
log.Debugf("Allocated new public IP block '%s'.", blockID)
}
return nil
}
// Has a firewall rule been created to allow inbound SSH for the server?
func (driver *Driver) isSSHFirewallRuleCreated() bool {
return driver.SSHFirewallRuleID != ""
}
// Create a firewall rule to enable inbound SSH connections to the target server from the client machine's (external) IP address.
func (driver *Driver) createSSHFirewallRule() error {
if !driver.isServerCreated() {
return fmt.Errorf("Server '%s' has not been created", driver.MachineName)
}
if driver.isSSHFirewallRuleCreated() {
return fmt.Errorf("SSH firewall rule '%s' has already been created for server '%s'", driver.SSHFirewallRuleID, driver.MachineName)
}
log.Debugf("Creating SSH firewall rule for server '%s' (allow inbound traffic on port %d from '%s' to '%s')...",
driver.MachineName,
driver.SSHPort,
driver.ClientPublicIPAddress,
driver.IPAddress,
)
ruleConfiguration := compute.FirewallRuleConfiguration{
Name: driver.buildFirewallRuleName("SSH"),
NetworkDomainID: driver.NetworkDomainID,
}
ruleConfiguration.Accept()
ruleConfiguration.Enable()
ruleConfiguration.IPv4()
ruleConfiguration.TCP()
ruleConfiguration.MatchSourceAddress(driver.ClientPublicIPAddress)
ruleConfiguration.MatchDestinationAddress(driver.IPAddress)
ruleConfiguration.MatchDestinationPort(driver.SSHPort)
ruleConfiguration.PlaceFirst()
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
firewallRuleID, err := client.CreateFirewallRule(ruleConfiguration)
if err != nil {
return err
}
driver.SSHFirewallRuleID = firewallRuleID
log.Debugf("Created SSH firewall rule '%s' for server '%s'.", driver.SSHFirewallRuleID, driver.ServerID)
return nil
}
// Delete the firewall rule that enables inbound SSH connections to the target server from the client machine's (external) IP address.
func (driver *Driver) deleteSSHFirewallRule() error {
if !driver.isServerCreated() {
return fmt.Errorf("Server '%s' has not been created", driver.MachineName)
}
if !driver.isSSHFirewallRuleCreated() {
return fmt.Errorf("SSH firewall rule has not been created for server '%s'", driver.MachineName)
}
log.Debugf("Deleting SSH firewall rule '%s' for server '%s'...",
driver.MachineName,
driver.SSHFirewallRuleID,
)
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
err = client.DeleteFirewallRule(driver.SSHFirewallRuleID)
if err != nil {
return err
}
log.Debugf("Deleted SSH firewall rule '%s'.", driver.SSHFirewallRuleID)
driver.SSHFirewallRuleID = ""
return nil
}
// Has a firewall rule been created to allow inbound Docker for the server?
func (driver *Driver) isDockerFirewallRuleCreated() bool {
return driver.DockerFirewallRuleID != ""
}
// Create a firewall rule to enable inbound Docker connections to the target server from the client machine's (external) IP address.
func (driver *Driver) createDockerFirewallRule() error {
if !driver.isServerCreated() {
return fmt.Errorf("Server '%s' has not been created", driver.MachineName)
}
if driver.isDockerFirewallRuleCreated() {
return fmt.Errorf("Docker firewall rule '%s' has already been created for server '%s'", driver.DockerFirewallRuleID, driver.MachineName)
}
log.Debugf("Creating Docker firewall rule for server '%s' (allow inbound traffic on port %d from '%s' to '%s')...",
driver.MachineName,
DefaultDockerSSLPort,
driver.ClientPublicIPAddress,
driver.IPAddress,
)
ruleConfiguration := compute.FirewallRuleConfiguration{
Name: driver.buildFirewallRuleName("Docker"),
NetworkDomainID: driver.NetworkDomainID,
}
ruleConfiguration.Accept()
ruleConfiguration.Enable()
ruleConfiguration.IPv4()
ruleConfiguration.TCP()
ruleConfiguration.MatchSourceAddress(driver.ClientPublicIPAddress)
ruleConfiguration.MatchDestinationAddress(driver.IPAddress)
ruleConfiguration.MatchDestinationPort(DefaultDockerSSLPort)
ruleConfiguration.PlaceFirst()
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
firewallRuleID, err := client.CreateFirewallRule(ruleConfiguration)
if err != nil {
return err
}
driver.DockerFirewallRuleID = firewallRuleID
log.Debugf("Created Docker firewall rule '%s' for server '%s'.", driver.DockerFirewallRuleID, driver.ServerID)
return nil
}
// Delete the firewall rule that enables inbound Docker connections to the target server from the client machine's (external) IP address.
func (driver *Driver) deleteDockerFirewallRule() error {
if !driver.isServerCreated() {
return fmt.Errorf("Server '%s' has not been created", driver.MachineName)
}
if !driver.isDockerFirewallRuleCreated() {
return fmt.Errorf("Docker firewall rule has not been created for server '%s'", driver.MachineName)
}
log.Debugf("Deleting Docker firewall rule '%s' for server '%s'...",
driver.MachineName,
driver.DockerFirewallRuleID,
)
client, err := driver.getCloudControlClient()
if err != nil {
return err
}
err = client.DeleteFirewallRule(driver.DockerFirewallRuleID)
if err != nil {
return err
}
log.Debugf("Deleted Docker firewall rule '%s'.", driver.DockerFirewallRuleID)
driver.DockerFirewallRuleID = ""
return nil
}
// Name sanitiser for firewall rules.
var firewallRuleNameSanitizer = strings.NewReplacer("-", ".", "_", ".")
// Build an acceptable name for a firewall rule.
func (driver *Driver) buildFirewallRuleName(suffix string) string {
return strings.ToLower(
firewallRuleNameSanitizer.Replace(driver.MachineName) + "." + suffix,
)
}