1"""
2* Copyright (C) 2022 Intel Corporation.
3*
4* SPDX-License-Identifier: BSD-3-Clause
5"""
6
7from flask import Flask
8from flask import send_file
9
10import numpy as np
11import pandas
12import random
13
14import matplotlib.pyplot as plt
15
16import posix_ipc as ipc
17import mmap
18
19app = Flask(__name__)
20
21#Runs when the user goes to our ip address
22@app.route('/')
23def histapp():
24
25	#Create and save the figure
26	create_hist()
27
28	#Send the histogram as a webpage to the user
29	return send_file("/root/hist.png", mimetype='image/png')
30
31#Creates the user histogram and saves to hist.png
32def create_hist():
33
34	#Go to the beginning of the shared memory region
35	shm.seek(0)
36
37	#Get the data
38	web_sem.acquire()
39	data = shm.readline();
40	web_sem.release()
41
42	#Transform the data into an array that matplotlib can understand
43	count, dataset = transform_data(data)
44
45	#Clear the figure and recreate from the new data
46	plt.clf()
47
48	#Setup the figure and save it
49	bins=np.arange(min(dataset),max(dataset)+2)-0.5
50	figure = plt.hist(dataset,bins,rwidth=0.5)
51
52	plt.title("ACRN Sample Application cyclictest display (unoptimized)")
53	plt.xlabel("Latency Value (microseconds)")
54	plt.ylabel("Count Percentage      " + f"{count:,}")
55	plt.savefig("/root/hist.png")
56
57	return figure
58
59def transform_data(data_string):
60
61	#Holds the transformed data
62	transformed_data_values = []
63
64	str_data = data_string.decode("utf-8")
65	str_data = str_data.replace('\n',"")
66
67	data_values = str_data.split()
68
69	#Holds the count of latencies that we have
70	total_count = data_values[0]
71
72	#Used for transforming the data values
73	data_percentages = data_values[1:]
74	if (len(data_percentages) % 2 != 0):
75		return transformed_data_values
76
77	#Transform the data into a list that can be fed to matplotlib
78	for i in range(0, int(len(data_percentages) / 2)):
79		transformed_data_values += ([int(data_percentages[i*2])] * int(data_percentages[i*2 + 1]))
80
81	return int(total_count), transformed_data_values
82
83if __name__ == '__main__':
84
85	#Set up shared memory between userapp and the webserver
86	shm_path = "/pyservershm"
87	shm_size = 1048576
88	shm_f =  ipc.SharedMemory(shm_path, 0, size=shm_size)
89	shm = mmap.mmap(shm_f.fd, shm_size)
90
91	#Set up the semaphore to maintaine synchronization
92	web_sem = ipc.Semaphore("/pyserversem", 0, 0o0774)
93
94	#Run the webserver
95	app.run(host="0.0.0.0", port=80, debug=False)
96