Repository navigation
Expand file tree
/
Copy pathpush.py
More file actions
189 lines (164 loc) · 6.78 KB
/
Copy pathpush.py
File metadata and controls
189 lines (164 loc) · 6.78 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
import subprocess, os, shutil, sys
def copy_files(source, destination, blacklist):
"""
Copie récursivement les fichiers du répertoire `source` vers `destination`,
en ignorant les répertoires dans `blacklist`.
:param source: Répertoire source
:param destination: Répertoire de destination
:param blacklist: Liste des répertoires (noms ou chemins relatifs depuis source) à ignorer
"""
blacklist_norm = [os.path.normpath(bl) for bl in blacklist]
for racine, dirs, fichiers in os.walk(source):
# Calcul du chemin relatif pour vérifier la blacklist
rel_path = os.path.relpath(racine, source)
rel_path_norm = os.path.normpath(rel_path)
# Vérifie si le chemin courant est dans la blacklist
if any(rel_path_norm.startswith(bl) for bl in blacklist_norm):
print(f"Skipping {rel_path_norm}")
continue
# Crée le répertoire dans la destination
dest_dir = os.path.join(destination, rel_path)
os.makedirs(dest_dir, exist_ok=True)
# Copie les fichiers
for fichier in fichiers:
src_fichier = os.path.join(racine, fichier)
dest_fichier = os.path.join(dest_dir, fichier)
shutil.copy2(src_fichier, dest_fichier)
def clean_directory(path : str):
"""
Supprime le répertoire donné s'il existe.
:param path: Chemin du répertoire à supprimer
"""
if os.path.isdir(path):
shutil.rmtree(path)
def scp(local_path : str, remote_path : str, ssh_key_path : str):
"""
Copie un fichier ou dossier vers un serveur distant via SCP.
:param local_path: Chemin local du fichier ou dossier à copier
:param remote_path: Chemin distant au format user@host:/chemin/distant
:param ssh_key_path: Chemin de la clé privée SSH
"""
try:
subprocess.run([
"scp",
"-i", ssh_key_path,
"-r",
local_path,
remote_path
], check=True)
print("Transfert SCP terminé avec succès.")
except subprocess.CalledProcessError as e:
print("❌ Erreur lors du transfert SCP :", e)
sys.exit(0)
import subprocess
def ssh(remote, ssh_key_path, commande):
"""
Exécute une commande sur un serveur distant via SSH.
:param remote: Cible au format user@host
:param ssh_key_path: Chemin vers la clé privée SSH
:param commande: Commande shell à exécuter sur le serveur
"""
try:
subprocess.run([
"ssh",
"-i", ssh_key_path,
remote,
commande
], check=True)
except subprocess.CalledProcessError as e:
print("❌ Erreur lors de l'exécution SSH :\n\t", e)
def say_hello():
print("""
███████╗███╗ ███╗███████╗██████╗ ██████╗ ███████╗███╗ ██╗ ██████╗██╗ ██╗
██╔════╝████╗ ████║██╔════╝██╔══██╗██╔════╝ ██╔════╝████╗ ██║██╔════╝╚██╗ ██╔╝
█████╗ ██╔████╔██║█████╗ ██████╔╝██║ ███╗█████╗ ██╔██╗ ██║██║ ╚████╔╝
██╔══╝ ██║╚██╔╝██║██╔══╝ ██╔══██╗██║ ██║██╔══╝ ██║╚██╗██║██║ ╚██╔╝
███████╗██║ ╚═╝ ██║███████╗██║ ██║╚██████╔╝███████╗██║ ╚████║╚██████╗ ██║
╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝
version 1.1
Seculabs
""")
INSTANCE_ID = open(".instance_id").read()
SSH_HOSTNAME = f"{INSTANCE_ID}.cabluses.ch"
SSH_USERNAME = "root"
SSH_KEY_PATH = ".ssh_key"
TMP_PATH = ".temp-cpy"
ANGULAR_ENV = """export const environment = {
production: true,
api_url : "http://%s.cabluses.ch:8001",
};""" % INSTANCE_ID
ANGULAR_ENV_PATH = os.path.normpath(
f"{TMP_PATH}/frontend/emergency-frontend/src/environments/environment.prod.ts"
)
if __name__ == "__main__":
say_hello()
print(f"📍 {INSTANCE_ID} (http://{SSH_HOSTNAME})")
# Nettoie le dossier temporaire (au cas où)
print("⌛️ Nettoyage du dossier temporaire...")
clean_directory(TMP_PATH)
print("✅ Nettoyage terminé.")
print("")
# Copie uniquement les fichiers nécessaires
print(f"⌛️ Copie des fichiers vers {TMP_PATH}")
copy_files(
source='code/challenge_app',
destination=TMP_PATH,
blacklist=[ 'backend/target',
'frontend/emergency-frontend/.angular/.cache'
]
)
print("✅ Copie terminé.")
print("")
# Reecrit l'environment angular
print(f"⌛️ Modification de l'environnement Angular")
with open(ANGULAR_ENV_PATH,"w") as file:
file.write(ANGULAR_ENV)
print("✅ Modification terminé.")
print("")
# Stop les services
print("⌛️ Arret des services...")
ssh(
remote=f"{SSH_USERNAME}@{SSH_HOSTNAME}",
ssh_key_path=SSH_KEY_PATH,
commande="cd /root/code/challenge_app; docker-compose down"
)
print("✅ Services arretés.")
# Stop les services
print("⌛️ Suppression de l'ancien code...")
ssh(
remote=f"{SSH_USERNAME}@{SSH_HOSTNAME}",
ssh_key_path=SSH_KEY_PATH,
commande="cd /root/code/challenge_app; rm -r *"
)
print("✅ Ancien code supprimé.")
print("")
# Pousse le code
print("⌛️ Téléversement du code...")
scp(
local_path=f"{TMP_PATH}/*",
remote_path=f"{SSH_USERNAME}@{SSH_HOSTNAME}:/root/code",
ssh_key_path=SSH_KEY_PATH
)
print("✅ Téléversement terminé.")
print("")
# Demarrage services
print("⌛️ Demarrage des services...")
ssh(
remote=f"{SSH_USERNAME}@{SSH_HOSTNAME}",
ssh_key_path=SSH_KEY_PATH,
commande="cd /root/code/challenge_app; docker-compose up -d"
)
print("✅ Services démarrés.")
print("")
# Nettoie le dossier temporaire
print("⌛️ Nettoyage du dossier temporaire...")
#clean_directory(TMP_PATH)
print("✅ Nettoyage terminé.")
print("")
print("="*40)
print("📢 Téléversement du code terminé !")
print(f"📍 {INSTANCE_ID} (http://{SSH_HOSTNAME})")
print(f" - Frontend : http://{SSH_HOSTNAME}:8000")
print(f" - Backend : http://{SSH_HOSTNAME}:8001")
print("="*40)
print("")