File: models.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (223 lines) | stat: -rw-r--r-- 7,999 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
"""PrometheusServiceBackend class with methods for supported APIs."""

from typing import Any, Callable, Optional

from moto.core.base_backend import BackendDict, BaseBackend
from moto.core.common_models import BaseModel
from moto.core.utils import unix_time
from moto.moto_api._internal import mock_random
from moto.utilities.paginator import paginate
from moto.utilities.tagging_service import TaggingService
from moto.utilities.utils import get_partition

from .exceptions import RuleGroupNamespaceNotFound, WorkspaceNotFound
from .utils import PAGINATION_MODEL


class RuleGroupNamespace(BaseModel):
    def __init__(
        self,
        account_id: str,
        region: str,
        workspace_id: str,
        name: str,
        data: str,
        tag_fn: Callable[[str], dict[str, str]],
    ):
        self.name = name
        self.data = data
        self.tag_fn = tag_fn
        self.arn = f"arn:{get_partition(region)}:aps:{region}:{account_id}:rulegroupsnamespace/{workspace_id}/{self.name}"
        self.created_at = unix_time()
        self.modified_at = self.created_at

    def update(self, new_data: str) -> None:
        self.data = new_data
        self.modified_at = unix_time()

    def to_dict(self) -> dict[str, Any]:
        return {
            "name": self.name,
            "arn": self.arn,
            "status": {"statusCode": "ACTIVE"},
            "createdAt": self.created_at,
            "modifiedAt": self.modified_at,
            "data": self.data,
            "tags": self.tag_fn(self.arn),
        }


class Workspace(BaseModel):
    def __init__(
        self,
        account_id: str,
        region: str,
        alias: str,
        tag_fn: Callable[[str], dict[str, str]],
    ):
        self.alias = alias
        self.workspace_id = f"ws-{mock_random.uuid4()}"
        self.arn = f"arn:{get_partition(region)}:aps:{region}:{account_id}:workspace/{self.workspace_id}"
        self.endpoint = f"https://aps-workspaces.{region}.amazonaws.com/workspaces/{self.workspace_id}/"
        self.status = {"statusCode": "ACTIVE"}
        self.created_at = unix_time()
        self.tag_fn = tag_fn
        self.rule_group_namespaces: dict[str, RuleGroupNamespace] = {}
        self.logging_config: Optional[dict[str, Any]] = None

    def to_dict(self) -> dict[str, Any]:
        return {
            "alias": self.alias,
            "arn": self.arn,
            "workspaceId": self.workspace_id,
            "status": self.status,
            "createdAt": self.created_at,
            "prometheusEndpoint": self.endpoint,
            "tags": self.tag_fn(self.arn),
        }


