blob: 4452ccdd22337f3503481c9879274367c259f778 [file] [log] [blame]
Zsolt Haraszti034db372016-10-03 22:26:41 -07001#!/usr/bin/env python
2#
3# Copyright 2016 the original author or authors.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18import os
19
20from klein import Klein
21from simplejson import dumps, load
22from structlog import get_logger
23from twisted.internet import reactor, endpoints
24from twisted.internet.defer import inlineCallbacks, returnValue
25from twisted.internet.tcp import Port
26from twisted.web.server import Site
27from twisted.web.static import File
28
29log = get_logger()
30
31'''
32## To be automated as part of the template
33from voltha.protos.voltha_pb2 import *
34from protobuf_to_dict import protobuf_to_dict, dict_to_protobuf
35
36def add_routes(app, grpc_client):
37
38 @app.route('/health', methods=['GET'])
39 def get_health(server, request):
40 log.debug('get-health-req', request=request, server=server)
41 req = NullMessage()
42 res = grpc_client.invoke(
43 HealthServiceStub, 'GetHealthStatus', req)
44 data = protobuf_to_dict(res, use_enum_labels=True)
45 request.setHeader('Content-Type', 'application/json')
46 log.debug('get-health-res', **data)
47 return dumps(data)
48
49 @app.route('/addresses', methods=['GET'])
50 def list_addresses(server, request):
51 log.debug('list-addresses-req', request=request, server=server)
52 req = NullMessage()
53 res = grpc_client.invoke(
54 ExampleServiceStub, 'ListAddresses', req)
55 data = protobuf_to_dict(res, use_enum_labels=True)
56 request.setHeader('Content-Type', 'application/json')
57 log.debug('list-addresses-res', **data)
58 return dumps(data)
59
60 @app.route('/addresses/<string:id>', methods=['GET'])
61 def get_address(server, request, id):
62 log.debug('get-address-req', request=request, server=server, id=id)
63 req = ID(id=id)
64 res = grpc_client.invoke(
65 ExampleServiceStub, 'GetAddress', req)
66 data = protobuf_to_dict(res, use_enum_labels=True)
67 request.setHeader('Content-Type', 'application/json')
68 log.debug('get-address-res', **data)
69 return dumps(data)
70
71 @app.route('/addresses/<string:id>', methods=['DELETE'])
72 def delete_address(server, request, id):
73 log.debug('delete-address-req', request=request, server=server, id=id)
74 req = ID(id=id)
75 res = grpc_client.invoke(
76 ExampleServiceStub, 'DeleteAddress', req)
77 data = protobuf_to_dict(res, use_enum_labels=True)
78 request.setHeader('Content-Type', 'application/json')
79 log.debug('delete-address-res', **data)
80 return dumps(data)
81
82 @app.route('/addresses', methods=['PATCH'])
83 def update_address(server, request):
84 log.debug('update-address-req', request=request, server=server)
85 data = load(request.content)
86 req = dict_to_protobuf(Address, data)
87 res = grpc_client.invoke(
88 ExampleServiceStub, 'UpdateAddress', req)
89 data = protobuf_to_dict(res, use_enum_labels=True)
90 request.setHeader('Content-Type', 'application/json')
91 log.debug('update-address-res', **data)
92 return dumps(data)
93
94## end
95'''
96
97class WebServer(object):
98
99 app = Klein()
100
101 def __init__(self, port, work_dir, grpc_client):
102 self.port = port
103 self.site = None
104 self.work_dir = work_dir
105 self.grpc_client = grpc_client
106
107 self.swagger_ui_root_dir = os.path.abspath(
108 os.path.join(os.path.dirname(__file__), '../swagger_ui'))
109
110 self.tcp_port = None
111
112 @inlineCallbacks
113 def run(self):
114 yield self._open_endpoint()
115 yield self._load_generated_routes()
116 returnValue(self)
117
118 def _load_generated_routes(self):
119 for fname in os.listdir(self.work_dir):
120 if fname.endswith('_gw.py'):
121 module_name = fname.replace('.py', '')
122 print 'module_name', module_name
123 m = __import__(module_name)
124 print dir(m)
125 assert hasattr(m, 'add_routes')
126 m.add_routes(self.app, self.grpc_client)
127
128 @inlineCallbacks
129 def _open_endpoint(self):
130 endpoint = endpoints.TCP4ServerEndpoint(reactor, self.port)
131 self.site = Site(self.app.resource())
132 self.tcp_port = yield endpoint.listen(self.site)
133 log.info('web-server-started', port=self.port)
134 self.endpoint = endpoint
135
136 @inlineCallbacks
137 def shutdown(self):
138 if self.tcp_porte is not None:
139 assert isinstance(self.tcp_port, Port)
140 yield self.tcp_port.socket.close()
141
142 # static swagger_ui website as landing page (for now)
143
144 @app.route('/', branch=True)
145 def static(self, request):
146 try:
147 log.debug(request=request)
148 return File(self.swagger_ui_root_dir)
149 except Exception, e:
150 log.exception('file-not-found', request=request)
151
152 # static swagger.json file to serve the schema
153
154 @app.route('/v1/swagger.json')
155 def swagger_json(self, request):
156 try:
157 return File(os.path.join(self.work_dir, 'swagger.json'))
158 except Exception, e:
159 log.exception('file-not-found', request=request)