-
Notifications
You must be signed in to change notification settings - Fork 0
/
ava
executable file
·438 lines (368 loc) · 15.4 KB
/
ava
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import os
import sys
import subprocess
import time
COMPANY_NAME = "IFRN"
PROJECT_NAME = "ava"
HOME = os.environ.get("HOME")
COMPANY_DIR = f"{HOME}/projetos/{COMPANY_NAME}"
PROJECT_DIR = f"{COMPANY_DIR}/{PROJECT_NAME}"
WORKSPACE_DIR = f"{PROJECT_DIR}/{PROJECT_NAME}_workspace"
class Color:
ENDC = "\033[0m"
def r(text: str) -> str:
"""Returns a *red* string"""
return f"\033[91m{text}{Color.ENDC}"
def b(text: str) -> str:
"""Returns a *blue* string"""
return f"\033[94m{text}{Color.ENDC}"
def g(text: str) -> str:
"""Returns a *green* string"""
return f"\033[92m{text}{Color.ENDC}"
def c(text: str) -> str:
"""Returns a *cyan* string"""
return f"\033[96m{text}{Color.ENDC}"
def m(text: str) -> str:
"""Returns a *magenta* string"""
return f"\033[95m{text}{Color.ENDC}"
def y(text: str) -> str:
"""Returns a *yellow* string"""
return f"\033[93m{text}{Color.ENDC}"
def s(text: str) -> str:
"""Returns a *strong* string"""
return f"\033[1m{text}{Color.ENDC}"
def u(text: str) -> str:
"""Returns a *underlined* string"""
return f"\033[4m{text}{Color.ENDC}"
class Helper:
_repositories = None
_services = None
_commands = None
@classmethod
def print_help(cls):
print("Comandos disponíveis:\n")
for k, c in cls.commands.items():
fixed = f"{k:8}"
print(f" {Color.m(fixed)} - {c.description}{Color.c(', '.join(c.scopes))}")
exit()
@classmethod
@property
def commands(cls):
if cls._commands is None:
cls._commands = {}
for k, v in Commands.__dict__.items():
if "function" in str(v):
match = re.search(r"^(.*)(Aplica-se a: )(.*)$", v.__doc__)
v.scopes = (
match.group(3)
.replace("$services_names$", ",".join(cls.services))
.split(",")
)
v.description = match.group(1) + match.group(2)
cls._commands[k] = v
return cls._commands
@classmethod
@property
def command(cls):
arg_command = sys.argv[1]
for k, v in Helper.commands.items():
if k == arg_command:
return v
return None
@classmethod
@property
def command_name(cls):
return sys.argv[1]
@classmethod
def _read_compose(cls):
def is_service(line):
result = re.search("^ (\\w*):$", line)
if result is not None:
if len(result.groups()) == 1 and result.group(1) != "default":
return result.group(1)
def is_image(line):
result = re.search("^( image: )(.*)$", line)
if result is not None:
if len(result.groups()) > 0:
image = result.group(2)
return image.split("/")[0] if image.count("/") > 1 else ""
if cls._services is None or cls._repositories is None:
f = os.popen("docker compose config")
cls._services = []
cls._repositories = []
for line in f.read().splitlines():
if is_service(line):
cls._services.append(is_service(line))
if is_image(line):
cls._repositories.append(is_image(line))
cls._repositories.append("")
cls._repositories = set(cls._repositories)
@classmethod
@property
def services(cls):
if cls._services is None:
cls._read_compose()
return cls._services
@classmethod
@property
def repositories(cls):
if cls._repositories is None:
cls._read_compose()
return cls._repositories
@classmethod
@property
def service(cls):
return sys.argv[0]
@classmethod
@property
def service_name(cls):
return cls.scope_name if cls.scope_name != "env" else ""
@staticmethod
def service_is_running(service_name):
f = os.popen("docker container ps")
for line in f.read().splitlines():
if re.match(f".*{PROJECT_NAME}-{service_name}-1.*", line):
return True
return False
@staticmethod
def service_is_healthy(service_name):
f = os.popen("docker container ps")
for line in f.read().splitlines():
if re.match(f".*{PROJECT_NAME}-{service_name}-1.*", line) and re.match(
f".*healthy.*", line
):
return True
return False
@classmethod
@property
def scope_name(cls):
_scope_name = sys.argv[2] if len(sys.argv) >= 3 else "env"
if not hasattr(Helper.command, "scopes"):
raise Exception(f"Comando {Helper.command_name} não possui scopes")
if _scope_name not in Helper.command.scopes:
_scope_name = None
return _scope_name
@classmethod
def validate(cls):
if len(sys.argv) == 1:
print(Color.r("Informe ao menos um comando"), "\n")
cls.print_help()
if cls.command is None:
print(f"Comando {Color.r(cls.command_name)} não reconhecido.\n")
cls.print_help()
if cls.scope_name is None:
print(
f"Para o comando {Color.m(cls.command_name)}, os serviços disponíveis são: "
+ Color.c(", ".join(cls.command.scopes))
)
exit()
@staticmethod
def execute(executable_file, *args):
# print(Color.b("Executando: "), f"{executable_file} {' '.join(args)}")
p = subprocess.Popen(
executable_file + " " + " ".join(args),
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stdout,
shell=True,
cwd=WORKSPACE_DIR,
)
p.wait()
@staticmethod
def writeShellFile(filename):
if os.path.exists(f"{HOME}/{filename}"):
with open(f"{HOME}/{filename}", "r") as f:
if f"{PROJECT_NAME}_workspace" not in f.read():
Helper.execute(f"echo 'PATH=$PATH:{WORKSPACE_DIR}' >> ~/{filename}")
print("Lembre-se de executar o comando abaixo:")
print(Color.g(f"source ~/{filename}"), "\n")
@classmethod
@property
def verb(cls):
return "exec" if Helper.service_is_running(Helper.service_name) else "run --rm"
@staticmethod
def read_envs():
with open(f"{WORKSPACE_DIR}/.env", "r") as f:
for l in f.readlines():
if l.startswith("#"):
continue
if l.strip() == "":
continue
varname = l.split("=", 2)[0]
varval = l.split("=", 2)[1][:-1]
if varname == "COMPOSE_PROJECT_NAME" and varval != PROJECT_NAME:
raise Exception(
f"No arquivo .env está como {l}, mas devia ser {varname}={PROJECT_NAME}"
)
os.environ[varname] = varval
@staticmethod
def prefixed_envs(prefix):
return {
k[len(prefix) :].lower(): v
for k, v in os.environ.items()
if k.startswith(prefix)
}
class Commands:
def down():
"""Para todo o ambiente ou o serviço especificado. Aplica-se a: $services_names$,env"""
Helper.execute(f"docker compose down {Helper.service_name}")
def restart():
"""Para e depois inicia ambiente ou o serviço especificado, não faz lock do CLI. Aplica-se a: $services_names$,env"""
Helper.execute(f"docker compose down {Helper.service_name}")
Helper.execute(f"docker compose up -d {Helper.service_name}")
def logs():
"""Acompanha os logs do ambiente ou o serviço especificado. Aplica-se a: $services_names$,env"""
Helper.execute(f"docker compose logs -f {Helper.service_name}")
def status():
"""Mostra o status ambiente ou o serviço especificado. Aplica-se a: $services_names$,env"""
Helper.execute(f"docker compose ps {Helper.service_name}")
def start():
"""Mostra o status ambiente ou o serviço especificado. Aplica-se a: $services_names$,env"""
Commands.restart()
Commands.logs()
def up():
"""Inicia ambiente ou o serviço especificado, faz lock do CLI. Aplica-se a: $services_names$,env"""
Helper.execute(f"docker compose up {Helper.service_name}")
def exec():
"""Executa um comando em um serviço que já esteja em execução. Aplica-se a: $services_names$,env"""
Helper.execute(
f"docker compose {Helper.verb} {Helper.service_name} ", *sys.argv[3:]
)
def build():
"""Constrói a imagem do serviço especificado ou de todos os serviços do ambiente. Aplica-se a: $services_names$,env"""
Helper.execute(f"docker compose build {Helper.service_name}")
def publish():
"""Publica a imagem do serviço especificado ou de todos os serviços do ambiente. Aplica-se a: $services_names$,env"""
Commands.build()
# docker login gitlab.ifrn.edu.br:4567
Helper.execute(f"docker compose push {Helper.service_name}")
def setup():
"""Executa o setup do ambiente, ou seja, clona todos os repositórios e configura o PATH e o /etc/hosts. Aplica-se a: env"""
def clone_projects():
for proj, url in Helper.prefixed_envs("GITCLONE_").items():
proj_dir = f"{PROJECT_DIR}/{proj.replace('__', '/')}"
os.makedirs(os.path.dirname(proj_dir), 0o770, True)
if not os.path.exists(proj_dir):
Helper.execute(f"git clone {url} {proj_dir}")
def write_hosts():
hosts = Helper.prefixed_envs("HOSTS")[""].split(":", 1)
hosts_name = hosts[0]
hosts_value = hosts[1]
with open("/etc/hosts", "r") as f:
if hosts_name not in f.read():
print(f"Adicionando este {hosts_value} em /etc/hosts:")
nls = "#" * 70
new_hosts = f"\n{nls}\n## {hosts_name}\n{nls}\n{hosts_value}\n"
Helper.execute(f"echo '{new_hosts}' | sudo tee -a /etc/hosts")
def mk_volumes():
for mkvols in Helper.prefixed_envs("MK_VOLUMES").items():
for mkvol in mkvols[1].split(","):
vol = f"{PROJECT_DIR}/volumes/{mkvol}"
os.makedirs(vol, exist_ok=True)
Helper.execute(f"sudo chmod -R 777 {vol}")
def write_profiles():
Helper.writeShellFile(".bashrc")
Helper.writeShellFile(".zshrc")
Commands.down()
clone_projects()
write_hosts()
mk_volumes()
Commands.build()
write_profiles()
def deploy():
"""Pára todo o ambiente, inicia os serviços de background (db e cache), constrói as imagens, iniciar os serviços web em background e acompanha o log do ambiente. Aplica-se a: env"""
Commands.setup()
Commands.start()
def undeploy():
"""Pára todo o ambiente e remove a pasta ../volumes. Aplica-se a: env"""
Commands.down()
Helper.execute(f"sudo rm -rf {PROJECT_DIR}/volumes/{Helper.service_name}")
def pull():
"""Pára todo o ambiente e remove a pasta ../volumes. Aplica-se a: env"""
print(f"Atualizando o código de {Color.m(WORKSPACE_DIR)}")
Helper.execute(f"cd {WORKSPACE_DIR};git pull")
for proj, url in Helper.prefixed_envs("GITCLONE_").items():
proj_dir = f"{PROJECT_DIR}/{proj.replace('__', '/')}"
if os.path.exists(proj_dir):
print(f"Atualizando o código de {Color.m(proj_dir)}")
Helper.execute(f"cd {proj_dir};git pull")
else:
print(f"O projeto {proj_dir} NÃO foi clonado ainda.")
def cli():
"""Executa a CLI padrão de um serviço, pode ser php, shell_plus, psql ou redis-cli, caso contrário será bash usará exec se já estiver em execução, run caso contrário. Aplica-se a: $services_names$"""
cmd = Helper.prefixed_envs("CLI_").get(Helper.service_name, "bash")
Helper.execute(
f"docker compose {Helper.verb} {Helper.service_name} {cmd} ", *sys.argv[3:]
)
def shell():
"""Executa o bash ou sh de um serviço, usará exec se já estiver em execução, run caso contrário. Aplica-se a: $services_names$"""
cmd = Helper.prefixed_envs("SHELL_").get(Helper.service_name, "bash")
Helper.execute(
f"docker compose {Helper.verb} {Helper.service_name} {cmd} ", *sys.argv[3:]
)
def shell_root():
"""Executa o bash ou sh de um serviço, usará exec se já estiver em execução, run caso contrário. Aplica-se a: $services_names$"""
cmd = Helper.prefixed_envs("SHELL_").get(Helper.service_name, "bash")
Helper.execute(
f"docker compose {Helper.verb} -u root {Helper.service_name} {cmd} ",
*sys.argv[3:],
)
def wait():
"""Aguarda até o banco de dados estar disponível. Aplica-se a: db"""
while not Helper.service_is_healthy("db"):
print(Color.y("Aguardando o banco de dados estar disponível..."))
time.sleep(3)
print(Color.g("Banco de dados disponível!"))
def login():
"""Mostra os logins do ambiente. Aplica-se a: env"""
for repository in Helper.repositories:
repository_alias = repository if repository != "" else "hub.docker.com"
print(f"Login em {Color.b(repository_alias)}")
Helper.execute(f"docker login {repository}")
def manage():
"""Mostra os logins do ambiente. Aplica-se a: $services_names$"""
Helper.execute(
f"docker compose {Helper.verb} {Helper.service_name} python3 manage.py ",
*sys.argv[3:],
)
def makemigrations():
"""Mostra os logins do ambiente. Aplica-se a: $services_names$"""
Helper.execute(
f"docker compose {Helper.verb} {Helper.service_name} python3 manage.py makemigrations",
*sys.argv[3:],
)
def migrate():
"""Mostra os logins do ambiente. Aplica-se a: $services_names$"""
Helper.execute(
f"docker compose {Helper.verb} {Helper.service_name} python3 manage.py migrate",
*sys.argv[3:],
)
def show_urls():
"""Mostra os logins do ambiente. Aplica-se a: $services_names$"""
Helper.execute(
f"docker compose {Helper.verb} {Helper.service_name} python3 manage.py show_urls",
*sys.argv[3:],
)
def test():
"""Mostra os logins do ambiente. Aplica-se a: $services_names$"""
Helper.execute(
f"docker compose {Helper.verb} {Helper.service_name} python3 manage.py test",
*sys.argv[3:],
)
def testserver():
"""Mostra os logins do ambiente. Aplica-se a: $services_names$"""
Helper.execute(
f"docker compose {Helper.verb} {Helper.service_name} python3 manage.py testserver",
*sys.argv[3:],
)
def help():
"""Imprime esta ajuda. Aplica-se a: env"""
Helper.print_help()
if __name__ == "__main__":
os.chdir(f"{PROJECT_DIR}/{PROJECT_NAME}_workspace")
Helper.read_envs()
Helper.validate()
Helper.command()