|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import json |
| 16 | +import logging |
| 17 | +import os |
| 18 | +from awslabs.cloudwatch_mcp_server.cloudwatch_metrics.constants import COMPARISON_OPERATOR_ANOMALY |
| 19 | +from jinja2 import Environment, FileSystemLoader, select_autoescape |
| 20 | +from typing import Any, Dict |
| 21 | + |
| 22 | + |
| 23 | +logger = logging.getLogger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +class CloudFormationTemplateGenerator: |
| 27 | + """Generate CloudFormation JSON for CloudWatch Anomaly Detection Alarms using templates.""" |
| 28 | + |
| 29 | + ANOMALY_DETECTION_ALARM_TEMPLATE = 'anomaly_detection_alarm.json' |
| 30 | + |
| 31 | + def __init__(self): |
| 32 | + """Initialize the CloudFormation template generator.""" |
| 33 | + template_dir = os.path.join(os.path.dirname(__file__), 'templates') |
| 34 | + self.env = Environment( |
| 35 | + loader=FileSystemLoader(template_dir), |
| 36 | + autoescape=select_autoescape(['html', 'xml', 'json']), |
| 37 | + ) |
| 38 | + |
| 39 | + def generate_template(self, alarm_data: Dict[str, Any]) -> Dict[str, Any]: |
| 40 | + """Generate CFN template for a single CloudWatch Alarm.""" |
| 41 | + if not self._is_anomaly_detection_alarm(alarm_data): |
| 42 | + return {} |
| 43 | + |
| 44 | + # Process alarm data and add computed fields |
| 45 | + formatted_data = self._format_anomaly_detection_alarm_data(alarm_data) |
| 46 | + alarm_json = self._generate_anomaly_detection_alarm_resource(formatted_data) |
| 47 | + resources = json.loads(alarm_json) |
| 48 | + |
| 49 | + final_template = { |
| 50 | + 'AWSTemplateFormatVersion': '2010-09-09', |
| 51 | + 'Description': 'CloudWatch Alarms and Anomaly Detectors', |
| 52 | + 'Resources': resources, |
| 53 | + } |
| 54 | + |
| 55 | + return final_template |
| 56 | + |
| 57 | + def _format_anomaly_detection_alarm_data(self, alarm_data: Dict[str, Any]) -> Dict[str, Any]: |
| 58 | + """Sanitise alarm data and add computed fields.""" |
| 59 | + formatted_data = alarm_data.copy() |
| 60 | + |
| 61 | + # Generate alarm name if not provided |
| 62 | + if 'alarmName' not in formatted_data: |
| 63 | + metric_name = alarm_data.get('metricName', 'Alarm') |
| 64 | + namespace = alarm_data.get('namespace', '') |
| 65 | + formatted_data['alarmName'] = self._generate_alarm_name(metric_name, namespace) |
| 66 | + |
| 67 | + # Generate resource key (sanitized alarm name for CloudFormation resource) |
| 68 | + formatted_data['resourceKey'] = self._sanitize_resource_name(formatted_data['alarmName']) |
| 69 | + |
| 70 | + # Process threshold value |
| 71 | + threshold = alarm_data.get('threshold', {}) |
| 72 | + formatted_data['sensitivity'] = threshold.get('sensitivity', 2) |
| 73 | + |
| 74 | + # Set defaults |
| 75 | + formatted_data.setdefault( |
| 76 | + 'alarmDescription', 'CloudWatch alarm generated by CloudWatch MCP server.' |
| 77 | + ) |
| 78 | + formatted_data.setdefault('statistic', 'Average') |
| 79 | + formatted_data.setdefault('period', 300) |
| 80 | + formatted_data.setdefault('evaluationPeriods', 2) |
| 81 | + formatted_data.setdefault('datapointsToAlarm', 2) |
| 82 | + formatted_data.setdefault('comparisonOperator', COMPARISON_OPERATOR_ANOMALY) |
| 83 | + formatted_data.setdefault('treatMissingData', 'missing') |
| 84 | + formatted_data.setdefault('dimensions', []) |
| 85 | + |
| 86 | + return formatted_data |
| 87 | + |
| 88 | + def _generate_anomaly_detection_alarm_resource(self, alarm_data: Dict[str, Any]) -> str: |
| 89 | + """Generate CloudWatch anomaly detection alarm template using Jinja2. |
| 90 | +
|
| 91 | + Args: |
| 92 | + alarm_data: Alarm configuration data |
| 93 | +
|
| 94 | + Returns: |
| 95 | + str: Generated CloudFormation template |
| 96 | + """ |
| 97 | + template = self.env.get_template(self.ANOMALY_DETECTION_ALARM_TEMPLATE) |
| 98 | + alarm_resource = template.render(**alarm_data) |
| 99 | + |
| 100 | + return alarm_resource |
| 101 | + |
| 102 | + def _is_anomaly_detection_alarm(self, alarm_data: Dict[str, Any]) -> bool: |
| 103 | + return alarm_data.get('comparisonOperator') == COMPARISON_OPERATOR_ANOMALY |
| 104 | + |
| 105 | + def _generate_alarm_name(self, metric_name: str, namespace: str) -> str: |
| 106 | + """Generate alarm name from metric name and namespace.""" |
| 107 | + return f'{metric_name.capitalize()}{namespace.replace("/", "").replace("AWS", "")}Alarm' |
| 108 | + |
| 109 | + def _sanitize_resource_name(self, name: str) -> str: |
| 110 | + """Sanitize name for CloudFormation resource key.""" |
| 111 | + sanitized = name.replace('-', '').replace('_', '').replace('/', '').replace(' ', '') |
| 112 | + # Validate CloudFormation naming requirements |
| 113 | + if not sanitized or not sanitized[0].isalpha(): |
| 114 | + logger.warning(f'Invalid resource name: {sanitized} (must start with letter)') |
| 115 | + sanitized = 'Resource' + sanitized |
| 116 | + if len(sanitized) > 255: |
| 117 | + logger.warning(f'Resource name too long ({len(sanitized)} chars), truncating') |
| 118 | + sanitized = sanitized[:255] |
| 119 | + return sanitized |
0 commit comments