Skip to content

panther_server ¤

PFVServer ¤

PFVServer(dir_path=None)
Source code in panther/panther_webapp/app/panther_server.py
 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
def __init__(self, dir_path=None):
    restore_config()

    # Initialize SocketIO
    PFVServer.socketio = SocketIO(PFVServer.app)

    # Setup configuration
    PFVServer.app.logger.info("Setup configuration ...")
    (
        PFVServer.supported_protocols,
        PFVServer.current_protocol,
        PFVServer.tests_enabled,
        PFVServer.conf_implementation_enable,
        PFVServer.implementation_enable,
        PFVServer.protocol_model_path,
        PFVServer.protocol_results_path,
        PFVServer.protocol_test_path,
        PFVServer.config,
        PFVServer.protocol_conf,
    ) = get_experiment_config(None, True, True)

    # Count number of directories in PFVServer.protocol_results_path
    PFVServer.total_exp_in_dir = 0
    with os.scandir(PFVServer.protocol_results_path) as entries:
        PFVServer.total_exp_in_dir = sum(1 for entry in entries if entry.is_dir())

    PFVServer.current_exp_path = os.path.join(
        PFVServer.protocol_results_path, str(PFVServer.total_exp_in_dir)
    )

    # Experiment parameters
    PFVServer.tests_requested = []
    PFVServer.implementation_requested = []
    PFVServer.experiment_iteration = 0
    PFVServer.experiment_current_iteration = 0
    PFVServer.is_experiment_started = False

    # Automatic GUI
    PFVServer.choices_args = {}

    PFVServer.get_quic_vizualier()

add_header ¤

add_header(r)

It sets the cache control headers to prevent caching

:param r: The response object :return: the response object with the headers added.

Source code in panther/panther_webapp/app/panther_server.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
@app.after_request
def add_header(r):
    """
    It sets the cache control headers to prevent caching

    :param r: The response object
    :return: the response object with the headers added.
    """
    r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    r.headers["Pragma"] = "no-cache"
    r.headers["Expires"] = "0"
    r.headers["Cache-Control"] = "public, max-age=0"
    r.headers.add("Access-Control-Allow-Headers", "authorization,content-type")
    r.headers.add(
        "Access-Control-Allow-Methods",
        "DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT",
    )
    r.headers.add("Access-Control-Allow-Origin", "*")
    return r

get_args ¤

get_args()

summary Get list of argument for automatic GUI generation Returns: type: description

