/
api.go
678 lines (579 loc) · 17.5 KB
/
api.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
// Copyright 2018 Red Hat
//
// 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 openstack
import (
"fmt"
"net/url"
"os"
"strings"
"time"
"github.com/coreos/pkg/capnslog"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingips"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/keypairs"
"github.com/gophercloud/gophercloud/openstack/compute/v2/flavors"
computeImages "github.com/gophercloud/gophercloud/openstack/compute/v2/images"
"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/imagedata"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport"
"github.com/gophercloud/gophercloud/openstack/imageservice/v2/images"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/groups"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/rules"
"github.com/gophercloud/gophercloud/openstack/networking/v2/networks"
"github.com/gophercloud/gophercloud/pagination"
ugroups "github.com/gophercloud/utils/openstack/networking/v2/extensions/security/groups"
"github.com/flatcar/mantle/auth"
"github.com/flatcar/mantle/platform"
"github.com/flatcar/mantle/util"
)
var (
plog = capnslog.NewPackageLogger("github.com/flatcar/mantle", "platform/api/openstack")
)
type Options struct {
*platform.Options
// Config file. Defaults to $HOME/.config/openstack.json.
ConfigPath string
// Profile name
Profile string
// Region (e.g. "regionOne")
Region string
// Instance Flavor ID
Flavor string
// Image ID
Image string
// Network ID
Network string
// Domain ID
Domain string
// Floating IP Pool
FloatingIPPool string
// Host can be used to optionally SSH into deployed VMs from the OpenStack host
Host string
// User is the one used for the SSH connection to the Host
User string
// Keyfile is the abs. path to private SSH key file for the User on the Host
Keyfile string
}
type Server struct {
Server *servers.Server
FloatingIP *floatingips.FloatingIP
}
type API struct {
opts *Options
computeClient *gophercloud.ServiceClient
imageClient *gophercloud.ServiceClient
networkClient *gophercloud.ServiceClient
}
func New(opts *Options) (*API, error) {
profiles, err := auth.ReadOpenStackConfig(opts.ConfigPath)
if err != nil {
return nil, fmt.Errorf("couldn't read OpenStack config: %v", err)
}
if opts.Profile == "" {
opts.Profile = "default"
}
profile, ok := profiles[opts.Profile]
if !ok {
return nil, fmt.Errorf("no such profile %q", opts.Profile)
}
if opts.Domain == "" {
opts.Domain = profile.Domain
}
osOpts := gophercloud.AuthOptions{
IdentityEndpoint: profile.AuthURL,
TenantID: profile.TenantID,
TenantName: profile.TenantName,
Username: profile.Username,
Password: profile.Password,
DomainID: profile.DomainID,
}
provider, err := openstack.AuthenticatedClient(osOpts)
if err != nil {
return nil, fmt.Errorf("failed creating provider: %v", err)
}
if opts.Region == "" {
opts.Region = profile.Region
}
computeClient, err := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{
Name: "nova",
Region: opts.Region,
})
if err != nil {
return nil, fmt.Errorf("failed to create compute client: %v", err)
}
imageClient, err := openstack.NewImageServiceV2(provider, gophercloud.EndpointOpts{
Name: "glance",
Region: opts.Region,
})
if err != nil {
return nil, fmt.Errorf("failed to create image client: %v", err)
}
networkClient, err := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{
Name: "neutron",
Region: opts.Region,
})
a := &API{
opts: opts,
computeClient: computeClient,
imageClient: imageClient,
networkClient: networkClient,
}
if a.opts.Flavor != "" {
tmp, err := a.resolveFlavor()
if err != nil {
return nil, fmt.Errorf("resolving flavor: %v", err)
}
a.opts.Flavor = tmp
}
if a.opts.Image != "" {
tmp, err := a.ResolveImage(a.opts.Image)
if err != nil {
return nil, fmt.Errorf("resolving image: %v", err)
}
a.opts.Image = tmp
}
if a.opts.Network != "" {
tmp, err := a.resolveNetwork()
if err != nil {
return nil, fmt.Errorf("resolving network: %v", err)
}
a.opts.Network = tmp
}
if a.opts.FloatingIPPool == "" {
a.opts.FloatingIPPool = profile.FloatingIPPool
}
return a, nil
}
func unwrapPages(pager pagination.Pager, allowEmpty bool) (pagination.Page, error) {
if pager.Err != nil {
return nil, fmt.Errorf("retrieving pager: %v", pager.Err)
}
pages, err := pager.AllPages()
if err != nil {
return nil, fmt.Errorf("retrieving pages: %v", err)
}
if !allowEmpty {
empty, err := pages.IsEmpty()
if err != nil {
return nil, fmt.Errorf("parsing pages: %v", err)
}
if empty {
return nil, fmt.Errorf("empty pager")
}
}
return pages, nil
}
func (a *API) resolveFlavor() (string, error) {
pager := flavors.ListDetail(a.computeClient, flavors.ListOpts{})
pages, err := unwrapPages(pager, false)
if err != nil {
return "", fmt.Errorf("flavors: %v", err)
}
flavors, err := flavors.ExtractFlavors(pages)
if err != nil {
return "", fmt.Errorf("extracting flavors: %v", err)
}
for _, flavor := range flavors {
if flavor.ID == a.opts.Flavor || flavor.Name == a.opts.Flavor {
return flavor.ID, nil
}
}
return "", fmt.Errorf("specified flavor %q not found", a.opts.Flavor)
}
func (a *API) ResolveImage(img string) (string, error) {
pager := computeImages.ListDetail(a.computeClient, computeImages.ListOpts{})
pages, err := unwrapPages(pager, false)
if err != nil {
return "", fmt.Errorf("images: %v", err)
}
images, err := computeImages.ExtractImages(pages)
if err != nil {
return "", fmt.Errorf("extracting images: %v", err)
}
for _, image := range images {
if image.ID == img || image.Name == img {
return image.ID, nil
}
}
return "", fmt.Errorf("specified image %q not found", img)
}
func (a *API) resolveNetwork() (string, error) {
networks, err := a.getNetworks()
if err != nil {
return "", err
}
for _, network := range networks {
if network.ID == a.opts.Network || network.Name == a.opts.Network {
return network.ID, nil
}
}
return "", fmt.Errorf("specified network %q not found", a.opts.Network)
}
func (a *API) PreflightCheck() error {
if err := servers.List(a.computeClient, servers.ListOpts{}).Err; err != nil {
return fmt.Errorf("listing servers: %v", err)
}
return nil
}
func (a *API) CreateServer(name, sshKeyID, userdata string) (*Server, error) {
networkID := a.opts.Network
if networkID == "" {
networks, err := a.getNetworks()
if err != nil {
return nil, fmt.Errorf("getting network: %v", err)
}
networkID = networks[0].ID
}
securityGroup, err := a.getSecurityGroup()
if err != nil {
return nil, fmt.Errorf("retrieving security group: %v", err)
}
server, err := servers.Create(a.computeClient, keypairs.CreateOptsExt{
CreateOptsBuilder: servers.CreateOpts{
Name: name,
FlavorRef: a.opts.Flavor,
ImageRef: a.opts.Image,
Metadata: map[string]string{
"CreatedBy": "mantle",
},
SecurityGroups: []string{securityGroup},
Networks: []servers.Network{
{
UUID: networkID,
},
},
UserData: []byte(userdata),
},
KeyName: sshKeyID,
}).Extract()
if err != nil {
return nil, fmt.Errorf("creating server: %v", err)
}
serverID := server.ID
err = util.WaitUntilReady(5*time.Minute, 10*time.Second, func() (bool, error) {
var err error
server, err = servers.Get(a.computeClient, serverID).Extract()
if err != nil {
return false, err
}
return server.Status == "ACTIVE", nil
})
if err != nil {
a.DeleteServer(serverID)
return nil, fmt.Errorf("waiting for instance to run: %v", err)
}
var floatingip *floatingips.FloatingIP
if a.opts.FloatingIPPool != "" {
floatingip, err = a.createFloatingIP()
if err != nil {
a.DeleteServer(serverID)
return nil, fmt.Errorf("creating floating ip: %v", err)
}
err = floatingips.AssociateInstance(a.computeClient, serverID, floatingips.AssociateOpts{
FloatingIP: floatingip.IP,
}).ExtractErr()
if err != nil {
a.DeleteServer(serverID)
// Explicitly delete the floating ip as DeleteServer only deletes floating IPs that are
// associated with servers
a.deleteFloatingIP(floatingip.ID)
return nil, fmt.Errorf("associating floating ip: %v", err)
}
server, err = servers.Get(a.computeClient, serverID).Extract()
if err != nil {
a.DeleteServer(serverID)
return nil, fmt.Errorf("retrieving server info: %v", err)
}
}
return &Server{
Server: server,
FloatingIP: floatingip,
}, nil
}
func (a *API) getNetworks() ([]networks.Network, error) {
pager := networks.List(a.networkClient, networks.ListOpts{})
pages, err := unwrapPages(pager, false)
if err != nil {
return nil, fmt.Errorf("networks: %v", err)
}
networks, err := networks.ExtractNetworks(pages)
if err != nil {
return nil, fmt.Errorf("extracting networks: %v", err)
}
return networks, nil
}
func (a *API) getSecurityGroup() (string, error) {
id, err := ugroups.IDFromName(a.networkClient, "kola")
if err != nil {
if _, ok := err.(gophercloud.ErrResourceNotFound); ok {
return a.createSecurityGroup()
}
return "", fmt.Errorf("finding security group: %v", err)
}
return id, nil
}
func (a *API) createSecurityGroup() (string, error) {
securityGroup, err := groups.Create(a.networkClient, groups.CreateOpts{
Name: "kola",
}).Extract()
if err != nil {
return "", fmt.Errorf("creating security group: %v", err)
}
ruleSet := []struct {
Direction rules.RuleDirection
EtherType rules.RuleEtherType
Protocol rules.RuleProtocol
PortRangeMin int
PortRangeMax int
RemoteGroupID string
RemoteIPPrefix string
}{
{
Direction: rules.DirIngress,
EtherType: rules.EtherType4,
RemoteGroupID: securityGroup.ID,
},
{
Direction: rules.DirIngress,
EtherType: rules.EtherType4,
Protocol: rules.ProtocolTCP,
PortRangeMin: 22,
PortRangeMax: 22,
RemoteIPPrefix: "0.0.0.0/0",
},
{
Direction: rules.DirIngress,
EtherType: rules.EtherType6,
RemoteGroupID: securityGroup.ID,
},
{
Direction: rules.DirIngress,
EtherType: rules.EtherType4,
Protocol: rules.ProtocolTCP,
PortRangeMin: 2379,
PortRangeMax: 2380,
RemoteIPPrefix: "0.0.0.0/0",
},
}
for _, rule := range ruleSet {
_, err = rules.Create(a.networkClient, rules.CreateOpts{
Direction: rule.Direction,
EtherType: rule.EtherType,
SecGroupID: securityGroup.ID,
PortRangeMax: rule.PortRangeMax,
PortRangeMin: rule.PortRangeMin,
Protocol: rule.Protocol,
RemoteGroupID: rule.RemoteGroupID,
RemoteIPPrefix: rule.RemoteIPPrefix,
}).Extract()
if err != nil {
a.deleteSecurityGroup(securityGroup.ID)
return "", fmt.Errorf("adding security rule: %v", err)
}
}
return securityGroup.ID, nil
}
func (a *API) deleteSecurityGroup(id string) error {
return groups.Delete(a.networkClient, id).ExtractErr()
}
func (a *API) createFloatingIP() (*floatingips.FloatingIP, error) {
return floatingips.Create(a.computeClient, floatingips.CreateOpts{
Pool: a.opts.FloatingIPPool,
}).Extract()
}
func (a *API) disassociateFloatingIP(serverID, id string) error {
return floatingips.DisassociateInstance(a.computeClient, serverID, floatingips.DisassociateOpts{
FloatingIP: id,
}).ExtractErr()
}
func (a *API) deleteFloatingIP(id string) error {
return floatingips.Delete(a.computeClient, id).ExtractErr()
}
func (a *API) findFloatingIP(serverID string) (*floatingips.FloatingIP, error) {
pager := floatingips.List(a.computeClient)
pages, err := unwrapPages(pager, true)
if err != nil {
return nil, fmt.Errorf("floating ips: %v", err)
}
floatingiplist, err := floatingips.ExtractFloatingIPs(pages)
if err != nil {
return nil, fmt.Errorf("extracting floating ips: %v", err)
}
for _, floatingip := range floatingiplist {
if floatingip.InstanceID == serverID {
return &floatingip, nil
}
}
return nil, nil
}
// Deletes the server, and disassociates & deletes any floating IP associated with the given server.
func (a *API) DeleteServer(id string) error {
fip, err := a.findFloatingIP(id)
if err != nil {
return err
}
if fip != nil {
if err := a.disassociateFloatingIP(id, fip.IP); err != nil {
return fmt.Errorf("couldn't disassociate floating ip %s from server %s: %v", fip.ID, id, err)
}
if err := a.deleteFloatingIP(fip.ID); err != nil {
// if the deletion of this floating IP fails then mantle cannot detect the floating IP was tied to the
// server anymore. as such warn and continue deleting the server.
plog.Warningf("couldn't delete floating ip %s: %v", fip.ID, err)
}
}
if err := servers.Delete(a.computeClient, id).ExtractErr(); err != nil {
return fmt.Errorf("deleting server: %v: %v", id, err)
}
return nil
}
func (a *API) GetConsoleOutput(id string) (string, error) {
return servers.ShowConsoleOutput(a.computeClient, id, servers.ShowConsoleOutputOpts{}).Extract()
}
func (a *API) webUpload(ID, URI string) error {
createOpts := imageimport.CreateOpts{
Name: imageimport.WebDownloadMethod,
URI: URI,
}
if err := imageimport.Create(a.imageClient, ID, createOpts).ExtractErr(); err != nil {
return fmt.Errorf("importing web image: %w", err)
}
return nil
}
func (a *API) UploadImage(name, path string) (string, error) {
image, err := images.Create(a.imageClient, images.CreateOpts{
Name: name,
ContainerFormat: "bare",
DiskFormat: "qcow2",
Tags: []string{"mantle"},
}).Extract()
if err != nil {
return "", fmt.Errorf("creating image: %v", err)
}
u, err := url.Parse(path)
if err == nil && u.Scheme != "" && image.ID != "" {
plog.Debug("creating image from URL")
if err := a.webUpload(image.ID, path); err != nil {
a.DeleteImage(image.ID)
return "", fmt.Errorf("web uploading: %w", err)
}
// It usually takes around 10 seconds to extract the image.
if err := util.WaitUntilReady(1*time.Minute, 5*time.Second, func() (bool, error) {
image, err = images.Get(a.imageClient, image.ID).Extract()
if err != nil {
return false, fmt.Errorf("getting image status: %w", err)
}
return image.Status == images.ImageStatusActive, nil
}); err != nil {
return "", fmt.Errorf("getting image active: %w", err)
}
return image.ID, nil
}
plog.Debug("creating image from source file")
data, err := os.Open(path)
if err != nil {
a.DeleteImage(image.ID)
return "", fmt.Errorf("opening image file: %v", err)
}
defer data.Close()
err = imagedata.Upload(a.imageClient, image.ID, data).ExtractErr()
if err != nil {
a.DeleteImage(image.ID)
return "", fmt.Errorf("uploading image data: %v", err)
}
return image.ID, nil
}
func (a *API) DeleteImage(imageID string) error {
return images.Delete(a.imageClient, imageID).ExtractErr()
}
func (a *API) AddKey(name, key string) error {
_, err := keypairs.Create(a.computeClient, keypairs.CreateOpts{
Name: name,
PublicKey: key,
}).Extract()
return err
}
func (a *API) DeleteKey(name string) error {
return keypairs.Delete(a.computeClient, name, nil).ExtractErr()
}
func (a *API) listServersWithMetadata(metadata map[string]string) ([]servers.Server, error) {
pager := servers.List(a.computeClient, servers.ListOpts{})
pages, err := unwrapPages(pager, true)
if err != nil {
return nil, fmt.Errorf("servers: %v", err)
}
allServers, err := servers.ExtractServers(pages)
if err != nil {
return nil, fmt.Errorf("extracting servers: %v", err)
}
var retServers []servers.Server
for _, server := range allServers {
isMatch := true
for key, val := range metadata {
if value, ok := server.Metadata[key]; !ok || val != value {
isMatch = false
break
}
}
if isMatch {
retServers = append(retServers, server)
}
}
return retServers, nil
}
func (a *API) listImagesWithTags(tags []string) ([]images.Image, error) {
listOpts := images.ListOpts{
Tags: tags,
}
allPages, err := images.List(a.imageClient, listOpts).AllPages()
if err != nil {
return nil, fmt.Errorf("listing images: %w", err)
}
allImages, err := images.ExtractImages(allPages)
if err != nil {
return nil, fmt.Errorf("extracting image list: %w", err)
}
return allImages, nil
}
func (a *API) GC(gracePeriod time.Duration) error {
threshold := time.Now().Add(-gracePeriod)
servers, err := a.listServersWithMetadata(map[string]string{
"CreatedBy": "mantle",
})
if err != nil {
return err
}
for _, server := range servers {
if strings.Contains(server.Status, "DELETED") || server.Created.After(threshold) {
continue
}
if err := a.DeleteServer(server.ID); err != nil {
return fmt.Errorf("couldn't delete server %s: %v", server.ID, err)
}
}
images, err := a.listImagesWithTags([]string{"mantle"})
if err != nil {
return fmt.Errorf("listing Mantle images: %w", err)
}
for _, image := range images {
if image.CreatedAt.After(threshold) {
continue
}
if err := a.DeleteImage(image.ID); err != nil {
return fmt.Errorf("deleting image with name: %s", image.Name)
}
}
return nil
}