File: loadbalancer.go

package info (click to toggle)
golang-github-gophercloud-gophercloud 1.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,416 kB
  • sloc: sh: 99; makefile: 21
file content (678 lines) | stat: -rw-r--r-- 23,974 bytes parent folder | download
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
package v2

import (
	"fmt"
	"strings"
	"testing"

	"github.com/gophercloud/gophercloud"
	"github.com/gophercloud/gophercloud/acceptance/clients"
	"github.com/gophercloud/gophercloud/acceptance/tools"
	"github.com/gophercloud/gophercloud/openstack/loadbalancer/v2/l7policies"
	"github.com/gophercloud/gophercloud/openstack/loadbalancer/v2/listeners"
	"github.com/gophercloud/gophercloud/openstack/loadbalancer/v2/loadbalancers"
	"github.com/gophercloud/gophercloud/openstack/loadbalancer/v2/monitors"
	"github.com/gophercloud/gophercloud/openstack/loadbalancer/v2/pools"
	th "github.com/gophercloud/gophercloud/testhelper"
)

// CreateListener will create a listener for a given load balancer on a random
// port with a random name. An error will be returned if the listener could not
// be created.
func CreateListener(t *testing.T, client *gophercloud.ServiceClient, lb *loadbalancers.LoadBalancer) (*listeners.Listener, error) {
	listenerName := tools.RandomString("TESTACCT-", 8)
	listenerDescription := tools.RandomString("TESTACCT-DESC-", 8)
	listenerPort := tools.RandomInt(1, 100)

	t.Logf("Attempting to create listener %s on port %d", listenerName, listenerPort)

	createOpts := listeners.CreateOpts{
		Name:           listenerName,
		Description:    listenerDescription,
		LoadbalancerID: lb.ID,
		Protocol:       listeners.ProtocolTCP,
		ProtocolPort:   listenerPort,
	}

	listener, err := listeners.Create(client, createOpts).Extract()
	if err != nil {
		return listener, err
	}

	t.Logf("Successfully created listener %s", listenerName)

	if err := WaitForLoadBalancerState(client, lb.ID, "ACTIVE"); err != nil {
		return listener, fmt.Errorf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	th.AssertEquals(t, listener.Name, listenerName)
	th.AssertEquals(t, listener.Description, listenerDescription)
	th.AssertEquals(t, listener.Loadbalancers[0].ID, lb.ID)
	th.AssertEquals(t, listener.Protocol, string(listeners.ProtocolTCP))
	th.AssertEquals(t, listener.ProtocolPort, listenerPort)

	return listener, nil
}

// CreateListenerHTTP will create an HTTP-based listener for a given load
// balancer on a random port with a random name. An error will be returned
// if the listener could not be created.
func CreateListenerHTTP(t *testing.T, client *gophercloud.ServiceClient, lb *loadbalancers.LoadBalancer) (*listeners.Listener, error) {
	tlsVersions := []listeners.TLSVersion{}
	tlsVersionsExp := []string(nil)
	listenerName := tools.RandomString("TESTACCT-", 8)
	listenerDescription := tools.RandomString("TESTACCT-DESC-", 8)
	listenerPort := tools.RandomInt(1, 100)

	t.Logf("Attempting to create listener %s on port %d", listenerName, listenerPort)

	headers := map[string]string{
		"X-Forwarded-For": "true",
	}

	// tls_version is only supported in microversion v2.17 introduced in victoria
	if clients.IsReleasesAbove(t, "stable/ussuri") {
		tlsVersions = []listeners.TLSVersion{"TLSv1.2", "TLSv1.3"}
		tlsVersionsExp = []string{"TLSv1.2", "TLSv1.3"}
	}

	createOpts := listeners.CreateOpts{
		Name:           listenerName,
		Description:    listenerDescription,
		LoadbalancerID: lb.ID,
		InsertHeaders:  headers,
		Protocol:       listeners.ProtocolHTTP,
		ProtocolPort:   listenerPort,
		TLSVersions:    tlsVersions,
	}

	listener, err := listeners.Create(client, createOpts).Extract()
	if err != nil {
		return listener, err
	}

	t.Logf("Successfully created listener %s", listenerName)

	if err := WaitForLoadBalancerState(client, lb.ID, "ACTIVE"); err != nil {
		return listener, fmt.Errorf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	th.AssertEquals(t, listener.Name, listenerName)
	th.AssertEquals(t, listener.Description, listenerDescription)
	th.AssertEquals(t, listener.Loadbalancers[0].ID, lb.ID)
	th.AssertEquals(t, listener.Protocol, string(listeners.ProtocolHTTP))
	th.AssertEquals(t, listener.ProtocolPort, listenerPort)
	th.AssertDeepEquals(t, listener.InsertHeaders, headers)
	th.AssertDeepEquals(t, listener.TLSVersions, tlsVersionsExp)

	return listener, nil
}

// CreateLoadBalancer will create a load balancer with a random name on a given
// subnet. An error will be returned if the loadbalancer could not be created.
func CreateLoadBalancer(t *testing.T, client *gophercloud.ServiceClient, subnetID string, tags []string, policyID string) (*loadbalancers.LoadBalancer, error) {
	lbName := tools.RandomString("TESTACCT-", 8)
	lbDescription := tools.RandomString("TESTACCT-DESC-", 8)

	t.Logf("Attempting to create loadbalancer %s on subnet %s", lbName, subnetID)

	createOpts := loadbalancers.CreateOpts{
		Name:         lbName,
		Description:  lbDescription,
		VipSubnetID:  subnetID,
		AdminStateUp: gophercloud.Enabled,
	}
	if len(tags) > 0 {
		createOpts.Tags = tags
	}

	if len(policyID) > 0 {
		createOpts.VipQosPolicyID = policyID
	}

	lb, err := loadbalancers.Create(client, createOpts).Extract()
	if err != nil {
		return lb, err
	}

	t.Logf("Successfully created loadbalancer %s on subnet %s", lbName, subnetID)
	t.Logf("Waiting for loadbalancer %s to become active", lbName)

	if err := WaitForLoadBalancerState(client, lb.ID, "ACTIVE"); err != nil {
		return lb, err
	}

	t.Logf("LoadBalancer %s is active", lbName)

	th.AssertEquals(t, lb.Name, lbName)
	th.AssertEquals(t, lb.Description, lbDescription)
	th.AssertEquals(t, lb.VipSubnetID, subnetID)
	th.AssertEquals(t, lb.AdminStateUp, true)

	if len(tags) > 0 {
		th.AssertDeepEquals(t, lb.Tags, tags)
	}

	if len(policyID) > 0 {
		th.AssertEquals(t, lb.VipQosPolicyID, policyID)
	}

	return lb, nil
}

// CreateLoadBalancerFullyPopulated will create a  fully populated load balancer with a random name on a given
// subnet. It will contain a listener, l7policy, l7rule, pool, member and health monitor.
// An error will be returned if the loadbalancer could not be created.
func CreateLoadBalancerFullyPopulated(t *testing.T, client *gophercloud.ServiceClient, subnetID string, tags []string) (*loadbalancers.LoadBalancer, error) {
	lbName := tools.RandomString("TESTACCT-", 8)
	lbDescription := tools.RandomString("TESTACCT-DESC-", 8)
	listenerName := tools.RandomString("TESTACCT-", 8)
	listenerDescription := tools.RandomString("TESTACCT-DESC-", 8)
	listenerPort := tools.RandomInt(1, 100)
	policyName := tools.RandomString("TESTACCT-", 8)
	policyDescription := tools.RandomString("TESTACCT-DESC-", 8)
	poolName := tools.RandomString("TESTACCT-", 8)
	poolDescription := tools.RandomString("TESTACCT-DESC-", 8)
	memberName := tools.RandomString("TESTACCT-", 8)
	memberPort := tools.RandomInt(100, 1000)
	memberWeight := tools.RandomInt(1, 10)

	t.Logf("Attempting to create fully populated loadbalancer %s on subnet %s which contains listener: %s, l7Policy: %s, pool %s, member %s",
		lbName, subnetID, listenerName, policyName, poolName, memberName)

	createOpts := loadbalancers.CreateOpts{
		Name:         lbName,
		Description:  lbDescription,
		VipSubnetID:  subnetID,
		AdminStateUp: gophercloud.Enabled,
		Listeners: []listeners.CreateOpts{{
			Name:         listenerName,
			Description:  listenerDescription,
			Protocol:     listeners.ProtocolHTTP,
			ProtocolPort: listenerPort,
			DefaultPool: &pools.CreateOpts{
				Name:        poolName,
				Description: poolDescription,
				Protocol:    pools.ProtocolHTTP,
				LBMethod:    pools.LBMethodLeastConnections,
				Members: []pools.BatchUpdateMemberOpts{{
					Name:         &memberName,
					ProtocolPort: memberPort,
					Weight:       &memberWeight,
					Address:      "1.2.3.4",
					SubnetID:     &subnetID,
				}},
				Monitor: &monitors.CreateOpts{
					Delay:          10,
					Timeout:        5,
					MaxRetries:     5,
					MaxRetriesDown: 4,
					Type:           monitors.TypeHTTP,
				},
			},
			L7Policies: []l7policies.CreateOpts{{
				Name:        policyName,
				Description: policyDescription,
				Action:      l7policies.ActionRedirectToURL,
				RedirectURL: "http://www.example.com",
				Rules: []l7policies.CreateRuleOpts{{
					RuleType:    l7policies.TypePath,
					CompareType: l7policies.CompareTypeStartWith,
					Value:       "/api",
				}},
			}},
		}},
	}
	if len(tags) > 0 {
		createOpts.Tags = tags
	}

	lb, err := loadbalancers.Create(client, createOpts).Extract()
	if err != nil {
		return lb, err
	}

	t.Logf("Successfully created loadbalancer %s on subnet %s", lbName, subnetID)
	t.Logf("Waiting for loadbalancer %s to become active", lbName)

	if err := WaitForLoadBalancerState(client, lb.ID, "ACTIVE"); err != nil {
		return lb, err
	}

	t.Logf("LoadBalancer %s is active", lbName)

	th.AssertEquals(t, lb.Name, lbName)
	th.AssertEquals(t, lb.Description, lbDescription)
	th.AssertEquals(t, lb.VipSubnetID, subnetID)
	th.AssertEquals(t, lb.AdminStateUp, true)

	th.AssertEquals(t, len(lb.Listeners), 1)
	th.AssertEquals(t, lb.Listeners[0].Name, listenerName)
	th.AssertEquals(t, lb.Listeners[0].Description, listenerDescription)
	th.AssertEquals(t, lb.Listeners[0].ProtocolPort, listenerPort)

	th.AssertEquals(t, len(lb.Listeners[0].L7Policies), 1)
	th.AssertEquals(t, lb.Listeners[0].L7Policies[0].Name, policyName)
	th.AssertEquals(t, lb.Listeners[0].L7Policies[0].Description, policyDescription)
	th.AssertEquals(t, lb.Listeners[0].L7Policies[0].Description, policyDescription)
	th.AssertEquals(t, len(lb.Listeners[0].L7Policies[0].Rules), 1)

	th.AssertEquals(t, len(lb.Pools), 1)
	th.AssertEquals(t, lb.Pools[0].Name, poolName)
	th.AssertEquals(t, lb.Pools[0].Description, poolDescription)

	th.AssertEquals(t, len(lb.Pools[0].Members), 1)
	th.AssertEquals(t, lb.Pools[0].Members[0].Name, memberName)
	th.AssertEquals(t, lb.Pools[0].Members[0].ProtocolPort, memberPort)
	th.AssertEquals(t, lb.Pools[0].Members[0].Weight, memberWeight)

	if len(tags) > 0 {
		th.AssertDeepEquals(t, lb.Tags, tags)
	}

	return lb, nil
}

// CreateMember will create a member with a random name, port, address, and
// weight. An error will be returned if the member could not be created.
func CreateMember(t *testing.T, client *gophercloud.ServiceClient, lb *loadbalancers.LoadBalancer, pool *pools.Pool, subnetID, subnetCIDR string) (*pools.Member, error) {
	memberName := tools.RandomString("TESTACCT-", 8)
	memberPort := tools.RandomInt(100, 1000)
	memberWeight := tools.RandomInt(1, 10)

	cidrParts := strings.Split(subnetCIDR, "/")
	subnetParts := strings.Split(cidrParts[0], ".")
	memberAddress := fmt.Sprintf("%s.%s.%s.%d", subnetParts[0], subnetParts[1], subnetParts[2], tools.RandomInt(10, 100))

	t.Logf("Attempting to create member %s", memberName)

	createOpts := pools.CreateMemberOpts{
		Name:         memberName,
		ProtocolPort: memberPort,
		Weight:       &memberWeight,
		Address:      memberAddress,
		SubnetID:     subnetID,
	}

	t.Logf("Member create opts: %#v", createOpts)

	member, err := pools.CreateMember(client, pool.ID, createOpts).Extract()
	if err != nil {
		return member, err
	}

	t.Logf("Successfully created member %s", memberName)

	if err := WaitForLoadBalancerState(client, lb.ID, "ACTIVE"); err != nil {
		return member, fmt.Errorf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	th.AssertEquals(t, member.Name, memberName)

	return member, nil
}

// CreateMonitor will create a monitor with a random name for a specific pool.
// An error will be returned if the monitor could not be created.
func CreateMonitor(t *testing.T, client *gophercloud.ServiceClient, lb *loadbalancers.LoadBalancer, pool *pools.Pool) (*monitors.Monitor, error) {
	monitorName := tools.RandomString("TESTACCT-", 8)

	t.Logf("Attempting to create monitor %s", monitorName)

	createOpts := monitors.CreateOpts{
		PoolID:         pool.ID,
		Name:           monitorName,
		Delay:          10,
		Timeout:        5,
		MaxRetries:     5,
		MaxRetriesDown: 4,
		Type:           monitors.TypePING,
	}

	monitor, err := monitors.Create(client, createOpts).Extract()
	if err != nil {
		return monitor, err
	}

	t.Logf("Successfully created monitor: %s", monitorName)

	if err := WaitForLoadBalancerState(client, lb.ID, "ACTIVE"); err != nil {
		return monitor, fmt.Errorf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	th.AssertEquals(t, monitor.Name, monitorName)
	th.AssertEquals(t, monitor.Type, monitors.TypePING)
	th.AssertEquals(t, monitor.Delay, 10)
	th.AssertEquals(t, monitor.Timeout, 5)
	th.AssertEquals(t, monitor.MaxRetries, 5)
	th.AssertEquals(t, monitor.MaxRetriesDown, 4)

	return monitor, nil
}

// CreatePool will create a pool with a random name with a specified listener
// and loadbalancer. An error will be returned if the pool could not be
// created.
func CreatePool(t *testing.T, client *gophercloud.ServiceClient, lb *loadbalancers.LoadBalancer) (*pools.Pool, error) {
	poolName := tools.RandomString("TESTACCT-", 8)
	poolDescription := tools.RandomString("TESTACCT-DESC-", 8)

	t.Logf("Attempting to create pool %s", poolName)

	createOpts := pools.CreateOpts{
		Name:           poolName,
		Description:    poolDescription,
		Protocol:       pools.ProtocolTCP,
		LoadbalancerID: lb.ID,
		LBMethod:       pools.LBMethodLeastConnections,
	}

	pool, err := pools.Create(client, createOpts).Extract()
	if err != nil {
		return pool, err
	}

	t.Logf("Successfully created pool %s", poolName)

	if err := WaitForLoadBalancerState(client, lb.ID, "ACTIVE"); err != nil {
		return pool, fmt.Errorf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	th.AssertEquals(t, pool.Name, poolName)
	th.AssertEquals(t, pool.Description, poolDescription)
	th.AssertEquals(t, pool.Protocol, string(pools.ProtocolTCP))
	th.AssertEquals(t, pool.Loadbalancers[0].ID, lb.ID)
	th.AssertEquals(t, pool.LBMethod, string(pools.LBMethodLeastConnections))

	return pool, nil
}

// CreatePoolHTTP will create an HTTP-based pool with a random name with a
// specified listener and loadbalancer. An error will be returned if the pool
// could not be created.
func CreatePoolHTTP(t *testing.T, client *gophercloud.ServiceClient, lb *loadbalancers.LoadBalancer) (*pools.Pool, error) {
	poolName := tools.RandomString("TESTACCT-", 8)
	poolDescription := tools.RandomString("TESTACCT-DESC-", 8)

	t.Logf("Attempting to create pool %s", poolName)

	createOpts := pools.CreateOpts{
		Name:           poolName,
		Description:    poolDescription,
		Protocol:       pools.ProtocolHTTP,
		LoadbalancerID: lb.ID,
		LBMethod:       pools.LBMethodLeastConnections,
	}

	pool, err := pools.Create(client, createOpts).Extract()
	if err != nil {
		return pool, err
	}

	t.Logf("Successfully created pool %s", poolName)

	if err := WaitForLoadBalancerState(client, lb.ID, "ACTIVE"); err != nil {
		return pool, fmt.Errorf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	th.AssertEquals(t, pool.Name, poolName)
	th.AssertEquals(t, pool.Description, poolDescription)
	th.AssertEquals(t, pool.Protocol, string(pools.ProtocolHTTP))
	th.AssertEquals(t, pool.Loadbalancers[0].ID, lb.ID)
	th.AssertEquals(t, pool.LBMethod, string(pools.LBMethodLeastConnections))

	return pool, nil
}

// CreateL7Policy will create a l7 policy with a random name with a specified listener
// and loadbalancer. An error will be returned if the l7 policy could not be
// created.
func CreateL7Policy(t *testing.T, client *gophercloud.ServiceClient, listener *listeners.Listener, lb *loadbalancers.LoadBalancer) (*l7policies.L7Policy, error) {
	policyName := tools.RandomString("TESTACCT-", 8)
	policyDescription := tools.RandomString("TESTACCT-DESC-", 8)

	t.Logf("Attempting to create l7 policy %s", policyName)

	createOpts := l7policies.CreateOpts{
		Name:        policyName,
		Description: policyDescription,
		ListenerID:  listener.ID,
		Action:      l7policies.ActionRedirectToURL,
		RedirectURL: "http://www.example.com",
	}

	policy, err := l7policies.Create(client, createOpts).Extract()
	if err != nil {
		return policy, err
	}

	t.Logf("Successfully created l7 policy %s", policyName)

	if err := WaitForLoadBalancerState(client, lb.ID, "ACTIVE"); err != nil {
		return policy, fmt.Errorf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	th.AssertEquals(t, policy.Name, policyName)
	th.AssertEquals(t, policy.Description, policyDescription)
	th.AssertEquals(t, policy.ListenerID, listener.ID)
	th.AssertEquals(t, policy.Action, string(l7policies.ActionRedirectToURL))
	th.AssertEquals(t, policy.RedirectURL, "http://www.example.com")

	return policy, nil
}

// CreateL7Rule creates a l7 rule for specified l7 policy.
func CreateL7Rule(t *testing.T, client *gophercloud.ServiceClient, policyID string, lb *loadbalancers.LoadBalancer) (*l7policies.Rule, error) {
	t.Logf("Attempting to create l7 rule for policy %s", policyID)

	createOpts := l7policies.CreateRuleOpts{
		RuleType:    l7policies.TypePath,
		CompareType: l7policies.CompareTypeStartWith,
		Value:       "/api",
	}

	rule, err := l7policies.CreateRule(client, policyID, createOpts).Extract()
	if err != nil {
		return rule, err
	}

	t.Logf("Successfully created l7 rule for policy %s", policyID)

	if err := WaitForLoadBalancerState(client, lb.ID, "ACTIVE"); err != nil {
		return rule, fmt.Errorf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	th.AssertEquals(t, rule.RuleType, string(l7policies.TypePath))
	th.AssertEquals(t, rule.CompareType, string(l7policies.CompareTypeStartWith))
	th.AssertEquals(t, rule.Value, "/api")

	return rule, nil
}

// DeleteL7Policy will delete a specified l7 policy. A fatal error will occur if
// the l7 policy could not be deleted. This works best when used as a deferred
// function.
func DeleteL7Policy(t *testing.T, client *gophercloud.ServiceClient, lbID, policyID string) {
	t.Logf("Attempting to delete l7 policy %s", policyID)

	if err := l7policies.Delete(client, policyID).ExtractErr(); err != nil {
		if _, ok := err.(gophercloud.ErrDefault404); !ok {
			t.Fatalf("Unable to delete l7 policy: %v", err)
		}
	}

	if err := WaitForLoadBalancerState(client, lbID, "ACTIVE"); err != nil {
		t.Fatalf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	t.Logf("Successfully deleted l7 policy %s", policyID)
}

// DeleteL7Rule will delete a specified l7 rule. A fatal error will occur if
// the l7 rule could not be deleted. This works best when used as a deferred
// function.
func DeleteL7Rule(t *testing.T, client *gophercloud.ServiceClient, lbID, policyID, ruleID string) {
	t.Logf("Attempting to delete l7 rule %s", ruleID)

	if err := l7policies.DeleteRule(client, policyID, ruleID).ExtractErr(); err != nil {
		if _, ok := err.(gophercloud.ErrDefault404); !ok {
			t.Fatalf("Unable to delete l7 rule: %v", err)
		}
	}

	if err := WaitForLoadBalancerState(client, lbID, "ACTIVE"); err != nil {
		t.Fatalf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	t.Logf("Successfully deleted l7 rule %s", ruleID)
}

// DeleteListener will delete a specified listener. A fatal error will occur if
// the listener could not be deleted. This works best when used as a deferred
// function.
func DeleteListener(t *testing.T, client *gophercloud.ServiceClient, lbID, listenerID string) {
	t.Logf("Attempting to delete listener %s", listenerID)

	if err := listeners.Delete(client, listenerID).ExtractErr(); err != nil {
		if _, ok := err.(gophercloud.ErrDefault404); !ok {
			t.Fatalf("Unable to delete listener: %v", err)
		}
	}

	if err := WaitForLoadBalancerState(client, lbID, "ACTIVE"); err != nil {
		t.Fatalf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	t.Logf("Successfully deleted listener %s", listenerID)
}

// DeleteMember will delete a specified member. A fatal error will occur if the
// member could not be deleted. This works best when used as a deferred
// function.
func DeleteMember(t *testing.T, client *gophercloud.ServiceClient, lbID, poolID, memberID string) {
	t.Logf("Attempting to delete member %s", memberID)

	if err := pools.DeleteMember(client, poolID, memberID).ExtractErr(); err != nil {
		if _, ok := err.(gophercloud.ErrDefault404); !ok {
			t.Fatalf("Unable to delete member: %s", memberID)
		}
	}

	if err := WaitForLoadBalancerState(client, lbID, "ACTIVE"); err != nil {
		t.Fatalf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	t.Logf("Successfully deleted member %s", memberID)
}

// DeleteLoadBalancer will delete a specified loadbalancer. A fatal error will
// occur if the loadbalancer could not be deleted. This works best when used
// as a deferred function.
func DeleteLoadBalancer(t *testing.T, client *gophercloud.ServiceClient, lbID string) {
	t.Logf("Attempting to delete loadbalancer %s", lbID)

	deleteOpts := loadbalancers.DeleteOpts{
		Cascade: false,
	}

	if err := loadbalancers.Delete(client, lbID, deleteOpts).ExtractErr(); err != nil {
		if _, ok := err.(gophercloud.ErrDefault404); !ok {
			t.Fatalf("Unable to delete loadbalancer: %v", err)
		}
	}

	t.Logf("Waiting for loadbalancer %s to delete", lbID)

	if err := WaitForLoadBalancerState(client, lbID, "DELETED"); err != nil {
		t.Fatalf("Loadbalancer did not delete in time: %s", err)
	}

	t.Logf("Successfully deleted loadbalancer %s", lbID)
}

// CascadeDeleteLoadBalancer will perform a cascading delete on a loadbalancer.
// A fatal error will occur if the loadbalancer could not be deleted. This works
// best when used as a deferred function.
func CascadeDeleteLoadBalancer(t *testing.T, client *gophercloud.ServiceClient, lbID string) {
	t.Logf("Attempting to cascade delete loadbalancer %s", lbID)

	deleteOpts := loadbalancers.DeleteOpts{
		Cascade: true,
	}

	if err := loadbalancers.Delete(client, lbID, deleteOpts).ExtractErr(); err != nil {
		t.Fatalf("Unable to cascade delete loadbalancer: %v", err)
	}

	t.Logf("Waiting for loadbalancer %s to cascade delete", lbID)

	if err := WaitForLoadBalancerState(client, lbID, "DELETED"); err != nil {
		t.Fatalf("Loadbalancer did not delete in time.")
	}

	t.Logf("Successfully deleted loadbalancer %s", lbID)
}

// DeleteMonitor will delete a specified monitor. A fatal error will occur if
// the monitor could not be deleted. This works best when used as a deferred
// function.
func DeleteMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID, monitorID string) {
	t.Logf("Attempting to delete monitor %s", monitorID)

	if err := monitors.Delete(client, monitorID).ExtractErr(); err != nil {
		if _, ok := err.(gophercloud.ErrDefault404); !ok {
			t.Fatalf("Unable to delete monitor: %v", err)
		}
	}

	if err := WaitForLoadBalancerState(client, lbID, "ACTIVE"); err != nil {
		t.Fatalf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	t.Logf("Successfully deleted monitor %s", monitorID)
}

// DeletePool will delete a specified pool. A fatal error will occur if the
// pool could not be deleted. This works best when used as a deferred function.
func DeletePool(t *testing.T, client *gophercloud.ServiceClient, lbID, poolID string) {
	t.Logf("Attempting to delete pool %s", poolID)

	if err := pools.Delete(client, poolID).ExtractErr(); err != nil {
		if _, ok := err.(gophercloud.ErrDefault404); !ok {
			t.Fatalf("Unable to delete pool: %v", err)
		}
	}

	if err := WaitForLoadBalancerState(client, lbID, "ACTIVE"); err != nil {
		t.Fatalf("Timed out waiting for loadbalancer to become active: %s", err)
	}

	t.Logf("Successfully deleted pool %s", poolID)
}

// WaitForLoadBalancerState will wait until a loadbalancer reaches a given state.
func WaitForLoadBalancerState(client *gophercloud.ServiceClient, lbID, status string) error {
	return tools.WaitFor(func() (bool, error) {
		current, err := loadbalancers.Get(client, lbID).Extract()
		if err != nil {
			if httpStatus, ok := err.(gophercloud.ErrDefault404); ok {
				if httpStatus.Actual == 404 {
					if status == "DELETED" {
						return true, nil
					}
				}
			}
			return false, err
		}

		if current.ProvisioningStatus == status {
			return true, nil
		}

		if current.ProvisioningStatus == "ERROR" {
			return false, fmt.Errorf("Load balancer is in ERROR state")
		}

		return false, nil
	})
}