-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
executable file
·338 lines (267 loc) · 9.45 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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Farsheed Ashouri'
"""
___ _ _
/ __\_ _ _ __ ___| |__ ___ ___ __| |
/ _\/ _` | '__/ __| '_ \ / _ \/ _ \/ _` |
/ / | (_| | | \__ \ | | | __/ __/ (_| |
\/ \__,_|_| |___/_| |_|\___|\___|\__,_|
Just remember: Each comment is like an apology!
Clean code is much better than Cleaner comments!
'''
'''
@desc: server.py
@author: F.Ashouri
"""
from gevent import monkey
monkey.patch_all()
from flask import Flask, request, abort, jsonify
from flask.ext.mako import render_template
from flask.ext.mako import MakoTemplates
from flask.ext.basicauth import BasicAuth
from bson.json_util import dumps
from bson.objectid import ObjectId
import ujson
from utils import general, server_tools, client_tools
from utils.parsers import alfred
from models.db import mongo
import hashlib
from copy import copy
from clientAgent import ca
__version__ = general.getVersion()
username, password = server_tools.getServerCreditentionals()
'''Register extensions'''
app = Flask(__name__)
mako = MakoTemplates(app)
app.config.update()
app.config['BASIC_AUTH_USERNAME'] = username
app.config['BASIC_AUTH_PASSWORD'] = password
basic_auth = BasicAuth(app)
@app.route("/server")
@basic_auth.required
def server():
return 'Server'
@app.route("/client")
def client():
body = render_template('client.tpl')
title = 'Client Dashboard'
data = render_template('index.tpl', body=body, title=title,
version=__version__)
return data
@app.route('/api/ping', methods=['POST'])
def ping():
''' This method pings server'''
client = server_tools.getClientIp(request)
'''Find if it's client's first ping'''
clientNewRawData = ujson.loads(request.data)
if clientNewRawData:
clientNewInfo = copy(clientNewRawData)
clientNewInfo['ip'] = client
if clientNewInfo:
data = {'ip': client, 'info': clientNewInfo,
'last_ping': general.now()}
slave = mongo.db.slaves.update({'ip': client}, data,
upsert=True) # update if find or insert new
return ujson.dumps({'message': 'PONG', 'clientInfo': clientNewInfo,
'last_ping': general.now()})
@app.route('/api/clientInfo', methods=['GET'])
def clientInfo():
client = server_tools.getClientIp(request)
slave = mongo.db.slaves.find_one({'ip': client})
return dumps(slave)
@app.route('/api/addJob', methods=['POST'])
def addJob():
"""Gets user uploded job description and add it to jobs"""
category = request.values.get('category')
if request.method == 'POST' and 'upload' in request.files:
f = request.files['upload']
data = {'job': f.read(), 'category': 'Alfred',
'filename': f.filename, 'category': category}
job = alfred.parse(data.get('job'))
#client = request.remote_addr
client = server_tools.getClientIp(request)
# hash of actual uploaded file
jobHash = hashlib.md5(data.get('job')).hexdigest()
if job:
newJob = {
'name': data.get('filename'),
'category': data.get('category'),
'data': job,
'md5': jobHash,
'bucket_size': 1,
'tags': [],
'queue': [],
'status': 'future',
'datetime': general.now(),
'owner': client,
'priority': 500,
'is_active': True,
'self': False,
'progress': 0,
}
#new = mongo.db.jobs.update({'md5':jobHash}, newJob, upsert=True)
new = mongo.db.jobs.insert(newJob)
server_tools.createNewTasks(new)
return dumps(newJob)
@app.route('/api/dbtest/<entery>', methods=['GET', 'POST'])
def dbtest(entery):
"""Simple mongodb database test"""
if request.method == 'POST':
if not request.data:
abort(400)
newData = ujson.loads(request.data)
new = mongo.db.dbtest.insert({'key': entery, 'data': newData})
return dumps(mongo.db.dbtest.find_one({'_id': new})), 201
elif request.method == 'GET':
data = mongo.db.dbtest.find({'key': entery})
return dumps(data)
@app.route('/api/getJobsInfo')
def getJobsInfo():
"""List jobs information for client"""
#client = request.remote_addr
client = server_tools.getClientIp(request)
jobs = server_tools.getClientJobsInformation(client)
return ujson.dumps(jobs)
@app.route('/api/fetchQueuedTasks')
def fetchQueuedTasks():
"""Give Queued tasks for a client to render"""
client = server_tools.getClientIp(request)
#client = request.remote_addr
data = server_tools.getQueuedTasksForClient(client)
return ujson.dumps(data)
@app.route('/api/updateTask', methods=['POST'])
def updateTask():
client = server_tools.getClientIp(request)
data = general.unpack(request.data)
tid = ObjectId(data.get('_id'))
data = data.get('data')
task = mongo.db.tasks.find_one({'_id': tid})
if not task:
abort(404)
task['last_activity'] = general.now()
for i in data:
if data[i]:
task[i] = data[i]
task['slave'] = client
mongo.db.tasks.update({'_id': tid}, task)
if task.get('status') == 'on progress':
job = mongo.db.jobs.find_one({'_id': task.get('job')})
job['status'] = 'on progress'
mongo.db.jobs.update({'_id': job.get('_id')}, job)
if task['progress'] == 100:
ca.AsyncResult(task.get('ctid')).revoke()
return general.pack('OK')
@app.route('/api/tasklog', methods=['POST'])
def tasklog():
'''client sends this data'''
data = general.unpack(request.data)
tid = ObjectId(data.get('_id'))
log = data.get('log')
log['datetime'] = general.now()
task = mongo.db.tasks.find_one({'_id': tid})
if not task:
abort(404)
task['logs'].append(log)
mongo.db.tasks.update({'_id': tid}, task)
return general.pack('OK')
@app.route('/api/cancelJob', methods=['POST'])
def cancelJob():
data = ujson.loads(request.data)
jobId = data.get('id') # get job is in string format
_id = ObjectId(jobId)
result = server_tools.cancelJob(_id)
return ujson.dumps(result)
@app.route('/api/pauseJob', methods=['POST'])
def pauseJob():
data = ujson.loads(request.data)
jobId = data.get('id') # get job is in string format
_id = ObjectId(jobId)
result = server_tools.pauseJob(_id)
return ujson.dumps(result)
@app.route('/api/archiveJob', methods=['POST'])
def archiveJob():
data = ujson.loads(request.data)
jobId = data.get('id') # get job is in string format
_id = ObjectId(jobId)
result = server_tools.archiveJob(_id)
return ujson.dumps(result)
@app.route('/api/resumeJob', methods=['POST'])
def resumeJob():
#client = request.remote_addr
client = server_tools.getClientIp(request)
data = ujson.loads(request.data)
jobId = data.get('id') # get job is in string format
_id = ObjectId(jobId)
result = server_tools.resumeJob(_id, client)
return ujson.dumps(result)
@app.route('/api/tryAgainJob', methods=['POST'])
def tryAgainJob():
data = ujson.loads(request.data)
jobId = data.get('id') # get job is in string format
_id = ObjectId(jobId)
result = server_tools.tryAgainJob(_id)
return ujson.dumps(result)
@app.route('/api/slaves', methods=['GET'])
def slaves():
'''Get slaves info for farm stats of client'''
return ujson.dumps(server_tools.getSlaveInfo())
@app.route('/api/taskStatus', methods=['POST'])
def taskStatus():
'''Get task status'''
data = general.unpack(request.data)
task_id = data.get('_id') # get job is in string format
_id = ObjectId(task_id)
result = server_tools.getTaskStatus(_id)
return general.pack(result)
@app.route('/api/jobDetail', methods=['POST'])
def jobDetail():
'''Get task status'''
data = ujson.loads(request.data)
job_id = data.get('_id') # get job is in string format
_id = ObjectId(job_id)
return ujson.dumps(server_tools.getJobDetail(_id))
@app.route('/api/workerPing', methods=['get'])
def workerPing():
client = server_tools.getClientIp(request)
return ujson.dumps(server_tools.getWorkerPing(client))
@app.route('/api/workerStats', methods=['get'])
def workerStats():
client = server_tools.getClientIp(request)
return ujson.dumps(server_tools.getWorkerStats(client))
@app.route('/api/killProcess', methods=['post'])
def killProcess():
data = ujson.loads(request.data)
_id = ObjectId(data.get('_id'))
return ujson.dumps(server_tools.killTaskprocess(_id))
@app.route('/api/workerStats', methods=['get'])
def showImage():
client = server_tools.getClientIp(request)
data = ujson.loads(request.data)
path = data.get(path)
return ujson.dumps(server_tools.shoImage(client, path))
if __name__ == "__main__":
def run_debug():
app.run(
host='0.0.0.0',
port=9000,
debug=True,
)
def run_tornado():
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(9000)
IOLoop.instance().start()
def run_gevent():
from gevent.wsgi import WSGIServer
http_server = WSGIServer(('0.0.0.0', 9000), app)
http_server.serve_forever()
def run_bjoern():
import bjoern
bjoern.run(app, '0.0.0.0', 9000)
#run_tornado()
run_debug()
#run_bjoern()
# run_gevent()