-
Notifications
You must be signed in to change notification settings - Fork 64
/
handlers.py
1867 lines (1523 loc) · 62.8 KB
/
handlers.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
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# Copyright (C) 2015 by seeedstudio
# Author: Jack Shao ([email protected])
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Dependences: see server.py header section
import os
from datetime import timedelta
import json
import sqlite3 as lite
import re
import jwt
import md5
import hashlib
import base64
import httplib
import uuid
from shutil import copy
from build_firmware import *
import yaml
import threading
import time
import smtplib
import traceback
import config as server_config
from tornado.httpserver import HTTPServer
from tornado.tcpserver import TCPServer
from tornado import ioloop
from tornado import gen
from tornado import iostream
from tornado import web
from tornado import websocket
from tornado import escape
from tornado.options import define, options
from tornado.log import *
from tornado.concurrent import Future
from tornado_cors import CorsMixin
from tornado.ioloop import IOLoop
from coroutine_msgbus import *
TOKEN_SECRET = "!@#$%^&*RG)))))))JM<==TTTT==>((((((&^HVFT767JJH"
class BaseHandler(CorsMixin, web.RequestHandler):
CORS_ORIGIN = '*'
CORS_HEADERS = 'Content-Type'
def get_current_user(self):
user = None
token = self.get_argument("access_token","")
if not token:
try:
token_str = self.request.headers.get("Authorization")
token = token_str.replace("token ","")
except:
token = None
if token:
try:
cur = self.application.cur
cur.execute('select * from users where token="%s"'%token)
rows = cur.fetchall()
if len(rows) > 0:
user = rows[0]
except:
user = None
else:
user = None
if not user:
self.resp(403,"Please login to get the token")
else:
gen_log.info("get current user, id: %s, email: %s" % (user['user_id'], user['email']))
return user
'''
200 OK - API call successfully executed.
400 Bad Request - Wrong Grove/method searching path provided, or wrong parameter for method provided
403 Forbidden - Your access token is not authorized.
404 Not Found - The device you requested is not currently online, or the resource/endpoint you requested does not exist.
408 Timed Out - The server can not communicate with device in a specified time out period.
500 Server errors - It's usually caused by the unexpected errors of our side.
'''
def resp (self, status_code, meta=None):
if status_code >= 300:
self.failure_reason = str(meta)
raise web.HTTPError(status_code)
else:
if isinstance(meta, dict):
self.write(meta)
elif isinstance(meta, list):
self.write({"data":meta})
elif not meta:
self.write({'result':'ok'})
else:
self.write(meta)
def write_error(self, status_code, **kwargs):
if self.settings.get("serve_traceback") and "exc_info" in kwargs:
# in debug mode, try to send a traceback
lines = []
for line in traceback.format_exception(*kwargs["exc_info"]):
lines.append(line)
self.finish({"error": self.failure_reason, "traceback": lines})
else:
try:
self.finish({"error": self.failure_reason})
except AttributeError:
self.finish({"error": "Unknown error occured."})
def get_uuid (self):
return str(uuid.uuid4())
def gen_uuid_without_dash(self):
return str(uuid.uuid1()).replace('-','')
def gen_token (self, email):
return jwt.encode({'email': email,'uuid':self.get_uuid()}, TOKEN_SECRET, algorithm='HS256').split(".")[2]
class IndexHandler(BaseHandler):
@web.authenticated
def get(self):
#DeviceServer.accepted_conns[0].submit_cmd("OTA\r")
self.resp(400, "Please specify the url as this format: /v1/node/grove_name/property")
class TestHandler(web.RequestHandler):
def get(self):
self.render("test.html", ip=self.request.remote_ip)
class UserCreateHandler(BaseHandler):
def get (self):
self.resp(404, "Please post to this url")
def post(self):
email = self.get_argument("email","")
passwd = self.get_argument("password","")
if not email:
self.resp(400, "Missing email information")
return
if not passwd:
self.resp(400, "Missing password information")
return
if not re.match(r'\w[\w\.-]*@\w[\w\.-]+\.\w+', email):
self.resp(400, "Bad email address")
return
cur = self.application.cur
token = self.gen_token(email)
try:
cur.execute('select * from users where email="%s"'%email)
rows = cur.fetchall()
if len(rows) > 0:
self.resp(400, "This email already registered")
return
cur.execute("INSERT INTO users(user_id,email,pwd,token,created_at) VALUES(?,?,?,?,datetime('now'))", (self.gen_uuid_without_dash(), email, md5.new(passwd).hexdigest(), token))
except web.HTTPError:
raise
except Exception,e:
self.resp(500,str(e))
return
finally:
self.application.conn.commit()
self.resp(200, meta={"token": token})
class ExtUsersHandler(BaseHandler):
def get (self, uri):
print uri
self.resp(404, "Please post to this url")
def post(self, uri):
email = self.get_argument("email","")
bind_id = self.get_argument("bind_id","")
bind_region = self.get_argument("bind_region","")
token = self.get_argument("token","")
secret = self.get_argument("secret","")
if secret != server_config.ext_user_secret:
self.resp(403, "Wrong secret")
return
if not bind_id and not email:
self.resp(400, "Missing bind_id / email information")
return
if not token:
self.resp(400, "Missing token information")
return
cur = self.application.cur
try:
create_new = False
if email:
cur.execute('SELECT * FROM users WHERE email=?', (email,))
rows = cur.fetchall()
if len(rows) > 0:
cur.execute('UPDATE users SET token=?,ext_bind_id=?,ext_bind_region=? WHERE email=?', (token, bind_id, bind_region, email))
else:
create_new = True
else:
cur.execute('SELECT * FROM users WHERE ext_bind_id=?', (bind_id,))
rows = cur.fetchall()
if len(rows) > 0:
cur.execute('UPDATE users SET token=? WHERE ext_bind_id=?', (token, bind_id))
else:
create_new = True
if create_new:
cur.execute("INSERT INTO users(user_id,email,token,ext_bind_id,ext_bind_region,created_at) VALUES(?,?,?,?,?,datetime('now'))",
(self.gen_uuid_without_dash(), email, token, bind_id, bind_region))
except web.HTTPError:
raise
except Exception,e:
self.resp(500,str(e))
return
finally:
self.application.conn.commit()
self.resp(200)
class UserChangePasswordHandler(BaseHandler):
def get (self):
self.resp(403, "Please post to this url")
@web.authenticated
def post(self):
passwd = self.get_argument("password","")
if not passwd:
self.resp(400, "Missing new password information")
return
email = self.current_user["email"]
token = self.current_user["token"]
gen_log.info("%s want to change password with token %s"%(email,token))
cur = self.application.cur
try:
new_token = self.gen_token(email)
cur.execute('update users set pwd=?,token=? where email=?', (md5.new(passwd).hexdigest(),new_token, email))
self.resp(200, meta={"token": new_token})
gen_log.info("%s succeed to change password"%(email))
except Exception,e:
self.resp(500,str(e))
return
finally:
self.application.conn.commit()
class UserRetrievePasswordHandler(BaseHandler):
def get(self):
self.retrieve()
def post(self):
self.retrieve()
def retrieve(self):
email = self.get_argument('email','')
if not email:
self.resp(400, "You must specify the email of the account which you want to retrieve password.")
return
if not re.match(r'^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$', email):
self.resp(400, "Bad email address")
return
gen_log.info("%s want to retrieve password"%(email))
cur = self.application.cur
try:
cur.execute('select * from users where email="%s"' % email)
row = cur.fetchone()
if not row:
self.resp(404, "No account registered with this email")
return
new_password = self.gen_token(email)[0:6]
cur.execute('update users set pwd=? where email=?', (md5.new(new_password).hexdigest(), email))
#start a thread sending email here
ioloop.IOLoop.current().add_callback(self.start_thread_send_email, email, new_password)
self.resp(200)
except web.HTTPError:
raise
except Exception,e:
self.resp(500, str(e))
return
finally:
self.application.conn.commit()
def start_thread_send_email (self, email, new_password):
thread_name = "email_thread-" + str(email)
li = threading.enumerate()
for l in li:
if l.getName() == thread_name:
gen_log.info('INFO: Skip same email request!')
return
threading.Thread(target=self.email_sending_thread, name=thread_name,
args=(email, new_password)).start()
def email_sending_thread (self, email, new_password):
s = smtplib.SMTP_SSL(server_config.smtp_server)
try:
s.login(server_config.smtp_user, server_config.smtp_pwd)
except Exception,e:
gen_log.error(e)
return
sender = '[email protected]'
receiver = email
message = """From: Wio_Link <%s>
To: <%s>
Subject: The password for your account of iot.seeed.cc has been retrieved
Dear User,
Thanks for your interest in iot.seeed.cc, the new password for your account is
%s
Please change it as soon as possible.
Thank you!
IOT Team from Seeed
""" % (sender, receiver, new_password)
try:
s.sendmail(sender, receiver, message)
except Exception,e:
gen_log.error(e)
return
gen_log.info('sent new password %s to %s' % (new_password, email))
class UserLoginHandler(BaseHandler):
def get (self):
self.resp(403, "Please post to this url")
def post(self):
if self.request.headers.get("content-type") and self.request.headers.get("content-type").find("json") > 0:
try:
json_data = json.loads(self.request.body)
email = json_data['email']
passwd = json_data['password']
except ValueError:
self.resp(400, 'Unable to parse JSON.')
else:
email = self.get_argument("email","")
passwd = self.get_argument("password","")
if not email:
self.resp(400, "Missing email information")
return
if not passwd:
self.resp(400, "Missing password information")
return
if not re.match(r'^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$', email):
self.resp(400, "Bad email address")
return
cur = self.application.cur
try:
cur.execute('select * from users where email=? and pwd=?', (email, md5.new(passwd).hexdigest()))
row = cur.fetchone()
if not row:
self.resp(400, "Login failed - invalid email or password")
return
self.resp(200, meta={"token": row["token"], "user_id": row["user_id"]})
except web.HTTPError:
raise
except Exception,e:
self.resp(500,str(e))
return
finally:
self.application.conn.commit()
class DriversHandler(BaseHandler):
@web.authenticated
def get (self):
cur_dir = os.path.split(os.path.realpath(__file__))[0]
json_drivers = {}
with open(os.path.join(cur_dir, "drivers.json")) as f:
json_drivers = json.load(f)
self.resp(200, meta={"drivers": json_drivers})
@web.authenticated
def post(self):
self.resp(403, "Please get this url")
class DriversStatusHandler(BaseHandler):
@web.authenticated
def get (self):
cur_dir = os.path.split(os.path.realpath(__file__))[0]
scan_status = {}
with open(os.path.join(cur_dir, "scan_status.json")) as f:
scan_status = json.load(f)
self.resp(200, meta=scan_status)
@web.authenticated
def post(self):
self.resp(403, "Please get this url")
class BoardsListHandler(BaseHandler):
@web.authenticated
def get (self):
cur_dir = os.path.split(os.path.realpath(__file__))[0]
boards = []
with open(os.path.join(cur_dir, "boards.json")) as f:
boards = json.load(f)
self.resp(200, meta={"boards": boards})
@web.authenticated
def post(self):
self.resp(403, "Please get this url")
class NodeCreateHandler(BaseHandler):
def get (self):
self.resp(404, "Please post to this url")
@web.authenticated
def post(self):
node_name = self.get_argument("name","").strip()
if not node_name:
self.resp(400, "Missing node name information")
return
board = self.get_argument("board","").strip()
if not board:
board = "Wio Link v1.0"
user = self.current_user
email = user["email"]
user_id = user["user_id"]
node_id = self.gen_uuid_without_dash()
node_sn = md5.new(self.get_uuid()).hexdigest()
node_key = md5.new(self.gen_token(email)).hexdigest() #we need the key to be 32bytes long too
cur = self.application.cur
try:
cur.execute("INSERT INTO nodes(node_id,user_id,node_sn,name,private_key,board) VALUES(?,?,?,?,?,?)", (node_id, user_id, node_sn,node_name, node_key, board))
self.resp(200, meta={"node_sn":node_sn,"node_key": node_key})
except Exception,e:
self.resp(500,str(e))
return
finally:
self.application.conn.commit()
class NodeListHandler(BaseHandler):
def initialize (self, conns):
self.conns = conns
@web.authenticated
def get (self):
user = self.current_user
email = user["email"]
user_id = user["user_id"]
cur = self.application.cur
try:
cur.execute("select * from nodes where user_id='%s'" % (user_id))
rows = cur.fetchall()
nodes = []
for r in rows:
online = False
if r['node_sn'] in self.conns:
conn = self.conns[r['node_sn']]
if conn.online_status == True:
online = True
board = r["board"] if r["board"] else "Wio Link v1.0"
nodes.append({"name":r["name"], "node_sn":r["node_sn"], "node_key":r['private_key'], "online":online, \
"dataxserver":r["dataxserver"], "board":board})
self.resp(200, meta={"nodes":nodes})
except Exception,e:
self.resp(500,str(e))
return
def post(self):
self.resp(404, "Please get this url")
class NodeInfoHandler(BaseHandler):
def initialize (self, conns):
self.conns = conns
@web.authenticated
def get (self, node_id):
cur = self.application.cur
try:
cur.execute("select * from nodes where node_id='%s'" % (node_id))
r = cur.fetchone()
if r:
online = False
if r['node_sn'] in self.conns:
conn = self.conns[r['node_sn']]
if conn.online_status == True:
online = True
board = r["board"] if r["board"] else "Wio Link v1.0"
node = {"name":r["name"], "node_sn":r["node_sn"], "node_key":r['private_key'], "online":online,
"dataxserver":r["dataxserver"], "board":board}
self.resp(200, meta=node)
else:
self.resp(400, "Node not exist")
except web.HTTPError:
raise
except Exception,e:
self.resp(500,str(e))
return
def post(self):
self.resp(404, "Please get this url")
class NodeRenameHandler(BaseHandler):
def get (self):
self.resp(404, "Please post to this url")
@web.authenticated
def post(self):
node_sn = self.get_argument("node_sn","").strip()
if not node_sn:
self.resp(400, "Missing node sn information")
return
new_node_name = self.get_argument("name","").strip()
gen_log.debug('node %s wants to change its name to %s' % (node_sn, new_node_name))
if not new_node_name:
self.resp(400, "Missing node name information")
return
cur = self.application.cur
try:
cur.execute("UPDATE nodes set name=? WHERE node_sn=?" , (new_node_name, node_sn))
if cur.rowcount > 0:
self.resp(200)
else:
self.resp(400, "Node not exist")
except web.HTTPError:
raise
except Exception,e:
self.resp(500,str(e))
return
finally:
self.application.conn.commit()
class NodeDeleteHandler(BaseHandler):
@web.authenticated
def get (self):
self.resp(404, "Please post to this url")
@web.authenticated
def post(self):
node_sn = self.get_argument("node_sn","").strip()
if not node_sn:
self.resp(400, "Missing node sn information")
return
user = self.current_user
user_id = user["user_id"]
cur = self.application.cur
try:
cur.execute("select * from nodes where user_id=? and node_sn=?", (user_id, node_sn))
rows = cur.fetchall()
if len(rows) > 0:
node_id = rows[0]['node_id']
cur.execute("delete from resources where node_id=?", (node_id, ))
cur.execute("delete from nodes where node_id=?", (node_id, ))
if cur.rowcount > 0:
self.resp(200)
else:
self.resp(400, "node not exist")
else:
self.resp(400, "node not exist")
except web.HTTPError:
raise
except Exception,e:
self.resp(500,str(e))
return
finally:
self.application.conn.commit()
class NodeBaseHandler(BaseHandler):
def initialize (self, conns, state_waiters, state_happened):
self.conns = conns
self.state_waiters = state_waiters
self.state_happened = state_happened
def get_current_user(self):
return None
def get_node (self):
node = None
token = self.get_argument("access_token","")
if not token:
try:
token_str = self.request.headers.get("Authorization")
token = token_str.replace("token ","")
except:
token = None
gen_log.debug("node token:"+ str(token))
if token:
node = self.application.cache.get(token)
if not node:
try:
cur = self.application.cur
cur.execute('select * from nodes where private_key="%s"'%token)
rows = cur.fetchall()
if len(rows) > 0:
node = rows[0]
self.application.cache.add(token, node, self.application.cache_expire)
except:
node = None
else:
node = None
if not node:
self.resp(403,"Please attach the valid node token (not the user token)")
else:
gen_log.debug("get current node, id: %s, name: %s" % (node['node_id'],node["name"]))
return node
class NodeReadWriteHandler(NodeBaseHandler):
@gen.coroutine
def pre_request(self, req_type, uri):
return True
@gen.coroutine
def post_request(self, req_type, uri, resp):
#append node name to the response of .well-known
if req_type == 'get' and uri.find('.well-known') >= 0 and 'msg' in resp and type(resp['msg']) == dict:
resp['msg']['name'] = self.node['name']
@gen.coroutine
def get(self, uri):
uri = uri.split("?")[0]
gen_log.debug("get: "+ str(uri))
node = self.get_node()
if not node:
return
self.node = node
if not self.pre_request('get', uri):
return
if node['node_sn'] in self.conns:
conn = self.conns[node['node_sn']]
if not conn.killed:
try:
cmd = "GET /%s\r\n"%(uri)
cmd = cmd.encode("ascii")
ok, resp = yield conn.submit_and_wait_resp (cmd, "resp_get")
if ok:
self.post_request('get', uri, resp)
if 'status' in resp and resp['status'] != 200:
msg = resp['msg'] or 'Unknown reason'
self.resp(resp['status'], msg)
else:
self.resp(200,meta=resp['msg'])
except web.HTTPError:
raise
except Exception,e:
gen_log.error(e)
return
self.resp(404, "Node is offline")
@gen.coroutine
def post (self, uri):
uri = uri.split("?")[0].rstrip("/")
gen_log.info("post to: "+ str(uri))
node = self.get_node()
if not node:
return
self.node = node
if self.request.headers.get("content-type") and self.request.headers.get("content-type").find("json") > 0:
self.resp(400, "Can not accept application/json post request.")
return
if not self.pre_request('post', uri):
return
if node['node_sn'] in self.conns:
conn = self.conns[node['node_sn']]
if not conn.killed:
try:
cmd = "POST /%s\r\n"%(uri)
cmd = cmd.encode("ascii")
ok, resp = yield conn.submit_and_wait_resp (cmd, "resp_post")
if ok:
self.post_request('post', uri, resp)
if 'status' in resp and resp['status'] != 200:
msg = resp['msg'] or 'Unknown reason'
self.resp(resp['status'], msg)
else:
self.resp(200,meta=resp['msg'])
except web.HTTPError:
raise
except Exception,e:
gen_log.error(e)
return
self.resp(404, "Node is offline")
class NodeFunctionHandler(NodeReadWriteHandler):
@gen.coroutine
def post (self, uri):
uri = uri.split("?")[0].rstrip("/")
gen_log.info("post to: "+ str(uri))
node = self.get_node()
if not node:
return
self.node = node
if self.request.headers.get("content-type") and self.request.headers.get("content-type").find("json") > 0:
self.resp(400, "Can not accept application/json post request.")
return
arg = None
try:
arg = self.get_body_argument('arg')
print arg
arg = base64.b64encode(arg)
print arg
except web.MissingArgumentError:
self.resp(400, "Missing function's argument - arg")
return
except UnicodeEncodeError:
self.resp(400, "Unicode is not supported")
return
uri = uri.strip('/')
if uri.count('/') > 1:
self.resp(400, "Bad URL - function's argument should in post body")
return
if self.node['node_sn'] in self.conns:
conn = self.conns[self.node['node_sn']]
if not conn.killed:
try:
cmd = "POST /%s/%s\r\n"%(uri.strip('/'), arg)
cmd = cmd.encode("ascii")
ok, resp = yield conn.submit_and_wait_resp (cmd, "resp_post")
if 'status' in resp and resp['status'] != 200:
msg = resp['msg'] or 'Unknown reason'
self.resp(resp['status'], msg)
else:
self.resp(200,meta=resp['msg'])
except web.HTTPError:
raise
except Exception,e:
gen_log.error(e)
return
self.resp(404, "Node is offline")
class NodeSettingHandler(NodeReadWriteHandler):
def pre_request(self, req_type, uri):
if req_type == 'post' and uri.find('setting/dataxserver') >= 0:
ips = re.findall(r'.*/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', uri)
if not ips:
self.resp(400, "please specify the correct ip address for data exchange server")
return False
url = self.get_argument('dataxurl', '').rstrip('/')
patt = r'^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*$'
if not url or not re.match(patt, url):
self.resp(400, "please specify the correct url for data exchange server")
return False
else:
return True
if req_type == 'post' and uri.find('setting/drop') >= 0:
if self.node['node_sn'] in self.conns:
conn = self.conns[self.node['node_sn']]
if not conn.killed:
conn.kill_myself()
self.resp(200)
return False
self.resp(404, "Node is offline")
return False
def post_request(self, req_type, uri, resp):
if req_type == 'post' and uri.find('setting/dataxserver') >= 0:
#ips = re.findall(r'.*/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', uri)
url = self.get_argument('dataxurl', '')
if url:
#print url
gen_log.debug('node %s want to change data x server to %s' % (self.node['node_id'], url))
try:
cur = self.application.cur
cur.execute('update nodes set dataxserver=? where node_id=?', (url, self.node['node_id']))
except Exception,e:
gen_log.error(e)
finally:
self.application.conn.commit()
class NodesEventHandler(websocket.WebSocketHandler):
def initialize (self, conns):
self.conns = conns
self.timeout_wait_token = None
def check_origin(self, origin):
return True
def get_user_by_token(self, token):
if token:
try:
cur = self.application.cur
cur.execute('select * from users where token="%s"' % token)
user = cur.fetchone()
gen_log.info("get current user in NodesEventHandler, id: %s, email: %s" % (user['user_id'], user['email']))
except:
user = None
else:
user = None
return user
def open(self):
gen_log.info("websocket open (NodesEventHandler) ...")
self.connected = True
self.timeout_wait_token = IOLoop.current().call_later(5, self.close)
def on_close(self):
gen_log.info("websocket close (NodesEventHandler)")
self.connected = False
if hasattr(self, 'event_q'):
self.event_listener.delete_queue(self.event_q)
self.event_listener = None
def on_message(self, message):
if self.timeout_wait_token:
IOLoop.current().remove_timeout(self.timeout_wait_token)
self.timeout_wait_token = None
if self.current_user:
return
self.user_token = message.strip()
self.current_user = self.get_user_by_token(self.user_token)
if not self.current_user:
self.write_message({"error":"invalid user token"})
self.connected = False
self.close()
return
self.event_listener = CoEventBus().listener('/event/users/{}'.format(self.current_user['user_id']))
self.event_q = self.event_listener.create_queue()
IOLoop.current().add_callback(self.fetch_event)
@gen.coroutine
def fetch_event(self):
while self.connected:
event = yield self.event_q.get()
if event:
self.write_message(event)
yield gen.moment
class NodeEventHandler(websocket.WebSocketHandler):
def initialize (self, conns):
self.conns = conns
self.cur_conn = None
self.node_key = None
self.connected = False
self.future = None
self.timeout_wait_token = None
def check_origin(self, origin):
return True
def open(self):
gen_log.info("websocket open")
self.connected = True
self.timeout_wait_token = IOLoop.current().call_later(5, self.close)
def on_close(self):
gen_log.info("websocket close")
if self.connected and self.cur_conn:
cur_waiters = self.cur_conn.event_waiters
if self.future in cur_waiters:
self.future.set_result(None)
cur_waiters.remove(self.future)
# cancel yield
pass
self.connected = False
def find_node_conn(self, key):
for sn, c in self.conns.iteritems():
if c.private_key == key and not c.killed:
return c
return None
def on_message(self, message):
if self.timeout_wait_token:
IOLoop.current().remove_timeout(self.timeout_wait_token)
self.timeout_wait_token = None
if self.cur_conn:
return
self.node_key = message
if len(message) != 32:
self.write_message({"error":"invalid node token"})
self.connected = False
self.close()
return
self.cur_conn = self.find_node_conn(message.strip())
if not self.cur_conn:
self.node_offline()
return
self.node_sn = self.cur_conn.sn
IOLoop.current().add_callback(self.fetch_event)
@gen.coroutine
def fetch_event(self):
while self.connected:
self.future = Future()
event = None
try:
self.cur_conn.event_waiters.append(self.future)
event = yield gen.with_timeout(timedelta(seconds=5), self.future, io_loop=ioloop.IOLoop.current())
except gen.TimeoutError:
if self.node_sn in self.conns and not self.conns[self.node_sn].killed:
self.cur_conn = self.conns[self.node_sn]
else:
self.cur_conn = None
if not self.cur_conn:
self.node_offline()
break
except Exception, e:
gen_log.error('Websocket error when fetch_event: %s' % str(e))
if event:
self.write_message(event)
yield gen.moment
def node_offline(self):
try:
self.write_message({"error":"node is offline"})
except:
pass
self.connected = False
self.close()