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