-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathresource_cloudstack_network_acl_rule.go
More file actions
1436 lines (1198 loc) · 44.4 KB
/
resource_cloudstack_network_acl_rule.go
File metadata and controls
1436 lines (1198 loc) · 44.4 KB
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
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package cloudstack
import (
"context"
"fmt"
"log"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/apache/cloudstack-go/v2/cloudstack"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceCloudStackNetworkACLRule() *schema.Resource {
return &schema.Resource{
Create: resourceCloudStackNetworkACLRuleCreate,
Read: resourceCloudStackNetworkACLRuleRead,
Update: resourceCloudStackNetworkACLRuleUpdate,
Delete: resourceCloudStackNetworkACLRuleDelete,
Importer: &schema.ResourceImporter{
State: resourceCloudStackNetworkACLRuleImport,
},
DeprecationMessage: "cloudstack_network_acl_rule is deprecated. Use cloudstack_network_acl_ruleset instead for better performance and in-place updates.",
CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, meta interface{}) error {
// Force replacement for migration from deprecated 'ports' to 'port' field
if diff.HasChange("rule") {
oldRules, newRules := diff.GetChange("rule")
oldRulesList := oldRules.([]interface{})
newRulesList := newRules.([]interface{})
log.Printf("[DEBUG] CustomizeDiff: checking %d old rules -> %d new rules for migration", len(oldRulesList), len(newRulesList))
// Check if ANY old rule uses deprecated 'ports' field
hasDeprecatedPorts := false
for i, oldRule := range oldRulesList {
oldRuleMap := oldRule.(map[string]interface{})
protocol := oldRuleMap["protocol"].(string)
if protocol == "tcp" || protocol == "udp" {
if portsSet, hasPortsSet := oldRuleMap["ports"].(*schema.Set); hasPortsSet && portsSet.Len() > 0 {
log.Printf("[DEBUG] CustomizeDiff: OLD rule %d has deprecated ports field with %d ports: %v", i, portsSet.Len(), portsSet.List())
hasDeprecatedPorts = true
break
}
}
}
// Check if ANY new rule uses new 'port' field
hasNewPortFormat := false
for i, newRule := range newRulesList {
newRuleMap := newRule.(map[string]interface{})
protocol := newRuleMap["protocol"].(string)
if protocol == "tcp" || protocol == "udp" {
if portStr, hasPort := newRuleMap["port"].(string); hasPort && portStr != "" {
log.Printf("[DEBUG] CustomizeDiff: NEW rule %d has port field: %s", i, portStr)
hasNewPortFormat = true
break
}
}
}
// Force replacement if migrating from deprecated ports to new port format
if hasDeprecatedPorts && hasNewPortFormat {
log.Printf("[DEBUG] CustomizeDiff: MIGRATION DETECTED - old rules use deprecated 'ports', new rules use 'port' - FORCING REPLACEMENT")
diff.ForceNew("rule")
return nil
}
// Also force replacement if old rules have deprecated ports but new rules don't use ports at all
if hasDeprecatedPorts && !hasNewPortFormat {
log.Printf("[DEBUG] CustomizeDiff: POTENTIAL MIGRATION - old rules use deprecated 'ports' but new rules don't - FORCING REPLACEMENT")
diff.ForceNew("rule")
return nil
}
log.Printf("[DEBUG] CustomizeDiff: No migration detected - hasDeprecatedPorts=%t, hasNewPortFormat=%t", hasDeprecatedPorts, hasNewPortFormat)
}
return nil
},
Schema: map[string]*schema.Schema{
"acl_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"managed": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"rule": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"rule_number": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"action": {
Type: schema.TypeString,
Optional: true,
Default: "allow",
},
"cidr_list": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"protocol": {
Type: schema.TypeString,
Required: true,
},
"icmp_type": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"icmp_code": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"ports": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Deprecated: "Use 'port' instead. The 'ports' field is deprecated and will be removed in a future version.",
},
"port": {
Type: schema.TypeString,
Optional: true,
},
"traffic_type": {
Type: schema.TypeString,
Optional: true,
Default: "ingress",
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"uuids": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
"project": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"parallelism": {
Type: schema.TypeInt,
Optional: true,
Default: 2,
},
},
}
}
func resourceCloudStackNetworkACLRuleCreate(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] Entering resourceCloudStackNetworkACLRuleCreate with acl_id=%s", d.Get("acl_id").(string))
// Make sure all required parameters are there
if err := verifyNetworkACLParams(d); err != nil {
log.Printf("[ERROR] Failed parameter verification: %v", err)
return err
}
// Create all rules that are configured
if nrs := d.Get("rule").([]interface{}); len(nrs) > 0 {
// Create an empty rule list to hold all newly created rules
rules := make([]interface{}, 0)
log.Printf("[DEBUG] Processing %d rules", len(nrs))
err := createNetworkACLRules(d, meta, &rules, nrs)
if err != nil {
log.Printf("[ERROR] Failed to create network ACL rules: %v", err)
return err
}
// Set the resource ID only after successful creation
log.Printf("[DEBUG] Setting resource ID to acl_id=%s", d.Get("acl_id").(string))
d.SetId(d.Get("acl_id").(string))
// Update state with created rules
if err := d.Set("rule", rules); err != nil {
log.Printf("[ERROR] Failed to set rule attribute: %v", err)
return err
}
} else {
log.Printf("[DEBUG] No rules provided, setting ID to acl_id=%s", d.Get("acl_id").(string))
d.SetId(d.Get("acl_id").(string))
}
log.Printf("[DEBUG] Calling resourceCloudStackNetworkACLRuleRead")
return resourceCloudStackNetworkACLRuleRead(d, meta)
}
func createNetworkACLRules(d *schema.ResourceData, meta interface{}, rules *[]interface{}, nrs []interface{}) error {
log.Printf("[DEBUG] Creating %d network ACL rules", len(nrs))
var errs *multierror.Error
results := make([]map[string]interface{}, len(nrs))
var mu sync.Mutex
var wg sync.WaitGroup
wg.Add(len(nrs))
sem := make(chan struct{}, d.Get("parallelism").(int))
for i, rule := range nrs {
// Put in a tiny sleep here to avoid DoS'ing the API
time.Sleep(500 * time.Millisecond)
go func(rule map[string]interface{}, index int) {
defer wg.Done()
sem <- struct{}{}
log.Printf("[DEBUG] Creating rule #%d: %+v", index+1, rule)
// Create a single rule
err := createNetworkACLRule(d, meta, rule)
if err != nil {
log.Printf("[ERROR] Failed to create rule #%d: %v", index+1, err)
mu.Lock()
errs = multierror.Append(errs, fmt.Errorf("rule #%d: %v", index+1, err))
mu.Unlock()
} else if len(rule["uuids"].(map[string]interface{})) > 0 {
log.Printf("[DEBUG] Successfully created rule #%d, storing at index %d", index+1, index)
results[index] = rule
} else {
log.Printf("[WARN] Rule #%d created but has no UUIDs", index+1)
}
<-sem
}(rule.(map[string]interface{}), i)
}
wg.Wait()
if err := errs.ErrorOrNil(); err != nil {
log.Printf("[ERROR] Errors occurred while creating rules: %v", err)
return err
}
for i, result := range results {
if result != nil {
*rules = append(*rules, result)
log.Printf("[DEBUG] Added rule #%d to final rules list", i+1)
}
}
log.Printf("[DEBUG] Successfully created all rules")
return nil
}
func createNetworkACLRule(d *schema.ResourceData, meta interface{}, rule map[string]interface{}) error {
cs := meta.(*cloudstack.CloudStackClient)
uuids := rule["uuids"].(map[string]interface{})
log.Printf("[DEBUG] Creating network ACL rule with protocol=%s", rule["protocol"].(string))
// Make sure all required parameters are there
if err := verifyNetworkACLRuleParams(d, rule); err != nil {
log.Printf("[ERROR] Failed to verify rule parameters: %v", err)
return err
}
// Create a new parameter struct
p := cs.NetworkACL.NewCreateNetworkACLParams(rule["protocol"].(string))
log.Printf("[DEBUG] Initialized CreateNetworkACLParams")
// If a rule ID is specified, set it
if ruleNum, ok := rule["rule_number"].(int); ok && ruleNum > 0 {
p.SetNumber(ruleNum)
log.Printf("[DEBUG] Set rule_number=%d", ruleNum)
}
// Set the acl ID from the configuration
aclID := d.Get("acl_id").(string)
p.SetAclid(aclID)
log.Printf("[DEBUG] Set aclid=%s", aclID)
// Set the action
p.SetAction(rule["action"].(string))
log.Printf("[DEBUG] Set action=%s", rule["action"].(string))
// Set the CIDR list
var cidrList []string
for _, cidr := range rule["cidr_list"].([]interface{}) {
cidrList = append(cidrList, cidr.(string))
}
p.SetCidrlist(cidrList)
log.Printf("[DEBUG] Set cidr_list=%v", cidrList)
// Set the traffic type
p.SetTraffictype(rule["traffic_type"].(string))
log.Printf("[DEBUG] Set traffic_type=%s", rule["traffic_type"].(string))
// Set the description
if desc, ok := rule["description"].(string); ok && desc != "" {
p.SetReason(desc)
log.Printf("[DEBUG] Set description=%s", desc)
}
// 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))
log.Printf("[DEBUG] Set icmp_type=%d, icmp_code=%d", rule["icmp_type"].(int), rule["icmp_code"].(int))
r, err := Retry(4, retryableACLCreationFunc(cs, p))
if err != nil {
log.Printf("[ERROR] Failed to create ICMP rule: %v", err)
return err
}
uuids["icmp"] = r.(*cloudstack.CreateNetworkACLResponse).Id
rule["uuids"] = uuids
log.Printf("[DEBUG] Created ICMP rule with ID=%s", r.(*cloudstack.CreateNetworkACLResponse).Id)
}
// If the protocol is ALL set the needed parameters
if rule["protocol"].(string) == "all" {
r, err := Retry(4, retryableACLCreationFunc(cs, p))
if err != nil {
log.Printf("[ERROR] Failed to create ALL rule: %v", err)
return err
}
uuids["all"] = r.(*cloudstack.CreateNetworkACLResponse).Id
rule["uuids"] = uuids
log.Printf("[DEBUG] Created ALL rule with ID=%s", r.(*cloudstack.CreateNetworkACLResponse).Id)
}
// If protocol is TCP or UDP, create the rule (with or without port)
if rule["protocol"].(string) == "tcp" || rule["protocol"].(string) == "udp" {
// Check if deprecated ports field is used and reject it
if portsSet, hasPortsSet := rule["ports"].(*schema.Set); hasPortsSet && portsSet.Len() > 0 {
log.Printf("[ERROR] Attempt to create rule with deprecated ports field")
return fmt.Errorf("The 'ports' field is no longer supported for creating new rules. Please use the 'port' field with separate rules for each port/range.")
}
portStr, hasPort := rule["port"].(string)
if hasPort && portStr != "" {
// Handle single port
log.Printf("[DEBUG] Processing single port for TCP/UDP rule: %s", portStr)
if _, ok := uuids[portStr]; !ok {
m := splitPorts.FindStringSubmatch(portStr)
if m == nil {
log.Printf("[ERROR] Invalid port format: %s", portStr)
return fmt.Errorf("%q is not a valid port value. Valid options are '80' or '80-90'", portStr)
}
startPort, err := strconv.Atoi(m[1])
if err != nil {
log.Printf("[ERROR] Failed to parse start port %s: %v", m[1], err)
return err
}
endPort := startPort
if m[2] != "" {
endPort, err = strconv.Atoi(m[2])
if err != nil {
log.Printf("[ERROR] Failed to parse end port %s: %v", m[2], err)
return err
}
}
p.SetStartport(startPort)
p.SetEndport(endPort)
log.Printf("[DEBUG] Set port start=%d, end=%d", startPort, endPort)
r, err := Retry(4, retryableACLCreationFunc(cs, p))
if err != nil {
log.Printf("[ERROR] Failed to create TCP/UDP rule for port %s: %v", portStr, err)
return err
}
uuids[portStr] = r.(*cloudstack.CreateNetworkACLResponse).Id
rule["uuids"] = uuids
log.Printf("[DEBUG] Created TCP/UDP rule for port %s with ID=%s", portStr, r.(*cloudstack.CreateNetworkACLResponse).Id)
} else {
log.Printf("[DEBUG] Port %s already has UUID, skipping", portStr)
}
} else {
// No port specified - create rule for all ports
log.Printf("[DEBUG] No port specified for TCP/UDP rule, creating rule for all ports")
r, err := Retry(4, retryableACLCreationFunc(cs, p))
if err != nil {
log.Printf("[ERROR] Failed to create TCP/UDP rule for all ports: %v", err)
return err
}
uuids["all_ports"] = r.(*cloudstack.CreateNetworkACLResponse).Id
rule["uuids"] = uuids
log.Printf("[DEBUG] Created TCP/UDP rule for all ports with ID=%s", r.(*cloudstack.CreateNetworkACLResponse).Id)
}
}
log.Printf("[DEBUG] Successfully created rule with uuids=%+v", uuids)
return nil
}
func processTCPUDPRule(rule map[string]interface{}, ruleMap map[string]*cloudstack.NetworkACL, uuids map[string]interface{}, rules *[]interface{}) {
// Check for deprecated ports field first (for reading existing state during migration)
ps, hasPortsSet := rule["ports"].(*schema.Set)
portStr, hasPort := rule["port"].(string)
if hasPortsSet && ps.Len() > 0 {
log.Printf("[DEBUG] Processing deprecated ports field with %d ports during state read", ps.Len())
// Process each port in the deprecated ports set during state read
for _, port := range ps.List() {
portStr := port.(string)
if processPortForRule(portStr, rule, ruleMap, uuids) {
log.Printf("[DEBUG] Processed deprecated port %s during state read", portStr)
}
}
// Only add the rule once with all processed ports
if len(uuids) > 0 {
*rules = append(*rules, rule)
log.Printf("[DEBUG] Added TCP/UDP rule with deprecated ports to state during read: %+v", rule)
}
} else if hasPort && portStr != "" {
log.Printf("[DEBUG] Processing single port for TCP/UDP rule: %s", portStr)
if processPortForRule(portStr, rule, ruleMap, uuids) {
rule["port"] = portStr
*rules = append(*rules, rule)
log.Printf("[DEBUG] Added TCP/UDP rule with single port to state: %+v", rule)
}
} else {
log.Printf("[DEBUG] Processing TCP/UDP rule with no port specified")
id, ok := uuids["all_ports"]
if !ok {
log.Printf("[DEBUG] No UUID for all_ports, skipping rule")
return
}
r, ok := ruleMap[id.(string)]
if !ok {
log.Printf("[DEBUG] TCP/UDP rule for all_ports with ID %s not found, removing UUID", id.(string))
delete(uuids, "all_ports")
return
}
delete(ruleMap, id.(string))
var cidrs []interface{}
for _, cidr := range strings.Split(r.Cidrlist, ",") {
cidrs = append(cidrs, cidr)
}
rule["action"] = strings.ToLower(r.Action)
rule["protocol"] = r.Protocol
rule["traffic_type"] = strings.ToLower(r.Traffictype)
rule["cidr_list"] = cidrs
rule["rule_number"] = r.Number
*rules = append(*rules, rule)
log.Printf("[DEBUG] Added TCP/UDP rule with no port to state: %+v", rule)
}
}
func processPortForRule(portStr string, rule map[string]interface{}, ruleMap map[string]*cloudstack.NetworkACL, uuids map[string]interface{}) bool {
id, ok := uuids[portStr]
if !ok {
log.Printf("[DEBUG] No UUID for port %s, skipping", portStr)
return false
}
r, ok := ruleMap[id.(string)]
if !ok {
log.Printf("[DEBUG] TCP/UDP rule for port %s with ID %s not found, removing UUID", portStr, id.(string))
delete(uuids, portStr)
return false
}
// Delete the known rule so only unknown rules remain in the ruleMap
delete(ruleMap, id.(string))
var cidrs []interface{}
for _, cidr := range strings.Split(r.Cidrlist, ",") {
cidrs = append(cidrs, cidr)
}
rule["action"] = strings.ToLower(r.Action)
rule["protocol"] = r.Protocol
rule["traffic_type"] = strings.ToLower(r.Traffictype)
rule["cidr_list"] = cidrs
rule["rule_number"] = r.Number
return true
}
func resourceCloudStackNetworkACLRuleRead(d *schema.ResourceData, meta interface{}) error {
cs := meta.(*cloudstack.CloudStackClient)
log.Printf("[DEBUG] Entering resourceCloudStackNetworkACLRuleRead with acl_id=%s", d.Id())
// 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 not exist", d.Id())
d.SetId("")
return nil
}
log.Printf("[ERROR] Failed to get ACL list by ID: %v", err)
return err
}
// Get all the rules from the running environment with retries
p := cs.NetworkACL.NewListNetworkACLsParams()
p.SetAclid(d.Id())
p.SetListall(true)
var l *cloudstack.ListNetworkACLsResponse
retryErr := retry.RetryContext(context.Background(), 30*time.Second, func() *retry.RetryError {
var err error
l, err = cs.NetworkACL.ListNetworkACLs(p)
if err != nil {
log.Printf("[DEBUG] Failed to list network ACL rules, retrying: %v", err)
return retry.RetryableError(err)
}
if l.Count == 0 {
log.Printf("[DEBUG] No network ACL rules found for ACL %s, retrying", d.Id())
return retry.RetryableError(fmt.Errorf("no network ACL rules found for ACL %s", d.Id()))
}
log.Printf("[DEBUG] Found %d network ACL rules for ACL %s", l.Count, d.Id())
return nil
})
if retryErr != nil {
log.Printf("[WARN] Network ACL rules for %s not found after retries", d.Id())
d.SetId("")
return nil
}
// 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
}
log.Printf("[DEBUG] Loaded %d rules into ruleMap", len(ruleMap))
// Create an empty rule list to hold all rules
var rules []interface{}
// Read all rules that are configured
if rs := d.Get("rule").([]interface{}); len(rs) > 0 {
for _, rule := range rs {
rule := rule.(map[string]interface{})
uuids := rule["uuids"].(map[string]interface{})
log.Printf("[DEBUG] Processing rule with protocol=%s, uuids=%+v", rule["protocol"].(string), uuids)
if rule["protocol"].(string) == "icmp" {
id, ok := uuids["icmp"]
if !ok {
log.Printf("[DEBUG] No ICMP UUID found, skipping rule")
continue
}
// Get the rule
r, ok := ruleMap[id.(string)]
if !ok {
log.Printf("[DEBUG] ICMP rule with ID %s not found, removing UUID", id.(string))
delete(uuids, "icmp")
continue
}
// Delete the known rule so only unknown rules remain in the ruleMap
delete(ruleMap, id.(string))
// Create a list with all CIDR's
var cidrs []interface{}
for _, cidr := range strings.Split(r.Cidrlist, ",") {
cidrs = append(cidrs, 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
rule["rule_number"] = r.Number
rules = append(rules, rule)
log.Printf("[DEBUG] Added ICMP rule to state: %+v", rule)
}
if rule["protocol"].(string) == "all" {
id, ok := uuids["all"]
if !ok {
log.Printf("[DEBUG] No ALL UUID found, skipping rule")
continue
}
// Get the rule
r, ok := ruleMap[id.(string)]
if !ok {
log.Printf("[DEBUG] ALL rule with ID %s not found, removing UUID", id.(string))
delete(uuids, "all")
continue
}
// Delete the known rule so only unknown rules remain in the ruleMap
delete(ruleMap, id.(string))
// Create a list with all CIDR's
var cidrs []interface{}
for _, cidr := range strings.Split(r.Cidrlist, ",") {
cidrs = append(cidrs, 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
rule["rule_number"] = r.Number
rules = append(rules, rule)
log.Printf("[DEBUG] Added ALL rule to state: %+v", rule)
}
if rule["protocol"].(string) == "tcp" || rule["protocol"].(string) == "udp" {
uuids := rule["uuids"].(map[string]interface{})
processTCPUDPRule(rule, ruleMap, uuids, &rules)
}
}
}
// 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 list as the
// cidr_list is a required field and thus needs a value
cidrs := []interface{}{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 list
rules = append(rules, rule)
log.Printf("[DEBUG] Added managed dummy rule for UUID %s", uuid)
}
}
if len(rules) > 0 {
log.Printf("[DEBUG] Setting %d rules in state", len(rules))
if err := d.Set("rule", rules); err != nil {
log.Printf("[ERROR] Failed to set rule attribute: %v", err)
return err
}
} else if !managed {
log.Printf("[DEBUG] No rules found and not managed, clearing ID")
d.SetId("")
}
log.Printf("[DEBUG] Completed resourceCloudStackNetworkACLRuleRead")
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 list has changed
if d.HasChange("rule") {
o, n := d.GetChange("rule")
oldRules := o.([]interface{})
newRules := n.([]interface{})
log.Printf("[DEBUG] Rule list changed: %d old rules -> %d new rules", len(oldRules), len(newRules))
// Check for migration from deprecated 'ports' to 'port' field
migrationDetected := isPortsMigration(oldRules, newRules)
if migrationDetected {
log.Printf("[DEBUG] Migration detected - performing complete rule replacement")
return performPortsMigration(d, meta, oldRules, newRules)
}
log.Printf("[DEBUG] Rule list changed, performing efficient updates")
err := updateNetworkACLRules(d, meta, oldRules, newRules)
if err != nil {
return err
}
}
return resourceCloudStackNetworkACLRuleRead(d, meta)
}
func resourceCloudStackNetworkACLRuleDelete(d *schema.ResourceData, meta interface{}) error {
// Delete all rules
if ors := d.Get("rule").([]interface{}); len(ors) > 0 {
for _, rule := range ors {
ruleMap := rule.(map[string]interface{})
err := deleteNetworkACLRule(d, meta, ruleMap)
if err != nil {
log.Printf("[ERROR] Failed to delete rule: %v", err)
return err
}
}
}
return nil
}
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 {
log.Printf("[DEBUG] Verifying parameters for rule: %+v", rule)
if ruleNum, ok := rule["rule_number"]; ok && ruleNum != nil {
if number, ok := ruleNum.(int); ok && number != 0 {
// Validate only if rule_number is explicitly set (non-zero)
if number < 1 || number > 65535 {
log.Printf("[ERROR] Invalid rule_number: %d", number)
return fmt.Errorf(
"%q must be between %d and %d inclusive, got: %d", "rule_number", 1, 65535, number)
}
}
}
action := rule["action"].(string)
if action != "allow" && action != "deny" {
log.Printf("[ERROR] Invalid action: %s", action)
return fmt.Errorf("Parameter action only accepts 'allow' or 'deny' as values")
}
protocol := rule["protocol"].(string)
log.Printf("[DEBUG] Validating protocol: %s", protocol)
switch protocol {
case "icmp":
if _, ok := rule["icmp_type"]; !ok {
log.Printf("[ERROR] Missing icmp_type for ICMP protocol")
return fmt.Errorf(
"Parameter icmp_type is a required parameter when using protocol 'icmp'")
}
if _, ok := rule["icmp_code"]; !ok {
log.Printf("[ERROR] Missing icmp_code for ICMP protocol")
return fmt.Errorf(
"Parameter icmp_code is a required parameter when using protocol 'icmp'")
}
case "all":
// No additional test are needed
log.Printf("[DEBUG] Protocol 'all' validated")
case "tcp", "udp":
// The deprecated 'ports' field is no longer supported in any scenario
portsSet, hasPortsSet := rule["ports"].(*schema.Set)
portStr, hasPort := rule["port"].(string)
// Block deprecated ports field completely
if hasPortsSet && portsSet.Len() > 0 {
log.Printf("[ERROR] Attempt to use deprecated ports field")
return fmt.Errorf("The 'ports' field is no longer supported. Please use the 'port' field instead.")
}
// Validate the new port field if used
if hasPort && portStr != "" {
log.Printf("[DEBUG] Found port for TCP/UDP: %s", portStr)
m := splitPorts.FindStringSubmatch(portStr)
if m == nil {
log.Printf("[ERROR] Invalid port format: %s", portStr)
return fmt.Errorf(
"%q is not a valid port value. Valid options are '80' or '80-90'", portStr)
}
} else {
log.Printf("[DEBUG] No port specified for TCP/UDP, allowing empty port")
}
default:
_, err := strconv.ParseInt(protocol, 0, 0)
if err != nil {
log.Printf("[ERROR] Invalid protocol: %s", protocol)
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" {
log.Printf("[ERROR] Invalid traffic_type: %s", traffic)
return fmt.Errorf(
"Parameter traffic_type only accepts 'ingress' or 'egress' as values")
}
log.Printf("[DEBUG] Rule parameters verified successfully")
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
}
}
func resourceCloudStackNetworkACLRuleImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
cs := meta.(*cloudstack.CloudStackClient)
aclID := d.Id()
log.Printf("[DEBUG] Attempting to import ACL list with ID: %s", aclID)
if aclExists, err := checkACLListExists(cs, aclID); err != nil {
return nil, fmt.Errorf("error checking ACL list existence: %v", err)
} else if !aclExists {
return nil, fmt.Errorf("ACL list with ID %s does not exist", aclID)
}
log.Printf("[DEBUG] Found ACL list with ID: %s", aclID)
d.Set("acl_id", aclID)
log.Printf("[DEBUG] Setting managed=true for ACL list import")
d.Set("managed", true)
return []*schema.ResourceData{d}, nil
}
func checkACLListExists(cs *cloudstack.CloudStackClient, aclID string) (bool, error) {
log.Printf("[DEBUG] Checking if ACL list exists: %s", aclID)
_, count, err := cs.NetworkACL.GetNetworkACLListByID(aclID)
if err != nil {
log.Printf("[DEBUG] Error getting ACL list by ID: %v", err)
return false, err
}
log.Printf("[DEBUG] ACL list check result: count=%d", count)
return count > 0, nil
}
func updateNetworkACLRules(d *schema.ResourceData, meta interface{}, oldRules, newRules []interface{}) error {
cs := meta.(*cloudstack.CloudStackClient)
log.Printf("[DEBUG] Updating ACL rules: %d old rules, %d new rules", len(oldRules), len(newRules))
log.Printf("[DEBUG] Performing normal rule updates")
return performNormalRuleUpdates(d, meta, cs, oldRules, newRules)
}
func performNormalRuleUpdates(d *schema.ResourceData, meta interface{}, cs *cloudstack.CloudStackClient, oldRules, newRules []interface{}) error {
rulesToUpdate := make(map[string]map[string]interface{}) // UUID -> new rule mapping
rulesToDelete := make([]map[string]interface{}, 0)
rulesToCreate := make([]map[string]interface{}, 0)
// Track which new rules match existing old rules
usedNewRules := make(map[int]bool)
// For each old rule, try to find a matching new rule
for _, oldRule := range oldRules {
oldRuleMap := oldRule.(map[string]interface{})
foundMatch := false
for newIdx, newRule := range newRules {
if usedNewRules[newIdx] {
continue
}
newRuleMap := newRule.(map[string]interface{})
log.Printf("[DEBUG] Comparing old rule %+v with new rule %+v", oldRuleMap, newRuleMap)
if rulesMatch(oldRuleMap, newRuleMap) {
log.Printf("[DEBUG] Found matching new rule for old rule")
if oldUUIDs, ok := oldRuleMap["uuids"].(map[string]interface{}); ok {
newRuleMap["uuids"] = oldUUIDs
}
if ruleNeedsUpdate(oldRuleMap, newRuleMap) {
log.Printf("[DEBUG] Rule needs updating")
if uuids, ok := oldRuleMap["uuids"].(map[string]interface{}); ok {
for _, uuid := range uuids {
if uuid != nil {
rulesToUpdate[uuid.(string)] = newRuleMap
break
}
}
}
}
usedNewRules[newIdx] = true
foundMatch = true
break
}
}
if !foundMatch {
log.Printf("[DEBUG] Old rule has no match, will be deleted")
rulesToDelete = append(rulesToDelete, oldRuleMap)
}
}