-
Notifications
You must be signed in to change notification settings - Fork 639
/
resource_ibm_lb_service.go
377 lines (308 loc) · 12.1 KB
/
resource_ibm_lb_service.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
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package classicinfrastructure
import (
"fmt"
"log"
"strconv"
"time"
"strings"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"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"
)
func ResourceIBMLbService() *schema.Resource {
return &schema.Resource{
Create: resourceIBMLbServiceCreate,
Read: resourceIBMLbServiceRead,
Update: resourceIBMLbServiceUpdate,
Delete: resourceIBMLbServiceDelete,
Exists: resourceIBMLbServiceExists,
Importer: &schema.ResourceImporter{},
Schema: map[string]*schema.Schema{
"service_group_id": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
Description: "service group ID",
},
"ip_address_id": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
Description: "IP Address ID",
},
"port": {
Type: schema.TypeInt,
Required: true,
Description: "Port number",
},
"enabled": {
Type: schema.TypeBool,
Required: true,
Description: "Boolean value true, if enabled else false",
},
"health_check_type": {
Type: schema.TypeString,
Required: true,
Description: "health check type",
},
"weight": {
Type: schema.TypeInt,
Required: true,
Description: "Weight value",
},
"tags": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Description: "Tags for the resource",
},
},
}
}
func resourceIBMLbServiceCreate(d *schema.ResourceData, meta interface{}) error {
sess := meta.(conns.ClientSession).SoftLayerSession()
// SoftLayer Local LBs consist of a multi-level hierarchy of types.
// (virtualIpAddress -> []virtualServer -> []serviceGroup -> []service)
// Using the service group ID provided in the config, find the IDs of the
// respective virtualServer and virtualIpAddress
sgID := d.Get("service_group_id").(int)
serviceGroup, err := services.GetNetworkApplicationDeliveryControllerLoadBalancerServiceGroupService(sess).
Id(sgID).
Mask("id,routingMethodId,routingTypeId,virtualServer[id,allocation,port,virtualIpAddress[id]]").
GetObject()
if err != nil {
return fmt.Errorf("[ERROR] Error retrieving load balancer service group from SoftLayer, %s", err)
}
// Store the IDs for later use
vsID := *serviceGroup.VirtualServer.Id
vipID := *serviceGroup.VirtualServer.VirtualIpAddress.Id
// Convert the health check type name to an ID
healthCheckTypeId, err := getHealthCheckTypeId(sess, d.Get("health_check_type").(string))
if err != nil {
return err
}
// The API only exposes edit capability at the root of the tree (virtualIpAddress),
// so need to send the full structure from the root down to the node to be added or
// modified
vip := datatypes.Network_Application_Delivery_Controller_LoadBalancer_VirtualIpAddress{
VirtualServers: []datatypes.Network_Application_Delivery_Controller_LoadBalancer_VirtualServer{{
Id: &vsID,
Allocation: serviceGroup.VirtualServer.Allocation,
Port: serviceGroup.VirtualServer.Port,
ServiceGroups: []datatypes.Network_Application_Delivery_Controller_LoadBalancer_Service_Group{{
Id: &sgID,
RoutingMethodId: serviceGroup.RoutingMethodId,
RoutingTypeId: serviceGroup.RoutingTypeId,
Services: []datatypes.Network_Application_Delivery_Controller_LoadBalancer_Service{{
Enabled: sl.Int(1),
Port: sl.Int(d.Get("port").(int)),
IpAddressId: sl.Int(d.Get("ip_address_id").(int)),
HealthChecks: []datatypes.Network_Application_Delivery_Controller_LoadBalancer_Health_Check{{
HealthCheckTypeId: &healthCheckTypeId,
}},
GroupReferences: []datatypes.Network_Application_Delivery_Controller_LoadBalancer_Service_Group_CrossReference{{
Weight: sl.Int(d.Get("weight").(int)),
}},
}},
}},
}},
}
log.Println("[INFO] Creating load balancer service")
err = updateLoadBalancerService(sess.SetRetries(0), vipID, &vip)
if err != nil {
return fmt.Errorf("[ERROR] Error creating load balancer service: %s", err)
}
// Retrieve the newly created object, to obtain its ID
svcs, err := services.GetNetworkApplicationDeliveryControllerLoadBalancerServiceGroupService(sess).
Id(sgID).
Mask("mask[id,port,ipAddressId]").
Filter(filter.New(
filter.Path("services.port").Eq(d.Get("port")),
filter.Path("services.ipAddressId").Eq(d.Get("ip_address_id"))).Build()).
GetServices()
if err != nil || len(svcs) == 0 {
return fmt.Errorf("[ERROR] Error retrieving load balancer: %s", err)
}
d.SetId(strconv.Itoa(*svcs[0].Id))
log.Printf("[INFO] Load Balancer Service ID: %s", d.Id())
return resourceIBMLbServiceRead(d, meta)
}
func resourceIBMLbServiceUpdate(d *schema.ResourceData, meta interface{}) error {
sess := meta.(conns.ClientSession).SoftLayerSession()
// Using the ID stored in the config, find the IDs of the respective
// serviceGroup, virtualServer and virtualIpAddress
svcID, _ := strconv.Atoi(d.Id())
svc, err := services.GetNetworkApplicationDeliveryControllerLoadBalancerServiceService(sess).
Id(svcID).
Mask("id,serviceGroup[id,routingTypeId,routingMethodId,virtualServer[id,allocation,port,virtualIpAddress[id]]]").
GetObject()
if err != nil {
return fmt.Errorf("[ERROR] Error retrieving load balancer service group from SoftLayer, %s", err)
}
// Store the IDs for later use
sgID := *svc.ServiceGroup.Id
vsID := *svc.ServiceGroup.VirtualServer.Id
vipID := *svc.ServiceGroup.VirtualServer.VirtualIpAddress.Id
// Convert the health check type name to an ID
healthCheckTypeId, err := getHealthCheckTypeId(sess, d.Get("health_check_type").(string))
if err != nil {
return err
}
// The API only exposes edit capability at the root of the tree (virtualIpAddress),
// so need to send the full structure from the root down to the node to be added or
// modified
vip := datatypes.Network_Application_Delivery_Controller_LoadBalancer_VirtualIpAddress{
VirtualServers: []datatypes.Network_Application_Delivery_Controller_LoadBalancer_VirtualServer{{
Id: &vsID,
Allocation: svc.ServiceGroup.VirtualServer.Allocation,
Port: svc.ServiceGroup.VirtualServer.Port,
ServiceGroups: []datatypes.Network_Application_Delivery_Controller_LoadBalancer_Service_Group{{
Id: &sgID,
RoutingMethodId: svc.ServiceGroup.RoutingMethodId,
RoutingTypeId: svc.ServiceGroup.RoutingTypeId,
Services: []datatypes.Network_Application_Delivery_Controller_LoadBalancer_Service{{
Id: &svcID,
Enabled: sl.Int(1),
Port: sl.Int(d.Get("port").(int)),
IpAddressId: sl.Int(d.Get("ip_address_id").(int)),
HealthChecks: []datatypes.Network_Application_Delivery_Controller_LoadBalancer_Health_Check{{
HealthCheckTypeId: &healthCheckTypeId,
}},
GroupReferences: []datatypes.Network_Application_Delivery_Controller_LoadBalancer_Service_Group_CrossReference{{
Weight: sl.Int(d.Get("weight").(int)),
}},
}},
}},
}},
}
log.Println("[INFO] Updating load balancer service")
err = updateLoadBalancerService(sess.SetRetries(0), vipID, &vip)
if err != nil {
return fmt.Errorf("[ERROR] Error updating load balancer service: %s", err)
}
return resourceIBMLbServiceRead(d, meta)
}
func resourceIBMLbServiceRead(d *schema.ResourceData, meta interface{}) error {
sess := meta.(conns.ClientSession).SoftLayerSession()
svcID, _ := strconv.Atoi(d.Id())
svc, err := services.GetNetworkApplicationDeliveryControllerLoadBalancerServiceService(sess).
Id(svcID).
Mask("ipAddressId,enabled,port,healthChecks[type[keyname]],groupReferences[weight],serviceGroup[id]").
GetObject()
if err != nil {
return fmt.Errorf("[ERROR] Error retrieving service: %s", err)
}
d.Set("ip_address_id", svc.IpAddressId)
d.Set("port", svc.Port)
d.Set("health_check_type", svc.HealthChecks[0].Type.Keyname)
d.Set("weight", svc.GroupReferences[0].Weight)
d.Set("enabled", (*svc.Enabled == 1))
d.Set("service_group_id", svc.ServiceGroup.Id)
return nil
}
func resourceIBMLbServiceDelete(d *schema.ResourceData, meta interface{}) error {
sess := meta.(conns.ClientSession).SoftLayerSession()
svcID, _ := strconv.Atoi(d.Id())
stateConf := &resource.StateChangeConf{
Pending: []string{"pending"},
Target: []string{"complete"},
Refresh: func() (interface{}, string, error) {
err := services.GetNetworkApplicationDeliveryControllerLoadBalancerServiceService(sess).
Id(svcID).
DeleteObject()
if apiErr, ok := err.(sl.Error); ok {
switch {
case apiErr.Exception == "SoftLayer_Exception_Network_Timeout" ||
strings.Contains(apiErr.Message, "There was a problem saving your configuration to the load balancer.") ||
strings.Contains(apiErr.Message, "The selected group could not be removed from the load balancer.") ||
strings.Contains(apiErr.Message, "The resource '480' is already in use."):
// The LB is busy with another transaction. Retry
return false, "pending", nil
case apiErr.StatusCode == 404 || // 404 - service was deleted on the previous attempt
strings.Contains(apiErr.Message, "Unable to find object with id"): // xmlrpc returns 200 instead of 404
return true, "complete", nil
default:
// Any other error is unexpected. Abort
return false, "", err
}
}
return true, "complete", nil
},
Timeout: 10 * time.Minute,
Delay: 5 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err := stateConf.WaitForState()
if err != nil {
return fmt.Errorf("[ERROR] Error deleting service: %s", err)
}
return nil
}
func resourceIBMLbServiceExists(d *schema.ResourceData, meta interface{}) (bool, error) {
sess := meta.(conns.ClientSession).SoftLayerSession()
svcID, _ := strconv.Atoi(d.Id())
_, err := services.GetNetworkApplicationDeliveryControllerLoadBalancerServiceService(sess).
Id(svcID).
Mask("id").
GetObject()
if err != nil {
if apiErr, ok := err.(sl.Error); ok {
if apiErr.StatusCode == 404 {
return false, nil
}
}
return false, fmt.Errorf("[ERROR] Error getting lb service: %s", err)
}
return true, nil
}
func getHealthCheckTypeId(sess *session.Session, healthCheckTypeName string) (int, error) {
healthCheckTypes, err := services.GetNetworkApplicationDeliveryControllerLoadBalancerHealthCheckTypeService(sess).
Mask("id").
Filter(filter.Build(
filter.Path("keyname").Eq(healthCheckTypeName))).
Limit(1).
GetAllObjects()
if err != nil {
return -1, err
}
if len(healthCheckTypes) < 1 {
return -1, fmt.Errorf("[ERROR] Invalid health check type: %s", healthCheckTypeName)
}
return *healthCheckTypes[0].Id, nil
}
func updateLoadBalancerService(sess *session.Session, vipID int, vip *datatypes.Network_Application_Delivery_Controller_LoadBalancer_VirtualIpAddress) error {
stateConf := &resource.StateChangeConf{
Pending: []string{"pending"},
Target: []string{"complete"},
Refresh: func() (interface{}, string, error) {
_, err := services.GetNetworkApplicationDeliveryControllerLoadBalancerVirtualIpAddressService(sess).
Id(vipID).
EditObject(vip)
if apiErr, ok := err.(sl.Error); ok {
// The LB is busy with another transaction. Retry
if apiErr.Exception == "SoftLayer_Exception_Network_Timeout" ||
strings.Contains(apiErr.Message, "There was a problem saving your configuration to the load balancer.") ||
strings.Contains(apiErr.Message, "The selected group could not be removed from the load balancer.") ||
strings.Contains(apiErr.Message, "The resource '480' is already in use.") {
return false, "pending", nil
}
// Any other error is unexpected. Abort
return false, "", err
}
return true, "complete", nil
},
Timeout: 10 * time.Minute,
Delay: 5 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err := stateConf.WaitForState()
return err
}