-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfabfile.py
175 lines (138 loc) · 5.07 KB
/
fabfile.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
#!/usr/bin/env python3
"""Deploys """
# import collections.abc
# collections.Mapping = collections.abc.Mapping
from fabric.api import *
from dotenv import load_dotenv
from os import getenv, path
from datetime import datetime
import json
load_dotenv()
SQL_ROOT_PWD = getenv("SQL_ROOT_PWD")
USER = getenv("DB_USER")
HOST = getenv("DB_HOST")
PWD = getenv("DB_PWD")
DB = getenv("DB_NAME")
PSN = getenv("PSN")
APP_FILES = json.loads(getenv('APP_FILES'))
def configureSQL():
"""Installs and sets the root password of MySQL"""
run("sudo apt install -y mysql-server")
run("sudo apt update")
sudo("service mysql stop")
sudo("mysqld_safe --skip-grant-tables &")
run("sleep 5")
sudo("service mysql start")
sudo(
f"mysql -u root -e \"ALTER USER 'root'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY '{SQL_ROOT_PWD}';\"")
sudo("service mysql start")
print("MySQL root password changed successfully.")
def installPackages():
"""Installs project required packages on the server"""
sudo("apt update")
sudo("apt install -y python3")
sudo("apt install -y python3-pip")
sudo("apt install -y python3-venv")
sudo("apt-get install -y pkg-config")
sudo("apt-get install -y libmysqlclient-dev")
sudo("apt install -y nginx")
sudo("apt install -y redis-server")
sudo("sed -i 's/supervised no/supervised systemd/' /etc/redis/redis.conf")
sudo("systemctl restart redis.service")
print("Packages installed successfully!")
def deployServiceFile():
"""Deploys the systemd service unit for the app"""
put(f"serverConfigurations/{PSN}.service",
"/etc/systemd/system/", use_sudo=True)
sudo("systemctl daemon-reload")
sudo(f"systemctl enable {PSN}.service")
print("Service file deployed successfully!")
def startUnitService():
"""Starts the apps unit service"""
sudo(f"systemctl start {PSN}.service")
print(f"{PSN} service started successfully!")
def stopUnitService():
"""Stops the apps unit service"""
sudo(f"systemctl stop {PSN}.service")
print(f"{PSN} service stopped successfully!")
def unitStatus():
"""Gets the status of the apps unit service"""
sudo(f"systemctl status {PSN}.service")
def restartUnitService():
"""Restarts the apps unit service"""
sudo(f"systemctl restart {PSN}.service")
print(f"{PSN} service restarted successfully!")
def deployNginxConfig():
"""Deploys Nginx configuration and restarts Nginx"""
put(f'serverConfigurations/{PSN}-nginx',
'/etc/nginx/sites-available/', use_sudo=True)
sudo(f"ln -s /etc/nginx/sites-available/{PSN}-nginx /etc/nginx/sites-enabled/")
sudo('systemctl restart nginx')
print("Nginx config deployed successfully!")
def restartNginx():
"""Restarts Nginx service"""
sudo('systemctl restart nginx')
print("Nginx service restarted successfully!")
def nginxStatus():
"""Checks the status of server's Nginx service"""
sudo('systemctl status nginx')
def packFiles():
"""Packs the application file in a .tgz archive"""
dateString = datetime.utcnow().strftime("%Y-%m-%d-%H-%M-%S")
archivePath = f"versions/{PSN}_{dateString}.tgz"
local("mkdir -p versions")
local(f"tar -cvzf {archivePath} {' '.join(APP_FILES)}")
return archivePath
def shipFiles(archivePath):
"""Unpacks the contents of an archive to the server(s)"""
if not path.exists(archivePath):
return False
remoteVersionsPath = f"/tmp/{PSN}/versions"
run(f"mkdir -p {remoteVersionsPath}")
put(archivePath, remoteVersionsPath, use_sudo=True)
run(f"mkdir -p {PSN}")
archiveName = archivePath.split('/')[1]
run(f"tar -xvzf {remoteVersionsPath}/{archiveName} -C {PSN}")
print("Files shipped successfully!")
def installGlobalRequirements():
"""Installs the projects global requirements"""
with cd(PSN):
run("pip3 install -r globals.txt")
def installRequirements():
"""Install project dependencies"""
with cd(PSN):
run("python3 -m venv .venv")
run("source .venv/bin/activate && pip3 install -r requirements.txt")
print("Requirements installed successfully!")
def setupDB():
"""(Re)Creates and prepopulates database with data"""
with cd(PSN):
run(f"cat setupDatabase.sql | mysql -h{HOST} -u{USER} -p{SQL_ROOT_PWD}")
run("python3 createRecipeDataDB.py")
print("Database is ready!")
def removeOldFiles():
"""Deletes the old deployed project files"""
run("rm -rf {PSN}")
print("Files removed successfully!")
def deployFiles():
archivePath = packFiles()
shipFiles(archivePath)
print("Files deployed successfully!")
def updateFiles():
"""Replaces old project files with current ones"""
removeOldFiles()
deployFiles()
print("Files updated successfully!")
restartUnitService()
def fullDeploy():
"""Performs a full deploy to a new server"""
deployFiles()
installPackages()
# configureSQL()
installGlobalRequirements()
installRequirements()
# setupDB()
deployNginxConfig()
deployServiceFile()
startUnitService()
print("Hurray!! Full deployment successful!")