Source code in panther/panther_webapp/app/panther_server.py
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
def get_args():
    """_summary_
    Get list of argument for automatic GUI generation
    Returns:
        _type_: _description_
    """
    # TODO refactor
    PFVServer.choices_args = {}
    args_parser = ArgumentParserRunner().parser
    args_list = [{}]
    is_mutually_exclusive = True
    for group_type in [
        args_parser._mutually_exclusive_groups,
        args_parser._action_groups,
    ]:
        for group in group_type:
            if group.title == "positional arguments":
                continue
            if group.title == "optional arguments":
                continue
            if group.title == "Usage type":
                continue

            cont = False
            for p in PFVServer.supported_protocols:
                if p in group.title.lower():
                    cont = True
            if cont:
                continue

            if len(args_list[-1]) == 3:
                args_list.append({})

            for action in group._group_actions:
                group_name = group.title
                if group_name not in args_list[-1]:
                    args_list[-1][group_name] = []
                if isinstance(action, argparse._StoreTrueAction):
                    args_list[-1][group_name].append(
                        {
                            "name": action.dest,
                            "help": action.help,
                            "type": "bool",
                            "default": False,
                            "is_mutually_exclusive": is_mutually_exclusive,
                            "description": action.metavar,
                        }
                    )
                elif isinstance(action, argparse._StoreFalseAction):
                    args_list[-1][group_name].append(
                        {
                            "name": action.dest,
                            "help": action.help,
                            "type": "bool",
                            "default": True,
                            "is_mutually_exclusive": is_mutually_exclusive,
                            "description": action.metavar,
                        }
                    )
                elif not isinstance(action, argparse._HelpAction):
                    if hasattr(action, "choices"):
                        if action.choices:
                            PFVServer.choices_args[action.dest] = action.choices
                        args_list[-1][group_name].append(
                            {
                                "name": action.dest,
                                "help": action.help,
                                "type": str(action.type),
                                "default": action.default,
                                "is_mutually_exclusive": is_mutually_exclusive,
                                "choices": action.choices,
                                "description": action.metavar,
                            }
                        )
                    else:
                        args_list[-1][group_name].append(
                            {
                                "name": action.dest,
                                "help": action.help,
                                "type": str(action.type),
                                "default": action.default,
                                "is_mutually_exclusive": is_mutually_exclusive,
                                "description": action.metavar,
                            }
                        )
        is_mutually_exclusive = False

    json_arg = args_list

    args_list = [{}]
    is_mutually_exclusive = True
    for group_type in [
        args_parser._mutually_exclusive_groups,
        args_parser._action_groups,
    ]:
        for group in group_type:
            for p in PFVServer.supported_protocols:
                if p in group.title.lower():
                    if p in PFVServer.current_protocol:
                        if len(args_list[-1]) == 3:
                            args_list.append({})

                        for action in group._group_actions:
                            group_name = group.title
                            if group_name not in args_list[-1]:
                                args_list[-1][group_name] = []
                            if isinstance(action, argparse._StoreTrueAction):
                                args_list[-1][group_name].append(
                                    {
                                        "name": action.dest,
                                        "help": action.help,
                                        "type": "bool",
                                        "default": False,
                                        "is_mutually_exclusive": is_mutually_exclusive,
                                        "description": action.metavar,
                                    }
                                )
                            elif isinstance(action, argparse._StoreFalseAction):
                                args_list[-1][group_name].append(
                                    {
                                        "name": action.dest,
                                        "help": action.help,
                                        "type": "bool",
                                        "default": True,
                                        "is_mutually_exclusive": is_mutually_exclusive,
                                        "description": action.metavar,
                                    }
                                )
                            elif not isinstance(action, argparse._HelpAction):
                                if hasattr(action, "choices"):
                                    if action.choices:
                                        PFVServer.choices_args[action.dest] = (
                                            action.choices
                                        )
                                    args_list[-1][group_name].append(
                                        {
                                            "name": action.dest,
                                            "help": action.help,
                                            "type": str(action.type),
                                            "default": action.default,
                                            "is_mutually_exclusive": is_mutually_exclusive,
                                            "choices": action.choices,
                                            "description": action.metavar,
                                        }
                                    )
                                else:
                                    args_list[-1][group_name].append(
                                        {
                                            "name": action.dest,
                                            "help": action.help,
                                            "type": str(action.type),
                                            "default": action.default,
                                            "is_mutually_exclusive": is_mutually_exclusive,
                                            "description": action.metavar,
                                        }
                                    )
                    is_mutually_exclusive = False
    prot_arg = args_list
    return json_arg, prot_arg

get_attack_model ¤

get_attack_model(attack_model)

It returns the attack model :param attack_model: the attack model :return: the attack model

Source code in panther/panther_webapp/app/panther_server.py
1006
1007
1008
1009
1010
1011
1012
def get_attack_model(self, attack_model):
    """
    It returns the attack model
    :param attack_model: the attack model
    :return: the attack model
    """
    return attack_model

get_json_graph ¤

get_json_graph()

It returns the json graph of the knowledge graph :return: the json graph of the knowledge graph

Source code in panther/panther_webapp/app/panther_server.py
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
@app.route("/kg/graph/json", methods=["GET"])
def get_json_graph():
    """
    It returns the json graph of the knowledge graph
    :return: the json graph of the knowledge graph
    """
    with open("/tmp/cytoscape_config.json", "r") as json_file:
        data = json.load(json_file)

    response = PFVServer.app.response_class(
        response=json.dumps(data), status=200, mimetype="application/json"
    )
    return response

redirection ¤

redirection()

It redirects the user to the index.html page :return: a redirect to the index.html page.

Source code in panther/panther_webapp/app/panther_server.py
140
141
142
143
144
145
146
@app.route("/")
def redirection():
    """
    It redirects the user to the index.html page
    :return: a redirect to the index.html page.
    """
    return redirect("index.html", code=302)

serve_attack ¤

serve_attack()

It creates a folder for the project, and then calls the upload function :return: the upload function.

