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": int(target_flavor
["memory-mb"]),
417 "vcpus": int(target_flavor
["vcpu-count"]),
421 if target_flavor
.get("guest-epa"):
424 if target_flavor
["guest-epa"].get("numa-node-policy"):
425 numa_node_policy
= target_flavor
["guest-epa"].get("numa-node-policy")
426 if numa_node_policy
.get("node"):
427 numa_node
= numa_node_policy
["node"][0]
428 if numa_node
.get("num-cores"):
429 numa
["cores"] = numa_node
["num-cores"]
431 if numa_node
.get("paired-threads"):
432 if numa_node
["paired-threads"].get("num-paired-threads"):
433 numa
["paired-threads"] = int(numa_node
["paired-threads"]["num-paired-threads"])
435 if len(numa_node
["paired-threads"].get("paired-thread-ids")):
436 numa
["paired-threads-id"] = []
437 for pair
in numa_node
["paired-threads"]["paired-thread-ids"]:
438 numa
["paired-threads-id"].append(
439 (str(pair
["thread-a"]), str(pair
["thread-b"]))
441 if numa_node
.get("num-threads"):
442 numa
["threads"] = int(numa_node
["num-threads"])
444 if numa_node
.get("memory-mb"):
445 numa
["memory"] = max(int(numa_node
["memory-mb"] / 1024), 1)
446 if target_flavor
["guest-epa"].get("mempage-size"):
447 extended
["mempage-size"] = target_flavor
["guest-epa"].get("mempage-size")
448 if target_flavor
["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set
:
449 if target_flavor
["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
450 if target_flavor
["guest-epa"].get("cpu-thread-pinning-policy") and \
451 target_flavor
["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
452 numa
["cores"] = max(flavor_data
["vcpus"], 1)
454 numa
["threads"] = max(flavor_data
["vcpus"], 1)
456 if target_flavor
["guest-epa"].get("cpu-quota") and not epa_vcpu_set
:
457 cpuquota
= _get_resource_allocation_params(target_flavor
["guest-epa"].get("cpu-quota"))
459 extended
["cpu-quota"] = cpuquota
460 if target_flavor
["guest-epa"].get("mem-quota"):
461 vduquota
= _get_resource_allocation_params(target_flavor
["guest-epa"].get("mem-quota"))
463 extended
["mem-quota"] = vduquota
464 if target_flavor
["guest-epa"].get("disk-io-quota"):
465 diskioquota
= _get_resource_allocation_params(target_flavor
["guest-epa"].get("disk-io-quota"))
467 extended
["disk-io-quota"] = diskioquota
468 if target_flavor
["guest-epa"].get("vif-quota"):
469 vifquota
= _get_resource_allocation_params(target_flavor
["guest-epa"].get("vif-quota"))
471 extended
["vif-quota"] = vifquota
473 extended
["numas"] = [numa
]
475 flavor_data
["extended"] = extended
477 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
478 flavor_data_name
= flavor_data
.copy()
479 flavor_data_name
["name"] = target_flavor
["name"]
480 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
483 def _ip_profile_2_ro(ip_profile
):
487 "ip_version": "IPv4" if "v4" in ip_profile
.get("ip-version", "ipv4") else "IPv6",
488 "subnet_address": ip_profile
.get("subnet-address"),
489 "gateway_address": ip_profile
.get("gateway-address"),
490 "dhcp_enabled": ip_profile
["dhcp-params"].get("enabled", True),
491 "dhcp_start_address": ip_profile
["dhcp-params"].get("start-address"),
492 "dhcp_count": ip_profile
["dhcp-params"].get("count"),
495 if ip_profile
.get("dns-server"):
496 ro_ip_profile
["dns_address"] = ";".join([v
["address"] for v
in ip_profile
["dns-server"]])
497 if ip_profile
.get('security-group'):
498 ro_ip_profile
["security_group"] = ip_profile
['security-group']
501 def _process_net_params(target_vld
, vim_info
, target_record_id
):
505 if vim_info
.get("sdn"):
506 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
507 # ns_preffix = "nsrs:{}".format(nsr_id)
508 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".") # remove the ending ".sdn
509 extra_dict
["params"] = {k
: vim_info
[k
] for k
in ("sdn-ports", "target_vim", "vlds", "type")
511 # TODO needed to add target_id in the dependency.
512 if vim_info
.get("target_vim"):
513 extra_dict
["depends_on"] = [vim_info
.get("target_vim") + " " + vld_target_record_id
]
516 if vim_info
.get("vim_network_name"):
517 extra_dict
["find_params"] = {"filter_dict": {"name": vim_info
.get("vim_network_name")}}
518 elif vim_info
.get("vim_network_id"):
519 extra_dict
["find_params"] = {"filter_dict": {"id": vim_info
.get("vim_network_id")}}
520 elif target_vld
.get("mgmt-network"):
521 extra_dict
["find_params"] = {"mgmt": True, "name": target_vld
["id"]}
524 extra_dict
["params"] = {
525 "net_name": "{}-{}".format(indata
["name"][:16], target_vld
.get("name", target_vld
["id"])[:16]),
526 "ip_profile": _ip_profile_2_ro(vim_info
.get('ip_profile')),
527 "provider_network_profile": vim_info
.get('provider_network'),
529 if not target_vld
.get("underlay"):
530 extra_dict
["params"]["net_type"] = "bridge"
532 extra_dict
["params"]["net_type"] = "ptp" if target_vld
.get("type") == "ELINE" else "data"
535 def _process_vdu_params(target_vdu
, vim_info
, target_record_id
):
540 nonlocal vdu2cloud_init
541 nonlocal tasks_by_target_record_id
542 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
543 ns_preffix
= "nsrs:{}".format(nsr_id
)
544 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
545 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
546 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
548 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
549 if interface
.get("ns-vld-id"):
550 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
551 elif interface
.get("vnf-vld-id"):
552 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
554 self
.logger
.error("Interface {} from vdu {} not connected to any vld".format(
555 iface_index
, target_vdu
["vdu-name"]))
556 continue # interface not connected to any vld
557 extra_dict
["depends_on"].append(net_text
)
558 net_item
= {x
: v
for x
, v
in interface
.items() if x
in
559 ("name", "vpci", "port_security", "port_security_disable_strategy", "floating_ip")}
560 net_item
["net_id"] = "TASK-" + net_text
561 net_item
["type"] = "virtual"
562 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
563 # TODO floating_ip: True/False (or it can be None)
564 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
565 # mark the net create task as type data
566 if deep_get(tasks_by_target_record_id
, net_text
, "params", "net_type"):
567 tasks_by_target_record_id
[net_text
]["params"]["net_type"] = "data"
568 net_item
["use"] = "data"
569 net_item
["model"] = interface
["type"]
570 net_item
["type"] = interface
["type"]
571 elif interface
.get("type") == "OM-MGMT" or interface
.get("mgmt-interface") or \
572 interface
.get("mgmt-vnf"):
573 net_item
["use"] = "mgmt"
574 else: # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
575 net_item
["use"] = "bridge"
576 net_item
["model"] = interface
.get("type")
577 if interface
.get("ip-address"):
578 net_item
["ip_address"] = interface
["ip-address"]
579 if interface
.get("mac-address"):
580 net_item
["mac_address"] = interface
["mac-address"]
581 net_list
.append(net_item
)
582 if interface
.get("mgmt-vnf"):
583 extra_dict
["mgmt_vnf_interface"] = iface_index
584 elif interface
.get("mgmt-interface"):
585 extra_dict
["mgmt_vdu_interface"] = iface_index
588 if target_vdu
.get("cloud-init"):
589 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
590 vdu2cloud_init
[target_vdu
["cloud-init"]] = self
._get
_cloud
_init
(target_vdu
["cloud-init"])
591 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
592 cloud_config
["user-data"] = self
._parse
_jinja
2(cloud_content_
, target_vdu
.get("additionalParams"),
593 target_vdu
["cloud-init"])
594 if target_vdu
.get("boot-data-drive"):
595 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
597 if target_vdu
.get("ssh-keys"):
598 ssh_keys
+= target_vdu
.get("ssh-keys")
599 if target_vdu
.get("ssh-access-required"):
600 ssh_keys
.append(ro_nsr_public_key
)
602 cloud_config
["key-pairs"] = ssh_keys
604 extra_dict
["params"] = {
605 "name": "{}-{}-{}-{}".format(indata
["name"][:16], vnfr
["member-vnf-index-ref"][:16],
606 target_vdu
["vdu-name"][:32], target_vdu
.get("count-index") or 0),
607 "description": target_vdu
["vdu-name"],
609 "image_id": "TASK-" + image_text
,
610 "flavor_id": "TASK-" + flavor_text
,
611 "net_list": net_list
,
612 "cloud_config": cloud_config
or None,
613 "disk_list": None, # TODO
614 "availability_zone_index": None, # TODO
615 "availability_zone_list": None, # TODO
619 def _process_items(target_list
, existing_list
, db_record
, db_update
, db_path
, item
, process_params
):
620 nonlocal db_new_tasks
621 nonlocal tasks_by_target_record_id
624 # ensure all the target_list elements has an "id". If not assign the index as id
625 for target_index
, tl
in enumerate(target_list
):
626 if tl
and not tl
.get("id"):
627 tl
["id"] = str(target_index
)
629 # step 1 items (networks,vdus,...) to be deleted/updated
630 for item_index
, existing_item
in enumerate(existing_list
):
631 target_item
= next((t
for t
in target_list
if t
["id"] == existing_item
["id"]), None)
632 for target_vim
, existing_viminfo
in existing_item
.get("vim_info", {}).items():
633 if existing_viminfo
is None:
636 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
638 target_viminfo
= None
639 if target_viminfo
is None:
641 self
.assign_vim(target_vim
)
642 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
644 if target_vim
.startswith("sdn"):
645 # item must be sdn-net instead of net if target_vim is a sdn
647 target_record_id
+= ".sdn"
649 target_vim
, item_
, "DELETE",
650 target_record
="{}.{}.vim_info.{}".format(db_record
, item_index
, target_vim
),
651 target_record_id
=target_record_id
)
652 tasks_by_target_record_id
[target_record_id
] = task
653 db_new_tasks
.append(task
)
655 # TODO check one by one the vims to be created/deleted
657 # step 2 items (networks,vdus,...) to be created
658 for target_item
in target_list
:
660 for item_index
, existing_item
in enumerate(existing_list
):
661 if existing_item
["id"] == target_item
["id"]:
665 db_update
[db_path
+ ".{}".format(item_index
)] = target_item
666 existing_list
.append(target_item
)
669 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
670 existing_viminfo
= None
672 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
673 # TODO check if different. Delete and create???
674 # TODO delete if not exist
675 if existing_viminfo
is not None:
678 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
680 if target_vim
.startswith("sdn"):
681 # item must be sdn-net instead of net if target_vim is a sdn
683 target_record_id
+= ".sdn"
684 extra_dict
= process_params(target_item
, target_viminfo
, target_record_id
)
686 self
.assign_vim(target_vim
)
688 target_vim
, item_
, "CREATE",
689 target_record
="{}.{}.vim_info.{}".format(db_record
, item_index
, target_vim
),
690 target_record_id
=target_record_id
,
691 extra_dict
=extra_dict
)
692 tasks_by_target_record_id
[target_record_id
] = task
693 db_new_tasks
.append(task
)
694 if target_item
.get("common_id"):
695 task
["common_id"] = target_item
["common_id"]
697 db_update
[db_path
+ ".{}".format(item_index
)] = target_item
699 def _process_action(indata
):
700 nonlocal db_new_tasks
705 if indata
["action"]["action"] == "inject_ssh_key":
706 key
= indata
["action"].get("key")
707 user
= indata
["action"].get("user")
708 password
= indata
["action"].get("password")
709 for vnf
in indata
.get("vnf", ()):
710 if vnf
["_id"] not in db_vnfrs
:
711 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
712 db_vnfr
= db_vnfrs
[vnf
["_id"]]
713 for target_vdu
in vnf
.get("vdur", ()):
714 vdu_index
, vdur
= next((i_v
for i_v
in enumerate(db_vnfr
["vdur"]) if
715 i_v
[1]["id"] == target_vdu
["id"]), (None, None))
717 raise NsException("Invalid vdu vnf={}.{}".format(vnf
["_id"], target_vdu
["id"]))
718 target_vim
, vim_info
= next(k_v
for k_v
in vdur
["vim_info"].items())
719 self
.assign_vim(target_vim
)
720 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(vnf
["_id"], vdu_index
)
722 "depends_on": ["vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])],
724 "ip_address": vdur
.get("ip-address"),
727 "password": password
,
728 "private_key": db_ro_nsr
["private_key"],
729 "salt": db_ro_nsr
["_id"],
730 "schema_version": db_ro_nsr
["_admin"]["schema_version"]
733 task
= _create_task(target_vim
, "vdu", "EXEC",
734 target_record
=target_record
,
735 target_record_id
=None,
736 extra_dict
=extra_dict
)
737 db_new_tasks
.append(task
)
739 with self
.write_lock
:
740 if indata
.get("action"):
741 _process_action(indata
)
743 # compute network differences
745 step
= "process NS VLDs"
746 _process_items(target_list
=indata
["ns"]["vld"] or [], existing_list
=db_nsr
.get("vld") or [],
747 db_record
="nsrs:{}:vld".format(nsr_id
), db_update
=db_nsr_update
,
748 db_path
="vld", item
="net", process_params
=_process_net_params
)
750 step
= "process NS images"
751 _process_items(target_list
=indata
.get("image") or [], existing_list
=db_nsr
.get("image") or [],
752 db_record
="nsrs:{}:image".format(nsr_id
),
753 db_update
=db_nsr_update
, db_path
="image", item
="image",
754 process_params
=_process_image_params
)
756 step
= "process NS flavors"
757 _process_items(target_list
=indata
.get("flavor") or [], existing_list
=db_nsr
.get("flavor") or [],
758 db_record
="nsrs:{}:flavor".format(nsr_id
),
759 db_update
=db_nsr_update
, db_path
="flavor", item
="flavor",
760 process_params
=_process_flavor_params
)
763 for vnfr_id
, vnfr
in db_vnfrs
.items():
764 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
765 step
= "process VNF={} VLDs".format(vnfr_id
)
766 target_vnf
= next((vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
), None)
767 target_list
= target_vnf
.get("vld") if target_vnf
else None
768 _process_items(target_list
=target_list
or [], existing_list
=vnfr
.get("vld") or [],
769 db_record
="vnfrs:{}:vld".format(vnfr_id
), db_update
=db_vnfrs_update
[vnfr
["_id"]],
770 db_path
="vld", item
="net", process_params
=_process_net_params
)
772 target_list
= target_vnf
.get("vdur") if target_vnf
else None
773 step
= "process VNF={} VDUs".format(vnfr_id
)
774 _process_items(target_list
=target_list
or [], existing_list
=vnfr
.get("vdur") or [],
775 db_record
="vnfrs:{}:vdur".format(vnfr_id
),
776 db_update
=db_vnfrs_update
[vnfr
["_id"]], db_path
="vdur", item
="vdu",
777 process_params
=_process_vdu_params
)
779 for db_task
in db_new_tasks
:
780 step
= "Updating database, Appending tasks to ro_tasks"
781 target_id
= db_task
.pop("target_id")
782 common_id
= db_task
.get("common_id")
784 if self
.db
.set_one("ro_tasks",
785 q_filter
={"target_id": target_id
,
786 "tasks.common_id": common_id
},
787 update_dict
={"to_check_at": now
, "modified_at": now
},
788 push
={"tasks": db_task
}, fail_on_empty
=False):
790 if not self
.db
.set_one("ro_tasks",
791 q_filter
={"target_id": target_id
,
792 "tasks.target_record": db_task
["target_record"]},
793 update_dict
={"to_check_at": now
, "modified_at": now
},
794 push
={"tasks": db_task
}, fail_on_empty
=False):
796 step
= "Updating database, Creating ro_tasks"
797 db_ro_task
= _create_ro_task(target_id
, db_task
)
799 self
.db
.create("ro_tasks", db_ro_task
)
800 step
= "Updating database, nsrs"
802 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
803 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
805 step
= "Updating database, vnfrs={}".format(vnfr_id
)
806 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
808 self
.logger
.debug(logging_text
+ "Exit. Created {} ro_tasks; {} tasks".format(nb_ro_tasks
,
810 return {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
}, action_id
, True
812 except Exception as e
:
813 if isinstance(e
, (DbException
, NsException
)):
814 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
816 e
= traceback_format_exc()
817 self
.logger
.critical(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
), exc_info
=True)
820 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
821 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
822 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
823 with self
.write_lock
:
825 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
826 except NsWorkerException
as e
:
828 return None, None, True
830 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
831 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
832 # .format(version, nsr_id, action_id, indata))
836 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
837 global_status
= "DONE"
839 for ro_task
in ro_tasks
:
840 for task
in ro_task
["tasks"]:
841 if task
and task
["action_id"] == action_id
:
842 task_list
.append(task
)
844 if task
["status"] == "FAILED":
845 global_status
= "FAILED"
846 error_text
= "Error at {} {}: {}".format(task
["action"].lower(), task
["item"],
847 ro_task
["vim_info"].get("vim_details") or "unknown")
848 details
.append(error_text
)
849 elif task
["status"] in ("SCHEDULED", "BUILD"):
850 if global_status
!= "FAILED":
851 global_status
= "BUILD"
855 "status": global_status
,
856 "details": ". ".join(details
) if details
else "progress {}/{}".format(done
, total
),
858 "action_id": action_id
,
861 return return_data
, None, True
863 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
864 print("ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(session
, indata
, version
,
866 return None, None, True
868 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
869 nsrs
= self
.db
.get_list("nsrs", {})
872 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
873 return return_data
, None, True
875 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
876 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
878 for ro_task
in ro_tasks
:
879 for task
in ro_task
["tasks"]:
880 if task
["action_id"] not in return_data
:
881 return_data
.append(task
["action_id"])
882 return return_data
, None, True