import time import os import requests from locust.stats import sort_stats TARGET_ENVIRONMENT = os.environ.get("TARGET_ENVIRONMENT") DD_CLIENT_API_KEY = os.environ.get("DD_API_KEY") METRICS = [ "num_requests", "num_failures", "median_response_time", "avg_response_time", "min_response_time", "max_response_time", "avg_content_length", "total_rps", "total_fail_per_sec", "fail_ratio", ] METRICS_PREFIX = "core_load_tester" SERIES_ENDPOINT = "https://api.datadoghq.com/api/v2/series" def send_stats_to_datadog(environment): if not DD_CLIENT_API_KEY: print("No api key for Datadog") return stats = environment.runner.stats timestamp = int(time.time()) host = TARGET_ENVIRONMENT or environment.host endpoints_stats = sort_stats(stats.entries) total_stats = stats.total for metric in METRICS: send_metric_to_datadog( f"total.{metric}", getattr(total_stats, metric), timestamp, host, [f"host:{host}"], ) for endpoint_stats in endpoints_stats: for metric in METRICS: send_metric_to_datadog( f"by_endpoint.{metric}", getattr(endpoint_stats, metric), timestamp, host, [ f"host:{host}", f"endpoint:{escape_value(endpoint_stats.name)}", f"method:{endpoint_stats.method}", f"method_endpoint:{endpoint_stats.method} {escape_value(endpoint_stats.name)}", ], ) def escape_value(value): return value.replace("{", "_").replace("}", "_") def send_metric_to_datadog(name, value, timestamp, host, tags): # https://docs.datadoghq.com/api/latest/metrics/#submit-metrics-v2 payload = { "series": [ { "metric": f"{METRICS_PREFIX}.{name}", "type": 3, # gauge "interval": 0, "points": [{"timestamp": timestamp, "value": value}], "resources": [{"name": host, "type": "host"}], "tags": tags, } ] } resp = requests.post( SERIES_ENDPOINT, headers={"DD-API-KEY": DD_CLIENT_API_KEY}, json=payload ) if not resp.ok: print(f"Error sending Datadog metric: {resp.text}") print(payload) else: print( f"Submitted Datadog metric: {METRICS_PREFIX}.{name}, {value}, {host}, {tags}" )