Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(logs): implement GetLogGroupFields from recent events (#1352)
ovsteenbc210066f931f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7c561ec7..59c21fa9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **CloudWatch Logs — `GetLogGroupFields`** — returns field names found in recent stored events with a rough presence percent (`logGroupFields: [{name, percent}]`). Honors `logGroupName` or `logGroupIdentifier`, optional `time` (±8 minutes) or the default last 15 minutes, system `@*` fields, and flattened JSON message keys.+### Fixed- **IoT — `CreateThingType` is idempotent for identical re-creates** — re-creating an existing thing type always returned `ResourceAlreadyExistsException`, so a retried request or a re-run provisioning script failed where AWS succeeds. The same `thingTypeProperties` now return the existing ids — absent, `null` and empty compare equal, `searchableAttributes` is unordered — and only a real mismatch keeps the `409`, as `CreateThing` already did. Contributed by @iot-rocket.- **EC2 — `RevokeSecurityGroupIngress` / `RevokeSecurityGroupEgress` honour `SecurityGroupRuleIds`** — both read only `IpPermissions`, so a revoke by rule id (as Terraform does) returned `Return=true` while removing nothing, leaving the rule in place forever. Ids now resolve against the group's `sgr-*` rules, which are removed with their tags and echoed in `revokedSecurityGroupRuleSet`; one unknown id rejects the whole call with `InvalidSecurityGroupRuleId.NotFound`. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex 8f5d1d93..235ea599 100644--- a/README.md+++ b/README.md@@ -408,7 +408,7 @@ subnet = ec2.create_subnet(| **ECS Task Metadata V4** | `GET /v4/<token>`, `GET /v4/<token>/task`, `GET /v4/<token>/stats`, `GET /v4/<token>/task/stats` | Per-container token injected as `ECS_CONTAINER_METADATA_URI_V4` on every container started by `RunTask`. `/task` returns sibling containers in the same task. Containers reach the gateway via `host.docker.internal` (mapped through `extra_hosts: host-gateway`, so it works on user-defined Docker networks); `networkMode: host` containers use loopback. Volatile by design (stripped on persistence, cleared by `/_ministack/reset`) || **ECS Container Credentials** | `GET /v2/credentials/<uuid>` | The path real ECS exposes via `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/<uuid>` (resolved by SDKs against `169.254.170.2`). MiniStack serves the same path on the gateway and returns the AWS-strict 5-field credentials document (`AccessKeyId`, `SecretAccessKey`, `Token`, `Expiration`, `RoleArn`) — distinct from the IMDS shape served at `/latest/meta-data/iam/security-credentials/<role>`. `RunTask` injects `AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_CONTAINER_AUTHORIZATION_TOKEN` (satisfies botocore's allow-list for non-loopback gateway hosts), and `AWS_ENDPOINT_URL` so unmodified SDKs inside the task fetch credentials and route service calls through MiniStack with no client config || **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, UpdateSecretVersionStage, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, ReplicateSecretToRegions, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | |-| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, GetLogRecord, StartLiveTail, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations, PutDestinationPolicy | `FilterLogEvents` supports `*`/`?` globs, multi-term AND, `-term` exclusion; `GetLogRecord` resolves Insights `@ptr` values issued at `PutLogEvents`; Insights CWLI subset: `fields`, chained `| filter` (`=` / `like /regex/`), `| sort @timestamp`, post-filter `| limit` as `min(query, API)`; `StartLiveTail` holds an AWS eventstream open until client disconnect and fans matching `PutLogEvents` into `sessionUpdate` frames (1s idle heartbeats; buffer of 10 updates, oldest dropped when full); use `Config(inject_host_prefix=False)` with a custom endpoint so boto3 does not prepend `stream-` to the hostname; `DescribeLogGroups` includes both `arn` (`:*`) and `logGroupArn` (no star) |+| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, GetLogRecord, GetLogGroupFields, StartLiveTail, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations, PutDestinationPolicy | `FilterLogEvents` supports `*`/`?` globs, multi-term AND, `-term` exclusion; `GetLogRecord` resolves Insights `@ptr` values issued at `PutLogEvents`; `GetLogGroupFields` scans recent stored events (optional `time` ±8m, else last 15m) and returns field names with rough presence percent, including system `@*` fields and flattened JSON message keys; Insights CWLI subset: `fields`, chained `| filter` (`=` / `like /regex/`), `| sort @timestamp`, post-filter `| limit` as `min(query, API)`; `StartLiveTail` holds an AWS eventstream open until client disconnect and fans matching `PutLogEvents` into `sessionUpdate` frames (1s idle heartbeats; buffer of 10 updates, oldest dropped when full); use `Config(inject_host_prefix=False)` with a custom endpoint so boto3 does not prepend `stream-` to the hostname; `DescribeLogGroups` includes both `arn` (`:*`) and `logGroupArn` (no star) |### Extended Servicesdiff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.pyindex af8787c3..5760708c 100644--- a/ministack/services/cloudwatch_logs.py+++ b/ministack/services/cloudwatch_logs.py@@ -3,7 +3,8 @@ CloudWatch Logs Service Emulator.JSON-based API via X-Amz-Target (Logs_20140328).Supports: CreateLogGroup, DeleteLogGroup, DescribeLogGroups,CreateLogStream, DeleteLogStream, DescribeLogStreams,- PutLogEvents, GetLogEvents, FilterLogEvents, GetLogRecord, StartLiveTail,+ PutLogEvents, GetLogEvents, FilterLogEvents, GetLogRecord, GetLogGroupFields,+ StartLiveTail,PutRetentionPolicy, DeleteRetentionPolicy,PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters,TagLogGroup, UntagLogGroup, ListTagsLogGroup,@@ -293,6 +294,7 @@ async def handle_request(method, path, headers, body, query_params):"GetLogEvents": _get_log_events,"FilterLogEvents": _filter_log_events,"GetLogRecord": _get_log_record,+ "GetLogGroupFields": _get_log_group_fields,"StartLiveTail": _start_live_tail,"PutRetentionPolicy": _put_retention_policy,"DeleteRetentionPolicy": _delete_retention_policy,@@ -646,6 +648,128 @@ def _get_log_record(data):return json_response({"logRecord": _public_log_record(record)})+_SYSTEM_LOG_GROUP_FIELDS = (+ "@timestamp",+ "@message",+ "@logStream",+ "@ptr",+ "@log",+)+++def _json_field_names(message: str) -> set[str]:+ """Discover dotted field names from a JSON object message (AWS-style flatten)."""+ try:+ parsed = json.loads(message)+ except (TypeError, ValueError, json.JSONDecodeError):+ return set()+ if not isinstance(parsed, dict):+ return set()++ names: set[str] = set()++ def walk(obj, prefix: str = "") -> None:+ if not isinstance(obj, dict):+ return+ for key, value in obj.items():+ name = f"{prefix}.{key}" if prefix else str(key)+ names.add(name)+ if isinstance(value, dict):+ walk(value, name)+ elif isinstance(value, list):+ # AWS Insights discovers array members with numeric index segments+ # (e.g. items.0.id), not flattened under the bare parent key.+ for idx, item in enumerate(value):+ indexed = f"{name}.{idx}"+ if isinstance(item, dict):+ names.add(indexed)+ walk(item, indexed)+ else:+ names.add(indexed)++ walk(parsed)+ return names+++def _resolve_log_group_fields_target(data) -> tuple[str | None, object | None]:+ """Return (group_name, error_response). Exactly one of name/identifier required."""+ name = data.get("logGroupName")+ identifier = data.get("logGroupIdentifier")+ has_name = bool(name)+ has_identifier = bool(identifier)+ if has_name == has_identifier:+ return None, error_response_json(+ "InvalidParameterException",+ "Exactly one of logGroupName or logGroupIdentifier must be specified",+ 400,+ )+ if has_name:+ return name, None+ if identifier.startswith("arn:") or ":log-group:" in identifier:+ resolved = _log_group_name_from_identifier_arn(identifier)+ if not resolved:+ return None, error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {identifier}",+ 400,+ )+ return resolved, None+ return identifier, None+++def _get_log_group_fields(data):+ """Return field names present in recent events, with rough presence percent.++ Time window matches AWS: optional ``time`` (epoch seconds) searches ±8 minutes+ around that center; otherwise the most recent 15 minutes. JSON object messages+ contribute flattened dotted keys; system ``@*`` fields are counted when present+ on the stored Insights record.+ """+ group_name, err = _resolve_log_group_fields_target(data)+ if err is not None:+ return err+ if group_name not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {group_name}",+ 400,+ )++ if data.get("time") is not None:+ center = int(data["time"])+ start_s = center - 8 * 60+ end_s = center + 8 * 60+ else:+ # _collect_query_records takes epoch seconds and uses end_s*1000 as an+ # inclusive ms bound. Flooring "now" to seconds would drop events in the+ # current partial second (timestamp > end_s*1000), so extend end by 1s.+ end_s = int(time.time()) + 1+ start_s = end_s - 15 * 60++ records = _collect_query_records([group_name], start_s, end_s)+ total = len(records)+ if total == 0:+ return json_response({"logGroupFields": []})++ counts: dict[str, int] = {}+ for record in records:+ present: set[str] = set()+ for field in _SYSTEM_LOG_GROUP_FIELDS:+ if field in record and record.get(field) is not None:+ present.add(field)+ present.update(_json_field_names(record.get("@message", "")))+ for field in present:+ counts[field] = counts.get(field, 0) + 1++ fields = []+ for name, count in counts.items():+ percent = int(round(100.0 * count / total))+ percent = max(0, min(100, percent))+ fields.append({"name": name, "percent": percent})+ fields.sort(key=lambda item: (-item["percent"], item["name"]))+ return json_response({"logGroupFields": fields})++# ---------------------------------------------------------------------------# Live Tail (StartLiveTail eventstream)# ---------------------------------------------------------------------------diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.pyindex fb2b3979..96f7bcd0 100644--- a/tests/test_cloudwatch_logs.py+++ b/tests/test_cloudwatch_logs.py@@ -368,6 +368,100 @@ def test_logs_get_log_record_round_trip(logs):assert "_timestamp_ms" not in record+def test_logs_get_log_group_fields_json_and_system(logs):+ """GetLogGroupFields discovers system @* fields and JSON keys with rough percent."""+ group = f"/intg/get-log-group-fields/{_uuid_mod.uuid4().hex[:8]}"+ stream = "stream-a"+ now_ms = int(time.time() * 1000)+ logs.create_log_group(logGroupName=group)+ logs.create_log_stream(logGroupName=group, logStreamName=stream)+ logs.put_log_events(+ logGroupName=group,+ logStreamName=stream,+ logEvents=[+ {+ "timestamp": now_ms - 1000,+ "message": json.dumps({"type": "a", "nested": {"level": 1}}),+ },+ {+ "timestamp": now_ms,+ "message": json.dumps({"type": "b", "duration": 13}),+ },+ ],+ )++ resp = logs.get_log_group_fields(logGroupName=group)+ by_name = {f["name"]: f["percent"] for f in resp["logGroupFields"]}+ assert by_name["@timestamp"] == 100+ assert by_name["@message"] == 100+ assert by_name["@logStream"] == 100+ assert by_name["@ptr"] == 100+ assert by_name["@log"] == 100+ assert by_name["type"] == 100+ assert by_name["nested"] == 50+ assert by_name["nested.level"] == 50+ assert by_name["duration"] == 50+ # Sorted by percent desc, then name.+ names = [f["name"] for f in resp["logGroupFields"]]+ assert names == sorted(names, key=lambda n: (-by_name[n], n))+++def test_logs_get_log_group_fields_time_window(logs):+ """Optional time searches ±8 minutes; default window is the last 15 minutes."""+ group = f"/intg/glgf-window/{_uuid_mod.uuid4().hex[:8]}"+ stream = "s1"+ now_s = int(time.time())+ now_ms = now_s * 1000+ logs.create_log_group(logGroupName=group)+ logs.create_log_stream(logGroupName=group, logStreamName=stream)+ logs.put_log_events(+ logGroupName=group,+ logStreamName=stream,+ logEvents=[+ {"timestamp": now_ms, "message": json.dumps({"in_window": True})},+ {+ "timestamp": (now_s - 20 * 60) * 1000,+ "message": json.dumps({"old_only": True}),+ },+ ],+ )++ default_resp = logs.get_log_group_fields(logGroupName=group)+ default_names = {f["name"] for f in default_resp["logGroupFields"]}+ assert "in_window" in default_names+ assert "old_only" not in default_names++ centered = logs.get_log_group_fields(logGroupName=group, time=now_s - 20 * 60)+ centered_names = {f["name"] for f in centered["logGroupFields"]}+ assert "old_only" in centered_names+ assert "in_window" not in centered_names+++def test_logs_get_log_group_fields_identifier_and_validation(logs):+ group = f"/intg/glgf-ident/{_uuid_mod.uuid4().hex[:8]}"+ stream = "s1"+ now_ms = int(time.time() * 1000)+ logs.create_log_group(logGroupName=group)+ logs.create_log_stream(logGroupName=group, logStreamName=stream)+ logs.put_log_events(+ logGroupName=group,+ logStreamName=stream,+ logEvents=[{"timestamp": now_ms, "message": json.dumps({"ok": 1})}],+ )++ arn = f"arn:aws:logs:us-east-1:000000000000:log-group:{group}"+ by_arn = logs.get_log_group_fields(logGroupIdentifier=arn)+ assert any(f["name"] == "ok" for f in by_arn["logGroupFields"])++ with pytest.raises(ClientError) as both:+ logs.get_log_group_fields(logGroupName=group, logGroupIdentifier=arn)+ assert both.value.response["Error"]["Code"] == "InvalidParameterException"++ with pytest.raises(ClientError) as missing:+ logs.get_log_group_fields(logGroupName=f"/missing/{_uuid_mod.uuid4().hex[:8]}")+ assert missing.value.response["Error"]["Code"] == "ResourceNotFoundException"++def test_logs_insights_filter_sort_limit(logs):"""CWLI filter/sort/limit: stream equality, like regex, AND, sort, post-filter limit."""import uuid as _uuid@@ -1275,6 +1369,94 @@ def test_get_log_record_inprocess_round_trip():mod.reset()+def test_get_log_group_fields_inprocess():+ """Handler-level GetLogGroupFields coverage without a running gateway."""+ import json as _json++ from ministack.core.responses import set_request_account_id, set_request_region++ mod = _module()+ mod.reset()+ set_request_account_id("000000000000")+ set_request_region("us-east-1")++ # Indexed array paths match AWS Insights discovery (items.0.id, not items.id).+ assert mod._json_field_names('{"items":[{"id":1}],"tags":["a"]}') == {+ "items",+ "items.0",+ "items.0.id",+ "tags",+ "tags.0",+ }++ group = "/aws/lambda/get-log-group-fields-unit"+ stream = "stream-a"+ # Mid-second ms timestamp: default window must not floor "now" away.+ now_ms = int(time.time() * 1000)+ if now_ms % 1000 == 0:+ now_ms += 1+ now_s = now_ms // 1000++ assert mod._create_log_group({"logGroupName": group})[0] == 200+ assert mod._create_log_stream({"logGroupName": group, "logStreamName": stream})[0] == 200+ put = mod._put_log_events({+ "logGroupName": group,+ "logStreamName": stream,+ "logEvents": [+ {+ "timestamp": now_ms - 1000,+ "message": _json.dumps({+ "type": "a",+ "nested": {"level": 1},+ "items": [{"id": 1}],+ }),+ },+ {+ "timestamp": now_ms,+ "message": _json.dumps({"type": "b", "duration": 13}),+ },+ {+ "timestamp": (now_s - 20 * 60) * 1000,+ "message": _json.dumps({"old_only": True}),+ },+ ],+ })+ assert put[0] == 200++ resp = mod._get_log_group_fields({"logGroupName": group})+ assert resp[0] == 200+ body = _json.loads(resp[2])+ by_name = {f["name"]: f["percent"] for f in body["logGroupFields"]}+ assert by_name["@timestamp"] == 100+ assert by_name["@message"] == 100+ assert by_name["type"] == 100+ assert by_name["nested.level"] == 50+ assert by_name["duration"] == 50+ assert by_name["items.0.id"] == 50+ assert "items.id" not in by_name+ assert "old_only" not in by_name++ centered = mod._get_log_group_fields({"logGroupName": group, "time": now_s - 20 * 60})+ assert centered[0] == 200+ centered_names = {f["name"] for f in _json.loads(centered[2])["logGroupFields"]}+ assert "old_only" in centered_names+ assert "type" not in centered_names++ arn = f"arn:aws:logs:us-east-1:000000000000:log-group:{group}"+ by_arn = mod._get_log_group_fields({"logGroupIdentifier": arn})+ assert by_arn[0] == 200+ assert any(f["name"] == "type" for f in _json.loads(by_arn[2])["logGroupFields"])++ both = mod._get_log_group_fields({"logGroupName": group, "logGroupIdentifier": arn})+ assert both[0] == 400+ assert _json.loads(both[2])["__type"] == "InvalidParameterException"++ missing = mod._get_log_group_fields({"logGroupName": "/missing/group"})+ assert missing[0] == 400+ assert _json.loads(missing[2])["__type"] == "ResourceNotFoundException"+ mod.reset()++@pytest.fixture(autouse=True)def _enable_persistence(monkeypatch, tmp_path):"""Force PERSIST_STATE on and point STATE_DIR at a tmp dir for the