forked from sauloal/pysensor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebserver.py
More file actions
319 lines (219 loc) · 6.18 KB
/
webserver.py
File metadata and controls
319 lines (219 loc) · 6.18 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
#!/usr/bin/python
import sys, os
import time
#easy_install flask
#easy_install jsonpickle
#easy_install simplejson
print "importing signal"
import signal
print "importing cpickle"
import cPickle
print "importing simple json"
import simplejson
print "importing jsonpickle"
import jsonpickle
print "importing hashlib"
import hashlib
print "importing flask"
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, make_response, jsonify, Markup, Response, send_from_directory, Blueprint
from jinja2 import TemplateNotFound
print "importing status"
sys.path.insert(0, '.')
import status
setupfile = 'setup.conf'
if not os.path.exists(setupfile):
print "count not find setup file %s" % setupfile
sys.exit(1)
exec( open(setupfile, 'r').read() )
DATA_URL_PATH = "/%s" % DATA_URL
dbPath = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), SERVER_DB)
#VARIABLES
app = Flask(__name__)
app.config.from_object(__name__)
app.jinja_env.globals['trim_blocks' ] = True
app.jinja_env.add_extension('jinja2.ext.do')
jsonpickle.set_preferred_backend('simplejson')
jsonpickle.set_encoder_options('simplejson', sort_keys=True, indent=1)
data = None
def tojason( data ):
resp = Response(
response=jsonpickle.encode( data ),
status=200,
mimetype='application/json'
)
return resp
@app.before_request
def before_request():
"""
before each request, add global variables to the global G variable.
If using WSGI (eg. apache), this won't work
"""
init_classes()
def init_classes():
"""
reads the data from the disk, parses and loads it to global variables.
has to be changed if using WSGI servers aroung it (eg. apache) once global variables
are not shared.
"""
global data
if data is None:
with app.app_context():
print "initializing db"
data = status.DataManager( db_path=dbPath, ext=pycklerext )
print "db loaded"
else:
with app.app_context():
print "updating db"
data.loadlast()
print "db updated"
with app.app_context():
g.modules = {
'memall': get_mem_all,
'memone': get_mem_one
}
g.glanularity = 60
# ===== API TO BROWSER =====
@app.route("/", methods=['GET'])
def get_base():
return "OK"
@app.route("/stats", methods=['GET'])
def get_stats():
computers = {}
comp_sum = 0
time_sum = 0
lines = ""
for utime in data.db:
for my_name in data.db[ utime ]:
if my_name not in computers:
computers[ my_name ] = 0
computers[ my_name ] += 1
comp_sum = len(computers)
time_sum = len(data.db)
for computer_name in computers:
val = computers[ computer_name ]
line = """\
<tr>
<td></td>
<td>%(computer_name)s</td>
<td>%(count)d</td>
</tr>
""" % { 'computer_name': computer_name, 'count': val }
lines += line
res = """<html>
<body>
<table>
<tr>
<td>Computers</td>
<td>%(computers)d</td>
<td></td>
</tr>
<tr>
<td>Times</td>
<td>%(times)d</td>
<td></td>
</tr>
%(lines)s
</table>
</body>
</html>""" % { 'computers': comp_sum, 'times': time_sum, 'lines': lines }
resp = Response(
response=res,
status=200,
mimetype='text/html'
)
return resp
@app.route("/raw", methods=['GET'])
def get_raw():
resp = Response(
response=jsonpickle.encode( data.get_dict() ),
status=200,
mimetype='application/json'
)
return resp
# ===== API TO GETTERS =====
@app.route("/get/<module>", methods=['GET'])
def get_module(module):
if module in g.modules:
return g.modules[ module ]( data, request )
else:
return abort( 404 )
def get_mem_all( data, request ):
mem_data = {}
for utime in data.db:
ctime = int(utime / g.glanularity) * g.glanularity
for my_name in data.db[ utime ]:
mem = data.db[ utime ][ my_name ][ 'memories' ]
for key in mem:
val = mem[ key ]
if key not in mem_data:
mem_data[ key ] = {}
if ctime not in mem_data[ key ]:
mem_data[ key ][ ctime ] = {}
mem_data[ key ][ ctime ][ my_name ] = val
return tojason( mem_data )
def get_mem_one( data, request ):
name = request.args.get('name', None)
if name is None:
return abort( 404 )
mem_data = {}
for utime in data.db:
ctime = int(utime / g.glanularity) * g.glanularity
for my_name in data.db[ utime ]:
if my_name != name:
continue
mem = data.db[ utime ][ my_name ][ 'memories' ]
for key in mem:
val = mem[ key ]
if key not in mem_data:
mem_data[ key ] = {}
if ctime not in mem_data[ key ]:
mem_data[ key ][ ctime ] = {}
mem_data[ key ][ ctime ][ my_name ] = val
if len( mem_data ) == 0:
return abort( 404 )
return tojason( mem_data )
# ===== API TO CLIENT =====
@app.route(DATA_URL_PATH, methods=['PUT'])
def master_register_node():
print "registering node"
#begin = request.data.find( ':' )
#if begin == -1:
# print "no hash found"
# abort(404)
#
#mydata = request.data[begin+1: ]
#sent_hash = request.data[ :begin]
#got_hash = hashlib.md5(mydata).hexdigest()
mydata = cPickle.loads( request.data )
sent_hash = mydata[0]
sent_data = mydata[1]
recv_hash = hashlib.md5( sent_data ).hexdigest()
if sent_hash == recv_hash:
print "hashs are the same"
else:
print "different hashes. error in transmission"
print "'%s'" % sent_hash
print "'%s'" % recv_hash
print "sent data"
print sent_data
abort(404)
#client_info = jsonpickle.decode( mydata )
client_info = cPickle.loads( sent_data )
print str( client_info )[:100]
#for k in client_info:
#nfo = client_info.pop( k )
#client_info[ float(k) ] = nfo
print data
data.add( client_info )
return 'OK'
@app.route("/options", methods=['OPTIONS'])
def master_get_options():
return jsonpickle.encode( {
DATA_URL_PATH : "Add data to the database"
}
)
def main():
app.debug = True
app.run(port=SERVER_PORT, host='0.0.0.0')
if __name__ == '__main__':
main()