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

localstack / localstack / 20300289556

17 Dec 2025 09:47AM UTC coverage: 86.917% (+0.04%) from 86.873%
20300289556

push

github

web-flow
CI: Skip failing DNS unit test (#13536)

69993 of 80529 relevant lines covered (86.92%)

0.87 hits per line

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

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

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

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

111

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

116

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

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

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

138

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

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

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

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

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

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

166
    def on_before_start(self):
1✔
167
        self.start_alarm_scheduler()
1✔
168

169
    def on_before_state_reset(self):
1✔
170
        self.shutdown_alarm_scheduler()
×
171
        self.cloudwatch_database.clear_tables()
×
172

173
    def on_after_state_reset(self):
1✔
174
        self.cloudwatch_database = CloudwatchDatabase()
×
175
        self.start_alarm_scheduler()
×
176

177
    def on_before_state_load(self):
1✔
178
        self.shutdown_alarm_scheduler()
×
179

180
    def on_after_state_load(self):
1✔
181
        self.start_alarm_scheduler()
×
182

183
        def restart_alarms(*args):
×
184
            poll_condition(lambda: SERVICE_PLUGINS.is_running("cloudwatch"))
×
185
            self.alarm_scheduler.restart_existing_alarms()
×
186

187
        start_worker_thread(restart_alarms)
×
188

189
    def on_before_stop(self):
1✔
190
        self.shutdown_alarm_scheduler()
1✔
191

192
    def start_alarm_scheduler(self):
1✔
193
        if not self.alarm_scheduler:
1✔
194
            LOG.debug("starting cloudwatch scheduler")
1✔
195
            self.alarm_scheduler = AlarmScheduler()
1✔
196

197
    def shutdown_alarm_scheduler(self):
1✔
198
        if self.alarm_scheduler:
1✔
199
            LOG.debug("stopping cloudwatch scheduler")
1✔
200
            self.alarm_scheduler.shutdown_scheduler()
1✔
201
            self.alarm_scheduler = None
1✔
202

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

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

228
        self.cloudwatch_database.add_metric_data(
1✔
229
            context.account_id, context.region, namespace, metric_data
230
        )
231

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

250
        for diff in LABEL_DIFFERENTIATORS:
1✔
251
            non_unique = []
1✔
252
            for query in metric_data_queries:
1✔
253
                non_unique.append(query["MetricStat"][diff])
1✔
254
            if len(set(non_unique)) > 1:
1✔
255
                label_additions.append(diff)
1✔
256

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

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

274
            timestamps = query_result.get("timestamps", {})
1✔
275
            values = query_result.get("values", {})
1✔
276

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

286
            pagination = PaginatedList(timestamp_value_dicts)
1✔
287
            timestamp_page, nxt = pagination.get_page(
1✔
288
                lambda item: str(item.get("Timestamp")),
289
                next_token=next_token,
290
                page_size=limit,
291
            )
292

293
            timestamps = [item.get("Timestamp") for item in timestamp_page]
1✔
294
            values = [item.get("Value") for item in timestamp_page]
1✔
295

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

305
        return GetMetricDataOutput(MetricDataResults=results, NextToken=nxt, Messages=messages)
1✔
306

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

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

338
            old_state = alarm.alarm["StateValue"]
1✔
339

340
            old_state_reason = alarm.alarm["StateReason"]
1✔
341
            old_state_update_timestamp = alarm.alarm["StateUpdatedTimestamp"]
1✔
342

343
            if old_state == state_value:
1✔
344
                return
×
345

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

352
            self._update_state(
1✔
353
                context,
354
                alarm,
355
                state_value,
356
                state_reason,
357
                state_reason_data,
358
            )
359

360
            self._evaluate_composite_alarms(context, alarm)
1✔
361

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

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

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

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

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

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

469
            alarm_rule = composite_alarm.alarm["AlarmRule"]
1✔
470
            rule_expression_validation_result = self._validate_alarm_rule_expression(alarm_rule)
1✔
471
            [LOG.warning(w) for w in rule_expression_validation_result]
1✔
472

473
            alarm_arn = composite_alarm.alarm["AlarmArn"]
1✔
474
            store.alarms[alarm_arn] = composite_alarm
1✔
475

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

503
        # TODO: Pagination
504
        metric_alarms = [a for a in alarms if a.get("AlarmRule") is None]
1✔
505
        composite_alarms = [a for a in alarms if a.get("AlarmRule") is not None]
1✔
506
        return DescribeAlarmsOutput(CompositeAlarms=composite_alarms, MetricAlarms=metric_alarms)
1✔
507

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

529
        if statistic:
1✔
530
            alarms = [a for a in alarms if a.get("Statistic") == statistic]
1✔
531
        if dimensions:
1✔
532
            alarms = [a for a in alarms if a.get("Dimensions") == dimensions]
1✔
533
        if period:
1✔
534
            alarms = [a for a in alarms if a.get("Period") == period]
×
535
        if unit:
1✔
536
            alarms = [a for a in alarms if a.get("Unit") == unit]
×
537
        return DescribeAlarmsForMetricOutput(MetricAlarms=alarms)
1✔
538

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

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

557
    def tag_resource(
1✔
558
        self, context: RequestContext, resource_arn: AmazonResourceName, tags: TagList, **kwargs
559
    ) -> TagResourceOutput:
560
        store = self.get_store(context.account_id, context.region)
1✔
561
        store.TAGS.tag_resource(resource_arn, tags)
1✔
562
        return TagResourceOutput()
1✔
563

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

578
        store = self.get_store(context.account_id, context.region)
1✔
579
        store.dashboards[dashboard_name] = LocalStackDashboard(
1✔
580
            context.account_id, context.region, dashboard_name, dashboard_body
581
        )
582
        return PutDashboardOutput()
1✔
583

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

592
        return GetDashboardOutput(
1✔
593
            DashboardName=dashboard_name,
594
            DashboardBody=dashboard.dashboard_body,
595
            DashboardArn=dashboard.dashboard_arn,
596
        )
597

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

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

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

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

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

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

685
        if not start_time_unix < end_time_unix:
1✔
686
            raise InvalidParameterValueException(
1✔
687
                "The parameter StartTime must be less than the parameter EndTime."
688
            )
689

690
        expected_datapoints = (end_time_unix - start_time_unix) / period
1✔
691

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

698
        stat_datapoints = {}
1✔
699

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

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

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

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

758
        return GetMetricStatisticsOutput(Datapoints=datapoints, Label=metric_name)
1✔
759

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

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

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

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

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

840
        if start_date:
1✔
841
            history = [h for h in history if (date := h.get("Timestamp")) and date >= start_date]
×
842
        if end_date:
1✔
843
            history = [h for h in history if (date := h.get("Timestamp")) and date <= end_date]
×
844
        return DescribeAlarmHistoryOutput(AlarmHistoryItems=history)
1✔
845

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

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

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

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

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

957

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

977

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

1010

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

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

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

1052
    alarm_statistic = _alarm.get("Statistic")
1✔
1053
    alarm_extended_statistic = _alarm.get("ExtendedStatistic")
1✔
1054

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

1062
    response["Trigger"] = details
1✔
1063

1064
    return json.dumps(response, cls=JSONEncoder)
1✔
1065

1066

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

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

1101
    response["TriggeringChildren"] = triggering_children
1✔
1102

1103
    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