51383efc034425b3d02641c589287fc2190adb59
[archive/20170607/tools/tic-core.git] / tic / server / tic_server.py
1 #!/usr/bin/python
2 # Copyright (c) 2016 Samsung Electronics Co., Ltd
3 #
4 # Licensed under the Flora License, Version 1.1 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #     http://floralicense.org/license/
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16 # Contributors:
17 # - S-Core Co., Ltd
18
19 import collections
20 from flask import Flask
21 from flask import Response
22 from flask.globals import request
23 from flask.helpers import url_for
24 import json
25 import os
26 import logging
27 from tic import command
28 from tic.utils import error
29
30 app = Flask(__name__)
31
32 @app.route('/')
33 def index():
34     return '''
35         <title>TIC-Core web server</title>
36         <h1> TIC-Core web server is working<h1>
37     '''
38
39 @app.route('/analysis', methods=['POST'])
40 def analysis():
41     try:
42         logger = logging.getLogger(__name__)
43         logger.info('%s - %s %s : data=%s' % (request.remote_addr, request.method, request.path, request.data))
44         target_info = json.loads(request.data)
45         view_data = command.analyze(target_info.get('recipes'))
46         #view_data = command.analyze(None)
47         resp = makeresponse(view_data, None)
48     except error.TICError as err:
49         logger.error(err)
50         resp = makeresponse(str(err), err)
51     except ValueError as ve:
52         logger.error(ve)
53         resp = makeresponse(str(ve), ve)
54     except Exception as ex:
55         logger.error(ex)
56         resp = makeresponse(str(ex), ex)
57     
58     return resp
59
60 @app.route('/imports', methods=['POST'])
61 def imports():
62     try:
63         logger = logging.getLogger(__name__)
64         logger.info('%s - %s %s : data=%s' % (request.remote_addr, request.method, request.path, request.data))
65         repo_info = json.loads(request.data)
66         view_data = command.imports(repo_info.get('recipes'))
67         resp = makeresponse(view_data, None)
68     except error.TICError as err:
69         logger.error(err)
70         resp = makeresponse(str(err), err)
71     except Exception as ex:
72         logger.error(ex)
73         resp = makeresponse(str(ex), ex)
74     
75     return resp
76
77 @app.route('/exports', methods=['POST'])
78 def exports():
79     try:
80         logger = logging.getLogger(__name__)
81         logger.info('%s - %s %s : data=%s' % (request.remote_addr, request.method, request.path, request.data))
82         exportInfo = json.loads(request.data)
83         export_type = request.args.get('format')
84         output = command.exports(export_type, exportInfo.get('recipes'), exportInfo.get('packages'), exportInfo.get('outdir'), exportInfo.get('filename'))
85         resp = makeresponse(output, None)
86     except error.TICError as err:
87         logger.error(err)
88         resp = makeresponse(str(err), err)
89     except ValueError as ve:
90         logger.error(ve)
91         resp = makeresponse(str(ve), ve)
92     except Exception as ex:
93         logger.error(ex)
94         resp = makeresponse(str(ex), ex)
95     return resp
96
97
98 def start(port_num=8082):
99     # cryptographic random generator
100     app.secret_key = os.urandom(24) 
101     
102     with app.test_request_context():
103         print(url_for('index'))
104         print(url_for('analysis'))
105         print(url_for('imports'))
106         print(url_for('exports'))
107     if isinstance(port_num, (str, unicode)):
108         port_num = int(port_num)
109     app.run(host='0.0.0.0', threaded=True, port=port_num)
110
111 def makeresponse(data, err):
112     status = 200
113     if err:
114         if isinstance(err, error.TICError) or isinstance(err, ValueError):
115             status = 400 # Bad Request
116         elif isinstance(err, Exception):
117             status = 500 # Internal Server Error
118             data='Internal Server Error'
119         res_body = json.dumps(ResultInfo('false', None, data)._asdict())
120     else:
121         res_body = json.dumps(ResultInfo('true', data, None)._asdict())
122     
123     resp = Response(status=status, 
124                     mimetype='application/json',
125                     response=res_body)
126     return resp
127
128 ResultInfoType = collections.namedtuple('ResultInfo', 'result, data, message')
129 def ResultInfo(result='false', data=None, message=None):
130     return ResultInfoType(result, data, message)
131
132 if __name__ == '__main__':
133     start(8082)