qontract-reconcile 0.10.2.dev345__py3-none-any.whl → 0.10.2.dev408__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. {qontract_reconcile-0.10.2.dev345.dist-info → qontract_reconcile-0.10.2.dev408.dist-info}/METADATA +11 -10
  2. {qontract_reconcile-0.10.2.dev345.dist-info → qontract_reconcile-0.10.2.dev408.dist-info}/RECORD +126 -120
  3. reconcile/aus/base.py +17 -14
  4. reconcile/automated_actions/config/integration.py +12 -0
  5. reconcile/aws_account_manager/integration.py +2 -2
  6. reconcile/aws_ami_cleanup/integration.py +6 -7
  7. reconcile/aws_ami_share.py +69 -62
  8. reconcile/aws_cloudwatch_log_retention/integration.py +155 -126
  9. reconcile/aws_ecr_image_pull_secrets.py +2 -2
  10. reconcile/aws_iam_keys.py +1 -0
  11. reconcile/aws_saml_idp/integration.py +7 -1
  12. reconcile/aws_saml_roles/integration.py +9 -3
  13. reconcile/change_owners/change_owners.py +1 -1
  14. reconcile/change_owners/diff.py +2 -4
  15. reconcile/checkpoint.py +11 -3
  16. reconcile/cli.py +33 -8
  17. reconcile/dashdotdb_dora.py +4 -11
  18. reconcile/database_access_manager.py +118 -111
  19. reconcile/endpoints_discovery/integration.py +4 -1
  20. reconcile/endpoints_discovery/merge_request_manager.py +9 -11
  21. reconcile/external_resources/factories.py +5 -12
  22. reconcile/external_resources/integration.py +1 -1
  23. reconcile/external_resources/manager.py +5 -3
  24. reconcile/external_resources/meta.py +0 -1
  25. reconcile/external_resources/model.py +10 -10
  26. reconcile/external_resources/reconciler.py +5 -2
  27. reconcile/external_resources/secrets_sync.py +4 -6
  28. reconcile/external_resources/state.py +5 -4
  29. reconcile/gabi_authorized_users.py +8 -5
  30. reconcile/gitlab_housekeeping.py +13 -15
  31. reconcile/gitlab_mr_sqs_consumer.py +2 -2
  32. reconcile/gitlab_owners.py +15 -11
  33. reconcile/gql_definitions/automated_actions/instance.py +41 -2
  34. reconcile/gql_definitions/aws_ami_cleanup/aws_accounts.py +10 -0
  35. reconcile/gql_definitions/aws_cloudwatch_log_retention/aws_accounts.py +22 -61
  36. reconcile/gql_definitions/aws_saml_idp/aws_accounts.py +10 -0
  37. reconcile/gql_definitions/aws_saml_roles/aws_accounts.py +10 -0
  38. reconcile/gql_definitions/common/aws_vpc_requests.py +10 -0
  39. reconcile/gql_definitions/common/clusters.py +2 -0
  40. reconcile/gql_definitions/external_resources/external_resources_namespaces.py +84 -1
  41. reconcile/gql_definitions/external_resources/external_resources_settings.py +2 -0
  42. reconcile/gql_definitions/fragments/aws_account_common.py +2 -0
  43. reconcile/gql_definitions/fragments/aws_organization.py +33 -0
  44. reconcile/gql_definitions/fragments/aws_vpc_request.py +2 -0
  45. reconcile/gql_definitions/introspection.json +3474 -1986
  46. reconcile/gql_definitions/jira_permissions_validator/jira_boards_for_permissions_validator.py +4 -0
  47. reconcile/gql_definitions/terraform_init/aws_accounts.py +14 -0
  48. reconcile/gql_definitions/terraform_resources/terraform_resources_namespaces.py +33 -1
  49. reconcile/gql_definitions/terraform_tgw_attachments/aws_accounts.py +10 -0
  50. reconcile/jenkins_worker_fleets.py +1 -0
  51. reconcile/jira_permissions_validator.py +236 -121
  52. reconcile/ocm/types.py +6 -0
  53. reconcile/openshift_base.py +47 -1
  54. reconcile/openshift_cluster_bots.py +2 -1
  55. reconcile/openshift_resources_base.py +6 -2
  56. reconcile/openshift_saas_deploy.py +2 -2
  57. reconcile/openshift_saas_deploy_trigger_cleaner.py +3 -5
  58. reconcile/openshift_upgrade_watcher.py +3 -3
  59. reconcile/queries.py +131 -0
  60. reconcile/saas_auto_promotions_manager/subscriber.py +4 -3
  61. reconcile/slack_usergroups.py +4 -3
  62. reconcile/sql_query.py +1 -0
  63. reconcile/statuspage/integrations/maintenances.py +4 -3
  64. reconcile/statuspage/status.py +5 -8
  65. reconcile/templates/rosa-classic-cluster-creation.sh.j2 +4 -0
  66. reconcile/templates/rosa-hcp-cluster-creation.sh.j2 +3 -0
  67. reconcile/templating/renderer.py +2 -1
  68. reconcile/terraform_aws_route53.py +7 -1
  69. reconcile/terraform_init/integration.py +185 -21
  70. reconcile/terraform_resources.py +11 -1
  71. reconcile/terraform_tgw_attachments.py +7 -1
  72. reconcile/terraform_users.py +7 -0
  73. reconcile/terraform_vpc_peerings.py +14 -3
  74. reconcile/terraform_vpc_resources/integration.py +7 -0
  75. reconcile/typed_queries/aws_account_tags.py +41 -0
  76. reconcile/typed_queries/saas_files.py +2 -2
  77. reconcile/utils/aggregated_list.py +4 -3
  78. reconcile/utils/aws_api.py +51 -20
  79. reconcile/utils/aws_api_typed/api.py +38 -9
  80. reconcile/utils/aws_api_typed/cloudformation.py +149 -0
  81. reconcile/utils/aws_api_typed/logs.py +73 -0
  82. reconcile/utils/datetime_util.py +67 -0
  83. reconcile/utils/differ.py +2 -3
  84. reconcile/utils/early_exit_cache.py +3 -2
  85. reconcile/utils/expiration.py +7 -3
  86. reconcile/utils/external_resource_spec.py +24 -1
  87. reconcile/utils/filtering.py +1 -1
  88. reconcile/utils/helm.py +2 -1
  89. reconcile/utils/helpers.py +1 -1
  90. reconcile/utils/jinja2/utils.py +4 -96
  91. reconcile/utils/jira_client.py +82 -63
  92. reconcile/utils/jjb_client.py +9 -12
  93. reconcile/utils/jobcontroller/controller.py +1 -1
  94. reconcile/utils/jobcontroller/models.py +17 -1
  95. reconcile/utils/json.py +32 -0
  96. reconcile/utils/merge_request_manager/merge_request_manager.py +3 -3
  97. reconcile/utils/merge_request_manager/parser.py +2 -2
  98. reconcile/utils/mr/app_interface_reporter.py +2 -2
  99. reconcile/utils/mr/base.py +2 -2
  100. reconcile/utils/mr/notificator.py +2 -2
  101. reconcile/utils/mr/update_access_report_base.py +3 -4
  102. reconcile/utils/oc.py +113 -95
  103. reconcile/utils/oc_filters.py +3 -3
  104. reconcile/utils/ocm/products.py +6 -0
  105. reconcile/utils/ocm/search_filters.py +3 -6
  106. reconcile/utils/ocm/service_log.py +3 -5
  107. reconcile/utils/openshift_resource.py +10 -5
  108. reconcile/utils/output.py +3 -2
  109. reconcile/utils/pagerduty_api.py +5 -5
  110. reconcile/utils/runtime/integration.py +1 -2
  111. reconcile/utils/runtime/runner.py +2 -2
  112. reconcile/utils/saasherder/models.py +2 -1
  113. reconcile/utils/saasherder/saasherder.py +9 -7
  114. reconcile/utils/slack_api.py +24 -2
  115. reconcile/utils/sloth.py +171 -2
  116. reconcile/utils/sqs_gateway.py +2 -1
  117. reconcile/utils/state.py +2 -1
  118. reconcile/utils/terraform_client.py +4 -3
  119. reconcile/utils/terrascript_aws_client.py +165 -111
  120. reconcile/utils/vault.py +1 -1
  121. reconcile/vault_replication.py +107 -42
  122. tools/app_interface_reporter.py +4 -4
  123. tools/cli_commands/systems_and_tools.py +5 -1
  124. tools/qontract_cli.py +25 -13
  125. {qontract_reconcile-0.10.2.dev345.dist-info → qontract_reconcile-0.10.2.dev408.dist-info}/WHEEL +0 -0
  126. {qontract_reconcile-0.10.2.dev345.dist-info → qontract_reconcile-0.10.2.dev408.dist-info}/entry_points.txt +0 -0
