-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
312 lines (275 loc) · 11.2 KB
/
Copy path__init__.py
File metadata and controls
312 lines (275 loc) · 11.2 KB
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import base64
from dataclasses import dataclass, field
from shlex import quote
from InfraBaseLib import ShellCommand
@dataclass(kw_only=True)
class Port:
number: int
protocol: str
zone: str
@dataclass(kw_only=True)
class ImageRegistry:
url: str
username: str | None = None
password: str | None = None
insecure: bool = False
@dataclass(kw_only=True)
class Image:
path: str
version: str
registry: ImageRegistry
full_name: str = field(init=False)
def __post_init__(self):
self.full_name = f"{self.registry.url}/{self.path}:{self.version}"
class ShellCollect:
@staticmethod
def _user_systemd_env(user: str) -> str:
return (f"uid=$(id -u {user}); export XDG_RUNTIME_DIR=/run/user/$uid; "
"export DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus;")
@staticmethod
def login_registries(registries: list[ImageRegistry], user: str, for_group: str) -> ShellCommand | None:
commands = []
for registry in registries:
if bool(registry.username) != bool(registry.password):
raise ValueError("Both image username and password must be set for registry authentication")
if not registry.username or not registry.password:
continue
tls_verify = " --tls-verify=false" if registry.insecure else ""
username_b64 = base64.b64encode(registry.username.encode("utf-8")).decode("ascii")
password_b64 = base64.b64encode(registry.password.encode("utf-8")).decode("ascii")
commands.append(
f"printf '%s' {quote(password_b64)} | base64 -d "
f"| podman login {quote(registry.url)} "
f"--username \"$(printf '%s' {quote(username_b64)} | base64 -d)\" "
f"--password-stdin{tls_verify}"
)
if not commands:
return None
return ShellCommand(
name="Login to Podman registries.yml",
user=user,
sudo=True,
full_login=True,
for_group=for_group,
cmd=" && ".join(commands),
)
@staticmethod
def logout_registries(registries: list[ImageRegistry], user: str, for_group: str) -> ShellCommand | None:
commands = []
for registry in registries:
if bool(registry.username) != bool(registry.password):
raise ValueError("Both image username and password must be set for registry authentication")
if registry.username and registry.password:
commands.append(f"podman logout {quote(registry.url)}")
if not commands:
return None
return ShellCommand(
name="Logout from Podman registries.yml",
user=user,
sudo=True,
full_login=True,
for_group=for_group,
cmd=" && ".join(commands),
)
@staticmethod
def download_images(images: list[Image], user: str, for_group: str) -> ShellCommand | None:
if not images:
return None
pull_commands = []
for image in images:
image_name = quote(image.full_name)
tls_verify = " --tls-verify=false" if image.registry.insecure else ""
pull_commands.append(
f"podman image exists {image_name} || podman pull{tls_verify} {image_name}"
)
cmd = (
f"printf '%s\\n' {' '.join(quote(command) for command in pull_commands)} "
f"| xargs -P {len(pull_commands)} -I {{}} sh -c {{}}"
)
return ShellCommand(
name="Download images",
user=user,
sudo=True,
full_login=True,
for_group=for_group,
cmd=cmd,
)
@staticmethod
def up_container(name_app: str, network: str, path_to_manifest: str, user: str, role: str) -> list[ShellCommand]:
return [ShellCommand(
name=f"Generate Podman unit {name_app}",
user=user,
sudo=True,
full_login=True,
for_group=role,
cmd=(
f"podlet --overwrite --unit-directory --name {name_app} "
f"podman kube play --network {network} --no-pod-prefix "
f"\"{path_to_manifest}\""
),
),
ShellCommand(
name=f"Start user container unit {name_app}",
user="",
sudo=True,
full_login=False,
for_group=role,
cmd=(
f"systemctl --user --machine={user}@.host daemon-reload && "
f"systemctl --user --machine={user}@.host start {name_app}.service"
),
)]
@staticmethod
def wait_user_service_active(name_app: str, user: str, role: str, attempts: int = 30,
delay: int = 2) -> ShellCommand:
return ShellCommand(
name=f"Wait user service {name_app} active",
user="",
sudo=True,
full_login=False,
for_group=role,
cmd=(
f"for i in $(seq 1 {attempts}); do "
f"systemctl --user --machine={user}@.host is-active --quiet {name_app}.service && exit 0; "
f"sleep {delay}; "
f"done; "
f"systemctl --user --machine={user}@.host status {name_app}.service --no-pager; "
f"exit 1"
),
)
@staticmethod
def wait_port_listen(port: Port, role: str, attempts: int = 30, delay: int = 2) -> ShellCommand:
ss_flag = "ltn" if port.protocol == "tcp" else "lun"
return ShellCommand(
name=f"Wait {port.number}/{port.protocol} listen",
user="",
sudo=True,
full_login=True,
for_group=role,
cmd=f"for i in $(seq 1 {attempts}); do "
f"ss -H -{ss_flag} 'sport = :{port.number}' | grep -q . && exit 0; "
f"sleep {delay}; "
f"done; "
f"ss -H -{ss_flag}; "
f"exit 1",
)
@staticmethod
def wait_current_app(name_app: str, ports: list[Port], user: str, role: str, attempts: int = 30,
delay: int = 2) -> list[ShellCommand]:
commands = [ShellCollect.wait_user_service_active(name_app, user, role, attempts, delay)]
for port in ports:
commands.append(ShellCollect.wait_port_listen(port, role, attempts, delay))
return commands
@staticmethod
def wait_cloud_init(role: str) -> ShellCommand:
return ShellCommand(
name="Wait cloud-init complete",
user="",
sudo=True,
full_login=False,
for_group=role,
cmd="cloud-init status --wait",
success_exit_codes=[0,2]
)
@staticmethod
def open_ports(ports: list[Port], role: str) -> list[ShellCommand]:
if not ports:
return []
commands = ["changed=0"]
for port in ports:
port_spec = f"{port.number}/{port.protocol}"
commands.append(
f"{{ firewall-cmd --permanent "
f"--zone={port.zone} "
f"--query-port={port_spec} "
f"|| {{ firewall-cmd --permanent "
f"--zone={port.zone} "
f"--add-port={port_spec}; changed=1; }}"
f"; }}"
)
commands.append('{ [ "$changed" -eq 0 ] || firewall-cmd --reload; }')
ports_label = ", ".join(f"{port.number}/{port.protocol}:{port.zone}" for port in ports)
return [
ShellCommand(
name=f"Open firewalld ports {ports_label}", user="", sudo=True, full_login=False,
for_group=role,
cmd=" && ".join(commands),
),
]
@staticmethod
def setting_podman_app_runtime(user: str, role: str) -> list[ShellCommand]:
app_home = f"/home/{user}"
return [
ShellCommand(
name="Ensure firewalld is running", user="", sudo=True, full_login=False,
for_group=role,
cmd="systemctl is-enabled --quiet firewalld || systemctl enable firewalld; "
"systemctl is-active --quiet firewalld || systemctl start firewalld",
),
ShellCommand(
name=f"Enable linger for {user}", user="", sudo=True, full_login=False,
for_group=role,
cmd=f"loginctl show-user {user} --property=Linger "
f"| grep -q '^Linger=yes$' "
f"|| loginctl enable-linger {user}",
),
ShellCommand(
name=f"Start user systemd manager for {user}", user="", sudo=True, full_login=False,
for_group=role,
cmd=f"systemctl is-active --quiet user@$(id -u {user}).service "
f"|| systemctl start user@$(id -u {user}).service",
),
ShellCommand(
name=f"Start user DBus socket for {user}",
user="",
sudo=True,
full_login=False,
for_group=role,
cmd=f"systemctl --user --machine={user}@.host start dbus.socket",
),
ShellCommand(
name=f"Enable user Podman socket for {user}",
user="",
sudo=True,
full_login=False,
for_group=role,
cmd=f"systemctl --user --machine={user}@.host enable --now podman.socket",
),
ShellCommand(
name=f"Create stable Podman socket path for {user}",
user="",
sudo=True,
full_login=False,
for_group=role,
cmd=f"ln -sfn /run/user/$(id -u {user})/podman/podman.sock "
f"{app_home}/podman.sock && "
f"chown -h {user}:$(id -gn {user}) {app_home}/podman.sock",
),
ShellCommand(
name="Ensure Podman engine ID for Docker API clients",
user="",
sudo=True,
full_login=False,
for_group=role,
cmd="install -d -m 755 /var/lib/docker && "
"{ test -s /var/lib/docker/engine-id || "
"cat /proc/sys/kernel/random/uuid > /var/lib/docker/engine-id; } && "
"chmod 644 /var/lib/docker/engine-id",
),
ShellCommand(
name=f"Create Podman config dirs for {user}", user="", sudo=True, full_login=False,
for_group=role,
cmd=f"install -d "
f"-o {user} "
f"-g $(id -gn {user}) "
f"-m 700 "
f"{app_home}/.config "
f"{app_home}/.config/containers "
f"{app_home}/.config/containers/systemd",
),
ShellCommand(
name="Create Podman network app-net", user=user, sudo=True, full_login=True,
for_group=role,
cmd="podman network exists app-net || podman network create app-net",
),
]