-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconverter_rules_engine.py
827 lines (712 loc) · 33.5 KB
/
converter_rules_engine.py
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
import logging
import random
from typing import Dict, List, Any, Set, Tuple, Optional
from azion_resources import AzionResource
from akamai.mapping import MAPPING
from akamai.utils import (
map_forward_host_header,
map_origin_type,
replace_variables,
map_operator,
map_variable,
behavior_key
)
from utils import sanitize_name
DEFAULT_CRITERIA = {
"name": "default",
"variable": "$${uri}",
"operator": "starts_with",
"conditional": "if",
"input_value": "/"
}
CONDITIONAL_MAP = {
"all": "and",
"any": "or",
"one": "if"
}
BEHAVIOR_CACHE_PHASE = ["NO_STORE", "NO_CACHE"]
def create_rule_engine(
azion_resources: AzionResource,
rule: Dict[str, Any],
context: Dict[str, Any],
name: str = None,
) -> List[Dict[str, Any]]:
"""
Create a rule engine resource from Akamai rule data.
Parameters:
azion_resources (AzionResource): Azion resource container
rule (Dict[str, Any]): Akamai rule data
context (Dict[str, Any]): Context variables
name (str): Rule name
Returns:
List[Dict[str, Any]]: Azion rule engine resource
"""
resources = []
rule_name = name if name else rule.get("name", "Unnamed Rule")
index = context.get("rule_index", 0)
main_setting_name = context.get("main_setting_name", "unnamed")
logging.info(f"[rules_engine] Processing rule: '{rule_name}' with index {index}")
# Extract behaviors and criteria
behaviors = rule.get("behaviors", [])
criteria = rule.get("criteria", [])
rule_condition = rule.get("criteriaMustSatisfy", "one")
logging.info(
f"[rules_engine] Found {len(behaviors)} behaviors and {len(criteria)} criteria for rule: '{rule_name}'"
)
try:
# Create resource if either behaviors or criteria exist
if behaviors or criteria:
# Process conditions
processed_rule = process_conditional_rule(rule)
# Process behaviors and criteria
azion_behaviors, depends_on_behaviors = process_behaviors(azion_resources, behaviors, context, rule_name)
behaviors_names = [behavior.get("name") for behavior in behaviors]
azion_criteria = process_criteria(criteria, behaviors_names, rule_condition)
# Handling depends_on
depends_on = [f"azion_edge_application_main_setting.{main_setting_name}"]
depends_on.extend(list(depends_on_behaviors))
# Handling behaviors by phase
request_behaviors = []
response_behaviors = []
for behavior in azion_behaviors:
if behavior.get('phase', 'both') == 'both':
request_behaviors.append(behavior)
response_behaviors.append(behavior)
elif behavior.get('phase', 'request') == 'request':
request_behaviors.append(behavior)
elif behavior.get('phase', 'request') == 'response':
response_behaviors.append(behavior)
# Create request phase rule
if len(request_behaviors) > 0:
resource = assemble_request_rule(processed_rule,
rule_name,
main_setting_name,
azion_criteria,
request_behaviors,
depends_on)
if resource:
resources.append(resource)
logging.info(f"[rules_engine] Rule engine resource created for rule: '{rule_name}'")
# Create response phase rule
if len(response_behaviors) > 0:
resource = assemble_response_rule(processed_rule,
rule_name,
main_setting_name,
azion_criteria,
response_behaviors,
depends_on)
if resource:
resources.append(resource)
logging.info(f"[rules_engine] Rule engine resource created for rule: '{rule_name}'")
# Enable image optimization if necessary
if "imageManager" in behaviors_names:
idx, main_settings = azion_resources.query_azion_resource_by_type('azion_edge_application_main_setting')
if main_settings:
az_resources = azion_resources.get_azion_resources()
main_settings["attributes"]["edge_application"]["image_optimization"] = True
az_resources[idx] = main_settings
else:
logging.warning(f"[rules_engine] No behaviors or criteria found for rule: '{rule_name}'. Skipping.")
except ValueError as e:
logging.error(f"[rules_engine] Error processing rule '{rule_name}': {str(e)}")
return resources
def assemble_request_rule(
rule: Dict[str, Any],
rule_name: str,
main_setting_name: str,
azion_criteria: Dict[str, Any],
request_behaviors: List[Dict[str, Any]],
depends_on: List[str]
) -> Optional[Dict[str, Any]]:
"""
Create a rule engine resource from Akamai rule data.
Parameters:
rule (Dict[str, Any]): Akamai rule data.
rule_name (str): Name of the rule.
main_setting_name (str): Name of the main setting.
azion_criteria (Dict[str, Any]): Criteria to be used in the rule.
request_behaviors (List[Dict[str, Any]]): List of behaviors to be applied in the rule.
depends_on (List[str]): List of dependencies for the rule.
Returns:
Dict[str, Any]: Rule engine resource.
"""
phase = "request" if rule_name != "default" else "default"
rule_description = rule.get("comments", "").replace("\n", " ").replace("\r", " ").replace("\"", "'")
random_number = str(random.randint(1000, 9999))
unique_rule_name = sanitize_name(rule_name) + "_" + random_number
resource = {
"type": "azion_edge_application_rule_engine",
"name": unique_rule_name,
"attributes": {
"edge_application_id": f"azion_edge_application_main_setting.{main_setting_name}.edge_application.application_id",
"results": {
"name": "Default Rule" if phase == "default" else unique_rule_name,
"description": rule_description,
"phase": phase,
"behaviors": request_behaviors
},
"depends_on": depends_on
}
}
# Only add criteria if we have entries
criteria = azion_criteria.get("request", None)
if criteria:
resource["attributes"]["results"]["criteria"] = criteria
else:
logging.warning(f"[rules_engine][assemble_request_rule] No criteria found for rule: '{rule_name}'. Skipping.")
resource = None
return resource
def assemble_response_rule(
rule: Dict[str, Any],
rule_name: str,
main_setting_name: str,
azion_criteria: Dict[str, Any],
behaviors: List[Dict[str, Any]],
depends_on: List[str]
) -> Optional[Dict[str, Any]]:
"""
Create a rule engine resource from Akamai rule data.
Parameters:
rule (Dict[str, Any]): Akamai rule data.
rule_name (str): Name of the rule.
main_setting_name (str): Name of the main setting.
azion_criteria (Dict[str, Any]): Criteria to be used in the rule.
behaviors (List[Dict[str, Any]]): List of behaviors to be applied in the rule.
depends_on (List[str]): List of dependencies for the rule.
Returns:
Dict[str, Any]: Rule engine resource.
"""
behavior_names = "_".join(sorted(set(b.get("name", "") for b in behaviors)))
name = sanitize_name(f"{rule_name}_{behavior_names}")
random_number = str(random.randint(1000, 9999))
unique_rule_name = sanitize_name(name) + "_" + random_number
# Find criteria for the behavior
criterias = azion_criteria.get("response", {}).get("entries")
selected_criteria = None
if criterias:
if len(criterias) == 1:
selected_criteria = azion_criteria.get("response")
else:
selection = []
for criteria in criterias:
for behavior in behaviors:
if criteria.get("name", "") == behavior.get('name') or \
criteria.get("phase", "both") != "request":
selection.append(criteria)
break
selected_criteria = {"entries": selection}
else:
#selected_criteria = azion_criteria.get("response_default")
logging.warning(f"[rules_engine][assemble_response_rule] No criteria found for rule: '{rule_name}'. Skipping.")
return None
rule_description = rule.get("comments", "").replace("\n", " ").replace("\r", " ").replace("\"", "'")
resource = {
"type": "azion_edge_application_rule_engine",
"name": unique_rule_name,
"attributes": {
"edge_application_id": f"azion_edge_application_main_setting.{main_setting_name}.edge_application.application_id",
"results": {
"name": unique_rule_name,
"description": rule_description,
"phase": "response",
"behaviors": behaviors
},
"depends_on": depends_on
}
}
# Only add criteria if we have entries
if len(selected_criteria) > 0:
resource["attributes"]["results"]["criteria"] = selected_criteria
return resource
def process_conditional_rule(rule: Dict[str, Any]) -> Dict[str, Any]:
"""
Process rules with conditions and create Azion-compatible conditions.
Parameters:
rule (Dict[str, Any]): The rule to process.
Returns:
Dict[str, Any]: Processed rule with Azion-compatible conditions.
"""
processed_rule = rule.copy()
conditions = rule.get("criteria", [])
if not conditions:
return processed_rule
azion_conditions = []
for condition in conditions:
condition_name = condition.get("name", "")
if condition_name in MAPPING.get("criteria", {}):
mapping = MAPPING["criteria"][condition_name]
# Handle content type criteria specially
if condition_name == "contentType":
content_types = condition.get("options", {}).get("values", [])
if content_types:
azion_conditions.append({
"conditional": mapping["azion_condition"],
"operator": mapping["azion_operator"],
"input_value": "|".join(content_types) # Join multiple content types with OR operator
})
else:
if condition_name == "requestHeader":
header_name = condition["options"]["headerName"]
mapping["azion_condition"] = f"$${{http_{sanitize_name(header_name)}}}"
# Handle other criteria types
azion_conditions.append({
"conditional": mapping["azion_condition"],
"operator": mapping["azion_operator"],
"input_value": condition.get("options", {}).get("value", "")
})
else:
logging.warning(f"Unmapped condition: {condition_name}")
if azion_conditions:
processed_rule["criteria"] = azion_conditions
return processed_rule
def process_criteria_default(behaviors_names: List[str]) -> Dict[str, Any]:
"""
Process default criteria for when no criteria is defined.
Parameters:
behaviors_names (List[str]): List of behavior names.
Returns:
Dict[str, Any]: Processed criteria.
"""
azion_criteria = {}
request_entries = []
response_entries = []
# Default criteria for when no criteria is defined
for behavior_name in behaviors_names:
mapping = MAPPING.get("criteria", {}).get(behavior_name)
if mapping:
entry = {
"name": mapping.get("name", behavior_name),
"variable": mapping.get("azion_condition"),
"operator": mapping.get("azion_operator"),
"conditional": mapping.get("conditional"),
"phase": mapping.get("phase", "request"),
"akamai_behavior": mapping.get("akamai_behavior", ""),
}
if mapping.get("azion_operator"):
entry["input_value"] = mapping.get("input_value")
# Append to the correct phase
if mapping.get("phase") == "response":
response_entries.append(entry)
else:
request_entries.append(entry)
azion_criteria["request_default"] = {"entries":[DEFAULT_CRITERIA]}
azion_criteria["response_default"] = {"entries":[DEFAULT_CRITERIA]}
if len(request_entries) > 0:
azion_criteria["request"] = {"entries": request_entries}
logging.info("No criteria found for request phase of the rule, using default criterias based on the behaviors")
if len(response_entries) > 0:
azion_criteria["response"] = {"entries": response_entries}
logging.info("No criteria found for response phase of the rule, using default criterias based on the behaviors")
return azion_criteria
def process_criteria(
criteria: List[Dict[str, Any]],
behaviors_names: List[str],
rule_condition: str
) -> List[Dict[str, Any]]:
"""
Processes and maps Akamai criteria to Azion-compatible criteria.
Parameters:
criteria (List[Dict[str, Any]]): List of Akamai criteria.
behaviors_names (List[str]): List of behavior names.
rule_condition (str): Condition to group criteria
Returns:
List[Dict[str, Any]]: List of Azion criteria grouped by phase.
"""
azion_criteria = {}
request_entries = []
response_entries = []
if not criteria:
azion_criteria = process_criteria_default(behaviors_names)
return azion_criteria
for index, criterion in enumerate(criteria):
name = criterion.get("name")
options = criterion.get("options", {})
if not name:
logging.warning(f"Criterion {criterion} at index {index} is missing a name. Skipping.")
continue
mapping = MAPPING.get("criteria", {}).get(name)
if not mapping:
logging.warning(f"No mapping found for criterion: {name}. Skipping.")
continue
# Map Akamai's criteriaMustSatisfy to Azion's conditional
criteria_has_condition = criterion.get("criteriaMustSatisfy", "one")
group_conditional = CONDITIONAL_MAP.get(criteria_has_condition, "one") if index == 0 else CONDITIONAL_MAP.get(rule_condition, "and")
try:
# Map operator
akamai_operator = options.get("matchOperator", "EQUALS")
if callable(mapping.get("azion_operator")):
azion_operator = mapping["azion_operator"](options)
else:
azion_operator = mapping.get("azion_operator")
if azion_operator is None:
azion_operator = map_operator(akamai_operator)
# Handle input values
values = options.get("values", [])
if len(values) == 0:
values = [options.get("value", "")]
# Handle single or multiple values based on the operator
if azion_operator in {"exists", "does_not_exist"}:
input_value = None
else:
if callable(mapping.get("input_value")):
input_value = mapping["input_value"](values)
elif values:
input_value = values[0]
else:
input_value = "*"
# Build the entry
entry = {
"variable": mapping["azion_condition"],
"operator": azion_operator,
"conditional": group_conditional,
"akamai_behavior": mapping.get("akamai_behavior",""),
}
if input_value is not None:
entry["input_value"] = input_value.replace("\r", "")
# Append to the correct phase
if mapping.get("phase") == "response":
response_entries.append(entry)
elif mapping.get("phase") == "request":
request_entries.append(entry)
else:
response_entries.append(entry)
request_entries.append(entry)
except ValueError as e:
logging.error(f"Error processing criterion {name}: {str(e)}")
# Assemble criteria groups
if request_entries:
azion_criteria["request"] = {"entries": request_entries}
if response_entries:
azion_criteria["response"] = {"entries": response_entries}
if not azion_criteria and not response_entries:
azion_criteria = process_criteria_default(behaviors_names)
return azion_criteria
def behavior_cache_setting(
context: Dict[str, Any],
azion_resources: AzionResource,
options: Dict[str, Any]
) -> Tuple[Dict[str, Any], str]:
"""
Handles cache settings dependencies for a behavior.
Parameters:
context (Dict[str, Any]): The context dictionary containing rule information.
azion_resources (AzionResource): The Azion resource container.
options (Dict[str, Any]): The options dictionary containing cache settings information.
Returns:
Tuple[Dict[str, Any], str]: A tuple containing the Azion behavior and cache settings reference.
"""
azion_behavior = None
cache_settings_ref = None
parent_rule_name = context.get("parent_rule_name")
rule_name = context.get("rule_name")
behavior = options.get("behavior", "").upper()
if behavior in BEHAVIOR_CACHE_PHASE:
azion_behavior = {
"name": "bypass_cache_phase",
"enabled": True,
"target": {},
"phase": "request"
}
return azion_behavior, None
else:
# Handle cache settings dependencies
cache_setttings = context.get("cache_setting")
if cache_setttings is None:
_, cache_setttings = azion_resources.query_azion_resource_by_type(
'azion_edge_application_cache_setting', sanitize_name(parent_rule_name), match="prefix")
if cache_setttings is None:
_, cache_setttings = azion_resources.query_azion_resource_by_type(
'azion_edge_application_cache_setting', sanitize_name(rule_name), match="prefix")
if cache_setttings:
cache_settings_name = cache_setttings.get("name")
cache_settings_ref = f'azion_edge_application_cache_setting.{cache_settings_name}'
azion_behavior = {
"name": "set_cache_policy",
"enabled": True,
"target": {"target": cache_settings_ref + ".id"},
"description": f"Set cache policy to {options.get('name', '')}",
"phase": "request"
}
return azion_behavior, cache_settings_ref
def behavior_set_origin(
context: Dict[str, Any],
azion_resources: AzionResource,
options: Dict[str, Any]
) -> Tuple[Dict[str, Any], str]:
"""
Handles origin settings dependencies for a behavior.
Parameters:
context (Dict[str, Any]): The context dictionary containing rule information.
azion_resources (AzionResource): The Azion resource container.
options (Dict[str, Any]): The options dictionary containing origin settings information.
Returns:
Tuple[Dict[str, Any], str]: A tuple containing the Azion behavior and origin settings reference.
"""
azion_behavior = None
origin_settings_ref = None
rule_name = context.get("rule_name")
parent_rule_name = context.get("parent_rule_name", "unamed")
# Handle origin settings dependencies
origin_settings = context.get("origin")
if origin_settings is None:
_, origin_settings = azion_resources.query_azion_resource_by_type(
"azion_edge_application_origin",
sanitize_name(parent_rule_name), match="prefix")
if origin_settings is None:
_, origin_settings = azion_resources.query_azion_resource_by_type(
"azion_edge_application_origin",
sanitize_name(rule_name), match="prefix")
if origin_settings is None:
origin_settings = azion_resources.query_azion_origin_by_address(options.get("hostname", ""))
if origin_settings:
origin_settings_name = origin_settings.get("name")
origin_settings_ref = f'azion_edge_application_origin.{origin_settings_name}'
azion_behavior = {
"name": "set_origin",
"enabled": True,
"target": {"target": origin_settings_ref + ".id"},
"description": f"Set origin to {options.get('name', '')}",
"phase": "request",
"akamai_behavior": "setOrigin"
}
return azion_behavior, origin_settings_ref
def behavior_capture_match_groups(
options: Dict[str, Any],
mapping: Dict[str, Any],
behavior: Dict[str, Any]
) -> Tuple[Dict[str, Any], str]:
"""
Handles capture match groups dependencies for a behavior.
Parameters:
options (Dict[str, Any]): The options dictionary containing capture match groups information.
mapping (Dict[str, Any]): The mapping dictionary containing the behavior information.
behavior (Dict[str, Any]): The behavior dictionary containing the behavior information.
Returns:
Tuple[Dict[str, Any], str]: A tuple containing the Azion behavior and capture match groups reference.
"""
azion_behavior = None
required_fields = {
"captured_array": options.get("variableName"),
"regex": options.get("regex")
}
missing_fields = {k: v for k, v in required_fields.items() if not v}
if missing_fields:
logging.warning(f"Behavior '{mapping['azion_behavior']}' is missing required fields: {missing_fields}")
return azion_behavior, None
regex_value = replace_variables(options.get('regex')).replace('/', r'\/').replace('.', r'\\.')
random_number = random.randint(1000, 9999)
captured_array = options.get("variableName",f"var{random_number}")[:10]
subject = map_variable(options.get("variableValue"))
azion_behavior = {
"name": mapping["azion_behavior"],
"enabled": True,
"description": behavior.get(
"description",
"Behavior capture_match_groups, variableName: " + options.get("variableName", "")
),
"target": {
"captured_array": f'"{captured_array}"',
"subject": f'{subject}',
"regex": f"\"(.*)\\\\/{regex_value}\"",
}
}
return azion_behavior, None
def process_behaviors(
azion_resources: AzionResource,
behaviors: List[Dict[str, Any]],
context: Dict[str, Any],
rule_name: str,
parent_rule_name: str = None
) -> Tuple[List[Dict[str, Any]], Set[str]]:
"""
Process and map Akamai behaviors to Azion-compatible behaviors.
Parameters:
azion_resources (AzionResource): The Azion resource container.
behaviors (List[Dict[str, Any]]): List of Akamai behaviors.
context (Dict[str, Any]): The context dictionary containing rule information.
rule_name (str): The name of the rule.
parent_rule_name (str): The name of the parent rule.
Returns:
Tuple[List[Dict[str, Any]], Set[str]]: A tuple containing a list of Azion-compatible behaviors and a set of dependencies.
"""
if not behaviors:
return [], set()
azion_behaviors = []
seen_behaviors = set() # Track unique behaviors
cache_policy_options = {} # Collect all cache policy related options
depends_on = set()
parent_rule_name = context.get("parent_rule_name", rule_name)
logging.info(f"[rules_engine][process_behaviors] Rule = '{rule_name}', Parent rule = '{parent_rule_name}'")
logging.info(f'[rules_engine][process_behaviors] Processing {len(behaviors)} behaviors')
for behavior in behaviors:
ak_behavior_name = behavior.get("name")
if not ak_behavior_name or ak_behavior_name not in MAPPING.get("behaviors", {}):
logging.warning(f"[rules_engine][process_behaviors] Unmapped behavior: {ak_behavior_name}")
logging.debug(f"[rules_engine][process_behaviors] Behavior options: {behavior.get('options', {})}")
continue
mapping = MAPPING["behaviors"][ak_behavior_name]
options = behavior.get("options", {})
# Handle behavior name
if callable(mapping.get("azion_behavior")):
try:
behavior_name = mapping["azion_behavior"](options)
except ValueError as e:
logging.error(f"[rules_engine][process_behaviors] Error processing azion_behavior in behavior '{ak_behavior_name}': {e}")
else:
behavior_name = mapping["azion_behavior"]
if behavior_name is None:
logging.debug(f"[rules_engine][process_behaviors] Behavior '{ak_behavior_name}' has no azion_behavior. Skipping.")
continue
logging.info(f"[rules_engine][process_behaviors] Mapping from '{ak_behavior_name}' to '{behavior_name}'")
# Skip behaviors that are explicitly disabled
if "enabled" in options and options["enabled"] is False:
logging.debug(f"[rules_engine][process_behaviors] Behavior '{behavior_name}' is explicitly disabled. Skipping.")
continue
# Handle special behavior: set_cache_policy
if mapping["azion_behavior"] == "set_cache_policy":
azion_behavior, cache_settings_ref = behavior_cache_setting(context, azion_resources, options)
unique_key = behavior_key(azion_behavior)
# Unique key for set_cache_policy
if unique_key in seen_behaviors:
logging.debug(f"[rules_engine][process_behaviors] already processed behavior {behavior_name}, key {unique_key}. Skipping.")
continue
if azion_behavior:
if cache_settings_ref is not None:
depends_on.add(cache_settings_ref)
azion_behaviors.append(azion_behavior)
seen_behaviors.add(unique_key)
else:
logging.debug(f"[rules_engine][process_behaviors] Cache settings not found for rule '{rule_name}'. Skipping.")
continue
# Handle special behavior: set_origin
if mapping["azion_behavior"] == "set_origin":
azion_behavior, origin_settings_ref = behavior_set_origin(context, azion_resources, options)
unique_key = behavior_key(azion_behavior)
# Unique key for set_origin
if unique_key in seen_behaviors:
logging.debug(f"[rules_engine][process_behaviors] already processed behavior {behavior_name}, key {unique_key}. Skipping.")
continue
if azion_behavior:
azion_behaviors.append(azion_behavior)
seen_behaviors.add(unique_key)
depends_on.add(origin_settings_ref)
else:
logging.debug(f"[rules_engine][process_behaviors] Origin settings not found for rule '{rule_name}'. Skipping.")
continue
# Handle compression
if options.get("compress", True):
azion_behavior = {
"name": "enable_gzip",
"enabled": True,
"description": "Compress content",
"target": {},
}
unique_key = behavior_key(azion_behavior)
# Unique key for enable_gzip
if unique_key in seen_behaviors:
logging.debug(f"[rules_engine][process_behaviors] already processed behavior {behavior_name}, key {unique_key}. Skipping.")
continue
azion_behaviors.append(azion_behavior)
seen_behaviors.add(unique_key)
# Handle true client ip (add_request_header)
if options.get("enableTrueClientIp", False) == True:
trueClientIpHeader = options.get("trueClientIpHeader", "")
if trueClientIpHeader:
azion_behavior = {
"name": "add_request_header",
"enabled": True,
"description": f"Add host header to {trueClientIpHeader}",
"target": { "target": '"' + f'{trueClientIpHeader}: ' + "$${remote_addr}" + '"' },
"phase": "request",
"akamai_behavior": "trueClientIpHeader"
}
unique_key = behavior_key(azion_behavior)
# Unique key for add_request_header
if unique_key in seen_behaviors:
logging.debug(f"[rules_engine][process_behaviors] already processed behavior {behavior_name}, key {unique_key}. Skipping.")
continue
azion_behaviors.append(azion_behavior)
seen_behaviors.add(unique_key)
continue
# Handle special behavior: set_host_header
if mapping["azion_behavior"] == "set_host_header":
host_header = map_forward_host_header(options)
azion_behavior = {
"name": "set_host_header",
"enabled": True,
"description": behavior.get("description", f"Set host header to {host_header}"),
"target": { "host_header": host_header },
"phase": "request"
}
unique_key = behavior_key(azion_behavior)
# Unique key for set_host_header
if unique_key in seen_behaviors:
logging.debug(f"[rules_engine][process_behaviors] already processed behavior {behavior_name}, key {unique_key}. Skipping.")
continue
azion_behaviors.append(azion_behavior)
seen_behaviors.add(unique_key)
continue
# Handle special behavior: capture_match_groups
if mapping["azion_behavior"] == "capture_match_groups":
azion_behavior, _ = behavior_capture_match_groups(options, mapping, behavior)
if azion_behavior:
# Create a unique key to track this behavior
unique_key = behavior_key(azion_behavior)
if unique_key in seen_behaviors:
logging.debug(f"[rules_engine][process_behaviors] already processed behavior {behavior_name}, key {unique_key}. Skipping.")
continue
azion_behaviors.append(azion_behavior)
seen_behaviors.add(unique_key)
continue
# Skip if we've already processed this behavior type
if behavior_name in seen_behaviors:
logging.debug(f"[rules_engine][process_behaviors] already processed behavior {behavior_name}, key {unique_key}. Skipping.")
continue
azion_behavior = {
"name": behavior_name,
"enabled": behavior.get("options", {}).get("enabled", True),
"description": behavior.get("description", f"Behavior for {behavior_name}"),
"phase": mapping.get("phase", "request")
}
# Process target if present
if "target" in mapping:
target = {}
if isinstance(mapping["target"], dict):
for target_key, option_key in mapping["target"].items():
try:
value = option_key(options) if callable(option_key) else options.get(option_key)
if value is not None:
target[target_key] = value
else:
target[target_key] = f'"{option_key}"'
except ValueError as e:
logging.error(
f"[rules_engine][process_behaviors] Error processing target for key '{target_key}' in behavior '{behavior_name}': {e}"
)
elif isinstance(mapping["target"], str):
try:
value = options.get(mapping["target"])
if value is not None:
target = value
except ValueError as e:
logging.error(f"[rules_engine][process_behaviors] Error accessing target for behavior '{behavior_name}': {e}")
# Special handling for origin
if behavior_name == "set_origin":
target["origin_type"] = map_origin_type(options.get("originType", "CUSTOMER"))
if target: # Only add target if we have values
azion_behavior["target"] = target
unique_key = behavior_key(azion_behavior)
if unique_key in seen_behaviors:
logging.debug(f"[rules_engine][process_behaviors] already processed behavior {behavior_name}, key {unique_key}. Skipping.")
continue
azion_behaviors.append(azion_behavior)
seen_behaviors.add(unique_key)
# Add consolidated cache policy if we collected any optionss
if cache_policy_options:
azion_behaviors.append({
"name": "set_cache_policy",
"enabled": True,
"target": cache_policy_options,
"description": "Cache policy consolidated from multiple behaviors"
})
return azion_behaviors, depends_on