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