This repository has been archived by the owner on Apr 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
test_helpers.go
851 lines (685 loc) · 26.5 KB
/
test_helpers.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
package test_helpers
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
slclient "github.com/maximilien/softlayer-go/client"
fakesslclient "github.com/maximilien/softlayer-go/client/fakes"
datatypes "github.com/maximilien/softlayer-go/data_types"
"github.com/maximilien/softlayer-go/softlayer"
)
var (
TIMEOUT time.Duration
POLLING_INTERVAL time.Duration
)
const (
TEST_NOTES_PREFIX = "TEST:softlayer-go"
TEST_LABEL_PREFIX = "TEST:softlayer-go"
DEFAULT_DATACENTER = "dal09"
TEST_EMAIL = "[email protected]"
TEST_HOST = "test.example.com"
TEST_TTL = 900
)
func ReadJsonTestFixtures(packageName, fileName string) ([]byte, error) {
wd, _ := os.Getwd()
return ioutil.ReadFile(filepath.Join(wd, "..", "test_fixtures", packageName, fileName))
}
func SetTestFixturesForFakeSoftLayerClient(fakeSoftLayerClient *fakesslclient.FakeSoftLayerClient, fileNames []string) {
for _, fileName := range fileNames {
fileContents, err := ReadJsonTestFixtures("services", fileName)
Expect(err).ToNot(HaveOccurred())
fakeSoftLayerClient.FakeHttpClient.DoRawHttpRequestResponses = append(fakeSoftLayerClient.FakeHttpClient.DoRawHttpRequestResponses, fileContents)
}
}
func FindTestVirtualGuests() ([]datatypes.SoftLayer_Virtual_Guest, error) {
accountService, err := CreateAccountService()
if err != nil {
return []datatypes.SoftLayer_Virtual_Guest{}, err
}
virtualGuests, err := accountService.GetVirtualGuests()
if err != nil {
return []datatypes.SoftLayer_Virtual_Guest{}, err
}
testVirtualGuests := []datatypes.SoftLayer_Virtual_Guest{}
for _, vGuest := range virtualGuests {
if strings.Contains(vGuest.Notes, TEST_NOTES_PREFIX) {
testVirtualGuests = append(testVirtualGuests, vGuest)
}
}
return testVirtualGuests, nil
}
func FindTestSshKeys() ([]datatypes.SoftLayer_Security_Ssh_Key, error) {
accountService, err := CreateAccountService()
if err != nil {
return []datatypes.SoftLayer_Security_Ssh_Key{}, err
}
sshKeys, err := accountService.GetSshKeys()
if err != nil {
return []datatypes.SoftLayer_Security_Ssh_Key{}, err
}
testSshKeys := []datatypes.SoftLayer_Security_Ssh_Key{}
for _, key := range sshKeys {
if key.Notes == TEST_NOTES_PREFIX {
testSshKeys = append(testSshKeys, key)
}
}
return testSshKeys, nil
}
func GetUsernameAndApiKey() (string, string, error) {
username := os.Getenv("SL_USERNAME")
if username == "" {
return "", "", errors.New("SL_USERNAME environment must be set")
}
apiKey := os.Getenv("SL_API_KEY")
if apiKey == "" {
return username, "", errors.New("SL_API_KEY environment must be set")
}
return username, apiKey, nil
}
func GetDatacenter() string {
datacenter := os.Getenv("SL_DATACENTER")
if datacenter == "" {
datacenter = DEFAULT_DATACENTER
}
return datacenter
}
func CreateAccountService() (softlayer.SoftLayer_Account_Service, error) {
username, apiKey, err := GetUsernameAndApiKey()
if err != nil {
return nil, err
}
client := slclient.NewSoftLayerClient(username, apiKey)
accountService, err := client.GetSoftLayer_Account_Service()
if err != nil {
return nil, err
}
return accountService, nil
}
func CreateVirtualGuestService() (softlayer.SoftLayer_Virtual_Guest_Service, error) {
username, apiKey, err := GetUsernameAndApiKey()
if err != nil {
return nil, err
}
client := slclient.NewSoftLayerClient(username, apiKey)
virtualGuestService, err := client.GetSoftLayer_Virtual_Guest_Service()
if err != nil {
return nil, err
}
return virtualGuestService, nil
}
func CreateVirtualGuestBlockDeviceTemplateGroupService() (softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service, error) {
username, apiKey, err := GetUsernameAndApiKey()
if err != nil {
return nil, err
}
client := slclient.NewSoftLayerClient(username, apiKey)
vgbdtgService, err := client.GetSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service()
if err != nil {
return nil, err
}
return vgbdtgService, nil
}
func CreateSecuritySshKeyService() (softlayer.SoftLayer_Security_Ssh_Key_Service, error) {
username, apiKey, err := GetUsernameAndApiKey()
if err != nil {
return nil, err
}
client := slclient.NewSoftLayerClient(username, apiKey)
sshKeyService, err := client.GetSoftLayer_Security_Ssh_Key_Service()
if err != nil {
return nil, err
}
return sshKeyService, nil
}
func CreateProductPackageService() (softlayer.SoftLayer_Product_Package_Service, error) {
username, apiKey, err := GetUsernameAndApiKey()
if err != nil {
return nil, err
}
client := slclient.NewSoftLayerClient(username, apiKey)
productPackageService, err := client.GetSoftLayer_Product_Package_Service()
if err != nil {
return nil, err
}
return productPackageService, nil
}
func CreateNetworkStorageService() (softlayer.SoftLayer_Network_Storage_Service, error) {
username, apiKey, err := GetUsernameAndApiKey()
if err != nil {
return nil, err
}
client := slclient.NewSoftLayerClient(username, apiKey)
networkStorageService, err := client.GetSoftLayer_Network_Storage_Service()
if err != nil {
return nil, err
}
return networkStorageService, nil
}
func FindAndDeleteTestSshKeys() error {
sshKeys, err := FindTestSshKeys()
if err != nil {
return err
}
sshKeyService, err := CreateSecuritySshKeyService()
if err != nil {
return err
}
for _, sshKey := range sshKeys {
deleted, err := sshKeyService.DeleteObject(sshKey.Id)
if err != nil {
return err
}
if !deleted {
return errors.New(fmt.Sprintf("Could not delete ssh key with id: %d", sshKey.Id))
}
}
return nil
}
func FindAndDeleteTestVirtualGuests() ([]int, error) {
virtualGuests, err := FindTestVirtualGuests()
if err != nil {
return []int{}, err
}
virtualGuestService, err := CreateVirtualGuestService()
if err != nil {
return []int{}, err
}
virtualGuestIds := []int{}
for _, virtualGuest := range virtualGuests {
virtualGuestIds = append(virtualGuestIds, virtualGuest.Id)
deleted, err := virtualGuestService.DeleteObject(virtualGuest.Id)
if err != nil {
return []int{}, err
}
if !deleted {
return []int{}, errors.New(fmt.Sprintf("Could not delete virtual guest with id: %d", virtualGuest.Id))
}
}
return virtualGuestIds, nil
}
func MarkVirtualGuestAsTest(virtualGuest datatypes.SoftLayer_Virtual_Guest) error {
virtualGuestService, err := CreateVirtualGuestService()
if err != nil {
return err
}
vgTemplate := datatypes.SoftLayer_Virtual_Guest{
Notes: TEST_NOTES_PREFIX,
}
edited, err := virtualGuestService.EditObject(virtualGuest.Id, vgTemplate)
if err != nil {
return err
}
if edited == false {
return errors.New(fmt.Sprintf("Could not edit virtual guest with id: %d", virtualGuest.Id))
}
return nil
}
func FileExists(filePath string) bool {
_, err := os.Stat(filePath)
if err != nil {
return false
}
return !os.IsNotExist(err)
}
func GenerateSshKey() (string, string, error) {
return generateSshKeyUsingSshKeyGen()
}
func CreateTestSshKey() (datatypes.SoftLayer_Security_Ssh_Key, string) {
_, testSshKeyValue, err := GenerateSshKey()
Expect(err).ToNot(HaveOccurred())
sshKey := datatypes.SoftLayer_Security_Ssh_Key{
Key: strings.Trim(string(testSshKeyValue), "\n"),
Label: TEST_LABEL_PREFIX,
Notes: TEST_NOTES_PREFIX,
}
sshKeyService, err := CreateSecuritySshKeyService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> creating ssh key in SL\n")
createdSshKey, err := sshKeyService.CreateObject(sshKey)
Expect(err).ToNot(HaveOccurred())
Expect(createdSshKey.Key).To(Equal(sshKey.Key), "key")
Expect(createdSshKey.Label).To(Equal(sshKey.Label), "label")
Expect(createdSshKey.Notes).To(Equal(sshKey.Notes), "notes")
Expect(createdSshKey.CreateDate).ToNot(BeNil(), "createDate")
Expect(createdSshKey.Id).To(BeNumerically(">", 0), "id")
Expect(createdSshKey.ModifyDate).To(BeNil(), "modifyDate")
fmt.Printf("----> created ssh key: %d\n in SL", createdSshKey.Id)
return createdSshKey, string(testSshKeyValue)
}
func CreateDisk(size int, location string) datatypes.SoftLayer_Network_Storage {
networkStorageService, err := CreateNetworkStorageService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> creating new disk\n")
disk, err := networkStorageService.CreateNetworkStorage(size, 1000, location, true)
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> created disk: %d\n", disk.Id)
return disk
}
func CreateVirtualGuestAndMarkItTest(securitySshKeys []datatypes.SoftLayer_Security_Ssh_Key) datatypes.SoftLayer_Virtual_Guest {
sshKeys := make([]datatypes.SshKey, len(securitySshKeys))
for i, securitySshKey := range securitySshKeys {
sshKeys[i] = datatypes.SshKey{Id: securitySshKey.Id}
}
virtualGuestTemplate := datatypes.SoftLayer_Virtual_Guest_Template{
Hostname: "test",
Domain: "softlayergo.com",
StartCpus: 1,
MaxMemory: 1024,
Datacenter: datatypes.Datacenter{
Name: GetDatacenter(),
},
SshKeys: sshKeys,
HourlyBillingFlag: true,
LocalDiskFlag: true,
OperatingSystemReferenceCode: "UBUNTU_LATEST",
}
virtualGuestService, err := CreateVirtualGuestService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> creating new virtual guest\n")
virtualGuest, err := virtualGuestService.CreateObject(virtualGuestTemplate)
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> created virtual guest: %d\n", virtualGuest.Id)
WaitForVirtualGuestToBeRunning(virtualGuest.Id)
WaitForVirtualGuestToHaveNoActiveTransactions(virtualGuest.Id)
fmt.Printf("----> marking virtual guest with TEST:softlayer-go\n")
err = MarkVirtualGuestAsTest(virtualGuest)
Expect(err).ToNot(HaveOccurred(), "Could not mark virtual guest as test")
fmt.Printf("----> marked virtual guest with TEST:softlayer-go\n")
return virtualGuest
}
func DeleteVirtualGuest(virtualGuestId int) {
virtualGuestService, err := CreateVirtualGuestService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> deleting virtual guest: %d\n", virtualGuestId)
deleted, err := virtualGuestService.DeleteObject(virtualGuestId)
Expect(err).ToNot(HaveOccurred())
Expect(deleted).To(BeTrue(), "could not delete virtual guest")
WaitForVirtualGuestToHaveNoActiveTransactions(virtualGuestId)
}
func CleanUpVirtualGuest(virtualGuestId int) {
WaitForVirtualGuestToHaveNoActiveTransactions(virtualGuestId)
DeleteVirtualGuest(virtualGuestId)
}
func DeleteSshKey(sshKeyId int) {
sshKeyService, err := CreateSecuritySshKeyService()
Expect(err).ToNot(HaveOccurred())
if SshKeyPresent(sshKeyId) {
fmt.Printf("----> deleting ssh key: %d\n", sshKeyId)
deleted, err := sshKeyService.DeleteObject(sshKeyId)
Expect(err).ToNot(HaveOccurred())
Expect(deleted).To(BeTrue(), "could not delete ssh key")
} else {
fmt.Printf("----> ssh key %d already not present\n", sshKeyId)
}
WaitForDeletedSshKeyToNoLongerBePresent(sshKeyId)
}
func DeleteDisk(diskId int) {
networkStorageService, err := CreateNetworkStorageService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> deleting disk: %d\n", diskId)
err = networkStorageService.DeleteNetworkStorage(diskId, true)
Expect(err).ToNot(HaveOccurred())
}
func WaitForVirtualGuest(virtualGuestId int, targetState string, timeout time.Duration) {
virtualGuestService, err := CreateVirtualGuestService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> waiting for virtual guest: %d, until %s\n", virtualGuestId, targetState)
Eventually(func() string {
vgPowerState, err := virtualGuestService.GetPowerState(virtualGuestId)
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> virtual guest: %d, has power state: %s\n", virtualGuestId, vgPowerState.KeyName)
return vgPowerState.KeyName
}, timeout, POLLING_INTERVAL).Should(Equal(targetState), fmt.Sprintf("failed waiting for virtual guest to be %s", targetState))
}
func WaitForVirtualGuestToBeRunning(virtualGuestId int) {
WaitForVirtualGuest(virtualGuestId, "RUNNING", TIMEOUT)
}
func WaitForVirtualGuestTransactionWithStatus(virtualGuestId int, status string) {
virtualGuestService, err := CreateVirtualGuestService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> waiting for virtual guest %d to have ugrade transactions with status '%s'\n", virtualGuestId, status)
Eventually(func() bool {
activeTransactions, err := virtualGuestService.GetActiveTransactions(virtualGuestId)
Expect(err).ToNot(HaveOccurred())
for _, transaction := range activeTransactions {
if strings.Contains(transaction.TransactionStatus.Name, status) {
return true
}
}
fmt.Printf("----> virtual guest: %d, doesn't have transactions with status '%s' yet\n", virtualGuestId, status)
return false
}, TIMEOUT, POLLING_INTERVAL).Should(BeTrue(), "failed waiting for virtual guest to have transactions with specifc status")
}
func WaitForVirtualGuestToHaveNoActiveTransactions(virtualGuestId int) {
virtualGuestService, err := CreateVirtualGuestService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> waiting for virtual guest to have no active transactions pending\n")
Eventually(func() int {
activeTransactions, err := virtualGuestService.GetActiveTransactions(virtualGuestId)
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> virtual guest: %d, has %d active transactions\n", virtualGuestId, len(activeTransactions))
return len(activeTransactions)
}, TIMEOUT, POLLING_INTERVAL).Should(Equal(0), "failed waiting for virtual guest to have no active transactions")
}
func WaitForVirtualGuestToHaveNoActiveTransactionsOrToErr(virtualGuestId int) {
virtualGuestService, err := CreateVirtualGuestService()
if err != nil {
return
}
fmt.Printf("----> waiting for virtual guest to have no active transactions pending\n")
Eventually(func() int {
activeTransactions, err := virtualGuestService.GetActiveTransactions(virtualGuestId)
if err != nil {
return 0
}
fmt.Printf("----> virtual guest: %d, has %d active transactions\n", virtualGuestId, len(activeTransactions))
return len(activeTransactions)
}, TIMEOUT, POLLING_INTERVAL).Should(Equal(0), "failed waiting for virtual guest to have no active transactions")
}
func SshKeyPresent(sshKeyId int) bool {
accountService, err := CreateAccountService()
Expect(err).ToNot(HaveOccurred())
sshKeys, err := accountService.GetSshKeys()
Expect(err).ToNot(HaveOccurred())
for _, sshKey := range sshKeys {
if sshKey.Id == sshKeyId {
return true
}
}
return false
}
func WaitForDeletedSshKeyToNoLongerBePresent(sshKeyId int) {
accountService, err := CreateAccountService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> waiting for deleted ssh key to no longer be present\n")
Eventually(func() bool {
sshKeys, err := accountService.GetSshKeys()
Expect(err).ToNot(HaveOccurred())
for _, sshKey := range sshKeys {
if sshKey.Id == sshKeyId {
return false
}
}
return true
}, TIMEOUT, POLLING_INTERVAL).Should(BeTrue(), "failed waiting for deleted ssh key to be removed from list of ssh keys")
}
func WaitForCreatedSshKeyToBePresent(sshKeyId int) {
accountService, err := CreateAccountService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> waiting for created ssh key to be present\n")
Eventually(func() bool {
sshKeys, err := accountService.GetSshKeys()
Expect(err).ToNot(HaveOccurred())
for _, sshKey := range sshKeys {
if sshKey.Id == sshKeyId {
return true
}
}
return false
}, TIMEOUT, POLLING_INTERVAL).Should(BeTrue(), "created ssh key but not in the list of ssh keys")
}
func WaitForVirtualGuestBlockTemplateGroupToHaveNoActiveTransactions(virtualGuestBlockTemplateGroupId int) {
vgbdtgService, err := CreateVirtualGuestBlockDeviceTemplateGroupService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> waiting for virtual guest block template group to have no active transactions pending\n")
Eventually(func() bool {
activeTransaction, err := vgbdtgService.GetTransaction(virtualGuestBlockTemplateGroupId)
Expect(err).ToNot(HaveOccurred())
transactionTrue := false
emptyTransaction := datatypes.SoftLayer_Provisioning_Version1_Transaction{}
if activeTransaction != emptyTransaction {
fmt.Printf("----> virtual guest template group: %d, has %#v pending\n", virtualGuestBlockTemplateGroupId, activeTransaction)
transactionTrue = true
}
return transactionTrue
}, TIMEOUT, POLLING_INTERVAL).Should(BeFalse(), "failed waiting for virtual guest block template group to have no active transactions")
}
func SetUserDataToVirtualGuest(virtualGuestId int, metadata string) {
virtualGuestService, err := CreateVirtualGuestService()
Expect(err).ToNot(HaveOccurred())
success, err := virtualGuestService.SetMetadata(virtualGuestId, metadata)
Expect(err).ToNot(HaveOccurred())
Expect(success).To(BeTrue())
fmt.Printf(fmt.Sprintf("----> successfully set metadata: `%s` to virtual guest instance: %d\n", metadata, virtualGuestId))
}
func ConfigureMetadataDiskOnVirtualGuest(virtualGuestId int) datatypes.SoftLayer_Provisioning_Version1_Transaction {
virtualGuestService, err := CreateVirtualGuestService()
Expect(err).ToNot(HaveOccurred())
transaction, err := virtualGuestService.ConfigureMetadataDisk(virtualGuestId)
Expect(err).ToNot(HaveOccurred())
fmt.Printf(fmt.Sprintf("----> successfully configured metadata disk for virtual guest instance: %d\n", virtualGuestId))
return transaction
}
func SetUserMetadataAndConfigureDisk(virtualGuestId int, userMetadata string) datatypes.SoftLayer_Provisioning_Version1_Transaction {
SetUserDataToVirtualGuest(virtualGuestId, userMetadata)
transaction := ConfigureMetadataDiskOnVirtualGuest(virtualGuestId)
Expect(transaction.Id).ToNot(Equal(0))
return transaction
}
func RunCommand(timeout time.Duration, cmd string, args ...string) *Session {
command := exec.Command(cmd, args...)
session, err := Start(command, GinkgoWriter, GinkgoWriter)
Ω(err).ShouldNot(HaveOccurred())
session.Wait(timeout)
return session
}
func ScpToVirtualGuest(virtualGuestId int, sshKeyFilePath string, localFilePath string, remotePath string) {
virtualGuestService, err := CreateVirtualGuestService()
Expect(err).ToNot(HaveOccurred())
virtualGuest, err := virtualGuestService.GetObject(virtualGuestId)
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> sending SCP command: %s\n", fmt.Sprintf("scp -i %s %s root@%s:%s", sshKeyFilePath, localFilePath, virtualGuest.PrimaryIpAddress, remotePath))
session := RunCommand(TIMEOUT, "scp", "-o", "StrictHostKeyChecking=no", "-i", sshKeyFilePath, localFilePath, fmt.Sprintf("root@%s:%s", virtualGuest.PrimaryIpAddress, remotePath))
Ω(session.ExitCode()).Should(Equal(0))
}
func SshExecOnVirtualGuest(virtualGuestId int, sshKeyFilePath string, remoteFilePath string, args ...string) int {
virtualGuestService, err := CreateVirtualGuestService()
Expect(err).ToNot(HaveOccurred())
virtualGuest, err := virtualGuestService.GetObject(virtualGuestId)
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> sending SSH command: %s\n", fmt.Sprintf("ssh -i %s root@%s '%s \"%s\"'", sshKeyFilePath, virtualGuest.PrimaryIpAddress, remoteFilePath, args[0]))
session := RunCommand(TIMEOUT, "ssh", "-o", "StrictHostKeyChecking=no", "-i", sshKeyFilePath, fmt.Sprintf("root@%s", virtualGuest.PrimaryIpAddress), fmt.Sprintf("%s \"%s\"", remoteFilePath, args[0]))
return session.ExitCode()
}
func TestUserMetadata(userMetadata, sshKeyValue string) {
workingDir, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
sshKeyFilePath := filepath.Join(workingDir, "sshTemp")
err = ioutil.WriteFile(sshKeyFilePath, []byte(sshKeyValue), 600)
defer os.Remove(sshKeyFilePath)
Expect(err).ToNot(HaveOccurred())
fetchUserMetadataShFilePath := filepath.Join(workingDir, "..", "scripts", "fetch_user_metadata.sh")
Expect(err).ToNot(HaveOccurred())
ScpToVirtualGuest(6396994, sshKeyFilePath, fetchUserMetadataShFilePath, "/tmp")
retCode := SshExecOnVirtualGuest(6396994, sshKeyFilePath, "/tmp/fetch_user_metadata.sh", userMetadata)
Expect(retCode).To(Equal(0))
}
func GetVirtualGuestPrimaryIpAddress(virtualGuestId int) string {
virtualGuestService, err := CreateVirtualGuestService()
Expect(err).ToNot(HaveOccurred())
vgIpAddress, err := virtualGuestService.GetPrimaryIpAddress(virtualGuestId)
Expect(err).ToNot(HaveOccurred())
return vgIpAddress
}
func CreateDnsDomainService() (softlayer.SoftLayer_Dns_Domain_Service, error) {
username, apiKey, err := GetUsernameAndApiKey()
if err != nil {
return nil, err
}
client := slclient.NewSoftLayerClient(username, apiKey)
dnsDomainService, err := client.GetSoftLayer_Dns_Domain_Service()
if err != nil {
return nil, err
}
return dnsDomainService, nil
}
func CreateDnsDomainResourceRecordService() (softlayer.SoftLayer_Dns_Domain_ResourceRecord_Service, error) {
username, apiKey, err := GetUsernameAndApiKey()
if err != nil {
return nil, err
}
client := slclient.NewSoftLayerClient(username, apiKey)
dnsDomainResourceRecordService, err := client.GetSoftLayer_Dns_Domain_ResourceRecord_Service()
if err != nil {
return nil, err
}
return dnsDomainResourceRecordService, nil
}
func CreateTestDnsDomain(name string) datatypes.SoftLayer_Dns_Domain {
template := datatypes.SoftLayer_Dns_Domain_Template{
Name: name,
}
dnsDomainService, err := CreateDnsDomainService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> creating dns domain in SL\n")
createdDnsDomain, err := dnsDomainService.CreateObject(template)
Expect(err).ToNot(HaveOccurred())
Expect(createdDnsDomain.Name).To(Equal(template.Name))
fmt.Printf("----> created dns domain : %d\n in SL", createdDnsDomain.Id)
return createdDnsDomain
}
func WaitForCreatedDnsDomainToBePresent(dnsDomainId int) {
dnsDomainService, err := CreateDnsDomainService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> waiting for created dns domain to be present\n")
Eventually(func() bool {
dnsDomain, err := dnsDomainService.GetObject(dnsDomainId)
Expect(err).ToNot(HaveOccurred())
if dnsDomain.Id == dnsDomainId {
return true
}
return false
}, TIMEOUT, POLLING_INTERVAL).Should(BeTrue(), "created dns domain but not found")
}
func WaitForDeletedDnsDomainToNoLongerBePresent(dnsDomainId int) {
dnsDomainService, err := CreateDnsDomainService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> waiting for deleted dns domain to no longer be present\n")
Eventually(func() bool {
dnsDomain, err := dnsDomainService.GetObject(dnsDomainId)
Expect(err).To(HaveOccurred())
if dnsDomain.Id == dnsDomainId {
return false
}
return true
}, TIMEOUT, POLLING_INTERVAL).Should(BeTrue(), "failed waiting for deleted dns domain to be removed")
}
func CreateTestDnsDomainResourceRecord(domainId int) datatypes.SoftLayer_Dns_Domain_ResourceRecord {
template := datatypes.SoftLayer_Dns_Domain_ResourceRecord_Template{
Data: "127.0.0.1",
DomainId: domainId,
Host: TEST_HOST,
ResponsiblePerson: TEST_EMAIL,
Ttl: TEST_TTL,
Type: "A",
}
dnsDomainResourceRecordService, err := CreateDnsDomainResourceRecordService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> creating dns domain resource record in SL\n")
createdDnsDomainResourceRecord, err := dnsDomainResourceRecordService.CreateObject(template)
Expect(err).ToNot(HaveOccurred())
Expect(createdDnsDomainResourceRecord.Data).To(Equal(template.Data), "127.0.0.1")
Expect(createdDnsDomainResourceRecord.Host).To(Equal(template.Host), TEST_HOST)
Expect(createdDnsDomainResourceRecord.ResponsiblePerson).To(Equal(template.ResponsiblePerson), TEST_EMAIL)
Expect(createdDnsDomainResourceRecord.Ttl).To(Equal(template.Ttl), "900")
Expect(createdDnsDomainResourceRecord.Type).To(Equal(template.Type), "A")
fmt.Printf("----> created dns domain resource record: %d\n in SL", createdDnsDomainResourceRecord.Id)
return createdDnsDomainResourceRecord
}
func WaitForCreatedDnsDomainResourceRecordToBePresent(dnsDomainResourceRecordId int) {
dnsDomainResourceRecordService, err := CreateDnsDomainResourceRecordService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> waiting for created dns domain resource record to be present\n")
Eventually(func() bool {
dnsDomainResourceRecord, err := dnsDomainResourceRecordService.GetObject(dnsDomainResourceRecordId)
Expect(err).ToNot(HaveOccurred())
if dnsDomainResourceRecord.Id == dnsDomainResourceRecordId {
return true
}
return false
}, TIMEOUT, POLLING_INTERVAL).Should(BeTrue(), "created dns domain resource record but not found")
}
func WaitForDeletedDnsDomainResourceRecordToNoLongerBePresent(dnsDomainResourceRecordId int) {
dnsDomainResourceRecordService, err := CreateDnsDomainResourceRecordService()
Expect(err).ToNot(HaveOccurred())
fmt.Printf("----> waiting for deleted dns domain resource record to no longer be present\n")
Eventually(func() bool {
dnsDomainResourceRecord, err := dnsDomainResourceRecordService.GetObject(dnsDomainResourceRecordId)
Expect(err).ToNot(HaveOccurred())
if dnsDomainResourceRecord.Id == dnsDomainResourceRecordId {
return false
}
return true
}, TIMEOUT, POLLING_INTERVAL).Should(BeTrue(), "failed waiting for deleted dns domain resource record to be removed")
}
// Private functions
func generateSshKeyUsingGo() (string, string, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2014)
if err != nil {
return "", "", err
}
fmt.Printf("----> creating ssh private key using Golang\n")
privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKey)
privateKeyBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privateKeyDer,
}
privateKeyPem := string(pem.EncodeToMemory(&privateKeyBlock))
fmt.Printf("----> creating ssh public key using Golang\n")
publicKey := privateKey.PublicKey
publicKeyDer, err := x509.MarshalPKIXPublicKey(&publicKey)
if err != nil {
return "", "", err
}
publicKeyBlock := pem.Block{
Type: "PUBLIC KEY",
Headers: nil,
Bytes: publicKeyDer,
}
publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))
return privateKeyPem, publicKeyPem, nil
}
func generateSshKeyUsingSshKeyGen() (string, string, error) {
tmpDir, err := ioutil.TempDir("", "generateSshKeyUsingSshKeyGen")
if err != nil {
return "", "", err
}
rsaKeyFileName := filepath.Join(tmpDir, "ssh_key_file.rsa")
rsaKeyFileNamePub := rsaKeyFileName + ".pub"
sshKeyGen, err := exec.LookPath("ssh-keygen")
if err != nil {
return "", "", err
}
_, err = exec.Command(sshKeyGen,
"-f", rsaKeyFileName,
"-t", "rsa", "-N", "").Output()
if err != nil {
return "", "", err
}
privateKey, err := ioutil.ReadFile(rsaKeyFileName)
if err != nil {
return "", "", err
}
publicKey, err := ioutil.ReadFile(rsaKeyFileNamePub)
if err != nil {
return "", "", err
}
err = os.RemoveAll(tmpDir)
if err != nil {
return "", "", err
}
return string(privateKey), string(publicKey), nil
}