af136a2fb90b4ee575e43291bce64bb41bd570da
[it/dep.git] / smo-install / test / pythonsdk / src / orantests / smo / network_simulators.py
1 #!/usr/bin/env python3
2 ###
3 # ============LICENSE_START=======================================================
4 # ORAN SMO PACKAGE - PYTHONSDK TESTS
5 # ================================================================================
6 # Copyright (C) 2021-2022 AT&T Intellectual Property. All rights
7 #                             reserved.
8 # ================================================================================
9 # Licensed under the Apache License, Version 2.0 (the "License");
10 # you may not use this file except in compliance with the License.
11 # You may obtain a copy of the License at
12 #
13 # http://www.apache.org/licenses/LICENSE-2.0
14 #
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS,
17 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 # See the License for the specific language governing permissions and
19 # limitations under the License.
20 # ============LICENSE_END============================================
21 # ===================================================================
22 #
23 ###
24
25 """NetworkSimulators module."""
26 import logging
27 import logging.config
28 import json
29 from subprocess import check_output, run
30 import sys
31 import requests
32 from onapsdk.configuration import settings
33 from waiting import wait
34
35 logging.config.dictConfig(settings.LOG_CONFIG)
36 logger = logging.getLogger("Network Simulators k8s")
37
38 class NetworkSimulators():
39     """Network simulators controls the simulators k8s deployment."""
40
41     resources_path = ""
42
43     def __init__(self, resources_dir):
44         """Create NetworkSimulators class."""
45         self.resources_path = resources_dir
46
47     def start_network_simulators(self):
48         """Start all simulators defined in resources_path."""
49         logger.info("Start the network simulators")
50         cmd = "kubectl create namespace network"
51         check_output(cmd, shell=True).decode('utf-8')
52         cmd = f"helm install --debug oran-simulator local/ru-du-simulators --namespace network -f {self.resources_path}/network-simulators-topology/network-simulators-override.yaml -f {self.resources_path}/network-simulators-topology/network-simulators-topology-override.yaml"
53         check_output(cmd, shell=True).decode('utf-8')
54
55     @staticmethod
56     def get_all_simulators():
57         """Retrieve all simulators defined in k8s services."""
58         dockerFilter = check_output("kubectl get services -n network -o name | awk -F \"/\" '{print $2}'", shell=True)
59         return dockerFilter.splitlines()
60
61     @staticmethod
62     def stop_network_simulators():
63         """Stop the simulators."""
64         logger.info("Clean up any network simulators")
65         cmd = "kubectl delete namespace network"
66         run(cmd, shell=True, check=False)
67
68     @staticmethod
69     def is_network_simulators_up() -> bool:
70         """Check if the network simulators are up."""
71         cmd = "kubectl get pods --field-selector status.phase!=Running -n network"
72         result = check_output(cmd, shell=True).decode('utf-8')
73         logger.info("Checking if network simulators is UP: %s", result)
74         if result == '':
75             logger.info("Network sims is Up")
76             return True
77         logger.info("Network sims is Down")
78         return False
79
80     def update_event_settings(self, nfName, nfType):
81         """Send one event for specific simulator of a specific type."""
82         file = f'{self.resources_path}/faults-config/event-settings-'+nfType+'.json'
83         logger.info("Faults parameters path: %s", file)
84         with open(file) as json_file:
85             body = json.load(json_file)
86             url = settings.SDNC_URL + '/rests/data/network-topology:network-topology/topology=topology-netconf/node=' + nfName + '/yang-ext:mount/nts-network-function:simulation/network-function'
87             logger.info("Using SDNC URL: %s", url)
88             headers = {
89                 'content-type': 'application/yang-data+json',
90                 'accept': 'application/yang-data+json',
91                 'Authorization' : settings.SDNC_AUTH
92             }
93             try:
94                 response = requests.put(url, verify=False, json=body, headers=headers)
95                 logger.info("Response: %s", str(response))
96             except requests.exceptions.Timeout:
97                 sys.exit('HTTP request failed, please check you internet connection.')
98             except requests.exceptions.TooManyRedirects:
99                 sys.exit('HTTP request failed, please check your proxy settings.')
100             except requests.exceptions.RequestException as e:
101                 raise SystemExit(e)
102             return response.status_code >= 200 and response.status_code < 300
103
104     def enable_events_for_all_simulators(self):
105         """Send event to sdnc for all sim containers."""
106         for container in NetworkSimulators.get_all_simulators():
107             name = container.decode("utf-8")
108             if "o-" in name:
109                 if "o-ru" in name:
110                     logger.info("Set %s %s", name, self.update_event_settings(name, "ru"))
111                 if "o-du" in name:
112                     logger.info("Set %s %s", name, self.update_event_settings(name, "du"))
113
114     @staticmethod
115     def wait_for_network_simulators_to_be_running():
116         """Check and wait for the network sims to be running."""
117         wait(lambda: NetworkSimulators.is_network_simulators_up(), sleep_seconds=10, timeout_seconds=60, waiting_for="Network simulators to be ready")