Revert "Revert "Create basic_cnf test leveraging onapsdk""
[testsuite/pythonsdk-tests.git] / src / onaptests / steps / instantiate / service_ala_carte.py
1 import time
2 from uuid import uuid4
3 from yaml import load
4
5 from onapsdk.aai.cloud_infrastructure import CloudRegion, Tenant
6 from onapsdk.aai.business import Customer, ServiceInstance, ServiceSubscription
7 from onapsdk.aai.business.owning_entity import OwningEntity as AaiOwningEntity
8 from onapsdk.configuration import settings
9 from onapsdk.sdc.service import Service
10 from onapsdk.so.instantiation import ServiceInstantiation
11 from onapsdk.vid import Project
12
13 import onaptests.utils.exceptions as onap_test_exceptions
14 from ..base import BaseStep, YamlTemplateBaseStep
15 from ..cloud.connect_service_subscription_to_cloud_region import ConnectServiceSubToCloudRegionStep
16 from ..onboard.service import ServiceOnboardStep, YamlTemplateServiceOnboardStep
17
18
19 class ServiceAlaCarteInstantiateStep(BaseStep):
20     """Instantiate service a'la carte."""
21
22     def __init__(self, cleanup=False):
23         """Initialize step.
24
25         Substeps:
26             - ServiceOnboardStep,
27             - ConnectServiceSubToCloudRegionStep.
28         """
29         super().__init__(cleanup=cleanup)
30         if not settings.ONLY_INSTANTIATE:
31             self.add_step(ServiceOnboardStep(cleanup))
32             self.add_step(ConnectServiceSubToCloudRegionStep(cleanup))
33
34     @BaseStep.store_state
35     def execute(self):
36         """Instantiate service.
37
38         Use settings values:
39          - SERVICE_NAME,
40          - GLOBAL_CUSTOMER_ID,
41          - CLOUD_REGION_CLOUD_OWNER,
42          - CLOUD_REGION_ID,
43          - TENANT_ID,
44          - OWNING_ENTITY,
45          - PROJECT,
46          - SERVICE_INSTANCE_NAME.
47         """
48         super().execute()
49         service = Service(settings.SERVICE_NAME)
50         customer: Customer = Customer.get_by_global_customer_id(settings.GLOBAL_CUSTOMER_ID)
51         cloud_region: CloudRegion = CloudRegion.get_by_id(
52             cloud_owner=settings.CLOUD_REGION_CLOUD_OWNER,
53             cloud_region_id=settings.CLOUD_REGION_ID,
54         )
55         tenant: Tenant = cloud_region.get_tenant(settings.TENANT_ID)
56         try:
57             owning_entity = AaiOwningEntity.get_by_owning_entity_name(
58                 settings.OWNING_ENTITY)
59         except ValueError:
60             self._logger.info("Owning entity not found, create it")
61             owning_entity = AaiOwningEntity.create(settings.OWNING_ENTITY)
62         vid_project = Project.create(settings.PROJECT)
63
64         service_instantiation = ServiceInstantiation.instantiate_so_ala_carte(
65             service,
66             cloud_region,
67             tenant,
68             customer,
69             owning_entity,
70             vid_project,
71             service_instance_name=settings.SERVICE_INSTANCE_NAME
72         )
73         while not service_instantiation.finished:
74             time.sleep(10)
75
76
77 class YamlTemplateServiceAlaCarteInstantiateStep(YamlTemplateBaseStep):
78     """Instantiate service a'la carte using YAML template."""
79
80     def __init__(self, cleanup=False):
81         """Initialize step.
82
83         Substeps:
84             - YamlTemplateServiceOnboardStep,
85             - ConnectServiceSubToCloudRegionStep.
86         """
87         super().__init__(cleanup=cleanup)
88         self._yaml_template: dict = None
89         self._service_instance_name: str = None
90         self._service_instance: str = None
91         if not settings.ONLY_INSTANTIATE:
92             self.add_step(YamlTemplateServiceOnboardStep(cleanup))
93             self.add_step(ConnectServiceSubToCloudRegionStep(cleanup))
94
95     @property
96     def yaml_template(self) -> dict:
97         """Step YAML template.
98
99         Load from file if it's a root step, get from parent otherwise.
100
101         Returns:
102             dict: Step YAML template
103
104         """
105         if self.is_root:
106             if not self._yaml_template:
107                 with open(settings.SERVICE_YAML_TEMPLATE, "r") as yaml_template:
108                     self._yaml_template: dict = load(yaml_template)
109             return self._yaml_template
110         return self.parent.yaml_template
111
112     @property
113     def service_name(self) -> str:
114         """Service name.
115
116         Get from YAML template if it's a root step, get from parent otherwise.
117
118         Returns:
119             str: Service name
120
121         """
122         if self.is_root:
123             return next(iter(self.yaml_template.keys()))
124         return self.parent.service_name
125
126     @property
127     def service_instance_name(self) -> str:
128         """Service instance name.
129
130         Generate using `service_name` and `uuid4()` function if it's a root step,
131             get from parent otherwise.
132
133         Returns:
134             str: Service instance name
135
136         """
137         if self.is_root:
138             if not self._service_instance_name:
139                 self._service_instance_name: str = f"{self.service_name}-{str(uuid4())}"
140             return self._service_instance_name
141         return self.parent.service_instance_name
142
143     @YamlTemplateBaseStep.store_state
144     def execute(self):
145         """Instantiate service.
146
147         Use settings values:
148          - GLOBAL_CUSTOMER_ID,
149          - CLOUD_REGION_CLOUD_OWNER,
150          - CLOUD_REGION_ID,
151          - TENANT_ID,
152          - OWNING_ENTITY,
153          - PROJECT.
154
155         Raises:
156             Exception: Service instantiation failed
157
158         """
159         super().execute()
160         service = Service(self.service_name)
161         customer: Customer = Customer.get_by_global_customer_id(settings.GLOBAL_CUSTOMER_ID)
162         cloud_region: CloudRegion = CloudRegion.get_by_id(
163             cloud_owner=settings.CLOUD_REGION_CLOUD_OWNER,
164             cloud_region_id=settings.CLOUD_REGION_ID,
165         )
166         tenant: Tenant = cloud_region.get_tenant(settings.TENANT_ID)
167         try:
168             owning_entity = AaiOwningEntity.get_by_owning_entity_name(
169                 settings.OWNING_ENTITY)
170         except ValueError:
171             self._logger.info("Owning entity not found, create it")
172             owning_entity = AaiOwningEntity.create(settings.OWNING_ENTITY)
173         vid_project = Project.create(settings.PROJECT)
174
175         # Before instantiating, be sure that the service has been distributed
176         self._logger.info("******** Check Service Distribution *******")
177         distribution_completed = False
178         nb_try = 0
179         nb_try_max = 10
180         while distribution_completed is False and nb_try < nb_try_max:
181             distribution_completed = service.distributed
182             if distribution_completed is True:
183                 self._logger.info(
184                 "Service Distribution for %s is sucessfully finished",
185                 service.name)
186                 break
187             self._logger.info(
188                 "Service Distribution for %s ongoing, Wait for 60 s",
189                 service.name)
190             time.sleep(60)
191             nb_try += 1
192
193         if distribution_completed is False:
194             self._logger.error(
195                 "Service Distribution for %s failed !!",service.name)
196             raise onap_test_exceptions.ServiceDistributionException
197
198         service_instantiation = ServiceInstantiation.instantiate_so_ala_carte(
199             service,
200             cloud_region,
201             tenant,
202             customer,
203             owning_entity,
204             vid_project,
205             service_instance_name=self.service_instance_name
206         )
207         while not service_instantiation.finished:
208             time.sleep(10)
209         if service_instantiation.failed:
210             raise onap_test_exceptions.ServiceInstantiateException
211         else:
212             service_subscription: ServiceSubscription = customer.get_service_subscription_by_service_type(self.service_name)
213             self._service_instance: ServiceInstance = service_subscription.get_service_instance_by_name(self.service_instance_name)
214
215
216     def cleanup(self) -> None:
217         """Cleanup Service.
218
219         Raises:
220             Exception: Service cleaning failed
221
222         """
223         service_deletion = self._service_instance.delete()
224         nb_try = 0
225         nb_try_max = 30
226         while not service_deletion.finished and nb_try < nb_try_max:
227             self._logger.info("Wait for Service deletion")
228             nb_try += 1
229             time.sleep(15)
230         if service_deletion.finished:
231             self._logger.info("Service %s deleted", self._service_instance_name)
232         else:
233             self._logger.error("Service deletion %s failed", self._service_instance_name)
234             raise onap_test_exceptions.ServiceCleanupException
235         super.cleanup()