generated from canonical/template-operator
-
Notifications
You must be signed in to change notification settings - Fork 4
/
models.py
264 lines (192 loc) · 7.81 KB
/
models.py
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
"""Cluster-related data structures / model classes."""
from abc import ABC
from datetime import datetime
from typing import Any, Dict, List, Literal, Optional
from charms.opensearch.v0.helper_enums import BaseStrEnum
from pydantic import BaseModel, Field, root_validator, validator
# The unique Charmhub library identifier, never change it
LIBID = "6007e8030e4542e6b189e2873c8fbfef"
# Increment this major API version when introducing breaking changes
LIBAPI = 0
# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 1
class Model(ABC, BaseModel):
"""Base model class."""
def to_str(self) -> str:
"""Deserialize object into a string."""
return self.json()
def to_dict(self) -> Dict[str, Any]:
"""Deserialize object into a dict."""
return self.dict()
@classmethod
def from_dict(cls, input_dict: Optional[Dict[str, Any]]):
"""Create a new instance of this class from a json/dict repr."""
if not input_dict: # to handle when classes defined defaults
return cls()
return cls(**input_dict)
@classmethod
def from_str(cls, input_str_dict: str):
"""Create a new instance of this class from a stringified json/dict repr."""
return cls.parse_raw(input_str_dict)
def __eq__(self, other) -> bool:
"""Implement equality."""
if other is None:
return False
equal = True
for attr_key, attr_val in self.__dict__.items():
other_attr_val = getattr(other, attr_key)
if isinstance(attr_val, list):
equal = equal and sorted(attr_val) == sorted(other_attr_val)
else:
equal = equal and (attr_val == other_attr_val)
return equal
class Node(Model):
"""Data class representing a node in a cluster."""
name: str
roles: List[str]
ip: str
app_name: str
unit_number: int
temperature: Optional[str] = None
@classmethod
@validator("roles")
def roles_set(cls, v):
"""Returns deduplicated list of roles."""
return list(set(v))
def is_cm_eligible(self):
"""Returns whether this node is a cluster manager eligible member."""
return "cluster_manager" in self.roles
def is_voting_only(self):
"""Returns whether this node is a voting member."""
return "voting_only" in self.roles
def is_data(self):
"""Returns whether this node is a data* node."""
for role in self.roles:
if role.startswith("data"):
return True
return False
class DeploymentType(BaseStrEnum):
"""Nature of a sub cluster deployment."""
MAIN_ORCHESTRATOR = "main-orchestrator"
FAILOVER_ORCHESTRATOR = "failover-orchestrator"
OTHER = "other"
class StartMode(BaseStrEnum):
"""Mode of start of units in this deployment."""
WITH_PROVIDED_ROLES = "start-with-provided-roles"
WITH_GENERATED_ROLES = "start-with-generated-roles"
class Directive(BaseStrEnum):
"""Directive indicating what the pending actions for the current deployments are."""
NONE = "none"
SHOW_STATUS = "show-status"
WAIT_FOR_PEER_CLUSTER_RELATION = "wait-for-peer-cluster-relation"
INHERIT_CLUSTER_NAME = "inherit-name"
VALIDATE_CLUSTER_NAME = "validate-cluster-name"
RECONFIGURE = "reconfigure-cluster"
class State(BaseStrEnum):
"""State of a deployment, directly mapping to the juju statuses."""
ACTIVE = "active"
BLOCKED_WAITING_FOR_RELATION = "blocked-waiting-for-peer-cluster-relation"
BLOCKED_WRONG_RELATED_CLUSTER = "blocked-wrong-related-cluster"
BLOCKED_CANNOT_START_WITH_ROLES = "blocked-cannot-start-with-current-set-roles"
BLOCKED_CANNOT_APPLY_NEW_ROLES = "blocked-cannot-apply-new-roles"
class DeploymentState(Model):
"""Full state of a deployment, along with the juju status."""
value: State
message: str = Field(default="")
@root_validator
def prevent_none(cls, values): # noqa: N805
"""Validate the message or lack of depending on the state."""
if values["value"] == State.ACTIVE:
values["message"] = ""
elif not values["message"].strip():
raise ValueError("The message must be set when state not Active.")
return values
class PeerClusterConfig(Model):
"""Model class for the multi-clusters related config set by the user."""
cluster_name: str
init_hold: bool
roles: List[str]
data_temperature: Optional[str] = None
@root_validator
def set_node_temperature(cls, values): # noqa: N805
"""Set and validate the node temperature."""
allowed_temps = ["hot", "warm", "cold", "frozen", "content"]
input_temps = set()
for role in values["roles"]:
if not role.startswith("data."):
continue
temp = role.split(".")[1]
if temp not in allowed_temps:
raise ValueError(f"data.'{temp}' not allowed. Allowed values: {allowed_temps}")
input_temps.add(temp)
if len(input_temps) > 1:
raise ValueError("More than 1 data temperature provided.")
elif input_temps:
temperature = input_temps.pop()
values["data_temperature"] = temperature
values["roles"].append("data")
values["roles"].remove(f"data.{temperature}")
values["roles"] = list(set(values["roles"]))
return values
class DeploymentDescription(Model):
"""Model class describing the current state of a deployment / sub-cluster."""
config: PeerClusterConfig
start: StartMode
pending_directives: List[Directive]
typ: DeploymentType
app: str
state: DeploymentState = DeploymentState(value=State.ACTIVE)
promotion_time: Optional[float]
@root_validator
def set_promotion_time(cls, values): # noqa: N805
"""Set promotion time of a failover to a main CM."""
if values["typ"] == DeploymentType.MAIN_ORCHESTRATOR:
values["promotion_time"] = datetime.now().timestamp()
return values
class S3RelDataCredentials(Model):
"""Model class for credentials passed on the PCluster relation."""
access_key: str
secret_key: str
class PeerClusterRelDataCredentials(Model):
"""Model class for credentials passed on the PCluster relation."""
admin_username: str
admin_password: str
admin_password_hash: str
admin_tls: Dict[str, Optional[str]]
s3: Optional[S3RelDataCredentials]
class PeerClusterRelData(Model):
"""Model class for the PCluster relation data."""
cluster_name: str
cm_nodes: List[Node]
credentials: PeerClusterRelDataCredentials
deployment_desc: Optional[DeploymentDescription]
class PeerClusterRelErrorData(Model):
"""Model class for the PCluster relation data."""
cluster_name: Optional[str]
should_sever_relation: bool
should_wait: bool
blocked_message: str
deployment_desc: Optional[DeploymentDescription]
class PeerClusterOrchestrators(Model):
"""Model class for the PClusters registered main/failover clusters."""
_TYPES = Literal["main", "failover"]
main_rel_id: int = -1
main_app: Optional[str]
failover_rel_id: int = -1
failover_app: Optional[str]
def delete(self, typ: _TYPES) -> None:
"""Delete an orchestrator from the current pair."""
if typ == "main":
self.main_rel_id = -1
self.main_app = None
else:
self.failover_rel_id = -1
self.failover_app = None
def promote_failover(self) -> None:
"""Delete previous main orchestrator and promote failover if any."""
self.main_app = self.failover_app
self.main_rel_id = self.failover_rel_id
self.delete("failover")