inmanta-nfv-test-api 2.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. inmanta_nfv_test_api-2.8.0.dist-info/METADATA +19 -0
  2. inmanta_nfv_test_api-2.8.0.dist-info/RECORD +52 -0
  3. inmanta_nfv_test_api-2.8.0.dist-info/WHEEL +5 -0
  4. inmanta_nfv_test_api-2.8.0.dist-info/entry_points.txt +5 -0
  5. inmanta_nfv_test_api-2.8.0.dist-info/top_level.txt +2 -0
  6. nfv_test_api/__init__.py +15 -0
  7. nfv_test_api/config.py +126 -0
  8. nfv_test_api/exceptions.py +19 -0
  9. nfv_test_api/host.py +64 -0
  10. nfv_test_api/main.py +98 -0
  11. nfv_test_api/py.typed +0 -0
  12. nfv_test_api/v2/__init__.py +152 -0
  13. nfv_test_api/v2/controllers/__init__.py +15 -0
  14. nfv_test_api/v2/controllers/actions.py +183 -0
  15. nfv_test_api/v2/controllers/common.py +30 -0
  16. nfv_test_api/v2/controllers/enodeb.py +292 -0
  17. nfv_test_api/v2/controllers/gnodeb.py +287 -0
  18. nfv_test_api/v2/controllers/instance.py +76 -0
  19. nfv_test_api/v2/controllers/interface.py +250 -0
  20. nfv_test_api/v2/controllers/namespace.py +140 -0
  21. nfv_test_api/v2/controllers/proxy.py +130 -0
  22. nfv_test_api/v2/controllers/route.py +314 -0
  23. nfv_test_api/v2/controllers/ue_4g.py +283 -0
  24. nfv_test_api/v2/controllers/ue_5g.py +276 -0
  25. nfv_test_api/v2/data/__init__.py +15 -0
  26. nfv_test_api/v2/data/base_model.py +68 -0
  27. nfv_test_api/v2/data/common.py +92 -0
  28. nfv_test_api/v2/data/enodeb.py +59 -0
  29. nfv_test_api/v2/data/gnodeb.py +84 -0
  30. nfv_test_api/v2/data/instance.py +69 -0
  31. nfv_test_api/v2/data/interface.py +157 -0
  32. nfv_test_api/v2/data/iperf.py +42 -0
  33. nfv_test_api/v2/data/namespace.py +46 -0
  34. nfv_test_api/v2/data/ping.py +47 -0
  35. nfv_test_api/v2/data/route.py +108 -0
  36. nfv_test_api/v2/data/ue_4g.py +57 -0
  37. nfv_test_api/v2/data/ue_5g.py +156 -0
  38. nfv_test_api/v2/services/__init__.py +15 -0
  39. nfv_test_api/v2/services/actions.py +179 -0
  40. nfv_test_api/v2/services/base_service.py +72 -0
  41. nfv_test_api/v2/services/bond_interface.py +68 -0
  42. nfv_test_api/v2/services/enodeb.py +268 -0
  43. nfv_test_api/v2/services/gnodeb.py +284 -0
  44. nfv_test_api/v2/services/instance.py +338 -0
  45. nfv_test_api/v2/services/interface.py +377 -0
  46. nfv_test_api/v2/services/namespace.py +155 -0
  47. nfv_test_api/v2/services/route.py +162 -0
  48. nfv_test_api/v2/services/ue_4g.py +259 -0
  49. nfv_test_api/v2/services/ue_5g.py +261 -0
  50. nfv_test_api/v2/services/vlan_interface.py +105 -0
  51. pytest_nfv_test_api/__init__.py +157 -0
  52. pytest_nfv_test_api/py.typed +0 -0
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.4
2
+ Name: inmanta-nfv-test-api
3
+ Version: 2.8.0
4
+ Summary: API for testing network functions.
5
+ Author: Inmanta
6
+ Author-email: code@inmanta.com
7
+ License: Apache-2.0
8
+ Requires-Dist: Flask<3
9
+ Requires-Dist: PyYAML
10
+ Requires-Dist: flask-cors
11
+ Requires-Dist: flask-restx
12
+ Requires-Dist: flask-apispec
13
+ Requires-Dist: click
14
+ Requires-Dist: pingparsing
15
+ Requires-Dist: trparse
16
+ Requires-Dist: werkzeug
17
+ Requires-Dist: apispec
18
+ Requires-Dist: requests
19
+ Requires-Dist: pydantic>=2
@@ -0,0 +1,52 @@
1
+ nfv_test_api/__init__.py,sha256=dsL9JL48UNTa5hWnDmrFDCOLsznGHq8dm-50ls9f1gw,560
2
+ nfv_test_api/config.py,sha256=6BLqGRZC4Qfuf1ZKiprN52txEYWd0ZPMaYUitph3ViI,4517
3
+ nfv_test_api/exceptions.py,sha256=TVIBuPTLnv5X8eVeuBNhekNUUuNOzRao-sXQAqjKJV8,601
4
+ nfv_test_api/host.py,sha256=OT2XbDV6SulN-ADob7ZJs4OHQcjhHZlDH_q8LMm_Qd4,2228
5
+ nfv_test_api/main.py,sha256=FReu9nCb5dcZERATJVp7kdfVnFhIYUD8fTy0bFA8vO4,2882
6
+ nfv_test_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ nfv_test_api/v2/__init__.py,sha256=lbT4iHFiuIYJ9ZeUnBlSNOuiFRR3RbDlmt2acC_owFI,5616
8
+ nfv_test_api/v2/controllers/__init__.py,sha256=dsL9JL48UNTa5hWnDmrFDCOLsznGHq8dm-50ls9f1gw,560
9
+ nfv_test_api/v2/controllers/actions.py,sha256=snsudoU3nCKGFNtAJ0eicmNEtK6gmUQp6q3nDtRq6Ao,6730
10
+ nfv_test_api/v2/controllers/common.py,sha256=Yz6rDbXFrePiua3BxSqoUgH2pzch5KlkM09aWFzkBrk,953
11
+ nfv_test_api/v2/controllers/enodeb.py,sha256=qS_Gto8PazhBlqRPwL0ZI5OPztFpch1HnXzjK-JDJVo,9543
12
+ nfv_test_api/v2/controllers/gnodeb.py,sha256=XgGXUcULAiMFCOqrxr0xC3lL13d1svyKKeku8zYVMqU,9319
13
+ nfv_test_api/v2/controllers/instance.py,sha256=5kF_WZETE6F4r1KZiDA18aYEVi_v8v0jUA47K-3mtEQ,2691
14
+ nfv_test_api/v2/controllers/interface.py,sha256=VCIEAAyNRr4b4zdwrUc1IyVaDxxWlJPEQ3ciXmH0Sco,8934
15
+ nfv_test_api/v2/controllers/namespace.py,sha256=bQwsaQWCGcfUhDAYhat8nRZDQqkYVfrjuIk7gLMa7LA,4788
16
+ nfv_test_api/v2/controllers/proxy.py,sha256=lvo1pR_9Z70I3KwYue4MR54L4DPfptVTu-rZfvrBUGM,4785
17
+ nfv_test_api/v2/controllers/route.py,sha256=wnKxkiEDpWPGvZQ-9I3UU-rH1q6Lzk8FB2A0Xy8_lk0,10795
18
+ nfv_test_api/v2/controllers/ue_4g.py,sha256=gcJxZyBlwLvIiAm2i8Sg8PsT5WuHQEhPRDcrR2s9EBE,9101
19
+ nfv_test_api/v2/controllers/ue_5g.py,sha256=mF9us7OazRw1yx7Sli2hYOUtwmXRkLhRZHYLCOb-tgw,8955
20
+ nfv_test_api/v2/data/__init__.py,sha256=dsL9JL48UNTa5hWnDmrFDCOLsznGHq8dm-50ls9f1gw,560
21
+ nfv_test_api/v2/data/base_model.py,sha256=b9q92RfpxFbuGHnrl0UD3TNTVRBShVlVW1jotBYVZzw,2015
22
+ nfv_test_api/v2/data/common.py,sha256=D1FuPdg9trX31AXkaFqKyFR2UFOuPlwploiRn2FUTMk,2459
23
+ nfv_test_api/v2/data/enodeb.py,sha256=k3yMVuywEbEFHlv1bbyFXqS_cUnXjvrnS567svMkqoM,1391
24
+ nfv_test_api/v2/data/gnodeb.py,sha256=E1VuhxzVLf5BPNVrRavxe8wjcIvqOyrA5N1GT5ULI5E,2186
25
+ nfv_test_api/v2/data/instance.py,sha256=wYzPCPnxu17COrQoC0fPhI5vEchf-gShLteJCKZcy14,2196
26
+ nfv_test_api/v2/data/interface.py,sha256=KMfUwEzTvbHPtVZaV8x8NNZMzooI_XrMx23EHNqVCHU,4564
27
+ nfv_test_api/v2/data/iperf.py,sha256=NtwcnlD18gyyYT2DO80_VZQw8DtHSa3_uMeI5KTQvx0,1221
28
+ nfv_test_api/v2/data/namespace.py,sha256=4Z9iBu_HHqDvdnBQWhsl7ZR7GbbfNXJFmMWxHJpuS5w,1211
29
+ nfv_test_api/v2/data/ping.py,sha256=_gnBbGmugCxVOzqlHiI534YqHThixSFvxFY_q4WkbCY,1614
30
+ nfv_test_api/v2/data/route.py,sha256=ehDkxRCvg_oCahIcVWXofyjwUNcOPUsq0XGvGM2hsFY,3238
31
+ nfv_test_api/v2/data/ue_4g.py,sha256=77qL-EMRft1H7VcwvhMvArW61Edsp8YHQE8N4-T_pTI,1495
32
+ nfv_test_api/v2/data/ue_5g.py,sha256=SHAhMOzwPfGRiQ-CteNxVomZVlnAReAmec2UFIpT6Z8,2925
33
+ nfv_test_api/v2/services/__init__.py,sha256=dsL9JL48UNTa5hWnDmrFDCOLsznGHq8dm-50ls9f1gw,560
34
+ nfv_test_api/v2/services/actions.py,sha256=89fDj8oO0UG-5h8Ur4_k_ZOxACDR9Qd_SJJtMFjaYLE,5623
35
+ nfv_test_api/v2/services/base_service.py,sha256=xRZEuyXX8Eg8qcCP3uFWZRRYExJTg4Jck_orh0NN2CQ,1889
36
+ nfv_test_api/v2/services/bond_interface.py,sha256=yOmGP1nxKaSyzeth4EqYahCUSw2zbEuUufdaLxEoWTA,2373
37
+ nfv_test_api/v2/services/enodeb.py,sha256=k8UkwP-3v-d82OuFySAtJYLHUkc_PjgCxFgx94Yqrm0,9407
38
+ nfv_test_api/v2/services/gnodeb.py,sha256=SctOGruwP5ve2ENzd7LX_Kuezntdkfpl_ZaAWNtwTQA,9996
39
+ nfv_test_api/v2/services/instance.py,sha256=O4OKqAjyM8g0TFf9i__lubUuL1iZ9j-n9eP3yB6f7BM,12857
40
+ nfv_test_api/v2/services/interface.py,sha256=B7LGL_9EvmpKbudg7ia8KiFmP-x0vYXI8_sVNDhAUSw,12431
41
+ nfv_test_api/v2/services/namespace.py,sha256=MUQbXTLqyzSlcLn0s4wyCx1Jh-qn7ZadESN-4ktNkXI,5645
42
+ nfv_test_api/v2/services/route.py,sha256=D2CAIsKuhuuC4YgoosBPqSQPw7tIxYJHjMC1H_Jk1XE,5537
43
+ nfv_test_api/v2/services/ue_4g.py,sha256=dkH-f4Esmdj33zjTFqG082OHq-tTfLbTwon0mp9B2pw,8918
44
+ nfv_test_api/v2/services/ue_5g.py,sha256=y4_hlXd-yJcxgpzDT0xhb0WxLplTnicgc9_ggLUixGM,8878
45
+ nfv_test_api/v2/services/vlan_interface.py,sha256=ht1vyYX46TyksqESzMIOopxo8EhqRCTFivl0UGu0B7c,3732
46
+ pytest_nfv_test_api/__init__.py,sha256=P6RdxWMnxLI-Bj9o-S3v7bJ72T9nDssnoAZpGkeZW1Y,4569
47
+ pytest_nfv_test_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
48
+ inmanta_nfv_test_api-2.8.0.dist-info/METADATA,sha256=MT04pFhwUtldunXBC0XFEz8kfOogr8uCjdm7GPu61XQ,471
49
+ inmanta_nfv_test_api-2.8.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
50
+ inmanta_nfv_test_api-2.8.0.dist-info/entry_points.txt,sha256=9ZuIvkWeU3nt7ghxpO6toEox_vUWkVHtqL7cAZhi_wk,103
51
+ inmanta_nfv_test_api-2.8.0.dist-info/top_level.txt,sha256=aKVSAhh0Z6ZOER9XkZZjDZIawXS6agD5Ex_AKWeh538,33
52
+ inmanta_nfv_test_api-2.8.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ nfv-test-api = nfv_test_api.main:main
3
+
4
+ [pytest11]
5
+ nfv_test_api = pytest_nfv_test_api
@@ -0,0 +1,2 @@
1
+ nfv_test_api
2
+ pytest_nfv_test_api
@@ -0,0 +1,15 @@
1
+ """
2
+ Copyright 2021 Inmanta
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
nfv_test_api/config.py ADDED
@@ -0,0 +1,126 @@
1
+ """
2
+ Copyright 2021 Inmanta
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ import os
18
+ import pathlib
19
+ from typing import Any, Dict, Optional
20
+
21
+ import yaml
22
+ from pydantic import BaseModel, Field
23
+
24
+
25
+ def env_flag(name: str, default: bool) -> bool:
26
+ raw = os.environ.get(name)
27
+ if raw is None:
28
+ return default
29
+ return raw.strip().lower() not in ("0", "false", "no", "off")
30
+
31
+
32
+ class Config(BaseModel):
33
+ host: str = "127.0.0.1"
34
+ port: int = 8080
35
+ # Directory with the built web UI (Vite `dist`) to serve. When unset, the
36
+ # NFV_TEST_API_WEB_UI environment variable is used as a fallback; if neither
37
+ # points at an existing directory, the UI is simply not served.
38
+ web_ui_path: Optional[str] = None
39
+ # Name of this instance, shown in the web UI and advertised to other
40
+ # instances via discovery. Defaults to the NFV_TEST_API_INSTANCE_NAME
41
+ # environment variable, or the hostname (= the container/node name in
42
+ # docker and containerlab) when unset.
43
+ instance_name: Optional[str] = Field(
44
+ default_factory=lambda: os.environ.get("NFV_TEST_API_INSTANCE_NAME")
45
+ )
46
+ # Discover other instances by broadcasting UDP beacons on the management
47
+ # network (the interface holding the default route). Set the
48
+ # NFV_TEST_API_DISCOVERY environment variable to "false" to disable.
49
+ discovery_enabled: bool = Field(
50
+ default_factory=lambda: env_flag("NFV_TEST_API_DISCOVERY", True)
51
+ )
52
+ # Instances only see peers in the same discovery group. Set this (or the
53
+ # NFV_TEST_API_DISCOVERY_GROUP environment variable) when multiple labs
54
+ # share the same L2 management network.
55
+ discovery_group: str = Field(
56
+ default_factory=lambda: os.environ.get("NFV_TEST_API_DISCOVERY_GROUP", "")
57
+ )
58
+ discovery_port: int = Field(
59
+ default_factory=lambda: int(
60
+ os.environ.get("NFV_TEST_API_DISCOVERY_PORT", "41963")
61
+ )
62
+ )
63
+ discovery_interval: float = 5.0
64
+ gnb_config_folder: str = "gnb_config/"
65
+ gnb_log_folder: str = "gnb_log/"
66
+ ue_5g_config_folder: str = "ue_5g_config/"
67
+ ue_5g_log_folder: str = "ue_5g_log/"
68
+ enb_config_folder: str = "enb_config/"
69
+ enb_log_folder: str = "enb_log/"
70
+ ue_4g_config_folder: str = "ue_4g_config/"
71
+ ue_4g_log_folder: str = "ue_4g_log/"
72
+ iperf_folder: str = "iperf/"
73
+
74
+
75
+ CONFIG = None
76
+
77
+
78
+ def get_config(
79
+ config_file: Optional[str] = None,
80
+ config_dict: Optional[Dict[str, Any]] = None,
81
+ ) -> Config:
82
+ global CONFIG
83
+ if CONFIG is not None:
84
+ return CONFIG
85
+
86
+ if config_dict is None:
87
+ default_path = "/etc/nfv-test-api.yaml"
88
+ path_config_file = config_file if config_file is not None else default_path
89
+ with open(path_config_file, "r") as stream:
90
+ config_dict = yaml.safe_load(stream)
91
+
92
+ CONFIG = Config(**config_dict)
93
+
94
+ # create gnb folders
95
+ gnb_config_folder = pathlib.Path(CONFIG.gnb_config_folder)
96
+ gnb_config_folder.mkdir(parents=True, exist_ok=True)
97
+
98
+ gnb_log_folder = pathlib.Path(CONFIG.gnb_log_folder)
99
+ gnb_log_folder.mkdir(parents=True, exist_ok=True)
100
+
101
+ # create 5g ue folders
102
+ ue_5g_config_folder = pathlib.Path(CONFIG.ue_5g_config_folder)
103
+ ue_5g_config_folder.mkdir(parents=True, exist_ok=True)
104
+
105
+ ue_5g_log_folder = pathlib.Path(CONFIG.ue_5g_log_folder)
106
+ ue_5g_log_folder.mkdir(parents=True, exist_ok=True)
107
+
108
+ # create enb folders
109
+ enb_config_folder = pathlib.Path(CONFIG.enb_config_folder)
110
+ enb_config_folder.mkdir(parents=True, exist_ok=True)
111
+
112
+ enb_log_folder = pathlib.Path(CONFIG.enb_log_folder)
113
+ enb_log_folder.mkdir(parents=True, exist_ok=True)
114
+
115
+ # create 5g ue folders
116
+ ue_4g_config_folder = pathlib.Path(CONFIG.ue_4g_config_folder)
117
+ ue_4g_config_folder.mkdir(parents=True, exist_ok=True)
118
+
119
+ ue_4g_log_folder = pathlib.Path(CONFIG.ue_4g_log_folder)
120
+ ue_4g_log_folder.mkdir(parents=True, exist_ok=True)
121
+
122
+ # create iperf folder
123
+ iperf_folder = pathlib.Path(CONFIG.iperf_folder)
124
+ iperf_folder.mkdir(parents=True, exist_ok=True)
125
+
126
+ return CONFIG
@@ -0,0 +1,19 @@
1
+ """
2
+ Copyright 2021 Inmanta
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+
18
+ class ServerError(Exception):
19
+ pass
nfv_test_api/host.py ADDED
@@ -0,0 +1,64 @@
1
+ """
2
+ Copyright 2021 Inmanta
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ import logging
18
+ import subprocess
19
+ from typing import List, Optional, Tuple
20
+
21
+ LOGGER = logging.getLogger(__name__)
22
+
23
+
24
+ class Host:
25
+ def __init__(self, shell_entry_point: List[str] = []) -> None:
26
+ self._shell_entry_point = shell_entry_point
27
+
28
+ def exec(self, command: List[str], timeout: Optional[int] = 10) -> Tuple[str, str]:
29
+ cmd = self._shell_entry_point + command
30
+ LOGGER.debug("Running command %s", cmd)
31
+ process = subprocess.Popen(
32
+ cmd,
33
+ shell=False,
34
+ universal_newlines=True,
35
+ stdout=subprocess.PIPE,
36
+ stderr=subprocess.PIPE,
37
+ )
38
+ try:
39
+ # Make sure our command terminates.
40
+ # We set a hard timeout of 10 seconds, it should work for all
41
+ # the commands we run. If it doesn't, we can create a more
42
+ # elaborate mechanism.
43
+ return process.communicate(timeout=timeout)
44
+ except subprocess.TimeoutExpired:
45
+ # Kill the process and return the output we had so far
46
+ process.terminate()
47
+ return process.communicate(timeout=1)
48
+
49
+ def hostname(self) -> str:
50
+ stdout, stderr = self.exec(["hostname"])
51
+ if stderr:
52
+ raise RuntimeError(f"Failed to run hostname command on host: {stderr}")
53
+
54
+ return stdout.strip()
55
+
56
+
57
+ class NamespaceHost(Host):
58
+ def __init__(self, namespace: str) -> None:
59
+ super().__init__(shell_entry_point=["ip", "netns", "exec", namespace])
60
+
61
+ def get_raw_namespaces(self) -> List[object]:
62
+ raise NotImplementedError(
63
+ "You shouldn't try to interact with namespaces from inside another one"
64
+ )
nfv_test_api/main.py ADDED
@@ -0,0 +1,98 @@
1
+ """
2
+ Copyright 2021 Inmanta
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ import logging
18
+ import os
19
+ from typing import Optional
20
+
21
+ import click # type: ignore
22
+ from flask import Flask, send_from_directory # type: ignore
23
+ from flask_cors import CORS # type: ignore
24
+ from werkzeug.exceptions import NotFound # type: ignore
25
+
26
+ from nfv_test_api.config import get_config
27
+ from nfv_test_api.v2 import blueprint as controllers
28
+ from nfv_test_api.v2.services.instance import get_instance_manager
29
+
30
+ app = Flask(__name__)
31
+ CORS(app)
32
+ app.config["RESTPLUS_MASK_SWAGGER"] = False
33
+ app.register_blueprint(controllers)
34
+
35
+ # Notes:
36
+ # * Static content available on /static
37
+
38
+
39
+ LOGGER = logging.getLogger(__name__)
40
+
41
+
42
+ def get_web_ui_dir() -> Optional[str]:
43
+ """
44
+ Resolve the directory containing the built web UI (the Vite `dist` output),
45
+ or None when the UI should not be served.
46
+
47
+ The `web_ui_path` config option takes precedence, with the
48
+ NFV_TEST_API_WEB_UI environment variable as a fallback.
49
+ """
50
+ path = os.environ.get("NFV_TEST_API_WEB_UI")
51
+ try:
52
+ configured = get_config().web_ui_path
53
+ except Exception:
54
+ # Config not loaded yet (e.g. imported by a WSGI server before main());
55
+ # fall back to the environment variable only.
56
+ configured = None
57
+ if configured:
58
+ path = configured
59
+
60
+ if path and os.path.isdir(path):
61
+ return path
62
+ return None
63
+
64
+
65
+ @app.route("/")
66
+ @app.route("/<path:path>")
67
+ def serve_web_ui(path: str = ""):
68
+ """
69
+ Serve the single-page web UI.
70
+
71
+ Existing files (the JS/CSS/asset bundles) are served directly; every other
72
+ path falls back to index.html so the client-side router can take over. API
73
+ requests are handled by the blueprint and are never shadowed here.
74
+ """
75
+ ui_dir = get_web_ui_dir()
76
+ if ui_dir is None:
77
+ raise NotFound()
78
+
79
+ # Don't let the SPA fallback swallow unmatched API requests.
80
+ if path.startswith("api/"):
81
+ raise NotFound()
82
+
83
+ if path and os.path.isfile(os.path.join(ui_dir, path)):
84
+ return send_from_directory(ui_dir, path)
85
+
86
+ return send_from_directory(ui_dir, "index.html")
87
+
88
+
89
+ @click.command()
90
+ @click.option("--config", help="The configuration file to use")
91
+ def main(config):
92
+ cfg = get_config(config)
93
+ get_instance_manager().start_discovery()
94
+ app.run(host=cfg.host, port=cfg.port, threaded=True)
95
+
96
+
97
+ if __name__ == "__main__":
98
+ main()
nfv_test_api/py.typed ADDED
File without changes
@@ -0,0 +1,152 @@
1
+ """
2
+ Copyright 2021 Inmanta
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ import logging
18
+ from typing import Optional, TypeVar
19
+
20
+ import requests # type: ignore
21
+ from flask import Blueprint # type: ignore
22
+ from flask_restx import Api # type: ignore
23
+ from requests.models import HTTPError # type: ignore
24
+ from werkzeug.exceptions import ServiceUnavailable # type: ignore
25
+
26
+ from nfv_test_api.v2.controllers.actions import namespace as actions_ns
27
+ from nfv_test_api.v2.controllers.enodeb import namespace as enb_ns
28
+ from nfv_test_api.v2.controllers.gnodeb import namespace as gnb_ns
29
+ from nfv_test_api.v2.controllers.instance import namespace as instance_ns
30
+ from nfv_test_api.v2.controllers.interface import namespace as interface_ns
31
+ from nfv_test_api.v2.controllers.namespace import namespace as namespace_ns
32
+ from nfv_test_api.v2.controllers.proxy import namespace as proxy_ns
33
+ from nfv_test_api.v2.controllers.route import namespace as route_ns
34
+ from nfv_test_api.v2.controllers.ue_4g import namespace as ue_4g_ns
35
+ from nfv_test_api.v2.controllers.ue_5g import namespace as ue_5g_ns
36
+
37
+ LOGGER = logging.getLogger(__name__)
38
+
39
+ blueprint = Blueprint("api v2", __name__, url_prefix="/api/v2")
40
+
41
+ api_extension = Api(
42
+ blueprint,
43
+ title="NFV Test API",
44
+ version="1.0",
45
+ description="Test api for client side network operations",
46
+ doc="/docs",
47
+ )
48
+
49
+ api_extension.add_namespace(namespace_ns)
50
+ api_extension.add_namespace(instance_ns)
51
+ api_extension.add_namespace(proxy_ns)
52
+ api_extension.add_namespace(interface_ns)
53
+ api_extension.add_namespace(route_ns)
54
+ api_extension.add_namespace(actions_ns)
55
+ api_extension.add_namespace(gnb_ns)
56
+ api_extension.add_namespace(ue_5g_ns)
57
+ api_extension.add_namespace(enb_ns)
58
+ api_extension.add_namespace(ue_4g_ns)
59
+
60
+ # Ugly patches to force openapi 3.0
61
+ from flask_restx.swagger import Swagger # type: ignore # noqa: E402
62
+
63
+ as_dict = Swagger.as_dict
64
+
65
+ T = TypeVar("T", list, dict, str, int, float, bool, bytes, object)
66
+ """
67
+ This type var will be used in replace_ref function. It indicates that for any input
68
+ type given the :param schema:, the same type will be returned. This is not true for
69
+ dict and list, as any subclass of dict and list will be converted to dict and list.
70
+ To workaround the type checking, and as we never expect anything else than List, Dict
71
+ or primitive types, we set them directly in the type var possible types.
72
+ """
73
+
74
+
75
+ def replace_ref(schema: T, schema_prefix: str) -> T:
76
+ """
77
+ Return the same schema as given in input, with all the reference transformed to have the
78
+ provided prefix. What comes after the prefix is the last part of the prefix reference.
79
+ The schema contains a reference if it is a dict, with a key "$ref".
80
+
81
+ :param schema: A schema to recursively search references in
82
+ :param schema_prefix: The new prefix to set
83
+ """
84
+ if isinstance(schema, list):
85
+ return [replace_ref(item, schema_prefix) for item in schema]
86
+
87
+ if isinstance(schema, dict):
88
+ if "$ref" in schema:
89
+ schema["$ref"] = schema_prefix + schema["$ref"].split("/")[-1]
90
+ return schema
91
+
92
+ return { # type: ignore
93
+ key: replace_ref(value, schema_prefix) for key, value in schema.items()
94
+ }
95
+
96
+ return schema
97
+
98
+
99
+ def as_dict_overwrite(self):
100
+ d = as_dict(self)
101
+
102
+ # Extract all the entity definitions that we have, even the nested ones
103
+ definitions = dict()
104
+
105
+ def extract_definitions(definition: dict, title: Optional[str] = None) -> None:
106
+ if title and title not in definitions:
107
+ definitions[title] = {
108
+ key: value for key, value in definition.items() if key != "definitions"
109
+ }
110
+
111
+ for t, d in definition.get("definitions", dict()).items():
112
+ extract_definitions(d, t)
113
+
114
+ extract_definitions(d)
115
+
116
+ # Place all the definitions in the definitions dict
117
+ for title, definition in definitions.items():
118
+ d["definitions"][title] = definition
119
+
120
+ # Replacing all wrong references
121
+ new_dict = replace_ref(d, "#/definitions/")
122
+
123
+ try:
124
+ # Converting the model to openapi 3 using swagger converter
125
+ response = requests.post(
126
+ "https://converter.swagger.io/api/convert",
127
+ json=new_dict,
128
+ headers={"content-type": "application/json"},
129
+ )
130
+ response.raise_for_status()
131
+ except HTTPError as e:
132
+ LOGGER.error(str(e))
133
+ raise ServiceUnavailable(
134
+ "Failed to convert the schema to openapi 3. "
135
+ "This is likely because this server is not connected to the internet. "
136
+ "Please check server logs for more details."
137
+ )
138
+
139
+ new_dict = response.json()
140
+
141
+ # In the conversion, we loose all of the "anyOf" in our schemas, so we set our old schemas back
142
+ # The place where they should go has changed with the new format
143
+ for title, definition in definitions.items():
144
+ new_dict["components"]["schemas"][title] = definition
145
+
146
+ # We replace the references again, with the new path where the definitions are located
147
+ new_dict = replace_ref(new_dict, "#/components/schemas/")
148
+
149
+ return new_dict
150
+
151
+
152
+ Swagger.as_dict = as_dict_overwrite
@@ -0,0 +1,15 @@
1
+ """
2
+ Copyright 2021 Inmanta
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """