-
Notifications
You must be signed in to change notification settings - Fork 1
/
diff.py
3797 lines (3058 loc) · 171 KB
/
diff.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from pprint import pprint
import time
from datetime import datetime
import logging
import os, shutil
import multiprocessing #Processing on multiple cores
from functools import partial #For passing extra arguments to pool.map
import pandas as pd
import numpy as np
import pymysql
import configparser, itertools
from flask import Flask, render_template, request, redirect, send_file, url_for, session, send_from_directory
from collections import OrderedDict
import csv
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from packaging.version import LegacyVersion
import json
# DB_HOST_IP = '1.21.1.65'
# DB_HOST_IP = '10.110.169.149'
DB_HOST_IP = 'localhost'
DB_USER = 'root'
DB_PASSWD = 'root'
DB_NAME = 'benchtooldb'
DB_PORT = 3306
# The number of cores to be used for multiprocessing
num_processes = 40
# Change the result_type according to result_type_map
# Mapping for Result type field
result_type_map = {0: "single thread", 1: 'single core',
2: 'single socket', 3: 'dual socket',
4: 'client scaling', 5: '1/8th socket',
6: '1/4th socket', 7: '1/2 socket',
8: '2 cores', 9: 'perf',
10: 'I/O utilization', 11: 'socmon',
12: 'OMP_MPI scaling', 20: 'Projection'}
month_name_map = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10: 'Oct', 11:'Nov', 12:'Dec'}
# Uncomment this line for toggling debugging messages on the console
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
logging.debug("Flask server restarted")
# Just a random secret key. Created by md5 hashing the string 'secretactividad'
app.secret_key = "05ec4a13767ac57407c4000e55bdc32c"
pd.set_option('display.max_rows', 500)
# RETURNS the Table name for the given 'index' from the dictionary of lists
# example : from 'origin_param_list' -> return 'origin'
@app.context_processor
def table_name():
def _table_name(list_of_keys, index):
tablename = list(list_of_keys)[index]
if tablename == "ram_details_param_list":
return "RAM_details"
return tablename[0: tablename.find("_param_list")].capitalize()
return dict(table_name=_table_name)
# RESERVED FOR LATER (Not important as of now. DO it if time permits)
# @app.template_filter('readable_timestamp')
# def readable_timestamp(timestamp):
# #type of timestamp is <class 'pandas._libs.tslibs.timestamps.Timestamp'>
# dt = timestamp.to_pydatetime();
# return dt.strftime("%d %B, %Y %I:%M:%S %p")
# Takes the originID, returns the testname
def get_test_name(originID):
db = pymysql.connect(host=DB_HOST_IP, user=DB_USER,
passwd=DB_PASSWD, db=DB_NAME, port=DB_PORT)
TEST_NAME_QUERY = """SELECT t.testname FROM testdescriptor as t
INNER JOIN origin o on o.testdescriptor_testdescriptorID=t.testdescriptorID
WHERE o.originID=""" + originID + ";"
test_name_dataframe = pd.read_sql(TEST_NAME_QUERY, db)
test_name = test_name_dataframe['testname'][0]
# close the database connection
try:
db.close()
except:
pass
return test_name
#Template filter for 'unique_list'
@app.template_filter('unique_list')
def unique_list_filter(input_list):
return unique_list(input_list)
# Takes input as a list containg duplicate elements.
# Returns a sorted list having unique elements
def unique_list(input_list, reverse=False):
def str_is_int(s):
try:
int(s)
return True
except:
return False
def str_is_float(s):
try:
# This fails if string isn't float
float(s) == int(s)
return True
except:
return False
# OrderedDict creates unique keys. It also preserves the order of insertion
lst = list(OrderedDict.fromkeys(input_list))
logging.debug(" = {}".format(lst))
if all(str_is_int(x) for x in lst):
logging.debug("WAS INSTANCE OF INT MAN")
lst = [int(x) for x in lst]
elif all(str_is_float(x) for x in lst):
logging.debug("WAS INSTANCE OF FLOAT MAN")
lst = [float(x) for x in lst]
else:
logging.debug("WAS INSTANCE OF NONE MAN")
# Return all values as STR
if reverse:
return list(reversed(list(map(lambda x: str(x), sorted(lst)))))
else:
return list(map(lambda x: str(x), sorted(lst)))
@app.template_filter('no_of_rows')
def no_of_rows(dictionary):
if dictionary != {}:
# this is a dictionary of lists
# return length of the first list in the dictionary
# fastest way
return len(dictionary[next(iter(dictionary))])
else:
return 0
def read_all_parameter_lists(parameter_lists, test_name):
# read metadata from metadata.ini file
env_metadata_file_path = './config/metadata.ini'
env_metadata_parser = configparser.ConfigParser()
env_metadata_parser.read(env_metadata_file_path)
# Read metadata for results in wiki_description.ini file
results_metadata_file_path = './config/wiki_description.ini'
results_metadata_parser = configparser.ConfigParser()
results_metadata_parser.read(results_metadata_file_path)
# Fill all parameter Lists in the dictionary
for param_list_name in parameter_lists:
if param_list_name == 'results_param_list':
parameter_lists[param_list_name] = results_metadata_parser.get(test_name, 'description') \
.replace('\"', '').replace(' ', '').split(',')
parameter_lists[param_list_name].extend(['number', 'resultype', 'unit', 'qualifier'])
elif param_list_name == 'qualifier':
parameter_lists[param_list_name] = results_metadata_parser.get(test_name, 'fields') \
.replace('\"','').lower().split(',')
elif param_list_name == 'min_or_max':
parameter_lists[param_list_name] = results_metadata_parser.get(test_name, 'higher_is_better') \
.replace('\"','').split(',')
else:
# extracts 'example' from 'example_param_list'
env_param_name = param_list_name[0:param_list_name.find("_param_list")]
parameter_lists[param_list_name] = env_metadata_parser.get(env_param_name, 'db_variables') \
.replace(' ', '').split(',')
return parameter_lists
def read_all_csv_files(compare_lists, parameter_lists, originID_compare_list):
db = pymysql.connect(host=DB_HOST_IP, user=DB_USER,
passwd=DB_PASSWD, db=DB_NAME, port=DB_PORT)
JENKINS_QUERY = """SELECT J.jobname, J.runID FROM origin O
INNER JOIN jenkins J ON O.jenkins_jenkinsID=J.jenkinsID
AND O.originID in """ + str(originID_compare_list).replace('[', '(').replace(']', ')') + ";"
jenkins_details = pd.read_sql(JENKINS_QUERY, db)
jobname_list = jenkins_details['jobname'].to_list()
runID_list = jenkins_details['runID'].to_list()
# The path on which file is to be read
file_path = "/mnt/nas/dbresults/"
# Fill all lists in the dictionary
for i in range(len(originID_compare_list)):
for j in range(len(compare_lists)):
param_values_dictionary = dict()
list_of_keys = list(compare_lists.keys())
table_name = list_of_keys[j][0:list_of_keys[j].find("_list")]
# Check if the file exists
if (
os.path.exists(file_path + str(jobname_list[i]) + '/' + str(runID_list[i]) + '/' + table_name + '.csv')):
pass
else:
table_name = list_of_keys[j][0:list_of_keys[j].find("_details_list")]
if(os.path.exists(file_path + str(jobname_list[i]) + '/' + str(runID_list[i]) + '/' + table_name + '.csv')):
pass
else:
continue
with open(file_path + str(jobname_list[i]) + '/' + str(runID_list[i]) + '/' + table_name + '.csv',
newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
try:
for k in range(0, len(parameter_lists[table_name + '_param_list'])):
param_values_dictionary[parameter_lists[table_name + '_param_list'][k]] = row[k]
break
except IndexError:
#If Index error occurs, pass. Let the value remain empty
pass
except:
for k in range(0, len(parameter_lists[table_name + '_details_param_list'])):
param_values_dictionary[parameter_lists[table_name + '_details_param_list'][k]] = row[k]
break
if (table_name + "_list" in compare_lists):
compare_lists[table_name + "_list"].append(param_values_dictionary)
else:
compare_lists[table_name + "_details_list"].append(param_values_dictionary)
# close the database connection
try:
db.close()
except:
pass
return compare_lists
# Returns INPUT_FILTER_CONDITION from 'test_name' and 'input_filters_list'
def get_input_filter_condition(test_name, input_filters_list, wiki_description_file='./config/wiki_description.ini'):
INPUT_FILTER_CONDITION = ""
results_metadata_file_path = wiki_description_file
results_metadata_parser = configparser.ConfigParser()
results_metadata_parser.read(results_metadata_file_path)
# For the input filters
input_parameters = results_metadata_parser.get(test_name, 'description') \
.replace('\"', '').replace(' ', '').split(',')
try:
for index, input_filter in enumerate(input_filters_list):
if(input_filter != "None"):
if(input_filter.isnumeric()):
INPUT_FILTER_CONDITION += " and SUBSTRING_INDEX(SUBSTRING_INDEX(s.description,','," + str(index+1) +"),',',-1) = \'" + input_filter + "\'"
else:
INPUT_FILTER_CONDITION += " and SUBSTRING_INDEX(SUBSTRING_INDEX(s.description,','," + str(index+1) +"),',',-1) LIKE \'%" + input_filter + "%\'"
except Exception as error_message:
logging.debug("ERRORS::::::: {}".format(error_message))
pass
return INPUT_FILTER_CONDITION
# Request route for favicon
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'images/favicon.ico', mimetype='image/vnd.microsoft.icon')
# Get all-tests data
def get_all_tests_data(wiki_description_file='./config/wiki_description.ini'):
parser = configparser.ConfigParser()
parser.read(wiki_description_file)
# Reference for best_of_all_graph
sku_file_path = './config/sku_definition.ini'
sku_parser = configparser.ConfigParser()
sku_parser.read(sku_file_path)
reference_list = sku_parser.sections();
logging.debug("SECTIONS")
logging.debug("{}".format(reference_list))
filter_labels_dict = {}
filter_labels_list = []
hpc_benchmarks_list = []
cloud_benchmarks_list = []
for section in parser.sections():
filter_labels_list.extend(
[label for label in parser.get(section, 'label').replace('\"', '').replace(' ', '').lower().split(',')
if label != '' and label not in filter_labels_list])
filter_labels_dict[section] = ','.join(
[label for label in parser.get(section, 'label').replace('\"', '').replace(' ', '').lower().split(',')])
type_of_benchmark = parser.get(section, 'model').strip()
if type_of_benchmark == '\"hpc\"':
hpc_benchmarks_list.append(section)
else:
cloud_benchmarks_list.append(section)
hpc_benchmarks_list = sorted(hpc_benchmarks_list, key=str.lower)
cloud_benchmarks_list = sorted(cloud_benchmarks_list, key=str.lower)
filter_labels_list = sorted(filter_labels_list, key=str.lower)
# If wiki_description_file = best_of_all_graph.ini, then benchmark list is actually sections list
# Give its value to sections_list and update benchmarks_list
hpc_sections_list = []
cloud_sections_list = []
if wiki_description_file == './config/best_of_all_graph.ini':
hpc_sections_list, cloud_sections_list = hpc_benchmarks_list, cloud_benchmarks_list
hpc_benchmarks_list = [parser.get(section, 'testname').strip() for section in hpc_sections_list]
cloud_benchmarks_list = [parser.get(section, 'testname').strip() for section in cloud_sections_list]
# Unique entries only
hpc_benchmarks_list = sorted(list(set(hpc_benchmarks_list)), key=str.lower)
cloud_benchmarks_list = sorted(list(set(cloud_benchmarks_list)), key=str.lower)
context = {
'hpc_benchmarks_list': hpc_benchmarks_list,
'cloud_benchmarks_list': cloud_benchmarks_list,
'filter_labels_list': filter_labels_list,
'filter_labels_dict': filter_labels_dict,
'reference_list': reference_list,
'hpc_sections_list' : hpc_sections_list,
'cloud_sections_list' : cloud_sections_list,
}
return context
# Error 404 custom page not found
@app.errorhandler(404)
def page_not_found(e):
# For 'Go To Benchmark' Dropdown
all_tests_data = get_all_tests_data()
# note that we set the 404 status explicitly
return render_template('404.html', all_tests_data=all_tests_data), 404
# ALL TESTS PAGE
@app.route('/')
def home_page():
context = get_all_tests_data()
# For result type filter
result_type_list = [3, 2, 7, 6, 5, 8, 1, 0]
# Convert to result_type string according to result_type_map
result_type_list = [result_type_map[x] for x in result_type_list]
context['result_type_list'] = result_type_list
return render_template('all-tests.html', context=context)
@app.route('/about')
def about_page():
# For 'Go To Benchmark' Dropdown
all_tests_data = get_all_tests_data()
return render_template('about.html', context = {}, all_tests_data=all_tests_data)
# Get data for All runs of the test 'testname' from database
def get_all_runs_data(testname, secret=False):
# Read metadata for results in wiki_description.ini file
results_metadata_file_path = './config/wiki_description.ini'
results_metadata_parser = configparser.ConfigParser()
results_metadata_parser.read(results_metadata_file_path)
qualifier_list = results_metadata_parser.get(testname, 'fields').replace('\"', '').split(',')
min_or_max_list = results_metadata_parser.get(testname, 'higher_is_better') \
.replace('\"', '').replace(' ', '').split(',')
logging.debug("########PRINTING QUALIFIER LIST AND MIN OR MAX LIST#########")
logging.debug("{}".format(qualifier_list))
logging.debug("{}".format(min_or_max_list))
if secret == True:
RESULTS_VALIDITY_CONDITION = " "
else:
RESULTS_VALIDITY_CONDITION = " AND r.isvalid = 1 "
if min_or_max_list[0] == '0':
ALL_RUNS_QUERY = "SELECT DISTINCT o.originID, o.testdate, o.hostname, MIN(r.number) as \'Best" +\
qualifier_list[0].replace(" ",'') + """\', o.notes, r.isvalid from result r INNER JOIN display disp
ON r.display_displayID = disp.displayID
INNER JOIN origin o ON o.originID = r.origin_originID
INNER JOIN testdescriptor t ON t.testdescriptorID = o.testdescriptor_testdescriptorID
where t.testname = \'""" + testname + """\'
AND disp.qualifier LIKE \'%""" + qualifier_list[0] + "%\'" + \
RESULTS_VALIDITY_CONDITION + """ GROUP BY o.originID, o.testdate, o.hostname, o.notes, r.isvalid
ORDER BY o.originID DESC"""
else:
ALL_RUNS_QUERY = "SELECT DISTINCT o.originID, o.testdate, o.hostname, MAX(r.number) as \'Best" +\
qualifier_list[0].replace(" ",'') + """\', o.notes, r.isvalid from result r INNER JOIN display disp
ON r.display_displayID = disp.displayID
INNER JOIN origin o ON o.originID = r.origin_originID
INNER JOIN testdescriptor t ON t.testdescriptorID = o.testdescriptor_testdescriptorID
where t.testname = \'""" + testname + """\'
AND disp.qualifier LIKE \'%""" + qualifier_list[0] + "%\'" + \
RESULTS_VALIDITY_CONDITION + """ GROUP BY o.originID, o.testdate, o.hostname, o.notes, r.isvalid
ORDER BY o.originID DESC"""
db = pymysql.connect(host=DB_HOST_IP, user=DB_USER,
passwd=DB_PASSWD, db=DB_NAME, port=DB_PORT)
dataframe = pd.read_sql(ALL_RUNS_QUERY, db)
rows, columns = dataframe.shape # returns a tuple (rows,columns)
# For secret page, return only table data. The secret function will redirect to secret page
if secret == True:
secret_context = {
'testname': testname,
'data': dataframe.to_dict(orient='list'),
'no_of_rows': rows,
'no_of_columns': columns,
}
# close the database connection
try:
db.close()
except:
pass
return secret_context
# Else render all-runs.html
else:
del dataframe['isvalid']
rows, columns = dataframe.shape # returns a tuple (rows,columns)
# Dropdown for input file
input_parameters = results_metadata_parser.get(testname, 'description') \
.replace('\"', '').replace(' ', '').split(',')
INPUT_FILE_QUERY = """SELECT DISTINCT s.description, r.isvalid FROM origin o INNER JOIN testdescriptor t
ON t.testdescriptorID=o.testdescriptor_testdescriptorID INNER JOIN result r
ON o.originID = r.origin_originID INNER JOIN subtest s
ON r.subtest_subtestID = s.subtestID WHERE t.testname = \'""" + testname + "\';" #RRG
logging.debug(INPUT_FILE_QUERY)
try:
input_details_df = pd.read_sql(INPUT_FILE_QUERY, db)
except:
pass
finally:
db.close()
# Filter results which are valid
input_details_df = input_details_df[input_details_df['isvalid'] == 1].reset_index(drop=True)
del input_details_df['isvalid']
logging.debug("{}".format(input_parameters))
logging.debug("{}".format(input_details_df))
# Function which splits the description string into various parameters
# according to 'description' field of the '.ini' file
def split_description(index, description):
try:
return description.split(',')[index]
except Exception as error_message:
logging.debug("{}".format(error_message))
return np.nan
# Split the 'description' column into multiple columns
for index, param in enumerate(input_parameters):
input_details_df[param] = input_details_df['description'].apply(lambda x: split_description(index, x))
# Delete the 'description' column
del input_details_df['description']
# Drop all the rows which have NaN as an element
input_details_df.dropna(inplace=True)
# Get default_inputs from wiki_description.ini
default_input_filters_list = results_metadata_parser.get(testname, 'default_input') \
.replace('\"', '').split(',')
# Read from test_summary.ini file
test_summary_file_path = "./config/test_summary.ini"
test_summary_parser = configparser.ConfigParser()
test_summary_parser.read(test_summary_file_path)
test_summary = {}
test_summary['summary'] = test_summary_parser.get(testname, 'summary').replace('\"','')
test_summary['source_code_link'] = test_summary_parser.get(testname, 'source_code_link')
test_summary['type_of_workload'] = test_summary_parser.get(testname, 'type_of_workload')
test_summary['default_input'] = test_summary_parser.get(testname, 'default_input')
test_summary['latest_version'] = test_summary_parser.get(testname, 'latest_version')
# For result type filter
result_type_list = [3, 2, 7, 6, 5, 8, 1, 0]
# Convert to result_type string according to result_type_map
result_type_list = [result_type_map[x] for x in result_type_list]
context = {
'testname': testname,
'data': dataframe.to_dict(orient='list'),
'no_of_rows': rows,
'no_of_columns': columns,
'qualifier_list': qualifier_list,
'input_details': input_details_df.to_dict(orient='list'),
'default_input_filters': default_input_filters_list,
'test_summary' : test_summary,
'result_type_list' : result_type_list,
}
# close the database connection
try:
db.close()
except:
pass
return context
# Show all runs of a test 'testname'
@app.route('/allruns/<testname>', methods=['GET'])
def all_runs_page(testname):
# Reference for best_of_all_graph
sku_file_path = './config/sku_definition.ini'
sku_parser = configparser.ConfigParser()
sku_parser.read(sku_file_path)
# Reference dropdown for timeline graphs
all_skus_list = sku_parser.sections()
try:
context = get_all_runs_data(testname)
context['all_skus_list'] = all_skus_list
error = None
except Exception as error_message:
context = None
error = error_message
# For 'Go To Benchmark' Dropdown
all_tests_data = get_all_tests_data()
return render_template('all-runs.html', error=error, context=context, all_tests_data=all_tests_data)
# Page for marking a test 'originID' invalid
@app.route('/allruns/secret/<testname>', methods=['GET', 'POST'])
def all_runs_secret_page(testname):
if request.method == 'GET':
# For 'Go To Benchmark' Dropdown
all_tests_data = get_all_tests_data()
return render_template('secret-all-runs.html', testname={'name':testname}, context={}, all_tests_data=all_tests_data)
else:
success = {}
error = {}
keyerror = {}
logging.debug("#######POSTED###########")
logging.debug("{}".format(request.args))
# Get doesn't throw error.
# If key is not present it sets to default ('None' most of the times)
success = session.get('success')
error = session.get('error')
keyerror = session.get('keyerror')
logging.debug('success = {}'.format(success))
logging.debug('error = {}'.format(error))
logging.debug('keyerror = {}'.format(keyerror))
logging.debug("#######SESSION BEFORE ####")
logging.debug(' = {}'.format(session))
logging.debug("########SESSION AFTER $$$$")
# Clear the contents of the session (cookies)
session.clear()
logging.debug(' = {}'.format(session))
context = context = get_all_runs_data(testname, secret=True)
# For 'Go To Benchmark' Dropdown
all_tests_data = get_all_tests_data()
return render_template('secret-all-runs.html', success=success, error=error, keyerror=keyerror, context=context, all_tests_data=all_tests_data)
@app.route('/mark-origin-id-invalid', methods=['POST'])
def mark_originID_invalid():
logging.debug("\n\n\n#REQUEST#########")
logging.debug(" = {}".format(request.form))
data = json.loads(request.form.get('data'))
logging.debug(" = {}".format(data))
originIDs = data.get('originIDs')
logging.debug("Printing selected originIDs = '{}' {}".format(originIDs, type(originIDs)))
testname = data.get('testname')
valid = data.get('valid')
secret_key = data.get('secretKey')
success = {}
error = {}
keyerror = {}
if secret_key == 'secret_123':
logging.debug("CAUTION!!! MArking result invalid")
db = pymysql.connect(host=DB_HOST_IP, user=DB_USER,
passwd=DB_PASSWD, db=DB_NAME, port=DB_PORT)
cursor = db.cursor()
if not valid:
success['message'] = "The originIDs [" + originIDs +"] were marked invalid successfully"
INVALID_ORIGINID_QUERY = "UPDATE result r SET r.isvalid=0 where r.origin_originID in (" + originIDs + ");"
else:
success['message'] = "The originIDs [" + originIDs +"] were marked valid successfully"
INVALID_ORIGINID_QUERY = "UPDATE result r SET r.isvalid=1 where r.origin_originID in (" + originIDs + ");"
logging.debug(INVALID_ORIGINID_QUERY)
cursor.execute(INVALID_ORIGINID_QUERY)
cursor.close()
db.commit()
db.close()
else:
keyerror['message'] = "BOOM! Wrong Password. This incident will be reported."
session['success'] = success
session['error'] = error
session['keyerror'] = keyerror
# code = 307 for keeping the original request type ('POST')
return redirect(url_for('all_runs_secret_page', testname=testname), code=307)
@app.route('/edit-notes', methods=['POST'])
def edit_notes():
data = json.loads(request.form.get('data'))
logging.debug(" = {}".format(data))
originID = data.get('originID')
testname = data.get('testname')
new_note = data.get('newNote')
logging.debug("OriginID = {}\ntestname = {}\nNew Note = {}".format(originID, testname, new_note))
success = {}
error = {}
keyerror = {}
db = pymysql.connect(host=DB_HOST_IP, user=DB_USER,
passwd=DB_PASSWD, db=DB_NAME, port=DB_PORT)
cursor = db.cursor()
success['message'] = "The 'notes' of originID '" + str(originID) + "' was changed to '" + new_note + "' successfully"
EDIT_NOTES_QUERY = "UPDATE origin SET notes = \'" + new_note + "\' where originID = " + str(originID) + ";"
logging.debug(EDIT_NOTES_QUERY)
cursor.execute(EDIT_NOTES_QUERY)
cursor.close()
db.commit()
db.close()
session['success'] = success
session['error'] = error
session['keyerror'] = keyerror
# code = 307 for keeping the original request type ('POST')
return redirect(url_for('all_runs_secret_page', testname=testname), code=307)
# Get details for test with originID = 'originID' from database
def get_test_details_data(originID, secret=False):
db = pymysql.connect(host=DB_HOST_IP, user=DB_USER,
passwd=DB_PASSWD, db=DB_NAME, port=DB_PORT)
# Just get the TEST name
test_name = get_test_name(originID)
if secret == True:
RESULTS_VALIDITY_CONDITION = " "
else:
RESULTS_VALIDITY_CONDITION = " AND R.isvalid = 1 "
# Read the subtests description from the wiki_description
config_file = "./config/wiki_description.ini"
config_options = configparser.ConfigParser()
config_options.read(config_file)
if config_options.has_section(test_name):
description_string = config_options[test_name]['description'].replace(
'\"', '')
else:
description_string = 'Description'
logging.debug("BEFORE GETTING DATAFRAME")
# RESULTS TABLE
RESULTS_QUERY = """SELECT R.resultID, S.description, R.number, S.resultype, disp.unit, disp.qualifier, R.isvalid FROM result R INNER JOIN subtest S ON S.subtestID=R.subtest_subtestID INNER JOIN display disp ON disp.displayID=R.display_displayID INNER JOIN origin O ON O.originID=R.origin_originID WHERE O.originID=""" + originID + \
RESULTS_VALIDITY_CONDITION + ";"
results_dataframe = pd.read_sql(RESULTS_QUERY, db)
# Map the resultype to the result type name Example 2-> Single Socket
index = list(results_dataframe.columns).index('number')
results_dataframe.insert(index, 'Result Type', [result_type_map.get(result_type, "Unkown resultype") for result_type in results_dataframe['resultype']])
# Drop the resultype column as it is no longer needed
del results_dataframe['resultype']
logging.debug("GOT RESULTS DATAFRAME")
# logging.debug("{}".format(results_dataframe))
for col in reversed(description_string.split(',')):
results_dataframe.insert(1, col, 'default value')
# Function which splits the description string into various parameters
# according to 'description' field of the '.ini' file
def split_description(index, description):
try:
return description.split(',')[index]
except Exception as error_message:
logging.debug("Error = {}".format(error_message))
return np.nan
# For all the rows in the dataframe, set the description_list values
description_list = description_string.split(',')
for j in range(len(description_list)):
results_dataframe[description_list[j]] = results_dataframe['description'].apply(lambda x: split_description(j, x))
# Drop the 'description' column as we have now split it into various columns according to description_string
del results_dataframe['description']
results_dataframe.dropna(inplace=True)
# For secret page, return only table data. The secret function will redirect to secret page
if secret == True:
secret_context = {
'testname': test_name,
'description_list': description_string.split(','),
'results': results_dataframe.to_dict(orient='list'),
'originID': originID,
}
# close the database connection
try:
db.close()
except:
pass
return secret_context
# Else render test-details.html
else:
logging.debug("SECRET WAS FALSE")
del results_dataframe['resultID']
del results_dataframe['isvalid']
# Get some System details
SYSTEM_DETAILS_QUERY = """SELECT DISTINCT O.hostname, O.testdate, O.notes, O.originID as 'Environment Details', S.resultype
FROM result R INNER JOIN subtest S ON S.subtestID=R.subtest_subtestID
INNER JOIN origin O ON O.originID=R.origin_originID
WHERE O.originID=""" + originID + ";"
system_details_dataframe = pd.read_sql(SYSTEM_DETAILS_QUERY, db)
# Update the Result type (E.g. 0->single thread)
try:
system_details_dataframe.update(pd.DataFrame(
{'resultype': [result_type_map[system_details_dataframe['resultype'][0]]]}))
# Get result_type and remove it from system_details_dataframe (pop)
result_type = system_details_dataframe.pop('resultype')[0]
except:
result_type = None
logging.warning('Couldn\'t get Result Type')
logging.debug(" = {}".format(result_type))
# Get Num_CPUs list if result_type is 'perf'
#if result_type == "perf":
#logging.debug('NUM CPUS START')
#try:
# Calls unique_list function on list of unique 'Num_CPUs'
#num_cpus_list = unique_list((results_dataframe['Num_CPUs']), reverse=True)
# raw_dir = '/mnt/nas/dbresults/' + jenkins_details['jobname'][0] + "/" + str(jenkins_details['runID'][0]) + '/results'
# logging.debug(raw_dir)
# raw_num_cpus_list = [d for d in os.listdir(raw_dir) if os.path.isdir(os.path.join(raw_dir, d))]
# num_cpus_list = []
# for one_by_one in raw_num_cpus_list:
# if one_by_one.isdigit() is True:
# num_cpus_list.append(one_by_one)
# logging.debug("GOT NUM CPUS")
# logging.debug(" = {}".format(num_cpus_list))
#except Exception as e:
# num_cpus_list = []
# logging.debug(" = {}".format(e))
# logging.debug(results_dataframe)
# logging.debug("DIDNT GET NUM CPUS")
#else:
# num_cpus_list = []
logging.debug("Result Type = {}".format(result_type))
system_details_dataframe = system_details_dataframe.head(1)
# Get the rest of the system details from jenkins table
JENKINS_QUERY = """SELECT J.jobname, J.runID FROM origin O INNER JOIN jenkins J
ON O.jenkins_jenkinsID=J.jenkinsID AND O.originID=""" + originID + ";"
jenkins_details = pd.read_sql(JENKINS_QUERY, db)
logging.debug('NUM CPUS START')
num_cpus_list = []
try:
# Calls unique_list function on list of unique 'Num_CPUs'
#num_cpus_list = unique_list((results_dataframe['Num_CPUs']), reverse=True)
raw_dir = '/mnt/nas/dbresults/' + jenkins_details['jobname'][0] + "/" + str(jenkins_details['runID'][0]) + '/results'
logging.debug(raw_dir)
raw_num_cpus_list = [d for d in os.listdir(raw_dir) if os.path.isdir(os.path.join(raw_dir, d))]
num_cpus_list = []
for one_by_one in raw_num_cpus_list:
if one_by_one.isdigit() is True:
num_cpus_list.append(one_by_one)
logging.debug("GOT NUM CPUS")
logging.debug(" = {}".format(num_cpus_list))
except Exception as e:
num_cpus_list = []
logging.debug(" = {}".format(e))
# logging.debug(results_dataframe)
logging.debug("DIDNT GET NUM CPUS")
#else:
# num_cpus_list = []
# list for creating a column in the system_details_dataframe
nas_link = []
nas_link.append("http://localhost:5000/dbresults/" +
jenkins_details['jobname'][0] + "/" + str(jenkins_details['runID'][0]))
jenkins_link = []
jenkins_link.append("http://localhost:5000/view/Production_Pipeline/job/" +
jenkins_details['jobname'][0] + "/" + str(jenkins_details['runID'][0]))
# Put the Jenkins details in the System Details Dataframe
system_details_dataframe['NAS Link'] = nas_link
system_details_dataframe['Jenkins Link'] = jenkins_link
# SYSTEM details is now ready
# Check if ramstat.csv exists
# Ram Utilization Graphs
nas_path = "/mnt/nas/dbresults/" + jenkins_details['jobname'][0] + '/' + str(jenkins_details['runID'][0]) + '/results/'
# Get list of directories in '/results/' directory
dir_list = []
for x in os.walk(nas_path):
dir_list = x[1]
break
# Get only numeric directories (corresponding to numCPUs)
dir_list = [x for x in dir_list if x.isnumeric()]
try:
ram_file = nas_path + '/' + dir_list[0] + '/ramstat.csv'
except:
ram_file = ''
# Check if ramstat.csv file exists
if os.path.isfile(ram_file):
ramstat_csv_exists = True
else:
ramstat_csv_exists = False
try:
freq_dump_file = nas_path + '/' + dir_list[0] + '/freq_dump.csv'
except:
freq_dump_file = ''
# Check if freq_dump.csv exists
if os.path.isfile(freq_dump_file):
freq_dump_csv_exists = True
else:
freq_dump_csv_exists = False
try:
iostat_csv_file = nas_path + '/' + dir_list[0] + '/iostat.csv'
except:
iostat_csv_file = ''
# Check if iostat.csv exists
if os.path.isfile(iostat_csv_file):
iostat_csv_exists = True
else:
iostat_csv_exists = False
context = {
'testname': test_name,
'system_details': system_details_dataframe.to_dict(orient='list'),
'description_list': description_string.split(','),
'results': results_dataframe.to_dict(orient='list'),
'originID': originID,
# Used For 'perf' scaling result_type
'result_type': result_type,
'jenkins_details' : {
'jobname' : jenkins_details['jobname'][0],
'runID' : str(jenkins_details['runID'][0]),
},
'num_cpus_list' : num_cpus_list,
'ramstat_csv_exists' : ramstat_csv_exists,
'freq_dump_csv_exists' : freq_dump_csv_exists,
'iostat_csv_exists' : iostat_csv_exists,
}
# close the database connection
try:
logging.debug("CLOSING CONNECTION FOR OriginID = {}".format(originID))
db.close()
except:
pass
return context
# View for handling Test details request
@app.route('/test/<originID>', methods=['GET'])
def test_details_page_old(originID):
return redirect('/test-details/' + originID)
@app.route('/test-details/<originID>', methods=['GET'])
def test_details_page(originID):
logging.debug("INSIDE TEST DETAILS FUNCTION = {}".format(originID))
try:
context = get_test_details_data(originID)
error = None
except Exception as error_message:
logging.debug("Printing error == {}".format(error_message))
context = None
error = error_message
# For 'Go To Benchmark' Dropdown
all_tests_data = get_all_tests_data()
logging.debug("PRINTING CONTEXT = {}".format(context))
return render_template('test-details.html', error=error, context=context, all_tests_data=all_tests_data)
# Page for marking Individual test 'result' as invalid
@app.route('/test-details/secret/<originID>', methods=['GET', 'POST'])
def test_details_secret_page(originID):
if request.method == 'GET':
# For 'Go To Benchmark' Dropdown
all_tests_data = get_all_tests_data()
return render_template('secret-test-details.html', originID={'ID':originID}, context={}, all_tests_data=all_tests_data)
else:
success = {}
error = {}
keyerror = {}
logging.debug("#######POSTED###########")
logging.debug(' = {}'.format(request.args))
# Get doesn't throw error.
# If key is not present it sets to default ('None' most of the times)
success = session.get('success')
error = session.get('error')
keyerror = session.get('keyerror')
logging.debug('success = {}'.format(success))
logging.debug('error = {}'.format(error))
logging.debug('keyerror = {}'.format(keyerror))
logging.debug("#######SESSION BEFORE ####")
logging.debug(' = {}'.format(session))
logging.debug("########SESSION AFTER $$$$")
# Clear the contents of the session (cookies)
session.clear()
logging.debug(' = {}'.format(session))
context = get_test_details_data(originID, secret=True)
# For 'Go To Benchmark' Dropdown
all_tests_data = get_all_tests_data()
return render_template('secret-test-details.html', success=success, error=error, keyerror=keyerror, context=context, all_tests_data=all_tests_data)
# Marks a single 'result' invalid
@app.route('/mark-result-id-invalid', methods=['POST'])
def mark_resultID_invalid():
logging.debug("\n\n\n#REQUEST#########")
logging.debug(' = {}'.format(request.form))
data = json.loads(request.form.get('data'))
logging.debug('Data = {}'.format(data))
originID = data.get('originID')
resultIDs = data.get('resultIDs')
valid = data.get('valid')
secret_key = data.get('secretKey')
success = {}
error = {}
keyerror = {}
if secret_key == 'secret_123':
logging.debug("CAUTION!!! Marking resultID invalid")
db = pymysql.connect(host=DB_HOST_IP, user=DB_USER,
passwd=DB_PASSWD, db=DB_NAME, port=DB_PORT)
cursor = db.cursor()
if not valid:
success['message'] = """The resultIDs [""" + resultIDs +"""] were marked invalid successfully"""
CHANGE_RESULTID_VALIDITY_QUERY = "UPDATE result r SET r.isvalid=0 where r.resultID in (" + resultIDs + ");"
else:
success['message'] = """The resultIDs [""" + resultIDs +"""] were marked valid successfully"""