/
management.py
346 lines (270 loc) · 11.7 KB
/
management.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
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
import subprocess
import json
from termcolor import cprint
import os
import sys
import platform
from validators import domain, ipv4
"""
Djeasy : Django simple quick setup
"""
# Main directory
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# As program only works on Python 3, avoiding to run on Python 2
# if not sys.version_info >= (3, 0):
# sys.exit("This program runs only on Python 3.x\nExiting...")
# This program will work only on Debian and Ubuntu.
# if sys.version_info < (3, 9):
# if not "debian" or not "ubuntu" in str(platform.linux_distribution()).lower():
# sys.exit("This program runs only on Debian and Ubuntu\nExiting...")
# else:
# if not "debian" or not "ubuntu" in str(platform.platform()).lower():
# sys.exit("This program runs only on Debian and Ubuntu\nExiting...")
class EasyInstall:
""" Package Install and Settings """
def __init__(self, project_name, server_name_or_ip, static_url,
gunicorn_file, nginx_file, project_file, virtualenv_file):
"""
:param project_name: Django project folder
:param server_name_or_ip: Server ip or domain
:param static_url: Django settings.py STATIC_URL address
:param gunicorn_file : gunicorn file name
:param nginx_file : nginx file name
:param virtualenv_file : virtualenv file directory
"""
self.project_name = project_name
self.server_name_or_ip = server_name_or_ip
self.static_url = static_url
self.gunicorn_file = gunicorn_file
self.nginx_file = nginx_file
self.project_file = project_file
self.virtualenv_file = virtualenv_file
# package.json read.
with open("{}/client/file/package.json".format(BASE_DIR)) as data_file:
self.data = json.load(data_file)
def __call__(self, *args, **kwargs):
"""Packages Loader"""
for package in self.data['package']:
cprint("{}".format(package['message']),
'white', 'on_red', attrs=['bold'])
subprocess.call(package['name'], shell=True)
# Restart.
subprocess.call("sudo systemctl daemon reload", shell=True)
subprocess.call("sudo systemctl restart nginx", shell=True)
# Successfull package
cprint("The packages have been successfully installed.",
'white', 'on_red', attrs=['bold'])
def __add__(self):
"""It records Gunicorn vs nginx files."""
# gunicorn file save and move
with open("{}/client/file/gunicorn.service".format(BASE_DIR)) as gunicorn_files:
gunicorn = gunicorn_files.read().format(
self.project_name, self.project_file, self.virtualenv_file)
file_gunicorn = open(
'{}/package/{}.service'.format(BASE_DIR, self.gunicorn_file), 'w')
file_gunicorn.write(gunicorn)
file_gunicorn.flush()
file_gunicorn.close()
cprint("{}.service file created.".format(
self.gunicorn_file), 'white', 'on_red', attrs=['bold'])
# File move operations
subprocess.call("sudo cp {}/package/{}.service /etc/systemd/system/".
format(BASE_DIR, self.gunicorn_file), shell=True)
# Gunicorn recording and restart
subprocess.call("sudo systemctl start {0} & sudo systemctl enable {0}".format(
self.gunicorn_file), shell=True)
cprint("Gunicorn was registered and restarted.",
'white', 'on_red', attrs=['bold'])
# nginx file save and move
with open("{}/client/file/nginx".format(BASE_DIR)) as nginx_files:
nginx = nginx_files.read().format(self.server_name_or_ip,
self.static_url, self.project_file, self.project_name)
nginx_file = nginx.replace('[', '{').replace(']', '}')
file_nignx = open(
"{}/package/{}".format(BASE_DIR, self.nginx_file), 'w')
file_nignx.write(nginx_file)
file_nignx.flush()
file_nignx.close()
cprint("{} file created.".format(self.nginx_file),
'white', 'on_red', attrs=['bold'])
# File move operations
subprocess.call("sudo cp {}/package/{} /etc/nginx/sites-available/".
format(BASE_DIR, self.nginx_file), shell=True)
# Nginx recording and restart
subprocess.call("sudo ln -s /etc/nginx/sites-available/{} /etc/nginx/sites-enabled".
format(self.nginx_file), shell=True)
def __copy__(self):
"""Gunicorn and nginx setting files"""
# Gunicorn
for gunicorn_package in self.data['gunicorn']:
cprint(gunicorn_package['message'],
'white', 'on_red', attrs=['bold'])
subprocess.call(gunicorn_package['name'], shell=True)
cprint("Gunicorn successful!", 'white', 'on_red', attrs=['bold'])
# Nginx
for nginx_package in self.data['nginx']:
cprint(nginx_package['message'], 'white', 'on_red', attrs=['bold'])
subprocess.call(nginx_package['name'], shell=True)
cprint("Nginx successful!", 'white', 'on_red', attrs=['bold'])
def requirements(self):
"""requirements.txt install"""
subprocess.call('{}/bin/pip3 install -r {}/requirements.txt'.format(self.virtualenv_file,
self.project_file), shell=True)
subprocess.call(
'{}/bin/pip3 install gunicorn'.format(self.virtualenv_file), shell=True)
cprint("requirements.txt successfully loaded.!",
'white', 'on_red', attrs=['bold'])
def save(self):
"""Records information."""
with open('{}/client/file/server.info'.format(BASE_DIR)) as server_file:
server_file = server_file.read().format(self.project_name, self.server_name_or_ip, self.static_url,
self.gunicorn_file, self.nginx_file,
self.project_file, self.virtualenv_file)
file_fix = server_file.replace('[', '{').replace(']', '}')
file = open('/home/{}.json'.format(self.project_name), 'w')
file.write(file_fix)
file.flush()
file.close()
cprint("/home/{}.json file created...".format(self.project_name),
'white', 'on_red', attrs=['bold'])
cprint("All successful!", 'white', 'on_red', attrs=['bold'])
subprocess.call(
'sudo chmod -R 777 /home/{}.json'.format(self.project_name), shell=True)
def nginx_restart():
"""Nginx Restart"""
subprocess.call("sudo service nginx restart", shell=True)
subprocess.call("sudo systemctl restart nginx", shell=True)
cprint("Nginx has been successfully restarted.",
'white', 'on_red', attrs=['bold'])
def gunicorn_restart(project_name):
"""Gunicorn Restart"""
with open("/home/{}.json".format(project_name)) as gunicorn_file:
data = json.load(gunicorn_file)
subprocess.call("sudo systemctl restart {}".format(
data['gunicorn_file']), shell=True)
cprint("Gunicorn has been successfully restarted.",
'white', 'on_red', attrs=['bold'])
def RunEasy():
"""It receives information from the user."""
# server_ip_or_domain
while True:
cprint("Please type in the server ip or domain address.",
'white', 'on_red', attrs=['bold'])
server_name_or_ip = str(input('server ip or domain = '))
if server_name_or_ip == "":
cprint("Please do not leave blank, try again...",
'white', 'on_red', attrs=['bold'])
continue
else:
if(domain(server_name_or_ip) or ipv4(server_name_or_ip)):
break
else:
cprint("Please enter a valid address...",
'white', 'on_red', attrs=['bold'])
continue
# Static Url
while True:
cprint("Write your STATIC_URL (Django Settings.py)",
'white', 'on_red', attrs=['bold'])
static_url = str(input('STATIC_URL = '))
if static_url == "":
cprint("Please do not leave blank, try again...",
'white', 'on_red', attrs=['bold'])
continue
else:
break
# guniorn file name
while True:
cprint("Write your gunicorn file name",
'white', 'on_red', attrs=['bold'])
gunicorn_file = str(input('Gunicorn File name = '))
if gunicorn_file == "":
cprint("Please do not leave blank, try again...",
'white', 'on_red', attrs=['bold'])
continue
else:
break
# nginx file
while True:
cprint("Write your nginx file name", 'white', 'on_red', attrs=['bold'])
nginx_file = str(input('Nginx File name = '))
if nginx_file == "":
cprint("Please do not leave blank, try again...",
'white', 'on_red', attrs=['bold'])
continue
else:
cprint("Write your virtualenv file path",
'white', 'on_red', attrs=['bold'])
cprint("Example : /home/DjangoEnv",
'white', 'on_red', attrs=['bold'])
break
# virtualenv file
while True:
virtualenv_file = str(input('Virtualenv File path = '))
if virtualenv_file == "":
cprint("Please do not leave blank, try again...",
'white', 'on_red', attrs=['bold'])
continue
else:
if(os.path.isdir(virtualenv_file)):
break
else:
cprint("No such file or directory",
'white', 'on_red', attrs=['bold'])
continue
# project file
while True:
cprint("Write your Project file path",
'white', 'on_red', attrs=['bold'])
cprint("Example : /home/Blog", 'white', 'on_red', attrs=['bold'])
project_file = str(input('Project File path = '))
if project_file == "":
cprint("Please do not leave blank, try again...",
'white', 'on_red', attrs=['bold'])
continue
else:
if(os.path.isdir(project_file)):
break
else:
cprint("No such file or directory",
'white', 'on_red', attrs=['bold'])
continue
project_name = str(project_file).split(
'/')[len(str(project_file).split('/'))-1]
easy = EasyInstall(project_name, server_name_or_ip, static_url, gunicorn_file,
nginx_file, project_file, virtualenv_file)
easy.__call__()
easy.__add__()
easy.__copy__()
easy.requirements()
easy.save()
# Restarting.
subprocess.call("sudo service nginx restart", shell=True)
subprocess.call("sudo systemctl restart nginx", shell=True)
subprocess.call("sudo systemctl restart {}".format(
gunicorn_file), shell=True)
def main():
"""Working area"""
message = """
Options:
--create Create a new site.
--nginx Nginx restart
Project_name --gunicorn Gunicorn restart
"""
if (len(sys.argv)) == 2:
if str(sys.argv[1]) == "--create":
RunEasy()
elif str(sys.argv[1]) == "--nginx":
nginx_restart()
else:
print("Command not found\n", message)
else:
if(len(sys.argv)) > 2:
if str(sys.argv[2]) == "--gunicorn":
gunicorn_restart(sys.argv[1])
else:
print("Command not found\n", message)
else:
print(message)
if __name__ == '__main__':
main()