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

localstack / localstack / 16820655284

07 Aug 2025 05:03PM UTC coverage: 86.841% (-0.05%) from 86.892%
16820655284

push

github

web-flow
CFNV2: support CDK bootstrap and deployment (#12967)

32 of 38 new or added lines in 5 files covered. (84.21%)

2013 existing lines in 125 files now uncovered.

66606 of 76699 relevant lines covered (86.84%)

0.87 hits per line

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

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

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

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

109

110
class ValidationError(CommonServiceException):
1✔
111
    # TODO: check this error against AWS (doesn't exist in the API)
112
    def __init__(self, message: str):
1✔
113
        super().__init__("ValidationError", message, 400, True)
1✔
114

115

116
class InvalidParameterCombination(CommonServiceException):
1✔
117
    def __init__(self, message: str):
1✔
118
        super().__init__("InvalidParameterCombination", message, 400, True)
1✔
119

120

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

129
        if metric_item.get("StatisticValues") and metric_item.get("Value"):
1✔
130
            raise InvalidParameterCombinationException(
1✔
131
                f"The parameters MetricData.member.{indexplusone}.Value and MetricData.member.{indexplusone}.StatisticValues are mutually exclusive and you have specified both."
132
            )
133

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

142

143
class CloudwatchProvider(CloudwatchApi, ServiceLifecycleHook):
1✔
144
    """
145
    Cloudwatch provider.
146

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

154
    def __init__(self):
1✔
155
        self.alarm_scheduler: AlarmScheduler = None
1✔
156
        self.store = None
1✔
157
        self.cloudwatch_database = CloudwatchDatabase()
1✔
158

159
    @staticmethod
1✔
160
    def get_store(account_id: str, region: str) -> CloudWatchStore:
1✔
161
        return cloudwatch_stores[account_id][region]
1✔
162

163
    def accept_state_visitor(self, visitor: StateVisitor):
1✔
UNCOV
164
        visitor.visit(cloudwatch_stores)
×
UNCOV
165
        visitor.visit(AssetDirectory(self.service, CloudwatchDatabase.CLOUDWATCH_DATA_ROOT))
×
166

167
    def on_after_init(self):
1✔
168
        ROUTER.add(PATH_GET_RAW_METRICS, self.get_raw_metrics)
1✔
169
        self.start_alarm_scheduler()
1✔
170

171
    def on_before_state_reset(self):
1✔
UNCOV
172
        self.shutdown_alarm_scheduler()
×
UNCOV
173
        self.cloudwatch_database.clear_tables()
×
174

175
    def on_after_state_reset(self):
1✔
UNCOV
176
        self.cloudwatch_database = CloudwatchDatabase()
×
UNCOV
177
        self.start_alarm_scheduler()
×
178

179
    def on_before_state_load(self):
1✔
UNCOV
180
        self.shutdown_alarm_scheduler()
×
181

182
    def on_after_state_load(self):
1✔
UNCOV
183
        self.start_alarm_scheduler()
×
184

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

189
        start_worker_thread(restart_alarms)
×
190

191
    def on_before_stop(self):
1✔
192
        self.shutdown_alarm_scheduler()
1✔
193

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

308
    def set_alarm_state(
1✔
309
        self,
310
        context: RequestContext,
311
        alarm_name: AlarmName,
312
        state_value: StateValue,
313
        state_reason: StateReason,
314
        state_reason_data: StateReasonData = None,
315
        **kwargs,
316
    ) -> None:
317
        try:
1✔
318
            if state_reason_data:
1✔
319
                state_reason_data = json.loads(state_reason_data)
1✔
UNCOV
320
        except ValueError:
×
UNCOV
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
            if state_value not in ("OK", "ALARM", "INSUFFICIENT_DATA"):
1✔
336
                raise ValidationError(
1✔
337
                    f"1 validation error detected: Value '{state_value}' at 'stateValue' failed to satisfy constraint: Member must satisfy enum value set: [INSUFFICIENT_DATA, ALARM, OK]"
338
                )
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✔
UNCOV
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:
UNCOV
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
UNCOV
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
        ]:
UNCOV
418
            raise ValidationError(
×
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✔
UNCOV
427
                    raise ValidationError("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
            ]:
UNCOV
436
                raise ValidationError(
×
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✔
UNCOV
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
        ):
UNCOV
450
            raise ValidationError(
×
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✔
UNCOV
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✔
UNCOV
498
        elif state_value:
×
UNCOV
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())]
×
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✔
UNCOV
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✔
UNCOV
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 InvalidParameterCombination(
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] = 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: str,
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
        store.histories.append(
1✔
785
            {
786
                "Timestamp": timestamp_millis(alarm.alarm["StateUpdatedTimestamp"]),
787
                "HistoryItemType": HistoryItemType.StateUpdate,
788
                "AlarmName": alarm.alarm["AlarmName"],
789
                "HistoryData": json.dumps(history_data),
790
                "HistorySummary": f"Alarm updated from {old_state} to {state_value}",
791
                "AlarmType": "MetricAlarm"
792
                if isinstance(alarm, LocalStackMetricAlarm)
793
                else "CompositeAlarm",
794
            }
795
        )
796
        alarm.alarm["StateValue"] = state_value
1✔
797
        alarm.alarm["StateReason"] = state_reason
1✔
798
        if state_reason_data:
1✔
799
            alarm.alarm["StateReasonData"] = json.dumps(state_reason_data)
1✔
800
        alarm.alarm["StateUpdatedTimestamp"] = current_time
1✔
801

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

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

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

822
    def describe_alarm_history(
1✔
823
        self,
824
        context: RequestContext,
825
        alarm_name: AlarmName = None,
826
        alarm_types: AlarmTypes = None,
827
        history_item_type: HistoryItemType = None,
828
        start_date: Timestamp = None,
829
        end_date: Timestamp = None,
830
        max_records: MaxRecords = None,
831
        next_token: NextToken = None,
832
        scan_by: ScanBy = 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
        def _get_timestamp(input: dict):
1✔
UNCOV
841
            if timestamp_string := input.get("Timestamp"):
×
UNCOV
842
                return datetime.datetime.fromisoformat(timestamp_string)
×
843
            return None
×
844

845
        if start_date:
1✔
UNCOV
846
            history = [h for h in history if (date := _get_timestamp(h)) and date >= start_date]
×
847
        if end_date:
1✔
848
            history = [h for h in history if (date := _get_timestamp(h)) and date <= end_date]
×
849
        return DescribeAlarmHistoryOutput(AlarmHistoryItems=history)
1✔
850

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

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

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

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

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

962

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

982

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

1015

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

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

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

1057
    alarm_statistic = _alarm.get("Statistic")
1✔
1058
    alarm_extended_statistic = _alarm.get("ExtendedStatistic")
1✔
1059

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

1067
    response["Trigger"] = details
1✔
1068

1069
    return json.dumps(response, cls=JSONEncoder)
1✔
1070

1071

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

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

1106
    response["TriggeringChildren"] = triggering_children
1✔
1107

1108
    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