@@ -6,9 +6,11 @@ from functools import cached_property
6
6
  from typing import TYPE_CHECKING, Any, TypeVar
7
7
 
8
8
  from boto3 import Session
9
+ from botocore.config import Config
9
10
  from pydantic import BaseModel
10
11
 
11
12
  import reconcile.utils.aws_api_typed.account
13
+ import reconcile.utils.aws_api_typed.cloudformation
12
14
  import reconcile.utils.aws_api_typed.dynamodb
13
15
  import reconcile.utils.aws_api_typed.iam
14
16
  import reconcile.utils.aws_api_typed.organization
@@ -17,8 +19,10 @@ import reconcile.utils.aws_api_typed.service_quotas
17
19
  import reconcile.utils.aws_api_typed.sts
18
20
  import reconcile.utils.aws_api_typed.support
19
21
  from reconcile.utils.aws_api_typed.account import AWSApiAccount
22
+ from reconcile.utils.aws_api_typed.cloudformation import AWSApiCloudFormation
20
23
  from reconcile.utils.aws_api_typed.dynamodb import AWSApiDynamoDB
21
24
  from reconcile.utils.aws_api_typed.iam import AWSApiIam
25
+ from reconcile.utils.aws_api_typed.logs import AWSApiLogs
22
26
  from reconcile.utils.aws_api_typed.organization import AWSApiOrganizations
