Rohan Patel | 6ec3508 | 2019-10-31 16:19:21 -0400 | [diff] [blame] | 1 | # 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 |
|
| 16 | import datetime
|
| 17 | import json
|
| 18 | import logging
|
| 19 | from logging import FileHandler
|
| 20 |
|
| 21 | import requests
|
| 22 | from flask import Flask, request, jsonify
|
| 23 |
|
| 24 | #redirect http to https
|
| 25 | app = Flask(__name__)
|
| 26 |
|
| 27 |
|
| 28 | # Prevents print statement every time an endpoint is triggered.
|
| 29 | logging.getLogger("werkzeug").setLevel(logging.WARNING)
|
| 30 |
|
| 31 | def unix_time_millis(dt):
|
| 32 | epoch = datetime.datetime.utcfromtimestamp(0)
|
| 33 | return (dt - epoch).total_seconds() * 1000.0
|
| 34 |
|
| 35 |
|
| 36 | @app.route("/otf/vth/oran/v1/health", methods=['GET'])
|
| 37 | def getHealth():
|
| 38 | return "UP"
|
| 39 |
|
| 40 | @app.route("/otf/vth/oran/ric/v1", methods =['POST'])
|
| 41 | def executeRicRequest():
|
| 42 |
|
| 43 | responseData = {
|
| 44 | 'vthResponse': {
|
| 45 | 'testDuration': '',
|
| 46 | 'dateTimeUTC': datetime.datetime.now(),
|
| 47 | 'abstractMessage': '',
|
| 48 | 'resultData': {}
|
| 49 | }
|
| 50 | }
|
| 51 |
|
| 52 | startTime = unix_time_millis(datetime.datetime.now())
|
| 53 |
|
| 54 | try:
|
| 55 | if not request.is_json:
|
| 56 | raise ValueError("request must be json")
|
| 57 |
|
| 58 | requestData = request.get_json()
|
| 59 |
|
| 60 | app.logger.info("Ric requestData:"+str(requestData))
|
| 61 |
|
| 62 | action = requestData['action'].lower()
|
| 63 | possibleActions = ['alive','ready','list', 'deploy','delete']
|
| 64 | responseData['vthResponse']['abstractMessage'] = 'Result from {}'.format(action)
|
| 65 |
|
| 66 | if action not in possibleActions:
|
| 67 | raise KeyError("invalid action")
|
| 68 | if (action == 'deploy' or action == 'delete') and 'name' not in requestData:
|
| 69 | raise KeyError("must include name")
|
| 70 |
|
| 71 | with open('config.json') as configFile:
|
| 72 | config = json.load(configFile)
|
| 73 |
|
| 74 | baseAddress= config['base_address']
|
| 75 |
|
| 76 | if action == 'alive' or action == 'ready':
|
| 77 | res = requests.get(baseAddress+config['actions_path'][action])
|
| 78 | responseData['vthResponse']['resultData']['statusCode'] = res.status_code
|
| 79 | responseData['vthResponse']['resultData']['resultOutput'] = res.text
|
| 80 | elif action == 'list':
|
| 81 | res = requests.get(baseAddress+config['actions_path'][action])
|
| 82 | responseData['vthResponse']['resultData']['statusCode'] = res.status_code
|
| 83 | responseData['vthResponse']['resultData']['resultOutput'] = res.json()
|
| 84 | elif action == 'deploy':
|
| 85 | payload = {'name': requestData['name']}
|
| 86 | res = requests.post(baseAddress+config['actions_path'][action], data=payload)
|
| 87 | responseData['vthResponse']['resultData']['statusCode'] = res.status_code
|
| 88 | responseData['vthResponse']['resultData']['resultOutput'] = res.json()
|
| 89 | elif action == 'delete':
|
| 90 | path= baseAddress+config['actions_path'][action]+"{}".format(requestData['name'])
|
| 91 | res = requests.delete(path)
|
| 92 | responseData['vthResponse']['resultData']['resultOutput'] = res.text
|
| 93 | responseData['vthResponse']['resultData']['statusCode'] = res.status_code
|
| 94 |
|
| 95 | except Exception as ex:
|
| 96 | endTime = unix_time_millis(datetime.datetime.now())
|
| 97 | totalTime = endTime - startTime
|
| 98 | responseData['vthResponse']['testDuration'] = totalTime
|
| 99 | responseData['vthResponse']['abstractMessage'] = str(ex)
|
| 100 | return jsonify(responseData)
|
| 101 |
|
| 102 | endTime = unix_time_millis(datetime.datetime.now())
|
| 103 | totalTime= endTime-startTime
|
| 104 |
|
| 105 | responseData['vthResponse']['testDuration'] = totalTime
|
| 106 |
|
| 107 | return jsonify(responseData),200
|
| 108 |
|
| 109 | if __name__ == '__main__':
|
| 110 | # logHandler = FileHandler('otf/logs/pingVTH.log', mode='a')
|
| 111 | logHandler = FileHandler('ricVTH.log', mode='a')
|
| 112 | logHandler.setLevel(logging.INFO)
|
| 113 | app.logger.setLevel(logging.INFO)
|
| 114 | app.logger.addHandler(logHandler)
|
| 115 | # context = ('opt/cert/otf.pem', 'opt/cert/privateKey.pem')
|
| 116 | # app.run(debug = False, host = '0.0.0.0', port = 5000, ssl_context = context)
|
| 117 | app.run(debug = False, host = '0.0.0.0', port = 5000)
|