-
Notifications
You must be signed in to change notification settings - Fork 673
/
Copy pathresource_ibm_pi_instance.go
1023 lines (866 loc) · 32.8 KB
/
resource_ibm_pi_instance.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 ibm
import (
"encoding/base64"
"fmt"
"log"
"sort"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/IBM-Cloud/bluemix-go/bmxerror"
st "github.com/IBM-Cloud/power-go-client/clients/instance"
"github.com/IBM-Cloud/power-go-client/helpers"
"github.com/IBM-Cloud/power-go-client/power/client/p_cloud_p_vm_instances"
"github.com/IBM-Cloud/power-go-client/power/models"
)
const (
createTimeOut = 120 * time.Second
updateTimeOut = 120 * time.Second
postTimeOut = 60 * time.Second
getTimeOut = 60 * time.Second
deleteTimeOut = 60 * time.Second
//Added timeout values for warning and active status
warningTimeOut = 30 * time.Second
activeTimeOut = 2 * time.Minute
)
func resourceIBMPIInstance() *schema.Resource {
return &schema.Resource{
Create: resourceIBMPIInstanceCreate,
Read: resourceIBMPIInstanceRead,
Update: resourceIBMPIInstanceUpdate,
Delete: resourceIBMPIInstanceDelete,
Exists: resourceIBMPIInstanceExists,
Importer: &schema.ResourceImporter{},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(120 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
helpers.PICloudInstanceId: {
Type: schema.TypeString,
Required: true,
Description: "This is the Power Instance id that is assigned to the account",
},
"status": {
Type: schema.TypeString,
Computed: true,
Description: "PI instance status",
},
"migratable": {
Type: schema.TypeBool,
Computed: true,
Description: "set to true to enable migration of the PI instance",
},
"min_processors": {
Type: schema.TypeFloat,
Computed: true,
Description: "Minimum number of the CPUs",
},
"min_memory": {
Type: schema.TypeFloat,
Computed: true,
Description: "Minimum memory",
},
"max_processors": {
Type: schema.TypeFloat,
Computed: true,
Description: "Maximum number of processors",
},
"max_memory": {
Type: schema.TypeFloat,
Computed: true,
Description: "Maximum memory size",
},
helpers.PIInstanceNetworkIds: {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Description: "Set of Networks that have been configured for the account",
DiffSuppressFunc: applyOnce,
},
helpers.PIInstanceVolumeIds: {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
DiffSuppressFunc: applyOnce,
Description: "List of PI volumes",
},
helpers.PIInstanceUserData: {
Type: schema.TypeString,
Optional: true,
Description: "Base64 encoded data to be passed in for invoking a cloud init script",
},
"addresses": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip": {
Type: schema.TypeString,
Computed: true,
},
"macaddress": {
Type: schema.TypeString,
Computed: true,
},
"network_id": {
Type: schema.TypeString,
Computed: true,
},
"network_name": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"external_ip": {
Type: schema.TypeString,
Computed: true,
},
/*"version": {
Type: schema.TypeFloat,
Computed: true,
},*/
},
},
},
"health_status": {
Type: schema.TypeString,
Computed: true,
Description: "PI Instance health status",
},
"instance_id": {
Type: schema.TypeString,
Computed: true,
Description: "Instance ID",
},
"pin_policy": {
Type: schema.TypeString,
Computed: true,
Description: "PIN Policy of the Instance",
},
helpers.PIInstanceImageName: {
Type: schema.TypeString,
Required: true,
Description: "PI instance image name",
},
helpers.PIInstanceProcessors: {
Type: schema.TypeFloat,
Required: true,
Description: "Processors count",
},
helpers.PIInstanceName: {
Type: schema.TypeString,
Required: true,
Description: "PI Instance name",
},
helpers.PIInstanceProcType: {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateAllowedStringValue([]string{"dedicated", "shared", "capped"}),
Description: "Instance processor type",
},
helpers.PIInstanceSSHKeyName: {
Type: schema.TypeString,
Required: true,
Description: "SSH key name",
},
helpers.PIInstanceMemory: {
Type: schema.TypeFloat,
Required: true,
Description: "Memory size",
},
helpers.PIInstanceSystemType: {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateAllowedStringValue([]string{"s922", "e880", "e980"}),
Description: "PI Instance system type",
},
helpers.PIInstanceReplicants: {
Type: schema.TypeFloat,
Optional: true,
Default: "1",
Description: "PI Instance replicas count",
},
helpers.PIInstanceReplicationPolicy: {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateAllowedStringValue([]string{"affinity", "anti-affinity", "none"}),
Default: "none",
Description: "Replication policy for the PI Instance",
},
helpers.PIInstanceReplicationScheme: {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateAllowedStringValue([]string{"prefix", "suffix"}),
Default: "suffix",
Description: "Replication scheme",
},
helpers.PIInstanceProgress: {
Type: schema.TypeFloat,
Computed: true,
Description: "Progress of the operation",
},
helpers.PIInstancePinPolicy: {
Type: schema.TypeString,
Optional: true,
Description: "Pin Policy of the instance",
Default: "none",
ValidateFunc: validateAllowedStringValue([]string{"none", "soft", "hard"}),
},
"reboot_for_resource_change": {
Type: schema.TypeString,
Optional: true,
Description: "Flag to be passed for CPU/Memory changes that require a reboot to take effect",
},
"operating_system": {
Type: schema.TypeString,
Computed: true,
Description: "Operating System",
},
"os_type": {
Type: schema.TypeString,
Computed: true,
Description: "OS Type",
},
helpers.PIInstanceHealthStatus: {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateAllowedStringValue([]string{"OK", "WARNING"}),
Default: "OK",
Description: "Allow the user to set the status of the lpar so that they can connect to it faster",
},
helpers.PIVirtualCoresAssigned: {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Virtual Cores Assigned to the PVMInstance",
},
"max_virtual_cores": {
Type: schema.TypeInt,
Computed: true,
Description: "Maximum Virtual Cores Assigned to the PVMInstance",
},
"min_virtual_cores": {
Type: schema.TypeInt,
Computed: true,
Description: "Minimum Virtual Cores Assigned to the PVMInstance",
},
},
}
}
func resourceIBMPIInstanceCreate(d *schema.ResourceData, meta interface{}) error {
log.Printf("Now in the PowerVMCreate")
sess, err := meta.(ClientSession).IBMPISession()
if err != nil {
return err
}
powerinstanceid := d.Get(helpers.PICloudInstanceId).(string)
name := d.Get(helpers.PIInstanceName).(string)
sshkey := d.Get(helpers.PIInstanceSSHKeyName).(string)
mem := d.Get(helpers.PIInstanceMemory).(float64)
procs := d.Get(helpers.PIInstanceProcessors).(float64)
systype := d.Get(helpers.PIInstanceSystemType).(string)
networks := expandStringList((d.Get(helpers.PIInstanceNetworkIds).(*schema.Set)).List())
volids := expandStringList((d.Get(helpers.PIInstanceVolumeIds).(*schema.Set)).List())
replicants := d.Get(helpers.PIInstanceReplicants).(float64)
replicationpolicy := d.Get(helpers.PIInstanceReplicationPolicy).(string)
replicationNamingScheme := d.Get(helpers.PIInstanceReplicationScheme).(string)
imageid := d.Get(helpers.PIInstanceImageName).(string)
processortype := d.Get(helpers.PIInstanceProcType).(string)
pinpolicy := d.Get(helpers.PIInstancePinPolicy).(string)
if d.Get(helpers.PIInstancePinPolicy) == "" {
pinpolicy = "none"
}
instance_ready_status := d.Get(helpers.PIInstanceHealthStatus).(string)
if d.Get(helpers.PIInstanceHealthStatus) == "" {
log.Printf("Instance Ready Status is not provided. Setting the default to OK")
instance_ready_status = "OK"
}
log.Printf("The accepted instance status for the LPAR [%s] can be [%s] ", name, instance_ready_status)
//var userdata = ""
user_data := d.Get(helpers.PIInstanceUserData).(string)
if d.Get(helpers.PIInstanceUserData) == "" {
user_data = ""
}
err = checkBase64(user_data)
if err != nil {
log.Printf("Data is not base64 encoded")
return err
}
sort.Strings(networks)
//publicinterface := d.Get(helpers.PIInstancePublicNetwork).(bool)
body := &models.PVMInstanceCreate{
//NetworkIds: networks,
Processors: &procs,
Memory: &mem,
ServerName: ptrToString(name),
SysType: systype,
KeyPairName: sshkey,
ImageID: ptrToString(imageid),
ProcType: ptrToString(processortype),
Replicants: replicants,
UserData: user_data,
ReplicantNamingScheme: ptrToString(replicationNamingScheme),
ReplicantAffinityPolicy: ptrToString(replicationpolicy),
Networks: buildPVMNetworks(networks),
}
if len(volids) > 0 {
body.VolumeIds = volids
}
if d.Get(helpers.PIInstancePinPolicy) == "soft" || d.Get(helpers.PIInstancePinPolicy) == "hard" {
body.PinPolicy = models.PinPolicy(pinpolicy)
}
if d.Get(helpers.PIVirtualCoresAssigned) != "" && d.Get(helpers.PIVirtualCoresAssigned) != 0 {
//cores, err := strconv.Atoi(d.Get(helpers.PIVirtualCoresAssigned).(string))
//if err != nil {
// fmt.Errorf("failed to convert %v", err)
//}
assigned_virtual_cores := int64(d.Get(helpers.PIVirtualCoresAssigned).(int))
body.VirtualCores = &models.VirtualCores{Assigned: &assigned_virtual_cores}
} else {
log.Printf("Virtual cores is not provided")
}
client := st.NewIBMPIInstanceClient(sess, powerinstanceid)
pvm, err := client.Create(&p_cloud_p_vm_instances.PcloudPvminstancesPostParams{
Body: body,
}, powerinstanceid, createTimeOut)
if err != nil {
return fmt.Errorf("failed to provision %v", err)
} else {
log.Printf("Printing the instance info %+v", &pvm)
}
var pvminstanceids []string
if replicants > 1 {
log.Printf("We are in a multi create mode")
for i := 0; i < int(replicants); i++ {
truepvmid := (*pvm)[i].PvmInstanceID
log.Printf("Printing the instance id %s", *truepvmid)
pvminstanceids = append(pvminstanceids, fmt.Sprintf("%s", *truepvmid))
log.Printf("Printing each of the pvminstance ids %s", pvminstanceids)
d.SetId(fmt.Sprintf("%s/%s", powerinstanceid, *truepvmid))
}
d.SetId(strings.Join(pvminstanceids, "/"))
} else {
log.Printf("Single Create Mode ")
truepvmid := (*pvm)[0].PvmInstanceID
d.SetId(fmt.Sprintf("%s/%s", powerinstanceid, *truepvmid))
pvminstanceids = append(pvminstanceids, *truepvmid)
log.Printf("Printing the instance id .. after the create ... %s", *truepvmid)
}
log.Printf("the number of pvminstanceids is %d", len(pvminstanceids))
for ids := range pvminstanceids {
log.Printf("The pvm instance id is [%s] .Checking for status", pvminstanceids[ids])
//ids, err = strconv.Atoi(str)
if err != nil {
return fmt.Errorf("failed to get information on the pvminstance %v", err)
}
_, err = isWaitForPIInstanceAvailable(client, pvminstanceids[ids], d.Timeout(schema.TimeoutCreate), powerinstanceid, instance_ready_status)
if err != nil {
return err
}
}
return resourceIBMPIInstanceRead(d, meta)
}
func resourceIBMPIInstanceRead(d *schema.ResourceData, meta interface{}) error {
log.Printf("Calling the PowerInstance Read code..")
sess, err := meta.(ClientSession).IBMPISession()
if err != nil {
return err
}
parts, err := idParts(d.Id())
if err != nil {
return err
}
powerinstanceid := parts[0]
powerC := st.NewIBMPIInstanceClient(sess, powerinstanceid)
powervmdata, err := powerC.Get(parts[1], powerinstanceid, getTimeOut)
if err != nil {
return fmt.Errorf("failed to get the instance %v", err)
}
d.Set(helpers.PIInstanceMemory, powervmdata.Memory)
d.Set(helpers.PIInstanceProcessors, powervmdata.Processors)
d.Set("status", powervmdata.Status)
d.Set(helpers.PIInstanceProcType, powervmdata.ProcType)
d.Set("migratable", powervmdata.Migratable)
d.Set("min_processors", powervmdata.Minproc)
d.Set(helpers.PIInstanceProgress, powervmdata.Progress)
d.Set(helpers.PICloudInstanceId, powerinstanceid)
d.Set("instance_id", powervmdata.PvmInstanceID)
d.Set(helpers.PIInstanceName, powervmdata.ServerName)
d.Set(helpers.PIInstanceImageName, powervmdata.ImageID)
var networks []string
networks = make([]string, 0)
if powervmdata.Networks != nil {
for _, n := range powervmdata.Networks {
if n != nil {
networks = append(networks, n.NetworkID)
}
}
}
d.Set(helpers.PIInstanceNetworkIds, newStringSet(schema.HashString, networks))
d.Set(helpers.PIInstanceVolumeIds, powervmdata.VolumeIds)
d.Set(helpers.PIInstanceSystemType, powervmdata.SysType)
d.Set("min_memory", powervmdata.Minmem)
d.Set("max_processors", powervmdata.Maxproc)
d.Set("max_memory", powervmdata.Maxmem)
d.Set("pin_policy", powervmdata.PinPolicy)
d.Set("operating_system", powervmdata.OperatingSystem)
d.Set("os_type", powervmdata.OsType)
if powervmdata.Addresses != nil {
pvmaddress := make([]map[string]interface{}, len(powervmdata.Addresses))
for i, pvmip := range powervmdata.Addresses {
log.Printf("Now entering the powervm address space....")
p := make(map[string]interface{})
p["ip"] = pvmip.IP
p["network_name"] = pvmip.NetworkName
p["network_id"] = pvmip.NetworkID
p["macaddress"] = pvmip.MacAddress
p["type"] = pvmip.Type
p["external_ip"] = pvmip.ExternalIP
pvmaddress[i] = p
}
d.Set("addresses", pvmaddress)
}
if powervmdata.Health != nil {
d.Set("health_status", powervmdata.Health.Status)
}
if powervmdata.VirtualCores.Assigned != nil {
d.Set(helpers.PIVirtualCoresAssigned, powervmdata.VirtualCores.Assigned)
d.Set("max_virtual_cores", powervmdata.VirtualCores.Max)
d.Set("min_virtual_cores", powervmdata.VirtualCores.Min)
}
return nil
}
func resourceIBMPIInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
name := d.Get(helpers.PIInstanceName).(string)
mem := d.Get(helpers.PIInstanceMemory).(float64)
procs := d.Get(helpers.PIInstanceProcessors).(float64)
processortype := d.Get(helpers.PIInstanceProcType).(string)
assigned_virtual_cores := int64(d.Get(helpers.PIVirtualCoresAssigned).(int))
sess, err := meta.(ClientSession).IBMPISession()
if err != nil {
return fmt.Errorf("failed to get the session from the IBM Cloud Service")
}
if d.Get("health_status") == "WARNING" {
return fmt.Errorf("the operation cannot be performed when the lpar health in the WARNING State")
}
parts, err := idParts(d.Id())
if err != nil {
return err
}
powerinstanceid := parts[0]
client := st.NewIBMPIInstanceClient(sess, powerinstanceid)
//if d.HasChange(helpers.PIInstanceName) || d.HasChange(helpers.PIInstanceProcessors) || d.HasChange(helpers.PIInstanceProcType) || d.HasChange(helpers.PIInstancePinPolicy){
if d.HasChange(helpers.PIInstanceProcType) {
// Stop the lpar
processortype := d.Get(helpers.PIInstanceProcType).(string)
if d.Get("status") == "SHUTOFF" {
log.Printf("the lpar is in the shutoff state. Nothing to do . Moving on ")
} else {
body := &models.PVMInstanceAction{
Action: ptrToString("immediate-shutdown"),
}
resp, err := client.Action(&p_cloud_p_vm_instances.PcloudPvminstancesActionPostParams{Body: body}, parts[1], powerinstanceid, postTimeOut)
if err != nil {
log.Printf("Stop Action failed on [%s]", name)
return fmt.Errorf("failed to perform the stop action on the pvm instance %v", err)
}
log.Printf("Getting the response from the shutdown ... %v", resp)
_, err = isWaitForPIInstanceStopped(client, parts[1], d.Timeout(schema.TimeoutUpdate), powerinstanceid)
if err != nil {
return fmt.Errorf("failed to perform the stop action on the pvm instance %v", err)
}
}
// Modify
log.Printf("At this point the lpar should be off. Executing the Processor Update Change")
updatebody := &models.PVMInstanceUpdate{ProcType: processortype}
updateresp, err := client.Update(parts[1], powerinstanceid, &p_cloud_p_vm_instances.PcloudPvminstancesPutParams{Body: updatebody}, updateTimeOut)
if err != nil {
return fmt.Errorf("failed to perform the modify operation on the pvm instance %v", err)
} else {
log.Printf("Getting the response from the change %s", updateresp.StatusURL)
}
// To check if the verify resize operation is complete.. and then it will go to SHUTOFF
_, err = isWaitForPIInstanceStopped(client, parts[1], d.Timeout(schema.TimeoutUpdate), powerinstanceid)
if err != nil {
return err
}
// Start
startbody := &models.PVMInstanceAction{
Action: ptrToString("start"),
}
startresp, err := client.Action(&p_cloud_p_vm_instances.PcloudPvminstancesActionPostParams{Body: startbody}, parts[1], powerinstanceid, postTimeOut)
if err != nil {
return fmt.Errorf("failed to perform the start action on the pvm instance %v", err)
} else {
log.Printf("Performing the start operation on the pvminstance")
}
log.Printf("Getting the response from the start %s", startresp)
_, err = isWaitForPIInstanceAvailable(client, parts[1], d.Timeout(schema.TimeoutUpdate), powerinstanceid, "OK")
if err != nil {
return err
}
}
// Start of the change for Memory and Processors
if d.HasChange(helpers.PIVirtualCoresAssigned) {
log.Printf("Calling the change for the Virtual Cores")
max_vc := d.Get("max_virtual_cores").(int)
log.Printf("the max virtual cores is set to %d", max_vc)
parts, err := idParts(d.Id())
if err != nil {
return err
}
powerinstanceid := parts[0]
client := st.NewIBMPIInstanceClient(sess, powerinstanceid)
body := &models.PVMInstanceUpdate{
VirtualCores: &models.VirtualCores{Assigned: &assigned_virtual_cores},
}
resp, err := client.Update(parts[1], powerinstanceid, &p_cloud_p_vm_instances.PcloudPvminstancesPutParams{Body: body}, updateTimeOut)
if err != nil {
return fmt.Errorf("failed to update the lpar with the change for virtual cores")
}
log.Printf("Getting the response from the bigger change block %s", resp.StatusURL)
_, err = isWaitForPIInstanceAvailable(client, parts[1], d.Timeout(schema.TimeoutUpdate), powerinstanceid, "OK")
if err != nil {
return err
}
}
if d.HasChange(helpers.PIInstanceMemory) || d.HasChange(helpers.PIInstanceProcessors) {
log.Printf("Checking for cpu / memory change..and also virtual cores")
max_mem_lpar := d.Get("max_memory").(float64)
max_cpu_lpar := d.Get("max_processors").(float64)
//log.Printf("the required memory is set to [%d] and current max memory is set to [%d] ", int(mem), int(max_mem_lpar))
if mem > max_mem_lpar || procs > max_cpu_lpar {
log.Printf("Will require a shutdown to perform the change")
} else {
log.Printf("max_mem_lpar is set to %f", max_mem_lpar)
log.Printf("max_cpu_lpar is set to %f", max_cpu_lpar)
}
//if d.GetOkExists("reboot_for_resource_change")
if mem > max_mem_lpar || procs > max_cpu_lpar {
_, err = performChangeAndReboot(client, parts[1], powerinstanceid, mem, procs)
//_, err = stopLparForResourceChange(client, parts[1], powerinstanceid)
if err != nil {
return fmt.Errorf("failed to perform the operation for the change")
}
} else {
log.Printf("Memory change is within limits")
parts, err := idParts(d.Id())
if err != nil {
return err
}
powerinstanceid := parts[0]
client := st.NewIBMPIInstanceClient(sess, powerinstanceid)
body := &models.PVMInstanceUpdate{
Memory: mem,
ProcType: processortype,
Processors: procs,
ServerName: name,
}
body.VirtualCores = &models.VirtualCores{Assigned: &assigned_virtual_cores}
resp, err := client.Update(parts[1], powerinstanceid, &p_cloud_p_vm_instances.PcloudPvminstancesPutParams{Body: body}, updateTimeOut)
if err != nil {
return fmt.Errorf("failed to update the lpar with the change")
}
log.Printf("Getting the response from the bigger change block %s", resp.StatusURL)
_, err = isWaitForPIInstanceAvailable(client, parts[1], d.Timeout(schema.TimeoutUpdate), powerinstanceid, "OK")
if err != nil {
return err
}
}
}
return resourceIBMPIInstanceRead(d, meta)
}
func resourceIBMPIInstanceDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("Calling the Instance Delete method")
sess, _ := meta.(ClientSession).IBMPISession()
parts, err := idParts(d.Id())
if err != nil {
return err
}
powerinstanceid := parts[0]
client := st.NewIBMPIInstanceClient(sess, powerinstanceid)
log.Printf("Deleting the instance with name/id %s and cloud_instance_id %s", parts[1], powerinstanceid)
err = client.Delete(parts[1], powerinstanceid, deleteTimeOut)
if err != nil {
return fmt.Errorf("failed to perform the delete action on the pvm instance %v", err)
}
_, err = isWaitForPIInstanceDeleted(client, parts[1], d.Timeout(schema.TimeoutDelete), powerinstanceid)
if err != nil {
return err
}
d.SetId("")
return nil
}
// Exists
func resourceIBMPIInstanceExists(d *schema.ResourceData, meta interface{}) (bool, error) {
log.Printf("Calling the PowerInstance Exists method")
sess, err := meta.(ClientSession).IBMPISession()
if err != nil {
return false, err
}
parts, err := idParts(d.Id())
if err != nil {
return false, err
}
powerinstanceid := parts[0]
client := st.NewIBMPIInstanceClient(sess, powerinstanceid)
instance, err := client.Get(parts[1], powerinstanceid, getTimeOut)
if err != nil {
if apiErr, ok := err.(bmxerror.RequestFailure); ok {
if apiErr.StatusCode() == 404 {
return false, nil
}
}
return false, fmt.Errorf("error communicating with the API: %s", err)
}
truepvmid := *instance.PvmInstanceID
return truepvmid == parts[1], nil
}
func isWaitForPIInstanceDeleted(client *st.IBMPIInstanceClient, id string, timeout time.Duration, powerinstanceid string) (interface{}, error) {
log.Printf("Waiting for (%s) to be deleted.", id)
stateConf := &resource.StateChangeConf{
Pending: []string{"retry", helpers.PIInstanceDeleting},
Target: []string{helpers.PIInstanceNotFound},
Refresh: isPIInstanceDeleteRefreshFunc(client, id, powerinstanceid),
Delay: 10 * time.Second,
MinTimeout: 10 * time.Second,
Timeout: 10 * time.Minute,
}
return stateConf.WaitForState()
}
func isPIInstanceDeleteRefreshFunc(client *st.IBMPIInstanceClient, id, powerinstanceid string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
pvm, err := client.Get(id, powerinstanceid, getTimeOut)
if err != nil {
log.Printf("The power vm does not exist")
return pvm, helpers.PIInstanceNotFound, nil
}
return pvm, helpers.PIInstanceNotFound, nil
}
}
func isWaitForPIInstanceAvailable(client *st.IBMPIInstanceClient, id string, timeout time.Duration, powerinstanceid string, instance_ready_status string) (interface{}, error) {
log.Printf("Waiting for PIInstance (%s) to be available and active ", id)
var queryTimeOut time.Duration
if instance_ready_status == "WARNING" {
queryTimeOut = warningTimeOut
} else {
queryTimeOut = activeTimeOut
}
stateConf := &resource.StateChangeConf{
Pending: []string{"PENDING", "BUILD", helpers.PIInstanceHealthWarning},
Target: []string{"OK", "ACTIVE", helpers.PIInstanceHealthOk},
Refresh: isPIInstanceRefreshFunc(client, id, powerinstanceid, instance_ready_status),
Delay: 10 * time.Second,
MinTimeout: queryTimeOut,
Timeout: 120 * time.Minute,
}
return stateConf.WaitForState()
}
func isPIInstanceRefreshFunc(client *st.IBMPIInstanceClient, id, powerinstanceid, instance_ready_status string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
pvm, err := client.Get(id, powerinstanceid, getTimeOut)
if err != nil {
return nil, "", err
}
allowableStatus := instance_ready_status
log.Printf("*** InstanceRefreshFunc - the allowable instance status is [%s]", allowableStatus)
//if pvm.Health.Status == helpers.PIInstanceHealthOk {
if *pvm.Status == helpers.PIInstanceAvailable && (pvm.Health.Status == allowableStatus) {
////if *pvm.Status == helpers.PIInstanceAvailable {
log.Printf("The health status is now %s", allowableStatus)
return pvm, helpers.PIInstanceAvailable, nil
}
return pvm, helpers.PIInstanceBuilding, nil
}
}
func checkBase64(input string) error {
fmt.Println("Calling the checkBase64")
data, err := base64.StdEncoding.DecodeString(input)
if err != nil {
fmt.Println("error:", err)
return err
}
fmt.Printf("Data is correctly Encoded to Base64 %s", data)
return err
}
func isWaitForPIInstanceStopped(client *st.IBMPIInstanceClient, id string, timeout time.Duration, powerinstanceid string) (interface{}, error) {
log.Printf("Waiting for PIInstance (%s) to be stopped and powered off ", id)
stateConf := &resource.StateChangeConf{
Pending: []string{"STOPPING", "RESIZE", "VERIFY_RESIZE", helpers.PIInstanceHealthWarning},
Target: []string{"OK", "SHUTOFF"},
Refresh: isPIInstanceRefreshFuncOff(client, id, powerinstanceid),
Delay: 10 * time.Second,
MinTimeout: 2 * time.Minute, // This is the time that the client will execute to check the status of the request
Timeout: 30 * time.Minute,
}
return stateConf.WaitForState()
}
func isPIInstanceRefreshFuncOff(client *st.IBMPIInstanceClient, id, powerinstanceid string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
log.Printf("Calling the check Refresh status of the pvm [%s] for cloud instance id [%s ]", id, powerinstanceid)
pvm, err := client.Get(id, powerinstanceid, getTimeOut)
if err != nil {
return nil, "", err
}
log.Printf("The lpar status with id [ %s] is now %s", id, *pvm.Status)
//if pvm.Health.Status == helpers.PIInstanceHealthOk {
if *pvm.Status == "SHUTOFF" && pvm.Health.Status == helpers.PIInstanceHealthOk {
log.Printf("The lpar is now off")
return pvm, "SHUTOFF", nil
//}
}
return pvm, "STOPPING", nil
}
}
func stopLparForResourceChange(client *st.IBMPIInstanceClient, id, powerinstanceid string) (interface{}, error) {
//TODO
log.Printf("Callin the stop lpar for Resource Change code ..")
body := &models.PVMInstanceAction{
//Action: ptrToString("stop"),
Action: ptrToString("immediate-shutdown"),
}
resp, err := client.Action(&p_cloud_p_vm_instances.PcloudPvminstancesActionPostParams{Body: body}, id, powerinstanceid, postTimeOut)
if err != nil {
log.Printf("Stop Action failed on [%s]", id)
return nil, err
}
log.Printf("Getting the response from the shutdown ... %v", resp)
_, err = isWaitForPIInstanceStopped(client, id, 30, powerinstanceid)
if err != nil {
return nil, fmt.Errorf("failed to stop the lpar")
}
return nil, err
}
// Start the lpar
func startLparAfterResourceChange(client *st.IBMPIInstanceClient, id, powerinstanceid string) (interface{}, error) {
//TODO
log.Printf("Callin the start lpar for Resource Change code ..")
body := &models.PVMInstanceAction{
//Action: ptrToString("stop"),
Action: ptrToString("start"),
}
resp, err := client.Action(&p_cloud_p_vm_instances.PcloudPvminstancesActionPostParams{Body: body}, id, powerinstanceid, postTimeOut)
if err != nil {
return nil, fmt.Errorf("start Action failed on [%s] %s", id, err)
}
log.Printf("Getting the response from the start ... %v", resp)
_, err = isWaitForPIInstanceAvailable(client, id, 30, powerinstanceid, "OK")
if err != nil {
return nil, fmt.Errorf("failed to stop the lpar")
}
return nil, err
}
// Stop / Modify / Start only when the lpar is off limits
func performChangeAndReboot(client *st.IBMPIInstanceClient, id, powerinstanceid string, mem, procs float64) (interface{}, error) {
/*
These are the steps
1. Stop the lpar - Check if the lpar is SHUTOFF
2. Once the lpar is SHUTOFF - Make the cpu / memory change - DUring this time , you can check for RESIZE and VERIFY_RESIZE as the transition states
3. If the change is successful , the lpar state will be back in SHUTOFF
4. Once the LPAR state is SHUTOFF , initiate the start again and check for ACTIVE + OK
*/
//Execute the stop
log.Printf("Callin the stop lpar for Resource Change code ..")
stopbody := &models.PVMInstanceAction{
//Action: ptrToString("stop"),
Action: ptrToString("immediate-shutdown"),
}
resp, err := client.Action(&p_cloud_p_vm_instances.PcloudPvminstancesActionPostParams{Body: stopbody}, id, powerinstanceid, postTimeOut)
if err != nil {
log.Printf("Stop Action failed on [%s]", id)
return nil, err
}
log.Printf("Getting the response from the shutdown ... %v", resp)
_, err = isWaitForPIInstanceStopped(client, id, 30, powerinstanceid)
if err != nil {
return nil, fmt.Errorf("failed to stop the lpar")
}
log.Printf("Completed the stop successfully. Initiating the resource change ")
body := &models.PVMInstanceUpdate{
Memory: mem,
//ProcType: processortype,
Processors: procs,
//ServerName: name,
}
update_resp, update_err := client.Update(id, powerinstanceid, &p_cloud_p_vm_instances.PcloudPvminstancesPutParams{Body: body}, updateTimeOut)
if update_err != nil {
return nil, fmt.Errorf("failed to update the lpar with the change, %s", update_err)
}
if update_resp.ServerName == "" {
log.Printf("the server name is null...from the update call")
} else {
log.Printf("printing the response from the update %s", update_resp.ServerName)
}
_, err = isWaitforPIInstanceUpdate(client, id, 30, powerinstanceid)
if err != nil {
return nil, fmt.Errorf("failed to get an update from the Service after the resource change, %s", err)
}
// Now we can start the lpar
log.Printf("Calling the start lpar After the Resource Change code ..")
startbody := &models.PVMInstanceAction{
//Action: ptrToString("stop"),
Action: ptrToString("start"),
}
startresp, starterr := client.Action(&p_cloud_p_vm_instances.PcloudPvminstancesActionPostParams{Body: startbody}, id, powerinstanceid, postTimeOut)
if starterr != nil {
log.Printf("Start Action failed on [%s]", id)
return nil, fmt.Errorf("the error from the start is %s", starterr)
}
log.Printf("Getting the response from the start ... %v", startresp)
_, err = isWaitForPIInstanceAvailable(client, id, 30, powerinstanceid, "OK")
if err != nil {
return nil, fmt.Errorf("failed to stop the lpar %s", err)
}
return nil, err
}
func isWaitforPIInstanceUpdate(client *st.IBMPIInstanceClient, id string, timeout time.Duration, powerinstanceid string) (interface{}, error) {
log.Printf("Waiting for PIInstance (%s) to be SHUTOFF AFTER THE RESIZE Due to DLPAR Operation ", id)
stateConf := &resource.StateChangeConf{
Pending: []string{"RESIZE", "VERIFY_RESIZE"},
Target: []string{"ACTIVE", "SHUTOFF", helpers.PIInstanceHealthOk},
Refresh: isPIInstanceShutAfterResourceChange(client, id, powerinstanceid),
Delay: 10 * time.Second,
MinTimeout: 5 * time.Minute,
Timeout: 60 * time.Minute,
}
return stateConf.WaitForState()
}
func isPIInstanceShutAfterResourceChange(client *st.IBMPIInstanceClient, id, powerinstanceid string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
log.Printf("Calling the check lpar status of the pvm [%s] for cloud instance id [%s ] after the resource change", id, powerinstanceid)
pvm, err := client.Get(id, powerinstanceid, getTimeOut)
if err != nil {
return nil, "", err
}
log.Printf("The lpar status with id [%s] is now %s", id, *pvm.Status)
//if pvm.Health.Status == helpers.PIInstanceHealthOk {
if *pvm.Status == "SHUTOFF" && pvm.Health.Status == helpers.PIInstanceHealthOk {
log.Printf("The lpar is now off after the resource change...")