added updated dockerfiles and ric workflow
[it/otf.git] / oran-ric-test-head / ric-test-head.py
1 #   Copyright (c) 2019 AT&T Intellectual Property.                             #\r
2 #                                                                              #\r
3 #   Licensed under the Apache License, Version 2.0 (the "License");            #\r
4 #   you may not use this file except in compliance with the License.           #\r
5 #   You may obtain a copy of the License at                                    #\r
6 #                                                                              #\r
7 #       http://www.apache.org/licenses/LICENSE-2.0                             #\r
8 #                                                                              #\r
9 #   Unless required by applicable law or agreed to in writing, software        #\r
10 #   distributed under the License is distributed on an "AS IS" BASIS,          #\r
11 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #\r
12 #   See the License for the specific language governing permissions and        #\r
13 #   limitations under the License.                                             #\r
14 ################################################################################\r
15 \r
16 import datetime\r
17 import json\r
18 import logging\r
19 from logging import FileHandler\r
20 import os\r
21 \r
22 import requests\r
23 from flask import Flask, request, jsonify\r
24 \r
25 #redirect http to https\r
26 app = Flask(__name__)\r
27 \r
28 \r
29 # Prevents print statement every time an endpoint is triggered.\r
30 logging.getLogger("werkzeug").setLevel(logging.WARNING)\r
31 \r
32 def unix_time_millis(dt):\r
33         epoch = datetime.datetime.utcfromtimestamp(0)\r
34         return (dt - epoch).total_seconds() * 1000.0\r
35 \r
36 \r
37 @app.route("/otf/vth/oran/v1/health", methods=['GET'])\r
38 def getHealth():\r
39         return "UP"\r
40 \r
41 @app.route("/otf/vth/oran/ric/v1", methods =['POST'])\r
42 def executeRicRequest():\r
43 \r
44         responseData = {\r
45                 'vthResponse': {\r
46                         'testDuration': '',\r
47                         'dateTimeUTC': datetime.datetime.now(),\r
48                         'abstractMessage': '',\r
49                         'resultData': {}\r
50                 }\r
51         }\r
52 \r
53         startTime = unix_time_millis(datetime.datetime.now())\r
54 \r
55         try:\r
56                 if not request.is_json:\r
57                         raise ValueError("request must be json")\r
58 \r
59                 requestData = request.get_json()\r
60 \r
61                 app.logger.info("Ric requestData:"+str(requestData))\r
62 \r
63                 action = requestData['action'].lower()\r
64                 possibleActions = ['alive','ready','list', 'deploy','delete']\r
65                 responseData['vthResponse']['abstractMessage'] = 'Result from {}'.format(action)\r
66 \r
67                 if action not in possibleActions:\r
68                         raise KeyError("invalid action")\r
69                 if (action == 'deploy' or action == 'delete') and 'name' not in requestData:\r
70                         raise KeyError("must include name")\r
71 \r
72                 with open('config.json') as configFile:\r
73                         config = json.load(configFile)\r
74 \r
75                 baseAddress=  config['base_address']\r
76 \r
77                 if action == 'alive' or action == 'ready':\r
78                         res = requests.get(baseAddress+config['actions_path'][action])\r
79                         responseData['vthResponse']['resultData']['statusCode'] = res.status_code\r
80                         responseData['vthResponse']['resultData']['resultOutput'] = res.text\r
81                 elif action == 'list':\r
82                         res = requests.get(baseAddress+config['actions_path'][action])\r
83                         responseData['vthResponse']['resultData']['statusCode'] = res.status_code\r
84                         responseData['vthResponse']['resultData']['resultOutput'] = res.json()\r
85                 elif action == 'deploy':\r
86                         payload = json.dumps({'name': requestData['name']})\r
87                         res = requests.post(baseAddress+config['actions_path'][action], data=payload)\r
88                         responseData['vthResponse']['resultData']['statusCode'] = res.status_code\r
89                         responseData['vthResponse']['resultData']['resultOutput'] = res.json()\r
90                 elif action == 'delete':\r
91                         path= baseAddress+config['actions_path'][action]+"{}".format(requestData['name'])\r
92                         res = requests.delete(path)\r
93                         responseData['vthResponse']['resultData']['resultOutput'] = res.text\r
94                         responseData['vthResponse']['resultData']['statusCode'] = res.status_code\r
95 \r
96         except Exception as ex:\r
97                 endTime = unix_time_millis(datetime.datetime.now())\r
98                 totalTime = endTime - startTime\r
99                 responseData['vthResponse']['testDuration'] = totalTime\r
100                 responseData['vthResponse']['abstractMessage'] = str(ex)\r
101                 return jsonify(responseData)\r
102 \r
103         endTime = unix_time_millis(datetime.datetime.now())\r
104         totalTime= endTime-startTime\r
105 \r
106         responseData['vthResponse']['testDuration'] = totalTime\r
107 \r
108         return jsonify(responseData),200\r
109 \r
110 if __name__ == '__main__':\r
111         # logHandler = FileHandler('otf/logs/pingVTH.log', mode='a')\r
112         logHandler = FileHandler('ricVTH.log', mode='a')\r
113         logHandler.setLevel(logging.INFO)\r
114         app.logger.setLevel(logging.INFO)\r
115         app.logger.addHandler(logHandler)\r
116         # context = ('opt/cert/otf.pem', 'opt/cert/privateKey.pem')\r
117         # app.run(debug = False, host = '0.0.0.0', port = 5000, ssl_context = context)\r
118         app.run(debug = False, host = '0.0.0.0', port = 5000)\r