23
27
  from reconcile.utils.aws_api_typed.s3 import AWSApiS3
24
28
  from reconcile.utils.aws_api_typed.service_quotas import AWSApiServiceQuotas
@@ -31,7 +35,9 @@ if TYPE_CHECKING:
31
35
  SubApi = TypeVar(
32
36
  "SubApi",
33
37
  AWSApiAccount,
38
+ AWSApiCloudFormation,
34
39
  AWSApiDynamoDB,
40
+ AWSApiLogs,
35
41
  AWSApiIam,
36
42
  AWSApiOrganizations,
37
43
  AWSApiS3,
@@ -40,6 +46,13 @@ SubApi = TypeVar(
40
46
  AWSApiSupport,
41
47
  )
42
48
 
49
+ DEFAULT_CONFIG = Config(
50
+ retries={
51
+ "mode": "standard",
52
+ "total_max_attempts": 10,
53
+ },
54
+ )
55
+
43
56
 
44
57
  class AWSCredentials(ABC):
45
58
  @abstractmethod
@@ -174,28 +187,34 @@ class AWSApi:
174
187
  """Return a new or cached sub api client."""
175
188
  match api_cls:
176
189
  case reconcile.utils.aws_api_typed.account.AWSApiAccount:
177
- client = self.session.client("account")
190
+ client = self.session.client("account", config=DEFAULT_CONFIG)
191
+ api = api_cls(client)
192
+ case reconcile.utils.aws_api_typed.cloudformation.AWSApiCloudFormation:
193
+ client = self.session.client("cloudformation", config=DEFAULT_CONFIG)
178
194
  api = api_cls(client)
179
195
  case reconcile.utils.aws_api_typed.dynamodb.AWSApiDynamoDB:
180
- client = self.session.client("dynamodb")
196
+ client = self.session.client("dynamodb", config=DEFAULT_CONFIG)
181
197
  api = api_cls(client)
182
198
  case reconcile.utils.aws_api_typed.iam.AWSApiIam:
183
- client = self.session.client("iam")
199
+ client = self.session.client("iam", config=DEFAULT_CONFIG)
200
+ api = api_cls(client)
201
+ case reconcile.utils.aws_api_typed.logs.AWSApiLogs:
202
+ client = self.session.client("logs", config=DEFAULT_CONFIG)
184
203
  api = api_cls(client)
185
204
  case reconcile.utils.aws_api_typed.organization.AWSApiOrganizations:
186
- client = self.session.client("organizations")
205
+ client = self.session.client("organizations", config=DEFAULT_CONFIG)
187
206
  api = api_cls(client)
188
207
  case reconcile.utils.aws_api_typed.s3.AWSApiS3:
189
- client = self.session.client("s3")
208
+ client = self.session.client("s3", config=DEFAULT_CONFIG)
190
209
  api = api_cls(client)
191
210
  case reconcile.utils.aws_api_typed.service_quotas.AWSApiServiceQuotas:
192
- client = self.session.client("service-quotas")
211
+ client = self.session.client("service-quotas", config=DEFAULT_CONFIG)
193
212
  api = api_cls(client)
194
213
  case reconcile.utils.aws_api_typed.sts.AWSApiSts:
195
- client = self.session.client("sts")
214
+ client = self.session.client("sts", config=DEFAULT_CONFIG)
196
215
  api = api_cls(client)
197
216
  case reconcile.utils.aws_api_typed.support.AWSApiSupport:
198
- client = self.session.client("support")
217
+ client = self.session.client("support", config=DEFAULT_CONFIG)
199
218
  api = api_cls(client)
200
219
  case _:
201
220
  raise ValueError(f"Unknown API class: {api_cls}")
@@ -205,9 +224,14 @@ class AWSApi:
205
224
 
206
225
  @cached_property
207
226
  def account(self) -> AWSApiAccount:
208
- """Return an AWS Acount Api client"""
227
+ """Return an AWS Account Api client"""
209
228
  return self._init_sub_api(AWSApiAccount)
210
229
 
230
+ @cached_property
231
+ def cloudformation(self) -> AWSApiCloudFormation:
232
+ """Return an AWS CloudFormation Api client"""
233
+ return self._init_sub_api(AWSApiCloudFormation)
234
+
211
235
  @cached_property
212
236
  def dynamodb(self) -> AWSApiDynamoDB:
213
237
  """Return an AWS DynamoDB Api client"""
@@ -218,6 +242,11 @@ class AWSApi:
218
242
  """Return an AWS IAM Api client."""
219
243
  return self._init_sub_api(AWSApiIam)
220
244
 
245
+ @cached_property
246
+ def logs(self) -> AWSApiLogs:
247
+ """Return an AWS Logs Api client."""
248
+ return self._init_sub_api(AWSApiLogs)
249
+
221
250
  @cached_property
222
251
  def organizations(self) -> AWSApiOrganizations:
223
252
  """Return an AWS Organizations Api client."""
@@ -0,0 +1,149 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from reconcile.utils.json import json_dumps
6
+
7
+ if TYPE_CHECKING:
8
+ from mypy_boto3_cloudformation import CloudFormationClient
9
+ from mypy_boto3_cloudformation.type_defs import (
10
+ ParameterTypeDef,
11
+ StackTypeDef,
12
+ TagTypeDef,
13
+ )
14
+
15
+
16
+ class AWSApiCloudFormation:
17
+ def __init__(self, client: CloudFormationClient) -> None:
18
+ self.client = client
19
+
20
+ def create_stack(
21
+ self,
22
+ stack_name: str,
23
+ change_set_name: str,
24
+ template_body: str,
25
+ parameters: dict[str, str] | None = None,
26
+ tags: dict[str, str] | None = None,
27
+ ) -> str:
28
+ """
29
+ Create a CloudFormation stack using a change set with import existing resources.
30
+ This method creates a change set of type "CREATE" with the provided template and parameters,
31
+ waits for the change set to be created, executes it, and then waits for the stack creation to complete.
32
+ It returns the StackId of the created stack.
33
+
34
+ Args:
35
+ stack_name (str): The name of the stack to create.
36
+ change_set_name (str): The name of the change set to create.
37
+ template_body (str): The CloudFormation template body as a string.
38
+ parameters (dict[str, str] | None): A dictionary of parameter key-value pairs for
39
+ the stack. Defaults to None.
40
+ tags (dict[str, str] | None): A dictionary of tag key-value pairs to
41
+ associate with the stack. Defaults to None.
42
+
43
+ Returns:
44
+ str: The StackId of the created stack.
45
+ """
46
+ response = self.client.create_change_set(
47
+ StackName=stack_name,
48
+ ChangeSetName=change_set_name,
49
+ TemplateBody=template_body,
50
+ ChangeSetType="CREATE",
51
+ Parameters=self._build_parameters(parameters or {}),
52
+ Tags=self._build_tags(tags or {}),
53
+ ImportExistingResources=True,
54
+ )
55
+ change_set_arn = response["Id"]
56
+ self.client.get_waiter("change_set_create_complete").wait(
57
+ ChangeSetName=change_set_arn
58
+ )
59
+ self.client.execute_change_set(ChangeSetName=change_set_arn)
60
+ self.client.get_waiter("stack_create_complete").wait(StackName=stack_name)
61
+ return response["StackId"]
62
+
63
+ def update_stack(
64
+ self,
65
+ stack_name: str,
66
+ template_body: str,
67
+ parameters: dict[str, str] | None = None,
68
+ tags: dict[str, str] | None = None,
69
+ ) -> str:
70
+ """
71
+ Update a CloudFormation stack with the provided template and parameters.
72
+ This method updates the specified stack, waits for the update to complete,
73
+ and returns the StackId of the updated stack.
74
+
75
+ Args:
76
+ stack_name (str): The name of the stack to update.
77
+ template_body (str): The CloudFormation template body as a string.
78
+ parameters (dict[str, str] | None): A dictionary of parameter key-value pairs for
79
+ the stack. Defaults to None.
80
+ tags (dict[str, str] | None): A dictionary of tag key-value pairs to
81
+ associate with the stack. Defaults to None.
82
+
83
+ Returns:
84
+ str: The StackId of the updated stack.
85
+ """
86
+ response = self.client.update_stack(
87
+ StackName=stack_name,
88
+ TemplateBody=template_body,
89
+ Parameters=self._build_parameters(parameters or {}),
90
+ Tags=self._build_tags(tags or {}),
91
+ )
92
+ self.client.get_waiter("stack_update_complete").wait(StackName=stack_name)
93
+ return response["StackId"]
94
+
95
+ def get_stack(self, stack_name: str) -> StackTypeDef | None:
96
+ """
97
+ Retrieve information about a CloudFormation stack by its name.
98
+ If the stack exists, it returns the stack details as a dictionary.
99
+ If the stack does not exist, it returns None.
100
+
101
+ Args:
102
+ stack_name (str): The name of the stack to retrieve.
103
+
104
+ Returns:
105
+ StackTypeDef | None: The stack details if found, otherwise None.
106
+ """
107
+ try:
108
+ response = self.client.describe_stacks(StackName=stack_name)
109
+ return response["Stacks"][0]
110
+ except self.client.exceptions.ClientError as e:
111
+ if e.response["Error"]["Code"] == "ValidationError":
112
+ return None
113
+ raise
114
+
115
+ def get_template_body(self, stack_name: str) -> str:
116
+ """
117
+ Retrieve the CloudFormation template body for a specified stack.
118
+
119
+ Args:
120
+ stack_name (str): The name of the stack whose template is to be retrieved.
121
+
122
+ Returns:
123
+ str: The CloudFormation template body as a string.
124
+ """
125
+ response = self.client.get_template(StackName=stack_name)
126
+ # TemplateBody is str when using yaml
127
+ if isinstance(response["TemplateBody"], str):
128
+ return response["TemplateBody"]
129
+ return json_dumps(response["TemplateBody"])
130
+
131
+ @staticmethod
132
+ def _build_parameters(parameters: dict[str, str]) -> list[ParameterTypeDef]:
133
+ return [
134
+ {
135
+ "ParameterKey": key,
136
+ "ParameterValue": value,
137
+ }
138
+ for key, value in sorted(parameters.items())
139
+ ]
140
+
141
+ @staticmethod
142
+ def _build_tags(tags: dict[str, str]) -> list[TagTypeDef]:
143
+ return [
144
+ {
145
+ "Key": key,
146
+ "Value": value,
147
+ }
148
+ for key, value in sorted(tags.items())
149
+ ]
@@ -0,0 +1,73 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from collections.abc import Iterable, Iterator
7
+
8
+ from mypy_boto3_logs import CloudWatchLogsClient
9
+ from mypy_boto3_logs.type_defs import LogGroupTypeDef
10
+
11
+
12
+ class AWSApiLogs:
13
+ def __init__(self, client: CloudWatchLogsClient) -> None:
14
+ self.client = client
15
+
16
+ def get_log_groups(self) -> Iterator[LogGroupTypeDef]:
17
+ paginator = self.client.get_paginator("describe_log_groups")
18
+ for page in paginator.paginate():
19
+ yield from page["logGroups"]
20
+
21
+ def delete_log_group(self, log_group_name: str) -> None:
22
+ self.client.delete_log_group(logGroupName=log_group_name)
23
+
24
+ def put_retention_policy(
25
+ self,
26
+ log_group_name: str,
27
+ retention_in_days: int,
28
+ ) -> None:
29
+ self.client.put_retention_policy(
30
+ logGroupName=log_group_name,
31
+ retentionInDays=retention_in_days,
32
+ )
33
+
34
+ def get_tags(self, arn: str) -> dict[str, str]:
35
+ tags = self.client.list_tags_for_resource(
36
+ resourceArn=self._normalize_log_group_arn(arn),
37
+ )
38
+ return tags.get("tags") or {}
39
+
40
+ def set_tags(
41
+ self,
42
+ arn: str,
43
+ tags: dict[str, str],
44
+ ) -> None:
45
+ self.client.tag_resource(
46
+ resourceArn=self._normalize_log_group_arn(arn),
47
+ tags=tags,
48
+ )
49
+
50
+ def delete_tags(
51
+ self,
52
+ arn: str,
53
+ tag_keys: Iterable[str],
54
+ ) -> None:
55
+ self.client.untag_resource(
56
+ resourceArn=self._normalize_log_group_arn(arn),
57
+ tagKeys=list(tag_keys),
58
+ )
59
+
60
+ @staticmethod
61
+ def _normalize_log_group_arn(arn: str) -> str:
62
+ """
63
+ Normalize a log group ARN by removing any trailing ":*".
64
+
65
+ DescribeLogGroups response arn has additional :* at the end.
66
+
67
+ Args:
68
+ arn: The ARN of the log group.
69
+
70
+ Returns:
71
+ The normalized ARN without the trailing ":*".
72
+ """
73
+ return arn.rstrip(":*")
@@ -0,0 +1,67 @@
1
+ from datetime import UTC, datetime
2
+
3
+ ISO8601 = "%Y-%m-%dT%H:%M:%SZ"
4
+ ISO8601_MICRO = "%Y-%m-%dT%H:%M:%S.%fZ"
5
+
6
+
7
+ def utc_now() -> datetime:
8
+ """
9
+ Get the current UTC datetime.
10
+
11
+ Returns:
12
+ A datetime object representing the current time in UTC.
13
+ """
14
+ return datetime.now(tz=UTC)
15
+
16
+
17
+ def ensure_utc(dt: datetime) -> datetime:
18
+ """
19
+ Ensure the provided datetime is in UTC timezone.
20
+
21
+ Args:
22
+ dt: A datetime object.
23
+
24
+ Returns:
25
+ A datetime object in UTC timezone.
26
+ """
27
+ if dt.tzinfo is None:
28
+ return dt.replace(tzinfo=UTC)
29
+ return dt.astimezone(UTC)
30
+
31
+
32
+ def to_utc_seconds_iso_format(dt: datetime) -> str:
33
+ """
34
+ Convert a datetime object to ISO 8601 format YYYY-MM-DDTHH:MM:SSZ.
35
+
36
+ Args:
37
+ dt: A datetime object.
38
+
39
+ Returns:
40
+ A string representing the datetime in ISO 8601 format.
41
+ """
42
+ return ensure_utc(dt).strftime(ISO8601)
43
+
44
+
45
+ def to_utc_microseconds_iso_format(dt: datetime) -> str:
46
+ """
47
+ Convert a datetime object to ISO 8601 format with microseconds YYYY-MM-DDTHH:MM:SS.mmmmmmZ.
48
+
49
+ Args:
50
+ dt: A datetime object.
51
+
52
+ Returns:
53
+ A string representing the datetime in ISO 8601 format with microseconds.
54
+ """
55
+ return ensure_utc(dt).strftime(ISO8601_MICRO)
56
+
57
+
58
+ def from_utc_iso_format(dt_str: str) -> datetime:
59
+ """
60
+ Parse a datetime string in ISO 8601 format to a datetime object.
61
+
62
+ Args:
63
+ dt_str: A string representing the datetime in ISO 8601 format.
64
+ Returns:
65
+ A datetime object in UTC timezone.
66
+ """
67
+ return ensure_utc(datetime.fromisoformat(dt_str))
reconcile/utils/differ.py CHANGED
@@ -7,7 +7,6 @@ from collections.abc import (
7
7
  from dataclasses import dataclass
8
8
  from typing import (
9
9
  Any,
10
- Generic,
11
10
  TypeVar,
12
11
  )
13
12
 
@@ -18,13 +17,13 @@ Key = TypeVar("Key")
18
17
 
19
18
 
20
19
  @dataclass(frozen=True, eq=True)
21
- class DiffPair(Generic[Current, Desired]):
20
+ class DiffPair[Current, Desired]:
22
21
  current: Current
23
22
  desired: Desired
24
23
 
25
24
 
26
25
  @dataclass(frozen=True, eq=True)
27
- class DiffResult(Generic[Current, Desired, Key]):
26
+ class DiffResult[Current, Desired, Key]:
28
27
  add: dict[Key, Desired]
29
28
  delete: dict[Key, Current]
30
29
  change: dict[Key, DiffPair[Current, Desired]]
@@ -7,6 +7,7 @@ from typing import Any, Self
7
7
  from deepdiff import DeepHash
8
8
  from pydantic import BaseModel
9
9
 
10
+ from reconcile.utils.datetime_util import utc_now
10
11
  from reconcile.utils.secret_reader import SecretReaderBase
11
12
  from reconcile.utils.state import State, init_state
12
13
 
@@ -185,7 +186,7 @@ class EarlyExitCache:
185
186
  :param latest_cache_source_digest: latest cache source digest, used to check stale for dry run cache
186
187
  :return: None
187
188
  """
188
- expire_at = datetime.now(tz=UTC) + timedelta(seconds=ttl_seconds)
189
+ expire_at = utc_now() + timedelta(seconds=ttl_seconds)
189
190
  metadata = {
190
191
  EXPIRE_AT_METADATA_KEY: str(int(expire_at.timestamp())),
191
192
  CACHE_SOURCE_DIGEST_METADATA_KEY: key.cache_source_digest,
@@ -233,7 +234,7 @@ class EarlyExitCache:
233
234
  int(metadata[EXPIRE_AT_METADATA_KEY]),
234
235
  tz=UTC,
235
236
  )
236
- now = datetime.now(UTC)
237
+ now = utc_now()
237
238
  return now >= expire_at
238
239
 
239
240
  def _head_dry_run_status(
@@ -6,6 +6,8 @@ from typing import (
6
6
  cast,
7
7
  )
8
8
 
9
+ from reconcile.utils.datetime_util import ensure_utc, utc_now
10
+
9
11
  DATE_FORMAT = "%Y-%m-%d"
10
12
 
11
13
 
@@ -17,12 +19,14 @@ DictsOrRoles = TypeVar("DictsOrRoles", bound=Iterable[FilterableRole] | Iterable
17
19
 
18
20
 
19
21
  def date_expired(date: str) -> bool:
20
- exp_date = datetime.datetime.strptime(date, DATE_FORMAT).date()
21
- current_date = datetime.datetime.utcnow().date()
22
+ exp_date = ensure_utc(datetime.datetime.strptime(date, DATE_FORMAT)).date() # noqa: DTZ007
23
+ current_date = utc_now().date()
22
24
  return current_date >= exp_date
23
25
 
24
26
 
25
- def filter(roles: DictsOrRoles | None) -> DictsOrRoles:
27
+ def filter[DictsOrRoles: Iterable[FilterableRole] | Iterable[dict]](
28
+ roles: DictsOrRoles | None,
29
+ ) -> DictsOrRoles:
26
30
  """Filters roles and returns the ones which are not yet expired."""
27
31
  filtered = []
28
32
  for r in roles or []:
@@ -144,13 +144,36 @@ class ExternalResourceSpec:
144
144
  return {}
145
145
 
146
146
  def tags(self, integration: str) -> dict[str, str]:
147
- return {
147
+ tags = {
148
148
  "managed_by_integration": integration,
149
149
  "cluster": self.cluster_name,
150
150
  "namespace": self.namespace_name,
151
151
  "environment": self.namespace["environment"]["name"],
152
152
  "app": self.namespace["app"]["name"],
153
153
  }
154
+ if app_code := self.namespace["app"].get("appCode"):
155
+ tags["app-code"] = app_code
156
+ if cost_center := self.namespace["app"].get("costCenter"):
157
+ tags["cost-center"] = cost_center
158
+ if service_phase := self.namespace["environment"].get("servicePhase"):
159
+ tags["service-phase"] = service_phase
160
+
161
+ resource_tags_str = self.resource.get("tags")
162
+ if resource_tags_str:
163
+ resource_tags = json.loads(resource_tags_str)
164
+ # normalize camelCase keys to kebab-case
165
+ key_mapping = {
166
+ "appCode": "app-code",
167
+ "costCenter": "cost-center",
168
+ "servicePhase": "service-phase",
169
+ }
170
+ normalized_tags = {}
171
+ for key, value in resource_tags.items():
172
+ normalized_key = key_mapping.get(key, key)
173
+ normalized_tags[normalized_key] = value
174
+ tags.update(normalized_tags)
175
+
176
+ return tags
154
177
 
155
178
  def get_secret_field(self, field: str) -> str | None:
156
179
  return self.secret.get(field)
@@ -6,7 +6,7 @@ KeyType = TypeVar("KeyType")
6
6
  ValueType = TypeVar("ValueType")
7
7
 
8
8
 
9
- def remove_none_values_from_dict(
9
+ def remove_none_values_from_dict[KeyType, ValueType](
10
10
  a_dict: dict[KeyType, ValueType | None],
11
11
  ) -> dict[KeyType, ValueType]:
12
12
  """
reconcile/utils/helm.py CHANGED
@@ -11,6 +11,7 @@ from typing import Any
11
11
  import yaml
12
12
 
13
13
  from reconcile.utils import git
14
+ from reconcile.utils.json import json_dumps
14
15
  from reconcile.utils.runtime.sharding import ShardSpec
15
16
 
16
17
 
@@ -70,7 +71,7 @@ def do_template(
70
71
  with tempfile.NamedTemporaryFile(
71
72
  mode="w+", encoding="locale"
72
73
  ) as values_file:
73
- values_file.write(json.dumps(values, cls=JSONEncoder))
74
+ values_file.write(json_dumps(values, cls=JSONEncoder))
74
75
  values_file.flush()
75
76
  cmd = [
76
77
  "helm",
@@ -47,7 +47,7 @@ def flatten(
47
47
  Item = TypeVar("Item")
48
48
 
49
49
 
50
- def find_duplicates(items: Iterable[Item]) -> list[Item]:
50
+ def find_duplicates[Item](items: Iterable[Item]) -> list[Item]:
51
51
  return [item for item, count in Counter(items).items() if count > 1]
52
52
 
53
53