Source code in panther/panther_webapp/app/panther_server.py
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
@app.route("/creator.html", methods=["GET", "POST"])
def serve_attack():
    """
    It creates a folder for the project, and then calls the upload function
    :return: the upload function.
    """
    # PFVServer.experiments.update_includes_ptls()
    # PFVServer.experiments.update_includes()
    setup_quic_model(PFVServer.protocol_test_path)
    setup_cytoscape()
    return render_template("creator.html")

serve_index ¤

serve_index()

It creates a folder for the project, and then calls the upload function :return: the upload function.

Source code in panther/panther_webapp/app/panther_server.py
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
@app.route("/index.html", methods=["GET", "POST"])
def serve_index():
    """
    It creates a folder for the project, and then calls the upload function
    :return: the upload function.
    """
    PFVServer.app.logger.info("Protocols under test: " + PFVServer.current_protocol)

    if DEBUG:
        json_arg, prot_arg = PFVServer.get_args()
        PFVServer.app.logger.info("JSON arguments availables:")
        for elem in json_arg:
            PFVServer.app.logger.info(elem)
        PFVServer.app.logger.info("PROTOCOL arguments availables:")
        for elem in prot_arg:
            PFVServer.app.logger.info(elem)

    if request.method == "POST":
        # TODO link json_arg and prot_arg to config so we can restore old config
        # TODO fix problem with alpn & initial version
        if (
            request.args.get("prot", "")
            and request.args.get("prot", "") in PFVServer.supported_protocols
        ):
            # The Selected Protocol change -> change GUI
            json_arg, prot_arg = PFVServer.change_current_protocol(
                request.args.get("prot", "")
            )

            (
                PFVServer.supported_protocols,
                PFVServer.current_protocol,
                PFVServer.tests_enabled,
                PFVServer.conf_implementation_enable,
                PFVServer.implementation_enable,
                PFVServer.protocol_model_path,
                PFVServer.protocol_results_path,
                PFVServer.protocol_test_path,
                PFVServer.config,
                PFVServer.protocol_conf,
            ) = get_experiment_config(PFVServer.current_protocol, True, False)

        # TODO implem progress, avoid to use post if experience already launched
        # TODO force to select at least one test and one implem
        PFVServer.app.logger.info("Form in POST request:")
        PFVServer.app.logger.info(request.form)
        if DEBUG:
            for c in request.form:
                for elem in request.form.getlist(c):
                    PFVServer.app.logger.info(elem)

        PFVServer.implementation_requested = []
        experiment_arguments = {}
        protocol_arguments = {}
        PFVServer.tests_requested = []

        arguments = dict(request.form)
        exp_number = 1
        for key, value in arguments.items():
            if (key, value) == ("boundary", "experiment separation"):
                exp_number += 1
            elif (
                key in PFVServer.implementation_enable.keys() and value == "true"
            ):
                PFVServer.implementation_requested.append(key)
            elif "test" in key and value == "true":
                PFVServer.tests_requested.append(key)
            elif value != "":
                if key in PFVServer.choices_args:
                    print(PFVServer.choices_args[key])
                    value = str(PFVServer.choices_args[key][int(value) - 1])
                if exp_number == 1:
                    experiment_arguments[key] = value
                elif exp_number == 2:
                    protocol_arguments[key] = value

        PFVServer.app.logger.info(
            "Experiment arguments: " + str(experiment_arguments)
        )
        PFVServer.app.logger.info("Protocol arguments: " + str(protocol_arguments))
        PFVServer.app.logger.info(
            "Experiment tests requested: " + str(PFVServer.tests_requested)
        )

        PFVServer.is_experiment_started = True
        PFVServer.experiment_iteration = (
            len(PFVServer.implementation_requested)
            * len(PFVServer.tests_requested)
            * int(experiment_arguments["iter"])
        )

        PFVServer.start_experiment_thread(experiment_arguments, protocol_arguments)
    else:
        if (
            request.args.get("prot", "")
            and request.args.get("prot", "") in PFVServer.supported_protocols
        ):
            json_arg, prot_arg = PFVServer.change_current_protocol(
                request.args.get("prot", "")
            )
            (
                PFVServer.supported_protocols,
                PFVServer.current_protocol,
                PFVServer.tests_enabled,
                PFVServer.conf_implementation_enable,
                PFVServer.implementation_enable,
                PFVServer.protocol_model_path,
                PFVServer.protocol_results_path,
                PFVServer.protocol_test_path,
                PFVServer.config,
                PFVServer.protocol_conf,
            ) = get_experiment_config(PFVServer.current_protocol, True, False)

    return render_template(
        "index.html",
        json_arg=json_arg,
        prot_arg=prot_arg,

        base_conf          =PFVServer.config,
        protocol_conf      =PFVServer.protocol_conf,
        supported_protocols=PFVServer.supported_protocols,
        current_protocol   =PFVServer.current_protocol,

        nb_exp                  =PFVServer.total_exp_in_dir,
        tests_enable            =PFVServer.tests_enabled,
        implementation_enable   =PFVServer.implementation_enable,
        implementation_requested=PFVServer.implementation_requested,
        progress                =PFVServer.experiment_current_iteration,  # PFVServer.experiments.count_1,
        iteration               =PFVServer.experiment_iteration,
    )

