/
client.go
2186 lines (1873 loc) · 76.8 KB
/
client.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 client
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshretry "github.com/cloudfoundry/bosh-utils/retrystrategy"
"github.com/go-openapi/strfmt"
"github.com/ncw/swift"
"github.com/softlayer/softlayer-go/datatypes"
"github.com/softlayer/softlayer-go/filter"
"github.com/softlayer/softlayer-go/services"
"github.com/softlayer/softlayer-go/session"
"github.com/softlayer/softlayer-go/sl"
"bosh-softlayer-cpi/logger"
"bosh-softlayer-cpi/registry"
vpsVm "bosh-softlayer-cpi/softlayer/vps_service/client/vm"
"bosh-softlayer-cpi/softlayer/vps_service/models"
"github.com/softlayer/softlayer-go/helpers/product"
)
const (
softlayerClientLogTag = "SoftlayerClient"
INSTANCE_DEFAULT_MASK = "id, globalIdentifier, hostname, hourlyBillingFlag, domain, fullyQualifiedDomainName, status.name, " +
"powerState.name, activeTransaction, datacenter.name, account.id, " +
"maxCpu, maxMemory, primaryIpAddress, primaryBackendIpAddress, " +
"privateNetworkOnlyFlag, dedicatedAccountHostOnlyFlag, dedicatedHost, createDate, modifyDate, " +
"billingItem[orderItem.order.userRecord.username, recurringFee], notes, tagReferences.tag.name"
INSTANCE_DETAIL_MASK = "id, globalIdentifier, hostname, domain, fullyQualifiedDomainName, status.name, " +
"powerState.name, activeTransaction, datacenter.name, " +
"operatingSystem[softwareLicense[softwareDescription[name,version]],passwords[username,password]], " +
" maxCpu, maxMemory, primaryIpAddress, primaryBackendIpAddress, " +
"privateNetworkOnlyFlag, dedicatedAccountHostOnlyFlag, dedicatedHost, createDate, modifyDate, " +
"billingItem[nextInvoiceTotalRecurringAmount, children[nextInvoiceTotalRecurringAmount]], notes, tagReferences.tag.name, networkVlans[id,vlanNumber,networkSpace], " +
"primaryBackendNetworkComponent[primaryIpAddress, networkVlan[id,name,vlanNumber,primaryRouter], subnets[netmask,networkIdentifier]], primaryNetworkComponent[primaryIpAddress, networkVlan[id,name,vlanNumber,primaryRouter], subnets[netmask,networkIdentifier]]"
INSTANCE_ID_MASK = "id"
INSTANCE_NETWORK_COMPONENTS_MASK = "primaryBackendNetworkComponent[primaryIpAddress, networkVlan[id,name,vlanNumber,primaryRouter], subnets[netmask,networkIdentifier]], primaryNetworkComponent[primaryIpAddress, networkVlan[id,name,vlanNumber,primaryRouter], subnets[netmask,networkIdentifier]]"
NETWORK_DEFAULT_VLAN_MASK = "id,primarySubnetId,networkSpace"
NETWORK_DEFAULT_SUBNET_MASK = "id,networkVlanId,addressSpace"
VOLUME_DEFAULT_MASK = "id,username,lunId,capacityGb,bytesUsed,serviceResource.datacenter.name,serviceResourceBackendIpAddress,activeTransactionCount,billingItem.orderItem.order[id,userRecord.username]"
ALLOWD_HOST_DEFAULT_MASK = "id, name, credential[username, password]"
VOLUME_DETAIL_MASK = "id,username,password,capacityGb,snapshotCapacityGb,parentVolume.snapshotSizeBytes,storageType.keyName," +
"serviceResource.datacenter.name,serviceResourceBackendIpAddress,iops,lunId,activeTransactionCount," +
"activeTransactions.transactionStatus.friendlyName,replicationPartnerCount,replicationStatus," +
"replicationPartners[id,username,serviceResourceBackendIpAddress,serviceResource.datacenter.name,replicationSchedule.type.keyname]"
IMAGE_DEFAULT_MASK = "id, name, globalIdentifier, imageType, accountId"
IMAGE_DETAIL_MASK = "id,globalIdentifier,name,datacenter.name,status.name,transaction.transactionStatus.name,accountId,publicFlag,imageType,flexImageFlag,note,createDate,blockDevicesDiskSpaceTotal,children[blockDevicesDiskSpaceTotal,datacenter.name]"
EPHEMERAL_DISK_CATEGORY_CODE = "guest_disk1"
UPGRADE_VIRTUAL_SERVER_ORDER_TYPE = "SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade"
NETWORK_PERFORMANCE_STORAGE_PACKAGE_ID = 222
NETWORK_STORAGE_AS_SERVICE_PACKAGE_ID = 759
SOFTLAYER_PUBLIC_EXCEPTION = "SoftLayer_Exception_Public"
SOFTLAYER_OBJECTNOTFOUND_EXCEPTION = "SoftLayer_Exception_ObjectNotFound"
SOFTLAYER_BLOCKINGOPERATIONINPROGRESS_EXCEPTION = "SoftLayer_Exception_Network_Storage_BlockingOperationInProgress"
SOFTLAYER_GROUP_ACCESSCONTROLERROR_EXCEPTION = "SoftLayer_Exception_Network_Storage_Group_AccessControlError"
SOFTLAYER_NOTIMPLEMENTED_EXCEPTION = "SoftLayer_Exception_NotImplemented"
)
// go:generate counterfeiter -o fakes/fake_client_factory.go . ClientFactory
type ClientFactory interface {
CreateClient() Client
}
type clientFactory struct {
slClient *ClientManager
}
func NewClientFactory(slClient *ClientManager) ClientFactory {
return &clientFactory{slClient}
}
func (factory *clientFactory) CreateClient() Client {
return factory.slClient
}
func NewSoftLayerClientManager(session *session.Session, vps *vpsVm.Client, swfitClient *swift.Connection, logger logger.Logger) *ClientManager {
return &ClientManager{
services.GetVirtualGuestService(session),
services.GetAccountService(session),
services.GetProductPackageService(session),
services.GetProductOrderService(session),
services.GetNetworkStorageService(session),
services.GetBillingItemService(session),
services.GetLocationDatacenterService(session),
services.GetNetworkVlanService(session),
services.GetNetworkSubnetService(session),
services.GetVirtualGuestBlockDeviceTemplateGroupService(session),
services.GetSecuritySshKeyService(session),
services.GetBillingOrderService(session),
services.GetTicketService(session),
services.GetTicketSubjectService(session),
vps,
swfitClient,
logger,
}
}
// go:generate counterfeiter -o fakes/fake_client.go . Client
type Client interface {
CancelInstance(id int) error
CreateInstance(template *datatypes.Virtual_Guest, userData *registry.SoftlayerUserData) (*datatypes.Virtual_Guest, error)
EditInstance(id int, template *datatypes.Virtual_Guest) (bool, error)
GetInstance(id int, mask string) (*datatypes.Virtual_Guest, bool, error)
GetInstanceByPrimaryBackendIpAddress(ip string) (*datatypes.Virtual_Guest, bool, error)
GetInstanceByPrimaryIpAddress(ip string) (*datatypes.Virtual_Guest, bool, error)
RebootInstance(id int, soft bool, hard bool) error
ReloadInstance(id int, stemcellId int, sshKeyIds []int, hostname string, domain string, userData *registry.SoftlayerUserData) error
UpgradeInstanceConfig(id int, cpu int, memory int, network int, privateCPU bool, dedicatedHost bool) error
UpgradeInstance(id int, cpu int, memory int, network int, privateCPU bool, dedicatedHost bool, secondDiskSize int) (int, error)
WaitInstanceUntilReady(id int, until time.Time) error
WaitInstanceUntilReadyWithTicket(id int, until time.Time) error
WaitInstanceHasActiveTransaction(id int, until time.Time) error
WaitInstanceHasNoneActiveTransaction(id int, until time.Time) error
WaitVolumeProvisioningWithOrderId(orderId int, until time.Time) (*datatypes.Network_Storage, error)
SetTags(id int, tags string) (bool, error)
SetInstanceMetadata(id int, encodedUserData *string) (bool, error)
AttachSecondDiskToInstance(id int, diskSize int) error
GetInstanceAllowedHost(id int) (*datatypes.Network_Storage_Allowed_Host, bool, error)
AuthorizeHostToVolume(instance *datatypes.Virtual_Guest, volumeId int, until time.Time) (bool, error)
DeauthorizeHostToVolume(instance *datatypes.Virtual_Guest, volumeId int, until time.Time) (bool, error)
CreateVolume(location string, size int, iops int, snapshotSpace int) (*datatypes.Network_Storage, error)
OrderBlockVolume(storageType string, location string, size int, iops int) (*datatypes.Container_Product_Order_Receipt, error)
OrderBlockVolume2(storageType string, location string, size int, iops int, snapshotSpace int) (*datatypes.Container_Product_Order_Receipt, error)
CancelBlockVolume(volumeId int, reason string, immediate bool) (bool, error)
GetBlockVolumeDetails(volumeId int, mask string) (*datatypes.Network_Storage, bool, error)
GetBlockVolumeDetailsBySoftLayerAccount(volumeId int, mask string) (datatypes.Network_Storage, error)
GetNetworkStorageTarget(volumeId int, mask string) (string, bool, error)
SetNotes(id int, notes string) (bool, error)
GetImage(imageId int, mask string) (*datatypes.Virtual_Guest_Block_Device_Template_Group, bool, error)
GetVlan(id int, mask string) (*datatypes.Network_Vlan, bool, error)
GetSubnet(id int, mask string) (*datatypes.Network_Subnet, bool, error)
GetAllowedHostCredential(id int) (*datatypes.Network_Storage_Allowed_Host, bool, error)
GetAllowedNetworkStorage(id int) ([]string, bool, error)
CreateSshKey(label *string, key *string, fingerPrint *string) (*datatypes.Security_Ssh_Key, error)
DeleteSshKey(id int) (bool, error)
CreateInstanceFromVPS(template *datatypes.Virtual_Guest, stemcellID int, sshKeys []int, userData *registry.SoftlayerUserData) (*datatypes.Virtual_Guest, error)
DeleteInstanceFromVPS(id int) error
CreateSnapshot(volumeId int, notes string) (datatypes.Network_Storage, error)
DeleteSnapshot(snapshotId int) error
CreateTicket(ticketSubject *string, ticketTitle *string, contents *string, attachmentId *int, attachmentType *string) error
CreateSwiftContainer(containerName string) error
DeleteSwiftContainer(containerName string) error
UploadSwiftLargeObject(containerName string, objectName string, objectFile string) error
DeleteSwiftLargeObject(containerName string, objectFileName string) error
CreateImageFromExternalSource(imageName string, note string, cluster string, osCode string) (int, error)
}
type ClientManager struct {
VirtualGuestService services.Virtual_Guest
AccountService services.Account
PackageService services.Product_Package
OrderService services.Product_Order
StorageService services.Network_Storage
BillingService services.Billing_Item
LocationService services.Location_Datacenter
NetworkVlanService services.Network_Vlan
NetworkSubnetService services.Network_Subnet
ImageService services.Virtual_Guest_Block_Device_Template_Group
SecuritySshKeyService services.Security_Ssh_Key
BillingOrderService services.Billing_Order
TicketService services.Ticket
TicketSubjectSerivce services.Ticket_Subject
vpsService *vpsVm.Client
swfitClient *swift.Connection
logger logger.Logger
}
func (c *ClientManager) GetInstance(id int, mask string) (*datatypes.Virtual_Guest, bool, error) {
if mask == "" {
mask = INSTANCE_DEFAULT_MASK
}
virtualGuest, err := c.VirtualGuestService.Id(id).Mask(mask).GetObject()
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.Exception == SOFTLAYER_OBJECTNOTFOUND_EXCEPTION {
return &datatypes.Virtual_Guest{}, false, nil
}
return &datatypes.Virtual_Guest{}, false, err
}
}
return &virtualGuest, true, err
}
func (c *ClientManager) GetVlan(id int, mask string) (*datatypes.Network_Vlan, bool, error) {
if mask == "" {
mask = NETWORK_DEFAULT_VLAN_MASK
}
vlan, err := c.NetworkVlanService.Id(id).Mask(mask).GetObject()
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.Exception == SOFTLAYER_OBJECTNOTFOUND_EXCEPTION {
return &datatypes.Network_Vlan{}, false, nil
}
return &datatypes.Network_Vlan{}, false, err
}
}
return &vlan, true, err
}
func (c *ClientManager) GetSubnet(id int, mask string) (*datatypes.Network_Subnet, bool, error) {
if mask == "" {
mask = NETWORK_DEFAULT_SUBNET_MASK
}
vlan, err := c.NetworkSubnetService.Id(id).Mask(mask).GetObject()
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.Exception == SOFTLAYER_OBJECTNOTFOUND_EXCEPTION {
return &datatypes.Network_Subnet{}, false, nil
}
return &datatypes.Network_Subnet{}, false, err
}
}
return &vlan, true, err
}
func (c *ClientManager) GetInstanceByPrimaryBackendIpAddress(ip string) (*datatypes.Virtual_Guest, bool, error) {
filters := filter.New()
filters = append(filters, filter.Path("virtualGuests.primaryBackendIpAddress").Eq(ip))
virtualguests, err := c.AccountService.Mask(INSTANCE_DEFAULT_MASK).Filter(filters.Build()).GetVirtualGuests()
if err != nil {
return &datatypes.Virtual_Guest{}, false, err
}
for _, virtualguest := range virtualguests {
// Return the first instance (it can only be 1 instance with the same primary backend ip addresss)
return &virtualguest, true, nil
}
return &datatypes.Virtual_Guest{}, false, err
}
func (c *ClientManager) GetInstanceByPrimaryIpAddress(ip string) (*datatypes.Virtual_Guest, bool, error) {
filters := filter.New()
filters = append(filters, filter.Path("virtualGuests.primaryIpAddress").Eq(ip))
virtualguests, err := c.AccountService.Mask(INSTANCE_DEFAULT_MASK).Filter(filters.Build()).GetVirtualGuests()
if err != nil {
return &datatypes.Virtual_Guest{}, false, err
}
for _, virtualguest := range virtualguests {
// Return the first instance (it can only be 1 instance with the same primary ip addresss)
return &virtualguest, true, nil
}
return &datatypes.Virtual_Guest{}, false, err
}
func (c *ClientManager) GetAllowedHostCredential(id int) (*datatypes.Network_Storage_Allowed_Host, bool, error) {
allowedHost, err := c.VirtualGuestService.Id(id).Mask(ALLOWD_HOST_DEFAULT_MASK).GetAllowedHost()
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.Exception == SOFTLAYER_OBJECTNOTFOUND_EXCEPTION {
return &datatypes.Network_Storage_Allowed_Host{}, false, nil
}
return &datatypes.Network_Storage_Allowed_Host{}, false, err
}
}
return &allowedHost, true, err
}
func (c *ClientManager) GetAllowedNetworkStorage(id int) ([]string, bool, error) {
var storages = make([]string, 1)
networkStorages, err := c.VirtualGuestService.Id(id).GetAllowedNetworkStorage()
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.Exception == SOFTLAYER_OBJECTNOTFOUND_EXCEPTION {
return storages, false, nil
}
return storages, false, err
}
}
for _, networkStorage := range networkStorages {
storages = append(storages, strconv.Itoa(*networkStorage.Id))
}
return storages, true, err
}
func (c *ClientManager) GetImage(imageId int, mask string) (*datatypes.Virtual_Guest_Block_Device_Template_Group, bool, error) {
if mask == "" {
mask = IMAGE_DETAIL_MASK
}
image, err := c.ImageService.Id(imageId).Mask(mask).GetObject()
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.Exception == SOFTLAYER_OBJECTNOTFOUND_EXCEPTION {
return &datatypes.Virtual_Guest_Block_Device_Template_Group{}, false, nil
}
return &datatypes.Virtual_Guest_Block_Device_Template_Group{}, false, err
}
}
return &image, true, err
}
// Check the virtual server instance is ready for use
func (c *ClientManager) WaitInstanceUntilReady(id int, until time.Time) error {
for {
virtualGuest, found, err := c.GetInstance(id, "id, lastOperatingSystemReload[id,modifyDate], activeTransaction[id,transactionStatus.name], provisionDate, powerState.keyName")
if err != nil {
return err
}
if !found {
return bosherr.WrapErrorf(err, "SoftLayer virtual guest '%d' does not exist", id)
}
lastReload := virtualGuest.LastOperatingSystemReload
activeTxn := virtualGuest.ActiveTransaction
provisionDate := virtualGuest.ProvisionDate
// if lastReload != nil && lastReload.ModifyDate != nil {
// fmt.Println("lastReload: ", (*lastReload.ModifyDate).Format(time.RFC3339))
// }
// if activeTxn != nil && activeTxn.TransactionStatus != nil && activeTxn.TransactionStatus.Name != nil {
// fmt.Println("activeTxn: ", *activeTxn.TransactionStatus.Name)
// }
// if provisionDate != nil {
// fmt.Println("provisionDate: ", (*provisionDate).Format(time.RFC3339))
// }
reloading := activeTxn != nil && lastReload != nil && *activeTxn.Id == *lastReload.Id
if provisionDate != nil && !reloading {
// fmt.Println("power state:", *virtualGuest.PowerState.KeyName)
if *virtualGuest.PowerState.KeyName == "RUNNING" {
return nil
}
}
now := time.Now()
if now.After(until) {
return bosherr.Errorf("Power on virtual guest with id %d Time Out!", *virtualGuest.Id)
}
min := math.Min(float64(10.0), float64(until.Sub(now)))
time.Sleep(time.Duration(min) * time.Second)
}
}
// @TODO: The method is experimental and needed to verify.
func (c *ClientManager) WaitInstanceUntilReadyWithTicket(id int, until time.Time) error {
now := time.Now()
halfDuration := until.Sub(now) / 2
ticketTime := now.Add(halfDuration)
// Wait half duration until ready, otherwise create a ticket
c.logger.Debug(softlayerClientLogTag, fmt.Sprintf("Waiting for intance '%d' ready unless it is over %.2f minutes to create ticket.", id,
halfDuration.Minutes()))
err := c.WaitInstanceUntilReady(id, ticketTime)
if err != nil {
if strings.Contains(err.Error(), fmt.Sprintf("Power on virtual guest with id %d Time Out!", id)) {
contents := fmt.Sprintf("The power state of virtual guest '%d' is not 'RUNNING' after OS reload. The ticket generated by Bosh Softlayer CPI.", id)
c.logger.Debug(softlayerClientLogTag, fmt.Sprintf("Creating ticket for intance '%d' timeout.", id))
err = c.CreateTicket(sl.String("OS Reload Question"), sl.String("OS reload hung."),
sl.String(contents), sl.Int(id), sl.String("VIRTUAL_GUEST"))
if err != nil {
c.logger.Error(softlayerClientLogTag, fmt.Sprintf("Creating ticket for intance '%d' with err : %v.", id, err))
// @TODO: To comment by test
// return bosherr.WrapError(err, "Creating ticket.")
}
} else {
return err
}
}
// Wait remaining half duration until ready, otherwise throw timeout error.
c.logger.Debug(softlayerClientLogTag, fmt.Sprintf("Waiting for intance '%d' ready unless it is over %.2f minutes to return the timeout error.", id,
halfDuration.Minutes()))
err = c.WaitInstanceUntilReady(id, until)
if err != nil {
return err
}
return nil
}
func (c *ClientManager) WaitInstanceHasActiveTransaction(id int, until time.Time) error {
for {
virtualGuest, found, err := c.GetInstance(id, "id, activeTransaction[id,transactionStatus.name]")
if err != nil {
return err
}
if !found {
return bosherr.WrapErrorf(err, "SoftLayer virtual guest '%d' does not exist", id)
}
// if activeTxn != nil && activeTxn.TransactionStatus != nil && activeTxn.TransactionStatus.Name != nil {
// fmt.Println("activeTxn: ", *activeTxn.TransactionStatus.Name)
// }
if virtualGuest.ActiveTransaction != nil {
return nil
}
now := time.Now()
if now.After(until) {
return bosherr.Errorf("Waiting instance with id of '%d' has active transaction time out", id)
}
min := math.Min(float64(5.0), float64(until.Sub(now)))
time.Sleep(time.Duration(min) * time.Second)
}
}
func (c *ClientManager) WaitOrderCompleted(id int, until time.Time) error {
if id == 0 {
return nil
}
for {
order, err := c.BillingOrderService.Id(id).Mask("id, status").GetObject()
if err != nil {
return err
}
if *order.Status == "COMPLETED" {
return nil
}
now := time.Now()
if now.After(until) {
return bosherr.Errorf("Waiting order with id of '%d' has been completed", id)
}
min := math.Min(float64(5.0), float64(until.Sub(now)))
time.Sleep(time.Duration(min) * time.Second)
}
}
func (c *ClientManager) WaitInstanceHasNoneActiveTransaction(id int, until time.Time) error {
for {
virtualGuest, found, err := c.GetInstance(id, "id, activeTransaction[id,transactionStatus.name]")
if err != nil {
return err
}
if !found {
return bosherr.WrapErrorf(bosherr.Error(SOFTLAYER_OBJECTNOTFOUND_EXCEPTION), "SoftLayer virtual guest '%d' does not exist", id)
}
if virtualGuest.ActiveTransaction == nil {
return nil
}
if virtualGuest.ActiveTransaction.TransactionStatus != nil && *virtualGuest.ActiveTransaction.TransactionStatus.Name == "RECLAIM_WAIT" {
return bosherr.Errorf("Instance with id of '%d' has 'RECLAIM_WAIT' transaction", id)
}
now := time.Now()
if now.After(until) {
return bosherr.Errorf("Waiting instance with id of '%d' has none active transaction time out", id)
}
min := math.Min(float64(5.0), float64(until.Sub(now)))
time.Sleep(time.Duration(min) * time.Second)
}
}
func (c *ClientManager) CreateInstance(template *datatypes.Virtual_Guest, userData *registry.SoftlayerUserData) (*datatypes.Virtual_Guest, error) {
virtualguest, err := c.VirtualGuestService.CreateObject(template)
if err != nil {
return &datatypes.Virtual_Guest{}, bosherr.WrapError(err, "Creating instance")
}
// Wait for instance ready
time.Sleep(90 * time.Second)
err = c.SetUserDataWithID(*virtualguest.Id, userData)
if err != nil {
return &datatypes.Virtual_Guest{}, bosherr.WrapErrorf(err, "Updating user data contents with instance '%d'", *virtualguest.Id)
}
until := time.Now().Add(time.Duration(4) * time.Hour)
if err := c.WaitInstanceUntilReady(*virtualguest.Id, until); err != nil {
return &datatypes.Virtual_Guest{}, bosherr.WrapError(err, "Waiting until instance is ready")
}
if err := c.WaitInstanceHasNoneActiveTransaction(*virtualguest.Id, until); err != nil {
return &datatypes.Virtual_Guest{}, bosherr.WrapError(err, "Waiting until instance has none active transaction")
}
return &virtualguest, nil
}
func (c *ClientManager) CreateInstanceFromVPS(template *datatypes.Virtual_Guest,
stemcellID int, sshKeys []int, userData *registry.SoftlayerUserData) (*datatypes.Virtual_Guest, error) {
reqFilter := &models.VMFilter{
CPU: int32(*template.StartCpus),
MemoryMb: int32(*template.MaxMemory),
PrivateVlan: int32(*template.PrimaryBackendNetworkComponent.NetworkVlan.Id),
PublicVlan: int32(*template.PrimaryNetworkComponent.NetworkVlan.Id),
State: models.StateFree,
}
orderVmResp, err := c.vpsService.OrderVMByFilter(vpsVm.NewOrderVMByFilterParams().WithBody(reqFilter))
if err != nil {
_, ok := err.(*vpsVm.OrderVMByFilterNotFound)
if !ok {
return &datatypes.Virtual_Guest{}, bosherr.WrapError(err, "Ordering vm from pool")
} else {
// From createBySoftlayer implement run in cpi action
virtualGuest, err := c.CreateInstance(template, userData)
if err != nil {
return &datatypes.Virtual_Guest{}, bosherr.WrapError(err, "Creating VirtualGuest from SoftLayer client")
}
slPoolVm := &models.VM{
Cid: int32(*virtualGuest.Id),
CPU: int32(*template.StartCpus),
MemoryMb: int32(*template.MaxMemory),
IP: strfmt.IPv4(*template.PrimaryBackendIpAddress),
Hostname: *virtualGuest.Hostname,
PrivateVlan: int32(*template.PrimaryBackendNetworkComponent.NetworkVlan.Id),
PublicVlan: int32(*template.PrimaryNetworkComponent.NetworkVlan.Id),
State: models.StateUsing,
}
_, err = c.vpsService.AddVM(vpsVm.NewAddVMParams().WithBody(slPoolVm))
if err != nil {
return &datatypes.Virtual_Guest{}, bosherr.WrapError(err, "Adding vm into pool")
}
return virtualGuest, nil
}
}
var vm *models.VM
var virtualGuestId int
vm = orderVmResp.Payload.VM
virtualGuestId = int((*vm).Cid)
err = c.ReloadInstance(virtualGuestId, stemcellID, sshKeys, *template.Hostname, *template.Domain, userData)
if err != nil {
return &datatypes.Virtual_Guest{}, bosherr.WrapError(err, "Reloading vm from pool")
}
virtualGuest, found, err := c.GetInstance(virtualGuestId, INSTANCE_DEFAULT_MASK)
if err != nil {
return &datatypes.Virtual_Guest{}, err
}
if !found {
return &datatypes.Virtual_Guest{}, bosherr.WrapErrorf(err, "SoftLayer virtual guest '%d' does not exist", virtualGuestId)
}
deviceName := &models.VM{
Cid: int32(virtualGuestId),
CPU: int32(*virtualGuest.StartCpus),
MemoryMb: int32(*virtualGuest.MaxMemory),
IP: strfmt.IPv4(*virtualGuest.PrimaryBackendIpAddress),
Hostname: *virtualGuest.Hostname,
PrivateVlan: int32(*virtualGuest.PrimaryBackendNetworkComponent.NetworkVlan.Id),
PublicVlan: int32(*virtualGuest.PrimaryNetworkComponent.NetworkVlan.Id),
State: models.StateUsing,
}
_, err = c.vpsService.UpdateVM(vpsVm.NewUpdateVMParams().WithBody(deviceName))
if err != nil {
return &datatypes.Virtual_Guest{}, bosherr.WrapErrorf(err, "Updating the hostname of vm %d in pool to using", virtualGuestId)
}
return virtualGuest, nil
}
func (c *ClientManager) EditInstance(id int, template *datatypes.Virtual_Guest) (bool, error) {
_, err := c.VirtualGuestService.Id(id).EditObject(template)
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.Exception == SOFTLAYER_OBJECTNOTFOUND_EXCEPTION {
return false, nil
}
return false, err
}
}
until := time.Now().Add(time.Duration(30) * time.Minute)
if err := c.WaitInstanceUntilReady(id, until); err != nil {
return false, bosherr.WrapError(err, "Waiting until instance is ready")
}
return true, err
}
func (c *ClientManager) RebootInstance(id int, soft bool, hard bool) error {
var err error
if soft == false && hard == false {
_, err = c.VirtualGuestService.Id(id).RebootDefault()
} else if soft == true && hard == false {
_, err = c.VirtualGuestService.Id(id).RebootSoft()
} else if soft == false && hard == true {
_, err = c.VirtualGuestService.Id(id).RebootHard()
} else {
err = bosherr.Error("The reboot type is not existing")
}
return err
}
func (c *ClientManager) ReloadInstance(id int, stemcellId int, sshKeyIds []int, hostname string, domain string, userData *registry.SoftlayerUserData) error {
var err error
reloadUntil := time.Now().Add(time.Duration(10) * time.Second)
transactionUntil := time.Now().Add(time.Duration(1) * time.Hour)
err = c.SetUserDataWithID(id, userData)
if err != nil {
return bosherr.WrapErrorf(err, "Updating user data contents with instance '%d'", id)
}
c.logger.Debug(softlayerClientLogTag, "Waiting virtual guest '%d' has none active transaction.", id)
if err = c.WaitInstanceHasNoneActiveTransaction(*sl.Int(id), transactionUntil); err != nil {
return bosherr.WrapError(err, "Waiting until instance has none active transaction before os_reload")
}
config := datatypes.Container_Hardware_Server_Configuration{
ImageTemplateId: sl.Int(stemcellId),
}
if sshKeyIds[0] != 0 {
config.SshKeyIds = sshKeyIds
}
c.logger.Debug(softlayerClientLogTag, "Reloading operating system of virtual guest '%d'.", id)
if err = c.reloadOperatingSystemWithConfig(id, &config, reloadUntil); err != nil {
return bosherr.WrapErrorf(err, "Reloading operating system of virtual guest '%d'", id)
}
transactionUntil = time.Now().Add(time.Duration(1) * time.Hour)
if err = c.WaitInstanceHasActiveTransaction(*sl.Int(id), transactionUntil); err != nil {
return bosherr.WrapError(err, "Waiting until instance has active transaction after launching os_reload")
}
transactionUntil = time.Now().Add(time.Duration(4) * time.Hour)
if err = c.WaitInstanceUntilReadyWithTicket(*sl.Int(id), transactionUntil); err != nil {
return bosherr.WrapError(err, "Waiting until instance is ready after os_reload")
}
succeed, err := c.EditInstance(id, &datatypes.Virtual_Guest{
Hostname: sl.String(hostname),
Domain: sl.String(domain),
})
if err != nil {
return bosherr.WrapError(err, "Editing VM hostname after OS Reload")
}
if !succeed {
return bosherr.WrapError(err, "Failed to edit VM hostname after OS Reload")
}
return nil
}
func (c *ClientManager) CancelInstance(id int) error {
var err error
until := time.Now().Add(time.Duration(10) * time.Minute)
if err = c.WaitInstanceHasNoneActiveTransaction(*sl.Int(id), until); err != nil {
if boshErr, ok := err.(bosherr.ComplexError); ok {
if strings.Contains(boshErr.Cause.Error(), SOFTLAYER_OBJECTNOTFOUND_EXCEPTION) {
c.logger.Warn(softlayerClientLogTag, fmt.Sprintf("Instance '%d' does not exist, CPI skips to cancel it", id))
return nil
}
}
if strings.Contains(err.Error(), "has 'RECLAIM_WAIT' transaction") {
c.logger.Warn(softlayerClientLogTag, fmt.Sprintf("Instance '%d' stays 'RECLAIM_WAIT' transaction, CPI skips to cancel it", id))
return nil
}
return bosherr.WrapError(err, "Waiting until instance has none active transaction before canceling")
}
resp, err := c.VirtualGuestService.Id(id).DeleteObject()
if err != nil {
return bosherr.WrapErrorf(err, "Deleting instance with id '%d'", id)
}
if !resp {
return bosherr.WrapErrorf(err, "Deleting instance with id '%d' failed", id)
}
return nil
}
func (c *ClientManager) DeleteInstanceFromVPS(id int) error {
_, err := c.vpsService.GetVMByCid(vpsVm.NewGetVMByCidParams().WithCid(int32(id)))
if err != nil {
_, ok := err.(*vpsVm.GetVMByCidNotFound)
if ok {
virtualGuest, err := c.VirtualGuestService.Id(id).GetObject()
if err != nil {
return bosherr.WrapError(err, fmt.Sprintf("Getting virtual guest %d details from SoftLayer", id))
}
slPoolVm := &models.VM{
Cid: int32(id),
CPU: int32(*virtualGuest.StartCpus),
MemoryMb: int32(*virtualGuest.MaxMemory),
IP: strfmt.IPv4(*virtualGuest.PrimaryBackendIpAddress),
Hostname: *virtualGuest.FullyQualifiedDomainName,
PrivateVlan: int32(*virtualGuest.PrimaryBackendNetworkComponent.NetworkVlan.Id),
PublicVlan: int32(*virtualGuest.PrimaryNetworkComponent.NetworkVlan.Id),
State: models.StateFree,
}
_, err = c.vpsService.AddVM(vpsVm.NewAddVMParams().WithBody(slPoolVm))
if err != nil {
return bosherr.WrapError(err, fmt.Sprintf("Adding vm %d to pool", id))
}
return nil
}
return bosherr.WrapError(err, "Removing vm from pool")
}
free := models.VMState{
State: models.StateFree,
}
_, err = c.vpsService.UpdateVMWithState(vpsVm.NewUpdateVMWithStateParams().WithBody(&free).WithCid(int32(id)))
if err != nil {
return bosherr.WrapErrorf(err, "Updating state of vm %d in pool to free", id)
}
return nil
}
func (c *ClientManager) UpgradeInstance(id int, cpu int, memory int, network int, privateCPU bool, dedicatedHost bool, secondDiskSize int) (int, error) {
upgradeOptions := make(map[string]float64, 0)
presetId := 0
// CPI only support public network speed currently
forPublicNetwork := true
if cpu != 0 {
upgradeOptions["guest_core"] = float64(cpu)
c.logger.Debug(softlayerClientLogTag, fmt.Sprintf("Upgrade item price for 'guest_core/%d'", cpu))
}
if memory != 0 {
upgradeOptions["ram"] = float64(memory / 1024)
c.logger.Debug(softlayerClientLogTag, fmt.Sprintf("Upgrade item price for 'ram/%d'", memory/1024))
}
if network != 0 {
upgradeOptions["port_speed"] = float64(network)
c.logger.Debug(softlayerClientLogTag, fmt.Sprintf("Upgrade item price for 'port_speed/%d'", network))
}
packageType := "VIRTUAL_SERVER_INSTANCE"
productPackages, err := c.PackageService.
Mask("id,name,description,isActive,type.keyName").
Filter(filter.New(filter.Path("type.keyName").Eq(packageType)).Build()).
GetAllObjects()
if err != nil {
return 0, err
}
if len(productPackages) == 0 {
return 0, bosherr.Errorf("No package found for type: %s", packageType)
}
packageID := *productPackages[0].Id
var prices = make([]datatypes.Product_Item_Price, 0)
if len(upgradeOptions) != 0 {
c.logger.Debug(softlayerClientLogTag, "Find upgrade item prices for instance upgrade")
includeDowngradeItemPrices := true
packageItemPrices, err := c.VirtualGuestService.
Id(id).
Mask("id, locationGroupId, categories[categoryCode], item[keyName, description, capacity]").
GetUpgradeItemPrices(&includeDowngradeItemPrices)
if err != nil {
return 0, err
}
prices = c.selectProductPricesByCategory(packageItemPrices, upgradeOptions, forPublicNetwork, !privateCPU, dedicatedHost)
}
if secondDiskSize != 0 {
c.logger.Debug(softlayerClientLogTag, fmt.Sprintf("Find upgrade item price for second disk: %dGB", secondDiskSize))
var diskItemPrice *datatypes.Product_Item_Price
diskItemPrice, presetId, err = c.getUpgradeItemPriceForSecondDisk(id, secondDiskSize)
if err != nil {
return 0, err
}
prices = append(prices, *diskItemPrice)
}
if len(prices) == 0 {
return 0, bosherr.Errorf("Unable to find prices for upgrade: %v", upgradeOptions)
}
order := datatypes.Container_Product_Order{
ComplexType: sl.String(UPGRADE_VIRTUAL_SERVER_ORDER_TYPE),
Prices: prices,
Properties: []datatypes.Container_Product_Order_Property{
{
Name: sl.String("MAINTENANCE_WINDOW"),
Value: sl.String(time.Now().UTC().Format(time.RFC3339)),
},
{
Name: sl.String("NOTE_GENERAL"),
Value: sl.String("Upgrade instance configuration."),
},
},
VirtualGuests: []datatypes.Virtual_Guest{
{
Id: &id,
},
},
PackageId: &packageID,
}
if presetId != 0 {
order.PresetId = sl.Int(presetId)
}
upgradeOrder := datatypes.Container_Product_Order_Virtual_Guest_Upgrade{
Container_Product_Order_Virtual_Guest: datatypes.Container_Product_Order_Virtual_Guest{
Container_Product_Order_Hardware_Server: datatypes.Container_Product_Order_Hardware_Server{
Container_Product_Order: order,
},
},
}
c.logger.Debug(softlayerClientLogTag, fmt.Sprintf("Place order for vm '%d'", id))
orderId := 0
execPlaceOrderRetryable := boshretry.NewRetryable(
func() (bool, error) {
orderReceipt, err := c.OrderService.PlaceOrder(&upgradeOrder, sl.Bool(false))
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if strings.Contains(apiErr.Message, "A current price was provided for the upgrade order") {
c.logger.Debug(softlayerClientLogTag, "Skipping to place the order because current price is the same as what you already have on the server")
orderId = 0
return false, nil
} else {
return false, bosherr.WrapErrorf(err, "Placing order with '%+v'", order)
}
} else {
return false, bosherr.WrapErrorf(err, "Placing order with '%+v'", order)
}
}
if orderReceipt.OrderId == nil {
return true, bosherr.Error("Unable to find order id")
} else {
orderId = *orderReceipt.OrderId
return false, nil
}
})
attemptRetryStrategy := boshretry.NewAttemptRetryStrategy(3, 5*time.Second, execPlaceOrderRetryable, c.logger.GetBoshLogger())
err = c.logger.ChangeRetryStrategyLogTag(&attemptRetryStrategy)
if err != nil {
return orderId, err
}
err = attemptRetryStrategy.Try()
if err != nil {
return orderId, err
}
return orderId, nil
}
func (c *ClientManager) SetTags(id int, tags string) (bool, error) {
_, err := c.VirtualGuestService.Id(id).SetTags(&tags)
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.Exception == SOFTLAYER_OBJECTNOTFOUND_EXCEPTION {
return false, nil
}
return false, err
}
}
return true, err
}
func (c *ClientManager) GetInstanceAllowedHost(id int) (*datatypes.Network_Storage_Allowed_Host, bool, error) {
mask := "id, name, credential[username, password]"
allowedHost, err := c.VirtualGuestService.Id(id).Mask(mask).GetAllowedHost()
if err != nil {
return &datatypes.Network_Storage_Allowed_Host{}, false, err
}
if allowedHost.Id == nil {
return &datatypes.Network_Storage_Allowed_Host{}, false, bosherr.Errorf("Unable to get allowed host with instance id: %d", id)
}
return &allowedHost, true, nil
}
func (c *ClientManager) getUpgradeItemPriceForSecondDisk(id int, diskSize int) (*datatypes.Product_Item_Price, int, error) {
// filter := filter.Build(
// filter.Path("productItemPrice.categories.categoryCode").Eq(EPHEMERAL_DISK_CATEGORY_CODE),
// )
mask := "id, categories[id, categoryCode], item[description, capacity]"
itemPrices, err := c.VirtualGuestService.Id(id).Mask(mask).GetUpgradeItemPrices(sl.Bool(true))
if err != nil {
return &datatypes.Product_Item_Price{}, 0, err
}
mask = "localDiskFlag, billingItem[id, orderItem[presetId]]"
virtualGuest, err := c.VirtualGuestService.Id(id).Mask(mask).GetObject()
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.Exception == SOFTLAYER_OBJECTNOTFOUND_EXCEPTION {
return &datatypes.Product_Item_Price{}, 0, nil
}
return &datatypes.Product_Item_Price{}, 0, err
}
}
var currentDiskCapacity int
var diskType string
var currentItemPrice datatypes.Product_Item_Price
if *virtualGuest.LocalDiskFlag {
diskType = "(LOCAL)"
} else {
diskType = "(SAN)"
}
for _, itemPrice := range itemPrices {
flag := false
for _, category := range itemPrice.Categories {
if *category.CategoryCode == EPHEMERAL_DISK_CATEGORY_CODE {
flag = true
break
}
}
if flag && strings.Contains(*itemPrice.Item.Description, diskType) {
if int(*itemPrice.Item.Capacity) >= diskSize {
if currentItemPrice.Id == nil || currentDiskCapacity >= int(*itemPrice.Item.Capacity) {
currentItemPrice = itemPrice
currentDiskCapacity = int(*itemPrice.Item.Capacity)
}
}
}
}
if currentItemPrice.Id == nil {
return &datatypes.Product_Item_Price{}, 0, bosherr.Errorf("No proper %s disk for size %d", diskType, diskSize)
}
if virtualGuest.BillingItem.OrderItem.PresetId == nil {
return ¤tItemPrice, 0, nil
}
return ¤tItemPrice, *virtualGuest.BillingItem.OrderItem.PresetId, nil
}
func (c *ClientManager) GetBlockVolumeDetails(volumeId int, mask string) (*datatypes.Network_Storage, bool, error) {
if mask == "" {
mask = VOLUME_DETAIL_MASK
}
volume, err := c.StorageService.Id(volumeId).Mask(mask).GetObject()
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.Exception == SOFTLAYER_OBJECTNOTFOUND_EXCEPTION {
return &datatypes.Network_Storage{}, false, nil
}
return &datatypes.Network_Storage{}, false, err
}
}
return &volume, true, nil
}
func (c *ClientManager) GetBlockVolumeDetailsBySoftLayerAccount(volumeId int, mask string) (datatypes.Network_Storage, error) {
if mask == "" {
mask = VOLUME_DETAIL_MASK
}
volumes, err := c.AccountService.Mask(mask).Filter(filter.Path("iscsiNetworkStorage.id").Eq(volumeId).Build()).GetIscsiNetworkStorage()
if err != nil {
return datatypes.Network_Storage{}, err
}