forked from justinmajetich/AirBnB_clone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100-clean_web_static.py
executable file
·93 lines (83 loc) · 2.77 KB
/
100-clean_web_static.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
#!/usr/bin/python3
"""
It deletes out-of-date archives, using the function do_clean
"""
import os
from datetime import datetime
from fabric.api import env, local, put, run, runs_once
env.hosts = ['18.209.223.65', '35.175.65.54']
@runs_once
def do_pack():
"""Archives the static files."""
if not os.path.isdir("versions"):
os.mkdir("versions")
cur_time = datetime.now()
output = "versions/web_static_{}{}{}{}{}{}.tgz".format(
cur_time.year,
cur_time.month,
cur_time.day,
cur_time.hour,
cur_time.minute,
cur_time.second
)
try:
print("Packing web_static to {}".format(output))
local("tar -cvzf {} web_static".format(output))
archize_size = os.stat(output).st_size
print("web_static packed: {} -> {} Bytes".format(output, archize_size))
except Exception:
output = None
return output
def do_deploy(archive_path):
"""Deploys the static files to the host servers.
Args:
archive_path (str): The path to the archived static files.
"""
if not os.path.exists(archive_path):
return False
file_name = os.path.basename(archive_path)
folder_name = file_name.replace(".tgz", "")
folder_path = "/data/web_static/releases/{}/".format(folder_name)
success = False
try:
put(archive_path, "/tmp/{}".format(file_name))
run("mkdir -p {}".format(folder_path))
run("tar -xzf /tmp/{} -C {}".format(file_name, folder_path))
run("rm -rf /tmp/{}".format(file_name))
run("mv {}web_static/* {}".format(folder_path, folder_path))
run("rm -rf {}web_static".format(folder_path))
run("rm -rf /data/web_static/current")
run("ln -s {} /data/web_static/current".format(folder_path))
print('New version deployed!')
success = True
except Exception:
success = False
return success
def deploy():
"""Archives and deploys the static files to the host servers.
"""
archive_path = do_pack()
return do_deploy(archive_path) if archive_path else False
def do_clean(number=0):
"""Deletes out-of-date archives of the static files.
Args:
number (Any): The number of archives to keep.
"""
archives = os.listdir('versions/')
archives.sort(reverse=True)
start = int(number)
if not start:
start += 1
if start < len(archives):
archives = archives[start:]
else:
archives = []
for archive in archives:
os.unlink('versions/{}'.format(archive))
cmd_parts = [
"rm -rf $(",
"find /data/web_static/releases/ -maxdepth 1 -type d -iregex",
" '/data/web_static/releases/web_static_.*'",
" | sort -r | tr '\\n' ' ' | cut -d ' ' -f{}-)".format(start + 1)
]
run(''.join(cmd_parts))