mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
* fix(cloudwatch): decompress gzip JSON PutMetricData bodies The AWS CLI and the SDKs that speak JSON 1.0 to CloudWatch gzip a PutMetricData body of 10 KiB or more and send Content-Encoding: gzip. AwsJsonController binds the body as a String, so Floci read the compressed bytes as text and every such request failed with HTTP 400 SerializationException. The metrics were never stored. Add a reader interceptor that decompresses that one operation's body when the controller reads it. It runs after every request filter, so the signature is still verified over the compressed bytes the client signed, and IAM still decides the request from X-Amz-Target first, which is sound because nothing in that decision comes from the body. The decompressed body is bounded by the decoder the CBOR protocol already uses: past 10 MiB it returns HTTP 413 PayloadTooLargeException, and a body that cannot be decompressed returns HTTP 400 InvalidRequestException, both in the controller's JSON error format. A name binding keeps the interceptor on AwsJsonController alone, so every other resource reads its body as before. In the native image a global reader interceptor breaks the tag endpoints that resources inherit from AbstractTagsController, because Quarkus REST then looks their methods up reflectively. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudwatch): publish a compressed metric batch through boto3 botocore gzips a PutMetricData body of 10 KiB or more, and with the pinned boto3 it calls CloudWatch over JSON 1.0. The Python compatibility suite only ever sent a handful of datums, so it never sent a compressed request. Send a 100-datum batch, check that botocore sent it as JSON 1.0 with Content-Encoding: gzip, and check that all 100 metrics are listed afterwards. Checking the content type keeps the test from passing through the CBOR path, which already decompressed gzip, should a later botocore prefer CBOR. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * chore(cloudwatch): reuse signed IAM test users --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
292 lines
11 KiB
Python
292 lines
11 KiB
Python
"""CloudWatch Metrics integration tests."""
|
|
|
|
import datetime
|
|
|
|
import pytest
|
|
|
|
|
|
class TestCloudWatchMetrics:
|
|
"""Test CloudWatch metrics operations."""
|
|
|
|
def test_put_metric_data(self, cloudwatch_client, unique_name):
|
|
"""Test PutMetricData writes metric."""
|
|
namespace = f"TestApp/PytestMetrics/{unique_name}"
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
|
|
cloudwatch_client.put_metric_data(
|
|
Namespace=namespace,
|
|
MetricData=[
|
|
{
|
|
"MetricName": "RequestCount",
|
|
"Value": 42.0,
|
|
"Unit": "Count",
|
|
"Timestamp": now,
|
|
}
|
|
],
|
|
)
|
|
# If no exception, test passes
|
|
|
|
def test_put_metric_data_with_dimensions(self, cloudwatch_client, unique_name):
|
|
"""Test PutMetricData with dimensions."""
|
|
namespace = f"TestApp/PytestMetrics/{unique_name}"
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
|
|
cloudwatch_client.put_metric_data(
|
|
Namespace=namespace,
|
|
MetricData=[
|
|
{
|
|
"MetricName": "Latency",
|
|
"Value": 125.5,
|
|
"Unit": "Milliseconds",
|
|
"Timestamp": now,
|
|
"Dimensions": [{"Name": "Host", "Value": "web01"}],
|
|
}
|
|
],
|
|
)
|
|
# If no exception, test passes
|
|
|
|
def test_list_metrics(self, cloudwatch_client, unique_name):
|
|
"""Test ListMetrics returns written metrics."""
|
|
namespace = f"TestApp/PytestMetrics/{unique_name}"
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
|
|
cloudwatch_client.put_metric_data(
|
|
Namespace=namespace,
|
|
MetricData=[
|
|
{"MetricName": "RequestCount", "Value": 42.0, "Unit": "Count", "Timestamp": now},
|
|
{"MetricName": "Latency", "Value": 125.5, "Unit": "Milliseconds", "Timestamp": now},
|
|
],
|
|
)
|
|
|
|
response = cloudwatch_client.list_metrics(Namespace=namespace)
|
|
has_rc = any(m["MetricName"] == "RequestCount" for m in response["Metrics"])
|
|
has_lat = any(m["MetricName"] == "Latency" for m in response["Metrics"])
|
|
assert has_rc and has_lat
|
|
|
|
def test_list_metrics_namespace_isolation(self, cloudwatch_client, unique_name):
|
|
"""Test ListMetrics respects namespace isolation."""
|
|
namespace_a = f"TestApp/PytestMetricsA/{unique_name}"
|
|
namespace_b = f"TestApp/PytestMetricsB/{unique_name}"
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
|
|
cloudwatch_client.put_metric_data(
|
|
Namespace=namespace_a,
|
|
MetricData=[{"MetricName": "MetricA", "Value": 1.0, "Unit": "Count", "Timestamp": now}],
|
|
)
|
|
cloudwatch_client.put_metric_data(
|
|
Namespace=namespace_b,
|
|
MetricData=[{"MetricName": "MetricB", "Value": 1.0, "Unit": "Count", "Timestamp": now}],
|
|
)
|
|
|
|
response_a = cloudwatch_client.list_metrics(Namespace=namespace_a)
|
|
response_b = cloudwatch_client.list_metrics(Namespace=namespace_b)
|
|
|
|
no_a_in_b = all(m["Namespace"] != namespace_a for m in response_b["Metrics"])
|
|
no_b_in_a = all(m["Namespace"] != namespace_b for m in response_a["Metrics"])
|
|
assert no_a_in_b and no_b_in_a
|
|
|
|
def test_get_metric_statistics(self, cloudwatch_client, unique_name):
|
|
"""Test GetMetricStatistics returns aggregated data."""
|
|
namespace = f"TestApp/PytestMetrics/{unique_name}"
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
|
|
# Put 5 data points
|
|
data_points = [
|
|
{
|
|
"MetricName": "CPUUtil",
|
|
"Value": v,
|
|
"Unit": "Percent",
|
|
"Timestamp": now - datetime.timedelta(seconds=s),
|
|
}
|
|
for v, s in [(10.0, 250), (20.0, 200), (30.0, 150), (40.0, 100), (50.0, 50)]
|
|
]
|
|
cloudwatch_client.put_metric_data(Namespace=namespace, MetricData=data_points)
|
|
|
|
response = cloudwatch_client.get_metric_statistics(
|
|
Namespace=namespace,
|
|
MetricName="CPUUtil",
|
|
StartTime=now - datetime.timedelta(hours=1),
|
|
EndTime=now + datetime.timedelta(seconds=60),
|
|
Period=3600,
|
|
Statistics=["Sum", "SampleCount"],
|
|
)
|
|
|
|
assert len(response["Datapoints"]) > 0
|
|
total_sum = sum(dp["Sum"] for dp in response["Datapoints"])
|
|
total_sc = sum(dp["SampleCount"] for dp in response["Datapoints"])
|
|
assert abs(total_sum - 150.0) < 0.001
|
|
assert abs(total_sc - 5.0) < 0.001
|
|
|
|
def test_put_metric_data_with_statistic_values(self, cloudwatch_client, unique_name):
|
|
"""Test PutMetricData with pre-calculated StatisticValues."""
|
|
namespace = f"TestApp/StatisticValues/{unique_name}"
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
|
|
# Put metric data with pre-calculated statistics
|
|
cloudwatch_client.put_metric_data(
|
|
Namespace=namespace,
|
|
MetricData=[
|
|
{
|
|
"MetricName": "AggregatedMetric",
|
|
"StatisticValues": {
|
|
"SampleCount": 5,
|
|
"Sum": 150.0,
|
|
"Minimum": 20.0,
|
|
"Maximum": 40.0,
|
|
},
|
|
"Unit": "Count",
|
|
}
|
|
],
|
|
)
|
|
|
|
# Query back the statistics
|
|
response = cloudwatch_client.get_metric_statistics(
|
|
Namespace=namespace,
|
|
MetricName="AggregatedMetric",
|
|
StartTime=now - datetime.timedelta(hours=1),
|
|
EndTime=now + datetime.timedelta(seconds=60),
|
|
Period=3600,
|
|
Statistics=["Sum", "Average", "Minimum", "Maximum", "SampleCount"],
|
|
)
|
|
|
|
assert response["Datapoints"]
|
|
dp = response["Datapoints"][0]
|
|
assert dp["Sum"] == 150.0
|
|
assert dp["SampleCount"] == 5
|
|
assert dp["Minimum"] == 20.0
|
|
assert dp["Maximum"] == 40.0
|
|
assert dp["Average"] == 30.0 # sum / sampleCount
|
|
|
|
def test_put_metric_data_compressed_batch(self, cloudwatch_client, unique_name):
|
|
"""Test a PutMetricData body past 10 KiB, which botocore sends gzip-compressed."""
|
|
namespace = f"TestApp/CompressedBatch/{unique_name}"
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
metric_data = [
|
|
{
|
|
"MetricName": "BatchRequests",
|
|
"Value": 1.0,
|
|
"Unit": "Count",
|
|
"Timestamp": now,
|
|
"Dimensions": [{"Name": "Host", "Value": f"host-{i:03d}-" + "x" * 60}],
|
|
}
|
|
for i in range(100)
|
|
]
|
|
names = ("Content-Encoding", "Content-Type")
|
|
sent = []
|
|
|
|
def record_headers(request, **kwargs):
|
|
sent.append({name: request.headers.get(name) for name in names})
|
|
|
|
event = "before-send.cloudwatch.PutMetricData"
|
|
cloudwatch_client.meta.events.register(event, record_headers)
|
|
try:
|
|
cloudwatch_client.put_metric_data(Namespace=namespace, MetricData=metric_data)
|
|
finally:
|
|
cloudwatch_client.meta.events.unregister(event, record_headers)
|
|
|
|
assert len(sent) == 1
|
|
headers = {name: v.decode() if isinstance(v, bytes) else v for name, v in sent[0].items()}
|
|
assert headers["Content-Encoding"] == "gzip"
|
|
# JSON 1.0 is the path this covers; a CBOR request would reach a decoder that predates it.
|
|
assert headers["Content-Type"] == "application/x-amz-json-1.0"
|
|
response = cloudwatch_client.list_metrics(Namespace=namespace, MetricName="BatchRequests")
|
|
assert len(response["Metrics"]) == 100
|
|
|
|
|
|
class TestCloudWatchAlarms:
|
|
"""Test CloudWatch alarm operations."""
|
|
|
|
def test_put_metric_alarm(self, cloudwatch_client, unique_name):
|
|
"""Test PutMetricAlarm creates an alarm."""
|
|
alarm_name = f"pytest-alarm-{unique_name}"
|
|
|
|
try:
|
|
cloudwatch_client.put_metric_alarm(
|
|
AlarmName=alarm_name,
|
|
MetricName="CPUUtilization",
|
|
Namespace="AWS/EC2",
|
|
Statistic="Average",
|
|
Period=60,
|
|
Threshold=80.0,
|
|
ComparisonOperator="GreaterThanThreshold",
|
|
EvaluationPeriods=1,
|
|
AlarmActions=["arn:aws:sns:us-east-1:000000000000:my-topic"],
|
|
)
|
|
# If no exception, test passes
|
|
finally:
|
|
cloudwatch_client.delete_alarms(AlarmNames=[alarm_name])
|
|
|
|
def test_describe_alarms(self, cloudwatch_client, unique_name):
|
|
"""Test DescribeAlarms returns alarm details."""
|
|
alarm_name = f"pytest-alarm-{unique_name}"
|
|
|
|
cloudwatch_client.put_metric_alarm(
|
|
AlarmName=alarm_name,
|
|
MetricName="CPUUtilization",
|
|
Namespace="AWS/EC2",
|
|
Statistic="Average",
|
|
Period=60,
|
|
Threshold=80.0,
|
|
ComparisonOperator="GreaterThanThreshold",
|
|
EvaluationPeriods=1,
|
|
)
|
|
|
|
try:
|
|
response = cloudwatch_client.describe_alarms(AlarmNames=[alarm_name])
|
|
alarms = response["MetricAlarms"]
|
|
assert any(a["AlarmName"] == alarm_name for a in alarms)
|
|
|
|
alarm = next(a for a in alarms if a["AlarmName"] == alarm_name)
|
|
assert alarm["StateValue"] == "INSUFFICIENT_DATA"
|
|
assert response["CompositeAlarms"] == []
|
|
assert response["LogAlarms"] == []
|
|
finally:
|
|
cloudwatch_client.delete_alarms(AlarmNames=[alarm_name])
|
|
|
|
def test_set_alarm_state(self, cloudwatch_client, unique_name):
|
|
"""Test SetAlarmState changes alarm state."""
|
|
alarm_name = f"pytest-alarm-{unique_name}"
|
|
|
|
cloudwatch_client.put_metric_alarm(
|
|
AlarmName=alarm_name,
|
|
MetricName="CPUUtilization",
|
|
Namespace="AWS/EC2",
|
|
Statistic="Average",
|
|
Period=60,
|
|
Threshold=80.0,
|
|
ComparisonOperator="GreaterThanThreshold",
|
|
EvaluationPeriods=1,
|
|
)
|
|
|
|
try:
|
|
cloudwatch_client.set_alarm_state(
|
|
AlarmName=alarm_name,
|
|
StateValue="ALARM",
|
|
StateReason="Threshold breached",
|
|
)
|
|
|
|
response = cloudwatch_client.describe_alarms(AlarmNames=[alarm_name])
|
|
assert response["MetricAlarms"][0]["StateValue"] == "ALARM"
|
|
finally:
|
|
cloudwatch_client.delete_alarms(AlarmNames=[alarm_name])
|
|
|
|
def test_delete_alarms(self, cloudwatch_client, unique_name):
|
|
"""Test DeleteAlarms removes alarms."""
|
|
alarm_name = f"pytest-alarm-{unique_name}"
|
|
|
|
cloudwatch_client.put_metric_alarm(
|
|
AlarmName=alarm_name,
|
|
MetricName="CPUUtilization",
|
|
Namespace="AWS/EC2",
|
|
Statistic="Average",
|
|
Period=60,
|
|
Threshold=80.0,
|
|
ComparisonOperator="GreaterThanThreshold",
|
|
EvaluationPeriods=1,
|
|
)
|
|
|
|
cloudwatch_client.delete_alarms(AlarmNames=[alarm_name])
|
|
|
|
response = cloudwatch_client.describe_alarms(AlarmNames=[alarm_name])
|
|
assert len(response["MetricAlarms"]) == 0
|