# -*- coding: UTF-8 -*- import subprocess import traffic_replay from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/v1/traffic', methods=["POST"]) def run_traffic_env(): try: print("Receive messages from api client.") json_data = request.get_json() type = json_data.get("type") if type == "curl": print("Execute curl operation.") command = json_data.get("command") p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8") output, error = p.communicate() cmd_result = output + error elif type == "trex": print("Execute trex operation.") pcap_name = json_data.get("pcap_name") + ".pcap" yaml_name = json_data.get("yaml_name") + ".yaml" m = json_data.get("m") d = json_data.get("d") clients_start_ip = json_data.get("clients_start_ip") clients_end_ip = json_data.get("clients_end_ip") servers_start_ip = json_data.get("servers_start_ip") servers_end_ip = json_data.get("servers_end_ip") path_dict = { "trex_workpath": "/opt/trex/v3.04", "traffic_playback_workpath": "/opt/traffic_replay" } tr = traffic_replay.TrafficReplay(path_dict) tr.trex_playback(yaml_name, pcap_name, m, d, clients_start_ip, clients_end_ip, servers_start_ip, servers_end_ip) cmd_result = "reset" response_result = {} response_result["code"] = 200 response_result["result"] = cmd_result response = jsonify(response_result) response.status_code = response_result["code"] return response except Exception as e: print(e) response_result = {} response_result["code"] = 418 response_result["result"] = "" response = jsonify(response_result) response.status_code = response_result["code"] return response if __name__ == '__main__': app.run(host = "0.0.0.0", port = 8900)