• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

localstack / localstack / 17964544913

23 Sep 2025 07:08PM UTC coverage: 86.885% (+0.02%) from 86.864%
17964544913

push

github

web-flow
S3: fix DeleteObjectTagging on current object (#13174)

1 of 1 new or added line in 1 file covered. (100.0%)

129 existing lines in 7 files now uncovered.

67738 of 77963 relevant lines covered (86.88%)

0.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.38
/localstack-core/localstack/services/cloudwatch/provider_v2.py
1
import datetime
1✔
2
import json
1✔
3
import logging
1✔
4
import re
1✔
5
import threading
1✔
6
import uuid
1✔
7

8
from localstack.aws.api import CommonServiceException, RequestContext, handler
1✔
9
from localstack.aws.api.cloudwatch import (
1✔
10
    AccountId,
11
    ActionPrefix,
12
    AlarmName,
13
    AlarmNamePrefix,
14
    AlarmNames,
15
    AlarmTypes,
16
    AmazonResourceName,
17
    CloudwatchApi,
18
    ContributorId,
19
    DashboardBody,
20
    DashboardName,
21
    DashboardNamePrefix,
22
    DashboardNames,
23
    Datapoint,
24
    DeleteDashboardsOutput,
25
    DescribeAlarmHistoryOutput,
26
    DescribeAlarmsForMetricOutput,
27
    DescribeAlarmsOutput,
28
    DimensionFilters,
29
    Dimensions,
30
    EntityMetricDataList,
31
    ExtendedStatistic,
32
    ExtendedStatistics,
33
    GetDashboardOutput,
34
    GetMetricDataMaxDatapoints,
35
    GetMetricDataOutput,
36
    GetMetricStatisticsOutput,
37
    HistoryItemType,
38
    IncludeLinkedAccounts,
39
    InvalidParameterCombinationException,
40
    InvalidParameterValueException,
41
    LabelOptions,
42
    ListDashboardsOutput,
43
    ListMetricsOutput,
44
    ListTagsForResourceOutput,
45
    MaxRecords,
46
    MetricData,
47
    MetricDataQueries,
48
    MetricDataQuery,
49
    MetricDataResult,
50
    MetricDataResultMessages,
51
    MetricName,
52
    MetricStat,
53
    Namespace,
54
    NextToken,
55
    Period,
56
    PutCompositeAlarmInput,
57
    PutDashboardOutput,
58
    PutMetricAlarmInput,
59
    RecentlyActive,
60
    ResourceNotFound,
61
    ScanBy,
62
    StandardUnit,
63
    StateReason,
64
    StateReasonData,
65
    StateValue,
66
    Statistic,
67
    Statistics,
68
    StrictEntityValidation,
69
    TagKeyList,
70
    TagList,
71
    TagResourceOutput,
72
    Timestamp,
73
    UntagResourceOutput,
74
)
75
from localstack.aws.connect import connect_to
1✔
76
from localstack.http import Request
1✔
77
from localstack.services.cloudwatch.alarm_scheduler import AlarmScheduler
1✔
78
from localstack.services.cloudwatch.cloudwatch_database_helper import CloudwatchDatabase
1✔
79
from localstack.services.cloudwatch.models import (
1✔
80
    CloudWatchStore,
81
    LocalStackAlarm,
82
    LocalStackCompositeAlarm,
83
    LocalStackDashboard,
84
    LocalStackMetricAlarm,
85
    cloudwatch_stores,
86
)
87
from localstack.services.edge import ROUTER
1✔
88
from localstack.services.plugins import SERVICE_PLUGINS, ServiceLifecycleHook
1✔
89
from localstack.state import AssetDirectory, StateVisitor
1✔
90
from localstack.utils.aws import arns
1✔
91
from localstack.utils.aws.arns import extract_account_id_from_arn, lambda_function_name
1✔
92
from localstack.utils.collections import PaginatedList
1✔
93
from localstack.utils.json import CustomEncoder as JSONEncoder
1✔
94
from localstack.utils.strings import camel_to_snake_case
1✔
95
from localstack.utils.sync import poll_condition
1✔
96
from localstack.utils.threads import start_worker_thread
1✔
97
from localstack.utils.time import timestamp_millis
1✔
98

99
PATH_GET_RAW_METRICS = "/_aws/cloudwatch/metrics/raw"
1✔
100
MOTO_INITIAL_UNCHECKED_REASON = "Unchecked: Initial alarm creation"
1✔
101
LIST_METRICS_MAX_RESULTS = 500
1✔
102
# If the values in these fields are not the same, their values are added when generating labels
103
LABEL_DIFFERENTIATORS = ["Stat", "Period"]
1✔
104
HISTORY_VERSION = "1.0"
1✔
105

106
LOG = logging.getLogger(__name__)
1✔
107
_STORE_LOCK = threading.RLock()
1✔
108
AWS_MAX_DATAPOINTS_ACCEPTED: int = 1440
1✔
109

110

111
class ValidationException(CommonServiceException):
1✔
112
    def __init__(self, message: str):
1✔
113
        super().__init__("ValidationError", message, 400, True)
1✔
114

115

116
def _validate_parameters_for_put_metric_data(metric_data: MetricData) -> None:
1✔
117
    for index, metric_item in enumerate(metric_data):
1✔
118
        indexplusone = index + 1
1✔
119
        if metric_item.get("Value") and metric_item.get("Values"):
1✔
120
            raise InvalidParameterCombinationException(
1✔
121
                f"The parameters MetricData.member.{indexplusone}.Value and MetricData.member.{indexplusone}.Values are mutually exclusive and you have specified both."
122
            )
123

124
        if metric_item.get("StatisticValues") and metric_item.get("Value"):
1✔
125
            raise InvalidParameterCombinationException(
1✔
126
                f"The parameters MetricData.member.{indexplusone}.Value and MetricData.member.{indexplusone}.StatisticValues are mutually exclusive and you have specified both."
127
            )
128

129
        if metric_item.get("Values") and metric_item.get("Counts"):
1✔
130
            values = metric_item.get("Values")
1✔
131
            counts = metric_item.get("Counts")
1✔
132
            if len(values) != len(counts):
1✔
133
                raise InvalidParameterValueException(
1✔
134
                    f"The parameters MetricData.member.{indexplusone}.Values and MetricData.member.{indexplusone}.Counts must be of the same size."
135
                )
136

137

138
class CloudwatchProvider(CloudwatchApi, ServiceLifecycleHook):
1✔
139
    """
140
    Cloudwatch provider.
141

142
    LIMITATIONS:
143
        - simplified composite alarm rule evaluation:
144
            - only OR operator is supported
145
            - only ALARM expression is supported
146
            - only metric alarms can be included in the rule and they should be referenced by ARN only
147
    """
148

149
    def __init__(self):
1✔
150
        self.alarm_scheduler: AlarmScheduler = None
1✔
151
        self.store = None
1✔
152
        self.cloudwatch_database = CloudwatchDatabase()
1✔
153

154
    @staticmethod
1✔
155
    def get_store(account_id: str, region: str) -> CloudWatchStore:
1✔
156
        return cloudwatch_stores[account_id][region]
1✔
157

158
    def accept_state_visitor(self, visitor: StateVisitor):
1✔
UNCOV
159
        visitor.visit(cloudwatch_stores)
×
UNCOV
160
        visitor.visit(AssetDirectory(self.service, CloudwatchDatabase.CLOUDWATCH_DATA_ROOT))
×
161

162
    def on_after_init(self):
1✔
163
        ROUTER.add(PATH_GET_RAW_METRICS, self.get_raw_metrics)
1✔
164
        self.start_alarm_scheduler()
1✔
165

166
    def on_before_state_reset(self):
1✔
UNCOV
167
        self.shutdown_alarm_scheduler()
×
UNCOV
168
        self.cloudwatch_database.clear_tables()
×
169

170
    def on_after_state_reset(self):
1✔
UNCOV
171
        self.cloudwatch_database = CloudwatchDatabase()
×
UNCOV
172
        self.start_alarm_scheduler()
×
173

174
    def on_before_state_load(self):
1✔
UNCOV
175
        self.shutdown_alarm_scheduler()
×
176

177
    def on_after_state_load(self):
1✔
178
        self.start_alarm_scheduler()
×
179

UNCOV
180
        def restart_alarms(*args):
×
181
            poll_condition(lambda: SERVICE_PLUGINS.is_running("cloudwatch"))
×
UNCOV
182
            self.alarm_scheduler.restart_existing_alarms()
×
183

184
        start_worker_thread(restart_alarms)
×
185

186
    def on_before_stop(self):
1✔
187
        self.shutdown_alarm_scheduler()
1✔
188

189
    def start_alarm_scheduler(self):
1✔
190
        if not self.alarm_scheduler:
1✔
191
            LOG.debug("starting cloudwatch scheduler")
1✔
192
            self.alarm_scheduler = AlarmScheduler()
1✔
193

194
    def shutdown_alarm_scheduler(self):
1✔
195
        LOG.debug("stopping cloudwatch scheduler")
1✔
196
        self.alarm_scheduler.shutdown_scheduler()
1✔
197
        self.alarm_scheduler = None
1✔
198

199
    def delete_alarms(self, context: RequestContext, alarm_names: AlarmNames, **kwargs) -> None:
1✔
200
        """
201
        Delete alarms.
202
        """
203
        with _STORE_LOCK:
1✔
204
            for alarm_name in alarm_names:
1✔
205
                alarm_arn = arns.cloudwatch_alarm_arn(
1✔
206
                    alarm_name, account_id=context.account_id, region_name=context.region
207
                )  # obtain alarm ARN from alarm name
208
                self.alarm_scheduler.delete_scheduler_for_alarm(alarm_arn)
1✔
209
                store = self.get_store(context.account_id, context.region)
1✔
210
                store.alarms.pop(alarm_arn, None)
1✔
211

212
    def put_metric_data(
1✔
213
        self,
214
        context: RequestContext,
215
        namespace: Namespace,
216
        metric_data: MetricData = None,
217
        entity_metric_data: EntityMetricDataList = None,
218
        strict_entity_validation: StrictEntityValidation = None,
219
        **kwargs,
220
    ) -> None:
221
        # TODO add support for entity_metric_data and strict_entity_validation
222
        _validate_parameters_for_put_metric_data(metric_data)
1✔
223

224
        self.cloudwatch_database.add_metric_data(
1✔
225
            context.account_id, context.region, namespace, metric_data
226
        )
227

228
    def get_metric_data(
1✔
229
        self,
230
        context: RequestContext,
231
        metric_data_queries: MetricDataQueries,
232
        start_time: Timestamp,
233
        end_time: Timestamp,
234
        next_token: NextToken = None,
235
        scan_by: ScanBy = None,
236
        max_datapoints: GetMetricDataMaxDatapoints = None,
237
        label_options: LabelOptions = None,
238
        **kwargs,
239
    ) -> GetMetricDataOutput:
240
        results: list[MetricDataResult] = []
1✔
241
        limit = max_datapoints or 100_800
1✔
242
        messages: MetricDataResultMessages = []
1✔
243
        nxt: str | None = None
1✔
244
        label_additions = []
1✔
245

246
        for diff in LABEL_DIFFERENTIATORS:
1✔
247
            non_unique = []
1✔
248
            for query in metric_data_queries:
1✔
249
                non_unique.append(query["MetricStat"][diff])
1✔
250
            if len(set(non_unique)) > 1:
1✔
251
                label_additions.append(diff)
1✔
252

253
        for query in metric_data_queries:
1✔
254
            query_result = self.cloudwatch_database.get_metric_data_stat(
1✔
255
                account_id=context.account_id,
256
                region=context.region,
257
                query=query,
258
                start_time=start_time,
259
                end_time=end_time,
260
                scan_by=scan_by,
261
            )
262
            if query_result.get("messages"):
1✔
UNCOV
263
                messages.extend(query_result.get("messages"))
×
264

265
            label = query.get("Label") or f"{query['MetricStat']['Metric']['MetricName']}"
1✔
266
            # TODO: does this happen even if a label is set in the query?
267
            for label_addition in label_additions:
1✔
268
                label = f"{label} {query['MetricStat'][label_addition]}"
1✔
269

270
            timestamps = query_result.get("timestamps", {})
1✔
271
            values = query_result.get("values", {})
1✔
272

273
            # Paginate
274
            timestamp_value_dicts = [
1✔
275
                {
276
                    "Timestamp": timestamp,
277
                    "Value": float(value),
278
                }
279
                for timestamp, value in zip(timestamps, values, strict=False)
280
            ]
281

282
            pagination = PaginatedList(timestamp_value_dicts)
1✔
283
            timestamp_page, nxt = pagination.get_page(
1✔
284
                lambda item: str(item.get("Timestamp")),
285
                next_token=next_token,
286
                page_size=limit,
287
            )
288

289
            timestamps = [item.get("Timestamp") for item in timestamp_page]
1✔
290
            values = [item.get("Value") for item in timestamp_page]
1✔
291

292
            metric_data_result = {
1✔
293
                "Id": query.get("Id"),
294
                "Label": label,
295
                "StatusCode": "Complete",
296
                "Timestamps": timestamps,
297
                "Values": values,
298
            }
299
            results.append(MetricDataResult(**metric_data_result))
1✔
300

301
        return GetMetricDataOutput(MetricDataResults=results, NextToken=nxt, Messages=messages)
1✔
302

303
    def set_alarm_state(
1✔
304
        self,
305
        context: RequestContext,
306
        alarm_name: AlarmName,
307
        state_value: StateValue,
308
        state_reason: StateReason,
309
        state_reason_data: StateReasonData = None,
310
        **kwargs,
311
    ) -> None:
312
        if state_value not in ("OK", "ALARM", "INSUFFICIENT_DATA"):
1✔
313
            raise ValidationException(
1✔
314
                f"1 validation error detected: Value '{state_value}' at 'stateValue' failed to satisfy constraint: Member must satisfy enum value set: [INSUFFICIENT_DATA, ALARM, OK]"
315
            )
316

317
        try:
1✔
318
            if state_reason_data:
1✔
319
                state_reason_data = json.loads(state_reason_data)
1✔
UNCOV
320
        except ValueError:
×
321
            raise InvalidParameterValueException(
×
322
                "TODO: check right error message: Json was not correctly formatted"
323
            )
324
        with _STORE_LOCK:
1✔
325
            store = self.get_store(context.account_id, context.region)
1✔
326
            alarm = store.alarms.get(
1✔
327
                arns.cloudwatch_alarm_arn(
328
                    alarm_name, account_id=context.account_id, region_name=context.region
329
                )
330
            )
331
            if not alarm:
1✔
332
                raise ResourceNotFound()
1✔
333

334
            old_state = alarm.alarm["StateValue"]
1✔
335

336
            old_state_reason = alarm.alarm["StateReason"]
1✔
337
            old_state_update_timestamp = alarm.alarm["StateUpdatedTimestamp"]
1✔
338

339
            if old_state == state_value:
1✔
UNCOV
340
                return
×
341

342
            alarm.alarm["StateTransitionedTimestamp"] = datetime.datetime.now(datetime.UTC)
1✔
343
            # update startDate (=last ALARM date) - should only update when a new alarm is triggered
344
            # the date is only updated if we have a reason-data, which is set by an alarm
345
            if state_reason_data:
1✔
346
                state_reason_data["startDate"] = state_reason_data.get("queryDate")
1✔
347

348
            self._update_state(
1✔
349
                context,
350
                alarm,
351
                state_value,
352
                state_reason,
353
                state_reason_data,
354
            )
355

356
            self._evaluate_composite_alarms(context, alarm)
1✔
357

358
            if not alarm.alarm["ActionsEnabled"]:
1✔
359
                return
1✔
360
            if state_value == "OK":
1✔
361
                actions = alarm.alarm["OKActions"]
1✔
362
            elif state_value == "ALARM":
1✔
363
                actions = alarm.alarm["AlarmActions"]
1✔
364
            else:
UNCOV
365
                actions = alarm.alarm["InsufficientDataActions"]
×
366
            for action in actions:
1✔
367
                data = arns.parse_arn(action)
1✔
368
                # test for sns - can this be done in a more generic way?
369
                if data["service"] == "sns":
1✔
370
                    service = connect_to(
1✔
371
                        region_name=data["region"], aws_access_key_id=data["account"]
372
                    ).sns
373
                    subject = f"""{state_value}: "{alarm_name}" in {context.region}"""
1✔
374
                    message = create_message_response_update_state_sns(alarm, old_state)
1✔
375
                    service.publish(TopicArn=action, Subject=subject, Message=message)
1✔
376
                elif data["service"] == "lambda":
1✔
377
                    service = connect_to(
1✔
378
                        region_name=data["region"], aws_access_key_id=data["account"]
379
                    ).lambda_
380
                    message = create_message_response_update_state_lambda(
1✔
381
                        alarm, old_state, old_state_reason, old_state_update_timestamp
382
                    )
383
                    service.invoke(FunctionName=lambda_function_name(action), Payload=message)
1✔
384
                else:
385
                    # TODO: support other actions
UNCOV
386
                    LOG.warning(
×
387
                        "Action for service %s not implemented, action '%s' will not be triggered.",
388
                        data["service"],
389
                        action,
390
                    )
391

392
    def get_raw_metrics(self, request: Request):
1✔
393
        """this feature was introduced with https://github.com/localstack/localstack/pull/3535
394
        # in the meantime, it required a valid aws-header so that the account-id/region could be extracted
395
        # with the new implementation, we want to return all data, but add the account-id/region as additional attributes
396

397
        # TODO endpoint should be refactored or deprecated at some point
398
        #   - result should be paginated
399
        #   - include aggregated metrics (but we would also need to change/adapt the shape of "metrics" that we return)
400
        :returns: json {"metrics": [{"ns": "namespace", "n": "metric_name", "v": value, "t": timestamp,
401
        "d": [<dimensions-key-pair-values>],"account": account, "region": region}]}
402
        """
403
        return {"metrics": self.cloudwatch_database.get_all_metric_data() or []}
1✔
404

405
    @handler("PutMetricAlarm", expand=False)
1✔
406
    def put_metric_alarm(self, context: RequestContext, request: PutMetricAlarmInput) -> None:
1✔
407
        # missing will be the default, when not set (but it will not explicitly be set)
408
        if request.get("TreatMissingData", "missing") not in [
1✔
409
            "breaching",
410
            "notBreaching",
411
            "ignore",
412
            "missing",
413
        ]:
UNCOV
414
            raise ValidationException(
×
415
                f"The value {request['TreatMissingData']} is not supported for TreatMissingData parameter. Supported values are [breaching, notBreaching, ignore, missing]."
416
            )
417
            # do some sanity checks:
418
        if request.get("Period"):
1✔
419
            # Valid values are 10, 30, and any multiple of 60.
420
            value = request.get("Period")
1✔
421
            if value not in (10, 30):
1✔
422
                if value % 60 != 0:
1✔
UNCOV
423
                    raise ValidationException("Period must be 10, 30 or a multiple of 60")
×
424
        if request.get("Statistic"):
1✔
425
            if request.get("Statistic") not in [
1✔
426
                "SampleCount",
427
                "Average",
428
                "Sum",
429
                "Minimum",
430
                "Maximum",
431
            ]:
UNCOV
432
                raise ValidationException(
×
433
                    f"Value '{request.get('Statistic')}' at 'statistic' failed to satisfy constraint: Member must satisfy enum value set: [Maximum, SampleCount, Sum, Minimum, Average]"
434
                )
435

436
        extended_statistic = request.get("ExtendedStatistic")
1✔
437
        if extended_statistic and not extended_statistic.startswith("p"):
1✔
UNCOV
438
            raise InvalidParameterValueException(
×
439
                f"The value {extended_statistic} for parameter ExtendedStatistic is not supported."
440
            )
441
        evaluate_low_sample_count_percentile = request.get("EvaluateLowSampleCountPercentile")
1✔
442
        if evaluate_low_sample_count_percentile and evaluate_low_sample_count_percentile not in (
1✔
443
            "evaluate",
444
            "ignore",
445
        ):
UNCOV
446
            raise ValidationException(
×
447
                f"Option {evaluate_low_sample_count_percentile} is not supported. "
448
                "Supported options for parameter EvaluateLowSampleCountPercentile are evaluate and ignore."
449
            )
450
        with _STORE_LOCK:
1✔
451
            store = self.get_store(context.account_id, context.region)
1✔
452
            metric_alarm = LocalStackMetricAlarm(context.account_id, context.region, {**request})
1✔
453
            alarm_arn = metric_alarm.alarm["AlarmArn"]
1✔
454
            store.alarms[alarm_arn] = metric_alarm
1✔
455
            self.alarm_scheduler.schedule_metric_alarm(alarm_arn)
1✔
456

457
    @handler("PutCompositeAlarm", expand=False)
1✔
458
    def put_composite_alarm(self, context: RequestContext, request: PutCompositeAlarmInput) -> None:
1✔
459
        with _STORE_LOCK:
1✔
460
            store = self.get_store(context.account_id, context.region)
1✔
461
            composite_alarm = LocalStackCompositeAlarm(
1✔
462
                context.account_id, context.region, {**request}
463
            )
464

465
            alarm_rule = composite_alarm.alarm["AlarmRule"]
1✔
466
            rule_expression_validation_result = self._validate_alarm_rule_expression(alarm_rule)
1✔
467
            [LOG.warning(w) for w in rule_expression_validation_result]
1✔
468

469
            alarm_arn = composite_alarm.alarm["AlarmArn"]
1✔
470
            store.alarms[alarm_arn] = composite_alarm
1✔
471

472
    def describe_alarms(
1✔
473
        self,
474
        context: RequestContext,
475
        alarm_names: AlarmNames = None,
476
        alarm_name_prefix: AlarmNamePrefix = None,
477
        alarm_types: AlarmTypes = None,
478
        children_of_alarm_name: AlarmName = None,
479
        parents_of_alarm_name: AlarmName = None,
480
        state_value: StateValue = None,
481
        action_prefix: ActionPrefix = None,
482
        max_records: MaxRecords = None,
483
        next_token: NextToken = None,
484
        **kwargs,
485
    ) -> DescribeAlarmsOutput:
486
        store = self.get_store(context.account_id, context.region)
1✔
487
        alarms = list(store.alarms.values())
1✔
488
        if action_prefix:
1✔
UNCOV
489
            alarms = [a.alarm for a in alarms if a.alarm["AlarmAction"].startswith(action_prefix)]
×
490
        elif alarm_name_prefix:
1✔
UNCOV
491
            alarms = [a.alarm for a in alarms if a.alarm["AlarmName"].startswith(alarm_name_prefix)]
×
492
        elif alarm_names:
1✔
493
            alarms = [a.alarm for a in alarms if a.alarm["AlarmName"] in alarm_names]
1✔
494
        elif state_value:
1✔
UNCOV
495
            alarms = [a.alarm for a in alarms if a.alarm["StateValue"] == state_value]
×
496
        else:
497
            alarms = [a.alarm for a in list(store.alarms.values())]
1✔
498

499
        # TODO: Pagination
500
        metric_alarms = [a for a in alarms if a.get("AlarmRule") is None]
1✔
501
        composite_alarms = [a for a in alarms if a.get("AlarmRule") is not None]
1✔
502
        return DescribeAlarmsOutput(CompositeAlarms=composite_alarms, MetricAlarms=metric_alarms)
1✔
503

504
    def describe_alarms_for_metric(
1✔
505
        self,
506
        context: RequestContext,
507
        metric_name: MetricName,
508
        namespace: Namespace,
509
        statistic: Statistic = None,
510
        extended_statistic: ExtendedStatistic = None,
511
        dimensions: Dimensions = None,
512
        period: Period = None,
513
        unit: StandardUnit = None,
514
        **kwargs,
515
    ) -> DescribeAlarmsForMetricOutput:
516
        store = self.get_store(context.account_id, context.region)
1✔
517
        alarms = [
1✔
518
            a.alarm
519
            for a in store.alarms.values()
520
            if isinstance(a, LocalStackMetricAlarm)
521
            and a.alarm.get("MetricName") == metric_name
522
            and a.alarm.get("Namespace") == namespace
523
        ]
524

525
        if statistic:
1✔
526
            alarms = [a for a in alarms if a.get("Statistic") == statistic]
1✔
527
        if dimensions:
1✔
528
            alarms = [a for a in alarms if a.get("Dimensions") == dimensions]
1✔
529
        if period:
1✔
UNCOV
530
            alarms = [a for a in alarms if a.get("Period") == period]
×
531
        if unit:
1✔
UNCOV
532
            alarms = [a for a in alarms if a.get("Unit") == unit]
×
533
        return DescribeAlarmsForMetricOutput(MetricAlarms=alarms)
1✔
534

535
    def list_tags_for_resource(
1✔
536
        self, context: RequestContext, resource_arn: AmazonResourceName, **kwargs
537
    ) -> ListTagsForResourceOutput:
538
        store = self.get_store(context.account_id, context.region)
1✔
539
        tags = store.TAGS.list_tags_for_resource(resource_arn)
1✔
540
        return ListTagsForResourceOutput(Tags=tags.get("Tags", []))
1✔
541

542
    def untag_resource(
1✔
543
        self,
544
        context: RequestContext,
545
        resource_arn: AmazonResourceName,
546
        tag_keys: TagKeyList,
547
        **kwargs,
548
    ) -> UntagResourceOutput:
549
        store = self.get_store(context.account_id, context.region)
1✔
550
        store.TAGS.untag_resource(resource_arn, tag_keys)
1✔
551
        return UntagResourceOutput()
1✔
552

553
    def tag_resource(
1✔
554
        self, context: RequestContext, resource_arn: AmazonResourceName, tags: TagList, **kwargs
555
    ) -> TagResourceOutput:
556
        store = self.get_store(context.account_id, context.region)
1✔
557
        store.TAGS.tag_resource(resource_arn, tags)
1✔
558
        return TagResourceOutput()
1✔
559

560
    def put_dashboard(
1✔
561
        self,
562
        context: RequestContext,
563
        dashboard_name: DashboardName,
564
        dashboard_body: DashboardBody,
565
        **kwargs,
566
    ) -> PutDashboardOutput:
567
        pattern = r"^[a-zA-Z0-9_-]+$"
1✔
568
        if not re.match(pattern, dashboard_name):
1✔
569
            raise InvalidParameterValueException(
1✔
570
                "The value for field DashboardName contains invalid characters. "
571
                "It can only contain alphanumerics, dash (-) and underscore (_).\n"
572
            )
573

574
        store = self.get_store(context.account_id, context.region)
1✔
575
        store.dashboards[dashboard_name] = LocalStackDashboard(
1✔
576
            context.account_id, context.region, dashboard_name, dashboard_body
577
        )
578
        return PutDashboardOutput()
1✔
579

580
    def get_dashboard(
1✔
581
        self, context: RequestContext, dashboard_name: DashboardName, **kwargs
582
    ) -> GetDashboardOutput:
583
        store = self.get_store(context.account_id, context.region)
1✔
584
        dashboard = store.dashboards.get(dashboard_name)
1✔
585
        if not dashboard:
1✔
UNCOV
586
            raise InvalidParameterValueException(f"Dashboard {dashboard_name} does not exist.")
×
587

588
        return GetDashboardOutput(
1✔
589
            DashboardName=dashboard_name,
590
            DashboardBody=dashboard.dashboard_body,
591
            DashboardArn=dashboard.dashboard_arn,
592
        )
593

594
    def delete_dashboards(
1✔
595
        self, context: RequestContext, dashboard_names: DashboardNames, **kwargs
596
    ) -> DeleteDashboardsOutput:
597
        store = self.get_store(context.account_id, context.region)
1✔
598
        for dashboard_name in dashboard_names:
1✔
599
            store.dashboards.pop(dashboard_name, None)
1✔
600
        return DeleteDashboardsOutput()
1✔
601

602
    def list_dashboards(
1✔
603
        self,
604
        context: RequestContext,
605
        dashboard_name_prefix: DashboardNamePrefix = None,
606
        next_token: NextToken = None,
607
        **kwargs,
608
    ) -> ListDashboardsOutput:
609
        store = self.get_store(context.account_id, context.region)
1✔
610
        dashboard_names = list(store.dashboards.keys())
1✔
611
        dashboard_names = [
1✔
612
            name for name in dashboard_names if name.startswith(dashboard_name_prefix or "")
613
        ]
614

615
        entries = [
1✔
616
            {
617
                "DashboardName": name,
618
                "DashboardArn": store.dashboards[name].dashboard_arn,
619
                "LastModified": store.dashboards[name].last_modified,
620
                "Size": store.dashboards[name].size,
621
            }
622
            for name in dashboard_names
623
        ]
624
        return ListDashboardsOutput(
1✔
625
            DashboardEntries=entries,
626
        )
627

628
    def list_metrics(
1✔
629
        self,
630
        context: RequestContext,
631
        namespace: Namespace = None,
632
        metric_name: MetricName = None,
633
        dimensions: DimensionFilters = None,
634
        next_token: NextToken = None,
635
        recently_active: RecentlyActive = None,
636
        include_linked_accounts: IncludeLinkedAccounts = None,
637
        owning_account: AccountId = None,
638
        **kwargs,
639
    ) -> ListMetricsOutput:
640
        result = self.cloudwatch_database.list_metrics(
1✔
641
            context.account_id,
642
            context.region,
643
            namespace,
644
            metric_name,
645
            dimensions or [],
646
        )
647

648
        metrics = [
1✔
649
            {
650
                "Namespace": metric.get("namespace"),
651
                "MetricName": metric.get("metric_name"),
652
                "Dimensions": metric.get("dimensions"),
653
            }
654
            for metric in result.get("metrics", [])
655
        ]
656
        aliases_list = PaginatedList(metrics)
1✔
657
        page, nxt = aliases_list.get_page(
1✔
658
            lambda metric: f"{metric.get('Namespace')}-{metric.get('MetricName')}-{metric.get('Dimensions')}",
659
            next_token=next_token,
660
            page_size=LIST_METRICS_MAX_RESULTS,
661
        )
662
        return ListMetricsOutput(Metrics=page, NextToken=nxt)
1✔
663

664
    def get_metric_statistics(
1✔
665
        self,
666
        context: RequestContext,
667
        namespace: Namespace,
668
        metric_name: MetricName,
669
        start_time: Timestamp,
670
        end_time: Timestamp,
671
        period: Period,
672
        dimensions: Dimensions = None,
673
        statistics: Statistics = None,
674
        extended_statistics: ExtendedStatistics = None,
675
        unit: StandardUnit = None,
676
        **kwargs,
677
    ) -> GetMetricStatisticsOutput:
678
        start_time_unix = int(start_time.timestamp())
1✔
679
        end_time_unix = int(end_time.timestamp())
1✔
680

681
        if not start_time_unix < end_time_unix:
1✔
682
            raise InvalidParameterValueException(
1✔
683
                "The parameter StartTime must be less than the parameter EndTime."
684
            )
685

686
        expected_datapoints = (end_time_unix - start_time_unix) / period
1✔
687

688
        if expected_datapoints > AWS_MAX_DATAPOINTS_ACCEPTED:
1✔
689
            raise InvalidParameterCombinationException(
1✔
690
                f"You have requested up to {int(expected_datapoints)} datapoints, which exceeds the limit of {AWS_MAX_DATAPOINTS_ACCEPTED}. "
691
                f"You may reduce the datapoints requested by increasing Period, or decreasing the time range."
692
            )
693

694
        stat_datapoints = {}
1✔
695

696
        units = (
1✔
697
            [unit]
698
            if unit
699
            else self.cloudwatch_database.get_units_for_metric_data_stat(
700
                account_id=context.account_id,
701
                region=context.region,
702
                start_time=start_time,
703
                end_time=end_time,
704
                metric_name=metric_name,
705
                namespace=namespace,
706
            )
707
        )
708

709
        for stat in statistics:
1✔
710
            for selected_unit in units:
1✔
711
                query_result = self.cloudwatch_database.get_metric_data_stat(
1✔
712
                    account_id=context.account_id,
713
                    region=context.region,
714
                    start_time=start_time,
715
                    end_time=end_time,
716
                    scan_by="TimestampDescending",
717
                    query=MetricDataQuery(
718
                        MetricStat=MetricStat(
719
                            Metric={
720
                                "MetricName": metric_name,
721
                                "Namespace": namespace,
722
                                "Dimensions": dimensions or [],
723
                            },
724
                            Period=period,
725
                            Stat=stat,
726
                            Unit=selected_unit,
727
                        )
728
                    ),
729
                )
730

731
                timestamps = query_result.get("timestamps", [])
1✔
732
                values = query_result.get("values", [])
1✔
733
                for i, timestamp in enumerate(timestamps):
1✔
734
                    stat_datapoints.setdefault(selected_unit, {})
1✔
735
                    stat_datapoints[selected_unit].setdefault(timestamp, {})
1✔
736
                    stat_datapoints[selected_unit][timestamp][stat] = float(values[i])
1✔
737
                    stat_datapoints[selected_unit][timestamp]["Unit"] = selected_unit
1✔
738

739
        datapoints: list[Datapoint] = []
1✔
740
        for selected_unit, results in stat_datapoints.items():
1✔
741
            for timestamp, stats in results.items():
1✔
742
                datapoints.append(
1✔
743
                    Datapoint(
744
                        Timestamp=timestamp,
745
                        SampleCount=stats.get("SampleCount"),
746
                        Average=stats.get("Average"),
747
                        Sum=stats.get("Sum"),
748
                        Minimum=stats.get("Minimum"),
749
                        Maximum=stats.get("Maximum"),
750
                        Unit="None" if selected_unit == "NULL_VALUE" else selected_unit,
751
                    )
752
                )
753

754
        return GetMetricStatisticsOutput(Datapoints=datapoints, Label=metric_name)
1✔
755

756
    def _update_state(
1✔
757
        self,
758
        context: RequestContext,
759
        alarm: LocalStackAlarm,
760
        state_value: str,
761
        state_reason: str,
762
        state_reason_data: dict = None,
763
    ):
764
        old_state = alarm.alarm["StateValue"]
1✔
765
        old_state_reason = alarm.alarm["StateReason"]
1✔
766
        store = self.get_store(context.account_id, context.region)
1✔
767
        current_time = datetime.datetime.now()
1✔
768
        # version is not present in state reason data for composite alarm, hence the check
769
        if state_reason_data and isinstance(alarm, LocalStackMetricAlarm):
1✔
770
            state_reason_data["version"] = HISTORY_VERSION
1✔
771
        history_data = {
1✔
772
            "version": HISTORY_VERSION,
773
            "oldState": {"stateValue": old_state, "stateReason": old_state_reason},
774
            "newState": {
775
                "stateValue": state_value,
776
                "stateReason": state_reason,
777
                "stateReasonData": state_reason_data,
778
            },
779
        }
780
        store.histories.append(
1✔
781
            {
782
                "Timestamp": timestamp_millis(alarm.alarm["StateUpdatedTimestamp"]),
783
                "HistoryItemType": HistoryItemType.StateUpdate,
784
                "AlarmName": alarm.alarm["AlarmName"],
785
                "HistoryData": json.dumps(history_data),
786
                "HistorySummary": f"Alarm updated from {old_state} to {state_value}",
787
                "AlarmType": "MetricAlarm"
788
                if isinstance(alarm, LocalStackMetricAlarm)
789
                else "CompositeAlarm",
790
            }
791
        )
792
        alarm.alarm["StateValue"] = state_value
1✔
793
        alarm.alarm["StateReason"] = state_reason
1✔
794
        if state_reason_data:
1✔
795
            alarm.alarm["StateReasonData"] = json.dumps(state_reason_data)
1✔
796
        alarm.alarm["StateUpdatedTimestamp"] = current_time
1✔
797

798
    def disable_alarm_actions(
1✔
799
        self, context: RequestContext, alarm_names: AlarmNames, **kwargs
800
    ) -> None:
801
        self._set_alarm_actions(context, alarm_names, enabled=False)
1✔
802

803
    def enable_alarm_actions(
1✔
804
        self, context: RequestContext, alarm_names: AlarmNames, **kwargs
805
    ) -> None:
806
        self._set_alarm_actions(context, alarm_names, enabled=True)
1✔
807

808
    def _set_alarm_actions(self, context, alarm_names, enabled):
1✔
809
        store = self.get_store(context.account_id, context.region)
1✔
810
        for name in alarm_names:
1✔
811
            alarm_arn = arns.cloudwatch_alarm_arn(
1✔
812
                name, account_id=context.account_id, region_name=context.region
813
            )
814
            alarm = store.alarms.get(alarm_arn)
1✔
815
            if alarm:
1✔
816
                alarm.alarm["ActionsEnabled"] = enabled
1✔
817

818
    def describe_alarm_history(
1✔
819
        self,
820
        context: RequestContext,
821
        alarm_name: AlarmName | None = None,
822
        alarm_contributor_id: ContributorId | None = None,
823
        alarm_types: AlarmTypes | None = None,
824
        history_item_type: HistoryItemType | None = None,
825
        start_date: Timestamp | None = None,
826
        end_date: Timestamp | None = None,
827
        max_records: MaxRecords | None = None,
828
        next_token: NextToken | None = None,
829
        scan_by: ScanBy | None = None,
830
        **kwargs,
831
    ) -> DescribeAlarmHistoryOutput:
832
        store = self.get_store(context.account_id, context.region)
1✔
833
        history = store.histories
1✔
834
        if alarm_name:
1✔
835
            history = [h for h in history if h["AlarmName"] == alarm_name]
1✔
836

837
        def _get_timestamp(input: dict):
1✔
UNCOV
838
            if timestamp_string := input.get("Timestamp"):
×
UNCOV
839
                return datetime.datetime.fromisoformat(timestamp_string)
×
UNCOV
840
            return None
×
841

842
        if start_date:
1✔
843
            history = [h for h in history if (date := _get_timestamp(h)) and date >= start_date]
×
844
        if end_date:
1✔
845
            history = [h for h in history if (date := _get_timestamp(h)) and date <= end_date]
×
846
        return DescribeAlarmHistoryOutput(AlarmHistoryItems=history)
1✔
847

848
    def _evaluate_composite_alarms(self, context: RequestContext, triggering_alarm):
1✔
849
        # TODO either pass store as a parameter or acquire RLock (with _STORE_LOCK:)
850
        # everything works ok now but better ensure protection of critical section in front of future changes
851
        store = self.get_store(context.account_id, context.region)
1✔
852
        alarms = list(store.alarms.values())
1✔
853
        composite_alarms = [a for a in alarms if isinstance(a, LocalStackCompositeAlarm)]
1✔
854
        for composite_alarm in composite_alarms:
1✔
855
            self._evaluate_composite_alarm(context, composite_alarm, triggering_alarm)
1✔
856

857
    def _evaluate_composite_alarm(self, context, composite_alarm, triggering_alarm):
1✔
858
        store = self.get_store(context.account_id, context.region)
1✔
859
        alarm_rule = composite_alarm.alarm["AlarmRule"]
1✔
860
        rule_expression_validation = self._validate_alarm_rule_expression(alarm_rule)
1✔
861
        if rule_expression_validation:
1✔
862
            LOG.warning(
1✔
863
                "Alarm rule contains unsupported expressions and will not be evaluated: %s",
864
                rule_expression_validation,
865
            )
866
            return
1✔
867
        new_state_value = StateValue.OK
1✔
868
        # assuming that a rule consists only of ALARM evaluations of metric alarms, with OR logic applied
869
        for metric_alarm_arn in self._get_alarm_arns(alarm_rule):
1✔
870
            metric_alarm = store.alarms.get(metric_alarm_arn)
1✔
871
            if not metric_alarm:
1✔
UNCOV
872
                LOG.warning(
×
873
                    "Alarm rule won't be evaluated as there is no alarm with ARN %s",
874
                    metric_alarm_arn,
875
                )
UNCOV
876
                return
×
877
            if metric_alarm.alarm["StateValue"] == StateValue.ALARM:
1✔
878
                triggering_alarm = metric_alarm
1✔
879
                new_state_value = StateValue.ALARM
1✔
880
                break
1✔
881
        old_state_value = composite_alarm.alarm["StateValue"]
1✔
882
        if old_state_value == new_state_value:
1✔
883
            return
1✔
884
        triggering_alarm_arn = triggering_alarm.alarm.get("AlarmArn")
1✔
885
        triggering_alarm_state = triggering_alarm.alarm.get("StateValue")
1✔
886
        triggering_alarm_state_change_timestamp = triggering_alarm.alarm.get(
1✔
887
            "StateTransitionedTimestamp"
888
        )
889
        state_reason_formatted_timestamp = triggering_alarm_state_change_timestamp.strftime(
1✔
890
            "%A %d %B, %Y %H:%M:%S %Z"
891
        )
892
        state_reason = (
1✔
893
            f"{triggering_alarm_arn} "
894
            f"transitioned to {triggering_alarm_state} "
895
            f"at {state_reason_formatted_timestamp}"
896
        )
897
        state_reason_data = {
1✔
898
            "triggeringAlarms": [
899
                {
900
                    "arn": triggering_alarm_arn,
901
                    "state": {
902
                        "value": triggering_alarm_state,
903
                        "timestamp": timestamp_millis(triggering_alarm_state_change_timestamp),
904
                    },
905
                }
906
            ]
907
        }
908
        self._update_state(
1✔
909
            context, composite_alarm, new_state_value, state_reason, state_reason_data
910
        )
911
        if composite_alarm.alarm["ActionsEnabled"]:
1✔
912
            self._run_composite_alarm_actions(
1✔
913
                context, composite_alarm, old_state_value, triggering_alarm
914
            )
915

916
    def _validate_alarm_rule_expression(self, alarm_rule):
1✔
917
        validation_result = []
1✔
918
        alarms_conditions = [alarm.strip() for alarm in alarm_rule.split("OR")]
1✔
919
        for alarm_condition in alarms_conditions:
1✔
920
            if not alarm_condition.startswith("ALARM"):
1✔
921
                validation_result.append(
1✔
922
                    f"Unsupported expression in alarm rule condition {alarm_condition}: Only ALARM expression is supported by Localstack as of now"
923
                )
924
        return validation_result
1✔
925

926
    def _get_alarm_arns(self, composite_alarm_rule):
1✔
927
        # regexp for everything within (" ")
928
        return re.findall(r'\("([^"]*)"\)', composite_alarm_rule)
1✔
929

930
    def _run_composite_alarm_actions(
1✔
931
        self, context, composite_alarm, old_state_value, triggering_alarm
932
    ):
933
        new_state_value = composite_alarm.alarm["StateValue"]
1✔
934
        if new_state_value == StateValue.OK:
1✔
935
            actions = composite_alarm.alarm["OKActions"]
1✔
936
        elif new_state_value == StateValue.ALARM:
1✔
937
            actions = composite_alarm.alarm["AlarmActions"]
1✔
938
        else:
UNCOV
939
            actions = composite_alarm.alarm["InsufficientDataActions"]
×
940
        for action in actions:
1✔
941
            data = arns.parse_arn(action)
1✔
942
            if data["service"] == "sns":
1✔
943
                service = connect_to(
1✔
944
                    region_name=data["region"], aws_access_key_id=data["account"]
945
                ).sns
946
                subject = f"""{new_state_value}: "{composite_alarm.alarm["AlarmName"]}" in {context.region}"""
1✔
947
                message = create_message_response_update_composite_alarm_state_sns(
1✔
948
                    composite_alarm, triggering_alarm, old_state_value
949
                )
950
                service.publish(TopicArn=action, Subject=subject, Message=message)
1✔
951
            else:
952
                # TODO: support other actions
UNCOV
953
                LOG.warning(
×
954
                    "Action for service %s not implemented, action '%s' will not be triggered.",
955
                    data["service"],
956
                    action,
957
                )
958

959

960
def create_metric_data_query_from_alarm(alarm: LocalStackMetricAlarm):
1✔
961
    # TODO may need to be adapted for other use cases
962
    #  verified return value with a snapshot test
963
    return [
1✔
964
        {
965
            "id": str(uuid.uuid4()),
966
            "metricStat": {
967
                "metric": {
968
                    "namespace": alarm.alarm["Namespace"],
969
                    "name": alarm.alarm["MetricName"],
970
                    "dimensions": alarm.alarm.get("Dimensions") or {},
971
                },
972
                "period": int(alarm.alarm["Period"]),
973
                "stat": alarm.alarm["Statistic"],
974
            },
975
            "returnData": True,
976
        }
977
    ]
978

979

980
def create_message_response_update_state_lambda(
1✔
981
    alarm: LocalStackMetricAlarm, old_state, old_state_reason, old_state_timestamp
982
):
983
    _alarm = alarm.alarm
1✔
984
    response = {
1✔
985
        "accountId": extract_account_id_from_arn(_alarm["AlarmArn"]),
986
        "alarmArn": _alarm["AlarmArn"],
987
        "alarmData": {
988
            "alarmName": _alarm["AlarmName"],
989
            "state": {
990
                "value": _alarm["StateValue"],
991
                "reason": _alarm["StateReason"],
992
                "timestamp": _alarm["StateUpdatedTimestamp"],
993
            },
994
            "previousState": {
995
                "value": old_state,
996
                "reason": old_state_reason,
997
                "timestamp": old_state_timestamp,
998
            },
999
            "configuration": {
1000
                "description": _alarm.get("AlarmDescription", ""),
1001
                "metrics": _alarm.get(
1002
                    "Metrics", create_metric_data_query_from_alarm(alarm)
1003
                ),  # TODO: add test with metric_data_queries
1004
            },
1005
        },
1006
        "time": _alarm["StateUpdatedTimestamp"],
1007
        "region": alarm.region,
1008
        "source": "aws.cloudwatch",
1009
    }
1010
    return json.dumps(response, cls=JSONEncoder)
1✔
1011

1012

1013
def create_message_response_update_state_sns(alarm: LocalStackMetricAlarm, old_state: StateValue):
1✔
1014
    _alarm = alarm.alarm
1✔
1015
    response = {
1✔
1016
        "AWSAccountId": alarm.account_id,
1017
        "OldStateValue": old_state,
1018
        "AlarmName": _alarm["AlarmName"],
1019
        "AlarmDescription": _alarm.get("AlarmDescription"),
1020
        "AlarmConfigurationUpdatedTimestamp": _alarm["AlarmConfigurationUpdatedTimestamp"],
1021
        "NewStateValue": _alarm["StateValue"],
1022
        "NewStateReason": _alarm["StateReason"],
1023
        "StateChangeTime": _alarm["StateUpdatedTimestamp"],
1024
        # the long-name for 'region' should be used - as we don't have it, we use the short name
1025
        # which needs to be slightly changed to make snapshot tests work
1026
        "Region": alarm.region.replace("-", " ").capitalize(),
1027
        "AlarmArn": _alarm["AlarmArn"],
1028
        "OKActions": _alarm.get("OKActions", []),
1029
        "AlarmActions": _alarm.get("AlarmActions", []),
1030
        "InsufficientDataActions": _alarm.get("InsufficientDataActions", []),
1031
    }
1032

1033
    # collect trigger details
1034
    details = {
1✔
1035
        "MetricName": _alarm.get("MetricName", ""),
1036
        "Namespace": _alarm.get("Namespace", ""),
1037
        "Unit": _alarm.get("Unit", None),  # testing with AWS revealed this currently returns None
1038
        "Period": int(_alarm.get("Period", 0)),
1039
        "EvaluationPeriods": int(_alarm.get("EvaluationPeriods", 0)),
1040
        "ComparisonOperator": _alarm.get("ComparisonOperator", ""),
1041
        "Threshold": float(_alarm.get("Threshold", 0.0)),
1042
        "TreatMissingData": _alarm.get("TreatMissingData", ""),
1043
        "EvaluateLowSampleCountPercentile": _alarm.get("EvaluateLowSampleCountPercentile", ""),
1044
    }
1045

1046
    # Dimensions not serializable
1047
    dimensions = []
1✔
1048
    alarm_dimensions = _alarm.get("Dimensions", [])
1✔
1049
    if alarm_dimensions:
1✔
1050
        for d in _alarm["Dimensions"]:
1✔
1051
            dimensions.append({"value": d["Value"], "name": d["Name"]})
1✔
1052
    details["Dimensions"] = dimensions or ""
1✔
1053

1054
    alarm_statistic = _alarm.get("Statistic")
1✔
1055
    alarm_extended_statistic = _alarm.get("ExtendedStatistic")
1✔
1056

1057
    if alarm_statistic:
1✔
1058
        details["StatisticType"] = "Statistic"
1✔
1059
        details["Statistic"] = camel_to_snake_case(alarm_statistic).upper()  # AWS returns uppercase
1✔
UNCOV
1060
    elif alarm_extended_statistic:
×
UNCOV
1061
        details["StatisticType"] = "ExtendedStatistic"
×
UNCOV
1062
        details["ExtendedStatistic"] = alarm_extended_statistic
×
1063

1064
    response["Trigger"] = details
1✔
1065

1066
    return json.dumps(response, cls=JSONEncoder)
1✔
1067

1068

1069
def create_message_response_update_composite_alarm_state_sns(
1✔
1070
    composite_alarm: LocalStackCompositeAlarm,
1071
    triggering_alarm: LocalStackMetricAlarm,
1072
    old_state: StateValue,
1073
):
1074
    _alarm = composite_alarm.alarm
1✔
1075
    response = {
1✔
1076
        "AWSAccountId": composite_alarm.account_id,
1077
        "AlarmName": _alarm["AlarmName"],
1078
        "AlarmDescription": _alarm.get("AlarmDescription"),
1079
        "AlarmRule": _alarm.get("AlarmRule"),
1080
        "OldStateValue": old_state,
1081
        "NewStateValue": _alarm["StateValue"],
1082
        "NewStateReason": _alarm["StateReason"],
1083
        "StateChangeTime": _alarm["StateUpdatedTimestamp"],
1084
        # the long-name for 'region' should be used - as we don't have it, we use the short name
1085
        # which needs to be slightly changed to make snapshot tests work
1086
        "Region": composite_alarm.region.replace("-", " ").capitalize(),
1087
        "AlarmArn": _alarm["AlarmArn"],
1088
        "OKActions": _alarm.get("OKActions", []),
1089
        "AlarmActions": _alarm.get("AlarmActions", []),
1090
        "InsufficientDataActions": _alarm.get("InsufficientDataActions", []),
1091
    }
1092

1093
    triggering_children = [
1✔
1094
        {
1095
            "Arn": triggering_alarm.alarm.get("AlarmArn"),
1096
            "State": {
1097
                "Value": triggering_alarm.alarm["StateValue"],
1098
                "Timestamp": triggering_alarm.alarm["StateUpdatedTimestamp"],
1099
            },
1100
        }
1101
    ]
1102

1103
    response["TriggeringChildren"] = triggering_children
1✔
1104

1105
    return json.dumps(response, cls=JSONEncoder)
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc