forked from open-lambda/open-lambda
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·73 lines (63 loc) · 2.13 KB
/
Copy pathserver.py
File metadata and controls
executable file
·73 lines (63 loc) · 2.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
#!/usr/bin/python
import traceback, json, socket, struct, os, sys
import rethinkdb
import flask
sys.path.append('/handler')
import lambda_func # assume submitted .py file is /handler/lambda_func
app = flask.Flask(__name__)
PROCESSES_DEFAULT = 10
PORT = 8080
initialized = False
config = None
db_conn = None
# run once per process
def init():
global initialized, config, db_conn
if initialized:
return
sys.stdout = sys.stderr # flask supresses stdout :(
with open('config.json') as f:
config = json.loads(f.read())
if config.get('db', None) == 'rethinkdb':
addr = os.environ.get('RETHINKDB_PORT_28015_TCP', None)
if addr != None:
host, port = addr.split('//')[-1].split(':')
else:
host, port = get_default_gateway_linux(), '28015'
try:
db_conn = rethinkdb.connect(host, int(port))
except:
print "connection to rethinkdb failed"
initialized = True
# source: http://stackoverflow.com/a/6556951
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
# catch everything
@app.route('/', defaults={'path': ''}, methods=['POST'])
@app.route('/<path:path>', methods=['POST'])
def flask_post(path):
try:
init()
flask.request.get_data()
data = flask.request.data
try :
event = json.loads(data)
except:
return ('bad POST data: "%s"'%str(data), 400)
return json.dumps(lambda_func.handler(db_conn, event))
except Exception:
return (traceback.format_exc(), 500) # internal error
def main():
with open('config.json') as f:
config = json.loads(f.read())
procs = config.get('processes', PROCESSES_DEFAULT)
print 'Starting %d flask processes' % procs
app.run(processes=procs, host='0.0.0.0', port=PORT)
if __name__ == '__main__':
main()