|
| 1 | +import boto3 |
| 2 | +from prometheus_client import Gauge, start_http_server |
| 3 | +import time |
| 4 | +from datetime import datetime,timedelta |
| 5 | +import os |
| 6 | +import logging |
| 7 | +from pythonjsonlogger import jsonlogger |
| 8 | + |
| 9 | +logging.basicConfig(level=logging.INFO) |
| 10 | + |
| 11 | +logger = logging.getLogger() |
| 12 | + |
| 13 | +logHandler = logging.StreamHandler() |
| 14 | +formatter = jsonlogger.JsonFormatter() |
| 15 | +logHandler.setFormatter(formatter) |
| 16 | +logger.addHandler(logHandler) |
| 17 | + |
| 18 | +logger.info({"state": "starting"}) |
| 19 | + |
| 20 | +# Create a CloudWatch client |
| 21 | +cloudwatch = boto3.client('cloudwatch', region_name=os.environ.get('AWS_REGION')) |
| 22 | + |
| 23 | +# Create Prometheus metrics |
| 24 | +cpu_utilization_gauge = Gauge('AWS_RDS_CPUUtilization', 'CPU Utilization of RDS instance', ['DBInstanceIdentifier']) |
| 25 | +database_connections_gauge = Gauge('AWS_RDS_DatabaseConnections', 'Database Connections of RDS instance', ['DBInstanceIdentifier']) |
| 26 | +volume_bytes_used_gauge = Gauge('AWS_RDS_VolumeBytesUsed', 'Volume Bytes Used of RDS instance', ['DBInstanceIdentifier']) |
| 27 | +cpu_credits_gauge = Gauge('AWS_RDS_CPUcredits', 'CPU credits of RDS instance', ['DBInstanceIdentifier']) |
| 28 | +freeable_memory_gauge = Gauge('AWS_RDS_FreeableMemory', 'Freeable Memory of RDS instance', ['DBInstanceIdentifier']) |
| 29 | + |
| 30 | +# Start the HTTP server to expose the metrics |
| 31 | +start_http_server(8000) |
| 32 | + |
| 33 | +def parse_time_string(time_string): |
| 34 | + value = int(time_string[:-1]) |
| 35 | + unit = time_string[-1] |
| 36 | + |
| 37 | + if unit == 's': |
| 38 | + return timedelta(seconds=value) |
| 39 | + elif unit == 'm': |
| 40 | + return timedelta(minutes=value) |
| 41 | + elif unit == 'h': |
| 42 | + return timedelta(hours=value) |
| 43 | + else: |
| 44 | + raise ValueError(f"Unknown time unit: {unit}") |
| 45 | + |
| 46 | + |
| 47 | +def get_metric_value(metric_name, db_instance_id): |
| 48 | + response = cloudwatch.get_metric_data( |
| 49 | + MetricDataQueries=[ |
| 50 | + { |
| 51 | + 'Id': 'm1', |
| 52 | + 'MetricStat': { |
| 53 | + 'Metric': { |
| 54 | + 'Namespace': 'AWS/RDS', |
| 55 | + 'MetricName': metric_name, |
| 56 | + 'Dimensions': [ |
| 57 | + { |
| 58 | + 'Name': 'DBInstanceIdentifier', |
| 59 | + 'Value': db_instance_id |
| 60 | + }, |
| 61 | + ] |
| 62 | + }, |
| 63 | + 'Period': 300, |
| 64 | + 'Stat': 'Average', |
| 65 | + }, |
| 66 | + 'ReturnData': True, |
| 67 | + }, |
| 68 | + ], |
| 69 | + StartTime=(datetime.now() - parse_time_string(os.environ.get('METRICS_SCRAPE_INTERVAL'))).timestamp(), |
| 70 | + EndTime=datetime.now().timestamp(), |
| 71 | + ) |
| 72 | + |
| 73 | + return response['MetricDataResults'][0]['Values'][0] if response['MetricDataResults'][0]['Values'] else None |
| 74 | + |
| 75 | +def collect_metrics(): |
| 76 | + rds_client = boto3.client('rds', region_name=os.environ.get('AWS_REGION')) |
| 77 | + instances = rds_client.describe_db_instances() |
| 78 | + |
| 79 | + for instance in instances['DBInstances']: |
| 80 | + db_instance_id = instance['DBInstanceIdentifier'] |
| 81 | + logger.info({"state": "processing", "db_instance_id": db_instance_id, "message": "Processing rds instance"}) |
| 82 | + |
| 83 | + cpu_utilization = get_metric_value('CPUUtilization', db_instance_id) |
| 84 | + if cpu_utilization is not None: |
| 85 | + cpu_utilization_gauge.labels(DBInstanceIdentifier=db_instance_id).set(cpu_utilization) |
| 86 | + |
| 87 | + database_connections = get_metric_value('DatabaseConnections', db_instance_id) |
| 88 | + if database_connections is not None: |
| 89 | + database_connections_gauge.labels(DBInstanceIdentifier=db_instance_id).set(database_connections) |
| 90 | + |
| 91 | + volume_bytes_used = get_metric_value('VolumeBytesUsed', db_instance_id) |
| 92 | + if volume_bytes_used is not None: |
| 93 | + volume_bytes_used_gauge.labels(DBInstanceIdentifier=db_instance_id).set(volume_bytes_used) |
| 94 | + |
| 95 | + cpu_credits = get_metric_value('CPUCreditBalance', db_instance_id) |
| 96 | + if cpu_credits is not None: |
| 97 | + cpu_credits_gauge.labels(DBInstanceIdentifier=db_instance_id).set(cpu_credits) |
| 98 | + |
| 99 | + freeable_memory = get_metric_value('FreeableMemory', db_instance_id) |
| 100 | + if freeable_memory is not None: |
| 101 | + freeable_memory_gauge.labels(DBInstanceIdentifier=db_instance_id).set(freeable_memory) |
| 102 | +while True: |
| 103 | + collect_metrics() |
| 104 | + time.sleep(60) # Collect metrics every minute |
0 commit comments