[APACHE] Add Apache CNF use case files
[demo.git] / tutorials / ApacheCNF / automation / delete.py
1 # ============LICENSE_START=======================================================
2 # Copyright (C) 2021 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
20 from config import Config, VariablesDict
21 from instantiate import get_customer, check_orchestration_status
22
23 from onapsdk.exceptions import ResourceNotFound, APIError
24 from onapsdk.aai.business import ServiceInstance
25
26 logger = logging.getLogger()
27 logger.setLevel(logging.DEBUG)
28
29
30 def get_service_subscription(customer, service_type):
31     try:
32         service_subscription = customer.get_service_subscription_by_service_type(
33             service_type=service_type)
34         return service_subscription
35     except ResourceNotFound:
36         logger.error("Service Subscription not found")
37         exit(1)
38
39
40 def get_service_instance(service_subscription, service_instance_name):
41     try:
42         service_instance = service_subscription.get_service_instance_by_name(
43             service_instance_name=service_instance_name)
44         return service_instance
45     except ResourceNotFound:
46         logger.error("Service Instance not found")
47         exit(1)
48
49
50 def delete_service_macro(service_instance: ServiceInstance, service_instance_info):
51     vnf_infos_list = []
52     for index, vnf_info in enumerate(service_instance_info["vnfs"]):
53         if not vnf_info.get("vnf_name_suffix"):
54             vnf_info["vnf_name_suffix"] = str(index)
55         vnf_info["instance_name"] = f"Instance_{vnf_info['model_name']}_{vnf_info['vnf_name_suffix']}"
56         vnf_infos_list.append(vnf_info)
57
58     ordered_vnf_instances = sorted(vnf_infos_list,
59                                    key=lambda _vnf: _vnf.get("processing_priority", 100),
60                                    reverse=True)
61
62     delete_vnfs_instances(service_instance, ordered_vnf_instances)
63
64     return check_orchestration_status(service_instance.delete(a_la_carte=False))
65
66
67 def delete_vnfs_instances(service_instance: ServiceInstance, ordered_vnf_instances):
68     for vnf in ordered_vnf_instances:
69         vnf_name = vnf.get("instance_name")
70         vnf_instance = next((vnf_instance
71                              for vnf_instance in service_instance.vnf_instances
72                              if vnf_instance.vnf_name == vnf_name), None)
73         if not vnf_instance:
74             continue
75
76         try:
77             vnf_deletion = vnf_instance.delete(a_la_carte=False)
78         except APIError:
79             logger.error("Operation not supported, whole service instance will be deleted with random order")
80             break
81         check_orchestration_status(vnf_deletion)
82     return
83
84
85 def delete_service_alacarte(service_instance):
86     for vnf in service_instance.vnf_instances:
87         for vf_module in vnf.vf_modules:
88             vf_module_deletion = vf_module.delete()
89             check_orchestration_status(vf_module_deletion)
90         vnf_deletion = vnf.delete()
91         check_orchestration_status(vnf_deletion)
92     service_deletion = service_instance.delete(a_la_carte=True)
93     check_orchestration_status(service_deletion)
94
95
96 def main():
97     logger.info("*******************************")
98     logger.info("**** SERVICE DELETION ****")
99     logger.info("*******************************")
100
101     config = Config(env_dict=VariablesDict.env_variable)
102     logger.info("******** GET Customer *******")
103     customer = get_customer(config.service_instance["customer_id"])
104
105     logger.info("******** Check Service Subscription *******")
106     service_subscription = get_service_subscription(customer, config.service_instance["model_name"])
107
108     logger.info("******** Get Service Instance details *******")
109     service_instance = get_service_instance(service_subscription, config.service_instance["instance_name"])
110
111     logger.info("******** Delete Service %s *******", service_instance.instance_name)
112     if config.service_model["macro_orchestration"]:
113         # if config.service_instance.get("deletion_policy") in ('InstantiationOrder', 'ReverseInstantiationOrder'):
114         #     delete_service_macro_delete_policy(service_instance, config.service_instance)
115         # else:
116         delete_service_macro(service_instance, config.service_instance)
117     else:
118         logger.error("A_la_carte orchestration method not updated")
119         if config.service_model["pnfs"] is not None:
120             raise NotImplementedError
121         else:
122             delete_service_alacarte(service_instance)
123
124
125 if __name__ == "__main__":
126     sh = logging.StreamHandler()
127     sh_formatter = logging.Formatter('%(asctime)s %(levelname)s %(lineno)d:%(filename)s(%(process)d) - %(message)s')
128     sh.setFormatter(sh_formatter)
129     logger.addHandler(sh)
130
131     main()