/
cloud.go
723 lines (617 loc) · 22.3 KB
/
cloud.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
package cloud
import (
"context"
"encoding/base64"
"fmt"
"net"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/bokwoon95/sq"
"github.com/pkg/errors"
"github.com/protosio/protos/internal/auth"
"github.com/protosio/protos/internal/db"
"github.com/protosio/protos/internal/p2p"
"github.com/protosio/protos/internal/p2p/proto"
"github.com/protosio/protos/internal/pcrypto"
"github.com/protosio/protos/internal/release"
"github.com/protosio/protos/internal/util"
)
var log = util.GetLogger("cloud")
type PeerConfigurator interface {
Refresh() error
}
// Type represents a specific cloud (AWS, GCP, DigitalOcean etc.)
type Type string
func (ct Type) String() string {
return string(ct)
}
const (
// Scaleway cloud provider
Scaleway = Type("scaleway")
// Local is a local VM provider
Local = Type("local")
)
// CreateManager creates and returns a cloud manager
func CreateManager(db *db.DB, um *auth.AuthManager, sm *pcrypto.Manager, p2p *p2p.P2P, configurator PeerConfigurator, selfName string) (*Manager, error) {
if db == nil || um == nil || sm == nil || p2p == nil {
return nil, fmt.Errorf("failed to create cloud manager: none of the inputs can be nil")
}
manager := &Manager{db: db, um: um, sm: sm, p2p: p2p, configurator: configurator}
return manager, nil
}
// Manager manages cloud providers and instances
type Manager struct {
db *db.DB
um *auth.AuthManager
sm *pcrypto.Manager
p2p *p2p.P2P
configurator PeerConfigurator
}
//
// Cloud manager methods
//
// NewProvider creates and returns a cloud provider. At this point it is not saved in the db
func (cm *Manager) NewProvider(cloudName string, cloud string) (CloudProvider, error) {
cloudType := Type(cloud)
cld := ProviderInfo{Name: cloudName, Type: cloudType, cm: cm}
return cld.getCloudProvider()
}
// SupportedProviders returns a list of supported cloud providers
func (cm *Manager) SupportedProviders() []string {
return []string{Scaleway.String()}
}
// GetProvider returns a cloud provider instance from the db
func (cm *Manager) GetProvider(name string) (CloudProvider, error) {
cpModel := sq.New[db.CLOUD_PROVIDER]("")
cpi, err := db.SelectOne(cm.db, createCloudProviderQueryMapper(cpModel, []sq.Predicate{cpModel.NAME.EqString(name)}))
if err != nil {
return nil, fmt.Errorf("failed to retrieve cloud provider '%s': %w", name, err)
}
cp, err := cpi.getCloudProvider()
if err != nil {
return nil, fmt.Errorf("failed to retrieve cloud provider '%s': %w", name, err)
}
return cp, fmt.Errorf("could not find cloud provider '%s'", name)
}
// DeleteProvider deletes a cloud provider from the db
func (cm *Manager) DeleteProvider(name string) error {
cld, err := cm.GetProvider(name)
if err != nil {
return err
}
providerInfo, ok := cld.(*ProviderInfo)
if !ok {
panic("Failed type assertion in delete provider")
}
err = db.Delete(cm.db, createInstanceDeleteByNameQuery(providerInfo.Name))
if err != nil {
return fmt.Errorf("failed to delete instance '%s': %w", name, err)
}
return nil
}
// GetProviders returns all the cloud providers from the db
func (cm *Manager) GetProviders() ([]CloudProvider, error) {
cloudProviders := []CloudProvider{}
clouds, err := db.SelectMultiple(cm.db, createCloudProviderQueryMapper(sq.New[db.CLOUD_PROVIDER](""), nil))
if err != nil {
return cloudProviders, fmt.Errorf("failed to retrieve cloud providers: %w", err)
}
for _, cloud := range clouds {
client, err := cloud.getCloudProvider()
if err != nil {
return cloudProviders, err
}
cloudProviders = append(cloudProviders, client)
}
return cloudProviders, nil
}
//
// Instance related methods
//
// DeployInstance deploys an instance on the provided cloud
func (cm *Manager) DeployInstance(instanceName string, cloudName string, cloudLocation string, release release.Release, machineType string) (InstanceInfo, error) {
usr, err := cm.um.GetAdmin()
if err != nil {
return InstanceInfo{}, err
}
// init cloud
provider, err := cm.GetProvider(cloudName)
if err != nil {
return InstanceInfo{}, fmt.Errorf("could not retrieve cloud '%s': %w", cloudName, err)
}
err = provider.Init()
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to init cloud provider '%s'(%s) API: %w", cloudName, provider.TypeStr(), err)
}
// validate machine type
supportedMachineTypes, err := provider.SupportedMachines(cloudLocation)
if err != nil {
return InstanceInfo{}, err
}
if _, found := supportedMachineTypes[machineType]; !found {
return InstanceInfo{}, errors.Errorf("Machine type '%s' is not valid for cloud provider '%s'. The following types are supported: \n%s", machineType, provider.TypeStr(), createMachineTypesString(supportedMachineTypes))
}
// add image
imageID := ""
images, err := provider.GetImages()
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to deploy Protos instance: %w", err)
}
for id, img := range images {
if img.Location == cloudLocation && img.Name == release.Version {
imageID = id
break
}
}
if imageID != "" {
log.Infof("found Protos image version '%s' in your cloud account", release.Version)
} else {
// upload protos image
if image, found := release.CloudImages[provider.TypeStr()]; found {
log.Infof("Protos image version '%s' not in your infra cloud account. Adding it.", release.Version)
imageID, err = provider.AddImage(image.URL, image.Digest, release.Version, cloudLocation)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to deploy Protos instance: %w", err)
}
} else {
return InstanceInfo{}, errors.Errorf("could not find a Protos version '%s' release for cloud '%s'", release.Version, provider.TypeStr())
}
}
// create SSH key used for instance
log.Info("Generating SSH key for the new VM instance")
instanceSSHKey, err := cm.sm.GenerateKey()
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to deploy Protos instance: %w", err)
}
// deploy a protos instance
log.Infof("Deploying instance '%s' of type '%s', using Protos version '%s' (image id '%s')", instanceName, machineType, release.Version, imageID)
vmID, err := provider.NewInstance(instanceName, imageID, instanceSSHKey.AuthorizedKey(), machineType, cloudLocation)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to deploy Protos instance: %w", err)
}
log.Infof("Instance with ID '%s' deployed", vmID)
// get instance info
instanceInfo, err := provider.GetInstanceInfo(vmID, cloudLocation)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to get Protos instance info: %w", err)
}
// allocate network
instances, err := cm.GetInstances()
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to allocate network for instance '%s': %w", instanceInfo.Name, err)
}
userDevices := usr.GetDevices()
network, err := allocateNetwork(instances, userDevices)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to allocate network for instance '%s': %w", instanceInfo.Name, err)
}
thisDevice, err := cm.um.GetCurrentDevice()
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to get current device : %w", err)
}
// save instance information
instanceInfo.SSHKeySeed = base64.StdEncoding.EncodeToString(instanceSSHKey.Seed())
instanceInfo.ProtosVersion = release.Version
instanceInfo.Network = network.String()
// create protos data volume
log.Infof("creating data volume for Protos instance '%s'", instanceName)
volumeID, err := provider.NewVolume(instanceName, 30000, cloudLocation)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to create data volume: %w", err)
}
// attach volume to instance
err = provider.AttachVolume(volumeID, vmID, cloudLocation)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to attach volume to instance '%s': %w", instanceName, err)
}
// start protos instance
log.Infof("Starting instance '%s'", instanceName)
err = provider.StartInstance(vmID, cloudLocation)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to start instance: %w", err)
}
// get instance info again
instanceUpdate, err := provider.GetInstanceInfo(vmID, cloudLocation)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to get instance info: %w", err)
}
instanceInfo.PublicIP = instanceUpdate.PublicIP
instanceInfo.Volumes = instanceUpdate.Volumes
// wait for port 22 to be open
err = util.WaitForPort(instanceInfo.PublicIP, "22", 20)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to deploy instance: %w", err)
}
// connect via SSH
sshCon, err := pcrypto.NewConnection(instanceInfo.PublicIP, "root", instanceSSHKey.SSHAuth(), 10)
if err != nil {
return InstanceInfo{}, err
}
// retrieve instance public key via SSH
instanceInfo.PublicKey, err = pcrypto.ExecuteCommand(fmt.Sprintf("cat %s", protosPublicKey), sshCon)
if err != nil {
return InstanceInfo{}, err
}
// close SSH connection
sshCon.Close()
p2pClient, err := cm.p2p.AddPeer(instanceInfo)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to initialize instance: %w", err)
}
// do the initialization
log.Infof("Initializing instance '%s'", instanceName)
resp, err := p2pClient.Init(context.TODO(), &proto.InitRequest{OriginDevice: thisDevice.GetName(), OriginDevicePublicKey: thisDevice.GetPublicKey(), Network: instanceInfo.Network, InstanceName: instanceName})
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to initialize instance: %w", err)
}
instanceUpdate, err = provider.GetInstanceInfo(vmID, cloudLocation)
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to get instance info: %w", err)
}
// final save instance info
instanceInfo.InternalIP = resp.InstanceIp
instanceInfo.Architecture = resp.Architecture
instanceInfo.Status = instanceUpdate.Status
err = db.Insert(cm.db, createInstanceInsertMapper(instanceInfo))
if err != nil {
return InstanceInfo{}, fmt.Errorf("failed to save instance '%s': %w", instanceName, err)
}
log.Infof("Instance '%s' at '%s' is ready", instanceName, instanceInfo.PublicIP)
return instanceInfo, nil
}
// InitDevInstance initializes an existing instance, without deploying one. Used for development purposes
func (cm *Manager) InitDevInstance(instanceName string, cloudName string, locationName string, keyFile string, ipString string) error {
instanceInfo := InstanceInfo{
VMID: instanceName,
PublicIP: ipString,
Name: instanceName,
CloudType: Local.String(),
CloudName: cloudName,
Location: locationName,
ProtosVersion: "dev",
}
ip := net.ParseIP(ipString)
if ip == nil {
return fmt.Errorf("String '%s' is not a valid IP address", ipString)
}
// we use a local key because we don't have a dedicated SSH key for the dev instance
sshAuth, err := cm.sm.NewAuthFromKeyFile(keyFile)
if err != nil {
return err
}
// allocate network for dev instance
instances, err := cm.GetInstances()
if err != nil {
return err
}
usr, err := cm.um.GetAdmin()
if err != nil {
return err
}
userDevices := usr.GetDevices()
developmentNetwork, err := allocateNetwork(instances, userDevices)
if err != nil {
return fmt.Errorf("failed to allocate network for instance '%s': %w", "dev", err)
}
thisDevice, err := cm.um.GetCurrentDevice()
if err != nil {
return fmt.Errorf("failed to get current device : %w", err)
}
// wait for port 22 to be open
err = util.WaitForPort(instanceInfo.PublicIP, "22", 20)
if err != nil {
return fmt.Errorf("failure while waiting for port: %w", err)
}
// connect via SSH
sshCon, err := pcrypto.NewConnection(instanceInfo.PublicIP, "root", sshAuth, 10)
if err != nil {
return fmt.Errorf("failed to connect to dev instance over SSH: %w", err)
}
// retrieve instance public key via SSH
instanceInfo.PublicKey, err = pcrypto.ExecuteCommand(fmt.Sprintf("cat %s", protosPublicKey), sshCon)
if err != nil {
return fmt.Errorf("failed to retrieve public key from dev instance: %w", err)
}
// close SSH connection
sshCon.Close()
p2pClient, err := cm.p2p.AddPeer(instanceInfo)
if err != nil {
return fmt.Errorf("failed to initialize instance: %w", err)
}
// do the initialization
log.Infof("Initializing instance '%s'", instanceName)
resp, err := p2pClient.Init(context.TODO(), &proto.InitRequest{OriginDevice: thisDevice.GetName(), OriginDevicePublicKey: thisDevice.GetPublicKey(), Network: developmentNetwork.String(), InstanceName: instanceName})
if err != nil {
return fmt.Errorf("failed to init dev instance: %w", err)
}
instanceInfo.InternalIP = ip.String()
instanceInfo.Architecture = resp.Architecture
instanceInfo.Network = developmentNetwork.String()
err = db.Insert(cm.db, createInstanceInsertMapper(instanceInfo))
if err != nil {
return fmt.Errorf("failed to save dev instance '%s': %w", instanceName, err)
}
log.Infof("Dev instance '%s' at '%s' is ready", instanceName, ipString)
return nil
}
// DeleteInstance deletes an instance
func (cm *Manager) DeleteInstance(name string) error {
instance, err := cm.GetInstance(name)
if err != nil {
return fmt.Errorf("could not retrieve instance '%s': %w", name, err)
}
// if local only, ignore any cloud resources
if instance.CloudType != string(Local) {
provider, err := cm.GetProvider(instance.CloudName)
if err != nil {
return fmt.Errorf("could not retrieve cloud '%s': %w", name, err)
}
err = provider.Init()
if err != nil {
return fmt.Errorf("could not init cloud '%s': %w", name, err)
}
found := true
vmInfo, err := provider.GetInstanceInfo(instance.VMID, instance.Location)
if err != nil {
if strings.Contains(err.Error(), "not found") {
found = false
} else {
return fmt.Errorf("failed to get details for instance '%s': %w", name, err)
}
}
// only delete cloud instance if found. Otherwise we proceed with removing it from local db
if found {
if vmInfo.Status == ServerStateRunning {
log.Infof("Stopping instance '%s' (%s)", instance.Name, instance.VMID)
err = provider.StopInstance(instance.VMID, instance.Location)
if err != nil {
return fmt.Errorf("could not stop instance '%s': %w", name, err)
}
}
log.Infof("Deleting instance '%s' (%s)", instance.Name, instance.VMID)
err = provider.DeleteInstance(instance.VMID, instance.Location)
if err != nil {
return fmt.Errorf("could not delete instance '%s': %w", name, err)
}
for _, vol := range vmInfo.Volumes {
log.Infof("Deleting volume '%s' (%s) for instance '%s'", vol.Name, vol.VolumeID, name)
err = provider.DeleteVolume(vol.VolumeID, instance.Location)
if err != nil {
log.Errorf("failed to delete volume '%s': %s", vol.Name, err.Error())
}
}
}
}
err = db.Delete(cm.db, createInstanceDeleteByNameQuery(instance.Name))
if err != nil {
return fmt.Errorf("failed to delete instance '%s': %w", name, err)
}
return nil
}
// StartInstance starts an instance
func (cm *Manager) StartInstance(name string) error {
instance, err := cm.GetInstance(name)
if err != nil {
return fmt.Errorf("could not retrieve instance '%s': %w", name, err)
}
provider, err := cm.GetProvider(instance.CloudName)
if err != nil {
return fmt.Errorf("could not retrieve cloud '%s': %w", name, err)
}
err = provider.Init()
if err != nil {
return fmt.Errorf("could not init cloud '%s': %w", name, err)
}
log.Infof("Starting instance '%s' (%s)", instance.Name, instance.VMID)
err = provider.StartInstance(instance.VMID, instance.Location)
if err != nil {
return fmt.Errorf("could not start instance '%s': %w", name, err)
}
// IP can change if an instance is stopped and started so a refresh is required
info, err := provider.GetInstanceInfo(instance.VMID, instance.Location)
if err != nil {
return fmt.Errorf("could not retrieve instance info for '%s': %w", name, err)
}
instance.PublicIP = info.PublicIP
instance.Volumes = info.Volumes
err = db.Update(cm.db, createInstanceUpdateMapper(instance))
if err != nil {
return fmt.Errorf("failed to save instance '%s': %w", name, err)
}
return nil
}
// StopInstance stops an instance
func (cm *Manager) StopInstance(name string) error {
instance, err := cm.GetInstance(name)
if err != nil {
return fmt.Errorf("could not retrieve instance '%s': %w", name, err)
}
provider, err := cm.GetProvider(instance.CloudName)
if err != nil {
return fmt.Errorf("could not retrieve cloud '%s': %w", name, err)
}
err = provider.Init()
if err != nil {
return fmt.Errorf("could not init cloud '%s': %w", name, err)
}
log.Infof("Stopping instance '%s' (%s)", instance.Name, instance.VMID)
err = provider.StopInstance(instance.VMID, instance.Location)
if err != nil {
return fmt.Errorf("could not stop instance '%s': %w", name, err)
}
return nil
}
// TunnelInstance creates and SSH tunnel to the instance
func (cm *Manager) TunnelInstance(name string) error {
instanceInfo, err := cm.GetInstance(name)
if err != nil {
return fmt.Errorf("could not retrieve instance '%s': %w", name, err)
}
key, err := cm.sm.NewKeyFromSeed(instanceInfo.SSHKeySeed)
if err != nil {
return fmt.Errorf("instance '%s' has an invalid SSH key: %w", name, err)
}
log.Infof("creating SSH tunnel to instance '%s', using ip '%s'", instanceInfo.Name, instanceInfo.PublicIP)
tunnel := pcrypto.NewTunnel(instanceInfo.PublicIP+":22", "root", key.SSHAuth(), "localhost:8080")
localPort, err := tunnel.Start()
if err != nil {
return fmt.Errorf("error while creating the SSH tunnel: %w", err)
}
quit := make(chan interface{}, 1)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go catchSignals(sigs, quit)
log.Infof("SSH tunnel ready. Use 'http://localhost:%d/' to access the instance dashboard. Once finished, press CTRL+C to terminate the SSH tunnel", localPort)
// waiting for a SIGTERM or SIGINT
<-quit
log.Info("CTRL+C received. Terminating the SSH tunnel")
err = tunnel.Close()
if err != nil {
return fmt.Errorf("error while terminating the SSH tunnel: %w", err)
}
log.Info("SSH tunnel terminated successfully")
return nil
}
// LogsRemoteInstance retrieves the Protos logs from an instance, via SSH
func (cm *Manager) LogsRemoteInstance(name string) (string, error) {
instanceInfo, err := cm.GetInstance(name)
if err != nil {
return "", err
}
if len(instanceInfo.SSHKeySeed) == 0 {
return "", fmt.Errorf("cannot find SSH key for instance '%s'", name)
}
key, err := cm.sm.NewKeyFromSeed(instanceInfo.SSHKeySeed)
if err != nil {
return "", err
}
sshCon, err := pcrypto.NewConnection(instanceInfo.PublicIP, "root", key.SSHAuth(), 10)
if err != nil {
return "", err
}
output, err := pcrypto.ExecuteCommand("cat /var/log/protos.log", sshCon)
if err != nil {
return "", err
}
return output, nil
}
// GetInstance retrieves an instance from the db and returns it
func (cm *Manager) GetInstance(name string) (InstanceInfo, error) {
instanceModel := sq.New[db.INSTANCE]("")
instance, err := db.SelectOne(cm.db, createInstanceQueryMapper(instanceModel, []sq.Predicate{instanceModel.NAME.EqString(name)}))
if err != nil {
return instance, fmt.Errorf("failed to retrieve instance: %w", err)
}
// if not local, we update the instance status
if instance.CloudName != Local.String() {
provider, err := cm.GetProvider(instance.CloudName)
if err != nil {
return InstanceInfo{}, err
}
err = provider.Init()
if err != nil {
return InstanceInfo{}, err
}
instanceInfo, err := provider.GetInstanceInfo(instance.VMID, instance.Location)
if err != nil {
log.Errorf("Failed to retrieve status for instance '%s': %s", instance.Name, err.Error())
instance.Status = "n/a"
} else {
instance.Status = instanceInfo.Status
}
} else {
instance.Status = "n/a"
}
return instance, nil
}
// GetInstances returns all the instances from the db
func (cm *Manager) GetInstances() ([]InstanceInfo, error) {
instances, err := db.SelectMultiple(cm.db, createInstanceQueryMapper(sq.New[db.INSTANCE](""), nil))
if err != nil {
return instances, fmt.Errorf("failed to retrieve instances: %w", err)
}
return instances, nil
}
func (cm *Manager) retrieveInstanceStatus(wg *sync.WaitGroup, instance *InstanceInfo) {
defer wg.Done()
if instance.CloudName != Local.String() {
provider, err := cm.GetProvider(instance.CloudName)
if err != nil {
instance.Status = "n/a"
log.Errorf("Failed to retrieve status for instance '%s': %s", instance.Name, err.Error())
return
}
err = provider.Init()
if err != nil {
instance.Status = "n/a"
log.Errorf("Failed to retrieve status for instance '%s': %s", instance.Name, err.Error())
return
}
instanceInfo, err := provider.GetInstanceInfo(instance.VMID, instance.Location)
if err != nil {
instance.Status = "n/a"
log.Errorf("Failed to retrieve status for instance '%s': %s", instance.Name, err.Error())
return
}
instance.Status = instanceInfo.Status
} else {
instance.Status = "n/a"
}
}
// GetInstances returns all the instances from the db
func (cm *Manager) GetInstancesWithUpdatedStatus() ([]InstanceInfo, error) {
instances, err := db.SelectMultiple(cm.db, createInstanceQueryMapper(sq.New[db.INSTANCE](""), nil))
if err != nil {
return instances, fmt.Errorf("failed to retrieve instances: %w", err)
}
var wg sync.WaitGroup
for _, instance := range instances {
wg.Add(1)
go cm.retrieveInstanceStatus(&wg, &instance)
}
wg.Wait()
return instances, nil
}
// UploadLocalImage uploads a local Protosd image to a specific cloud
func (cm *Manager) UploadLocalImage(imagePath string, imageName string, cloudName string, cloudLocation string, timeout time.Duration) error {
errMsg := fmt.Sprintf("failed to upload local image '%s' to cloud '%s'", imagePath, cloudName)
// check local image file
finfo, err := os.Stat(imagePath)
if err != nil {
return fmt.Errorf("%s: %w", errMsg, err)
}
if finfo.IsDir() {
return fmt.Errorf("%s: Path '%s' is a directory", errMsg, imagePath)
}
if finfo.Size() == 0 {
return fmt.Errorf("%s: Image '%s' has 0 bytes", errMsg, imagePath)
}
provider, err := cm.GetProvider(cloudName)
if err != nil {
return fmt.Errorf("%s: %w", errMsg, err)
}
err = provider.Init()
if err != nil {
return fmt.Errorf("%s: %w", errMsg, err)
}
// find image
images, err := provider.GetImages()
if err != nil {
return fmt.Errorf("%s: %w", errMsg, err)
}
for _, img := range images {
if img.Location == cloudLocation && img.Name == imageName {
return fmt.Errorf("%s: Found an image with the same name", errMsg)
}
}
// upload image
_, err = provider.UploadLocalImage(imagePath, imageName, cloudLocation, timeout)
if err != nil {
return fmt.Errorf("%s: %w", errMsg, err)
}
return nil
}