blob: d2476ec15b47f1a670408219c0a1e180840671aa [file] [log] [blame]
magnussonl2b0e2d72020-02-04 10:52:46 +01001#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3
4# Copyright 2020 ArctosLabs Scandinavia AB
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15# implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18
19import asyncio
20import logging
magnussonl31181aa2020-11-25 09:04:51 +010021import itertools
magnussonl2b0e2d72020-02-04 10:52:46 +010022from pathlib import Path
23
magnussonl2b0e2d72020-02-04 10:52:46 +010024import yaml
25from osm_common import dbmemory, dbmongo, msglocal, msgkafka
26
27from osm_pla.config.config import Config
28from osm_pla.placement.mznplacement import MznPlacementConductor
29from osm_pla.placement.mznplacement import NsPlacementDataFactory
30
31
32class Server:
garciadeblas20fc3b72022-11-14 00:48:32 +010033 pil_price_list_file = Path("/placement/pil_price_list.yaml")
34 vnf_price_list_file = Path("/placement/vnf_price_list.yaml")
magnussonl2b0e2d72020-02-04 10:52:46 +010035
36 def __init__(self, config: Config, loop=None):
37 self.log = logging.getLogger("pla.server")
38 self.db = None
39 self.msgBus = None
40 self.config = config
41 self.loop = loop or asyncio.get_event_loop()
42
43 try:
garciadeblas20fc3b72022-11-14 00:48:32 +010044 if config.get("database", "driver") == "mongo":
magnussonl2b0e2d72020-02-04 10:52:46 +010045 self.db = dbmongo.DbMongo()
garciadeblas20fc3b72022-11-14 00:48:32 +010046 self.db.db_connect(config.get("database"))
47 elif config.get("database", "driver") == "memory":
magnussonl2b0e2d72020-02-04 10:52:46 +010048 self.db = dbmemory.DbMemory()
garciadeblas20fc3b72022-11-14 00:48:32 +010049 self.db.db_connect(config.get("database"))
magnussonl2b0e2d72020-02-04 10:52:46 +010050 else:
garciadeblas20fc3b72022-11-14 00:48:32 +010051 raise Exception(
52 "Invalid configuration param '{}' at '[database]':'driver'".format(
53 config.get("database", "driver")
54 )
55 )
magnussonl2b0e2d72020-02-04 10:52:46 +010056
garciadeblas20fc3b72022-11-14 00:48:32 +010057 if config.get("message", "driver") == "local":
magnussonl2b0e2d72020-02-04 10:52:46 +010058 self.msgBus = msglocal.MsgLocal()
garciadeblas20fc3b72022-11-14 00:48:32 +010059 elif config.get("message", "driver") == "kafka":
magnussonl2b0e2d72020-02-04 10:52:46 +010060 self.msgBus = msgkafka.MsgKafka()
61 else:
garciadeblas20fc3b72022-11-14 00:48:32 +010062 raise Exception(
63 "Invalid message bus driver {}".format(
64 config.get("message", "driver")
65 )
66 )
magnussonl2b0e2d72020-02-04 10:52:46 +010067 self.msgBus.loop = loop
garciadeblas20fc3b72022-11-14 00:48:32 +010068 self.msgBus.connect(config.get("message"))
magnussonl2b0e2d72020-02-04 10:52:46 +010069
70 except Exception as e:
71 self.log.exception("kafka setup error. Exception: {}".format(e))
72
73 def _get_nslcmop(self, nsdlcmop_id):
74 """
75 :param nsdlcmop_id:
76 :return: nslcmop from database corresponding to nslcmop_id
77 """
78 db_filter = {"_id": nsdlcmop_id}
79 nslcmop = self.db.get_one("nslcmops", db_filter)
80 return nslcmop
81
magnussonld8c1b392020-06-30 16:48:08 +020082 def _get_projects(self):
83 """
84 :return: project name to project id mapping
85 """
86 projects = self.db.get_list("projects")
garciadeblas20fc3b72022-11-14 00:48:32 +010087 return {project["_id"]: project["name"] for project in projects}
magnussonld8c1b392020-06-30 16:48:08 +020088
magnussonl2b0e2d72020-02-04 10:52:46 +010089 def _get_nsd(self, nsd_id):
90 """
91 :param nsd_id:
92 :return: nsd from database corresponding to nsd_id
93 """
94 db_filter = {"_id": nsd_id}
95 return self.db.get_one("nsds", db_filter)
96
97 def _get_vim_accounts(self, vim_account_ids):
98 """
99 :param vim_account_ids: list of VIM account ids
100 :return: list of vim account entries from database corresponding to list in vim_accounts_id
101 """
102 db_filter = {"_id": vim_account_ids}
103 return self.db.get_list("vim_accounts", db_filter)
104
magnussonld8c1b392020-06-30 16:48:08 +0200105 def _read_vnf_price_list(self, price_list_file_path):
magnussonl2b0e2d72020-02-04 10:52:46 +0100106 """
magnussonld8c1b392020-06-30 16:48:08 +0200107 read vnf price list configuration file
108 :param price_list_file_path:
109 :return:
magnussonl2b0e2d72020-02-04 10:52:46 +0100110 """
111 with open(str(price_list_file_path)) as pl_fd:
magnussonld8c1b392020-06-30 16:48:08 +0200112 price_list = yaml.safe_load_all(pl_fd)
113 return next(price_list)
114
115 def _price_list_with_project(self, price_list):
116 """
117 Figure out if this price list is with project or not.
118 Note: to handle the unlikely event that a project is called 'prices' we do not simply check if 'prices'
119 is in the dict keys for a price list sequence but rather go down one step in the nesting
120 in which we either have
121 1) 'prices:{vim_url:...}' if prices are also per project, or
122 2) '{vim_url:...}' if prices are only per vim
123
124 :param price_list:
125 :return: True if project part of price list, else False
126 """
127 price_list_entry_keys = set(price_list[0].keys())
garciadeblas20fc3b72022-11-14 00:48:32 +0100128 price_list_entry_keys.remove("vnfd")
magnussonld8c1b392020-06-30 16:48:08 +0200129 pl_key = price_list_entry_keys.pop()
130 entry_to_check = price_list[0][pl_key][0].keys()
garciadeblas20fc3b72022-11-14 00:48:32 +0100131 return True if "prices" in entry_to_check else False
magnussonld8c1b392020-06-30 16:48:08 +0200132
133 def _get_vnf_price_list(self, price_list_file_path, project_name=None):
134 """
135 read vnf price list configuration file, determine its type and reformat content accordingly
136
137 :param price_list_file_path:
138 :param project_name:
139 :return: dictionary formatted as {'<vnfd>': {'<vim-url>':'<price>'}}
140 """
141 price_list_data = self._read_vnf_price_list(price_list_file_path)
142 if self._price_list_with_project(price_list_data):
143 res = {}
144 for i in price_list_data:
garciadeblas20fc3b72022-11-14 00:48:32 +0100145 price_data = (
146 i[project_name]
147 if type(i[project_name]) is dict
148 else i[project_name][0]
149 )
150 res_component = {
151 i["vim_name"]: i["price"] for i in price_data["prices"]
152 }
153 res.update({i["vnfd"]: res_component})
magnussonld8c1b392020-06-30 16:48:08 +0200154 return res
155 else:
garciadeblas20fc3b72022-11-14 00:48:32 +0100156 return {
157 i["vnfd"]: {i1["vim_name"]: i1["price"] for i1 in i["prices"]}
158 for i in price_list_data
159 }
magnussonl2b0e2d72020-02-04 10:52:46 +0100160
161 def _get_pil_info(self, pil_info_file_path):
162 """
163 read and return pil information from file
164 :param pil_info_file_path: Path to pil_info file
165 :return pil configuration file content as Python object
166 """
167 with open(str(pil_info_file_path)) as pil_fd:
168 data = yaml.safe_load_all(pil_fd)
169 return next(data)
170
magnussonl31181aa2020-11-25 09:04:51 +0100171 def _create_vnf_id_maps(self, nsd):
172 """
173 map identifier for 'member-vnf-index' in nsd to syntax that is safe for mzn
174
175 return tuples with mappings {<adjusted id>: <original id>} and {<original id>: <adjusted id>}
176 """
garciaaleb2b0a442021-01-08 14:59:23 -0300177 # TODO: Change for multiple DF support
garciadeblas20fc3b72022-11-14 00:48:32 +0100178 ns_df = nsd.get("df", [{}])[0]
magnussonl31181aa2020-11-25 09:04:51 +0100179 next_idx = itertools.count()
garciadeblas20fc3b72022-11-14 00:48:32 +0100180 member_vnf_index2mzn = {
181 e["id"]: "VNF" + str(next(next_idx)) for e in ns_df.get("vnf-profile", [])
182 }
magnussonl31181aa2020-11-25 09:04:51 +0100183
184 # reverse the name map dictionary, used when the placement result is remapped
185 mzn_name2member_vnf_index = {v: k for k, v in member_vnf_index2mzn.items()}
186
187 return member_vnf_index2mzn, mzn_name2member_vnf_index
188
magnussonl2b0e2d72020-02-04 10:52:46 +0100189 async def get_placement(self, nslcmop_id):
190 """
191 - Collects and prepares placement information.
192 - Request placement computation.
193 - Formats and distribute placement result
194
195 Note: exceptions result in empty response message
196
197 :param nslcmop_id:
198 :return:
199 """
200 try:
201 nslcmop = self._get_nslcmop(nslcmop_id)
garciadeblas20fc3b72022-11-14 00:48:32 +0100202 nsd = self._get_nsd(nslcmop["operationParams"]["nsdId"])
magnussonl31181aa2020-11-25 09:04:51 +0100203 member_vnf_index2mzn, mzn2member_vnf_index = self._create_vnf_id_maps(nsd)
204 # adjust vnf identifiers
garciaaleb2b0a442021-01-08 14:59:23 -0300205 # TODO: Change for multiple DF support
garciadeblas20fc3b72022-11-14 00:48:32 +0100206 ns_df = nsd.get("df", [{}])[0]
207 for vnf_profile in ns_df.get("vnf-profile", []):
208 vnf_profile["id"] = member_vnf_index2mzn[vnf_profile["id"]]
209 for vlc in vnf_profile.get("virtual-link-connectivity", []):
210 for ccpd in vlc.get("constituent-cpd-id", []):
211 ccpd["constituent-base-element-id"] = member_vnf_index2mzn[
212 ccpd["constituent-base-element-id"]
213 ]
magnussonl31181aa2020-11-25 09:04:51 +0100214 self.log.info("adjusted nsd: {}".format(nsd))
magnussonld8c1b392020-06-30 16:48:08 +0200215 projects = self._get_projects()
216 self.log.info("projects: {}".format(projects))
garciadeblas20fc3b72022-11-14 00:48:32 +0100217 nslcmop_project = nslcmop["_admin"]["projects_read"][0]
magnussonld8c1b392020-06-30 16:48:08 +0200218 self.log.info("nslcmop_project: {}".format(nslcmop_project))
garciadeblas20fc3b72022-11-14 00:48:32 +0100219 valid_vim_accounts = nslcmop["operationParams"]["validVimAccounts"]
magnussonl2b0e2d72020-02-04 10:52:46 +0100220 vim_accounts_data = self._get_vim_accounts(valid_vim_accounts)
garciadeblas20fc3b72022-11-14 00:48:32 +0100221 vims_information = {_["name"]: _["_id"] for _ in vim_accounts_data}
222 price_list = self._get_vnf_price_list(
223 Server.vnf_price_list_file, projects[nslcmop_project]
224 )
magnussonl2b0e2d72020-02-04 10:52:46 +0100225 pil_info = self._get_pil_info(Server.pil_price_list_file)
garciadeblas20fc3b72022-11-14 00:48:32 +0100226 pinnings = nslcmop["operationParams"].get("vnf", [])
magnussonl31181aa2020-11-25 09:04:51 +0100227 # remap member-vnf-index values according to id map
228 for pinning in pinnings:
garciadeblas20fc3b72022-11-14 00:48:32 +0100229 pinning["member-vnf-index"] = member_vnf_index2mzn[
230 pinning["member-vnf-index"]
231 ]
magnussonl31181aa2020-11-25 09:04:51 +0100232 self.log.info("pinnings: {}".format(pinnings))
garciadeblas20fc3b72022-11-14 00:48:32 +0100233 order_constraints = nslcmop["operationParams"].get("placement-constraints")
magnussonl2b0e2d72020-02-04 10:52:46 +0100234 self.log.info("order constraints: {}".format(order_constraints))
235
garciadeblas20fc3b72022-11-14 00:48:32 +0100236 nspd = NsPlacementDataFactory(
237 vims_information, price_list, nsd, pil_info, pinnings, order_constraints
238 ).create_ns_placement_data()
magnussonl2b0e2d72020-02-04 10:52:46 +0100239
garciadeblas20fc3b72022-11-14 00:48:32 +0100240 vnf_placement = MznPlacementConductor(self.log).do_placement_computation(
241 nspd
242 )
magnussonl2b0e2d72020-02-04 10:52:46 +0100243
244 except Exception as e:
245 # Note: there is no cure for failure so we have a catch-all clause here
246 self.log.exception("PLA fault. Exception: {}".format(e))
247 vnf_placement = []
248 finally:
magnussonl31181aa2020-11-25 09:04:51 +0100249 # remap names in vnf_placement
250 for e in vnf_placement:
garciadeblas20fc3b72022-11-14 00:48:32 +0100251 e["member-vnf-index"] = mzn2member_vnf_index[e["member-vnf-index"]]
252 await self.msgBus.aiowrite(
253 "pla",
254 "placement",
255 {"placement": {"vnf": vnf_placement, "nslcmopId": nslcmop_id}},
256 )
magnussonl2b0e2d72020-02-04 10:52:46 +0100257
258 def handle_kafka_command(self, topic, command, params):
259 self.log.info("Kafka msg arrived: {} {} {}".format(topic, command, params))
260 if topic == "pla" and command == "get_placement":
garciadeblas20fc3b72022-11-14 00:48:32 +0100261 nslcmop_id = params.get("nslcmopId")
magnussonl2b0e2d72020-02-04 10:52:46 +0100262 self.loop.create_task(self.get_placement(nslcmop_id))
263
264 async def kafka_read(self):
265 self.log.info("Task kafka_read start")
266 while True:
267 try:
268 topics = "pla"
269 await self.msgBus.aioread(topics, self.loop, self.handle_kafka_command)
270 except Exception as e:
271 self.log.error("kafka read error. Exception: {}".format(e))
272 await asyncio.sleep(5, loop=self.loop)
273
274 def run(self):
275 self.loop.run_until_complete(self.kafka_read())
276 self.loop.close()
277 self.loop = None
278 if self.msgBus:
279 self.msgBus.disconnect()