[TIC-CORE] fix name of default recipe for export function
[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 traceback
20 import collections
21 from flask import Flask
22 from flask import Response
23 from flask.globals import request
24 from flask.helpers import url_for
25 import json
26 import os
27 import logging
28 from tic import command
29 from tic.utils import error
30
31 app = Flask(__name__)
32
33 @app.route('/')
34 def index():
35     return '''
36         <title>TIC-Core web server</title>
37         <h1> TIC-Core web server is working<h1>
38     '''
39
40 @app.route('/analysis', methods=['POST'])
41 def analysis():
42     try:
43         logger = logging.getLogger(__name__)
44         logger.info('%s - %s %s : data=%s' % (request.remote_addr, request.method, request.path, request.data))
45         target_info = json.loads(request.data)
46         view_data = command.analyze(target_info.get('recipes'))
47         #view_data = command.analyze(None)
48         resp = makeresponse(view_data, None)
49     except error.TICError as err:
50         logger.error(err)
51         resp = makeresponse(str(err), err)
52     except ValueError as ve:
53         logger.error(ve)
54         resp = makeresponse(str(ve), ve)
55     except Exception as ex:
56         logger.error(traceback.print_exc())
57         resp = makeresponse(str(ex), ex)
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(traceback.print_exc())
73         resp = makeresponse(str(ex), ex)
74     return resp
75
76 @app.route('/exports', methods=['POST'])
77 def exports():
78     try:
79         logger = logging.getLogger(__name__)
80         logger.info('%s - %s %s : data=%s' % (request.remote_addr, request.method, request.path, request.data))
81         exportInfo = json.loads(request.data)
82         export_type = request.args.get('format')
83         output = command.exports(export_type, exportInfo.get('recipes'), exportInfo.get('packages'), exportInfo.get('outdir'), exportInfo.get('filename'))
84         resp = makeresponse(output, None)
85     except error.TICError as err:
86         logger.error(err)
87         resp = makeresponse(str(err), err)
88     except ValueError as ve:
89         logger.error(ve)
90         resp = makeresponse(str(ve), ve)
91     except Exception as ex:
92         logger.error(traceback.print_exc())
93         resp = makeresponse(str(ex), ex)
94     return resp
95
96 def start(port_num=8082):
97     # cryptographic random generator
98     app.secret_key = os.urandom(24)
99     with app.test_request_context():
100         print(url_for('index'))
101         print(url_for('analysis'))
102         print(url_for('imports'))
103         print(url_for('exports'))
104     if isinstance(port_num, (str, unicode)):
105         port_num = int(port_num)
106     app.run(host='0.0.0.0', threaded=True, port=port_num)
107
108 def makeresponse(data, err):
109     status = 200
110     if err:
111         if isinstance(err, error.TICError) or isinstance(err, ValueError):
112             status = 400 # Bad Request
113         elif isinstance(err, Exception):
114             status = 500 # Internal Server Error
115             data='Internal Server Error'
116         res_body = json.dumps(ResultInfo('false', None, data)._asdict())
117     else:
118         res_body = json.dumps(ResultInfo('true', data, None)._asdict())
119     
120     resp = Response(status=status, 
121                     mimetype='application/json',
122                     response=res_body)
123     return resp
124
125 ResultInfoType = collections.namedtuple('ResultInfo', 'result, data, message')
126 def ResultInfo(result='false', data=None, message=None):
127     return ResultInfoType(result, data, message)
128
129 if __name__ == '__main__':
130     start(8082)