Real vFW CNF config-assign and config-deploy
[demo.git] / heat / vFW_CNF_CDS / automation / instantiate.py
1 # ============LICENSE_START=======================================================
2 # Copyright (C) 2020 Orange
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 # ============LICENSE_END=========================================================
17
18 import logging
19 import zipfile
20 from io import BytesIO
21 from time import sleep
22 from uuid import uuid4
23
24 import oyaml as yaml
25
26 from config import Config
27 from onapsdk.aai.cloud_infrastructure import (
28     CloudRegion,
29 )
30 from onapsdk.aai.business import (
31     Customer,
32     OwningEntity as AaiOwningEntity
33 )
34 from onapsdk.msb.k8s import Definition
35
36 from onapsdk.so.instantiation import (
37     ServiceInstantiation,
38     InstantiationParameter, VnfParameters, VfmoduleParameters)
39 from onapsdk.sdc.service import Service
40 from onapsdk.vid import LineOfBusiness, OwningEntity, Platform, Project
41 from onapsdk.so.so_element import OrchestrationRequest
42
43 logger = logging.getLogger("")
44 logger.setLevel(logging.DEBUG)
45 fh = logging.StreamHandler()
46 fh_formatter = logging.Formatter('%(asctime)s %(levelname)s %(lineno)d:%(filename)s(%(process)d) - %(message)s')
47 fh.setFormatter(fh_formatter)
48 logger.addHandler(fh)
49
50 logger.info("*******************************")
51 logger.info("**** SERVICE INSTANTIATION ****")
52 logger.info("*******************************")
53
54 logger.info("******** Create Customer *******")
55 customer = None
56 for found_customer in list(Customer.get_all()):
57     logger.debug("Customer %s found", found_customer.subscriber_name)
58     if found_customer.subscriber_name == Config.GLOBAL_CUSTOMER_ID:
59         logger.info("Customer %s found", found_customer.subscriber_name)
60         customer = found_customer
61         break
62 if not customer:
63     customer = Customer.create(Config.GLOBAL_CUSTOMER_ID, Config.GLOBAL_CUSTOMER_ID, "INFRA")
64
65 logger.info("******** Find Service in SDC *******")
66 service = None
67 services = Service.get_all()
68 for found_service in services:
69     logger.debug("Service %s is found, distribution %s", found_service.name, found_service.distribution_status)
70     if found_service.name == Config.SERVICENAME:
71         logger.info("Found Service %s in SDC", found_service.name)
72         service = found_service
73         break
74
75 if not service:
76     logger.error("Service %s not found in SDC", Config.SERVICENAME)
77     exit(1)
78
79 logger.info("******** Check Service Subscription *******")
80 service_subscription = None
81 for service_sub in customer.service_subscriptions:
82     logger.debug("Service subscription %s is found", service_sub.service_type)
83     if service_sub.service_type == Config.SERVICENAME:
84         logger.info("Service %s subscribed", Config.SERVICENAME)
85         service_subscription = service_sub
86         break
87
88 if not service_subscription:
89     logger.info("******** Subscribe Service *******")
90     customer.subscribe_service(service)
91
92 logger.info("******** Get Tenant *******")
93 cloud_region = CloudRegion(cloud_owner=Config.CLOUD_OWNER, cloud_region_id=Config.CLOUD_REGION,
94                            orchestration_disabled=True, in_maint=False)
95 tenant = None
96 for found_tenant in cloud_region.tenants:
97     logger.debug("Tenant %s found in %s_%s", found_tenant.name, cloud_region.cloud_owner, cloud_region.cloud_region_id)
98     if found_tenant.name == Config.TENANT_NAME:
99         logger.info("Found my Tenant %s", found_tenant.name)
100         tenant = found_tenant
101         break
102
103 if not tenant:
104     logger.error("tenant %s not found", Config.TENANT_NAME)
105     exit(1)
106
107 logger.info("******** Connect Service to Tenant *******")
108 service_subscription = None
109 for service_sub in customer.service_subscriptions:
110     logger.debug("Service subscription %s is found", service_sub.service_type)
111     if service_sub.service_type == Config.SERVICENAME:
112         logger.info("Service %s subscribed", Config.SERVICENAME)
113         service_subscription = service_sub
114         break
115
116 if not service_subscription:
117     logger.error("Service subscription %s is not found", Config.SERVICENAME)
118     exit(1)
119
120 service_subscription.link_to_cloud_region_and_tenant(cloud_region, tenant)
121
122 logger.info("******** Add Business Objects (OE, P, Pl, LoB) in VID *******")
123 vid_owning_entity = OwningEntity.create(Config.OWNING_ENTITY)
124 vid_project = Project.create(Config.PROJECT)
125 vid_platform = Platform.create(Config.PLATFORM)
126 vid_line_of_business = LineOfBusiness.create(Config.LINE_OF_BUSINESS)
127
128 logger.info("******** Add Owning Entity in AAI *******")
129 owning_entity = None
130 for oe in AaiOwningEntity.get_all():
131     if oe.name == vid_owning_entity.name:
132         owning_entity = oe
133         break
134 if not owning_entity:
135     logger.info("******** Owning Entity not existing: create *******")
136     owning_entity = AaiOwningEntity.create(vid_owning_entity.name, str(uuid4()))
137
138 logger.info("******** Delete old profiles ********")
139 for vnf in service.vnfs:
140     for vf_module in vnf.vf_modules:
141         definition = Definition.get_definition_by_name_version(vf_module.metadata["vfModuleModelInvariantUUID"],
142                                                                vf_module.metadata["vfModuleModelUUID"])
143         vf_module_label = vf_module.properties["vf_module_label"]
144         if vf_module_label == "base_template_dummy_ignore":
145             continue
146         profile_name = Config.VF_MODULE_PARAM_LIST[vf_module_label]["k8s-rb-profile-name"]
147         try:
148             profile = definition.get_profile_by_name(profile_name)
149             namespace = None
150             if "k8s-rb-profile-namespace" in Config.VNF_PARAM_LIST:
151                 namespace = Config.VNF_PARAM_LIST["k8s-rb-profile-namespace"]
152             if "k8s-rb-profile-namespace" in Config.VF_MODULE_PARAM_LIST[vf_module_label]:
153                 namespace = Config.VF_MODULE_PARAM_LIST[vf_module_label]["k8s-rb-profile-namespace"]
154             if namespace != None and profile.namespace != namespace:
155                 profile.delete()
156                 logger.info("Profile: " + profile_name + " for " + vf_module.name + " deleted")
157             else:
158                 logger.info("No need to delete Profile " + profile_name +
159                             " for " + vf_module.name + ". Namespace is fine")
160         except ValueError:
161             logger.info("Profile: " + profile_name + " for " + vf_module.name + " not found")
162
163
164 # Read SDNC MODEL NAME and VERSION from CBA.zip
165 logger.info("*******************************")
166 logger.info("Retrieving SDNC MODEL NAME and VERSION")
167 logger.info("*******************************")
168 with zipfile.ZipFile(Config.VSPFILE, 'r') as package:
169     cba_io = BytesIO(package.read("CBA.zip"))
170     with zipfile.ZipFile(cba_io) as cba:
171         with cba.open('TOSCA-Metadata/TOSCA.meta') as meta_file:
172             tosca_meta = yaml.load(meta_file, Loader=yaml.FullLoader)
173             SDNC_MODEL_NAME = tosca_meta.get("Template-Name")
174             SDNC_MODEL_VERSION = tosca_meta.get("Template-Version")
175
176 logger.info("******** Instantiate Service *******")
177 service_instance = None
178 service_instantiation = None
179 for se in service_subscription.service_instances:
180     if se.instance_name == Config.SERVICE_INSTANCE_NAME:
181         service_instance = se
182         break
183 if not service_instance:
184     logger.info("******** Service Instance not existing: Instantiate *******")
185     # Instantiate service
186     vfmodules_list = Config.VF_MODULE_PARAM_LIST
187     vnf_param_list = Config.VNF_PARAM_LIST
188
189     vnf_param = [
190         InstantiationParameter(name="sdnc_model_name", value=SDNC_MODEL_NAME),
191         InstantiationParameter(name="sdnc_model_version", value=SDNC_MODEL_VERSION),
192         InstantiationParameter(name="sdnc_artifact_name", value=Config.SDNC_ARTIFACT_NAME)]
193
194     for vnf_param_name, vnf_param_value in vnf_param_list.items():
195         vnf_param.append(
196             InstantiationParameter(name=vnf_param_name, value=vnf_param_value)
197         )
198
199     vfmodules_param = []
200     for vfmodule in vfmodules_list:
201         params = [
202             InstantiationParameter(name="sdnc_model_name", value=SDNC_MODEL_NAME),
203             InstantiationParameter(name="sdnc_model_version", value=SDNC_MODEL_VERSION),
204             InstantiationParameter(name="vf_module_label", value=vfmodule)]
205
206         for vfmodule_param_name, vfmodule_param_value in vfmodules_list[vfmodule].items():
207             params.append(
208                 InstantiationParameter(name=vfmodule_param_name, value=vfmodule_param_value)
209             )
210
211         vfmodules_param.append(VfmoduleParameters(vfmodule, params))
212
213     vnf_params = VnfParameters(name=Config.VFNAME, vnf_parameters=vnf_param, vfmodule_parameters=vfmodules_param)
214
215     service_instantiation = ServiceInstantiation.instantiate_macro(
216         sdc_service=service,
217         cloud_region=cloud_region,
218         tenant=tenant,
219         customer=customer,
220         owning_entity=owning_entity,
221         project=vid_project,
222         line_of_business=vid_line_of_business,
223         platform=vid_platform,
224         service_instance_name=Config.SERVICE_INSTANCE_NAME,
225         vnf_parameters=[vnf_params]
226     )
227     status = None
228     while not (status == OrchestrationRequest.StatusEnum.COMPLETED
229                or status == OrchestrationRequest.StatusEnum.FAILED):
230         sleep(10)
231         status = service_instantiation.status
232         logger.info(f"Orchestration status is: {status.value}")