forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_cloudstack_network_acl_rule.go
666 lines (539 loc) · 16.4 KB
/
resource_cloudstack_network_acl_rule.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
package cloudstack
import (
"fmt"
"log"
"strconv"
"strings"
"sync"
"time"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform/helper/schema"
"github.com/xanzy/go-cloudstack/cloudstack"
)
func resourceCloudStackNetworkACLRule() *schema.Resource {
return &schema.Resource{
Create: resourceCloudStackNetworkACLRuleCreate,
Read: resourceCloudStackNetworkACLRuleRead,
Update: resourceCloudStackNetworkACLRuleUpdate,
Delete: resourceCloudStackNetworkACLRuleDelete,
Schema: map[string]*schema.Schema{
"acl_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"managed": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"rule": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"action": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "allow",
},
"cidr_list": &schema.Schema{
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"protocol": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"icmp_type": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"icmp_code": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"ports": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"traffic_type": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "ingress",
},
"uuids": &schema.Schema{
Type: schema.TypeMap,
Computed: true,
},
},
},
},
"project": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"parallelism": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 2,
},
},
}
}
func resourceCloudStackNetworkACLRuleCreate(d *schema.ResourceData, meta interface{}) error {
// Make sure all required parameters are there
if err := verifyNetworkACLParams(d); err != nil {
return err
}
// We need to set this upfront in order to be able to save a partial state
d.SetId(d.Get("acl_id").(string))
// Create all rules that are configured
if nrs := d.Get("rule").(*schema.Set); nrs.Len() > 0 {
// Create an empty rule set to hold all newly created rules
rules := resourceCloudStackNetworkACLRule().Schema["rule"].ZeroValue().(*schema.Set)
err := createNetworkACLRules(d, meta, rules, nrs)
// We need to update this first to preserve the correct state
d.Set("rule", rules)
if err != nil {
return err
}
}
return resourceCloudStackNetworkACLRuleRead(d, meta)
}
func createNetworkACLRules(d *schema.ResourceData, meta interface{}, rules *schema.Set, nrs *schema.Set) error {
var errs *multierror.Error
var wg sync.WaitGroup
wg.Add(nrs.Len())
sem := make(chan struct{}, d.Get("parallelism").(int))
for _, rule := range nrs.List() {
// Put in a tiny sleep here to avoid DoS'ing the API
time.Sleep(500 * time.Millisecond)
go func(rule map[string]interface{}) {
defer wg.Done()
sem <- struct{}{}
// Create a single rule
err := createNetworkACLRule(d, meta, rule)
// If we have at least one UUID, we need to save the rule
if len(rule["uuids"].(map[string]interface{})) > 0 {
rules.Add(rule)
}
if err != nil {
errs = multierror.Append(errs, err)
}
<-sem
}(rule.(map[string]interface{}))
}
wg.Wait()
return errs.ErrorOrNil()
}
func createNetworkACLRule(d *schema.ResourceData, meta interface{}, rule map[string]interface{}) error {
cs := meta.(*cloudstack.CloudStackClient)
uuids := rule["uuids"].(map[string]interface{})
// Make sure all required parameters are there
if err := verifyNetworkACLRuleParams(d, rule); err != nil {
return err
}
// Create a new parameter struct
p := cs.NetworkACL.NewCreateNetworkACLParams(rule["protocol"].(string))
// Set the acl ID
p.SetAclid(d.Id())
// Set the action
p.SetAction(rule["action"].(string))
// Set the CIDR list
var cidrList []string
for _, cidr := range rule["cidr_list"].(*schema.Set).List() {
cidrList = append(cidrList, cidr.(string))
}
p.SetCidrlist(cidrList)
// Set the traffic type
p.SetTraffictype(rule["traffic_type"].(string))
// If the protocol is ICMP set the needed ICMP parameters
if rule["protocol"].(string) == "icmp" {
p.SetIcmptype(rule["icmp_type"].(int))
p.SetIcmpcode(rule["icmp_code"].(int))
r, err := Retry(4, retryableACLCreationFunc(cs, p))
if err != nil {
return err
}
uuids["icmp"] = r.(*cloudstack.CreateNetworkACLResponse).Id
rule["uuids"] = uuids
}
// If the protocol is ALL set the needed parameters
if rule["protocol"].(string) == "all" {
r, err := Retry(4, retryableACLCreationFunc(cs, p))
if err != nil {
return err
}
uuids["all"] = r.(*cloudstack.CreateNetworkACLResponse).Id
rule["uuids"] = uuids
}
// If protocol is TCP or UDP, loop through all ports
if rule["protocol"].(string) == "tcp" || rule["protocol"].(string) == "udp" {
if ps := rule["ports"].(*schema.Set); ps.Len() > 0 {
// Create an empty schema.Set to hold all processed ports
ports := &schema.Set{F: schema.HashString}
for _, port := range ps.List() {
if _, ok := uuids[port.(string)]; ok {
ports.Add(port)
rule["ports"] = ports
continue
}
m := splitPorts.FindStringSubmatch(port.(string))
startPort, err := strconv.Atoi(m[1])
if err != nil {
return err
}
endPort := startPort
if m[2] != "" {
endPort, err = strconv.Atoi(m[2])
if err != nil {
return err
}
}
p.SetStartport(startPort)
p.SetEndport(endPort)
r, err := Retry(4, retryableACLCreationFunc(cs, p))
if err != nil {
return err
}
ports.Add(port)
rule["ports"] = ports
uuids[port.(string)] = r.(*cloudstack.CreateNetworkACLResponse).Id
rule["uuids"] = uuids
}
}
}
return nil
}
func resourceCloudStackNetworkACLRuleRead(d *schema.ResourceData, meta interface{}) error {
cs := meta.(*cloudstack.CloudStackClient)
// First check if the ACL itself still exists
_, count, err := cs.NetworkACL.GetNetworkACLListByID(
d.Id(),
cloudstack.WithProject(d.Get("project").(string)),
)
if err != nil {
if count == 0 {
log.Printf(
"[DEBUG] Network ACL list %s does no longer exist", d.Id())
d.SetId("")
return nil
}
return err
}
// Get all the rules from the running environment
p := cs.NetworkACL.NewListNetworkACLsParams()
p.SetAclid(d.Id())
p.SetListall(true)
l, err := cs.NetworkACL.ListNetworkACLs(p)
if err != nil {
return err
}
// Make a map of all the rules so we can easily find a rule
ruleMap := make(map[string]*cloudstack.NetworkACL, l.Count)
for _, r := range l.NetworkACLs {
ruleMap[r.Id] = r
}
// Create an empty schema.Set to hold all rules
rules := resourceCloudStackNetworkACLRule().Schema["rule"].ZeroValue().(*schema.Set)
// Read all rules that are configured
if rs := d.Get("rule").(*schema.Set); rs.Len() > 0 {
for _, rule := range rs.List() {
rule := rule.(map[string]interface{})
uuids := rule["uuids"].(map[string]interface{})
if rule["protocol"].(string) == "icmp" {
id, ok := uuids["icmp"]
if !ok {
continue
}
// Get the rule
r, ok := ruleMap[id.(string)]
if !ok {
delete(uuids, "icmp")
continue
}
// Delete the known rule so only unknown rules remain in the ruleMap
delete(ruleMap, id.(string))
// Create a set with all CIDR's
cidrs := &schema.Set{F: schema.HashString}
for _, cidr := range strings.Split(r.Cidrlist, ",") {
cidrs.Add(cidr)
}
// Update the values
rule["action"] = strings.ToLower(r.Action)
rule["protocol"] = r.Protocol
rule["icmp_type"] = r.Icmptype
rule["icmp_code"] = r.Icmpcode
rule["traffic_type"] = strings.ToLower(r.Traffictype)
rule["cidr_list"] = cidrs
rules.Add(rule)
}
if rule["protocol"].(string) == "all" {
id, ok := uuids["all"]
if !ok {
continue
}
// Get the rule
r, ok := ruleMap[id.(string)]
if !ok {
delete(uuids, "all")
continue
}
// Delete the known rule so only unknown rules remain in the ruleMap
delete(ruleMap, id.(string))
// Create a set with all CIDR's
cidrs := &schema.Set{F: schema.HashString}
for _, cidr := range strings.Split(r.Cidrlist, ",") {
cidrs.Add(cidr)
}
// Update the values
rule["action"] = strings.ToLower(r.Action)
rule["protocol"] = r.Protocol
rule["traffic_type"] = strings.ToLower(r.Traffictype)
rule["cidr_list"] = cidrs
rules.Add(rule)
}
// If protocol is tcp or udp, loop through all ports
if rule["protocol"].(string) == "tcp" || rule["protocol"].(string) == "udp" {
if ps := rule["ports"].(*schema.Set); ps.Len() > 0 {
// Create an empty schema.Set to hold all ports
ports := &schema.Set{F: schema.HashString}
// Loop through all ports and retrieve their info
for _, port := range ps.List() {
id, ok := uuids[port.(string)]
if !ok {
continue
}
// Get the rule
r, ok := ruleMap[id.(string)]
if !ok {
delete(uuids, port.(string))
continue
}
// Delete the known rule so only unknown rules remain in the ruleMap
delete(ruleMap, id.(string))
// Create a set with all CIDR's
cidrs := &schema.Set{F: schema.HashString}
for _, cidr := range strings.Split(r.Cidrlist, ",") {
cidrs.Add(cidr)
}
// Update the values
rule["action"] = strings.ToLower(r.Action)
rule["protocol"] = r.Protocol
rule["traffic_type"] = strings.ToLower(r.Traffictype)
rule["cidr_list"] = cidrs
ports.Add(port)
}
// If there is at least one port found, add this rule to the rules set
if ports.Len() > 0 {
rule["ports"] = ports
rules.Add(rule)
}
}
}
}
}
// If this is a managed firewall, add all unknown rules into dummy rules
managed := d.Get("managed").(bool)
if managed && len(ruleMap) > 0 {
for uuid := range ruleMap {
// We need to create and add a dummy value to a schema.Set as the
// cidr_list is a required field and thus needs a value
cidrs := &schema.Set{F: schema.HashString}
cidrs.Add(uuid)
// Make a dummy rule to hold the unknown UUID
rule := map[string]interface{}{
"cidr_list": cidrs,
"protocol": uuid,
"uuids": map[string]interface{}{uuid: uuid},
}
// Add the dummy rule to the rules set
rules.Add(rule)
}
}
if rules.Len() > 0 {
d.Set("rule", rules)
} else if !managed {
d.SetId("")
}
return nil
}
func resourceCloudStackNetworkACLRuleUpdate(d *schema.ResourceData, meta interface{}) error {
// Make sure all required parameters are there
if err := verifyNetworkACLParams(d); err != nil {
return err
}
// Check if the rule set as a whole has changed
if d.HasChange("rule") {
o, n := d.GetChange("rule")
ors := o.(*schema.Set).Difference(n.(*schema.Set))
nrs := n.(*schema.Set).Difference(o.(*schema.Set))
// We need to start with a rule set containing all the rules we
// already have and want to keep. Any rules that are not deleted
// correctly and any newly created rules, will be added to this
// set to make sure we end up in a consistent state
rules := o.(*schema.Set).Intersection(n.(*schema.Set))
// First loop through all the new rules and create (before destroy) them
if nrs.Len() > 0 {
err := createNetworkACLRules(d, meta, rules, nrs)
// We need to update this first to preserve the correct state
d.Set("rule", rules)
if err != nil {
return err
}
}
// Then loop through all the old rules and delete them
if ors.Len() > 0 {
err := deleteNetworkACLRules(d, meta, rules, ors)
// We need to update this first to preserve the correct state
d.Set("rule", rules)
if err != nil {
return err
}
}
}
return resourceCloudStackNetworkACLRuleRead(d, meta)
}
func resourceCloudStackNetworkACLRuleDelete(d *schema.ResourceData, meta interface{}) error {
// Create an empty rule set to hold all rules that where
// not deleted correctly
rules := resourceCloudStackNetworkACLRule().Schema["rule"].ZeroValue().(*schema.Set)
// Delete all rules
if ors := d.Get("rule").(*schema.Set); ors.Len() > 0 {
err := deleteNetworkACLRules(d, meta, rules, ors)
// We need to update this first to preserve the correct state
d.Set("rule", rules)
if err != nil {
return err
}
}
return nil
}
func deleteNetworkACLRules(d *schema.ResourceData, meta interface{}, rules *schema.Set, ors *schema.Set) error {
var errs *multierror.Error
var wg sync.WaitGroup
wg.Add(ors.Len())
sem := make(chan struct{}, d.Get("parallelism").(int))
for _, rule := range ors.List() {
// Put a sleep here to avoid DoS'ing the API
time.Sleep(500 * time.Millisecond)
go func(rule map[string]interface{}) {
defer wg.Done()
sem <- struct{}{}
// Delete a single rule
err := deleteNetworkACLRule(d, meta, rule)
// If we have at least one UUID, we need to save the rule
if len(rule["uuids"].(map[string]interface{})) > 0 {
rules.Add(rule)
}
if err != nil {
errs = multierror.Append(errs, err)
}
<-sem
}(rule.(map[string]interface{}))
}
wg.Wait()
return errs.ErrorOrNil()
}
func deleteNetworkACLRule(d *schema.ResourceData, meta interface{}, rule map[string]interface{}) error {
cs := meta.(*cloudstack.CloudStackClient)
uuids := rule["uuids"].(map[string]interface{})
for k, id := range uuids {
// We don't care about the count here, so just continue
if k == "%" {
continue
}
// Create the parameter struct
p := cs.NetworkACL.NewDeleteNetworkACLParams(id.(string))
// Delete the rule
if _, err := cs.NetworkACL.DeleteNetworkACL(p); err != nil {
// This is a very poor way to be told the ID does no longer exist :(
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", id.(string))) {
delete(uuids, k)
rule["uuids"] = uuids
continue
}
return err
}
// Delete the UUID of this rule
delete(uuids, k)
rule["uuids"] = uuids
}
return nil
}
func verifyNetworkACLParams(d *schema.ResourceData) error {
managed := d.Get("managed").(bool)
_, rules := d.GetOk("rule")
if !rules && !managed {
return fmt.Errorf(
"You must supply at least one 'rule' when not using the 'managed' firewall feature")
}
return nil
}
func verifyNetworkACLRuleParams(d *schema.ResourceData, rule map[string]interface{}) error {
action := rule["action"].(string)
if action != "allow" && action != "deny" {
return fmt.Errorf("Parameter action only accepts 'allow' or 'deny' as values")
}
protocol := rule["protocol"].(string)
switch protocol {
case "icmp":
if _, ok := rule["icmp_type"]; !ok {
return fmt.Errorf(
"Parameter icmp_type is a required parameter when using protocol 'icmp'")
}
if _, ok := rule["icmp_code"]; !ok {
return fmt.Errorf(
"Parameter icmp_code is a required parameter when using protocol 'icmp'")
}
case "all":
// No additional test are needed, so just leave this empty...
case "tcp", "udp":
if ports, ok := rule["ports"].(*schema.Set); ok {
for _, port := range ports.List() {
m := splitPorts.FindStringSubmatch(port.(string))
if m == nil {
return fmt.Errorf(
"%q is not a valid port value. Valid options are '80' or '80-90'", port.(string))
}
}
} else {
return fmt.Errorf(
"Parameter ports is a required parameter when *not* using protocol 'icmp'")
}
default:
_, err := strconv.ParseInt(protocol, 0, 0)
if err != nil {
return fmt.Errorf(
"%q is not a valid protocol. Valid options are 'tcp', 'udp', "+
"'icmp', 'all' or a valid protocol number", protocol)
}
}
traffic := rule["traffic_type"].(string)
if traffic != "ingress" && traffic != "egress" {
return fmt.Errorf(
"Parameter traffic_type only accepts 'ingress' or 'egress' as values")
}
return nil
}
func retryableACLCreationFunc(
cs *cloudstack.CloudStackClient,
p *cloudstack.CreateNetworkACLParams) func() (interface{}, error) {
return func() (interface{}, error) {
r, err := cs.NetworkACL.CreateNetworkACL(p)
if err != nil {
return nil, err
}
return r, nil
}
}