blob: 472ce795102b4da00aec82d0b766c5ac37216519 [file] [log] [blame]
tierno1d213f42020-04-24 14:02:51 +00001# -*- coding: utf-8 -*-
2
3##
4# Copyright 2020 Telefonica Investigacion y Desarrollo, S.A.U.
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14# implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17##
18
sousaedu0fe84cb2022-01-17 13:48:22 +000019from http import HTTPStatus
sousaedu80135b92021-02-17 15:05:18 +010020import logging
sousaedu0fe84cb2022-01-17 13:48:22 +000021from random import choice as random_choice
22from threading import Lock
23from time import time
tierno1d213f42020-04-24 14:02:51 +000024from traceback import format_exc as traceback_format_exc
sousaedu0fe84cb2022-01-17 13:48:22 +000025from uuid import uuid4
26
27from cryptography.hazmat.backends import default_backend as crypto_default_backend
28from cryptography.hazmat.primitives import serialization as crypto_serialization
29from cryptography.hazmat.primitives.asymmetric import rsa
30from jinja2 import (
31 Environment,
32 StrictUndefined,
33 TemplateError,
34 TemplateNotFound,
35 UndefinedError,
36)
sousaedu80135b92021-02-17 15:05:18 +010037from osm_common import (
sousaedu80135b92021-02-17 15:05:18 +010038 dbmemory,
sousaedu0fe84cb2022-01-17 13:48:22 +000039 dbmongo,
sousaedu80135b92021-02-17 15:05:18 +010040 fslocal,
41 fsmongo,
sousaedu80135b92021-02-17 15:05:18 +010042 msgkafka,
sousaedu0fe84cb2022-01-17 13:48:22 +000043 msglocal,
sousaedu80135b92021-02-17 15:05:18 +010044 version as common_version,
45)
tierno1d213f42020-04-24 14:02:51 +000046from osm_common.dbbase import DbException
47from osm_common.fsbase import FsException
48from osm_common.msgbase import MsgException
sousaedu0fe84cb2022-01-17 13:48:22 +000049from osm_ng_ro.ns_thread import deep_get, NsWorker, NsWorkerException
50from osm_ng_ro.validation import deploy_schema, validate_input
tierno1d213f42020-04-24 14:02:51 +000051
52__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
53min_common_version = "0.1.16"
54
55
56class NsException(Exception):
tierno1d213f42020-04-24 14:02:51 +000057 def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
58 self.http_code = http_code
59 super(Exception, self).__init__(message)
60
61
62def get_process_id():
63 """
64 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
65 will provide a random one
66 :return: Obtained ID
67 """
68 # Try getting docker id. If fails, get pid
69 try:
70 with open("/proc/self/cgroup", "r") as f:
71 text_id_ = f.readline()
72 _, _, text_id = text_id_.rpartition("/")
73 text_id = text_id.replace("\n", "")[:12]
sousaedu80135b92021-02-17 15:05:18 +010074
tierno1d213f42020-04-24 14:02:51 +000075 if text_id:
76 return text_id
77 except Exception:
78 pass
sousaedu80135b92021-02-17 15:05:18 +010079
tierno1d213f42020-04-24 14:02:51 +000080 # Return a random id
81 return "".join(random_choice("0123456789abcdef") for _ in range(12))
82
83
84def versiontuple(v):
85 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
86 filled = []
sousaedu80135b92021-02-17 15:05:18 +010087
tierno1d213f42020-04-24 14:02:51 +000088 for point in v.split("."):
89 filled.append(point.zfill(8))
sousaedu80135b92021-02-17 15:05:18 +010090
tierno1d213f42020-04-24 14:02:51 +000091 return tuple(filled)
92
93
94class Ns(object):
tierno1d213f42020-04-24 14:02:51 +000095 def __init__(self):
96 self.db = None
97 self.fs = None
98 self.msg = None
99 self.config = None
100 # self.operations = None
tierno70eeb182020-10-19 16:38:00 +0000101 self.logger = None
102 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
103 # If done now it will not be linked to parent not getting its handler and level
tierno1d213f42020-04-24 14:02:51 +0000104 self.map_topic = {}
105 self.write_lock = None
tierno86153522020-12-06 18:27:16 +0000106 self.vims_assigned = {}
tierno1d213f42020-04-24 14:02:51 +0000107 self.next_worker = 0
108 self.plugins = {}
109 self.workers = []
110
111 def init_db(self, target_version):
112 pass
113
114 def start(self, config):
115 """
116 Connect to database, filesystem storage, and messaging
117 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
118 :param config: Configuration of db, storage, etc
119 :return: None
120 """
121 self.config = config
122 self.config["process_id"] = get_process_id() # used for HA identity
tierno70eeb182020-10-19 16:38:00 +0000123 self.logger = logging.getLogger("ro.ns")
sousaedu80135b92021-02-17 15:05:18 +0100124
tierno1d213f42020-04-24 14:02:51 +0000125 # check right version of common
126 if versiontuple(common_version) < versiontuple(min_common_version):
sousaedu80135b92021-02-17 15:05:18 +0100127 raise NsException(
128 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
129 common_version, min_common_version
130 )
131 )
tierno1d213f42020-04-24 14:02:51 +0000132
133 try:
134 if not self.db:
135 if config["database"]["driver"] == "mongo":
136 self.db = dbmongo.DbMongo()
137 self.db.db_connect(config["database"])
138 elif config["database"]["driver"] == "memory":
139 self.db = dbmemory.DbMemory()
140 self.db.db_connect(config["database"])
141 else:
sousaedu80135b92021-02-17 15:05:18 +0100142 raise NsException(
143 "Invalid configuration param '{}' at '[database]':'driver'".format(
144 config["database"]["driver"]
145 )
146 )
147
tierno1d213f42020-04-24 14:02:51 +0000148 if not self.fs:
149 if config["storage"]["driver"] == "local":
150 self.fs = fslocal.FsLocal()
151 self.fs.fs_connect(config["storage"])
152 elif config["storage"]["driver"] == "mongo":
153 self.fs = fsmongo.FsMongo()
154 self.fs.fs_connect(config["storage"])
tierno70eeb182020-10-19 16:38:00 +0000155 elif config["storage"]["driver"] is None:
156 pass
tierno1d213f42020-04-24 14:02:51 +0000157 else:
sousaedu80135b92021-02-17 15:05:18 +0100158 raise NsException(
159 "Invalid configuration param '{}' at '[storage]':'driver'".format(
160 config["storage"]["driver"]
161 )
162 )
163
tierno1d213f42020-04-24 14:02:51 +0000164 if not self.msg:
165 if config["message"]["driver"] == "local":
166 self.msg = msglocal.MsgLocal()
167 self.msg.connect(config["message"])
168 elif config["message"]["driver"] == "kafka":
169 self.msg = msgkafka.MsgKafka()
170 self.msg.connect(config["message"])
171 else:
sousaedu80135b92021-02-17 15:05:18 +0100172 raise NsException(
173 "Invalid configuration param '{}' at '[message]':'driver'".format(
174 config["message"]["driver"]
175 )
176 )
tierno1d213f42020-04-24 14:02:51 +0000177
178 # TODO load workers to deal with exising database tasks
179
180 self.write_lock = Lock()
181 except (DbException, FsException, MsgException) as e:
182 raise NsException(str(e), http_code=e.http_code)
sousaedu80135b92021-02-17 15:05:18 +0100183
tierno86153522020-12-06 18:27:16 +0000184 def get_assigned_vims(self):
185 return list(self.vims_assigned.keys())
tierno1d213f42020-04-24 14:02:51 +0000186
187 def stop(self):
188 try:
189 if self.db:
190 self.db.db_disconnect()
sousaedu80135b92021-02-17 15:05:18 +0100191
tierno1d213f42020-04-24 14:02:51 +0000192 if self.fs:
193 self.fs.fs_disconnect()
sousaedu80135b92021-02-17 15:05:18 +0100194
tierno1d213f42020-04-24 14:02:51 +0000195 if self.msg:
196 self.msg.disconnect()
sousaedu80135b92021-02-17 15:05:18 +0100197
tierno1d213f42020-04-24 14:02:51 +0000198 self.write_lock = None
199 except (DbException, FsException, MsgException) as e:
200 raise NsException(str(e), http_code=e.http_code)
sousaedu80135b92021-02-17 15:05:18 +0100201
tierno1d213f42020-04-24 14:02:51 +0000202 for worker in self.workers:
203 worker.insert_task(("terminate",))
204
tierno86153522020-12-06 18:27:16 +0000205 def _create_worker(self):
206 """
207 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
208 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
209 return the index of the assigned worker thread. Worker threads are storead at self.workers
210 """
211 # Look for a thread in idle status
sousaedu80135b92021-02-17 15:05:18 +0100212 worker_id = next(
213 (
214 i
215 for i in range(len(self.workers))
216 if self.workers[i] and self.workers[i].idle
217 ),
218 None,
219 )
220
tierno86153522020-12-06 18:27:16 +0000221 if worker_id is not None:
222 # unset idle status to avoid race conditions
223 self.workers[worker_id].idle = False
tierno70eeb182020-10-19 16:38:00 +0000224 else:
225 worker_id = len(self.workers)
sousaedu80135b92021-02-17 15:05:18 +0100226
tierno70eeb182020-10-19 16:38:00 +0000227 if worker_id < self.config["global"]["server.ns_threads"]:
228 # create a new worker
sousaedu80135b92021-02-17 15:05:18 +0100229 self.workers.append(
230 NsWorker(worker_id, self.config, self.plugins, self.db)
231 )
tierno70eeb182020-10-19 16:38:00 +0000232 self.workers[worker_id].start()
233 else:
234 # reached maximum number of threads, assign VIM to an existing one
235 worker_id = self.next_worker
sousaedu80135b92021-02-17 15:05:18 +0100236 self.next_worker = (self.next_worker + 1) % self.config["global"][
237 "server.ns_threads"
238 ]
239
tierno1d213f42020-04-24 14:02:51 +0000240 return worker_id
241
tierno70eeb182020-10-19 16:38:00 +0000242 def assign_vim(self, target_id):
tierno86153522020-12-06 18:27:16 +0000243 with self.write_lock:
244 return self._assign_vim(target_id)
245
246 def _assign_vim(self, target_id):
247 if target_id not in self.vims_assigned:
248 worker_id = self.vims_assigned[target_id] = self._create_worker()
249 self.workers[worker_id].insert_task(("load_vim", target_id))
tierno70eeb182020-10-19 16:38:00 +0000250
251 def reload_vim(self, target_id):
252 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
253 # this is because database VIM information is cached for threads working with SDN
tierno86153522020-12-06 18:27:16 +0000254 with self.write_lock:
255 for worker in self.workers:
256 if worker and not worker.idle:
257 worker.insert_task(("reload_vim", target_id))
tierno70eeb182020-10-19 16:38:00 +0000258
259 def unload_vim(self, target_id):
tierno86153522020-12-06 18:27:16 +0000260 with self.write_lock:
261 return self._unload_vim(target_id)
262
263 def _unload_vim(self, target_id):
264 if target_id in self.vims_assigned:
265 worker_id = self.vims_assigned[target_id]
tierno70eeb182020-10-19 16:38:00 +0000266 self.workers[worker_id].insert_task(("unload_vim", target_id))
tierno86153522020-12-06 18:27:16 +0000267 del self.vims_assigned[target_id]
tierno70eeb182020-10-19 16:38:00 +0000268
269 def check_vim(self, target_id):
tierno86153522020-12-06 18:27:16 +0000270 with self.write_lock:
271 if target_id in self.vims_assigned:
272 worker_id = self.vims_assigned[target_id]
273 else:
274 worker_id = self._create_worker()
tierno70eeb182020-10-19 16:38:00 +0000275
276 worker = self.workers[worker_id]
277 worker.insert_task(("check_vim", target_id))
tierno1d213f42020-04-24 14:02:51 +0000278
tierno86153522020-12-06 18:27:16 +0000279 def unload_unused_vims(self):
280 with self.write_lock:
281 vims_to_unload = []
sousaedu80135b92021-02-17 15:05:18 +0100282
tierno86153522020-12-06 18:27:16 +0000283 for target_id in self.vims_assigned:
sousaedu80135b92021-02-17 15:05:18 +0100284 if not self.db.get_one(
285 "ro_tasks",
286 q_filter={
287 "target_id": target_id,
288 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
289 },
290 fail_on_empty=False,
291 ):
tierno86153522020-12-06 18:27:16 +0000292 vims_to_unload.append(target_id)
sousaedu80135b92021-02-17 15:05:18 +0100293
tierno86153522020-12-06 18:27:16 +0000294 for target_id in vims_to_unload:
295 self._unload_vim(target_id)
296
tierno1d213f42020-04-24 14:02:51 +0000297 def _get_cloud_init(self, where):
298 """
tierno86153522020-12-06 18:27:16 +0000299 Not used as cloud init content is provided in the http body. This method reads cloud init from a file
tierno1d213f42020-04-24 14:02:51 +0000300 :param where: can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
301 :return:
302 """
303 vnfd_id, _, other = where.partition(":")
304 _type, _, name = other.partition(":")
305 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
sousaedu80135b92021-02-17 15:05:18 +0100306
tierno1d213f42020-04-24 14:02:51 +0000307 if _type == "file":
308 base_folder = vnfd["_admin"]["storage"]
sousaedu80135b92021-02-17 15:05:18 +0100309 cloud_init_file = "{}/{}/cloud_init/{}".format(
310 base_folder["folder"], base_folder["pkg-dir"], name
311 )
312
tierno70eeb182020-10-19 16:38:00 +0000313 if not self.fs:
sousaedu80135b92021-02-17 15:05:18 +0100314 raise NsException(
315 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
316 cloud_init_file
317 )
318 )
319
tierno1d213f42020-04-24 14:02:51 +0000320 with self.fs.file_open(cloud_init_file, "r") as ci_file:
321 cloud_init_content = ci_file.read()
322 elif _type == "vdu":
323 cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"]
324 else:
325 raise NsException("Mismatch descriptor for cloud init: {}".format(where))
sousaedu80135b92021-02-17 15:05:18 +0100326
tierno1d213f42020-04-24 14:02:51 +0000327 return cloud_init_content
328
329 def _parse_jinja2(self, cloud_init_content, params, context):
tierno70eeb182020-10-19 16:38:00 +0000330 try:
331 env = Environment(undefined=StrictUndefined)
332 template = env.from_string(cloud_init_content)
sousaedu80135b92021-02-17 15:05:18 +0100333
tierno70eeb182020-10-19 16:38:00 +0000334 return template.render(params or {})
335 except UndefinedError as e:
336 raise NsException(
337 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
sousaedu80135b92021-02-17 15:05:18 +0100338 "inside the 'additionalParamsForVnf' block".format(e, context)
339 )
tierno70eeb182020-10-19 16:38:00 +0000340 except (TemplateError, TemplateNotFound) as e:
sousaedu80135b92021-02-17 15:05:18 +0100341 raise NsException(
342 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
343 context, e
344 )
345 )
tierno1d213f42020-04-24 14:02:51 +0000346
347 def _create_db_ro_nsrs(self, nsr_id, now):
348 try:
349 key = rsa.generate_private_key(
sousaedu80135b92021-02-17 15:05:18 +0100350 backend=crypto_default_backend(), public_exponent=65537, key_size=2048
tierno1d213f42020-04-24 14:02:51 +0000351 )
352 private_key = key.private_bytes(
353 crypto_serialization.Encoding.PEM,
354 crypto_serialization.PrivateFormat.PKCS8,
sousaedu80135b92021-02-17 15:05:18 +0100355 crypto_serialization.NoEncryption(),
356 )
tierno1d213f42020-04-24 14:02:51 +0000357 public_key = key.public_key().public_bytes(
358 crypto_serialization.Encoding.OpenSSH,
sousaedu80135b92021-02-17 15:05:18 +0100359 crypto_serialization.PublicFormat.OpenSSH,
tierno1d213f42020-04-24 14:02:51 +0000360 )
sousaedu80135b92021-02-17 15:05:18 +0100361 private_key = private_key.decode("utf8")
tierno70eeb182020-10-19 16:38:00 +0000362 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
363 i = private_key.find("\n")
364 private_key = "-----BEGIN RSA PRIVATE KEY-----" + private_key[i:]
sousaedu80135b92021-02-17 15:05:18 +0100365 public_key = public_key.decode("utf8")
tierno1d213f42020-04-24 14:02:51 +0000366 except Exception as e:
367 raise NsException("Cannot create ssh-keys: {}".format(e))
368
369 schema_version = "1.1"
sousaedu80135b92021-02-17 15:05:18 +0100370 private_key_encrypted = self.db.encrypt(
371 private_key, schema_version=schema_version, salt=nsr_id
372 )
tierno1d213f42020-04-24 14:02:51 +0000373 db_content = {
374 "_id": nsr_id,
375 "_admin": {
376 "created": now,
377 "modified": now,
sousaedu80135b92021-02-17 15:05:18 +0100378 "schema_version": schema_version,
tierno1d213f42020-04-24 14:02:51 +0000379 },
380 "public_key": public_key,
381 "private_key": private_key_encrypted,
sousaedu80135b92021-02-17 15:05:18 +0100382 "actions": [],
tierno1d213f42020-04-24 14:02:51 +0000383 }
384 self.db.create("ro_nsrs", db_content)
sousaedu80135b92021-02-17 15:05:18 +0100385
tierno1d213f42020-04-24 14:02:51 +0000386 return db_content
387
388 def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
tierno70eeb182020-10-19 16:38:00 +0000389 self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
tierno1d213f42020-04-24 14:02:51 +0000390 validate_input(indata, deploy_schema)
391 action_id = indata.get("action_id", str(uuid4()))
392 task_index = 0
393 # get current deployment
sousaedu80135b92021-02-17 15:05:18 +0100394 db_nsr_update = {} # update operation on nsrs
tierno1d213f42020-04-24 14:02:51 +0000395 db_vnfrs_update = {}
sousaedu80135b92021-02-17 15:05:18 +0100396 db_vnfrs = {} # vnf's info indexed by _id
tierno70eeb182020-10-19 16:38:00 +0000397 nb_ro_tasks = 0 # for logging
398 vdu2cloud_init = indata.get("cloud_init_content") or {}
sousaedu80135b92021-02-17 15:05:18 +0100399 step = ""
tierno1d213f42020-04-24 14:02:51 +0000400 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
401 self.logger.debug(logging_text + "Enter")
sousaedu80135b92021-02-17 15:05:18 +0100402
tierno1d213f42020-04-24 14:02:51 +0000403 try:
404 step = "Getting ns and vnfr record from db"
tierno1d213f42020-04-24 14:02:51 +0000405 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tierno1d213f42020-04-24 14:02:51 +0000406 db_new_tasks = []
tierno70eeb182020-10-19 16:38:00 +0000407 tasks_by_target_record_id = {}
tierno1d213f42020-04-24 14:02:51 +0000408 # read from db: vnf's of this ns
409 step = "Getting vnfrs from db"
410 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
sousaedu80135b92021-02-17 15:05:18 +0100411
tierno1d213f42020-04-24 14:02:51 +0000412 if not db_vnfrs_list:
413 raise NsException("Cannot obtain associated VNF for ns")
sousaedu80135b92021-02-17 15:05:18 +0100414
tierno1d213f42020-04-24 14:02:51 +0000415 for vnfr in db_vnfrs_list:
416 db_vnfrs[vnfr["_id"]] = vnfr
417 db_vnfrs_update[vnfr["_id"]] = {}
sousaedu80135b92021-02-17 15:05:18 +0100418
tierno1d213f42020-04-24 14:02:51 +0000419 now = time()
420 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
sousaedu80135b92021-02-17 15:05:18 +0100421
tierno1d213f42020-04-24 14:02:51 +0000422 if not db_ro_nsr:
423 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
sousaedu80135b92021-02-17 15:05:18 +0100424
tierno1d213f42020-04-24 14:02:51 +0000425 ro_nsr_public_key = db_ro_nsr["public_key"]
426
427 # check that action_id is not in the list of actions. Suffixed with :index
428 if action_id in db_ro_nsr["actions"]:
429 index = 1
sousaedu80135b92021-02-17 15:05:18 +0100430
tierno1d213f42020-04-24 14:02:51 +0000431 while True:
432 new_action_id = "{}:{}".format(action_id, index)
sousaedu80135b92021-02-17 15:05:18 +0100433
tierno1d213f42020-04-24 14:02:51 +0000434 if new_action_id not in db_ro_nsr["actions"]:
435 action_id = new_action_id
sousaedu80135b92021-02-17 15:05:18 +0100436 self.logger.debug(
437 logging_text
438 + "Changing action_id in use to {}".format(action_id)
439 )
tierno1d213f42020-04-24 14:02:51 +0000440 break
sousaedu80135b92021-02-17 15:05:18 +0100441
tierno1d213f42020-04-24 14:02:51 +0000442 index += 1
443
sousaedu80135b92021-02-17 15:05:18 +0100444 def _create_task(
445 target_id,
446 item,
447 action,
448 target_record,
449 target_record_id,
450 extra_dict=None,
451 ):
tierno1d213f42020-04-24 14:02:51 +0000452 nonlocal task_index
453 nonlocal action_id
454 nonlocal nsr_id
455
456 task = {
tierno70eeb182020-10-19 16:38:00 +0000457 "target_id": target_id, # it will be removed before pushing at database
tierno1d213f42020-04-24 14:02:51 +0000458 "action_id": action_id,
459 "nsr_id": nsr_id,
460 "task_id": "{}:{}".format(action_id, task_index),
461 "status": "SCHEDULED",
462 "action": action,
463 "item": item,
464 "target_record": target_record,
465 "target_record_id": target_record_id,
466 }
sousaedu80135b92021-02-17 15:05:18 +0100467
tierno1d213f42020-04-24 14:02:51 +0000468 if extra_dict:
sousaedu80135b92021-02-17 15:05:18 +0100469 task.update(extra_dict) # params, find_params, depends_on
470
tierno1d213f42020-04-24 14:02:51 +0000471 task_index += 1
sousaedu80135b92021-02-17 15:05:18 +0100472
tierno1d213f42020-04-24 14:02:51 +0000473 return task
474
tierno70eeb182020-10-19 16:38:00 +0000475 def _create_ro_task(target_id, task):
tierno1d213f42020-04-24 14:02:51 +0000476 nonlocal action_id
477 nonlocal task_index
478 nonlocal now
479
tierno70eeb182020-10-19 16:38:00 +0000480 _id = task["task_id"]
tierno1d213f42020-04-24 14:02:51 +0000481 db_ro_task = {
482 "_id": _id,
483 "locked_by": None,
484 "locked_at": 0.0,
tierno70eeb182020-10-19 16:38:00 +0000485 "target_id": target_id,
tierno1d213f42020-04-24 14:02:51 +0000486 "vim_info": {
487 "created": False,
488 "created_items": None,
489 "vim_id": None,
490 "vim_name": None,
491 "vim_status": None,
492 "vim_details": None,
493 "refresh_at": None,
494 },
495 "modified_at": now,
496 "created_at": now,
497 "to_check_at": now,
tierno70eeb182020-10-19 16:38:00 +0000498 "tasks": [task],
tierno1d213f42020-04-24 14:02:51 +0000499 }
sousaedu80135b92021-02-17 15:05:18 +0100500
tierno1d213f42020-04-24 14:02:51 +0000501 return db_ro_task
502
tierno70eeb182020-10-19 16:38:00 +0000503 def _process_image_params(target_image, vim_info, target_record_id):
tierno1d213f42020-04-24 14:02:51 +0000504 find_params = {}
sousaedu80135b92021-02-17 15:05:18 +0100505
tierno1d213f42020-04-24 14:02:51 +0000506 if target_image.get("image"):
507 find_params["filter_dict"] = {"name": target_image.get("image")}
sousaedu80135b92021-02-17 15:05:18 +0100508
tierno1d213f42020-04-24 14:02:51 +0000509 if target_image.get("vim_image_id"):
sousaedu80135b92021-02-17 15:05:18 +0100510 find_params["filter_dict"] = {
511 "id": target_image.get("vim_image_id")
512 }
513
tierno1d213f42020-04-24 14:02:51 +0000514 if target_image.get("image_checksum"):
sousaedu80135b92021-02-17 15:05:18 +0100515 find_params["filter_dict"] = {
516 "checksum": target_image.get("image_checksum")
517 }
518
tierno1d213f42020-04-24 14:02:51 +0000519 return {"find_params": find_params}
520
tierno70eeb182020-10-19 16:38:00 +0000521 def _process_flavor_params(target_flavor, vim_info, target_record_id):
tierno1d213f42020-04-24 14:02:51 +0000522 def _get_resource_allocation_params(quota_descriptor):
523 """
524 read the quota_descriptor from vnfd and fetch the resource allocation properties from the
525 descriptor object
526 :param quota_descriptor: cpu/mem/vif/disk-io quota descriptor
527 :return: quota params for limit, reserve, shares from the descriptor object
528 """
529 quota = {}
sousaedu80135b92021-02-17 15:05:18 +0100530
tierno1d213f42020-04-24 14:02:51 +0000531 if quota_descriptor.get("limit"):
532 quota["limit"] = int(quota_descriptor["limit"])
sousaedu80135b92021-02-17 15:05:18 +0100533
tierno1d213f42020-04-24 14:02:51 +0000534 if quota_descriptor.get("reserve"):
535 quota["reserve"] = int(quota_descriptor["reserve"])
sousaedu80135b92021-02-17 15:05:18 +0100536
tierno1d213f42020-04-24 14:02:51 +0000537 if quota_descriptor.get("shares"):
538 quota["shares"] = int(quota_descriptor["shares"])
sousaedu80135b92021-02-17 15:05:18 +0100539
tierno1d213f42020-04-24 14:02:51 +0000540 return quota
541
sousaedu0e958862021-11-22 14:02:17 +0000542 nonlocal indata
543
tierno1d213f42020-04-24 14:02:51 +0000544 flavor_data = {
545 "disk": int(target_flavor["storage-gb"]),
tierno1d213f42020-04-24 14:02:51 +0000546 "ram": int(target_flavor["memory-mb"]),
tiernofb13d2e2020-11-26 15:55:20 +0000547 "vcpus": int(target_flavor["vcpu-count"]),
tierno1d213f42020-04-24 14:02:51 +0000548 }
tierno70eeb182020-10-19 16:38:00 +0000549 numa = {}
550 extended = {}
sousaedu80135b92021-02-17 15:05:18 +0100551
sousaedu0e958862021-11-22 14:02:17 +0000552 target_vdur = None
553 for vnf in indata.get("vnf", []):
554 for vdur in vnf.get("vdur", []):
555 if vdur.get("ns-flavor-id") == target_flavor["id"]:
556 target_vdur = vdur
557
558 for storage in target_vdur.get("virtual-storages", []):
559 if (
560 storage.get("type-of-storage")
561 == "etsi-nfv-descriptors:ephemeral-storage"
562 ):
563 flavor_data["ephemeral"] = int(
564 storage.get("size-of-storage", 0)
565 )
sousaedu61f8b372021-11-22 14:09:15 +0000566 elif (
567 storage.get("type-of-storage")
568 == "etsi-nfv-descriptors:swap-storage"
569 ):
570 flavor_data["swap"] = int(storage.get("size-of-storage", 0))
sousaedu0e958862021-11-22 14:02:17 +0000571
tierno1d213f42020-04-24 14:02:51 +0000572 if target_flavor.get("guest-epa"):
573 extended = {}
tierno1d213f42020-04-24 14:02:51 +0000574 epa_vcpu_set = False
sousaedu80135b92021-02-17 15:05:18 +0100575
tierno1d213f42020-04-24 14:02:51 +0000576 if target_flavor["guest-epa"].get("numa-node-policy"):
sousaedu80135b92021-02-17 15:05:18 +0100577 numa_node_policy = target_flavor["guest-epa"].get(
578 "numa-node-policy"
579 )
580
tierno1d213f42020-04-24 14:02:51 +0000581 if numa_node_policy.get("node"):
582 numa_node = numa_node_policy["node"][0]
sousaedu80135b92021-02-17 15:05:18 +0100583
tierno1d213f42020-04-24 14:02:51 +0000584 if numa_node.get("num-cores"):
585 numa["cores"] = numa_node["num-cores"]
586 epa_vcpu_set = True
sousaedu80135b92021-02-17 15:05:18 +0100587
tierno1d213f42020-04-24 14:02:51 +0000588 if numa_node.get("paired-threads"):
sousaedu80135b92021-02-17 15:05:18 +0100589 if numa_node["paired-threads"].get(
590 "num-paired-threads"
591 ):
592 numa["paired-threads"] = int(
593 numa_node["paired-threads"][
594 "num-paired-threads"
595 ]
596 )
tierno1d213f42020-04-24 14:02:51 +0000597 epa_vcpu_set = True
sousaedu80135b92021-02-17 15:05:18 +0100598
599 if len(
600 numa_node["paired-threads"].get("paired-thread-ids")
601 ):
tierno1d213f42020-04-24 14:02:51 +0000602 numa["paired-threads-id"] = []
sousaedu80135b92021-02-17 15:05:18 +0100603
604 for pair in numa_node["paired-threads"][
605 "paired-thread-ids"
606 ]:
tierno1d213f42020-04-24 14:02:51 +0000607 numa["paired-threads-id"].append(
sousaedu80135b92021-02-17 15:05:18 +0100608 (
609 str(pair["thread-a"]),
610 str(pair["thread-b"]),
611 )
tierno1d213f42020-04-24 14:02:51 +0000612 )
sousaedu80135b92021-02-17 15:05:18 +0100613
tierno1d213f42020-04-24 14:02:51 +0000614 if numa_node.get("num-threads"):
615 numa["threads"] = int(numa_node["num-threads"])
616 epa_vcpu_set = True
sousaedu80135b92021-02-17 15:05:18 +0100617
tierno1d213f42020-04-24 14:02:51 +0000618 if numa_node.get("memory-mb"):
sousaedu80135b92021-02-17 15:05:18 +0100619 numa["memory"] = max(
620 int(numa_node["memory-mb"] / 1024), 1
621 )
622
tierno1d213f42020-04-24 14:02:51 +0000623 if target_flavor["guest-epa"].get("mempage-size"):
sousaedu80135b92021-02-17 15:05:18 +0100624 extended["mempage-size"] = target_flavor["guest-epa"].get(
625 "mempage-size"
626 )
627
628 if (
629 target_flavor["guest-epa"].get("cpu-pinning-policy")
630 and not epa_vcpu_set
631 ):
632 if (
633 target_flavor["guest-epa"]["cpu-pinning-policy"]
634 == "DEDICATED"
635 ):
636 if (
637 target_flavor["guest-epa"].get(
638 "cpu-thread-pinning-policy"
639 )
640 and target_flavor["guest-epa"][
641 "cpu-thread-pinning-policy"
642 ]
643 != "PREFER"
644 ):
tierno1d213f42020-04-24 14:02:51 +0000645 numa["cores"] = max(flavor_data["vcpus"], 1)
646 else:
647 numa["threads"] = max(flavor_data["vcpus"], 1)
sousaedu80135b92021-02-17 15:05:18 +0100648
tierno1d213f42020-04-24 14:02:51 +0000649 epa_vcpu_set = True
sousaedu80135b92021-02-17 15:05:18 +0100650
tierno1d213f42020-04-24 14:02:51 +0000651 if target_flavor["guest-epa"].get("cpu-quota") and not epa_vcpu_set:
sousaedu80135b92021-02-17 15:05:18 +0100652 cpuquota = _get_resource_allocation_params(
653 target_flavor["guest-epa"].get("cpu-quota")
654 )
655
tierno1d213f42020-04-24 14:02:51 +0000656 if cpuquota:
657 extended["cpu-quota"] = cpuquota
sousaedu80135b92021-02-17 15:05:18 +0100658
tierno1d213f42020-04-24 14:02:51 +0000659 if target_flavor["guest-epa"].get("mem-quota"):
sousaedu80135b92021-02-17 15:05:18 +0100660 vduquota = _get_resource_allocation_params(
661 target_flavor["guest-epa"].get("mem-quota")
662 )
663
tierno1d213f42020-04-24 14:02:51 +0000664 if vduquota:
665 extended["mem-quota"] = vduquota
sousaedu80135b92021-02-17 15:05:18 +0100666
tierno1d213f42020-04-24 14:02:51 +0000667 if target_flavor["guest-epa"].get("disk-io-quota"):
sousaedu80135b92021-02-17 15:05:18 +0100668 diskioquota = _get_resource_allocation_params(
669 target_flavor["guest-epa"].get("disk-io-quota")
670 )
671
tierno1d213f42020-04-24 14:02:51 +0000672 if diskioquota:
673 extended["disk-io-quota"] = diskioquota
sousaedu80135b92021-02-17 15:05:18 +0100674
tierno1d213f42020-04-24 14:02:51 +0000675 if target_flavor["guest-epa"].get("vif-quota"):
sousaedu80135b92021-02-17 15:05:18 +0100676 vifquota = _get_resource_allocation_params(
677 target_flavor["guest-epa"].get("vif-quota")
678 )
679
tierno1d213f42020-04-24 14:02:51 +0000680 if vifquota:
681 extended["vif-quota"] = vifquota
sousaedu80135b92021-02-17 15:05:18 +0100682
tierno1d213f42020-04-24 14:02:51 +0000683 if numa:
684 extended["numas"] = [numa]
sousaedu80135b92021-02-17 15:05:18 +0100685
tierno1d213f42020-04-24 14:02:51 +0000686 if extended:
687 flavor_data["extended"] = extended
688
689 extra_dict = {"find_params": {"flavor_data": flavor_data}}
690 flavor_data_name = flavor_data.copy()
691 flavor_data_name["name"] = target_flavor["name"]
692 extra_dict["params"] = {"flavor_data": flavor_data_name}
sousaedu80135b92021-02-17 15:05:18 +0100693
tierno1d213f42020-04-24 14:02:51 +0000694 return extra_dict
695
aticig72c67142022-03-31 22:03:33 +0300696 def _process_affinity_group_params(
697 target_affinity_group, vim_info, target_record_id
698 ):
Alexis Romero73993212022-04-13 18:03:30 +0200699 extra_dict = {}
700
701 affinity_group_data = {
702 "name": target_affinity_group["name"],
703 "type": target_affinity_group["type"],
704 "scope": target_affinity_group["scope"],
705 }
706
707 extra_dict["params"] = {
708 "affinity_group_data": affinity_group_data,
709 }
710
711 return extra_dict
712
tierno70eeb182020-10-19 16:38:00 +0000713 def _ip_profile_2_ro(ip_profile):
714 if not ip_profile:
715 return None
sousaedu80135b92021-02-17 15:05:18 +0100716
tierno70eeb182020-10-19 16:38:00 +0000717 ro_ip_profile = {
sousaedu80135b92021-02-17 15:05:18 +0100718 "ip_version": "IPv4"
719 if "v4" in ip_profile.get("ip-version", "ipv4")
720 else "IPv6",
tierno70eeb182020-10-19 16:38:00 +0000721 "subnet_address": ip_profile.get("subnet-address"),
722 "gateway_address": ip_profile.get("gateway-address"),
sousaeduf29a91f2021-03-02 01:42:51 +0100723 "dhcp_enabled": ip_profile.get("dhcp-params", {}).get(
724 "enabled", False
725 ),
726 "dhcp_start_address": ip_profile.get("dhcp-params", {}).get(
727 "start-address", None
728 ),
sousaedu96abfc22021-02-18 14:57:01 +0100729 "dhcp_count": ip_profile.get("dhcp-params", {}).get("count", None),
tierno70eeb182020-10-19 16:38:00 +0000730 }
sousaedu80135b92021-02-17 15:05:18 +0100731
tierno70eeb182020-10-19 16:38:00 +0000732 if ip_profile.get("dns-server"):
sousaedu80135b92021-02-17 15:05:18 +0100733 ro_ip_profile["dns_address"] = ";".join(
734 [v["address"] for v in ip_profile["dns-server"]]
735 )
736
737 if ip_profile.get("security-group"):
738 ro_ip_profile["security_group"] = ip_profile["security-group"]
739
tierno70eeb182020-10-19 16:38:00 +0000740 return ro_ip_profile
741
742 def _process_net_params(target_vld, vim_info, target_record_id):
tierno1d213f42020-04-24 14:02:51 +0000743 nonlocal indata
744 extra_dict = {}
tierno70eeb182020-10-19 16:38:00 +0000745
746 if vim_info.get("sdn"):
747 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
748 # ns_preffix = "nsrs:{}".format(nsr_id)
sousaedu80135b92021-02-17 15:05:18 +0100749 # remove the ending ".sdn
750 vld_target_record_id, _, _ = target_record_id.rpartition(".")
751 extra_dict["params"] = {
752 k: vim_info[k]
753 for k in ("sdn-ports", "target_vim", "vlds", "type")
754 if vim_info.get(k)
755 }
756
tierno70eeb182020-10-19 16:38:00 +0000757 # TODO needed to add target_id in the dependency.
758 if vim_info.get("target_vim"):
sousaedu80135b92021-02-17 15:05:18 +0100759 extra_dict["depends_on"] = [
760 vim_info.get("target_vim") + " " + vld_target_record_id
761 ]
762
tierno70eeb182020-10-19 16:38:00 +0000763 return extra_dict
764
tierno1d213f42020-04-24 14:02:51 +0000765 if vim_info.get("vim_network_name"):
sousaedu80135b92021-02-17 15:05:18 +0100766 extra_dict["find_params"] = {
767 "filter_dict": {"name": vim_info.get("vim_network_name")}
768 }
tierno1d213f42020-04-24 14:02:51 +0000769 elif vim_info.get("vim_network_id"):
sousaedu80135b92021-02-17 15:05:18 +0100770 extra_dict["find_params"] = {
771 "filter_dict": {"id": vim_info.get("vim_network_id")}
772 }
tierno1d213f42020-04-24 14:02:51 +0000773 elif target_vld.get("mgmt-network"):
774 extra_dict["find_params"] = {"mgmt": True, "name": target_vld["id"]}
775 else:
776 # create
777 extra_dict["params"] = {
sousaedu80135b92021-02-17 15:05:18 +0100778 "net_name": "{}-{}".format(
779 indata["name"][:16],
780 target_vld.get("name", target_vld["id"])[:16],
781 ),
782 "ip_profile": _ip_profile_2_ro(vim_info.get("ip_profile")),
783 "provider_network_profile": vim_info.get("provider_network"),
tierno1d213f42020-04-24 14:02:51 +0000784 }
sousaedu80135b92021-02-17 15:05:18 +0100785
tierno1d213f42020-04-24 14:02:51 +0000786 if not target_vld.get("underlay"):
787 extra_dict["params"]["net_type"] = "bridge"
788 else:
sousaedu80135b92021-02-17 15:05:18 +0100789 extra_dict["params"]["net_type"] = (
790 "ptp" if target_vld.get("type") == "ELINE" else "data"
791 )
792
tierno1d213f42020-04-24 14:02:51 +0000793 return extra_dict
794
tierno70eeb182020-10-19 16:38:00 +0000795 def _process_vdu_params(target_vdu, vim_info, target_record_id):
tierno1d213f42020-04-24 14:02:51 +0000796 nonlocal vnfr_id
797 nonlocal nsr_id
798 nonlocal indata
799 nonlocal vnfr
800 nonlocal vdu2cloud_init
tierno70eeb182020-10-19 16:38:00 +0000801 nonlocal tasks_by_target_record_id
sousaedu80135b92021-02-17 15:05:18 +0100802
tierno1d213f42020-04-24 14:02:51 +0000803 vnf_preffix = "vnfrs:{}".format(vnfr_id)
804 ns_preffix = "nsrs:{}".format(nsr_id)
805 image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
806 flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
807 extra_dict = {"depends_on": [image_text, flavor_text]}
808 net_list = []
sousaedu80135b92021-02-17 15:05:18 +0100809
tierno1d213f42020-04-24 14:02:51 +0000810 for iface_index, interface in enumerate(target_vdu["interfaces"]):
811 if interface.get("ns-vld-id"):
812 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
tierno55fa0bb2020-12-08 23:11:53 +0000813 elif interface.get("vnf-vld-id"):
tierno1d213f42020-04-24 14:02:51 +0000814 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
tierno55fa0bb2020-12-08 23:11:53 +0000815 else:
sousaedu80135b92021-02-17 15:05:18 +0100816 self.logger.error(
817 "Interface {} from vdu {} not connected to any vld".format(
818 iface_index, target_vdu["vdu-name"]
819 )
820 )
821
822 continue # interface not connected to any vld
823
tierno1d213f42020-04-24 14:02:51 +0000824 extra_dict["depends_on"].append(net_text)
sousaedu38d12172021-03-02 00:15:52 +0100825
826 if "port-security-enabled" in interface:
sousaedu96abfc22021-02-18 14:57:01 +0100827 interface["port_security"] = interface.pop(
828 "port-security-enabled"
sousaedu38d12172021-03-02 00:15:52 +0100829 )
830
831 if "port-security-disable-strategy" in interface:
sousaedu96abfc22021-02-18 14:57:01 +0100832 interface["port_security_disable_strategy"] = interface.pop(
833 "port-security-disable-strategy"
sousaedu38d12172021-03-02 00:15:52 +0100834 )
835
sousaedu80135b92021-02-17 15:05:18 +0100836 net_item = {
837 x: v
838 for x, v in interface.items()
839 if x
840 in (
841 "name",
842 "vpci",
843 "port_security",
844 "port_security_disable_strategy",
845 "floating_ip",
846 )
847 }
tierno70eeb182020-10-19 16:38:00 +0000848 net_item["net_id"] = "TASK-" + net_text
849 net_item["type"] = "virtual"
sousaedu80135b92021-02-17 15:05:18 +0100850
tierno70eeb182020-10-19 16:38:00 +0000851 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
852 # TODO floating_ip: True/False (or it can be None)
tierno1d213f42020-04-24 14:02:51 +0000853 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
tierno70eeb182020-10-19 16:38:00 +0000854 # mark the net create task as type data
sousaedu80135b92021-02-17 15:05:18 +0100855 if deep_get(
856 tasks_by_target_record_id, net_text, "params", "net_type"
857 ):
858 tasks_by_target_record_id[net_text]["params"][
859 "net_type"
860 ] = "data"
861
tierno1d213f42020-04-24 14:02:51 +0000862 net_item["use"] = "data"
863 net_item["model"] = interface["type"]
864 net_item["type"] = interface["type"]
sousaedu80135b92021-02-17 15:05:18 +0100865 elif (
866 interface.get("type") == "OM-MGMT"
867 or interface.get("mgmt-interface")
868 or interface.get("mgmt-vnf")
869 ):
tierno1d213f42020-04-24 14:02:51 +0000870 net_item["use"] = "mgmt"
sousaedu80135b92021-02-17 15:05:18 +0100871 else:
872 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
tierno1d213f42020-04-24 14:02:51 +0000873 net_item["use"] = "bridge"
874 net_item["model"] = interface.get("type")
sousaedu80135b92021-02-17 15:05:18 +0100875
tierno70eeb182020-10-19 16:38:00 +0000876 if interface.get("ip-address"):
877 net_item["ip_address"] = interface["ip-address"]
sousaedu80135b92021-02-17 15:05:18 +0100878
tierno70eeb182020-10-19 16:38:00 +0000879 if interface.get("mac-address"):
880 net_item["mac_address"] = interface["mac-address"]
sousaedu80135b92021-02-17 15:05:18 +0100881
tierno1d213f42020-04-24 14:02:51 +0000882 net_list.append(net_item)
sousaedu80135b92021-02-17 15:05:18 +0100883
tierno1d213f42020-04-24 14:02:51 +0000884 if interface.get("mgmt-vnf"):
885 extra_dict["mgmt_vnf_interface"] = iface_index
886 elif interface.get("mgmt-interface"):
887 extra_dict["mgmt_vdu_interface"] = iface_index
sousaedu80135b92021-02-17 15:05:18 +0100888
tierno1d213f42020-04-24 14:02:51 +0000889 # cloud config
890 cloud_config = {}
sousaedu80135b92021-02-17 15:05:18 +0100891
tierno1d213f42020-04-24 14:02:51 +0000892 if target_vdu.get("cloud-init"):
893 if target_vdu["cloud-init"] not in vdu2cloud_init:
sousaedu80135b92021-02-17 15:05:18 +0100894 vdu2cloud_init[target_vdu["cloud-init"]] = self._get_cloud_init(
895 target_vdu["cloud-init"]
896 )
897
tierno1d213f42020-04-24 14:02:51 +0000898 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
sousaedu80135b92021-02-17 15:05:18 +0100899 cloud_config["user-data"] = self._parse_jinja2(
900 cloud_content_,
901 target_vdu.get("additionalParams"),
902 target_vdu["cloud-init"],
903 )
904
tierno1d213f42020-04-24 14:02:51 +0000905 if target_vdu.get("boot-data-drive"):
906 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
sousaedu80135b92021-02-17 15:05:18 +0100907
tierno1d213f42020-04-24 14:02:51 +0000908 ssh_keys = []
sousaedu80135b92021-02-17 15:05:18 +0100909
tierno1d213f42020-04-24 14:02:51 +0000910 if target_vdu.get("ssh-keys"):
911 ssh_keys += target_vdu.get("ssh-keys")
sousaedu80135b92021-02-17 15:05:18 +0100912
tierno1d213f42020-04-24 14:02:51 +0000913 if target_vdu.get("ssh-access-required"):
914 ssh_keys.append(ro_nsr_public_key)
sousaedu80135b92021-02-17 15:05:18 +0100915
tierno1d213f42020-04-24 14:02:51 +0000916 if ssh_keys:
917 cloud_config["key-pairs"] = ssh_keys
918
sousaedu812bc6f2021-11-11 22:00:27 +0000919 disk_list = None
920 if target_vdu.get("virtual-storages"):
921 disk_list = [
922 {"size": disk["size-of-storage"]}
923 for disk in target_vdu["virtual-storages"]
924 if disk.get("type-of-storage")
925 == "persistent-storage:persistent-storage"
926 ]
927
Alexis Romero73993212022-04-13 18:03:30 +0200928 affinity_group_list = []
929
930 if target_vdu.get("affinity-or-anti-affinity-group-id"):
931 affinity_group = {}
aticig72c67142022-03-31 22:03:33 +0300932 for affinity_group_id in target_vdu[
933 "affinity-or-anti-affinity-group-id"
934 ]:
Alexis Romero73993212022-04-13 18:03:30 +0200935 affinity_group_text = (
aticig72c67142022-03-31 22:03:33 +0300936 ns_preffix
937 + ":affinity-or-anti-affinity-group."
938 + affinity_group_id
Alexis Romero73993212022-04-13 18:03:30 +0200939 )
940
941 extra_dict["depends_on"].append(affinity_group_text)
aticig72c67142022-03-31 22:03:33 +0300942 affinity_group["affinity_group_id"] = (
943 "TASK-" + affinity_group_text
944 )
Alexis Romero73993212022-04-13 18:03:30 +0200945 affinity_group_list.append(affinity_group)
946
tierno1d213f42020-04-24 14:02:51 +0000947 extra_dict["params"] = {
sousaedu80135b92021-02-17 15:05:18 +0100948 "name": "{}-{}-{}-{}".format(
949 indata["name"][:16],
950 vnfr["member-vnf-index-ref"][:16],
951 target_vdu["vdu-name"][:32],
952 target_vdu.get("count-index") or 0,
953 ),
tierno1d213f42020-04-24 14:02:51 +0000954 "description": target_vdu["vdu-name"],
955 "start": True,
956 "image_id": "TASK-" + image_text,
957 "flavor_id": "TASK-" + flavor_text,
Alexis Romero73993212022-04-13 18:03:30 +0200958 "affinity_group_list": affinity_group_list,
tierno1d213f42020-04-24 14:02:51 +0000959 "net_list": net_list,
960 "cloud_config": cloud_config or None,
sousaedu812bc6f2021-11-11 22:00:27 +0000961 "disk_list": disk_list,
tierno1d213f42020-04-24 14:02:51 +0000962 "availability_zone_index": None, # TODO
963 "availability_zone_list": None, # TODO
964 }
sousaedu80135b92021-02-17 15:05:18 +0100965
tierno1d213f42020-04-24 14:02:51 +0000966 return extra_dict
967
sousaedu80135b92021-02-17 15:05:18 +0100968 def _process_items(
969 target_list,
970 existing_list,
971 db_record,
972 db_update,
973 db_path,
974 item,
975 process_params,
976 ):
tierno1d213f42020-04-24 14:02:51 +0000977 nonlocal db_new_tasks
tierno70eeb182020-10-19 16:38:00 +0000978 nonlocal tasks_by_target_record_id
tierno1d213f42020-04-24 14:02:51 +0000979 nonlocal task_index
980
tierno70eeb182020-10-19 16:38:00 +0000981 # ensure all the target_list elements has an "id". If not assign the index as id
tierno1d213f42020-04-24 14:02:51 +0000982 for target_index, tl in enumerate(target_list):
983 if tl and not tl.get("id"):
984 tl["id"] = str(target_index)
985
tierno70eeb182020-10-19 16:38:00 +0000986 # step 1 items (networks,vdus,...) to be deleted/updated
987 for item_index, existing_item in enumerate(existing_list):
sousaedu80135b92021-02-17 15:05:18 +0100988 target_item = next(
989 (t for t in target_list if t["id"] == existing_item["id"]), None
990 )
991
992 for target_vim, existing_viminfo in existing_item.get(
993 "vim_info", {}
994 ).items():
tierno70eeb182020-10-19 16:38:00 +0000995 if existing_viminfo is None:
tierno1d213f42020-04-24 14:02:51 +0000996 continue
sousaedu80135b92021-02-17 15:05:18 +0100997
tierno70eeb182020-10-19 16:38:00 +0000998 if target_item:
sousaedu80135b92021-02-17 15:05:18 +0100999 target_viminfo = target_item.get("vim_info", {}).get(
1000 target_vim
1001 )
tierno1d213f42020-04-24 14:02:51 +00001002 else:
1003 target_viminfo = None
sousaedu80135b92021-02-17 15:05:18 +01001004
tierno70eeb182020-10-19 16:38:00 +00001005 if target_viminfo is None:
tierno1d213f42020-04-24 14:02:51 +00001006 # must be deleted
tierno86153522020-12-06 18:27:16 +00001007 self._assign_vim(target_vim)
sousaedu80135b92021-02-17 15:05:18 +01001008 target_record_id = "{}.{}".format(
1009 db_record, existing_item["id"]
1010 )
tierno70eeb182020-10-19 16:38:00 +00001011 item_ = item
sousaedu80135b92021-02-17 15:05:18 +01001012
tierno70eeb182020-10-19 16:38:00 +00001013 if target_vim.startswith("sdn"):
1014 # item must be sdn-net instead of net if target_vim is a sdn
1015 item_ = "sdn_net"
1016 target_record_id += ".sdn"
sousaedu80135b92021-02-17 15:05:18 +01001017
tierno70eeb182020-10-19 16:38:00 +00001018 task = _create_task(
sousaedu80135b92021-02-17 15:05:18 +01001019 target_vim,
1020 item_,
1021 "DELETE",
1022 target_record="{}.{}.vim_info.{}".format(
1023 db_record, item_index, target_vim
1024 ),
1025 target_record_id=target_record_id,
1026 )
tierno70eeb182020-10-19 16:38:00 +00001027 tasks_by_target_record_id[target_record_id] = task
1028 db_new_tasks.append(task)
tierno1d213f42020-04-24 14:02:51 +00001029 # TODO delete
1030 # TODO check one by one the vims to be created/deleted
1031
tierno70eeb182020-10-19 16:38:00 +00001032 # step 2 items (networks,vdus,...) to be created
1033 for target_item in target_list:
1034 item_index = -1
sousaedu80135b92021-02-17 15:05:18 +01001035
tierno70eeb182020-10-19 16:38:00 +00001036 for item_index, existing_item in enumerate(existing_list):
1037 if existing_item["id"] == target_item["id"]:
tierno1d213f42020-04-24 14:02:51 +00001038 break
1039 else:
tierno70eeb182020-10-19 16:38:00 +00001040 item_index += 1
1041 db_update[db_path + ".{}".format(item_index)] = target_item
1042 existing_list.append(target_item)
1043 existing_item = None
tierno1d213f42020-04-24 14:02:51 +00001044
sousaedu80135b92021-02-17 15:05:18 +01001045 for target_vim, target_viminfo in target_item.get(
1046 "vim_info", {}
1047 ).items():
tierno1d213f42020-04-24 14:02:51 +00001048 existing_viminfo = None
sousaedu80135b92021-02-17 15:05:18 +01001049
tierno70eeb182020-10-19 16:38:00 +00001050 if existing_item:
sousaedu80135b92021-02-17 15:05:18 +01001051 existing_viminfo = existing_item.get("vim_info", {}).get(
1052 target_vim
1053 )
1054
tierno1d213f42020-04-24 14:02:51 +00001055 # TODO check if different. Delete and create???
1056 # TODO delete if not exist
tierno70eeb182020-10-19 16:38:00 +00001057 if existing_viminfo is not None:
tierno1d213f42020-04-24 14:02:51 +00001058 continue
1059
tierno70eeb182020-10-19 16:38:00 +00001060 target_record_id = "{}.{}".format(db_record, target_item["id"])
1061 item_ = item
sousaedu80135b92021-02-17 15:05:18 +01001062
tierno70eeb182020-10-19 16:38:00 +00001063 if target_vim.startswith("sdn"):
1064 # item must be sdn-net instead of net if target_vim is a sdn
1065 item_ = "sdn_net"
1066 target_record_id += ".sdn"
tierno1d213f42020-04-24 14:02:51 +00001067
sousaedu80135b92021-02-17 15:05:18 +01001068 extra_dict = process_params(
1069 target_item, target_viminfo, target_record_id
1070 )
tierno86153522020-12-06 18:27:16 +00001071 self._assign_vim(target_vim)
tierno70eeb182020-10-19 16:38:00 +00001072 task = _create_task(
sousaedu80135b92021-02-17 15:05:18 +01001073 target_vim,
1074 item_,
1075 "CREATE",
1076 target_record="{}.{}.vim_info.{}".format(
1077 db_record, item_index, target_vim
1078 ),
tierno70eeb182020-10-19 16:38:00 +00001079 target_record_id=target_record_id,
sousaedu80135b92021-02-17 15:05:18 +01001080 extra_dict=extra_dict,
1081 )
tierno70eeb182020-10-19 16:38:00 +00001082 tasks_by_target_record_id[target_record_id] = task
1083 db_new_tasks.append(task)
sousaedu80135b92021-02-17 15:05:18 +01001084
tierno70eeb182020-10-19 16:38:00 +00001085 if target_item.get("common_id"):
1086 task["common_id"] = target_item["common_id"]
tierno1d213f42020-04-24 14:02:51 +00001087
tierno70eeb182020-10-19 16:38:00 +00001088 db_update[db_path + ".{}".format(item_index)] = target_item
tierno1d213f42020-04-24 14:02:51 +00001089
1090 def _process_action(indata):
tierno1d213f42020-04-24 14:02:51 +00001091 nonlocal db_new_tasks
1092 nonlocal task_index
1093 nonlocal db_vnfrs
1094 nonlocal db_ro_nsr
1095
tierno70eeb182020-10-19 16:38:00 +00001096 if indata["action"]["action"] == "inject_ssh_key":
1097 key = indata["action"].get("key")
1098 user = indata["action"].get("user")
1099 password = indata["action"].get("password")
sousaedu80135b92021-02-17 15:05:18 +01001100
tierno1d213f42020-04-24 14:02:51 +00001101 for vnf in indata.get("vnf", ()):
tierno70eeb182020-10-19 16:38:00 +00001102 if vnf["_id"] not in db_vnfrs:
tierno1d213f42020-04-24 14:02:51 +00001103 raise NsException("Invalid vnf={}".format(vnf["_id"]))
sousaedu80135b92021-02-17 15:05:18 +01001104
tierno1d213f42020-04-24 14:02:51 +00001105 db_vnfr = db_vnfrs[vnf["_id"]]
sousaedu80135b92021-02-17 15:05:18 +01001106
tierno1d213f42020-04-24 14:02:51 +00001107 for target_vdu in vnf.get("vdur", ()):
sousaedu80135b92021-02-17 15:05:18 +01001108 vdu_index, vdur = next(
1109 (
1110 i_v
1111 for i_v in enumerate(db_vnfr["vdur"])
1112 if i_v[1]["id"] == target_vdu["id"]
1113 ),
1114 (None, None),
1115 )
1116
tierno1d213f42020-04-24 14:02:51 +00001117 if not vdur:
sousaedu80135b92021-02-17 15:05:18 +01001118 raise NsException(
1119 "Invalid vdu vnf={}.{}".format(
1120 vnf["_id"], target_vdu["id"]
1121 )
1122 )
1123
1124 target_vim, vim_info = next(
1125 k_v for k_v in vdur["vim_info"].items()
1126 )
tierno86153522020-12-06 18:27:16 +00001127 self._assign_vim(target_vim)
sousaedu80135b92021-02-17 15:05:18 +01001128 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
1129 vnf["_id"], vdu_index
1130 )
tierno1d213f42020-04-24 14:02:51 +00001131 extra_dict = {
sousaedu80135b92021-02-17 15:05:18 +01001132 "depends_on": [
1133 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
1134 ],
tierno1d213f42020-04-24 14:02:51 +00001135 "params": {
tierno70eeb182020-10-19 16:38:00 +00001136 "ip_address": vdur.get("ip-address"),
tierno1d213f42020-04-24 14:02:51 +00001137 "user": user,
1138 "key": key,
1139 "password": password,
1140 "private_key": db_ro_nsr["private_key"],
1141 "salt": db_ro_nsr["_id"],
sousaedu80135b92021-02-17 15:05:18 +01001142 "schema_version": db_ro_nsr["_admin"][
1143 "schema_version"
1144 ],
1145 },
tierno1d213f42020-04-24 14:02:51 +00001146 }
sousaedu80135b92021-02-17 15:05:18 +01001147 task = _create_task(
1148 target_vim,
1149 "vdu",
1150 "EXEC",
1151 target_record=target_record,
1152 target_record_id=None,
1153 extra_dict=extra_dict,
1154 )
tierno70eeb182020-10-19 16:38:00 +00001155 db_new_tasks.append(task)
tierno1d213f42020-04-24 14:02:51 +00001156
1157 with self.write_lock:
1158 if indata.get("action"):
1159 _process_action(indata)
1160 else:
1161 # compute network differences
1162 # NS.vld
1163 step = "process NS VLDs"
sousaedu80135b92021-02-17 15:05:18 +01001164 _process_items(
1165 target_list=indata["ns"]["vld"] or [],
1166 existing_list=db_nsr.get("vld") or [],
1167 db_record="nsrs:{}:vld".format(nsr_id),
1168 db_update=db_nsr_update,
1169 db_path="vld",
1170 item="net",
1171 process_params=_process_net_params,
1172 )
tierno1d213f42020-04-24 14:02:51 +00001173
1174 step = "process NS images"
sousaedu80135b92021-02-17 15:05:18 +01001175 _process_items(
1176 target_list=indata.get("image") or [],
1177 existing_list=db_nsr.get("image") or [],
1178 db_record="nsrs:{}:image".format(nsr_id),
1179 db_update=db_nsr_update,
1180 db_path="image",
1181 item="image",
1182 process_params=_process_image_params,
1183 )
tierno1d213f42020-04-24 14:02:51 +00001184
1185 step = "process NS flavors"
sousaedu80135b92021-02-17 15:05:18 +01001186 _process_items(
1187 target_list=indata.get("flavor") or [],
1188 existing_list=db_nsr.get("flavor") or [],
1189 db_record="nsrs:{}:flavor".format(nsr_id),
1190 db_update=db_nsr_update,
1191 db_path="flavor",
1192 item="flavor",
1193 process_params=_process_flavor_params,
1194 )
tierno1d213f42020-04-24 14:02:51 +00001195
Alexis Romero73993212022-04-13 18:03:30 +02001196 step = "process NS Affinity Groups"
1197 _process_items(
1198 target_list=indata.get("affinity-or-anti-affinity-group") or [],
aticig72c67142022-03-31 22:03:33 +03001199 existing_list=db_nsr.get("affinity-or-anti-affinity-group")
1200 or [],
1201 db_record="nsrs:{}:affinity-or-anti-affinity-group".format(
1202 nsr_id
1203 ),
Alexis Romero73993212022-04-13 18:03:30 +02001204 db_update=db_nsr_update,
1205 db_path="affinity-or-anti-affinity-group",
1206 item="affinity-or-anti-affinity-group",
1207 process_params=_process_affinity_group_params,
1208 )
1209
tierno1d213f42020-04-24 14:02:51 +00001210 # VNF.vld
1211 for vnfr_id, vnfr in db_vnfrs.items():
1212 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1213 step = "process VNF={} VLDs".format(vnfr_id)
sousaedu80135b92021-02-17 15:05:18 +01001214 target_vnf = next(
1215 (
1216 vnf
1217 for vnf in indata.get("vnf", ())
1218 if vnf["_id"] == vnfr_id
1219 ),
1220 None,
1221 )
tierno1d213f42020-04-24 14:02:51 +00001222 target_list = target_vnf.get("vld") if target_vnf else None
sousaedu80135b92021-02-17 15:05:18 +01001223 _process_items(
1224 target_list=target_list or [],
1225 existing_list=vnfr.get("vld") or [],
1226 db_record="vnfrs:{}:vld".format(vnfr_id),
1227 db_update=db_vnfrs_update[vnfr["_id"]],
1228 db_path="vld",
1229 item="net",
1230 process_params=_process_net_params,
1231 )
tierno1d213f42020-04-24 14:02:51 +00001232
1233 target_list = target_vnf.get("vdur") if target_vnf else None
1234 step = "process VNF={} VDUs".format(vnfr_id)
sousaedu80135b92021-02-17 15:05:18 +01001235 _process_items(
1236 target_list=target_list or [],
1237 existing_list=vnfr.get("vdur") or [],
1238 db_record="vnfrs:{}:vdur".format(vnfr_id),
1239 db_update=db_vnfrs_update[vnfr["_id"]],
1240 db_path="vdur",
1241 item="vdu",
1242 process_params=_process_vdu_params,
1243 )
tierno1d213f42020-04-24 14:02:51 +00001244
tierno70eeb182020-10-19 16:38:00 +00001245 for db_task in db_new_tasks:
1246 step = "Updating database, Appending tasks to ro_tasks"
1247 target_id = db_task.pop("target_id")
1248 common_id = db_task.get("common_id")
sousaedu80135b92021-02-17 15:05:18 +01001249
tierno70eeb182020-10-19 16:38:00 +00001250 if common_id:
sousaedu80135b92021-02-17 15:05:18 +01001251 if self.db.set_one(
1252 "ro_tasks",
1253 q_filter={
1254 "target_id": target_id,
1255 "tasks.common_id": common_id,
1256 },
1257 update_dict={"to_check_at": now, "modified_at": now},
1258 push={"tasks": db_task},
1259 fail_on_empty=False,
1260 ):
tierno70eeb182020-10-19 16:38:00 +00001261 continue
sousaedu80135b92021-02-17 15:05:18 +01001262
1263 if not self.db.set_one(
1264 "ro_tasks",
1265 q_filter={
1266 "target_id": target_id,
1267 "tasks.target_record": db_task["target_record"],
1268 },
1269 update_dict={"to_check_at": now, "modified_at": now},
1270 push={"tasks": db_task},
1271 fail_on_empty=False,
1272 ):
tierno70eeb182020-10-19 16:38:00 +00001273 # Create a ro_task
1274 step = "Updating database, Creating ro_tasks"
1275 db_ro_task = _create_ro_task(target_id, db_task)
1276 nb_ro_tasks += 1
1277 self.db.create("ro_tasks", db_ro_task)
sousaedu80135b92021-02-17 15:05:18 +01001278
tierno1d213f42020-04-24 14:02:51 +00001279 step = "Updating database, nsrs"
1280 if db_nsr_update:
1281 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
sousaedu80135b92021-02-17 15:05:18 +01001282
tierno1d213f42020-04-24 14:02:51 +00001283 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
1284 if db_vnfr_update:
1285 step = "Updating database, vnfrs={}".format(vnfr_id)
1286 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
1287
sousaedu80135b92021-02-17 15:05:18 +01001288 self.logger.debug(
1289 logging_text
1290 + "Exit. Created {} ro_tasks; {} tasks".format(
1291 nb_ro_tasks, len(db_new_tasks)
1292 )
1293 )
tierno1d213f42020-04-24 14:02:51 +00001294
sousaedu80135b92021-02-17 15:05:18 +01001295 return (
1296 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
1297 action_id,
1298 True,
1299 )
tierno1d213f42020-04-24 14:02:51 +00001300 except Exception as e:
1301 if isinstance(e, (DbException, NsException)):
sousaedu80135b92021-02-17 15:05:18 +01001302 self.logger.error(
1303 logging_text + "Exit Exception while '{}': {}".format(step, e)
1304 )
tierno1d213f42020-04-24 14:02:51 +00001305 else:
1306 e = traceback_format_exc()
sousaedu80135b92021-02-17 15:05:18 +01001307 self.logger.critical(
1308 logging_text + "Exit Exception while '{}': {}".format(step, e),
1309 exc_info=True,
1310 )
1311
tierno1d213f42020-04-24 14:02:51 +00001312 raise NsException(e)
1313
1314 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
tierno70eeb182020-10-19 16:38:00 +00001315 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
tierno1d213f42020-04-24 14:02:51 +00001316 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
sousaedu80135b92021-02-17 15:05:18 +01001317
tierno70eeb182020-10-19 16:38:00 +00001318 with self.write_lock:
1319 try:
1320 NsWorker.delete_db_tasks(self.db, nsr_id, None)
1321 except NsWorkerException as e:
1322 raise NsException(e)
sousaedu80135b92021-02-17 15:05:18 +01001323
tierno1d213f42020-04-24 14:02:51 +00001324 return None, None, True
1325
1326 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
tierno70eeb182020-10-19 16:38:00 +00001327 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
1328 # .format(version, nsr_id, action_id, indata))
tierno1d213f42020-04-24 14:02:51 +00001329 task_list = []
1330 done = 0
1331 total = 0
1332 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
1333 global_status = "DONE"
1334 details = []
sousaedu80135b92021-02-17 15:05:18 +01001335
tierno1d213f42020-04-24 14:02:51 +00001336 for ro_task in ro_tasks:
1337 for task in ro_task["tasks"]:
tierno70eeb182020-10-19 16:38:00 +00001338 if task and task["action_id"] == action_id:
tierno1d213f42020-04-24 14:02:51 +00001339 task_list.append(task)
1340 total += 1
sousaedu80135b92021-02-17 15:05:18 +01001341
tierno1d213f42020-04-24 14:02:51 +00001342 if task["status"] == "FAILED":
1343 global_status = "FAILED"
sousaedu80135b92021-02-17 15:05:18 +01001344 error_text = "Error at {} {}: {}".format(
1345 task["action"].lower(),
1346 task["item"],
1347 ro_task["vim_info"].get("vim_details") or "unknown",
1348 )
tierno70eeb182020-10-19 16:38:00 +00001349 details.append(error_text)
tierno1d213f42020-04-24 14:02:51 +00001350 elif task["status"] in ("SCHEDULED", "BUILD"):
1351 if global_status != "FAILED":
1352 global_status = "BUILD"
1353 else:
1354 done += 1
sousaedu80135b92021-02-17 15:05:18 +01001355
tierno1d213f42020-04-24 14:02:51 +00001356 return_data = {
1357 "status": global_status,
sousaedu80135b92021-02-17 15:05:18 +01001358 "details": ". ".join(details)
1359 if details
1360 else "progress {}/{}".format(done, total),
tierno1d213f42020-04-24 14:02:51 +00001361 "nsr_id": nsr_id,
1362 "action_id": action_id,
sousaedu80135b92021-02-17 15:05:18 +01001363 "tasks": task_list,
tierno1d213f42020-04-24 14:02:51 +00001364 }
sousaedu80135b92021-02-17 15:05:18 +01001365
tierno1d213f42020-04-24 14:02:51 +00001366 return return_data, None, True
1367
1368 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
sousaedu80135b92021-02-17 15:05:18 +01001369 print(
1370 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
1371 session, indata, version, nsr_id, action_id
1372 )
1373 )
1374
tierno1d213f42020-04-24 14:02:51 +00001375 return None, None, True
1376
1377 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1378 nsrs = self.db.get_list("nsrs", {})
1379 return_data = []
sousaedu80135b92021-02-17 15:05:18 +01001380
tierno1d213f42020-04-24 14:02:51 +00001381 for ns in nsrs:
1382 return_data.append({"_id": ns["_id"], "name": ns["name"]})
sousaedu80135b92021-02-17 15:05:18 +01001383
tierno1d213f42020-04-24 14:02:51 +00001384 return return_data, None, True
1385
1386 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1387 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
1388 return_data = []
sousaedu80135b92021-02-17 15:05:18 +01001389
tierno1d213f42020-04-24 14:02:51 +00001390 for ro_task in ro_tasks:
1391 for task in ro_task["tasks"]:
1392 if task["action_id"] not in return_data:
1393 return_data.append(task["action_id"])
sousaedu80135b92021-02-17 15:05:18 +01001394
tierno1d213f42020-04-24 14:02:51 +00001395 return return_data, None, True