1 # -*- coding: utf-8 -*-
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
21 from traceback
import format_exc
as traceback_format_exc
22 from osm_ng_ro
.ns_thread
import NsWorker
, NsWorkerException
, deep_get
23 from osm_ng_ro
.validation
import validate_input
, deploy_schema
24 from osm_common
import dbmongo
, dbmemory
, fslocal
, fsmongo
, msglocal
, msgkafka
, version
as common_version
25 from osm_common
.dbbase
import DbException
26 from osm_common
.fsbase
import FsException
27 from osm_common
.msgbase
import MsgException
28 from http
import HTTPStatus
29 from uuid
import uuid4
30 from threading
import Lock
31 from random
import choice
as random_choice
33 from jinja2
import Environment
, TemplateError
, TemplateNotFound
, StrictUndefined
, UndefinedError
34 from cryptography
.hazmat
.primitives
import serialization
as crypto_serialization
35 from cryptography
.hazmat
.primitives
.asymmetric
import rsa
36 from cryptography
.hazmat
.backends
import default_backend
as crypto_default_backend
38 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
39 min_common_version
= "0.1.16"
42 class NsException(Exception):
44 def __init__(self
, message
, http_code
=HTTPStatus
.BAD_REQUEST
):
45 self
.http_code
= http_code
46 super(Exception, self
).__init
__(message
)
51 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
52 will provide a random one
55 # Try getting docker id. If fails, get pid
57 with
open("/proc/self/cgroup", "r") as f
:
58 text_id_
= f
.readline()
59 _
, _
, text_id
= text_id_
.rpartition("/")
60 text_id
= text_id
.replace("\n", "")[:12]
66 return "".join(random_choice("0123456789abcdef") for _
in range(12))
70 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
72 for point
in v
.split("."):
73 filled
.append(point
.zfill(8))
84 # self.operations = None
86 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
87 # If done now it will not be linked to parent not getting its handler and level
89 self
.write_lock
= None
91 self
.assignment_list
= []
96 def init_db(self
, target_version
):
99 def start(self
, config
):
101 Connect to database, filesystem storage, and messaging
102 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
103 :param config: Configuration of db, storage, etc
107 self
.config
["process_id"] = get_process_id() # used for HA identity
108 self
.logger
= logging
.getLogger("ro.ns")
109 # check right version of common
110 if versiontuple(common_version
) < versiontuple(min_common_version
):
111 raise NsException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
112 common_version
, min_common_version
))
116 if config
["database"]["driver"] == "mongo":
117 self
.db
= dbmongo
.DbMongo()
118 self
.db
.db_connect(config
["database"])
119 elif config
["database"]["driver"] == "memory":
120 self
.db
= dbmemory
.DbMemory()
121 self
.db
.db_connect(config
["database"])
123 raise NsException("Invalid configuration param '{}' at '[database]':'driver'".format(
124 config
["database"]["driver"]))
126 if config
["storage"]["driver"] == "local":
127 self
.fs
= fslocal
.FsLocal()
128 self
.fs
.fs_connect(config
["storage"])
129 elif config
["storage"]["driver"] == "mongo":
130 self
.fs
= fsmongo
.FsMongo()
131 self
.fs
.fs_connect(config
["storage"])
132 elif config
["storage"]["driver"] is None:
135 raise NsException("Invalid configuration param '{}' at '[storage]':'driver'".format(
136 config
["storage"]["driver"]))
138 if config
["message"]["driver"] == "local":
139 self
.msg
= msglocal
.MsgLocal()
140 self
.msg
.connect(config
["message"])
141 elif config
["message"]["driver"] == "kafka":
142 self
.msg
= msgkafka
.MsgKafka()
143 self
.msg
.connect(config
["message"])
145 raise NsException("Invalid configuration param '{}' at '[message]':'driver'".format(
146 config
["message"]["driver"]))
148 # TODO load workers to deal with exising database tasks
150 self
.write_lock
= Lock()
151 except (DbException
, FsException
, MsgException
) as e
:
152 raise NsException(str(e
), http_code
=e
.http_code
)
157 self
.db
.db_disconnect()
159 self
.fs
.fs_disconnect()
161 self
.msg
.disconnect()
162 self
.write_lock
= None
163 except (DbException
, FsException
, MsgException
) as e
:
164 raise NsException(str(e
), http_code
=e
.http_code
)
165 for worker
in self
.workers
:
166 worker
.insert_task(("terminate",))
168 def _create_worker(self
, target_id
, load
=True):
169 # Look for a thread not alive
170 worker_id
= next((i
for i
in range(len(self
.workers
)) if not self
.workers
[i
].is_alive()), None)
173 self
.workers
[worker_id
].start()
175 worker_id
= len(self
.workers
)
176 if worker_id
< self
.config
["global"]["server.ns_threads"]:
177 # create a new worker
178 self
.workers
.append(NsWorker(worker_id
, self
.config
, self
.plugins
, self
.db
))
179 self
.workers
[worker_id
].start()
181 # reached maximum number of threads, assign VIM to an existing one
182 worker_id
= self
.next_worker
183 self
.next_worker
= (self
.next_worker
+ 1) % self
.config
["global"]["server.ns_threads"]
185 self
.workers
[worker_id
].insert_task(("load_vim", target_id
))
188 def assign_vim(self
, target_id
):
189 if target_id
not in self
.assignment
:
190 self
.assignment
[target_id
] = self
._create
_worker
(target_id
)
191 self
.assignment_list
.append(target_id
)
193 def reload_vim(self
, target_id
):
194 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
195 # this is because database VIM information is cached for threads working with SDN
196 # if target_id in self.assignment:
197 # worker_id = self.assignment[target_id]
198 # self.workers[worker_id].insert_task(("reload_vim", target_id))
199 for worker
in self
.workers
:
200 if worker
.is_alive():
201 worker
.insert_task(("reload_vim", target_id
))
203 def unload_vim(self
, target_id
):
204 if target_id
in self
.assignment
:
205 worker_id
= self
.assignment
[target_id
]
206 self
.workers
[worker_id
].insert_task(("unload_vim", target_id
))
207 del self
.assignment
[target_id
]
208 self
.assignment_list
.remove(target_id
)
210 def check_vim(self
, target_id
):
211 if target_id
in self
.assignment
:
212 worker_id
= self
.assignment
[target_id
]
214 worker_id
= self
._create
_worker
(target_id
, load
=False)
216 worker
= self
.workers
[worker_id
]
217 worker
.insert_task(("check_vim", target_id
))
219 def _get_cloud_init(self
, where
):
222 :param where: can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
225 vnfd_id
, _
, other
= where
.partition(":")
226 _type
, _
, name
= other
.partition(":")
227 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
229 base_folder
= vnfd
["_admin"]["storage"]
230 cloud_init_file
= "{}/{}/cloud_init/{}".format(base_folder
["folder"], base_folder
["pkg-dir"], name
)
232 raise NsException("Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver"
233 .format(cloud_init_file
))
234 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
235 cloud_init_content
= ci_file
.read()
237 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
239 raise NsException("Mismatch descriptor for cloud init: {}".format(where
))
240 return cloud_init_content
242 def _parse_jinja2(self
, cloud_init_content
, params
, context
):
245 env
= Environment(undefined
=StrictUndefined
)
246 template
= env
.from_string(cloud_init_content
)
247 return template
.render(params
or {})
248 except UndefinedError
as e
:
250 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
251 "inside the 'additionalParamsForVnf' block".format(e
, context
))
252 except (TemplateError
, TemplateNotFound
) as e
:
253 raise NsException("Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(context
, e
))
255 def _create_db_ro_nsrs(self
, nsr_id
, now
):
257 key
= rsa
.generate_private_key(
258 backend
=crypto_default_backend(),
259 public_exponent
=65537,
262 private_key
= key
.private_bytes(
263 crypto_serialization
.Encoding
.PEM
,
264 crypto_serialization
.PrivateFormat
.PKCS8
,
265 crypto_serialization
.NoEncryption())
266 public_key
= key
.public_key().public_bytes(
267 crypto_serialization
.Encoding
.OpenSSH
,
268 crypto_serialization
.PublicFormat
.OpenSSH
270 private_key
= private_key
.decode('utf8')
271 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
272 i
= private_key
.find("\n")
273 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
274 public_key
= public_key
.decode('utf8')
275 except Exception as e
:
276 raise NsException("Cannot create ssh-keys: {}".format(e
))
278 schema_version
= "1.1"
279 private_key_encrypted
= self
.db
.encrypt(private_key
, schema_version
=schema_version
, salt
=nsr_id
)
285 "schema_version": schema_version
287 "public_key": public_key
,
288 "private_key": private_key_encrypted
,
291 self
.db
.create("ro_nsrs", db_content
)
294 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
295 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
296 validate_input(indata
, deploy_schema
)
297 action_id
= indata
.get("action_id", str(uuid4()))
299 # get current deployment
300 db_nsr_update
= {} # update operation on nsrs
302 db_vnfrs
= {} # vnf's info indexed by _id
303 nb_ro_tasks
= 0 # for logging
304 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
306 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
307 self
.logger
.debug(logging_text
+ "Enter")
309 step
= "Getting ns and vnfr record from db"
310 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
312 tasks_by_target_record_id
= {}
313 # read from db: vnf's of this ns
314 step
= "Getting vnfrs from db"
315 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
316 if not db_vnfrs_list
:
317 raise NsException("Cannot obtain associated VNF for ns")
318 for vnfr
in db_vnfrs_list
:
319 db_vnfrs
[vnfr
["_id"]] = vnfr
320 db_vnfrs_update
[vnfr
["_id"]] = {}
322 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
324 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
325 ro_nsr_public_key
= db_ro_nsr
["public_key"]
327 # check that action_id is not in the list of actions. Suffixed with :index
328 if action_id
in db_ro_nsr
["actions"]:
331 new_action_id
= "{}:{}".format(action_id
, index
)
332 if new_action_id
not in db_ro_nsr
["actions"]:
333 action_id
= new_action_id
334 self
.logger
.debug(logging_text
+ "Changing action_id in use to {}".format(action_id
))
338 def _create_task(target_id
, item
, action
, target_record
, target_record_id
, extra_dict
=None):
344 "target_id": target_id
, # it will be removed before pushing at database
345 "action_id": action_id
,
347 "task_id": "{}:{}".format(action_id
, task_index
),
348 "status": "SCHEDULED",
351 "target_record": target_record
,
352 "target_record_id": target_record_id
,
355 task
.update(extra_dict
) # params, find_params, depends_on
359 def _create_ro_task(target_id
, task
):
364 _id
= task
["task_id"]
369 "target_id": target_id
,
372 "created_items": None,
386 def _process_image_params(target_image
, vim_info
, target_record_id
):
388 if target_image
.get("image"):
389 find_params
["filter_dict"] = {"name": target_image
.get("image")}
390 if target_image
.get("vim_image_id"):
391 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
392 if target_image
.get("image_checksum"):
393 find_params
["filter_dict"] = {"checksum": target_image
.get("image_checksum")}
394 return {"find_params": find_params
}
396 def _process_flavor_params(target_flavor
, vim_info
, target_record_id
):
398 def _get_resource_allocation_params(quota_descriptor
):
400 read the quota_descriptor from vnfd and fetch the resource allocation properties from the
402 :param quota_descriptor: cpu/mem/vif/disk-io quota descriptor
403 :return: quota params for limit, reserve, shares from the descriptor object
406 if quota_descriptor
.get("limit"):
407 quota
["limit"] = int(quota_descriptor
["limit"])
408 if quota_descriptor
.get("reserve"):
409 quota
["reserve"] = int(quota_descriptor
["reserve"])
410 if quota_descriptor
.get("shares"):
411 quota
["shares"] = int(quota_descriptor
["shares"])
415 "disk": int(target_flavor
["storage-gb"]),
416 # "ram": max(int(target_flavor["memory-mb"]) // 1024, 1),
417 # ^ TODO manage at vim_connectors MB instead of GB
418 "ram": int(target_flavor
["memory-mb"]),
419 "vcpus": target_flavor
["vcpu-count"],
423 if target_flavor
.get("guest-epa"):
426 if target_flavor
["guest-epa"].get("numa-node-policy"):
427 numa_node_policy
= target_flavor
["guest-epa"].get("numa-node-policy")
428 if numa_node_policy
.get("node"):
429 numa_node
= numa_node_policy
["node"][0]
430 if numa_node
.get("num-cores"):
431 numa
["cores"] = numa_node
["num-cores"]
433 if numa_node
.get("paired-threads"):
434 if numa_node
["paired-threads"].get("num-paired-threads"):
435 numa
["paired-threads"] = int(numa_node
["paired-threads"]["num-paired-threads"])
437 if len(numa_node
["paired-threads"].get("paired-thread-ids")):
438 numa
["paired-threads-id"] = []
439 for pair
in numa_node
["paired-threads"]["paired-thread-ids"]:
440 numa
["paired-threads-id"].append(
441 (str(pair
["thread-a"]), str(pair
["thread-b"]))
443 if numa_node
.get("num-threads"):
444 numa
["threads"] = int(numa_node
["num-threads"])
446 if numa_node
.get("memory-mb"):
447 numa
["memory"] = max(int(numa_node
["memory-mb"] / 1024), 1)
448 if target_flavor
["guest-epa"].get("mempage-size"):
449 extended
["mempage-size"] = target_flavor
["guest-epa"].get("mempage-size")
450 if target_flavor
["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set
:
451 if target_flavor
["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
452 if target_flavor
["guest-epa"].get("cpu-thread-pinning-policy") and \
453 target_flavor
["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
454 numa
["cores"] = max(flavor_data
["vcpus"], 1)
456 numa
["threads"] = max(flavor_data
["vcpus"], 1)
458 if target_flavor
["guest-epa"].get("cpu-quota") and not epa_vcpu_set
:
459 cpuquota
= _get_resource_allocation_params(target_flavor
["guest-epa"].get("cpu-quota"))
461 extended
["cpu-quota"] = cpuquota
462 if target_flavor
["guest-epa"].get("mem-quota"):
463 vduquota
= _get_resource_allocation_params(target_flavor
["guest-epa"].get("mem-quota"))
465 extended
["mem-quota"] = vduquota
466 if target_flavor
["guest-epa"].get("disk-io-quota"):
467 diskioquota
= _get_resource_allocation_params(target_flavor
["guest-epa"].get("disk-io-quota"))
469 extended
["disk-io-quota"] = diskioquota
470 if target_flavor
["guest-epa"].get("vif-quota"):
471 vifquota
= _get_resource_allocation_params(target_flavor
["guest-epa"].get("vif-quota"))
473 extended
["vif-quota"] = vifquota
475 extended
["numas"] = [numa
]
477 flavor_data
["extended"] = extended
479 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
480 flavor_data_name
= flavor_data
.copy()
481 flavor_data_name
["name"] = target_flavor
["name"]
482 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
485 def _ip_profile_2_ro(ip_profile
):
489 "ip_version": "IPv4" if "v4" in ip_profile
.get("ip-version", "ipv4") else "IPv6",
490 "subnet_address": ip_profile
.get("subnet-address"),
491 "gateway_address": ip_profile
.get("gateway-address"),
492 "dhcp_enabled": ip_profile
["dhcp-params"].get("enabled", True),
493 "dhcp_start_address": ip_profile
["dhcp-params"].get("start-address"),
494 "dhcp_count": ip_profile
["dhcp-params"].get("count"),
497 if ip_profile
.get("dns-server"):
498 ro_ip_profile
["dns_address"] = ";".join([v
["address"] for v
in ip_profile
["dns-server"]])
499 if ip_profile
.get('security-group'):
500 ro_ip_profile
["security_group"] = ip_profile
['security-group']
503 def _process_net_params(target_vld
, vim_info
, target_record_id
):
507 if vim_info
.get("sdn"):
508 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
509 # ns_preffix = "nsrs:{}".format(nsr_id)
510 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".") # remove the ending ".sdn
511 extra_dict
["params"] = {k
: vim_info
[k
] for k
in ("sdn-ports", "target_vim", "vlds", "type")
513 # TODO needed to add target_id in the dependency.
514 if vim_info
.get("target_vim"):
515 extra_dict
["depends_on"] = [vim_info
.get("target_vim") + " " + vld_target_record_id
]
518 if vim_info
.get("vim_network_name"):
519 extra_dict
["find_params"] = {"filter_dict": {"name": vim_info
.get("vim_network_name")}}
520 elif vim_info
.get("vim_network_id"):
521 extra_dict
["find_params"] = {"filter_dict": {"id": vim_info
.get("vim_network_id")}}
522 elif target_vld
.get("mgmt-network"):
523 extra_dict
["find_params"] = {"mgmt": True, "name": target_vld
["id"]}
526 extra_dict
["params"] = {
527 "net_name": "{}-{}".format(indata
["name"][:16], target_vld
.get("name", target_vld
["id"])[:16]),
528 "ip_profile": _ip_profile_2_ro(vim_info
.get('ip_profile')),
529 "provider_network_profile": vim_info
.get('provider_network'),
531 if not target_vld
.get("underlay"):
532 extra_dict
["params"]["net_type"] = "bridge"
534 extra_dict
["params"]["net_type"] = "ptp" if target_vld
.get("type") == "ELINE" else "data"
537 def _process_vdu_params(target_vdu
, vim_info
, target_record_id
):
542 nonlocal vdu2cloud_init
543 nonlocal tasks_by_target_record_id
544 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
545 ns_preffix
= "nsrs:{}".format(nsr_id
)
546 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
547 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
548 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
550 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
551 if interface
.get("ns-vld-id"):
552 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
554 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
555 extra_dict
["depends_on"].append(net_text
)
556 net_item
= {x
: v
for x
, v
in interface
.items() if x
in
557 ("name", "vpci", "port_security", "port_security_disable_strategy", "floating_ip")}
558 net_item
["net_id"] = "TASK-" + net_text
559 net_item
["type"] = "virtual"
560 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
561 # TODO floating_ip: True/False (or it can be None)
562 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
563 # mark the net create task as type data
564 if deep_get(tasks_by_target_record_id
, net_text
, "params", "net_type"):
565 tasks_by_target_record_id
[net_text
]["params"]["net_type"] = "data"
566 net_item
["use"] = "data"
567 net_item
["model"] = interface
["type"]
568 net_item
["type"] = interface
["type"]
569 elif interface
.get("type") == "OM-MGMT" or interface
.get("mgmt-interface") or \
570 interface
.get("mgmt-vnf"):
571 net_item
["use"] = "mgmt"
572 else: # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
573 net_item
["use"] = "bridge"
574 net_item
["model"] = interface
.get("type")
575 if interface
.get("ip-address"):
576 net_item
["ip_address"] = interface
["ip-address"]
577 if interface
.get("mac-address"):
578 net_item
["mac_address"] = interface
["mac-address"]
579 net_list
.append(net_item
)
580 if interface
.get("mgmt-vnf"):
581 extra_dict
["mgmt_vnf_interface"] = iface_index
582 elif interface
.get("mgmt-interface"):
583 extra_dict
["mgmt_vdu_interface"] = iface_index
586 if target_vdu
.get("cloud-init"):
587 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
588 vdu2cloud_init
[target_vdu
["cloud-init"]] = self
._get
_cloud
_init
(target_vdu
["cloud-init"])
589 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
590 cloud_config
["user-data"] = self
._parse
_jinja
2(cloud_content_
, target_vdu
.get("additionalParams"),
591 target_vdu
["cloud-init"])
592 if target_vdu
.get("boot-data-drive"):
593 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
595 if target_vdu
.get("ssh-keys"):
596 ssh_keys
+= target_vdu
.get("ssh-keys")
597 if target_vdu
.get("ssh-access-required"):
598 ssh_keys
.append(ro_nsr_public_key
)
600 cloud_config
["key-pairs"] = ssh_keys
602 extra_dict
["params"] = {
603 "name": "{}-{}-{}-{}".format(indata
["name"][:16], vnfr
["member-vnf-index-ref"][:16],
604 target_vdu
["vdu-name"][:32], target_vdu
.get("count-index") or 0),
605 "description": target_vdu
["vdu-name"],
607 "image_id": "TASK-" + image_text
,
608 "flavor_id": "TASK-" + flavor_text
,
609 "net_list": net_list
,
610 "cloud_config": cloud_config
or None,
611 "disk_list": None, # TODO
612 "availability_zone_index": None, # TODO
613 "availability_zone_list": None, # TODO
617 def _process_items(target_list
, existing_list
, db_record
, db_update
, db_path
, item
, process_params
):
618 nonlocal db_new_tasks
619 nonlocal tasks_by_target_record_id
622 # ensure all the target_list elements has an "id". If not assign the index as id
623 for target_index
, tl
in enumerate(target_list
):
624 if tl
and not tl
.get("id"):
625 tl
["id"] = str(target_index
)
627 # step 1 items (networks,vdus,...) to be deleted/updated
628 for item_index
, existing_item
in enumerate(existing_list
):
629 target_item
= next((t
for t
in target_list
if t
["id"] == existing_item
["id"]), None)
630 for target_vim
, existing_viminfo
in existing_item
.get("vim_info", {}).items():
631 if existing_viminfo
is None:
634 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
636 target_viminfo
= None
637 if target_viminfo
is None:
639 self
.assign_vim(target_vim
)
640 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
642 if target_vim
.startswith("sdn"):
643 # item must be sdn-net instead of net if target_vim is a sdn
645 target_record_id
+= ".sdn"
647 target_vim
, item_
, "DELETE",
648 target_record
="{}.{}.vim_info.{}".format(db_record
, item_index
, target_vim
),
649 target_record_id
=target_record_id
)
650 tasks_by_target_record_id
[target_record_id
] = task
651 db_new_tasks
.append(task
)
653 # TODO check one by one the vims to be created/deleted
655 # step 2 items (networks,vdus,...) to be created
656 for target_item
in target_list
:
658 for item_index
, existing_item
in enumerate(existing_list
):
659 if existing_item
["id"] == target_item
["id"]:
663 db_update
[db_path
+ ".{}".format(item_index
)] = target_item
664 existing_list
.append(target_item
)
667 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
668 existing_viminfo
= None
670 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
671 # TODO check if different. Delete and create???
672 # TODO delete if not exist
673 if existing_viminfo
is not None:
676 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
678 if target_vim
.startswith("sdn"):
679 # item must be sdn-net instead of net if target_vim is a sdn
681 target_record_id
+= ".sdn"
682 extra_dict
= process_params(target_item
, target_viminfo
, target_record_id
)
684 self
.assign_vim(target_vim
)
686 target_vim
, item_
, "CREATE",
687 target_record
="{}.{}.vim_info.{}".format(db_record
, item_index
, target_vim
),
688 target_record_id
=target_record_id
,
689 extra_dict
=extra_dict
)
690 tasks_by_target_record_id
[target_record_id
] = task
691 db_new_tasks
.append(task
)
692 if target_item
.get("common_id"):
693 task
["common_id"] = target_item
["common_id"]
695 db_update
[db_path
+ ".{}".format(item_index
)] = target_item
697 def _process_action(indata
):
698 nonlocal db_new_tasks
703 if indata
["action"]["action"] == "inject_ssh_key":
704 key
= indata
["action"].get("key")
705 user
= indata
["action"].get("user")
706 password
= indata
["action"].get("password")
707 for vnf
in indata
.get("vnf", ()):
708 if vnf
["_id"] not in db_vnfrs
:
709 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
710 db_vnfr
= db_vnfrs
[vnf
["_id"]]
711 for target_vdu
in vnf
.get("vdur", ()):
712 vdu_index
, vdur
= next((i_v
for i_v
in enumerate(db_vnfr
["vdur"]) if
713 i_v
[1]["id"] == target_vdu
["id"]), (None, None))
715 raise NsException("Invalid vdu vnf={}.{}".format(vnf
["_id"], target_vdu
["id"]))
716 target_vim
, vim_info
= next(k_v
for k_v
in vdur
["vim_info"].items())
717 self
.assign_vim(target_vim
)
718 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(vnf
["_id"], vdu_index
)
720 "depends_on": ["vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])],
722 "ip_address": vdur
.get("ip-address"),
725 "password": password
,
726 "private_key": db_ro_nsr
["private_key"],
727 "salt": db_ro_nsr
["_id"],
728 "schema_version": db_ro_nsr
["_admin"]["schema_version"]
731 task
= _create_task(target_vim
, "vdu", "EXEC",
732 target_record
=target_record
,
733 target_record_id
=None,
734 extra_dict
=extra_dict
)
735 db_new_tasks
.append(task
)
737 with self
.write_lock
:
738 if indata
.get("action"):
739 _process_action(indata
)
741 # compute network differences
743 step
= "process NS VLDs"
744 _process_items(target_list
=indata
["ns"]["vld"] or [], existing_list
=db_nsr
.get("vld") or [],
745 db_record
="nsrs:{}:vld".format(nsr_id
), db_update
=db_nsr_update
,
746 db_path
="vld", item
="net", process_params
=_process_net_params
)
748 step
= "process NS images"
749 _process_items(target_list
=indata
.get("image") or [], existing_list
=db_nsr
.get("image") or [],
750 db_record
="nsrs:{}:image".format(nsr_id
),
751 db_update
=db_nsr_update
, db_path
="image", item
="image",
752 process_params
=_process_image_params
)
754 step
= "process NS flavors"
755 _process_items(target_list
=indata
.get("flavor") or [], existing_list
=db_nsr
.get("flavor") or [],
756 db_record
="nsrs:{}:flavor".format(nsr_id
),
757 db_update
=db_nsr_update
, db_path
="flavor", item
="flavor",
758 process_params
=_process_flavor_params
)
761 for vnfr_id
, vnfr
in db_vnfrs
.items():
762 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
763 step
= "process VNF={} VLDs".format(vnfr_id
)
764 target_vnf
= next((vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
), None)
765 target_list
= target_vnf
.get("vld") if target_vnf
else None
766 _process_items(target_list
=target_list
or [], existing_list
=vnfr
.get("vld") or [],
767 db_record
="vnfrs:{}:vld".format(vnfr_id
), db_update
=db_vnfrs_update
[vnfr
["_id"]],
768 db_path
="vld", item
="net", process_params
=_process_net_params
)
770 target_list
= target_vnf
.get("vdur") if target_vnf
else None
771 step
= "process VNF={} VDUs".format(vnfr_id
)
772 _process_items(target_list
=target_list
or [], existing_list
=vnfr
.get("vdur") or [],
773 db_record
="vnfrs:{}:vdur".format(vnfr_id
),
774 db_update
=db_vnfrs_update
[vnfr
["_id"]], db_path
="vdur", item
="vdu",
775 process_params
=_process_vdu_params
)
777 for db_task
in db_new_tasks
:
778 step
= "Updating database, Appending tasks to ro_tasks"
779 target_id
= db_task
.pop("target_id")
780 common_id
= db_task
.get("common_id")
782 if self
.db
.set_one("ro_tasks",
783 q_filter
={"target_id": target_id
,
784 "tasks.common_id": common_id
},
785 update_dict
={"to_check_at": now
, "modified_at": now
},
786 push
={"tasks": db_task
}, fail_on_empty
=False):
788 if not self
.db
.set_one("ro_tasks",
789 q_filter
={"target_id": target_id
,
790 "tasks.target_record": db_task
["target_record"]},
791 update_dict
={"to_check_at": now
, "modified_at": now
},
792 push
={"tasks": db_task
}, fail_on_empty
=False):
794 step
= "Updating database, Creating ro_tasks"
795 db_ro_task
= _create_ro_task(target_id
, db_task
)
797 self
.db
.create("ro_tasks", db_ro_task
)
798 step
= "Updating database, nsrs"
800 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
801 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
803 step
= "Updating database, vnfrs={}".format(vnfr_id
)
804 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
806 self
.logger
.debug(logging_text
+ "Exit. Created {} ro_tasks; {} tasks".format(nb_ro_tasks
,
808 return {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
}, action_id
, True
810 except Exception as e
:
811 if isinstance(e
, (DbException
, NsException
)):
812 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
814 e
= traceback_format_exc()
815 self
.logger
.critical(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
), exc_info
=True)
818 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
819 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
820 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
821 with self
.write_lock
:
823 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
824 except NsWorkerException
as e
:
826 return None, None, True
828 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
829 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
830 # .format(version, nsr_id, action_id, indata))
834 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
835 global_status
= "DONE"
837 for ro_task
in ro_tasks
:
838 for task
in ro_task
["tasks"]:
839 if task
and task
["action_id"] == action_id
:
840 task_list
.append(task
)
842 if task
["status"] == "FAILED":
843 global_status
= "FAILED"
844 error_text
= "Error at {} {}: {}".format(task
["action"].lower(), task
["item"],
845 ro_task
["vim_info"].get("vim_details") or "unknown")
846 details
.append(error_text
)
847 elif task
["status"] in ("SCHEDULED", "BUILD"):
848 if global_status
!= "FAILED":
849 global_status
= "BUILD"
853 "status": global_status
,
854 "details": ". ".join(details
) if details
else "progress {}/{}".format(done
, total
),
856 "action_id": action_id
,
859 return return_data
, None, True
861 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
862 print("ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(session
, indata
, version
,
864 return None, None, True
866 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
867 nsrs
= self
.db
.get_list("nsrs", {})
870 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
871 return return_data
, None, True
873 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
874 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
876 for ro_task
in ro_tasks
:
877 for task
in ro_task
["tasks"]:
878 if task
["action_id"] not in return_data
:
879 return_data
.append(task
["action_id"])
880 return return_data
, None, True