Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
401 lines (329 loc) · 13 KB
/
Copy pathserver.py
File metadata and controls
401 lines (329 loc) · 13 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
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
import time
import jsonify as jsonify
from flask import Flask, stream_with_context, request, Response, render_template, make_response, redirect, url_for
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash
from config import *
from ssh import *
from template import *
import os
import paramiko
import json
from collections import namedtuple
import argparse
import json
from collections import namedtuple
# import sys, getopt
# from basic_auth import app
app = Flask(__name__)
# https://flask-basicauth.readthedocs.io/en/latest/
# If you would like to protect you entire site with basic access authentication, just set BASIC_AUTH_FORCE configuration variable to True:
# app.config['BASIC_AUTH_FORCE'] = True
# context = ('ssl.cert', 'ssl.key')
# hostname = '127.0.0.1'
auth = HTTPBasicAuth()
users = {}
users[Server.username] = generate_password_hash(Server.password)
print(users)
@auth.verify_password
def verify_password(username, password):
if username in users and \
check_password_hash(users.get(username), password):
return username
from multiprocessing import Process
import threading
import multiprocessing
import time
class processClass:
client = ''
command = ''
folder = ''
env = ''
def __init__(self, client, command, folder, env):
self.client = client
self.command = command
self.folder = folder
self.env = env
# p = Process(target=self.run, args=())
# p.daemon = True # Daemonize it
# p.start() # Start the execution
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start()
def run(self):
#
# This might take several minutes to complete
# print(self.command)
clientCommand(self.client, self.command, self.folder, self.env)
# time.sleep(5)
# print("stop")
# clientCommand(self.client, "stop", self.folder, self.env)
# p = multiprocessing.Process(target=clientCommand, name="clientCommand", args=(client, key, folder, env))
# p.start()
# time.sleep(5)
# p.terminate()
# p.join()
# Start foo as a process
# p = multiprocessing.Process(target=clientCommand, name="clientCommand", args=(self.client, self.command, self.folder, self.env))
# p.start()
# Wait 10 seconds for foo
# time.sleep(5)
# Terminate foo
# p.terminate()
# Cleanup
# p.join()
self.client.close()
# http://localhost/?clone=https://github.com/goethe-pl/app&cmd=start
# http://localhost/?clone=https://github.com/goethe-pl/app&install&start
# http://localhost/?github=goethe-pl/app&install&start
# http://localhost/?start
@app.route('/', methods=['GET'])
@auth.login_required
def index():
print(request.args)
folder = domain = "monit.page"
## SSH connection
Server = getBy(domain, 'hostname', config_server)
client = connect(Server)
env = 'node'
# Env List
result = {
'sourcecode': {},
'clone': {},
'github': {},
'environment': {},
'command': {},
'cmd': {},
'env': {},
}
# if "environment" in request.json:
# environment = request.json["environment"]
# clientEnvironment(client, environment, folder, result)
for key in request.args:
print("==")
print(key)
val = request.args[key]
print(val)
if key == "github":
# script = "git --quiet clone git@github.com:" + val + ".git " + folder
# script = "git clone git@github.com:" + val + ".git " + folder
script = "git clone https://github.com/" + val + ".git " + folder
commands = commandList(["ls", script], client)
result['github'][folder] = commands
# result['clone'] = clientSourcecode(client, val, folder, result)
client.close()
if key == "sourcecode":
result['sourcecode'] = clientProject(client, folder, result)
client.close()
if key == "cmd":
result['cmd'] = clientCommand(client, val, folder, env)
client.close()
if key == "start" or key == "stop" or key == "install" or key == "status":
result['env'] = clientCommand(client, "stop", folder, env)
try:
begin = processClass(client, key, folder, env)
except:
# abort(500)
return redirect("http://" + Server.ip + "/", code=500)
# result['env'] = clientCommand(client, key, folder, env)
# return redirect("http://" + Server.ip + "/", code=307)
if key == "git":
script = "apt-get install git -y"
commands = commandList(["ls", script], client)
result['command'][folder] = commands
script = "git --version"
commands = commandList(["ls", script], client)
result['command'][folder] = commands
# 'ssh-keygen -R hostname'
# script = 'if [ ! -n "$(grep "^bitbucket.org " ~/.ssh/known_hosts)" ]; then ssh-keyscan bitbucket.org >> ~/.ssh/known_hosts 2>/dev/null; fi'
'echo -e "Host github.com\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config'
script = "ssh-keygen -F github.com || ssh-keyscan github.com >> ~/.ssh/known_hosts"
commands = commandList(["ls", script], client)
result['command'][folder] = commands
client.close()
time.sleep(0.2)
# return {'server': Server.hostname, 'ip': Server.ip, 'result': result, 'param': request.args}
return redirect("http://" + Server.ip + "/", code=302)
@app.route('/test')
@auth.login_required
def test():
return "Hello, {}!".format(auth.current_user())
# return auth.current_user()
from deploy_app import *
# poprzenosic do innego pliku
# stworzyc plik konfiguracyjny: txt/json/yaml/xml
# jaka biblioteka do konwersji pomiedzy formatami? txt/json/yaml/xml
# przeniesienie do apiexec
@app.route('/deploy', methods=['GET', 'POST'])
@auth.login_required
def deploy():
## Domain
print(request.json)
# folder = domain = "2.faas.ovh"
if "domain" in request.json:
folder = domain = request.json["domain"]
## SSH connection
Server = getBy(domain, 'hostname', config_server)
client = connect(Server)
if "folder" in Server:
folder = Server.folder
print(folder)
# Env List
result = {
'sourcecode': {},
'environment': {},
'command': {},
}
if "environment" in request.json:
environment = request.json["environment"]
result = clientEnvironment(client, environment, folder, result)
if "sourcecode" in request.json:
sourcecode = request.json["sourcecode"]
result = clientSourcecode(client, sourcecode, folder, result)
result = clientProject(client, folder, result)
if "command" in request.json:
command = request.json["command"]
result = clientCommand(client, command, folder, result)
client.close()
return {'server': Server.hostname, 'ip': Server.ip, 'result': result}
def clientEnvironment(client, environment, folder, result):
print("environment:")
print(environment)
list = getEnvProjects("python", folder, ["install"])
print(list)
for e in list:
dict = list[e]
print(dict)
Env = namedtuple("Env", dict.keys())(*dict.values())
scriptpath = envTemplate(Env)
bashScript(scriptpath, client)
result['command'][e] = {Env.name: Env.command}
return result
def clientSourcecode(client, sourcecode, folder, result):
print("sourcecode:")
print(sourcecode)
list = getEnvList(sourcecode, "project", folder, domain)
print(list)
for e in list:
dict = list[e]
print(dict)
Env = namedtuple("Env", dict.keys())(*dict.values())
# print(Env.name, Env.command, Env.script, Env.folder, Env.github, Env.domain)
scriptpath = sourcecodeTemplate(Env)
bashScript(scriptpath, client)
result['sourcecode'][e] = {Env.name: Env.command}
# print("sourcecode")
# print(request.json["sourcecode"])
# list = getGithub(request.json["sourcecode"], "project", domain, folder)
# for e in list:
# dict = list[e]
# print(dict)
# Env = namedtuple("Env", dict.keys())(*dict.values())
# # print(Env.name, Env.command, Env.script, Env.folder, Env.github, Env.domain)
# scriptpath = sourcecodeTemplate(Env)
# bashScript(scriptpath, client)
# result['sourcecode'][e] = {Env.name: Env.command}
return result
def clientProject(client, folder, result):
print("project:")
print(folder)
list = getEnvProjects("project", folder, ["install", "start"])
for e in list:
dict = list[e]
print(dict)
Env = namedtuple("Env", dict.keys())(*dict.values())
# print(Env.name, Env.command, Env.script, Env.folder, Env.github, Env.domain)
scriptpath = envTemplate(Env)
bashScript(scriptpath, client)
result['command'][e] = {Env.name: Env.command}
print(result)
# list = getGithub("faas-ovh/www", "project-environment", domain, folder)
# for e in list:
# dict = list[e]
# # print(dict)
# Env = namedtuple("Env", dict.keys())(*dict.values())
# # print(Env.name, Env.command, Env.script, Env.folder, Env.github, Env.domain)
# script = Env.command + '.' + os_ext_script
# template = os.path.join('environment', Env.name, script + '.$')
# scriptpath = os.path.join('environment', Env.name, script)
# createFileFromTemplate(scriptpath, template, {'domain': Env.domain, 'folder': Env.folder, 'github': Env.github})
# bashScript(scriptpath, client)
# result[e] = {Env.name: Env.command}
return result
def clientCommand(client, command, folder, env):
print("command:")
print(command)
result = {}
if (command == "install") or (command == "update") or (command == "remove") \
or (command == "start") or (command == "stop") or (command == "status"):
print(command)
# print(Env.name, Env.command, Env.script, Env.folder, Env.github, Env.domain)
if (command == "start"):
if (env == 'node'):
# script = "cd " + folder + " && node server.js"
script = "cd " + folder + " && sh " + command + ".sh"
else:
script = "python3 " + folder + "/app.py 0.0.0.0 80"
elif (command == "stop"):
if (env == 'node'):
# script = 'pkill -f node'
script = "cd " + folder + " && sh " + command + ".sh"
else:
script = "sh " + folder + "/" + command + ".sh"
else:
# script = "sh " + folder + "/" + command + ".sh"
script = "cd " + folder + " && sh " + command + ".sh"
# script = "cd " + folder + " & ls & " + command + ".sh"
commands = commandList(["ls", script], client)
# time.sleep(5)
# commands = commandList(['pkill -f node'], client)
# scriptpath = envTemplate(Env)
# bashScript(scriptpath, client)
# result['command'][folder] = {command: script}
result[folder] = commands
# result['command'][e] = {Env.name: Env.command, 'commands': commands}
else:
result[folder] = {command: "command not recognized"}
return result
# pobieranie z git env
@app.route('/query', methods=['GET', 'POST'])
@auth.login_required
def query():
# if request.method == 'GET':
# # return render_template('static/index.html')
# return app.send_static_file('index.html')
# else:
# environment = request.args['environment']
# sourcecode = request.json['sourcecode']
# return request.query_string
# return request.json['environment']
# return {'environment': request.json['environment'], 'sourcecode': request.json['sourcecode']}
return {'environment': request.json}
@app.route('/remove', methods=['GET', 'POST'])
@auth.login_required
def remove():
domain = "app.faas.ovh"
Server = getBy(domain, 'hostname', config_server)
client = connect(Server)
folder = "api.faas.ovh"
# remove
# path = "environment\\python\\"
script = "remove.sh"
template = os.path.join('environment', 'python', script + '.$')
scriptpath = os.path.join('environment', 'python', script)
createFileFromTemplate(scriptpath, template, {'folder': folder})
bashScript(scriptpath, client)
client.close()
return {'server': Server.hostname, 'ip': Server.ip}
def authenticate():
message = {'message': "Authenticate."}
resp = jsonify(message)
resp.status_code = 401
resp.headers['WWW-Authenticate'] = 'Basic realm="Main"'
return resp
if __name__ == '__main__':
# app.run()
# main(sys.argv[1:])
# context = ('ssl.cert', 'ssl.key')
# app.run(host='0.0.0.0', port=80, ssl_context=context)
app.run(host=host, port=port, threaded=True)