-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
238 lines (222 loc) · 9.97 KB
/
app.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
import flask, os, sqlite3, docker, sys, flask_sock, json, flask_cors, time
def sqlquery(sql, *parameter):
conn = sqlite3.connect("database.db", check_same_thread=False)
cursor = conn.cursor()
data = cursor.execute(sql, (parameter)).fetchall()
conn.commit()
return data
os.chdir("/etc/deamon")
client = docker.from_env()
app = flask.Flask(__name__)
sock = flask_sock.Sock(app)
cors = flask_cors.CORS(app, resources={r"/*": {"origins": "*"}})
@app.route("/api/servers/<uuid>/stop", methods=["POST"])
def stop_server(uuid):
data = sqlquery("SELECT * FROM containers WHERE uuid = ? and user_token = ?", uuid, flask.request.json["user_token"])
if len(data):
try:
container = client.containers.get(uuid)
container.kill()
container.remove(force=True)
response = flask.jsonify({"succes": "server stopped"})
response.headers["Access-Control-Allow-Origin"] = "*"
return response
except:
response = flask.jsonify({"error": "server already running"})
response.headers["Access-Control-Allow-Origin"] = "*"
return response
else:
flask.abort(401)
@app.route("/api/servers/<uuid>/files/upload", methods=["POST"])
def upload_file(uuid):
if len(sqlquery("SELECT * FROM containers WHERE uuid = ? and user_token = ?", uuid, flask.request.form["user_token"])):
file = flask.request.files["file"]
if file.filename == "":
return "something went wrong"
if file:
file.save("{}/{}/{}/{}".format(app.config["UPLOAD_FOLDER"], uuid, flask.request.form.get("path"), file.filename))
return "file uploaded"
else:
flask.abort(401)
@app.route("/api/servers/<uuid>/files", methods=["POST"])
def server_files(uuid):
if len(sqlquery("SELECT * FROM containers WHERE uuid = ? and user_token = ?", uuid, flask.request.form["user_token"])):
directory = []
for file in os.listdir("/etc/deamon/data/{}/{}".format(uuid, flask.request.form.get("path"))):
if os.path.isdir("/etc/deamon/data/{}/{}/{}".format(uuid, flask.request.form.get("path"), file)):
directory.append({"name": file, "type": "dir", "edit": False, "path": flask.request.form.get("path")})
else:
directory.append({"name": file, "type": "file", "edit": True, "path": flask.request.form.get("path")})
return flask.jsonify(directory)
else:
flask.abort(401)
@app.route("/api/servers/<uuid>/files/edit", methods=["GET", "POST"])
def file_content(uuid):
if len(sqlquery("SELECT * FROM containers WHERE uuid = ? and user_token = ?", uuid, flask.request.form["user_token"])):
if flask.request.method == "GET":
return open("/etc/deamon/data/{}/{}".format(uuid, flask.request.form.get("file")), "r").read()
else:
open("/etc/deamon/data/{}/{}".format(uuid, flask.request.form.get("file")), "w").write(flask.request.form.get("content"))
return "updated succesfully"
else:
flask.abort(401)
@app.route("/api/servers/<uuid>/files/create", methods=["POST"])
def create_file(uuid):
if len(sqlquery("SELECT * FROM containers WHERE uuid = ? and user_token = ?", uuid, flask.request.form["user_token"])):
if flask.request.form.get("type") == "file":
open("/etc/deamon/data/{}/{}/{}".format(uuid, flask.request.form.get("path"), flask.request.form.get("file_name")), "w")
return "created succesfully"
else:
try:
os.mkdir("/etc/deamon/data/{}/{}/{}".format(uuid, flask.request.form.get("path"), flask.request.form.get("dir_name")))
except:
os.makedirs("/etc/deamon/data/{}/{}/{}".format(uuid, flask.request.form.get("path"), flask.request.form.get("dir_name")))
return "created succesfully"
else:
flask.abort(401)
@app.route("/api/servers/<uuid>/start", methods=["POST"])
def start_server(uuid):
data = sqlquery("SELECT * FROM containers WHERE uuid = ? and user_token = ?", uuid, flask.request.json["user_token"])
if len(data):
try:
container = client.containers.get(uuid)
if container.status == "exited":
container.stop()
container.remove(force=True)
mount = docker.types.Mount(
target="/home/container",
source="/etc/deamon/data/{}".format(uuid),
type="bind"
)
container = client.containers.run(
image=flask.request.json["image"],
command=["sh", "-c", flask.request.json["startup_command"]],
mounts=[mount],
environment=["TERM=xterm-256color"],
name=uuid,
ports={data[0][3]:data[0][3]},
detach=True,
working_dir="/home/container",
stdout=True,
stderr=True
)
response = flask.jsonify({"succes": "server started"})
response.headers["Access-Control-Allow-Origin"] = "*"
return response
else:
response = flask.jsonify({"error": "server already running"})
response.headers["Access-Control-Allow-Origin"] = "*"
return response
except:
mount = docker.types.Mount(
target="/home/container",
source="/etc/deamon/data/{}".format(uuid),
type="bind"
)
container = client.containers.run(
image=flask.request.json["image"],
command=["sh", "-c", flask.request.json["startup_command"]],
mounts=[mount],
environment=["TERM=xterm-256color"],
name=uuid,
ports={data[0][3]:data[0][3]},
detach=True,
working_dir="/home/container",
stdout=True,
stderr=True
)
response = flask.jsonify({"succes": "server started"})
response.headers["Access-Control-Allow-Origin"] = "*"
return response
else:
flask.abort(401)
@app.route("/api/servers/<uuid>/create", methods=["POST"])
def create_server(uuid):
if flask.request.form["system_token"] == app.config["SYSTEM_TOKEN"]:
os.mkdir("/etc/deamon/data/{}".format(uuid))
sqlquery("INSERT INTO containers (uuid, user_token, port, memory) VALUES (?, ?, ?, ?)", uuid, flask.request.form.get("user_token"), flask.request.form.get("port"), flask.request.form.get("memory"))
return "server created"
else:
flask.abort(401)
@app.route("/")
def main():
response = flask.jsonify({"succes": "node online"})
response.headers.add("Access-Control-Allow-Origin", "*")
return response
@sock.route("/logs")
def logs(ws):
while True:
data = json.loads(ws.receive())
if data.get("uuid"):
try:
if client.containers.get(data.get("uuid")).status == "exited":
container = client.containers.get(data.get("uuid"))
ws.send("Server marked as offline..\n")
if client.containers.get(data.get("uuid")).status == "running":
container = client.containers.get(data.get("uuid"))
for line in container.attach(stdout=True, stream=True, logs=True):
ws.send(line.decode())
ws.send("\nServer marked as offline..\n")
except Exception:
ws.send("Server marked as offline..\n")
@sock.route("/memory")
def stats(ws):
while True:
data = json.loads(ws.receive())
if data.get("uuid"):
try:
if client.containers.get(data.get("uuid")).status == "running":
container = client.containers.get(data.get("uuid"))
for line in container.stats(decode=True, stream=True):
ws.send(line["memory_stats"]["usage"])
except Exception:
pass
@sock.route("/disk")
def disk(ws):
while True:
data = json.loads(ws.receive())
if data.get("uuid"):
while True:
container_size = 0
for path, dirs, files in os.walk("/etc/deamon/data/{}".format(data.get("uuid"))):
for f in files:
fp = os.path.join(path, f)
container_size += os.path.getsize(fp)
ws.send(container_size)
time.sleep(4)
@sock.route("/status")
def status(ws):
while True:
data = json.loads(ws.receive())
if data.get("uuid"):
while True:
time.sleep(0.1)
try:
if client.containers.get(data.get("uuid")).status == "exited":
ws.send("offline")
if client.containers.get(data.get("uuid")).status == "running":
ws.send("online")
except Exception:
ws.send("offline")
try:
if sys.argv[1] == "--token":
conn = sqlite3.connect("database.db", check_same_thread=False)
cursor = conn.cursor()
cursor.executescript(open("schema.sql").read())
conn.commit()
if not os.path.exists("/etc/deamon/data"):
os.mkdir("/etc/deamon/data")
print("\n-> Node configured succesfully")
print("-> Enter: service deamon start, to start deamon\n")
cursor.execute("INSERT INTO settings (system_token) VALUES (?)", (sys.argv[2],))
conn.commit()
os._exit(1)
except:
if os.path.isfile("database.db"):
app.config["SYSTEM_TOKEN"] = sqlquery("SELECT * FROM settings")[0][0]
app.config["SECRET_KEY"] = os.urandom(30).hex()
app.config["UPLOAD_FOLDER"] = "/etc/deamon/data"
app.run(debug=False, host="0.0.0.0", port=5001)
else:
print("\n-> Node not configured")
os._exit(1)