forked from JonasProgrammer/docker-machine-driver-hetzner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
1096 lines (943 loc) · 30.2 KB
/
driver.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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"fmt"
"net"
"os"
"strings"
"time"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnflag"
"github.com/docker/machine/libmachine/mcnutils"
mcnssh "github.com/docker/machine/libmachine/ssh"
"github.com/docker/machine/libmachine/state"
"github.com/hetznercloud/hcloud-go/hcloud"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
// Driver contains hetzner-specific data to implement [drivers.Driver]
type Driver struct {
*drivers.BaseDriver
AccessToken string
Image string
ImageID int
cachedImage *hcloud.Image
Type string
cachedType *hcloud.ServerType
Location string
cachedLocation *hcloud.Location
KeyID int
cachedKey *hcloud.SSHKey
IsExistingKey bool
originalKey string
dangling []func()
ServerID int
cachedServer *hcloud.Server
userData string
Volumes []string
Networks []string
UsePrivateNetwork bool
DisablePublic4 bool
DisablePublic6 bool
Firewalls []string
ServerLabels map[string]string
keyLabels map[string]string
placementGroup string
cachedPGrp *hcloud.PlacementGroup
AdditionalKeys []string
AdditionalKeyIDs []int
cachedAdditionalKeys []*hcloud.SSHKey
}
const (
defaultImage = "ubuntu-18.04"
defaultType = "cx11"
flagAPIToken = "hetzner-api-token"
flagImage = "hetzner-image"
flagImageID = "hetzner-image-id"
flagType = "hetzner-server-type"
flagLocation = "hetzner-server-location"
flagExKeyID = "hetzner-existing-key-id"
flagExKeyPath = "hetzner-existing-key-path"
flagUserData = "hetzner-user-data"
flagVolumes = "hetzner-volumes"
flagNetworks = "hetzner-networks"
flagUsePrivateNetwork = "hetzner-use-private-network"
flagDisablePublic4 = "hetzner-disable-public-4"
flagDisablePublic6 = "hetzner-disable-public-6"
flagDisablePublic = "hetzner-disable-public"
flagFirewalls = "hetzner-firewalls"
flagAdditionalKeys = "hetzner-additional-key"
flagServerLabel = "hetzner-server-label"
flagKeyLabel = "hetzner-key-label"
flagPlacementGroup = "hetzner-placement-group"
flagAutoSpread = "hetzner-auto-spread"
flagSshUser = "hetzner-ssh-user"
flagSshPort = "hetzner-ssh-port"
labelNamespace = "docker-machine"
labelAutoSpreadPg = "auto-spread"
labelAutoCreated = "auto-created"
autoSpreadPgName = "__auto_spread"
defaultSSHPort = 22
defaultSSHUser = "root"
)
// NewDriver initializes a new driver instance; see [drivers.Driver.NewDriver]
func NewDriver() *Driver {
return &Driver{
Type: defaultType,
IsExistingKey: false,
BaseDriver: &drivers.BaseDriver{},
}
}
// DriverName returns the hard-coded string "hetzner"; see [drivers.Driver.DriverName]
func (d *Driver) DriverName() string {
return "hetzner"
}
// GetCreateFlags retrieves additional driver-specific arguments; see [drivers.Driver.GetCreateFlags]
func (d *Driver) GetCreateFlags() []mcnflag.Flag {
return []mcnflag.Flag{
mcnflag.StringFlag{
EnvVar: "HETZNER_API_TOKEN",
Name: flagAPIToken,
Usage: "Project-specific Hetzner API token",
Value: "",
},
mcnflag.StringFlag{
EnvVar: "HETZNER_IMAGE",
Name: flagImage,
Usage: "Image to use for server creation",
Value: "",
},
mcnflag.IntFlag{
EnvVar: "HETZNER_IMAGE_ID",
Name: flagImageID,
Usage: "Image to use for server creation",
},
mcnflag.StringFlag{
EnvVar: "HETZNER_TYPE",
Name: flagType,
Usage: "Server type to create",
Value: defaultType,
},
mcnflag.StringFlag{
EnvVar: "HETZNER_LOCATION",
Name: flagLocation,
Usage: "Location to create machine at",
Value: "",
},
mcnflag.IntFlag{
EnvVar: "HETZNER_EXISTING_KEY_ID",
Name: flagExKeyID,
Usage: "Existing key ID to use for server; requires --hetzner-existing-key-path",
Value: 0,
},
mcnflag.StringFlag{
EnvVar: "HETZNER_EXISTING_KEY_PATH",
Name: flagExKeyPath,
Usage: "Path to existing key (new public key will be created unless --hetzner-existing-key-id is specified)",
Value: "",
},
mcnflag.StringFlag{
EnvVar: "HETZNER_USER_DATA",
Name: flagUserData,
Usage: "Cloud-init based User data",
Value: "",
},
mcnflag.StringSliceFlag{
EnvVar: "HETZNER_VOLUMES",
Name: flagVolumes,
Usage: "Volume IDs or names which should be attached to the server",
Value: []string{},
},
mcnflag.StringSliceFlag{
EnvVar: "HETZNER_NETWORKS",
Name: flagNetworks,
Usage: "Network IDs or names which should be attached to the server private network interface",
Value: []string{},
},
mcnflag.BoolFlag{
EnvVar: "HETZNER_USE_PRIVATE_NETWORK",
Name: flagUsePrivateNetwork,
Usage: "Use private network",
},
mcnflag.BoolFlag{
EnvVar: "HETZNER_DISABLE_PUBLIC_4",
Name: flagDisablePublic4,
Usage: "Disable public ipv4",
},
mcnflag.BoolFlag{
EnvVar: "HETZNER_DISABLE_PUBLIC_6",
Name: flagDisablePublic6,
Usage: "Disable public ipv6",
},
mcnflag.BoolFlag{
EnvVar: "HETZNER_DISABLE_PUBLIC",
Name: flagDisablePublic,
Usage: "Disable public ip (v4 & v6)",
},
mcnflag.StringSliceFlag{
EnvVar: "HETZNER_FIREWALLS",
Name: flagFirewalls,
Usage: "Firewall IDs or names which should be applied on the server",
Value: []string{},
},
mcnflag.StringSliceFlag{
EnvVar: "HETZNER_ADDITIONAL_KEYS",
Name: flagAdditionalKeys,
Usage: "Additional public keys to be attached to the server",
Value: []string{},
},
mcnflag.StringSliceFlag{
EnvVar: "HETZNER_SERVER_LABELS",
Name: flagServerLabel,
Usage: "Key value pairs of additional labels to assign to the server",
Value: []string{},
},
mcnflag.StringSliceFlag{
EnvVar: "HETZNER_KEY_LABELS",
Name: flagKeyLabel,
Usage: "Key value pairs of additional labels to assign to the SSH key",
Value: []string{},
},
mcnflag.StringFlag{
EnvVar: "HETZNER_PLACEMENT_GROUP",
Name: flagPlacementGroup,
Usage: "Placement group ID or name to add the server to; will be created if it does not exist",
Value: "",
},
mcnflag.BoolFlag{
EnvVar: "HETZNER_AUTO_SPREAD",
Name: flagAutoSpread,
Usage: "Auto-spread on a docker-machine-specific default placement group",
},
mcnflag.StringFlag{
EnvVar: "HETZNER_SSH_USER",
Name: flagSshUser,
Usage: "SSH username",
Value: defaultSSHUser,
},
mcnflag.IntFlag{
EnvVar: "HETZNER_SSH_PORT",
Name: flagSshPort,
Usage: "SSH port",
Value: defaultSSHPort,
},
}
}
// SetConfigFromFlags handles additional driver arguments as retrieved by [Driver.GetCreateFlags];
// see [drivers.Driver.SetConfigFromFlags]
func (d *Driver) SetConfigFromFlags(opts drivers.DriverOptions) error {
return d.setConfigFromFlags(opts)
}
func (d *Driver) setConfigFromFlagsImpl(opts drivers.DriverOptions) error {
d.AccessToken = opts.String(flagAPIToken)
d.Image = opts.String(flagImage)
d.ImageID = opts.Int(flagImageID)
d.Location = opts.String(flagLocation)
d.Type = opts.String(flagType)
d.KeyID = opts.Int(flagExKeyID)
d.IsExistingKey = d.KeyID != 0
d.originalKey = opts.String(flagExKeyPath)
d.userData = opts.String(flagUserData)
d.Volumes = opts.StringSlice(flagVolumes)
d.Networks = opts.StringSlice(flagNetworks)
disablePublic := opts.Bool(flagDisablePublic)
d.UsePrivateNetwork = opts.Bool(flagUsePrivateNetwork) || disablePublic
d.DisablePublic4 = opts.Bool(flagDisablePublic4) || disablePublic
d.DisablePublic6 = opts.Bool(flagDisablePublic6) || disablePublic
d.Firewalls = opts.StringSlice(flagFirewalls)
d.AdditionalKeys = opts.StringSlice(flagAdditionalKeys)
d.SSHUser = opts.String(flagSshUser)
d.SSHPort = opts.Int(flagSshPort)
d.placementGroup = opts.String(flagPlacementGroup)
if opts.Bool(flagAutoSpread) {
if d.placementGroup != "" {
return d.flagFailure("%v and %v are mutually exclusive", flagAutoSpread, flagPlacementGroup)
}
d.placementGroup = autoSpreadPgName
}
err := d.setLabelsFromFlags(opts)
if err != nil {
return err
}
d.SetSwarmConfigFromFlags(opts)
if d.AccessToken == "" {
return d.flagFailure("hetzner requires --%v to be set", flagAPIToken)
}
if d.ImageID != 0 && d.Image != "" && d.Image != defaultImage /* support legacy behaviour */ {
return d.flagFailure("--%v and --%v are mutually exclusive", flagImage, flagImageID)
} else if d.ImageID == 0 && d.Image == "" {
d.Image = defaultImage
}
if d.DisablePublic4 && d.DisablePublic6 && !d.UsePrivateNetwork {
return d.flagFailure("--%v must be used if public networking is disabled (hint: implicitly set by --%v)",
flagUsePrivateNetwork, flagDisablePublic)
}
return nil
}
// GetSSHUsername retrieves the SSH username used to connect to the server during provisioning
func (d *Driver) GetSSHUsername() string {
return d.SSHUser
}
// GetSSHPort retrieves the port used to connect to the server during provisioning
func (d *Driver) GetSSHPort() (int, error) {
return d.SSHPort, nil
}
func (d *Driver) setLabelsFromFlags(opts drivers.DriverOptions) error {
d.ServerLabels = make(map[string]string)
for _, label := range opts.StringSlice(flagServerLabel) {
split := strings.SplitN(label, "=", 2)
if len(split) != 2 {
return d.flagFailure("server label %v is not in key=value format", label)
}
d.ServerLabels[split[0]] = split[1]
}
d.keyLabels = make(map[string]string)
for _, label := range opts.StringSlice(flagKeyLabel) {
split := strings.SplitN(label, "=", 2)
if len(split) != 2 {
return errors.Errorf("key label %v is not in key=value format", label)
}
d.keyLabels[split[0]] = split[1]
}
return nil
}
// PreCreateCheck validates the Driver data is in a valid state for creation; see [drivers.Driver.PreCreateCheck]
func (d *Driver) PreCreateCheck() error {
if d.IsExistingKey {
if d.originalKey == "" {
return d.flagFailure("specifying an existing key ID requires the existing key path to be set as well")
}
key, err := d.getKey()
if err != nil {
return errors.Wrap(err, "could not get key")
}
buf, err := os.ReadFile(d.originalKey + ".pub")
if err != nil {
return errors.Wrap(err, "could not read public key")
}
// Will also parse `ssh-rsa w309jwf0e39jf asdf` public keys
pubk, _, _, _, err := ssh.ParseAuthorizedKey(buf)
if err != nil {
return errors.Wrap(err, "could not parse authorized key")
}
if key.Fingerprint != ssh.FingerprintLegacyMD5(pubk) &&
key.Fingerprint != ssh.FingerprintSHA256(pubk) {
return errors.Errorf("remote key %d does not match local key %s", d.KeyID, d.originalKey)
}
}
if _, err := d.getType(); err != nil {
return errors.Wrap(err, "could not get type")
}
if _, err := d.getImage(); err != nil {
return errors.Wrap(err, "could not get image")
}
if _, err := d.getLocation(); err != nil {
return errors.Wrap(err, "could not get location")
}
if _, err := d.getPlacementGroup(); err != nil {
return fmt.Errorf("could not create placement group: %w", err)
}
if d.UsePrivateNetwork && len(d.Networks) == 0 {
return errors.Errorf("No private network attached.")
}
return nil
}
// Create actually creates the hetzner-cloud server; see [drivers.Driver.Create]
func (d *Driver) Create() error {
err := d.prepareLocalKey()
if err != nil {
return err
}
defer d.destroyDangling()
err = d.createRemoteKeys()
if err != nil {
return err
}
log.Infof("Creating Hetzner server...")
srvopts, err := d.makeCreateServerOptions()
if err != nil {
return err
}
srv, _, err := d.getClient().Server.Create(context.Background(), *srvopts)
if err != nil {
return errors.Wrap(err, "could not create server")
}
log.Infof(" -> Creating server %s[%d] in %s[%d]", srv.Server.Name, srv.Server.ID, srv.Action.Command, srv.Action.ID)
if err = d.waitForAction(srv.Action); err != nil {
return errors.Wrap(err, "could not wait for action")
}
d.ServerID = srv.Server.ID
log.Infof(" -> Server %s[%d]: Waiting to come up...", srv.Server.Name, srv.Server.ID)
err = d.waitForRunningServer()
if err != nil {
return err
}
err = d.configureNetworkAccess(srv)
if err != nil {
return err
}
log.Infof(" -> Server %s[%d] ready. Ip %s", srv.Server.Name, srv.Server.ID, d.IPAddress)
// Successful creation, so no keys dangle anymore
d.dangling = nil
return nil
}
func (d *Driver) configureNetworkAccess(srv hcloud.ServerCreateResult) error {
if d.UsePrivateNetwork {
for {
// we need to wait until network is attached
log.Infof("Wait until private network attached ...")
server, _, err := d.getClient().Server.GetByID(context.Background(), srv.Server.ID)
if err != nil {
return errors.Wrapf(err, "could not get newly created server [%d]", srv.Server.ID)
}
if server.PrivateNet != nil {
d.IPAddress = server.PrivateNet[0].IP.String()
break
}
time.Sleep(1 * time.Second)
}
} else if d.DisablePublic4 {
log.Infof("Using public IPv6 network ...")
pv6 := srv.Server.PublicNet.IPv6
ip := pv6.IP
if ip.Mask(pv6.Network.Mask).Equal(pv6.Network.IP) { // no host given
ip[net.IPv6len-1] |= 0x01 // TODO make this configurable
}
ips := ip.String()
log.Infof(" -> resolved %v ...", ips)
d.IPAddress = ips
} else {
log.Infof("Using public network ...")
d.IPAddress = srv.Server.PublicNet.IPv4.IP.String()
}
return nil
}
func (d *Driver) waitForRunningServer() error {
for {
srvstate, err := d.GetState()
if err != nil {
return errors.Wrap(err, "could not get state")
}
if srvstate == state.Running {
break
}
time.Sleep(1 * time.Second)
}
return nil
}
func (d *Driver) makeCreateServerOptions() (*hcloud.ServerCreateOpts, error) {
pgrp, err := d.getPlacementGroup()
if err != nil {
return nil, err
}
srvopts := hcloud.ServerCreateOpts{
Name: d.GetMachineName(),
UserData: d.userData,
Labels: d.ServerLabels,
PlacementGroup: pgrp,
}
if d.DisablePublic4 || d.DisablePublic6 {
srvopts.PublicNet = &hcloud.ServerCreatePublicNet{
EnableIPv4: !d.DisablePublic4,
EnableIPv6: !d.DisablePublic6,
}
}
networks, err := d.createNetworks()
if err != nil {
return nil, err
}
srvopts.Networks = networks
firewalls, err := d.createFirewalls()
if err != nil {
return nil, err
}
srvopts.Firewalls = firewalls
volumes, err := d.createVolumes()
if err != nil {
return nil, err
}
srvopts.Volumes = volumes
if srvopts.Location, err = d.getLocation(); err != nil {
return nil, errors.Wrap(err, "could not get location")
}
if srvopts.ServerType, err = d.getType(); err != nil {
return nil, errors.Wrap(err, "could not get type")
}
if srvopts.Image, err = d.getImage(); err != nil {
return nil, errors.Wrap(err, "could not get image")
}
key, err := d.getKey()
if err != nil {
return nil, errors.Wrap(err, "could not get ssh key")
}
srvopts.SSHKeys = append(d.cachedAdditionalKeys, key)
return &srvopts, nil
}
func (d *Driver) createNetworks() ([]*hcloud.Network, error) {
networks := []*hcloud.Network{}
for _, networkIDorName := range d.Networks {
network, _, err := d.getClient().Network.Get(context.Background(), networkIDorName)
if err != nil {
return nil, errors.Wrap(err, "could not get network by ID or name")
}
if network == nil {
return nil, errors.Errorf("network '%s' not found", networkIDorName)
}
networks = append(networks, network)
}
return networks, nil
}
func (d *Driver) createFirewalls() ([]*hcloud.ServerCreateFirewall, error) {
firewalls := []*hcloud.ServerCreateFirewall{}
for _, firewallIDorName := range d.Firewalls {
firewall, _, err := d.getClient().Firewall.Get(context.Background(), firewallIDorName)
if err != nil {
return nil, errors.Wrap(err, "could not get firewall by ID or name")
}
if firewall == nil {
return nil, errors.Errorf("firewall '%s' not found", firewallIDorName)
}
firewalls = append(firewalls, &hcloud.ServerCreateFirewall{Firewall: *firewall})
}
return firewalls, nil
}
func (d *Driver) createVolumes() ([]*hcloud.Volume, error) {
volumes := []*hcloud.Volume{}
for _, volumeIDorName := range d.Volumes {
volume, _, err := d.getClient().Volume.Get(context.Background(), volumeIDorName)
if err != nil {
return nil, errors.Wrap(err, "could not get volume by ID or name")
}
if volume == nil {
return nil, errors.Errorf("volume '%s' not found", volumeIDorName)
}
volumes = append(volumes, volume)
}
return volumes, nil
}
func (d *Driver) createRemoteKeys() error {
if d.KeyID == 0 {
log.Infof("Creating SSH key...")
buf, err := os.ReadFile(d.GetSSHKeyPath() + ".pub")
if err != nil {
return errors.Wrap(err, "could not read ssh public key")
}
key, err := d.getRemoteKeyWithSameFingerprint(buf)
if err != nil {
return errors.Wrap(err, "error retrieving potentially existing key")
}
if key == nil {
log.Infof("SSH key not found in Hetzner. Uploading...")
key, err = d.makeKey(d.GetMachineName(), string(buf), d.keyLabels)
if err != nil {
return err
}
} else {
d.IsExistingKey = true
log.Debugf("SSH key found in Hetzner. ID: %d", key.ID)
}
d.KeyID = key.ID
}
for i, pubkey := range d.AdditionalKeys {
key, err := d.getRemoteKeyWithSameFingerprint([]byte(pubkey))
if err != nil {
return errors.Wrapf(err, "error checking for existing key for %v", pubkey)
}
if key == nil {
log.Infof("Creating new key for %v...", pubkey)
key, err = d.makeKey(fmt.Sprintf("%v-additional-%d", d.GetMachineName(), i), pubkey, d.keyLabels)
if err != nil {
return errors.Wrapf(err, "error creating new key for %v", pubkey)
}
log.Infof(" -> Created %v", key.ID)
d.AdditionalKeyIDs = append(d.AdditionalKeyIDs, key.ID)
} else {
log.Infof("Using existing key (%v) %v", key.ID, key.Name)
}
d.cachedAdditionalKeys = append(d.cachedAdditionalKeys, key)
}
return nil
}
func (d *Driver) prepareLocalKey() error {
if d.originalKey != "" {
log.Debugf("Copying SSH key...")
if err := d.copySSHKeyPair(d.originalKey); err != nil {
return errors.Wrap(err, "could not copy ssh key pair")
}
} else {
log.Debugf("Generating SSH key...")
if err := mcnssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {
return errors.Wrap(err, "could not generate ssh key")
}
}
return nil
}
// Creates a new key for the machine and appends it to the dangling key list
func (d *Driver) makeKey(name string, pubkey string, labels map[string]string) (*hcloud.SSHKey, error) {
keyopts := hcloud.SSHKeyCreateOpts{
Name: name,
PublicKey: pubkey,
Labels: labels,
}
key, _, err := d.getClient().SSHKey.Create(context.Background(), keyopts)
if err != nil {
return nil, errors.Wrap(err, "could not create ssh key")
} else if key == nil {
return nil, errors.Errorf("key upload did not return an error, but key was nil")
}
d.dangling = append(d.dangling, func() {
_, err := d.getClient().SSHKey.Delete(context.Background(), key)
if err != nil {
log.Error(fmt.Errorf("could not delete ssh key: %w", err))
}
})
return key, nil
}
func (d *Driver) destroyDangling() {
for _, destructor := range d.dangling {
destructor()
}
}
// GetSSHHostname retrieves the SSH host to connect to the machine; see [drivers.Driver.GetSSHHostname]
func (d *Driver) GetSSHHostname() (string, error) {
return d.GetIP()
}
// GetURL retrieves the URL of the docker daemon on the machine; see [drivers.Driver.GetURL]
func (d *Driver) GetURL() (string, error) {
if err := drivers.MustBeRunning(d); err != nil {
return "", errors.Wrap(err, "could not execute drivers.MustBeRunning")
}
ip, err := d.GetIP()
if err != nil {
return "", errors.Wrap(err, "could not get IP")
}
return fmt.Sprintf("tcp://%s", net.JoinHostPort(ip, "2376")), nil
}
// GetState retrieves the state the machine is currently in; see [drivers.Driver.GetState]
func (d *Driver) GetState() (state.State, error) {
srv, _, err := d.getClient().Server.GetByID(context.Background(), d.ServerID)
if err != nil {
return state.None, errors.Wrap(err, "could not get server by ID")
}
if srv == nil {
return state.None, errors.New("server not found")
}
switch srv.Status {
case hcloud.ServerStatusInitializing:
return state.Starting, nil
case hcloud.ServerStatusRunning:
return state.Running, nil
case hcloud.ServerStatusOff:
return state.Stopped, nil
}
return state.None, nil
}
// Remove deletes the hetzner server and additional resources created during creation; see [drivers.Driver.Remove]
func (d *Driver) Remove() error {
if d.ServerID != 0 {
srv, err := d.getServerHandle()
if err != nil {
return errors.Wrap(err, "could not get server handle")
}
if srv == nil {
log.Infof(" -> Server does not exist anymore")
} else {
log.Infof(" -> Destroying server %s[%d] in...", srv.Name, srv.ID)
if _, err := d.getClient().Server.Delete(context.Background(), srv); err != nil {
return errors.Wrap(err, "could not delete server")
}
// failure to remove a placement group is not a hard error
if softErr := d.removeEmptyServerPlacementGroup(srv); softErr != nil {
log.Error(softErr)
}
}
}
// failure to remove a key is not ha hard error
for i, id := range d.AdditionalKeyIDs {
log.Infof(" -> Destroying additional key #%d (%d)", i, id)
key, _, softErr := d.getClient().SSHKey.GetByID(context.Background(), id)
if softErr != nil {
log.Warnf(" -> -> could not retrieve key %v", softErr)
} else if key == nil {
log.Warnf(" -> -> %d no longer exists", id)
}
_, softErr = d.getClient().SSHKey.Delete(context.Background(), key)
if softErr != nil {
log.Warnf(" -> -> could not remove key: %v", softErr)
}
}
// failure to remove a server-specific key is a hard error
if !d.IsExistingKey && d.KeyID != 0 {
key, err := d.getKey()
if err != nil {
return errors.Wrap(err, "could not get ssh key")
}
if key == nil {
log.Infof(" -> SSH key does not exist anymore")
return nil
}
log.Infof(" -> Destroying SSHKey %s[%d]...", key.Name, key.ID)
if _, err := d.getClient().SSHKey.Delete(context.Background(), key); err != nil {
return errors.Wrap(err, "could not delete ssh key")
}
}
return nil
}
// Restart instructs the hetzner cloud server to reboot; see [drivers.Driver.Restart]
func (d *Driver) Restart() error {
srv, err := d.getServerHandle()
if err != nil {
return errors.Wrap(err, "could not get server handle")
}
if srv == nil {
return errors.New("server not found")
}
act, _, err := d.getClient().Server.Reboot(context.Background(), srv)
if err != nil {
return errors.Wrap(err, "could not reboot server")
}
log.Infof(" -> Rebooting server %s[%d] in %s[%d]...", srv.Name, srv.ID, act.Command, act.ID)
return d.waitForAction(act)
}
// Start instructs the hetzner cloud server to power up; see [drivers.Driver.Start]
func (d *Driver) Start() error {
srv, err := d.getServerHandle()
if err != nil {
return errors.Wrap(err, "could not get server handle")
}
if srv == nil {
return errors.New("server not found")
}
act, _, err := d.getClient().Server.Poweron(context.Background(), srv)
if err != nil {
return errors.Wrap(err, "could not power on server")
}
log.Infof(" -> Starting server %s[%d] in %s[%d]...", srv.Name, srv.ID, act.Command, act.ID)
return d.waitForAction(act)
}
// Stop instructs the hetzner cloud server to shut down; see [drivers.Driver.Stop]
func (d *Driver) Stop() error {
srv, err := d.getServerHandle()
if err != nil {
return errors.Wrap(err, "could not get server handle")
}
if srv == nil {
return errors.New("server not found")
}
act, _, err := d.getClient().Server.Shutdown(context.Background(), srv)
if err != nil {
return errors.Wrap(err, "could not shutdown server")
}
log.Infof(" -> Shutting down server %s[%d] in %s[%d]...", srv.Name, srv.ID, act.Command, act.ID)
return d.waitForAction(act)
}
// Kill forcefully shuts down the hetzner cloud server; see [drivers.Driver.Kill]
func (d *Driver) Kill() error {
srv, err := d.getServerHandle()
if err != nil {
return errors.Wrap(err, "could not get server handle")
}
if srv == nil {
return errors.New("server not found")
}
act, _, err := d.getClient().Server.Poweroff(context.Background(), srv)
if err != nil {
return errors.Wrap(err, "could not poweroff server")
}
log.Infof(" -> Powering off server %s[%d] in %s[%d]...", srv.Name, srv.ID, act.Command, act.ID)
return d.waitForAction(act)
}
func (d *Driver) getClient() *hcloud.Client {
return hcloud.NewClient(hcloud.WithToken(d.AccessToken), hcloud.WithApplication("docker-machine-driver", Version))
}
func (d *Driver) copySSHKeyPair(src string) error {
if err := mcnutils.CopyFile(src, d.GetSSHKeyPath()); err != nil {
return errors.Wrap(err, "could not copy ssh key")
}
if err := mcnutils.CopyFile(src+".pub", d.GetSSHKeyPath()+".pub"); err != nil {
return errors.Wrap(err, "could not copy ssh public key")
}
if err := os.Chmod(d.GetSSHKeyPath(), 0600); err != nil {
return errors.Wrap(err, "could not set permissions on the ssh key")
}
return nil
}
func (d *Driver) getLocation() (*hcloud.Location, error) {
if d.cachedLocation != nil {
return d.cachedLocation, nil
}
location, _, err := d.getClient().Location.GetByName(context.Background(), d.Location)
if err != nil {
return location, errors.Wrap(err, "could not get location by name")
}
d.cachedLocation = location
return location, nil
}
func (d *Driver) getType() (*hcloud.ServerType, error) {
if d.cachedType != nil {
return d.cachedType, nil
}
stype, _, err := d.getClient().ServerType.GetByName(context.Background(), d.Type)
if err != nil {
return stype, errors.Wrap(err, "could not get type by name")
}
d.cachedType = stype
return stype, nil
}
func (d *Driver) getImage() (*hcloud.Image, error) {
if d.cachedImage != nil {
return d.cachedImage, nil
}
var image *hcloud.Image
var err error
if d.ImageID != 0 {
image, _, err = d.getClient().Image.GetByID(context.Background(), d.ImageID)
if err != nil {
return image, errors.Wrap(err, fmt.Sprintf("could not get image by id %v", d.ImageID))
}
} else {
image, _, err = d.getClient().Image.GetByName(context.Background(), d.Image)
if err != nil {
return image, errors.Wrap(err, fmt.Sprintf("could not get image by name %v", d.Image))
}
}
d.cachedImage = image
return image, nil
}
func (d *Driver) getKey() (*hcloud.SSHKey, error) {
if d.cachedKey != nil {
return d.cachedKey, nil
}
stype, _, err := d.getClient().SSHKey.GetByID(context.Background(), d.KeyID)
if err != nil {
return stype, errors.Wrap(err, "could not get sshkey by ID")
}
d.cachedKey = stype
return stype, nil
}
func (d *Driver) getRemoteKeyWithSameFingerprint(publicKeyBytes []byte) (*hcloud.SSHKey, error) {
publicKey, _, _, _, err := ssh.ParseAuthorizedKey(publicKeyBytes)
if err != nil {
return nil, errors.Wrap(err, "could not parse ssh public key")
}
fp := ssh.FingerprintLegacyMD5(publicKey)
remoteKey, _, err := d.getClient().SSHKey.GetByFingerprint(context.Background(), fp)
if err != nil {
return remoteKey, errors.Wrap(err, "could not get sshkey by fingerprint")
}
return remoteKey, nil
}
func (d *Driver) getServerHandle() (*hcloud.Server, error) {
if d.cachedServer != nil {
return d.cachedServer, nil
}
if d.ServerID == 0 {
return nil, errors.New("server ID was 0")
}
srv, _, err := d.getClient().Server.GetByID(context.Background(), d.ServerID)
if err != nil {
return nil, errors.Wrap(err, "could not get client by ID")
}
d.cachedServer = srv
return srv, nil
}
func (d *Driver) waitForAction(a *hcloud.Action) error {
for {
act, _, err := d.getClient().Action.GetByID(context.Background(), a.ID)
if err != nil {
return errors.Wrap(err, "could not get client by ID")
}
if act.Status == hcloud.ActionStatusSuccess {
log.Debugf(" -> finished %s[%d]", act.Command, act.ID)
break
} else if act.Status == hcloud.ActionStatusRunning {
log.Debugf(" -> %s[%d]: %d %%", act.Command, act.ID, act.Progress)
} else if act.Status == hcloud.ActionStatusError {
return act.Error()
}
time.Sleep(1 * time.Second)
}
return nil
}
func (d *Driver) labelName(name string) string {