serve_results ¤

serve_results()

It creates a folder for the project, and then calls the upload function :return: the upload function.

Source code in panther/panther_webapp/app/panther_server.py
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
@app.route("/results.html", methods=["GET", "POST"])
def serve_results():
    """
    It creates a folder for the project, and then calls the upload function
    :return: the upload function.
    """
    PFVServer.app.logger.info(
        "Current Protocol Tests output folder: " + PFVServer.protocol_results_path
    )
    PFVServer.app.logger.info(os.listdir(PFVServer.protocol_results_path))

    with os.scandir(PFVServer.protocol_results_path) as entries:
        PFVServer.total_exp_in_dir = sum(1 for entry in entries if entry.is_dir())

    default_page = 0
    page = request.args.get("page", default_page)
    try:
        page = page.number
    except:
        pass
    # Get queryset of items to paginate
    rge = range(PFVServer.total_exp_in_dir, 0, -1)
    PFVServer.app.logger.info([i for i in rge])
    PFVServer.app.logger.info(page)
    items = [i for i in rge]

    # Paginate items
    items_per_page = 1
    paginator = Paginator(items, per_page=items_per_page)

    try:
        items_page = paginator.page(page)
    except PageNotAnInteger:
        items_page = paginator.page(default_page)
    except EmptyPage:
        items_page = paginator.page(paginator.num_pages)

    df_csv = pd.read_csv(PFVServer.protocol_results_path + "data.csv").set_index(
        "Run"
    )
    PFVServer.app.logger.info(PFVServer.total_exp_in_dir - int(page))

    result_row = df_csv.iloc[-1]
    output = "df_csv_row.html"
    # TODO change the label
    # result_row.to_frame().T
    # subdf = df_csv.drop("ErrorIEV", axis=1).drop("OutputFile", axis=1).drop("date", axis=1).drop("date", axis=1).drop("date", axis=1) #.reset_index()
    subdf = df_csv[["Implementation", "NbPktSend", "packet_event", "recv_packet"]]
    subdf.fillna(0, inplace=True)
    # subdf["isPass"] = subdf["isPass"].astype(int)
    subdf["NbPktSend"] = subdf["NbPktSend"].astype(int)
    # PFVServer.app.logger.info(subdf)
    # PFVServer.app.logger.info(df_csv.columns)
    # PFVServer.app.logger.info(subdf.columns)
    # subdf.columns = df_csv.columns
    configurationData = [
        {
            "id": str(uuid.uuid4()),  # Must be unique TODO df_csv_scdg['filename']
            "name": "Experiences coverage view",
            "parameters": ["Run"],  # "Implementation",
            "measurements": [
                "NbPktSend"
            ],  # , "Total number of blocks",'Number Syscall found' , 'Number Address found', 'Number of blocks visited', "Total number of blocks","time"
            "data": subdf.to_csv(),
        },
        {
            "id": str(uuid.uuid4()),  # Must be unique TODO df_csv_scdg['filename']
            "name": "Experiences packet view",
            "parameters": ["Run"],  # "Implementation"
            "measurements": [
                "packet_event",
                "recv_packet",
            ],  # , "Total number of blocks",'Number Syscall found' , 'Number Address found', 'Number of blocks visited', "Total number of blocks","time"
            "data": subdf.to_csv(),  # index=False -> need index
        },
    ]

    export(configurationData, output)

    # PFVServer.app.logger.info(configurationData)

    with open(output, "r") as f:
        df_csv_content = f.read()

    summary = {}
    summary["nb_pkt"] = result_row["NbPktSend"]
    summary["initial_version"] = result_row["initial_version"]

    PFVServer.current_exp_path = PFVServer.protocol_results_path + str(
        PFVServer.total_exp_in_dir - int(page)
    )
    exp_dir = os.listdir(PFVServer.current_exp_path)
    ivy_stderr = "No output"
    ivy_stdout = "No output"
    implem_err = "No output"
    implem_out = "No output"
    iev_out = "No output"
    qlog_file = ""
    pcap_file = ""
    for file in exp_dir:
        PFVServer.app.logger.info(file)
        if "ivy_stderr.txt" in file:
            with open(PFVServer.current_exp_path + "/" + file, "r") as f:
                content = f.read()
                if content == "":
                    pass
                else:
                    ivy_stderr = content
        elif "ivy_stdout.txt" in file:
            with open(PFVServer.current_exp_path + "/" + file, "r") as f:
                content = f.read()
                if content == "":
                    pass
                else:
                    ivy_stdout = content
        elif ".err" in file:
            with open(PFVServer.current_exp_path + "/" + file, "r") as f:
                content = f.read()
                if content == "":
                    pass
                else:
                    implem_err = content
        elif ".out" in file:
            with open(PFVServer.current_exp_path + "/" + file, "r") as f:
                content = f.read()
                if content == "":
                    pass
                else:
                    implem_out = content
        elif ".iev" in file:
            # TODO use csv file
            # file creation timestamp in float
            c_time = os.path.getctime(PFVServer.current_exp_path + "/" + file)
            # convert creation timestamp into DateTime object
            dt_c = datetime.datetime.fromtimestamp(c_time)
            PFVServer.app.logger.info("Created on:" + str(dt_c))
            summary["date"] = dt_c
            test_name = file.replace(".iev", "")[0:-1]
            summary["test_name"] = test_name
            with open(PFVServer.current_exp_path + "/" + file, "r") as f:
                content = f.read()
                summary["test_result"] = (
                    "Pass" if "test_completed" in content else "Fail"
                )

            try:
                plantuml_file = PFVServer.current_exp_path + "/plantuml.puml"
                generate_graph_input(
                    PFVServer.current_exp_path + "/" + file, plantuml_file
                )
                plantuml_obj = PlantUML(
                    url="http://www.plantuml.com/plantuml/img/",
                    basic_auth={},
                    form_auth={},
                    http_opts={},
                    request_opts={},
                )

                plantuml_file_png = plantuml_file.replace(
                    ".puml", ".png"
                )  # "media/" + str(nb_exp) + "_plantuml.png"
                plantuml_obj.processes_file(plantuml_file, plantuml_file_png)

                with open(PFVServer.current_exp_path + "/" + file, "r") as f:
                    content = f.read()
                    if content == "":
                        pass
                    else:
                        iev_out = content
            except:
                pass
        elif ".pcap" in file:
            pcap_file = file
            # Now we need qlogs and pcap informations
            summary["implementation"] = file.split("_")[0]
            summary["test_type"] = file.split("_")[2]

        elif ".qlog" in file:
            qlog_file = file

    # Get page number from request,
    # default to first page
    try:
        binary_fc = open(plantuml_file_png, "rb").read()  # fc aka file_content
        base64_utf8_str = b64encode(binary_fc).decode("utf-8")

        ext = plantuml_file_png.split(".")[-1]
    except:
        base64_utf8_str = ""
        ext = "png"
    dataurl = f"data:image/{ext};base64,{base64_utf8_str}"
    PFVServer.app.logger.info(items_page)
    PFVServer.app.logger.info(paginator)

    return render_template(
        "results.html",
        items_page=items_page,
        nb_exp=PFVServer.total_exp_in_dir,
        page=int(page),
        current_exp=PFVServer.current_exp_path,
        ivy_stderr=ivy_stderr,
        ivy_stdout=ivy_stdout,
        implem_err=implem_err,
        implem_out=implem_out,
        iev_out=iev_out,
        plantuml_file_png=dataurl,
        summary=summary,  # "http://"+PFVServer.vizualiser_ip+":80/?file=http://"
        pcap_frame_link=(
            "http://ivy-visualizer:80/?file=http://ivy-standalone:80/directory/"
            + str(PFVServer.total_exp_in_dir - int(page))
            + "/file/"
            + pcap_file
            + "&secrets=http://ivy-standalone:80/key/"
            + summary["implementation"]
            + "_key.log"
            if pcap_file != ""
            else None
        ),
        qlog_frame_link=(
            "http://ivy-visualizer:80/?file=http://ivy-standalone:80/directory/"
            + str(PFVServer.total_exp_in_dir - int(page))
            + "/file/"
            + qlog_file
            if qlog_file != ""
            else None
        ),
        df_csv_content=df_csv_content,
    )

