blob: e62eef59207fa72ef9b26f47768e12313447c432 [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
tierno1d213f42020-04-24 14:02:51 +000019# import yaml
sousaedu2ad85172021-02-17 15:05:18 +010020import logging
tierno1d213f42020-04-24 14:02:51 +000021from traceback import format_exc as traceback_format_exc
tierno70eeb182020-10-19 16:38:00 +000022from osm_ng_ro.ns_thread import NsWorker, NsWorkerException, deep_get
tierno1d213f42020-04-24 14:02:51 +000023from osm_ng_ro.validation import validate_input, deploy_schema
sousaedu2ad85172021-02-17 15:05:18 +010024from osm_common import (
25 dbmongo,
26 dbmemory,
27 fslocal,
28 fsmongo,
29 msglocal,
30 msgkafka,
31 version as common_version,
32)
tierno1d213f42020-04-24 14:02:51 +000033from osm_common.dbbase import DbException
34from osm_common.fsbase import FsException
35from osm_common.msgbase import MsgException
36from http import HTTPStatus
37from uuid import uuid4
38from threading import Lock
39from random import choice as random_choice
40from time import time
sousaedu2ad85172021-02-17 15:05:18 +010041from jinja2 import (
42 Environment,
43 TemplateError,
44 TemplateNotFound,
45 StrictUndefined,
46 UndefinedError,
47)
tierno1d213f42020-04-24 14:02:51 +000048from cryptography.hazmat.primitives import serialization as crypto_serialization
49from cryptography.hazmat.primitives.asymmetric import rsa
50from cryptography.hazmat.backends import default_backend as crypto_default_backend
51
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]
sousaedu2ad85172021-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
sousaedu2ad85172021-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 = []
sousaedu2ad85172021-02-17 15:05:18 +010087
tierno1d213f42020-04-24 14:02:51 +000088 for point in v.split("."):
89 filled.append(point.zfill(8))
sousaedu2ad85172021-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
tiernobc891ce2020-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")
sousaedu2ad85172021-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):
sousaedu2ad85172021-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:
sousaedu2ad85172021-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:
sousaedu2ad85172021-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:
sousaedu2ad85172021-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)
sousaedu2ad85172021-02-17 15:05:18 +0100183
tiernobc891ce2020-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()
sousaedu2ad85172021-02-17 15:05:18 +0100191
tierno1d213f42020-04-24 14:02:51 +0000192 if self.fs:
193 self.fs.fs_disconnect()
sousaedu2ad85172021-02-17 15:05:18 +0100194
tierno1d213f42020-04-24 14:02:51 +0000195 if self.msg:
196 self.msg.disconnect()
sousaedu2ad85172021-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)
sousaedu2ad85172021-02-17 15:05:18 +0100201
tierno1d213f42020-04-24 14:02:51 +0000202 for worker in self.workers:
203 worker.insert_task(("terminate",))
204
tiernobc891ce2020-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
sousaedu2ad85172021-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
tiernobc891ce2020-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)
sousaedu2ad85172021-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
sousaedu2ad85172021-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
sousaedu2ad85172021-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):
tiernobc891ce2020-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
tiernobc891ce2020-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):
tiernobc891ce2020-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))
tiernobc891ce2020-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):
tiernobc891ce2020-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
tiernobc891ce2020-12-06 18:27:16 +0000279 def unload_unused_vims(self):
280 with self.write_lock:
281 vims_to_unload = []
sousaedu2ad85172021-02-17 15:05:18 +0100282
tiernobc891ce2020-12-06 18:27:16 +0000283 for target_id in self.vims_assigned:
sousaedu2ad85172021-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 ):
tiernobc891ce2020-12-06 18:27:16 +0000292 vims_to_unload.append(target_id)
sousaedu2ad85172021-02-17 15:05:18 +0100293
tiernobc891ce2020-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 """
tiernobc891ce2020-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})
sousaedu2ad85172021-02-17 15:05:18 +0100306
tierno1d213f42020-04-24 14:02:51 +0000307 if _type == "file":
308 base_folder = vnfd["_admin"]["storage"]
sousaedu2ad85172021-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:
sousaedu2ad85172021-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))
sousaedu2ad85172021-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)
sousaedu2ad85172021-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"
sousaedu2ad85172021-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:
sousaedu2ad85172021-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(
sousaedu2ad85172021-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,
sousaedu2ad85172021-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,
sousaedu2ad85172021-02-17 15:05:18 +0100359 crypto_serialization.PublicFormat.OpenSSH,
tierno1d213f42020-04-24 14:02:51 +0000360 )
sousaedu2ad85172021-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:]
sousaedu2ad85172021-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"
sousaedu2ad85172021-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,
sousaedu2ad85172021-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,
sousaedu2ad85172021-02-17 15:05:18 +0100382 "actions": [],
tierno1d213f42020-04-24 14:02:51 +0000383 }
384 self.db.create("ro_nsrs", db_content)
sousaedu2ad85172021-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
sousaedu2ad85172021-02-17 15:05:18 +0100394 db_nsr_update = {} # update operation on nsrs
tierno1d213f42020-04-24 14:02:51 +0000395 db_vnfrs_update = {}
sousaedu2ad85172021-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 {}
sousaedu2ad85172021-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")
sousaedu2ad85172021-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})
sousaedu2ad85172021-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")
sousaedu2ad85172021-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"]] = {}
sousaedu2ad85172021-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)
sousaedu2ad85172021-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)
sousaedu2ad85172021-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
sousaedu2ad85172021-02-17 15:05:18 +0100430
tierno1d213f42020-04-24 14:02:51 +0000431 while True:
432 new_action_id = "{}:{}".format(action_id, index)
sousaedu2ad85172021-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
sousaedu2ad85172021-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
sousaedu2ad85172021-02-17 15:05:18 +0100441
tierno1d213f42020-04-24 14:02:51 +0000442 index += 1
443
sousaedu2ad85172021-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 }
sousaedu2ad85172021-02-17 15:05:18 +0100467
tierno1d213f42020-04-24 14:02:51 +0000468 if extra_dict:
sousaedu2ad85172021-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
sousaedu2ad85172021-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 }
sousaedu2ad85172021-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 = {}
sousaedu2ad85172021-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")}
sousaedu2ad85172021-02-17 15:05:18 +0100508
tierno1d213f42020-04-24 14:02:51 +0000509 if target_image.get("vim_image_id"):
sousaedu2ad85172021-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"):
sousaedu2ad85172021-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 = {}
sousaedu2ad85172021-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"])
sousaedu2ad85172021-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"])
sousaedu2ad85172021-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"])
sousaedu2ad85172021-02-17 15:05:18 +0100539
tierno1d213f42020-04-24 14:02:51 +0000540 return quota
541
542 flavor_data = {
543 "disk": int(target_flavor["storage-gb"]),
tierno1d213f42020-04-24 14:02:51 +0000544 "ram": int(target_flavor["memory-mb"]),
tiernofb13d2e2020-11-26 15:55:20 +0000545 "vcpus": int(target_flavor["vcpu-count"]),
tierno1d213f42020-04-24 14:02:51 +0000546 }
tierno70eeb182020-10-19 16:38:00 +0000547 numa = {}
548 extended = {}
sousaedu2ad85172021-02-17 15:05:18 +0100549
tierno1d213f42020-04-24 14:02:51 +0000550 if target_flavor.get("guest-epa"):
551 extended = {}
tierno1d213f42020-04-24 14:02:51 +0000552 epa_vcpu_set = False
sousaedu2ad85172021-02-17 15:05:18 +0100553
tierno1d213f42020-04-24 14:02:51 +0000554 if target_flavor["guest-epa"].get("numa-node-policy"):
sousaedu2ad85172021-02-17 15:05:18 +0100555 numa_node_policy = target_flavor["guest-epa"].get(
556 "numa-node-policy"
557 )
558
tierno1d213f42020-04-24 14:02:51 +0000559 if numa_node_policy.get("node"):
560 numa_node = numa_node_policy["node"][0]
sousaedu2ad85172021-02-17 15:05:18 +0100561
tierno1d213f42020-04-24 14:02:51 +0000562 if numa_node.get("num-cores"):
563 numa["cores"] = numa_node["num-cores"]
564 epa_vcpu_set = True
sousaedu2ad85172021-02-17 15:05:18 +0100565
tierno1d213f42020-04-24 14:02:51 +0000566 if numa_node.get("paired-threads"):
sousaedu2ad85172021-02-17 15:05:18 +0100567 if numa_node["paired-threads"].get(
568 "num-paired-threads"
569 ):
570 numa["paired-threads"] = int(
571 numa_node["paired-threads"][
572 "num-paired-threads"
573 ]
574 )
tierno1d213f42020-04-24 14:02:51 +0000575 epa_vcpu_set = True
sousaedu2ad85172021-02-17 15:05:18 +0100576
577 if len(
578 numa_node["paired-threads"].get("paired-thread-ids")
579 ):
tierno1d213f42020-04-24 14:02:51 +0000580 numa["paired-threads-id"] = []
sousaedu2ad85172021-02-17 15:05:18 +0100581
582 for pair in numa_node["paired-threads"][
583 "paired-thread-ids"
584 ]:
tierno1d213f42020-04-24 14:02:51 +0000585 numa["paired-threads-id"].append(
sousaedu2ad85172021-02-17 15:05:18 +0100586 (
587 str(pair["thread-a"]),
588 str(pair["thread-b"]),
589 )
tierno1d213f42020-04-24 14:02:51 +0000590 )
sousaedu2ad85172021-02-17 15:05:18 +0100591
tierno1d213f42020-04-24 14:02:51 +0000592 if numa_node.get("num-threads"):
593 numa["threads"] = int(numa_node["num-threads"])
594 epa_vcpu_set = True
sousaedu2ad85172021-02-17 15:05:18 +0100595
tierno1d213f42020-04-24 14:02:51 +0000596 if numa_node.get("memory-mb"):
sousaedu2ad85172021-02-17 15:05:18 +0100597 numa["memory"] = max(
598 int(numa_node["memory-mb"] / 1024), 1
599 )
600
tierno1d213f42020-04-24 14:02:51 +0000601 if target_flavor["guest-epa"].get("mempage-size"):
sousaedu2ad85172021-02-17 15:05:18 +0100602 extended["mempage-size"] = target_flavor["guest-epa"].get(
603 "mempage-size"
604 )
605
606 if (
607 target_flavor["guest-epa"].get("cpu-pinning-policy")
608 and not epa_vcpu_set
609 ):
610 if (
611 target_flavor["guest-epa"]["cpu-pinning-policy"]
612 == "DEDICATED"
613 ):
614 if (
615 target_flavor["guest-epa"].get(
616 "cpu-thread-pinning-policy"
617 )
618 and target_flavor["guest-epa"][
619 "cpu-thread-pinning-policy"
620 ]
621 != "PREFER"
622 ):
tierno1d213f42020-04-24 14:02:51 +0000623 numa["cores"] = max(flavor_data["vcpus"], 1)
624 else:
625 numa["threads"] = max(flavor_data["vcpus"], 1)
sousaedu2ad85172021-02-17 15:05:18 +0100626
tierno1d213f42020-04-24 14:02:51 +0000627 epa_vcpu_set = True
sousaedu2ad85172021-02-17 15:05:18 +0100628
tierno1d213f42020-04-24 14:02:51 +0000629 if target_flavor["guest-epa"].get("cpu-quota") and not epa_vcpu_set:
sousaedu2ad85172021-02-17 15:05:18 +0100630 cpuquota = _get_resource_allocation_params(
631 target_flavor["guest-epa"].get("cpu-quota")
632 )
633
tierno1d213f42020-04-24 14:02:51 +0000634 if cpuquota:
635 extended["cpu-quota"] = cpuquota
sousaedu2ad85172021-02-17 15:05:18 +0100636
tierno1d213f42020-04-24 14:02:51 +0000637 if target_flavor["guest-epa"].get("mem-quota"):
sousaedu2ad85172021-02-17 15:05:18 +0100638 vduquota = _get_resource_allocation_params(
639 target_flavor["guest-epa"].get("mem-quota")
640 )
641
tierno1d213f42020-04-24 14:02:51 +0000642 if vduquota:
643 extended["mem-quota"] = vduquota
sousaedu2ad85172021-02-17 15:05:18 +0100644
tierno1d213f42020-04-24 14:02:51 +0000645 if target_flavor["guest-epa"].get("disk-io-quota"):
sousaedu2ad85172021-02-17 15:05:18 +0100646 diskioquota = _get_resource_allocation_params(
647 target_flavor["guest-epa"].get("disk-io-quota")
648 )
649
tierno1d213f42020-04-24 14:02:51 +0000650 if diskioquota:
651 extended["disk-io-quota"] = diskioquota
sousaedu2ad85172021-02-17 15:05:18 +0100652
tierno1d213f42020-04-24 14:02:51 +0000653 if target_flavor["guest-epa"].get("vif-quota"):
sousaedu2ad85172021-02-17 15:05:18 +0100654 vifquota = _get_resource_allocation_params(
655 target_flavor["guest-epa"].get("vif-quota")
656 )
657
tierno1d213f42020-04-24 14:02:51 +0000658 if vifquota:
659 extended["vif-quota"] = vifquota
sousaedu2ad85172021-02-17 15:05:18 +0100660
tierno1d213f42020-04-24 14:02:51 +0000661 if numa:
662 extended["numas"] = [numa]
sousaedu2ad85172021-02-17 15:05:18 +0100663
tierno1d213f42020-04-24 14:02:51 +0000664 if extended:
665 flavor_data["extended"] = extended
666
667 extra_dict = {"find_params": {"flavor_data": flavor_data}}
668 flavor_data_name = flavor_data.copy()
669 flavor_data_name["name"] = target_flavor["name"]
670 extra_dict["params"] = {"flavor_data": flavor_data_name}
sousaedu2ad85172021-02-17 15:05:18 +0100671
tierno1d213f42020-04-24 14:02:51 +0000672 return extra_dict
673
tierno70eeb182020-10-19 16:38:00 +0000674 def _ip_profile_2_ro(ip_profile):
675 if not ip_profile:
676 return None
sousaedu2ad85172021-02-17 15:05:18 +0100677
tierno70eeb182020-10-19 16:38:00 +0000678 ro_ip_profile = {
sousaedu2ad85172021-02-17 15:05:18 +0100679 "ip_version": "IPv4"
680 if "v4" in ip_profile.get("ip-version", "ipv4")
681 else "IPv6",
tierno70eeb182020-10-19 16:38:00 +0000682 "subnet_address": ip_profile.get("subnet-address"),
683 "gateway_address": ip_profile.get("gateway-address"),
sousaedu39deab72021-03-02 01:42:51 +0100684 "dhcp_enabled": ip_profile.get("dhcp-params", {}).get(
685 "enabled", False
686 ),
687 "dhcp_start_address": ip_profile.get("dhcp-params", {}).get(
688 "start-address", None
689 ),
690 "dhcp_count": ip_profile.get("dhcp-params", {}).get(
691 "count", None
692 ),
tierno70eeb182020-10-19 16:38:00 +0000693 }
sousaedu2ad85172021-02-17 15:05:18 +0100694
tierno70eeb182020-10-19 16:38:00 +0000695 if ip_profile.get("dns-server"):
sousaedu2ad85172021-02-17 15:05:18 +0100696 ro_ip_profile["dns_address"] = ";".join(
697 [v["address"] for v in ip_profile["dns-server"]]
698 )
699
700 if ip_profile.get("security-group"):
701 ro_ip_profile["security_group"] = ip_profile["security-group"]
702
tierno70eeb182020-10-19 16:38:00 +0000703 return ro_ip_profile
704
705 def _process_net_params(target_vld, vim_info, target_record_id):
tierno1d213f42020-04-24 14:02:51 +0000706 nonlocal indata
707 extra_dict = {}
tierno70eeb182020-10-19 16:38:00 +0000708
709 if vim_info.get("sdn"):
710 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
711 # ns_preffix = "nsrs:{}".format(nsr_id)
sousaedu2ad85172021-02-17 15:05:18 +0100712 # remove the ending ".sdn
713 vld_target_record_id, _, _ = target_record_id.rpartition(".")
714 extra_dict["params"] = {
715 k: vim_info[k]
716 for k in ("sdn-ports", "target_vim", "vlds", "type")
717 if vim_info.get(k)
718 }
719
tierno70eeb182020-10-19 16:38:00 +0000720 # TODO needed to add target_id in the dependency.
721 if vim_info.get("target_vim"):
sousaedu2ad85172021-02-17 15:05:18 +0100722 extra_dict["depends_on"] = [
723 vim_info.get("target_vim") + " " + vld_target_record_id
724 ]
725
tierno70eeb182020-10-19 16:38:00 +0000726 return extra_dict
727
tierno1d213f42020-04-24 14:02:51 +0000728 if vim_info.get("vim_network_name"):
sousaedu2ad85172021-02-17 15:05:18 +0100729 extra_dict["find_params"] = {
730 "filter_dict": {"name": vim_info.get("vim_network_name")}
731 }
tierno1d213f42020-04-24 14:02:51 +0000732 elif vim_info.get("vim_network_id"):
sousaedu2ad85172021-02-17 15:05:18 +0100733 extra_dict["find_params"] = {
734 "filter_dict": {"id": vim_info.get("vim_network_id")}
735 }
tierno1d213f42020-04-24 14:02:51 +0000736 elif target_vld.get("mgmt-network"):
737 extra_dict["find_params"] = {"mgmt": True, "name": target_vld["id"]}
738 else:
739 # create
740 extra_dict["params"] = {
sousaedu2ad85172021-02-17 15:05:18 +0100741 "net_name": "{}-{}".format(
742 indata["name"][:16],
743 target_vld.get("name", target_vld["id"])[:16],
744 ),
745 "ip_profile": _ip_profile_2_ro(vim_info.get("ip_profile")),
746 "provider_network_profile": vim_info.get("provider_network"),
tierno1d213f42020-04-24 14:02:51 +0000747 }
sousaedu2ad85172021-02-17 15:05:18 +0100748
tierno1d213f42020-04-24 14:02:51 +0000749 if not target_vld.get("underlay"):
750 extra_dict["params"]["net_type"] = "bridge"
751 else:
sousaedu2ad85172021-02-17 15:05:18 +0100752 extra_dict["params"]["net_type"] = (
753 "ptp" if target_vld.get("type") == "ELINE" else "data"
754 )
755
tierno1d213f42020-04-24 14:02:51 +0000756 return extra_dict
757
tierno70eeb182020-10-19 16:38:00 +0000758 def _process_vdu_params(target_vdu, vim_info, target_record_id):
tierno1d213f42020-04-24 14:02:51 +0000759 nonlocal vnfr_id
760 nonlocal nsr_id
761 nonlocal indata
762 nonlocal vnfr
763 nonlocal vdu2cloud_init
tierno70eeb182020-10-19 16:38:00 +0000764 nonlocal tasks_by_target_record_id
sousaedu2ad85172021-02-17 15:05:18 +0100765
tierno1d213f42020-04-24 14:02:51 +0000766 vnf_preffix = "vnfrs:{}".format(vnfr_id)
767 ns_preffix = "nsrs:{}".format(nsr_id)
768 image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
769 flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
770 extra_dict = {"depends_on": [image_text, flavor_text]}
771 net_list = []
sousaedu2ad85172021-02-17 15:05:18 +0100772
tierno1d213f42020-04-24 14:02:51 +0000773 for iface_index, interface in enumerate(target_vdu["interfaces"]):
774 if interface.get("ns-vld-id"):
775 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
tierno55fa0bb2020-12-08 23:11:53 +0000776 elif interface.get("vnf-vld-id"):
tierno1d213f42020-04-24 14:02:51 +0000777 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
tierno55fa0bb2020-12-08 23:11:53 +0000778 else:
sousaedu2ad85172021-02-17 15:05:18 +0100779 self.logger.error(
780 "Interface {} from vdu {} not connected to any vld".format(
781 iface_index, target_vdu["vdu-name"]
782 )
783 )
784
785 continue # interface not connected to any vld
786
tierno1d213f42020-04-24 14:02:51 +0000787 extra_dict["depends_on"].append(net_text)
sousaedu42f80772021-03-02 00:15:52 +0100788
789 if "port-security-enabled" in interface:
790 interface["port_security"] = (
791 interface.pop("port-security-enabled")
792 )
793
794 if "port-security-disable-strategy" in interface:
795 interface["port_security_disable_strategy"] = (
796 interface.pop("port-security-disable-strategy")
797 )
798
sousaedu2ad85172021-02-17 15:05:18 +0100799 net_item = {
800 x: v
801 for x, v in interface.items()
802 if x
803 in (
804 "name",
805 "vpci",
806 "port_security",
807 "port_security_disable_strategy",
808 "floating_ip",
809 )
810 }
tierno70eeb182020-10-19 16:38:00 +0000811 net_item["net_id"] = "TASK-" + net_text
812 net_item["type"] = "virtual"
sousaedu2ad85172021-02-17 15:05:18 +0100813
tierno70eeb182020-10-19 16:38:00 +0000814 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
815 # TODO floating_ip: True/False (or it can be None)
tierno1d213f42020-04-24 14:02:51 +0000816 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
tierno70eeb182020-10-19 16:38:00 +0000817 # mark the net create task as type data
sousaedu2ad85172021-02-17 15:05:18 +0100818 if deep_get(
819 tasks_by_target_record_id, net_text, "params", "net_type"
820 ):
821 tasks_by_target_record_id[net_text]["params"][
822 "net_type"
823 ] = "data"
824
tierno1d213f42020-04-24 14:02:51 +0000825 net_item["use"] = "data"
826 net_item["model"] = interface["type"]
827 net_item["type"] = interface["type"]
sousaedu2ad85172021-02-17 15:05:18 +0100828 elif (
829 interface.get("type") == "OM-MGMT"
830 or interface.get("mgmt-interface")
831 or interface.get("mgmt-vnf")
832 ):
tierno1d213f42020-04-24 14:02:51 +0000833 net_item["use"] = "mgmt"
sousaedu2ad85172021-02-17 15:05:18 +0100834 else:
835 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
tierno1d213f42020-04-24 14:02:51 +0000836 net_item["use"] = "bridge"
837 net_item["model"] = interface.get("type")
sousaedu2ad85172021-02-17 15:05:18 +0100838
tierno70eeb182020-10-19 16:38:00 +0000839 if interface.get("ip-address"):
840 net_item["ip_address"] = interface["ip-address"]
sousaedu2ad85172021-02-17 15:05:18 +0100841
tierno70eeb182020-10-19 16:38:00 +0000842 if interface.get("mac-address"):
843 net_item["mac_address"] = interface["mac-address"]
sousaedu2ad85172021-02-17 15:05:18 +0100844
tierno1d213f42020-04-24 14:02:51 +0000845 net_list.append(net_item)
sousaedu2ad85172021-02-17 15:05:18 +0100846
tierno1d213f42020-04-24 14:02:51 +0000847 if interface.get("mgmt-vnf"):
848 extra_dict["mgmt_vnf_interface"] = iface_index
849 elif interface.get("mgmt-interface"):
850 extra_dict["mgmt_vdu_interface"] = iface_index
sousaedu2ad85172021-02-17 15:05:18 +0100851
tierno1d213f42020-04-24 14:02:51 +0000852 # cloud config
853 cloud_config = {}
sousaedu2ad85172021-02-17 15:05:18 +0100854
tierno1d213f42020-04-24 14:02:51 +0000855 if target_vdu.get("cloud-init"):
856 if target_vdu["cloud-init"] not in vdu2cloud_init:
sousaedu2ad85172021-02-17 15:05:18 +0100857 vdu2cloud_init[target_vdu["cloud-init"]] = self._get_cloud_init(
858 target_vdu["cloud-init"]
859 )
860
tierno1d213f42020-04-24 14:02:51 +0000861 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
sousaedu2ad85172021-02-17 15:05:18 +0100862 cloud_config["user-data"] = self._parse_jinja2(
863 cloud_content_,
864 target_vdu.get("additionalParams"),
865 target_vdu["cloud-init"],
866 )
867
tierno1d213f42020-04-24 14:02:51 +0000868 if target_vdu.get("boot-data-drive"):
869 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
sousaedu2ad85172021-02-17 15:05:18 +0100870
tierno1d213f42020-04-24 14:02:51 +0000871 ssh_keys = []
sousaedu2ad85172021-02-17 15:05:18 +0100872
tierno1d213f42020-04-24 14:02:51 +0000873 if target_vdu.get("ssh-keys"):
874 ssh_keys += target_vdu.get("ssh-keys")
sousaedu2ad85172021-02-17 15:05:18 +0100875
tierno1d213f42020-04-24 14:02:51 +0000876 if target_vdu.get("ssh-access-required"):
877 ssh_keys.append(ro_nsr_public_key)
sousaedu2ad85172021-02-17 15:05:18 +0100878
tierno1d213f42020-04-24 14:02:51 +0000879 if ssh_keys:
880 cloud_config["key-pairs"] = ssh_keys
881
882 extra_dict["params"] = {
sousaedu2ad85172021-02-17 15:05:18 +0100883 "name": "{}-{}-{}-{}".format(
884 indata["name"][:16],
885 vnfr["member-vnf-index-ref"][:16],
886 target_vdu["vdu-name"][:32],
887 target_vdu.get("count-index") or 0,
888 ),
tierno1d213f42020-04-24 14:02:51 +0000889 "description": target_vdu["vdu-name"],
890 "start": True,
891 "image_id": "TASK-" + image_text,
892 "flavor_id": "TASK-" + flavor_text,
893 "net_list": net_list,
894 "cloud_config": cloud_config or None,
895 "disk_list": None, # TODO
896 "availability_zone_index": None, # TODO
897 "availability_zone_list": None, # TODO
898 }
sousaedu2ad85172021-02-17 15:05:18 +0100899
tierno1d213f42020-04-24 14:02:51 +0000900 return extra_dict
901
sousaedu2ad85172021-02-17 15:05:18 +0100902 def _process_items(
903 target_list,
904 existing_list,
905 db_record,
906 db_update,
907 db_path,
908 item,
909 process_params,
910 ):
tierno1d213f42020-04-24 14:02:51 +0000911 nonlocal db_new_tasks
tierno70eeb182020-10-19 16:38:00 +0000912 nonlocal tasks_by_target_record_id
tierno1d213f42020-04-24 14:02:51 +0000913 nonlocal task_index
914
tierno70eeb182020-10-19 16:38:00 +0000915 # ensure all the target_list elements has an "id". If not assign the index as id
tierno1d213f42020-04-24 14:02:51 +0000916 for target_index, tl in enumerate(target_list):
917 if tl and not tl.get("id"):
918 tl["id"] = str(target_index)
919
tierno70eeb182020-10-19 16:38:00 +0000920 # step 1 items (networks,vdus,...) to be deleted/updated
921 for item_index, existing_item in enumerate(existing_list):
sousaedu2ad85172021-02-17 15:05:18 +0100922 target_item = next(
923 (t for t in target_list if t["id"] == existing_item["id"]), None
924 )
925
926 for target_vim, existing_viminfo in existing_item.get(
927 "vim_info", {}
928 ).items():
tierno70eeb182020-10-19 16:38:00 +0000929 if existing_viminfo is None:
tierno1d213f42020-04-24 14:02:51 +0000930 continue
sousaedu2ad85172021-02-17 15:05:18 +0100931
tierno70eeb182020-10-19 16:38:00 +0000932 if target_item:
sousaedu2ad85172021-02-17 15:05:18 +0100933 target_viminfo = target_item.get("vim_info", {}).get(
934 target_vim
935 )
tierno1d213f42020-04-24 14:02:51 +0000936 else:
937 target_viminfo = None
sousaedu2ad85172021-02-17 15:05:18 +0100938
tierno70eeb182020-10-19 16:38:00 +0000939 if target_viminfo is None:
tierno1d213f42020-04-24 14:02:51 +0000940 # must be deleted
tiernobc891ce2020-12-06 18:27:16 +0000941 self._assign_vim(target_vim)
sousaedu2ad85172021-02-17 15:05:18 +0100942 target_record_id = "{}.{}".format(
943 db_record, existing_item["id"]
944 )
tierno70eeb182020-10-19 16:38:00 +0000945 item_ = item
sousaedu2ad85172021-02-17 15:05:18 +0100946
tierno70eeb182020-10-19 16:38:00 +0000947 if target_vim.startswith("sdn"):
948 # item must be sdn-net instead of net if target_vim is a sdn
949 item_ = "sdn_net"
950 target_record_id += ".sdn"
sousaedu2ad85172021-02-17 15:05:18 +0100951
tierno70eeb182020-10-19 16:38:00 +0000952 task = _create_task(
sousaedu2ad85172021-02-17 15:05:18 +0100953 target_vim,
954 item_,
955 "DELETE",
956 target_record="{}.{}.vim_info.{}".format(
957 db_record, item_index, target_vim
958 ),
959 target_record_id=target_record_id,
960 )
tierno70eeb182020-10-19 16:38:00 +0000961 tasks_by_target_record_id[target_record_id] = task
962 db_new_tasks.append(task)
tierno1d213f42020-04-24 14:02:51 +0000963 # TODO delete
964 # TODO check one by one the vims to be created/deleted
965
tierno70eeb182020-10-19 16:38:00 +0000966 # step 2 items (networks,vdus,...) to be created
967 for target_item in target_list:
968 item_index = -1
sousaedu2ad85172021-02-17 15:05:18 +0100969
tierno70eeb182020-10-19 16:38:00 +0000970 for item_index, existing_item in enumerate(existing_list):
971 if existing_item["id"] == target_item["id"]:
tierno1d213f42020-04-24 14:02:51 +0000972 break
973 else:
tierno70eeb182020-10-19 16:38:00 +0000974 item_index += 1
975 db_update[db_path + ".{}".format(item_index)] = target_item
976 existing_list.append(target_item)
977 existing_item = None
tierno1d213f42020-04-24 14:02:51 +0000978
sousaedu2ad85172021-02-17 15:05:18 +0100979 for target_vim, target_viminfo in target_item.get(
980 "vim_info", {}
981 ).items():
tierno1d213f42020-04-24 14:02:51 +0000982 existing_viminfo = None
sousaedu2ad85172021-02-17 15:05:18 +0100983
tierno70eeb182020-10-19 16:38:00 +0000984 if existing_item:
sousaedu2ad85172021-02-17 15:05:18 +0100985 existing_viminfo = existing_item.get("vim_info", {}).get(
986 target_vim
987 )
988
tierno1d213f42020-04-24 14:02:51 +0000989 # TODO check if different. Delete and create???
990 # TODO delete if not exist
tierno70eeb182020-10-19 16:38:00 +0000991 if existing_viminfo is not None:
tierno1d213f42020-04-24 14:02:51 +0000992 continue
993
tierno70eeb182020-10-19 16:38:00 +0000994 target_record_id = "{}.{}".format(db_record, target_item["id"])
995 item_ = item
sousaedu2ad85172021-02-17 15:05:18 +0100996
tierno70eeb182020-10-19 16:38:00 +0000997 if target_vim.startswith("sdn"):
998 # item must be sdn-net instead of net if target_vim is a sdn
999 item_ = "sdn_net"
1000 target_record_id += ".sdn"
tierno1d213f42020-04-24 14:02:51 +00001001
sousaedu2ad85172021-02-17 15:05:18 +01001002 extra_dict = process_params(
1003 target_item, target_viminfo, target_record_id
1004 )
tiernobc891ce2020-12-06 18:27:16 +00001005 self._assign_vim(target_vim)
tierno70eeb182020-10-19 16:38:00 +00001006 task = _create_task(
sousaedu2ad85172021-02-17 15:05:18 +01001007 target_vim,
1008 item_,
1009 "CREATE",
1010 target_record="{}.{}.vim_info.{}".format(
1011 db_record, item_index, target_vim
1012 ),
tierno70eeb182020-10-19 16:38:00 +00001013 target_record_id=target_record_id,
sousaedu2ad85172021-02-17 15:05:18 +01001014 extra_dict=extra_dict,
1015 )
tierno70eeb182020-10-19 16:38:00 +00001016 tasks_by_target_record_id[target_record_id] = task
1017 db_new_tasks.append(task)
sousaedu2ad85172021-02-17 15:05:18 +01001018
tierno70eeb182020-10-19 16:38:00 +00001019 if target_item.get("common_id"):
1020 task["common_id"] = target_item["common_id"]
tierno1d213f42020-04-24 14:02:51 +00001021
tierno70eeb182020-10-19 16:38:00 +00001022 db_update[db_path + ".{}".format(item_index)] = target_item
tierno1d213f42020-04-24 14:02:51 +00001023
1024 def _process_action(indata):
tierno1d213f42020-04-24 14:02:51 +00001025 nonlocal db_new_tasks
1026 nonlocal task_index
1027 nonlocal db_vnfrs
1028 nonlocal db_ro_nsr
1029
tierno70eeb182020-10-19 16:38:00 +00001030 if indata["action"]["action"] == "inject_ssh_key":
1031 key = indata["action"].get("key")
1032 user = indata["action"].get("user")
1033 password = indata["action"].get("password")
sousaedu2ad85172021-02-17 15:05:18 +01001034
tierno1d213f42020-04-24 14:02:51 +00001035 for vnf in indata.get("vnf", ()):
tierno70eeb182020-10-19 16:38:00 +00001036 if vnf["_id"] not in db_vnfrs:
tierno1d213f42020-04-24 14:02:51 +00001037 raise NsException("Invalid vnf={}".format(vnf["_id"]))
sousaedu2ad85172021-02-17 15:05:18 +01001038
tierno1d213f42020-04-24 14:02:51 +00001039 db_vnfr = db_vnfrs[vnf["_id"]]
sousaedu2ad85172021-02-17 15:05:18 +01001040
tierno1d213f42020-04-24 14:02:51 +00001041 for target_vdu in vnf.get("vdur", ()):
sousaedu2ad85172021-02-17 15:05:18 +01001042 vdu_index, vdur = next(
1043 (
1044 i_v
1045 for i_v in enumerate(db_vnfr["vdur"])
1046 if i_v[1]["id"] == target_vdu["id"]
1047 ),
1048 (None, None),
1049 )
1050
tierno1d213f42020-04-24 14:02:51 +00001051 if not vdur:
sousaedu2ad85172021-02-17 15:05:18 +01001052 raise NsException(
1053 "Invalid vdu vnf={}.{}".format(
1054 vnf["_id"], target_vdu["id"]
1055 )
1056 )
1057
1058 target_vim, vim_info = next(
1059 k_v for k_v in vdur["vim_info"].items()
1060 )
tiernobc891ce2020-12-06 18:27:16 +00001061 self._assign_vim(target_vim)
sousaedu2ad85172021-02-17 15:05:18 +01001062 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
1063 vnf["_id"], vdu_index
1064 )
tierno1d213f42020-04-24 14:02:51 +00001065 extra_dict = {
sousaedu2ad85172021-02-17 15:05:18 +01001066 "depends_on": [
1067 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
1068 ],
tierno1d213f42020-04-24 14:02:51 +00001069 "params": {
tierno70eeb182020-10-19 16:38:00 +00001070 "ip_address": vdur.get("ip-address"),
tierno1d213f42020-04-24 14:02:51 +00001071 "user": user,
1072 "key": key,
1073 "password": password,
1074 "private_key": db_ro_nsr["private_key"],
1075 "salt": db_ro_nsr["_id"],
sousaedu2ad85172021-02-17 15:05:18 +01001076 "schema_version": db_ro_nsr["_admin"][
1077 "schema_version"
1078 ],
1079 },
tierno1d213f42020-04-24 14:02:51 +00001080 }
sousaedu2ad85172021-02-17 15:05:18 +01001081 task = _create_task(
1082 target_vim,
1083 "vdu",
1084 "EXEC",
1085 target_record=target_record,
1086 target_record_id=None,
1087 extra_dict=extra_dict,
1088 )
tierno70eeb182020-10-19 16:38:00 +00001089 db_new_tasks.append(task)
tierno1d213f42020-04-24 14:02:51 +00001090
1091 with self.write_lock:
1092 if indata.get("action"):
1093 _process_action(indata)
1094 else:
1095 # compute network differences
1096 # NS.vld
1097 step = "process NS VLDs"
sousaedu2ad85172021-02-17 15:05:18 +01001098 _process_items(
1099 target_list=indata["ns"]["vld"] or [],
1100 existing_list=db_nsr.get("vld") or [],
1101 db_record="nsrs:{}:vld".format(nsr_id),
1102 db_update=db_nsr_update,
1103 db_path="vld",
1104 item="net",
1105 process_params=_process_net_params,
1106 )
tierno1d213f42020-04-24 14:02:51 +00001107
1108 step = "process NS images"
sousaedu2ad85172021-02-17 15:05:18 +01001109 _process_items(
1110 target_list=indata.get("image") or [],
1111 existing_list=db_nsr.get("image") or [],
1112 db_record="nsrs:{}:image".format(nsr_id),
1113 db_update=db_nsr_update,
1114 db_path="image",
1115 item="image",
1116 process_params=_process_image_params,
1117 )
tierno1d213f42020-04-24 14:02:51 +00001118
1119 step = "process NS flavors"
sousaedu2ad85172021-02-17 15:05:18 +01001120 _process_items(
1121 target_list=indata.get("flavor") or [],
1122 existing_list=db_nsr.get("flavor") or [],
1123 db_record="nsrs:{}:flavor".format(nsr_id),
1124 db_update=db_nsr_update,
1125 db_path="flavor",
1126 item="flavor",
1127 process_params=_process_flavor_params,
1128 )
tierno1d213f42020-04-24 14:02:51 +00001129
1130 # VNF.vld
1131 for vnfr_id, vnfr in db_vnfrs.items():
1132 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1133 step = "process VNF={} VLDs".format(vnfr_id)
sousaedu2ad85172021-02-17 15:05:18 +01001134 target_vnf = next(
1135 (
1136 vnf
1137 for vnf in indata.get("vnf", ())
1138 if vnf["_id"] == vnfr_id
1139 ),
1140 None,
1141 )
tierno1d213f42020-04-24 14:02:51 +00001142 target_list = target_vnf.get("vld") if target_vnf else None
sousaedu2ad85172021-02-17 15:05:18 +01001143 _process_items(
1144 target_list=target_list or [],
1145 existing_list=vnfr.get("vld") or [],
1146 db_record="vnfrs:{}:vld".format(vnfr_id),
1147 db_update=db_vnfrs_update[vnfr["_id"]],
1148 db_path="vld",
1149 item="net",
1150 process_params=_process_net_params,
1151 )
tierno1d213f42020-04-24 14:02:51 +00001152
1153 target_list = target_vnf.get("vdur") if target_vnf else None
1154 step = "process VNF={} VDUs".format(vnfr_id)
sousaedu2ad85172021-02-17 15:05:18 +01001155 _process_items(
1156 target_list=target_list or [],
1157 existing_list=vnfr.get("vdur") or [],
1158 db_record="vnfrs:{}:vdur".format(vnfr_id),
1159 db_update=db_vnfrs_update[vnfr["_id"]],
1160 db_path="vdur",
1161 item="vdu",
1162 process_params=_process_vdu_params,
1163 )
tierno1d213f42020-04-24 14:02:51 +00001164
tierno70eeb182020-10-19 16:38:00 +00001165 for db_task in db_new_tasks:
1166 step = "Updating database, Appending tasks to ro_tasks"
1167 target_id = db_task.pop("target_id")
1168 common_id = db_task.get("common_id")
sousaedu2ad85172021-02-17 15:05:18 +01001169
tierno70eeb182020-10-19 16:38:00 +00001170 if common_id:
sousaedu2ad85172021-02-17 15:05:18 +01001171 if self.db.set_one(
1172 "ro_tasks",
1173 q_filter={
1174 "target_id": target_id,
1175 "tasks.common_id": common_id,
1176 },
1177 update_dict={"to_check_at": now, "modified_at": now},
1178 push={"tasks": db_task},
1179 fail_on_empty=False,
1180 ):
tierno70eeb182020-10-19 16:38:00 +00001181 continue
sousaedu2ad85172021-02-17 15:05:18 +01001182
1183 if not self.db.set_one(
1184 "ro_tasks",
1185 q_filter={
1186 "target_id": target_id,
1187 "tasks.target_record": db_task["target_record"],
1188 },
1189 update_dict={"to_check_at": now, "modified_at": now},
1190 push={"tasks": db_task},
1191 fail_on_empty=False,
1192 ):
tierno70eeb182020-10-19 16:38:00 +00001193 # Create a ro_task
1194 step = "Updating database, Creating ro_tasks"
1195 db_ro_task = _create_ro_task(target_id, db_task)
1196 nb_ro_tasks += 1
1197 self.db.create("ro_tasks", db_ro_task)
sousaedu2ad85172021-02-17 15:05:18 +01001198
tierno1d213f42020-04-24 14:02:51 +00001199 step = "Updating database, nsrs"
1200 if db_nsr_update:
1201 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
sousaedu2ad85172021-02-17 15:05:18 +01001202
tierno1d213f42020-04-24 14:02:51 +00001203 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
1204 if db_vnfr_update:
1205 step = "Updating database, vnfrs={}".format(vnfr_id)
1206 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
1207
sousaedu2ad85172021-02-17 15:05:18 +01001208 self.logger.debug(
1209 logging_text
1210 + "Exit. Created {} ro_tasks; {} tasks".format(
1211 nb_ro_tasks, len(db_new_tasks)
1212 )
1213 )
tierno1d213f42020-04-24 14:02:51 +00001214
sousaedu2ad85172021-02-17 15:05:18 +01001215 return (
1216 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
1217 action_id,
1218 True,
1219 )
tierno1d213f42020-04-24 14:02:51 +00001220 except Exception as e:
1221 if isinstance(e, (DbException, NsException)):
sousaedu2ad85172021-02-17 15:05:18 +01001222 self.logger.error(
1223 logging_text + "Exit Exception while '{}': {}".format(step, e)
1224 )
tierno1d213f42020-04-24 14:02:51 +00001225 else:
1226 e = traceback_format_exc()
sousaedu2ad85172021-02-17 15:05:18 +01001227 self.logger.critical(
1228 logging_text + "Exit Exception while '{}': {}".format(step, e),
1229 exc_info=True,
1230 )
1231
tierno1d213f42020-04-24 14:02:51 +00001232 raise NsException(e)
1233
1234 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
tierno70eeb182020-10-19 16:38:00 +00001235 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
tierno1d213f42020-04-24 14:02:51 +00001236 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
sousaedu2ad85172021-02-17 15:05:18 +01001237
tierno70eeb182020-10-19 16:38:00 +00001238 with self.write_lock:
1239 try:
1240 NsWorker.delete_db_tasks(self.db, nsr_id, None)
1241 except NsWorkerException as e:
1242 raise NsException(e)
sousaedu2ad85172021-02-17 15:05:18 +01001243
tierno1d213f42020-04-24 14:02:51 +00001244 return None, None, True
1245
1246 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
tierno70eeb182020-10-19 16:38:00 +00001247 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
1248 # .format(version, nsr_id, action_id, indata))
tierno1d213f42020-04-24 14:02:51 +00001249 task_list = []
1250 done = 0
1251 total = 0
1252 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
1253 global_status = "DONE"
1254 details = []
sousaedu2ad85172021-02-17 15:05:18 +01001255
tierno1d213f42020-04-24 14:02:51 +00001256 for ro_task in ro_tasks:
1257 for task in ro_task["tasks"]:
tierno70eeb182020-10-19 16:38:00 +00001258 if task and task["action_id"] == action_id:
tierno1d213f42020-04-24 14:02:51 +00001259 task_list.append(task)
1260 total += 1
sousaedu2ad85172021-02-17 15:05:18 +01001261
tierno1d213f42020-04-24 14:02:51 +00001262 if task["status"] == "FAILED":
1263 global_status = "FAILED"
sousaedu2ad85172021-02-17 15:05:18 +01001264 error_text = "Error at {} {}: {}".format(
1265 task["action"].lower(),
1266 task["item"],
1267 ro_task["vim_info"].get("vim_details") or "unknown",
1268 )
tierno70eeb182020-10-19 16:38:00 +00001269 details.append(error_text)
tierno1d213f42020-04-24 14:02:51 +00001270 elif task["status"] in ("SCHEDULED", "BUILD"):
1271 if global_status != "FAILED":
1272 global_status = "BUILD"
1273 else:
1274 done += 1
sousaedu2ad85172021-02-17 15:05:18 +01001275
tierno1d213f42020-04-24 14:02:51 +00001276 return_data = {
1277 "status": global_status,
sousaedu2ad85172021-02-17 15:05:18 +01001278 "details": ". ".join(details)
1279 if details
1280 else "progress {}/{}".format(done, total),
tierno1d213f42020-04-24 14:02:51 +00001281 "nsr_id": nsr_id,
1282 "action_id": action_id,
sousaedu2ad85172021-02-17 15:05:18 +01001283 "tasks": task_list,
tierno1d213f42020-04-24 14:02:51 +00001284 }
sousaedu2ad85172021-02-17 15:05:18 +01001285
tierno1d213f42020-04-24 14:02:51 +00001286 return return_data, None, True
1287
1288 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
sousaedu2ad85172021-02-17 15:05:18 +01001289 print(
1290 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
1291 session, indata, version, nsr_id, action_id
1292 )
1293 )
1294
tierno1d213f42020-04-24 14:02:51 +00001295 return None, None, True
1296
1297 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1298 nsrs = self.db.get_list("nsrs", {})
1299 return_data = []
sousaedu2ad85172021-02-17 15:05:18 +01001300
tierno1d213f42020-04-24 14:02:51 +00001301 for ns in nsrs:
1302 return_data.append({"_id": ns["_id"], "name": ns["name"]})
sousaedu2ad85172021-02-17 15:05:18 +01001303
tierno1d213f42020-04-24 14:02:51 +00001304 return return_data, None, True
1305
1306 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1307 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
1308 return_data = []
sousaedu2ad85172021-02-17 15:05:18 +01001309
tierno1d213f42020-04-24 14:02:51 +00001310 for ro_task in ro_tasks:
1311 for task in ro_task["tasks"]:
1312 if task["action_id"] not in return_data:
1313 return_data.append(task["action_id"])
sousaedu2ad85172021-02-17 15:05:18 +01001314
tierno1d213f42020-04-24 14:02:51 +00001315 return return_data, None, True