-
Notifications
You must be signed in to change notification settings - Fork 124
/
provider.go
566 lines (482 loc) · 16.7 KB
/
provider.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
/*
Copyright 2019 The Machine Controller Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package digitalocean
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"time"
"github.com/digitalocean/godo"
"go.uber.org/zap"
"golang.org/x/oauth2"
"github.com/kubermatic/machine-controller/pkg/apis/cluster/common"
clusterv1alpha1 "github.com/kubermatic/machine-controller/pkg/apis/cluster/v1alpha1"
"github.com/kubermatic/machine-controller/pkg/cloudprovider/common/ssh"
cloudprovidererrors "github.com/kubermatic/machine-controller/pkg/cloudprovider/errors"
"github.com/kubermatic/machine-controller/pkg/cloudprovider/instance"
digitaloceantypes "github.com/kubermatic/machine-controller/pkg/cloudprovider/provider/digitalocean/types"
cloudprovidertypes "github.com/kubermatic/machine-controller/pkg/cloudprovider/types"
"github.com/kubermatic/machine-controller/pkg/cloudprovider/util"
"github.com/kubermatic/machine-controller/pkg/providerconfig"
providerconfigtypes "github.com/kubermatic/machine-controller/pkg/providerconfig/types"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
)
type provider struct {
configVarResolver *providerconfig.ConfigVarResolver
}
// New returns a digitalocean provider.
func New(configVarResolver *providerconfig.ConfigVarResolver) cloudprovidertypes.Provider {
return &provider{configVarResolver: configVarResolver}
}
type Config struct {
Token string
Region string
Size string
Backups bool
IPv6 bool
PrivateNetworking bool
Monitoring bool
Tags []string
}
const (
createCheckPeriod = 10 * time.Second
createCheckTimeout = 5 * time.Minute
createCheckFailedWaitPeriod = 10 * time.Second
)
type TokenSource struct {
AccessToken string
}
func (t *TokenSource) Token() (*oauth2.Token, error) {
token := &oauth2.Token{
AccessToken: t.AccessToken,
}
return token, nil
}
func getSlugForOS(os providerconfigtypes.OperatingSystem) (string, error) {
switch os {
case providerconfigtypes.OperatingSystemUbuntu:
return "ubuntu-22-04-x64", nil
case providerconfigtypes.OperatingSystemCentOS:
return "centos-7-x64", nil
case providerconfigtypes.OperatingSystemRockyLinux:
return "rockylinux-8-x64", nil
}
return "", providerconfigtypes.ErrOSNotSupported
}
func getClient(ctx context.Context, token string) *godo.Client {
tokenSource := &TokenSource{
AccessToken: token,
}
oauthClient := oauth2.NewClient(ctx, tokenSource)
return godo.NewClient(oauthClient)
}
func (p *provider) getConfig(provSpec clusterv1alpha1.ProviderSpec) (*Config, *providerconfigtypes.Config, error) {
if provSpec.Value == nil {
return nil, nil, fmt.Errorf("machine.spec.providerconfig.value is nil")
}
pconfig, err := providerconfigtypes.GetConfig(provSpec)
if err != nil {
return nil, nil, err
}
if pconfig.OperatingSystemSpec.Raw == nil {
return nil, nil, errors.New("operatingSystemSpec in the MachineDeployment cannot be empty")
}
rawConfig, err := digitaloceantypes.GetConfig(*pconfig)
if err != nil {
return nil, nil, err
}
c := Config{}
c.Token, err = p.configVarResolver.GetConfigVarStringValueOrEnv(rawConfig.Token, "DO_TOKEN")
if err != nil {
return nil, nil, fmt.Errorf("failed to get the value of \"token\" field, error = %w", err)
}
c.Region, err = p.configVarResolver.GetConfigVarStringValue(rawConfig.Region)
if err != nil {
return nil, nil, err
}
c.Size, err = p.configVarResolver.GetConfigVarStringValue(rawConfig.Size)
if err != nil {
return nil, nil, err
}
c.Backups, _, err = p.configVarResolver.GetConfigVarBoolValue(rawConfig.Backups)
if err != nil {
return nil, nil, err
}
c.IPv6, _, err = p.configVarResolver.GetConfigVarBoolValue(rawConfig.IPv6)
if err != nil {
return nil, nil, err
}
c.PrivateNetworking, _, err = p.configVarResolver.GetConfigVarBoolValue(rawConfig.PrivateNetworking)
if err != nil {
return nil, nil, err
}
c.Monitoring, _, err = p.configVarResolver.GetConfigVarBoolValue(rawConfig.Monitoring)
if err != nil {
return nil, nil, err
}
for _, tag := range rawConfig.Tags {
tagVal, err := p.configVarResolver.GetConfigVarStringValue(tag)
if err != nil {
return nil, nil, err
}
c.Tags = append(c.Tags, tagVal)
}
return &c, pconfig, err
}
func (p *provider) AddDefaults(_ *zap.SugaredLogger, spec clusterv1alpha1.MachineSpec) (clusterv1alpha1.MachineSpec, error) {
return spec, nil
}
func (p *provider) Validate(ctx context.Context, _ *zap.SugaredLogger, spec clusterv1alpha1.MachineSpec) error {
c, pc, err := p.getConfig(spec.ProviderSpec)
if err != nil {
return fmt.Errorf("failed to parse config: %w", err)
}
if c.Token == "" {
return errors.New("token is missing")
}
if c.Region == "" {
return errors.New("region is missing")
}
if c.Size == "" {
return errors.New("size is missing")
}
_, err = getSlugForOS(pc.OperatingSystem)
if err != nil {
return fmt.Errorf("invalid operating system specified %q: %w", pc.OperatingSystem, err)
}
switch f := pc.Network.GetIPFamily(); f {
case util.IPFamilyUnspecified, util.IPFamilyIPv4:
// noop
case util.IPFamilyIPv6:
return fmt.Errorf(util.ErrIPv6OnlyUnsupported)
case util.IPFamilyIPv4IPv6, util.IPFamilyIPv6IPv4:
// noop
default:
return fmt.Errorf(util.ErrUnknownNetworkFamily, f)
}
client := getClient(ctx, c.Token)
regions, _, err := client.Regions.List(ctx, &godo.ListOptions{PerPage: 1000})
if err != nil {
return err
}
var foundRegion bool
for _, region := range regions {
if region.Slug == c.Region {
foundRegion = true
break
}
}
if !foundRegion {
return fmt.Errorf("region %q not found", c.Region)
}
sizes, _, err := client.Sizes.List(ctx, &godo.ListOptions{PerPage: 1000})
if err != nil {
return err
}
var foundSize bool
for _, size := range sizes {
if size.Slug == c.Size {
if !size.Available {
return fmt.Errorf("size is not available")
}
var regionAvailable bool
for _, region := range size.Regions {
if region == c.Region {
regionAvailable = true
break
}
}
if !regionAvailable {
return fmt.Errorf("size %q is not available in region %q", c.Size, c.Region)
}
foundSize = true
break
}
}
if !foundSize {
return fmt.Errorf("size %q not found", c.Size)
}
return nil
}
// uploadRandomSSHPublicKey generates a random key pair and uploads the public part of the key to
// digital ocean because it is not possible to create a droplet without ssh key assigned
// this method returns an error if the key already exists.
func uploadRandomSSHPublicKey(ctx context.Context, service godo.KeysService) (string, error) {
sshkey, err := ssh.NewKey()
if err != nil {
return "", fmt.Errorf("failed to generate ssh key: %w", err)
}
existingkey, res, err := service.GetByFingerprint(ctx, sshkey.FingerprintMD5)
if err == nil && existingkey != nil && res.StatusCode >= http.StatusOK && res.StatusCode <= http.StatusAccepted {
return "", fmt.Errorf("failed to create ssh public key, the key already exists")
}
newDoKey, rsp, err := service.Create(ctx, &godo.KeyCreateRequest{
PublicKey: sshkey.PublicKey,
Name: sshkey.Name,
})
if err != nil {
return "", doStatusAndErrToTerminalError(rsp.StatusCode, fmt.Errorf("failed to create ssh public key on digitalocean: %w", err))
}
return newDoKey.Fingerprint, nil
}
func (p *provider) Create(ctx context.Context, log *zap.SugaredLogger, machine *clusterv1alpha1.Machine, _ *cloudprovidertypes.ProviderData, userdata string) (instance.Instance, error) {
c, pc, err := p.getConfig(machine.Spec.ProviderSpec)
if err != nil {
return nil, cloudprovidererrors.TerminalError{
Reason: common.InvalidConfigurationMachineError,
Message: fmt.Sprintf("Failed to parse MachineSpec, due to %v", err),
}
}
client := getClient(ctx, c.Token)
fingerprint, err := uploadRandomSSHPublicKey(ctx, client.Keys)
if err != nil {
return nil, err
}
defer func() {
_, err := client.Keys.DeleteByFingerprint(ctx, fingerprint)
if err != nil {
log.Errorw("Failed to remove a temporary ssh key", "fingerprint", fingerprint, zap.Error(err))
}
}()
slug, err := getSlugForOS(pc.OperatingSystem)
if err != nil {
return nil, cloudprovidererrors.TerminalError{
Reason: common.InvalidConfigurationMachineError,
Message: fmt.Sprintf("Failed to parse MachineSpec, invalid operating system specified %q: %v", pc.OperatingSystem, err),
}
}
createRequest := &godo.DropletCreateRequest{
Image: godo.DropletCreateImage{Slug: slug},
Name: machine.Spec.Name,
Region: c.Region,
Size: c.Size,
IPv6: c.IPv6 || pc.Network.GetIPFamily().IsDualstack(),
PrivateNetworking: c.PrivateNetworking,
Backups: c.Backups,
Monitoring: c.Monitoring,
UserData: userdata,
SSHKeys: []godo.DropletCreateSSHKey{{Fingerprint: fingerprint}},
Tags: append(c.Tags, string(machine.UID)),
}
droplet, rsp, err := client.Droplets.Create(ctx, createRequest)
if err != nil {
return nil, doStatusAndErrToTerminalError(rsp.StatusCode, err)
}
dropletLog := log.With("droplet", droplet.ID)
//We need to wait until the droplet really got created as tags will be only applied when the droplet is running
err = wait.PollUntilContextTimeout(ctx, createCheckPeriod, createCheckTimeout, false, func(ctx context.Context) (bool, error) {
newDroplet, rsp, err := client.Droplets.Get(ctx, droplet.ID)
if err != nil {
tErr := doStatusAndErrToTerminalError(rsp.StatusCode, err)
if isTerminalError, _, _ := cloudprovidererrors.IsTerminalError(tErr); isTerminalError {
return true, tErr
}
//Well just wait 10 sec and hope the droplet got started by then...
time.Sleep(createCheckFailedWaitPeriod)
return false, fmt.Errorf("droplet %q got created but we failed to fetch its status", droplet.ID)
}
if sets.NewString(newDroplet.Tags...).Has(string(machine.UID)) {
dropletLog.Debug("Droplet got fully created")
return true, nil
}
dropletLog.Debug("Waiting until droplet got fully created...")
return false, nil
})
return &doInstance{droplet: droplet}, err
}
func (p *provider) Cleanup(ctx context.Context, _ *zap.SugaredLogger, machine *clusterv1alpha1.Machine, _ *cloudprovidertypes.ProviderData) (bool, error) {
instance, err := p.get(ctx, machine)
if err != nil {
if errors.Is(err, cloudprovidererrors.ErrInstanceNotFound) {
return true, nil
}
return false, err
}
c, _, err := p.getConfig(machine.Spec.ProviderSpec)
if err != nil {
return false, cloudprovidererrors.TerminalError{
Reason: common.InvalidConfigurationMachineError,
Message: fmt.Sprintf("Failed to parse MachineSpec, due to %v", err),
}
}
client := getClient(ctx, c.Token)
doID, err := strconv.Atoi(instance.ID())
if err != nil {
return false, fmt.Errorf("failed to convert instance id %s to int: %w", instance.ID(), err)
}
rsp, err := client.Droplets.Delete(ctx, doID)
if err != nil {
return false, doStatusAndErrToTerminalError(rsp.StatusCode, err)
}
return false, nil
}
func (p *provider) Get(ctx context.Context, _ *zap.SugaredLogger, machine *clusterv1alpha1.Machine, _ *cloudprovidertypes.ProviderData) (instance.Instance, error) {
return p.get(ctx, machine)
}
func (p *provider) get(ctx context.Context, machine *clusterv1alpha1.Machine) (*doInstance, error) {
c, _, err := p.getConfig(machine.Spec.ProviderSpec)
if err != nil {
return nil, cloudprovidererrors.TerminalError{
Reason: common.InvalidConfigurationMachineError,
Message: fmt.Sprintf("Failed to parse MachineSpec, due to %v", err),
}
}
droplets, err := p.listDroplets(ctx, c.Token)
if err != nil {
return nil, err
}
for i, droplet := range droplets {
if droplet.Name == machine.Spec.Name && sets.NewString(droplet.Tags...).Has(string(machine.UID)) {
return &doInstance{droplet: &droplets[i]}, nil
}
}
return nil, cloudprovidererrors.ErrInstanceNotFound
}
func (p *provider) listDroplets(ctx context.Context, token string) ([]godo.Droplet, error) {
client := getClient(ctx, token)
result := make([]godo.Droplet, 0)
opt := &godo.ListOptions{
PerPage: 200,
}
for {
droplets, resp, err := client.Droplets.List(ctx, opt)
if err != nil {
return nil, doStatusAndErrToTerminalError(resp.StatusCode, fmt.Errorf("failed to get droplets: %w", err))
}
result = append(result, droplets...)
if resp.Links == nil || resp.Links.IsLastPage() {
break
}
page, err := resp.Links.CurrentPage()
if err != nil {
return nil, err
}
opt.Page = page + 1
}
return result, nil
}
func (p *provider) MigrateUID(ctx context.Context, _ *zap.SugaredLogger, machine *clusterv1alpha1.Machine, newUID types.UID) error {
c, _, err := p.getConfig(machine.Spec.ProviderSpec)
if err != nil {
return fmt.Errorf("failed to decode providerconfig: %w", err)
}
client := getClient(ctx, c.Token)
droplets, _, err := client.Droplets.List(ctx, &godo.ListOptions{PerPage: 1000})
if err != nil {
return fmt.Errorf("failed to list droplets: %w", err)
}
// The create does not fail if that tag already exists, it even keep responding with a http/201
_, response, err := client.Tags.Create(ctx, &godo.TagCreateRequest{Name: string(newUID)})
if err != nil {
return fmt.Errorf("failed to create new UID tag: %w, status code: %v", err, response.StatusCode)
}
for _, droplet := range droplets {
if droplet.Name == machine.Spec.Name && sets.NewString(droplet.Tags...).Has(string(machine.UID)) {
tagResourceRequest := &godo.TagResourcesRequest{
Resources: []godo.Resource{{ID: strconv.Itoa(droplet.ID), Type: godo.DropletResourceType}},
}
_, err = client.Tags.TagResources(ctx, string(newUID), tagResourceRequest)
if err != nil {
return fmt.Errorf("failed to tag droplet with new UID tag: %w", err)
}
untagResourceRequest := &godo.UntagResourcesRequest{
Resources: []godo.Resource{{ID: strconv.Itoa(droplet.ID), Type: godo.DropletResourceType}},
}
_, err = client.Tags.UntagResources(ctx, string(machine.UID), untagResourceRequest)
if err != nil {
return fmt.Errorf("failed to remove old UID tag: %w", err)
}
}
}
return nil
}
func (p *provider) GetCloudConfig(_ clusterv1alpha1.MachineSpec) (config string, name string, err error) {
return "", "", nil
}
func (p *provider) MachineMetricsLabels(machine *clusterv1alpha1.Machine) (map[string]string, error) {
labels := make(map[string]string)
c, _, err := p.getConfig(machine.Spec.ProviderSpec)
if err == nil {
labels["size"] = c.Size
labels["region"] = c.Region
}
return labels, err
}
type doInstance struct {
droplet *godo.Droplet
}
func (d *doInstance) Name() string {
return d.droplet.Name
}
func (d *doInstance) ID() string {
return strconv.Itoa(d.droplet.ID)
}
func (d *doInstance) ProviderID() string {
if d.droplet == nil || d.droplet.Name == "" {
return ""
}
return fmt.Sprintf("digitalocean://%d", d.droplet.ID)
}
func (d *doInstance) Addresses() map[string]v1.NodeAddressType {
addresses := map[string]v1.NodeAddressType{}
for _, n := range d.droplet.Networks.V4 {
if n.Type == "public" {
addresses[n.IPAddress] = v1.NodeExternalIP
} else {
addresses[n.IPAddress] = v1.NodeInternalIP
}
}
for _, n := range d.droplet.Networks.V6 {
if n.Type == "public" {
addresses[n.IPAddress] = v1.NodeExternalIP
} else {
addresses[n.IPAddress] = v1.NodeInternalIP
}
}
return addresses
}
func (d *doInstance) Status() instance.Status {
switch d.droplet.Status {
case "new":
return instance.StatusCreating
case "active":
return instance.StatusRunning
default:
return instance.StatusUnknown
}
}
// doStatusAndErrToTerminalError judges if the given HTTP status
// can be qualified as a "terminal" error, for more info see v1alpha1.MachineStatus
// if the given error doesn't qualify the error passed as
// an argument will be returned.
func doStatusAndErrToTerminalError(status int, err error) error {
switch status {
case http.StatusUnauthorized:
// authorization primitives come from MachineSpec
// thus we are setting InvalidConfigurationMachineError
return cloudprovidererrors.TerminalError{
Reason: common.InvalidConfigurationMachineError,
Message: "A request has been rejected due to invalid credentials which were taken from the MachineSpec",
}
default:
return err
}
}
func (p *provider) SetMetricsForMachines(_ clusterv1alpha1.MachineList) error {
return nil
}