serve_results_global ¤

serve_results_global()

It creates a folder for the project, and then calls the upload function :return: the upload function.

Source code in panther/panther_webapp/app/panther_server.py
 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
1001
1002
1003
1004
@app.route("/results-global.html", methods=["GET", "POST"])
def serve_results_global():
    """
    It creates a folder for the project, and then calls the upload function
    :return: the upload function.
    """
    PFVServer.total_exp_in_dir = (
        len(os.listdir(PFVServer.protocol_results_path)) - 2
    )

    PFVServer.app.logger.info(request.form)

    summary = {}
    df_csv = pd.read_csv(
        PFVServer.protocol_results_path + "data.csv", parse_dates=["date"]
    )

    df_simplify_date = df_csv
    df_simplify_date["date"] = df_csv["date"].dt.strftime("%d/%m/%Y")
    df_date_min_max = df_simplify_date["date"].agg(["min", "max"])
    df_nb_date = df_simplify_date["date"].nunique()
    df_dates = df_simplify_date["date"].unique()
    PFVServer.app.logger.info(list(df_dates))
    PFVServer.app.logger.info(df_date_min_max)
    PFVServer.app.logger.info(df_nb_date)
    minimum_date = df_date_min_max["min"]
    maximum_date = df_date_min_max["max"]

    subdf = None
    # if len(request.form) >= 0:
    for key in request.form:
        if key == "date_range":
            minimum = df_dates[int(request.form.get("date_range").split(",")[0])]
            maximum = df_dates[int(request.form.get("date_range").split(",")[1])]
            if subdf is None:
                subdf = df_csv.query("date >= @minimum and date <= @maximum")
            else:
                subdf = subdf.query("date >= @minimum and date <= @maximum")
        elif key == "iter_range":
            minimum = request.form.get("iter_range").split(",")[0]
            maximum = request.form.get("iter_range").split(",")[1]
            if subdf is None:  # TOODO
                subdf = df_csv.loc[df_csv["Run"] >= int(minimum)]
                subdf = subdf.loc[subdf["Run"] <= int(maximum)]
            else:
                subdf = subdf.loc[subdf["Run"] >= int(minimum)]
                subdf = subdf.loc[subdf["Run"] <= int(maximum)]
        elif key == "version":
            if request.form.get("version") != "all":
                if subdf is None:  # TOODO
                    subdf = df_csv.loc[
                        df_csv["initial_version"] == request.form.get("version")
                    ]
                else:
                    subdf = subdf.loc[
                        subdf["initial_version"] == request.form.get("version")
                    ]
        elif key == "ALPN":
            if request.form.get("ALPN") != "all":
                if subdf is None:  # TOODO
                    subdf = df_csv.loc[
                        df_csv["Mode"] == request.form.get("test_type")
                    ]
                else:
                    subdf = subdf.loc[
                        subdf["Mode"] == request.form.get("test_type")
                    ]
        elif key == "test_type":
            if request.form.get("test_type") != "all":
                if subdf is None:
                    subdf = df_csv.loc[
                        df_csv["Mode"] == request.form.get("test_type")
                    ]
                else:
                    subdf = subdf.loc[
                        subdf["Mode"] == request.form.get("test_type")
                    ]
        elif key == "isPass":
            ispass = True if "True" in request.form.get("isPass") else False
            if request.form.get("isPass") != "all":
                if subdf is None:
                    subdf = df_csv.loc[df_csv["isPass"] == ispass]
                else:
                    subdf = subdf.loc[subdf["isPass"] == ispass]
        elif key == "implem":
            for i in request.form.getlist("implem"):
                PFVServer.app.logger.info(i)
                if subdf is None:
                    subdf = df_csv.loc[df_csv["Implementation"] == i]
                else:
                    subdf = subdf.loc[subdf["Implementation"] == i]
        elif key == "server_test":
            for i in request.form.getlist("server_test"):
                if subdf is None:
                    subdf = df_csv.loc[df_csv["TestName"] == i]
                else:
                    subdf = subdf.loc[subdf["TestName"] == i]
        elif key == "client_test":
            for i in request.form.getlist("client_test"):
                if subdf is None:
                    subdf = df_csv.loc[df_csv["TestName"] == i]
                else:
                    subdf = subdf.loc[subdf["TestName"] == i]

    if subdf is not None:
        df_csv = subdf

    csv_text = df_csv.to_csv()

    output = "df_csv.html"
    # TODO change the label
    configurationData = [
        {
            "id": str(uuid.uuid4()),  # Must be unique TODO df_csv_scdg['filename']
            "name": "Experiences coverage view",
            "parameters": ["Implementation", "Mode", "TestName"],
            "measurements": [
                "isPass",
                "ErrorIEV",
                "packet_event",
                "packet_event_retry",
                "packet_event_vn",
                "packet_event_0rtt",
                "packet_event_coal_0rtt",
                "recv_packet",
                "recv_packet_retry",
                "handshake_done",
                "tls.finished",
                "recv_packet_vn",
                "recv_packet_0rtt",
                "undecryptable_packet_event",
                "version_not_found_event",
                "date",
                "initial_version",
                "NbPktSend",
                "version_not_found",
            ],  # , "Total number of blocks",'Number Syscall found' , 'Number Address found', 'Number of blocks visited', "Total number of blocks","time"
            "data": df_csv.to_csv(index=False),
        },
        {
            "id": str(uuid.uuid4()),  # Must be unique TODO df_csv_scdg['filename']
            "name": "Experiences coverage view",
            "parameters": ["Implementation", "Mode", "TestName"],
            "measurements": [
                "isPass",
                "ErrorIEV",
                "packet_event",
                "packet_event_retry",
                "packet_event_vn",
                "packet_event_0rtt",
                "packet_event_coal_0rtt",
                "recv_packet",
                "recv_packet_retry",
                "handshake_done",
                "tls.finished",
                "recv_packet_vn",
                "recv_packet_0rtt",
                "undecryptable_packet_event",
                "version_not_found_event",
                "date",
                "initial_version",
                "NbPktSend",
                "version_not_found",
            ],  # , "Total number of blocks",'Number Syscall found' , 'Number Address found', 'Number of blocks visited', "Total number of blocks","time"
            "data": df_csv.to_csv(index=False),
        },
        {
            "id": str(uuid.uuid4()),  # Must be unique TODO df_csv_scdg['filename']
            "name": "Experiences coverage view",
            "parameters": ["Implementation", "Mode", "TestName"],
            "measurements": [
                "isPass",
                "ErrorIEV",
                "packet_event",
                "packet_event_retry",
                "packet_event_vn",
                "packet_event_0rtt",
                "packet_event_coal_0rtt",
                "recv_packet",
                "recv_packet_retry",
                "handshake_done",
                "tls.finished",
                "recv_packet_vn",
                "recv_packet_0rtt",
                "undecryptable_packet_event",
                "version_not_found_event",
                "date",
                "initial_version",
                "NbPktSend",
                "version_not_found",
            ],  # , "Total number of blocks",'Number Syscall found' , 'Number Address found', 'Number of blocks visited', "Total number of blocks","time"
            "data": df_csv.to_csv(index=False),
        },
    ]
    # The above code is not valid Python code. It appears to be the beginning of a comment or
    # documentation string, but it is missing the closing characters.

    export(configurationData, output)

    # PFVServer.app.logger.info(configurationData)

    with open(output, "r") as f:
        df_csv_content = f.read()

    return render_template(
        "result-global.html",
        nb_exp=PFVServer.total_exp_in_dir,
        current_exp=PFVServer.current_exp_path,
        summary=summary,
        csv_text=csv_text,
        tests_requested=PFVServer.tests_requested,
        client_tests=PFVServer.client_tests,
        implementation_requested=PFVServer.implementation_requested,
        min_date=None,
        max_date=None,
        df_nb_date=df_nb_date,
        df_dates=list(df_dates),
        df_csv_content=df_csv_content,
    )