Fix/add use cases under SMO package
[it/dep.git] / smo-install / test / pythonsdk / src / oransdk / utils / healthcheck.py
1 #!/usr/bin/env python3
2 ###
3 # ============LICENSE_START=======================================================
4 # ORAN SMO PACKAGE - PYTHONSDK TESTS
5 # ================================================================================
6 # Copyright (C) 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 """Module called by pytest."""
25 import logging
26 import logging.config
27
28 from subprocess import check_output, run
29 from requests import RequestException
30 from onapsdk.configuration import settings
31 from onapsdk.exceptions import ConnectionFailed, APIError
32 from urllib3.exceptions import NewConnectionError
33 from oransdk.aai.aai import Aai
34 from oransdk.msb.msb_microservice import OranMsb
35 from oransdk.oof.oof import Oof
36 from oransdk.policy.clamp import ClampToscaTemplate
37 from oransdk.policy.policy import OranPolicy
38 from oransdk.sdc.sdc import SdcTemplate
39 from oransdk.sdnc.sdnc import OranSdnc
40 from oransdk.so.so import OranSo
41
42 logging.config.dictConfig(settings.LOG_CONFIG)
43 logger = logging.getLogger("Health check")
44
45 clamp = ClampToscaTemplate(settings.CLAMP_BASICAUTH)
46 sdnc = OranSdnc()
47 policy = OranPolicy()
48 aai = Aai()
49 sdc = SdcTemplate()
50 so = OranSo()
51 msb = OranMsb()
52 oof = Oof()
53
54 class HealthCheck():
55     """Healthcheck class for ONAP component."""
56
57     @classmethod
58     def is_onap_up(cls, up_no) -> bool:
59         """Verify if ONAP platform is up or not."""
60         cmd = "kubectl get pods --field-selector 'status.phase=Failed' -n onap -o name | xargs kubectl delete -n onap"
61         run(cmd, shell=True, check=False)
62         cmd = "kubectl get pods --field-selector status.phase!=Running -n onap | wc -l"
63         result = check_output(cmd, shell=True).decode('utf-8')
64         logger.info("Number of Onap pods not in Running state (expected <= %s): %s", up_no, result)
65         if int(result) <= up_no:
66             logger.info("ONAP is Up")
67             return True
68         logger.info("ONAP is Down")
69         return False
70
71     @classmethod
72     def policy_component_ready(cls):
73         """Check if Policy components are ready."""
74         logger.info("Verify Policy components are ready")
75         try:
76             policy_ready = {"api_ready": False, "pap_ready": False, "apex_ready": False}
77         except (RequestException, NewConnectionError, ConnectionFailed, APIError) as e:
78             logger.error(e)
79             return False
80         policy_status = policy.get_components_status(settings.POLICY_BASICAUTH)
81         if (policy_status["api"]["healthy"] and not policy_ready["api_ready"]):
82             logger.info("Policy Api is ready")
83             policy_ready["api_ready"] = True
84         if (policy_status["pap"]["healthy"] and not policy_ready["pap_ready"]):
85             logger.info("Policy Pap is ready")
86             policy_ready["pap_ready"] = True
87         if (len(policy_status["pdps"]["apex"]) > 0 and policy_status["pdps"]["apex"][0]["healthy"] == "HEALTHY" and not policy_ready["apex_ready"]):
88             logger.info("Policy Apex is ready")
89             policy_ready["apex_ready"] = True
90         return policy_ready["api_ready"] and policy_ready["pap_ready"] and policy_ready["apex_ready"]
91
92     @classmethod
93     def sdnc_component_ready(cls):
94         """Check if SDNC component is ready."""
95         logger.info("Verify SDNC component is ready")
96
97         try:
98             response = OranSdnc.get_events(settings.SDNC_BASICAUTH, "test")
99         except (RequestException, NewConnectionError, ConnectionFailed, APIError) as e:
100             logger.error(e)
101             return False
102         return response.status_code == 200
103
104     @classmethod
105     def clamp_component_ready(cls):
106         """Check if Clamp component is ready."""
107         logger.info("Verify Clamp component is ready")
108         try:
109             response = clamp.get_template_instance()
110         except (RequestException, NewConnectionError, ConnectionFailed, APIError) as e:
111             logger.error(e)
112             return False
113         return response["automationCompositionList"] is not None
114
115     @classmethod
116     def sdc_component_ready(cls):
117         """Check if SDC component is ready."""
118         logger.info("Verify SDC component is ready")
119
120         try:
121             response = sdc.healthcheck()
122         except (RequestException, NewConnectionError, ConnectionFailed, APIError) as e:
123             logger.error(e)
124             return False
125
126         so_ready = {"BE": False, "CASSANDRA": False, "ON_BOARDING": False, "JANUSGRAPH": False}
127         so_list = response["componentsInfo"]
128         for so_status in so_list:
129             if (so_status["healthCheckComponent"] == "BE" and so_status["healthCheckStatus"] == "UP"):
130                 so_ready["BE"] = True
131             if (so_status["healthCheckComponent"] == "CASSANDRA" and so_status["healthCheckStatus"] == "UP"):
132                 so_ready["CASSANDRA"] = True
133             if (so_status["healthCheckComponent"] == "ON_BOARDING" and so_status["healthCheckStatus"] == "UP"):
134                 so_ready["ON_BOARDING"] = True
135             if (so_status["healthCheckComponent"] == "JANUSGRAPH" and so_status["healthCheckStatus"] == "UP"):
136                 so_ready["JANUSGRAPH"] = True
137
138         return so_ready["BE"] and so_ready["CASSANDRA"] and so_ready["ON_BOARDING"] and so_ready["JANUSGRAPH"]
139
140     @classmethod
141     def aai_component_ready(cls):
142         """Check if AAI component is ready."""
143         logger.info("Verify AAI component is ready")
144
145         try:
146             response = aai.healthcheck()
147         except (RequestException, NewConnectionError, ConnectionFailed, APIError) as e:
148             logger.error(e)
149             return False
150         return "Successful health check:OK" in str(response)
151
152     @classmethod
153     def so_component_ready(cls):
154         """Check if SO component is ready."""
155         logger.info("Verify SO component is ready")
156
157         try:
158             response = so.healthcheck()
159         except (RequestException, NewConnectionError, ConnectionFailed, APIError) as e:
160             logger.error(e)
161             return False
162         return response["status"] == "UP"
163
164     @classmethod
165     def msb_component_ready(cls):
166         """Check if MSB component is ready."""
167         logger.info("Verify MSB component is ready")
168
169         try:
170             response = msb.get_services()
171         except (RequestException, NewConnectionError, ConnectionFailed, APIError) as e:
172             logger.error(e)
173             return False
174         return response is not None and len(response) > 0
175
176     @classmethod
177     def oof_component_ready(cls):
178         """Check if OOF component is ready."""
179         logger.info("Verify OOF component is ready")
180
181         try:
182             response = oof.get_versions()
183         except (RequestException, NewConnectionError, ConnectionFailed, APIError) as e:
184             logger.error(e)
185             return False
186         return response["versions"] is not None