Skip to content
MEC application.ipynb 35.9 KiB
Newer Older
Yann Garcia's avatar
Yann Garcia committed
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How to develop a MEC application using the MEC Sandbox HTTP REST API\n",
    "\n",
    "## Table of contents\n",
    "\r\n",
    "1. What is a MEC applicationn](what_is_a_mec_applicationn)\r\n",
    "2. The basics of developing a MEC applicationh](the_basics_of_developing_a_mec_application)\n",
    "3. [Use the MEC Sandbox HTTP REST API models and code](#use_the_mec_sandbox_http_rest_api_models_and_code)\n",
    "4. [Create our first MEC application](#create_our_first_mec_application)\n",
    "    4.1. [The login function](#the_login_function)\n",
    "    4.2. [The logout function](#the_logout_function)\n",
    "5. [Second step: Retrieve the list of network scenarios](#second_step_retrieve_the_list_of_network_scenarios)\n",
    "6. [Third step: Activate and deactivate a network scenario](#third_step_activate_and_deactivate_a_network_scenario)\n",
    "    6.1. [The activate function](#the_activate_function)\n",
    "    6.2. [The deactivate function](#thedeactivate_function)\n",
    "7. [Fourth step: Create and delete an appliction instance id](#fourth_step_create_and_delete_an_appliction_instance_id)\n",
    "8. [MEC Registration and the READY indication](#mec_registration_and_the_ready_indication)\n",
    "9. [Annexes](#annexes)\n",
    "10. [Bibliography](#bibliography)t\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What is a MEC application\n",
    "\n",
    "See [The Wiki MEC web site](https://www.etsi.org/technologies/multi-access-edge-computing)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The basics of developing a MEC application\n",
    "\n",
    "The developement of a MEC application follows a strict process in order to access the ETSI MEC services and provides valueable services to the customers.\n",
    "Mainly, this process can be split in several steps:\n",
    "1. Global initializations (constant, variables...)\n",
    "2. Create of a new instance of a MEC Sandbox (Note that using an existing one could be a solution too (see Annex A)\n",
    "3. Activate a network scenario in order to access the ETSI MEC services\n",
    "4. Create a new application identifier\n",
    "5. Register our MEC application and subscribe to service termination (see MEC 011)\n",
    "6. Use MEC services in order to provide valueable services to the customers\n",
    "    6.1. Apply MEC services required subscriptions (e.g. MEC 013 location subscription)\n",
    "7. Terminate the MEC application\n",
    "    7.1. Remove MEC services subscriptions\n",
    "    7.2. Deactivate the current network scenario\n",
    "    7.3. Delete the instance of the MEC Sandbox\n",
    "8. Release all the MEC application resources\n",
    "\n",
    "## Use the MEC Sandbox HTTP REST API models and code\n",
    "\n",
    "The MEC sandbox provides a piece of code (the python sub) that shall be used to develop the MEC applicationand interact with the MEC Sandbox. This piece of code mainly contains swagger models to serialize/deserialize JSON data structures and HTTP REST API call functions.\n",
    "The openApi file is availabe [here](https://forge.etsi.org/rep/mec/AdvantEDGE/-/blob/Task2_PoC/go-apps/meep-sandbox-api/api/swagger.yaml) and the [Swagger editor](https://editor-next.swagger.io/) is used to generate the python sub.\n",
    "\n",
    "The project architecture is describe below:\n",
    "\n",
    "```sh\n",
    ".\r\n",
    "├── mecapp\r\n",
    "│   ├── docs\r\n",
    "│   ├── swagger_client\r\n",
    "│   │   ├── api\r\n",
    "│   │   │   └── __pycache__\r\n",
    "│   │   ├── models\r\n",
    "│   │   │   └── __pycache__\r\n",
    "│   │   └── __pycache__\r\n",
    "│   └── notebook\n",
    " te└\n",
    " ebirectory:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The api folder contains the python implementation of the HTTP REST API definitions introduced by the openApi [file](https://forge.etsi.org/rep/mec/AdvantEDGE/-/blob/Task2_PoC/go-apps/meep-sandbox-api/api/swagger.yaml).\n",
    "The model folder contains the python implementation of the data type definitions introduced by the openApi [file](https://forge.etsi.org/rep/mec/AdvantEDGE/-/blob/Task2_PoC/go-apps/meep-sandbox-api/api/swagger.yaml)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before to create our MEC ap[plication skeleton, the following steps shall be done:\n",
    "1) Change the working directory (see the project architecture)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "os.chdir(os.path.join(os.getcwd(), '../mecapp'))\n",
    "print(os.getcwd())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2) Do the python import"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import division # Import floating-point division (1/4=0.25) instead of Euclidian division (1/4=0)\n",
    "\n",
    "import os\n",
    "import sys\n",
    "import logging\n",
    "import time\n",
    "import json\n",
    "import uuid\n",
    "\n",
    "from pprint import pprint\n",
    "\n",
    "import swagger_client\n",
    "from swagger_client.rest import ApiException\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3) to initialize the global constants (cell 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "MEC_SANDBOX     = 'https://mec-platform.etsi.org/sandbox-api/v1'         # MEC Sandbox host/base URL\n",
    "PROVIDER        = 'gitlab'                                               # Login provider value\n",
    "MEC_PLTF        = 'mep1'                                                 # MEC plateform name. Linked to the network scenario\n",
    "LOGGER_FORMAT   = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' # Logging format\n",
    "STABLE_TIME_OUT = 6"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4) to setup a logger instance and initialize the global variables  (cell 4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize the logger\n",
    "logger = logging.getLogger(__name__)\n",
    "logger.setLevel(logging.DEBUG)\n",
    "logging.basicConfig(filename='/tmp/' + time.strftime(\"%Y%m%d-%H%M%S\") + '.log')\n",
    "l = logging.StreamHandler()\n",
    "l.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\n",
    "logger.addHandler(l)\n",
    "\n",
    "# Setup the HTTP REST API configuration\n",
    "configuration               = swagger_client.Configuration()\n",
    "configuration.host          = MEC_SANDBOX\n",
    "configuration.verify_ssl    = False\n",
    "configuration.debug         = True\n",
    "configuration.logger_format = LOGGER_FORMAT\n",
    "\n",
    "# Initialize the global variables\n",
    "nw_scenarios    = []   # The list of available network scenarios\n",
    "nw_scenario_idx = -1   # The network scenario idx to activate (deactivate)\n",
    "app_inst_id     = None # The requested application instance identifier\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create our first MEC application\n",
    "\n",
    "The first step to develop a MEC application is to create the application skeleton which contains the minimum steps below:\n",
    " \n",
    "- Login to instanciate a MEC Sandbox\n",
    "- Logout to delete a existing MEC Sandbox"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### First steps: the login/logout\n",
    "\n",
    "Here is the first squeleton with the following sequence:\n",
    "- Login\n",
    "- Print sandbox identifier\n",
    "- Logout\n",
    "- Check that logout is effective\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### The login function\n",
    "\n",
    "It uses the HTTP POST request with the URL 'POST /sandbox-api/v1/login?provide=gitlab' (see PROVIDER constant).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Login\n",
    "def process_login() -> swagger_client.Sandbox:\n",
    "    \"\"\"\n",
    "    Authenticate and create a new MEC Sandbox instance.\n",
    "\n",
    "    :return: The swagger_client.Sandbox instance on success, None otherwise\n",
    "    \"\"\" \n",
    "\n",
    "    global PROVIDER, MEC_SANDBOX, LOGGER_FORMAT, logger, configuration\n",
    "\n",
    "    logger.debug(\">>> process_login\")\n",
    "\n",
    "    try:\n",
    "        api = swagger_client.ApiClient(configuration, 'Content-Type', 'application/json')\n",
    "        auth = swagger_client.AuthorizationApi(api)\n",
    "        result = auth.login(PROVIDER, async_req = False)  # noqa: E501\n",
    "        logger.debug(\"process_login: result: \" + str(result))\n",
    "        return result\n",
    "    except ApiException as e:\n",
    "        logger.error(\"Exception when calling AuthorizationApi->login: %s\\n\" % e)\n",
    "\n",
    "    return None\n",
    "    # End of function process_login\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### The logout function\n",
    "\n",
    "It uses the HTTP POST request with the URL 'POST /sandbox-api/v1/logout?sandbox_name={sandbox_name}'.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Logout\n",
    "def process_logout(sandbox: swagger_client.Sandbox) -> int:\n",
    "    \"\"\"\n",
    "    Delete the specified MEC Sandbox instance.\n",
    "\n",
    "    :param sandbox: The MEC Sandbox to delete\n",
    "    :return: 0 on success, -1 otherwise\n",
    "    \"\"\"\n",
    "\n",
    "    global PROVIDER, MEC_SANDBOX, LOGGER_FORMAT, logger, configuration\n",
    "\n",
    "    logger.debug(\">>> process_logout: sandbox.name=\" + sandbox.name)\n",
    "\n",
    "    try:\n",
    "        api = swagger_client.ApiClient(configuration, 'Content-Type', 'application/json')\n",
    "        auth = swagger_client.AuthorizationApi(api)\n",
    "        result = auth.logout(sandbox.name, async_req = False)  # noqa: E501\n",
    "        return 0\n",
    "    except ApiException as e:\n",
    "        logger.error(\"Exception when calling AuthorizationApi->logout: %s\\n\" % e)\n",
    "    return -1\n",
    "    # End of function process_logout\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let put in action our Login/Logout functions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_main():\n",
    "    \"\"\"\n",
    "    This is the skeleton of our MEC application:\n",
    "        - Login\n",
    "        - Print sandbox identifier\n",
    "        - Logout\n",
    "        - Check that logout is effective\n",
    "    This skeleton will be the bas of the next sprint in order to achieve a full implementation of a MEC application\n",
    "    \"\"\" \n",
    "\n",
    "    global PROVIDER, MEC_SANDBOX, LOGGER_FORMAT, logger\n",
    "\n",
    "    logger.debug(\"Starting at \" + time.strftime(\"%Y%m%d-%H%M%S\"))\n",
    "    logger.debug(\"\\t pwd= \" + os.getcwd())\n",
    "\n",
    "    # Login\n",
    "    sandbox = process_login()\n",
    "    if sandbox is None:\n",
    "        return\n",
    "\n",
    "    # Print sandbox identifier\n",
    "    logger.info(\"Sandbox created: \" + sandbox.name)\n",
    "    # Wait for the MEC Sandbox is running\n",
    "    time.sleep(STABLE_TIME_OUT) # Sleep for 3 seconds\n",
    "\n",
    "    # Logout\n",
    "    process_logout(sandbox)\n",
    "\n",
    "    # Check that logout is effective\n",
    "    logger.debug(\"To check that logout is effective, verify on the MEC Sandbox server that the MEC Sandbox is removed (kubectl get pods -A\")\n",
    "  \n",
    "    logger.debug(\"Stopped at \" + time.strftime(\"%Y%m%d-%H%M%S\"))\n",
    "    # End of function process_main\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    process_main()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Second step: Retrieve the list of network scenarios\n",
    "\n",
    "Let's go futhur and see how we can retrieve the list of the network scenarios available in order to activate one of them and access the MEC services exposed such as MEC 013 or MEC 030.\n",
    "\n",
    "The sequence will be:\n",
    "- Login\n",
    "- Print sandbox identifier\n",
    "- Print available network scenarios\n",
    "- Logout\n",
    "- Check that logout is effective\n",
    "\n",
    "The login and logout functions are described in cell 3 and 4.\n",
    "\n",
    "To retrieve the list of the network scenarios, let's create a new function called 'get_network_scenarios'. It uses the HTTP GET request with the URL '/sandbox-api/v1/sandboxNetworkScenarios?sandbox_name={sandbox_name}'."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_network_scenarios(sandbox: swagger_client.Sandbox) -> list:\n",
    "    \"\"\"\n",
    "    Retrieve the list of the available network scenarios.\n",
    "\n",
    "    :param sandbox: The MEC Sandbox instance to use\n",
    "    :return: The list of the available network scenarios on success, None otherwise\n",
    "    \"\"\"\n",
    "\n",
    "    global PROVIDER, MEC_SANDBOX, LOGGER_FORMAT, logger, configuration\n",
    "\n",
    "    logger.debug(\">>> get_network_scenarios: sandbox.name=\" + sandbox.name)\n",
    "\n",
    "    try:\n",
    "        api = swagger_client.ApiClient(configuration, 'Content-Type', 'application/json')\n",
    "        nw = swagger_client.SandboxNetworkScenariosApi(api)\n",
    "        result = nw.sandbox_network_scenarios_get(sandbox.name, async_req = False)  # noqa: E501\n",
    "        logger.debug(\"get_network_scenarios: result: \" + str(result))\n",
    "        return result\n",
    "    except ApiException as e:\n",
    "        logger.error(\"Exception when calling SandboxNetworkScenariosApi->sandbox_network_scenarios_get: %s\\n\" % e)\n",
    "\n",
    "    return None\n",
    "    # End of function get_network_scenarios\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Putting everything together:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_main():\n",
    "    \"\"\"\n",
    "    This is the first sprint of our skeleton of our MEC application:\n",
    "        - Login\n",
    "        - Print sandbox identifier\n",
    "        - Print available network scenarios\n",
    "        - Logout\n",
    "        - Check that logout is effective\n",
    "    \"\"\" \n",
    "    global PROVIDER, MEC_SANDBOX, LOGGER_FORMAT, nw_scenarios, logger\n",
    "\n",
    "    logger.debug(\"Starting at \" + time.strftime(\"%Y%m%d-%H%M%S\"))\n",
    "    logger.debug(\"\\t pwd= \" + os.getcwd())\n",
    "\n",
    "    # Login\n",
    "    sandbox = process_login()\n",
    "    if sandbox is None:\n",
    "        logger.error(\"Failed to instanciate a MEC Sandbox\")\n",
    "        return\n",
    "\n",
    "    # Print sandbox identifier\n",
    "    logger.info(\"Sandbox created: \" + sandbox.name)\n",
    "    # Wait for the MEC Sandbox is running\n",
    "    time.sleep(STABLE_TIME_OUT) # Sleep for 3 seconds\n",
    "\n",
    "    # Print available network scenarios\n",
    "    nw_scenarios = get_network_scenarios(sandbox)\n",
    "    if nw_scenarios is None:\n",
    "        logger.error(\"Failed to retrieve the list of network scenarios\")\n",
    "    elif len(nw_scenarios) != 0:\n",
    "        logger.info(\"nw_scenarios: %s\", str(type(nw_scenarios[0])))\n",
    "        logger.info(\"nw_scenarios: %s\", str(nw_scenarios))\n",
    "    else:\n",
    "        logger.info(\"nw_scenarios: No scenario available\")\n",
    "\n",
    "    # Logout\n",
    "    process_logout(sandbox)\n",
    "\n",
    "    # Check that logout is effective\n",
    "    logger.debug(\"To check that logout is effective, verify on the MEC Sandbox server that the MEC Sandbox is removed (kubectl get pods -A\")\n",
    "  \n",
    "    logger.debug(\"Stopped at \" + time.strftime(\"%Y%m%d-%H%M%S\"))\n",
    "    # End of function process_main\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    process_main()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Third step: Activate and deactivate a network scenario\n",
    "\n",
    "Having a list of network scenarion, the next step is to actvate (and deactivate) a network scenario. This step is mandatory to create a new application instance id and access the MEC services.\n",
    "\n",
    "In this section, we will arbitrary activate the network scenario called '4g-5g-macro-v2x', which is at the index 0 of the nw_scenarios. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def select_network_scenario_based_on_criteria(criterias_list: list) -> int:\n",
    "    \"\"\"\n",
    "    Select the network scenario to activate based of the provided list of criterias.\n",
    "\n",
    "    :param criterias_list: The list of criterias to select the correct network scenario\n",
    "    :return: 0 on success, -1 otherwise\n",
    "    \"\"\"\n",
    "    return 0 # The index of the '4g-5g-macro-v2x' network scenario - Hard coded"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### The activate function\n",
    "\n",
    "The process to activate a scenario is based on an HTTP POST request with the URL '/sandboxNetworkScenarios/{sandbox_name}?network_scenario_id={network_scenario_id}'.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def activate_network_scenario(sandbox: swagger_client.Sandbox) -> int:\n",
    "    \"\"\"\n",
    "    Activate the specified network scenario.\n",
    "\n",
    "    :param sandbox: The MEC Sandbox instance to use\n",
    "    :return: 0 on success, -1 otherwise\n",
    "    \"\"\"\n",
    "\n",
    "    global MEC_SANDBOX, LOGGER_FORMAT, logger, configuration, nw_scenarios, nw_scenario_idx\n",
    "\n",
    "    logger.debug(\">>> activate_network_scenario: \" + sandbox.name)\n",
    "\n",
    "    nw_scenario_idx = select_network_scenario_based_on_criteria([])\n",
    "    if nw_scenario_idx == -1:\n",
    "        logger.error(\"activate_network_scenario: Failed to select a network scenarion\")\n",
    "        return -1\n",
    "\n",
    "    try:\n",
    "        api = swagger_client.ApiClient(configuration, 'Content-Type', 'application/json')\n",
    "        nw = swagger_client.SandboxNetworkScenariosApi(api)\n",
    "        result = nw.sandbox_network_scenario_post(sandbox.name, nw_scenarios[nw_scenario_idx].id, async_req = False)  # noqa: E501\n",
    "        logger.debug(\"activate_network_scenario: result: \" + str(result))\n",
    "        return result\n",
    "    except ApiException as e:\n",
    "        logger.error(\"Exception when calling SandboxNetworkScenariosApi->activate_network_scenario: %s\\n\" % e)\n",
    "\n",
    "    return -1\n",
    "    # End of function activate_network_scenario\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### The deactivate function\n",
    "\n",
    "The process to deactivate a scenario is based on an HTTP DELETE request with the URL '/sandboxNetworkScenarios/{sandbox_name}?network_scenario_id={network_scenario_id}'.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def deactivate_network_scenario(sandbox: swagger_client.Sandbox) -> int:\n",
    "    \"\"\"\n",
    "    Deactivate the current network scenario.\n",
    "\n",
    "    :param sandbox: The MEC Sandbox instance to use\n",
    "    :return: 0 on success, -1 otherwise\n",
    "    \"\"\"\n",
    "\n",
    "    global MEC_SANDBOX, LOGGER_FORMAT, logger, configuration, nw_scenarios, nw_scenario_idx\n",
    "\n",
    "    logger.debug(\">>> deactivate_network_scenario: \" + sandbox.name)\n",
    "\n",
    "    try:\n",
    "        api = swagger_client.ApiClient(configuration, 'Content-Type', 'application/json')\n",
    "        nw = swagger_client.SandboxNetworkScenariosApi(api)\n",
    "        result = nw.sandbox_network_scenario_delete(sandbox.name, nw_scenarios[nw_scenario_idx].id, async_req = False)  # noqa: E501\n",
    "        logger.debug(\"deactivate_network_scenario: result: \" + str(result))\n",
    "        return result\n",
    "    except ApiException as e:\n",
    "        logger.error(\"Exception when calling SandboxNetworkScenariosApi->deactivate_network_scenario: %s\\n\" % e)\n",
    "\n",
    "    return -1\n",
    "    # End of function deactivate_network_scenario\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, it is time to create the second iteration of our MEC application.\n",
    "\n",
    "The sequence is the following:\n",
    "- Login\n",
    "- Print sandbox identifier\n",
    "- Print available network scenarios\n",
    "- Activate a network scenario\n",
    "- Check that the network scenario is activated and the MEC services are running\n",
    "- Deactivate a network scenario\n",
    "- Logout\n",
    "- Check that logout is effective\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_main():\n",
    "    \"\"\"\n",
    "    This is the second sprint of our skeleton of our MEC application:\n",
    "        - Login\n",
    "        - Print sandbox identifier\n",
    "        - Print available network scenarios\n",
    "        - Activate a network scenario\n",
    "        - Check that the network scenario is activated and the MEC services are running\n",
    "        - Deactivate a network scenario\n",
    "        - Logout\n",
    "        - Check that logout is effective\n",
    "    \"\"\" \n",
    "    global PROVIDER, MEC_SANDBOX, LOGGER_FORMAT, nw_scenarios, logger\n",
    "\n",
    "    logger.debug(\"Starting at \" + time.strftime(\"%Y%m%d-%H%M%S\"))\n",
    "    logger.debug(\"\\t pwd= \" + os.getcwd())\n",
    "\n",
    "    # Login\n",
    "    sandbox = process_login()\n",
    "    if sandbox is None:\n",
    "        logger.error(\"Failed to instanciate a MEC Sandbox\")\n",
    "        return\n",
    "\n",
    "    # Print sandbox identifier\n",
    "    logger.info(\"Sandbox created: \" + sandbox.name)\n",
    "    # Wait for the MEC Sandbox is running\n",
    "    time.sleep(STABLE_TIME_OUT) # Sleep for 3 seconds\n",
    "\n",
    "    # Print available network scenarios\n",
    "    nw_scenarios = get_network_scenarios(sandbox)\n",
    "    if nw_scenarios is None:\n",
    "        logger.error(\"Failed to retrieve the list of network scenarios\")\n",
    "    elif len(nw_scenarios) != 0:\n",
    "        logger.info(\"nw_scenarios: %s\", str(type(nw_scenarios[0])))\n",
    "        logger.info(\"nw_scenarios: %s\", str(nw_scenarios))\n",
    "        # Wait for the MEC Sandbox is running\n",
    "        time.sleep(STABLE_TIME_OUT) # Sleep for 3 seconds\n",
    "    else:\n",
    "        logger.info(\"nw_scenarios: No scenario available\")\n",
    "\n",
    "    # Activate a network scenario based on a list of criterias (hard coded!!!)\n",
    "    if activate_network_scenario(sandbox) == -1:\n",
    "        logger.error(\"Failed to activate network scenario\")\n",
    "    else:\n",
    "        logger.info(\"Network scenario activated: \" + nw_scenarios[nw_scenario_idx].id)\n",
    "        # Wait for the MEC services are running\n",
    "        time.sleep(STABLE_TIME_OUT) # Sleep for 3 seconds\n",
    "\n",
    "    # Check that the network scenario is activated and the MEC services are running \n",
    "    logger.info(\"To check that the network scenario is activated, verify on the MEC Sandbox server that the MEC services are running (kubectl get pods -A\")\n",
    "    time.sleep(60) # Sleep for 3 seconds\n",
    "\n",
    "    # Deactivate a network scenario based on a list of criterias (hard coded!!!)\n",
    "    if deactivate_network_scenario(sandbox) == -1:\n",
    "        logger.error(\"Failed to deactivate network scenario\")\n",
    "    else:\n",
    "        logger.info(\"Network scenario deactivated: \" + nw_scenarios[nw_scenario_idx].id)\n",
    "        # Wait for the MEC services are terminated\n",
    "        time.sleep(STABLE_TIME_OUT)\n",
    "\n",
    "    # Logout\n",
    "    process_logout(sandbox)\n",
    "\n",
    "    # Check that logout is effective\n",
    "    logger.debug(\"To check that logout is effective, verify on the MEC Sandbox server that the MEC Sandbox is removed (kubectl get pods -A\")\n",
    "  \n",
    "    logger.debug(\"Stopped at \" + time.strftime(\"%Y%m%d-%H%M%S\"))\n",
    "    # End of function process_main\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    process_main()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Fourth step: Create and delete an appliction instance id\n",
    "\n",
    "To enable our MEC application to be part of the activated network scenario, we need to request the MEC sandbox to create a new application instance identifer. Our MEC application will use this identifier to register to the MEC Sandbox according to MEC 011.\n",
    "\n",
    "#### The appliction instance id creation function\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def request_application_instance_id(sandbox: swagger_client.Sandbox) -> swagger_client.models.ApplicationInfo:\n",
    "    \"\"\"\n",
    "    \"\"\"\n",
    "\n",
    "    global MEC_SANDBOX, LOGGER_FORMAT, logger, configuration, app_inst_id\n",
    "\n",
    "    logger.debug(\">>> request_application_instance_id: \" + sandbox.name)\n",
    "\n",
    "    # Create a instance of our MEC application\n",
    "    a = swagger_client.models.ApplicationInfo(id=uuid.uuid4(), name='JupyterMecApp', node_name=MEC_PLTF, type='USER'):  # noqa: E501\n",
    "    \n",
    "    try:\n",
    "        api = swagger_client.ApiClient(configuration, 'Content-Type', 'application/json')\n",
    "        nw = swagger_client.SandboxAppInstancesApi(api)\n",
    "        result = nw.sandbox_app_instances_post(sandbox.name, a, async_req = False)  # noqa: E501\n",
    "        logger.debug(\"request_application_instance_id: result: \" + str(result))\n",
    "        return result\n",
    "    except ApiException as e:\n",
    "        logger.error(\"Exception when calling SandboxAppInstancesApi->sandbox_app_instances_post: %s\\n\" % e)\n",
    "\n",
    "    return None\n",
    "    # End of function request_application_instance_id"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### The appliction instance id deletion function\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def deletet_application_instance_id(sandbox: swagger_client.Sandbox) -> int:\n",
    "    \"\"\"\n",
    "    \"\"\"\n",
    "\n",
    "    global MEC_SANDBOX, LOGGER_FORMAT, logger, configuration, app_inst_id\n",
    "\n",
    "    logger.debug(\">>> deletet_application_instance_id: \" + sandbox.name)\n",
    "\n",
    "    try:\n",
    "        api = swagger_client.ApiClient(configuration, 'Content-Type', 'application/json')\n",
    "        nw = swagger_client.SandboxAppInstancesApi(api)\n",
    "        result = nw.sandbox_app_instances_delete(sandbox.name, app_inst_id.id, async_req = False)  # noqa: E501\n",
    "        logger.debug(\"deletet_application_instance_id: result: \" + str(result))\n",
    "        return result\n",
    "    except ApiException as e:\n",
    "        logger.error(\"Exception when calling SandboxAppInstancesApi->sandbox_app_instances_delete: %s\\n\" % e)\n",
    "\n",
    "    return -1\n",
    "    # End of function deletet_application_instance_id"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is time now to create the our third iteration of our MEC application.\n",
    "\n",
    "The sequence is the following:\n",
    "- Login\n",
    "- Print sandbox identifier\n",
    "- Print available network scenarios\n",
    "- Activate a network scenario\n",
    "- Request for a new application instance identifer\n",
    "- Check \n",
    "- Delete our application instance identifer\n",
    "- Deactivate a network scenario\n",
    "- Logout\n",
    "- Check that logout is effective\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_main():\n",
    "    \"\"\"\n",
    "    This is the second sprint of our skeleton of our MEC application:\n",
    "        - Login\n",
    "        - Print sandbox identifier\n",
    "        - Print available network scenarios\n",
    "        - Activate a network scenario\n",
    "        - Check that the network scenario is activated and the MEC services are running\n",
    "        - Deactivate a network scenario\n",
    "        - Logout\n",
    "        - Check that logout is effective\n",
    "    \"\"\" \n",
    "    global PROVIDER, MEC_SANDBOX, LOGGER_FORMAT, nw_scenarios, logger\n",
    "\n",
    "    logger.debug(\"Starting at \" + time.strftime(\"%Y%m%d-%H%M%S\"))\n",
    "    logger.debug(\"\\t pwd= \" + os.getcwd())\n",
    "\n",
    "    # Login\n",
    "    sandbox = process_login()\n",
    "    if sandbox is None:\n",
    "        logger.error(\"Failed to instanciate a MEC Sandbox\")\n",
    "        return\n",
    "\n",
    "    # Print sandbox identifier\n",
    "    logger.info(\"Sandbox created: \" + sandbox.name)\n",
    "    # Wait for the MEC Sandbox is running\n",
    "    time.sleep(STABLE_TIME_OUT) # Sleep for 3 seconds\n",
    "\n",
    "    # Print available network scenarios\n",
    "    nw_scenarios = get_network_scenarios(sandbox)\n",
    "    if nw_scenarios is None:\n",
    "        logger.error(\"Failed to retrieve the list of network scenarios\")\n",
    "    elif len(nw_scenarios) != 0:\n",
    "        logger.info(\"nw_scenarios: %s\", str(type(nw_scenarios[0])))\n",
    "        logger.info(\"nw_scenarios: %s\", str(nw_scenarios))\n",
    "        # Wait for the MEC Sandbox is running\n",
    "        time.sleep(STABLE_TIME_OUT) # Sleep for 3 seconds\n",
    "    else:\n",
    "        logger.info(\"nw_scenarios: No scenario available\")\n",
    "\n",
    "    # Activate a network scenario based on a list of criterias (hard coded!!!)\n",
    "    if activate_network_scenario(sandbox) == -1:\n",
    "        logger.error(\"Failed to activate network scenario\")\n",
    "    else:\n",
    "        logger.info(\"Network scenario activated: \" + nw_scenarios[nw_scenario_idx].id)\n",
    "        # Wait for the MEC services are running\n",
    "        time.sleep(STABLE_TIME_OUT) # Sleep for 3 seconds\n",
    "\n",
    "    # Request for a new application instance identifer\n",
    "    app_inst_id = request_application_instance_id(sandbox)\n",
    "    if app_inst_id == None:\n",
    "        logger.error(\"Failed to request an application instance identifer\")\n",
    "    else:\n",
    "        logger.info(\"app_inst_id: %s\", str(type(app_inst_id)))\n",
    "        logger.info(\"app_inst_id: %s\", str(app_inst_id))\n",
    "\n",
    "    # Check that the network scenario is activated and the MEC services are running \n",
    "    logger.info(\"To check that the app_inst_id is created, verify on the MEC Sandbox server that the MEC services are running (kubectl get pods -A\")\n",
    "    time.sleep(3) # Sleep for 3 seconds\n",
    "\n",
    "    # Request for a new application instance identifer\n",
    "    if delete_application_instance_id(sandbox) == -1:\n",
    "        logger.error(\"Failed to delete the application instance identifer\")\n",
    "    else:\n",
    "        logger.info(\"app_inst_id deleted: \" + app_inst_id.id)\n",
    "\n",
    "    # Deactivate a network scenario based on a list of criterias (hard coded!!!)\n",
    "    if deactivate_network_scenario(sandbox) == -1:\n",
    "        logger.error(\"Failed to deactivate network scenario\")\n",
    "    else:\n",
    "        logger.info(\"Network scenario deactivated: \" + nw_scenarios[nw_scenario_idx].id)\n",
    "        # Wait for the MEC services are terminated\n",
    "        time.sleep(STABLE_TIME_OUT)\n",
    "\n",
    "    # Logout\n",
    "    process_logout(sandbox)\n",
    "\n",
    "    # Check that logout is effective\n",
    "    logger.debug(\"To check that logout is effective, verify on the MEC Sandbox server that the MEC Sandbox is removed (kubectl get pods -A\")\n",
    "  \n",
    "    logger.debug(\"Stopped at \" + time.strftime(\"%Y%m%d-%H%M%S\"))\n",
    "    # End of function process_main\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    process_main()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## MEC Registration and the READY indication\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Annexes\n",
    "\n",
    "## Annex A: How to use an existing MEC sandbox instance\n",
    "\n",
    "TODO\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Bibliography\n",
    "\n",
    "1. ETSI GS MEC 002 (V2.2.1) (01-2022): \"Multi-access Edge Computing (MEC); Phase 2: Use Cases and Requirements\".\n",
    "2. ETSI GS MEC 010-1 (V1.1.1) (10-2017): \"Mobile Edge Computing (MEC); Mobile Edge Management; Part 1: System, host and platform management\".\n",
    "3. ETSI GS MEC 010-2 (V2.2.1) (02-2022): \"Multi-access Edge Computing (MEC); MEC Management; Part 2: Application lifecycle, rules and requirements management\".\n",
    "4. ETSI GS MEC 011 (V3.1.1) (09-2022): \"Multi-access Edge Computing (MEC); Edge Platform Application Enablement\".\n",
    "5. ETSI GS MEC 012 (V2.2.1) (02-2022): \"Multi-access Edge Computing (MEC); Radio Network Information API\".\n",
    "6. ETSI GS MEC 013 (V2.2.1) (01-2022): \"Multi-access Edge Computing (MEC); Location API\".\n",
    "7. ETSI GS MEC 014 (V2.1.1) (03-2021): \"Multi-access Edge Computing (MEC); UE Identity API\".\n",
    "8. ETSI GS MEC 015 (V2.1.1) (06-2020): \"Multi-Access Edge Computing (MEC); Traffic Management APIs\".\n",
    "9. ETSI GS MEC 016 (V2.2.1) (04-2020): \"Multi-access Edge Computing (MEC); Device application interface\".\n",
    "10. ETSI GS MEC 021 (V2.2.1) (02-2022): \"Multi-access Edge Computing (MEC); Application Mobility Service API\".\n",
    "11. ETSI GS MEC 028 (V2.3.1) (07-2022): \"Multi-access Edge Computing (MEC); WLAN Access Information API\".\n",
    "12. ETSI GS MEC 029 (V2.2.1) (01-2022): \"Multi-access Edge Computing (MEC); Fixed Access Information API\".\n",
    "13. ETSI GS MEC 030 (V2.2.1) (05-2022): \"Multi-access Edge Computing (MEC); V2X Information Service API\".\n",
    "14. ETSI GR MEC-DEC 025 (V2.1.1) (06-2019): \"Multi-access Edge Computing (MEC); MEC Testing Framework\".\n",
    "15. ETSI GR MEC 001 (V3.1.1) (01-2022): \"Multi-access Edge Computing (MEC); Terminology\".\n",
    "16. [The Wiki MEC web site](https://www.etsi.org/technologies/multi-access-edge-computing)\n",
    "17. "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}