class PrometheusServiceBackend(BaseBackend):
    """Implementation of PrometheusService APIs."""

    def __init__(self, region_name: str, account_id: str):
        super().__init__(region_name, account_id)
        self.workspaces: dict[str, Workspace] = {}
        self.tagger = TaggingService()

    def create_workspace(self, alias: str, tags: dict[str, str]) -> Workspace:
        """
        The ClientToken-parameter is not yet implemented
        """
        workspace = Workspace(
            self.account_id,
            self.region_name,
            alias=alias,
            tag_fn=self.list_tags_for_resource,
        )
        self.workspaces[workspace.workspace_id] = workspace
        self.tag_resource(workspace.arn, tags)
        return workspace

    def describe_workspace(self, workspace_id: str) -> Workspace:
        if workspace_id not in self.workspaces:
            raise WorkspaceNotFound(workspace_id)
        return self.workspaces[workspace_id]

    def list_tags_for_resource(self, resource_arn: str) -> dict[str, str]:
        return self.tagger.get_tag_dict_for_resource(resource_arn)

    def update_workspace_alias(self, alias: str, workspace_id: str) -> None:
        """
        The ClientToken-parameter is not yet implemented
        """
        self.workspaces[workspace_id].alias = alias

    def delete_workspace(self, workspace_id: str) -> None:
        """
        The ClientToken-parameter is not yet implemented
        """
        self.workspaces.pop(workspace_id, None)

    @paginate(pagination_model=PAGINATION_MODEL)
    def list_workspaces(self, alias: str) -> list[Workspace]:
        if alias:
            return [w for w in self.workspaces.values() if w.alias == alias]
        return list(self.workspaces.values())

    def tag_resource(self, resource_arn: str, tags: dict[str, str]) -> None:
        tag_list = self.tagger.convert_dict_to_tags_input(tags)
        self.tagger.tag_resource(resource_arn, tag_list)

    def untag_resource(self, resource_arn: str, tag_keys: list[str]) -> None:
        self.tagger.untag_resource_using_names(resource_arn, tag_keys)

    def create_rule_groups_namespace(
        self, data: str, name: str, tags: dict[str, str], workspace_id: str
    ) -> RuleGroupNamespace:
        """
        The ClientToken-parameter is not yet implemented
        """
        workspace = self.describe_workspace(workspace_id)
        group = RuleGroupNamespace(
            account_id=self.account_id,
            region=self.region_name,
            workspace_id=workspace_id,
            name=name,
            data=data,
            tag_fn=self.list_tags_for_resource,
        )
        workspace.rule_group_namespaces[name] = group
        self.tag_resource(group.arn, tags)
        return group

    def delete_rule_groups_namespace(self, name: str, workspace_id: str) -> None:
        """
        The ClientToken-parameter is not yet implemented
        """
        ws = self.describe_workspace(workspace_id)
        ws.rule_group_namespaces.pop(name, None)

    def describe_rule_groups_namespace(
        self, name: str, workspace_id: str
    ) -> RuleGroupNamespace:
        ws = self.describe_workspace(workspace_id)
        if name not in ws.rule_group_namespaces:
            raise RuleGroupNamespaceNotFound(name=name)
        return ws.rule_group_namespaces[name]

    def put_rule_groups_namespace(
        self, data: str, name: str, workspace_id: str
    ) -> RuleGroupNamespace:
        """
        The ClientToken-parameter is not yet implemented
        """
        ns = self.describe_rule_groups_namespace(name=name, workspace_id=workspace_id)
        ns.update(data)
        return ns

    @paginate(pagination_model=PAGINATION_MODEL)
    def list_rule_groups_namespaces(
        self, name: str, workspace_id: str
    ) -> list[RuleGroupNamespace]:
        ws = self.describe_workspace(workspace_id)
        if name:
            return [
                ns
                for ns_name, ns in ws.rule_group_namespaces.items()
                if ns_name.startswith(name)
            ]
        return list(ws.rule_group_namespaces.values())

    def create_logging_configuration(
        self, workspace_id: str, log_group_arn: str
    ) -> dict[str, str]:
        ws = self.describe_workspace(workspace_id)
        ws.logging_config = {
            "logGroupArn": log_group_arn,
            "createdAt": unix_time(),
            "status": {"statusCode": "ACTIVE"},
            "workspace": workspace_id,
        }
        return ws.logging_config["status"]

    def describe_logging_configuration(self, workspace_id: str) -> dict[str, Any]:
        ws = self.describe_workspace(workspace_id)
        if ws.logging_config is None:
            return {}
        return ws.logging_config

    def delete_logging_configuration(self, workspace_id: str) -> None:
        ws = self.describe_workspace(workspace_id)
        ws.logging_config = None

    def update_logging_configuration(
        self, workspace_id: str, log_group_arn: str
    ) -> dict[str, str]:
        ws = self.describe_workspace(workspace_id)
        ws.logging_config["logGroupArn"] = log_group_arn  # type: ignore[index]
        ws.logging_config["modifiedAt"] = unix_time()  # type: ignore[index]
        return ws.logging_config["status"]  # type: ignore[index]


amp_backends = BackendDict(PrometheusServiceBackend, "amp")