Feature 10944 Change naming of charms
[osm/LCM.git] / osm_lcm / lcm_utils.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2018 Telefonica S.A.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
16 # under the License.
17 ##
18
19 import asyncio
20 import checksumdir
21 from collections import OrderedDict
22 import os
23 import shutil
24 import traceback
25 from time import time
26
27 from osm_common.fsbase import FsException
28 from osm_lcm.data_utils.database.database import Database
29 from osm_lcm.data_utils.filesystem.filesystem import Filesystem
30 import yaml
31 from zipfile import ZipFile, BadZipfile
32
33 # from osm_common.dbbase import DbException
34
35 __author__ = "Alfonso Tierno"
36
37
38 class LcmException(Exception):
39 pass
40
41
42 class LcmExceptionNoMgmtIP(LcmException):
43 pass
44
45
46 class LcmExceptionExit(LcmException):
47 pass
48
49
50 def versiontuple(v):
51 """utility for compare dot separate versions. Fills with zeros to proper number comparison
52 package version will be something like 4.0.1.post11+gb3f024d.dirty-1. Where 4.0.1 is the git tag, postXX is the
53 number of commits from this tag, and +XXXXXXX is the git commit short id. Total length is 16 with until 999 commits
54 """
55 filled = []
56 for point in v.split("."):
57 point, _, _ = point.partition("+")
58 point, _, _ = point.partition("-")
59 filled.append(point.zfill(20))
60 return tuple(filled)
61
62
63 def deep_get(target_dict, key_list, default_value=None):
64 """
65 Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None
66 Example target_dict={a: {b: 5}}; key_list=[a,b] returns 5; both key_list=[a,b,c] and key_list=[f,h] return None
67 :param target_dict: dictionary to be read
68 :param key_list: list of keys to read from target_dict
69 :param default_value: value to return if key is not present in the nested dictionary
70 :return: The wanted value if exist, None otherwise
71 """
72 for key in key_list:
73 if not isinstance(target_dict, dict) or key not in target_dict:
74 return default_value
75 target_dict = target_dict[key]
76 return target_dict
77
78
79 def get_iterable(in_dict, in_key):
80 """
81 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
82 :param in_dict: a dictionary
83 :param in_key: the key to look for at in_dict
84 :return: in_dict[in_var] or () if it is None or not present
85 """
86 if not in_dict.get(in_key):
87 return ()
88 return in_dict[in_key]
89
90
91 def check_juju_bundle_existence(vnfd: dict) -> str:
92 """Checks the existence of juju-bundle in the descriptor
93
94 Args:
95 vnfd: Descriptor as a dictionary
96
97 Returns:
98 Juju bundle if dictionary has juju-bundle else None
99
100 """
101 if vnfd.get("vnfd"):
102 vnfd = vnfd["vnfd"]
103
104 for kdu in vnfd.get("kdu", []):
105 return kdu.get("juju-bundle", None)
106
107
108 def get_charm_artifact_path(base_folder, charm_name, charm_type, revision=str()) -> str:
109 """Finds the charm artifact paths
110
111 Args:
112 base_folder: Main folder which will be looked up for charm
113 charm_name: Charm name
114 charm_type: Type of charm native_charm, lxc_proxy_charm or k8s_proxy_charm
115 revision: vnf package revision number if there is
116
117 Returns:
118 artifact_path: (str)
119
120 """
121 extension = ""
122 if revision:
123 extension = ":" + str(revision)
124
125 if base_folder.get("pkg-dir"):
126 artifact_path = "{}/{}/{}/{}".format(
127 base_folder["folder"].split(":")[0] + extension,
128 base_folder["pkg-dir"],
129 "charms"
130 if charm_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
131 else "helm-charts",
132 charm_name,
133 )
134
135 else:
136 # For SOL004 packages
137 artifact_path = "{}/Scripts/{}/{}".format(
138 base_folder["folder"].split(":")[0] + extension,
139 "charms"
140 if charm_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
141 else "helm-charts",
142 charm_name,
143 )
144
145 return artifact_path
146
147
148 def populate_dict(target_dict, key_list, value):
149 """
150 Update target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
151 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
152 :param target_dict: dictionary to be changed
153 :param key_list: list of keys to insert at target_dict
154 :param value:
155 :return: None
156 """
157 for key in key_list[0:-1]:
158 if key not in target_dict:
159 target_dict[key] = {}
160 target_dict = target_dict[key]
161 target_dict[key_list[-1]] = value
162
163
164 class LcmBase:
165 def __init__(self, msg, logger):
166 """
167
168 :param db: database connection
169 """
170 self.db = Database().instance.db
171 self.msg = msg
172 self.fs = Filesystem().instance.fs
173 self.logger = logger
174
175 def update_db_2(self, item, _id, _desc):
176 """
177 Updates database with _desc information. If success _desc is cleared
178 :param item: collection
179 :param _id: the _id to use in the query filter
180 :param _desc: dictionary with the content to update. Keys are dot separated keys for
181 :return: None. Exception is raised on error
182 """
183 if not _desc:
184 return
185 now = time()
186 _desc["_admin.modified"] = now
187 self.db.set_one(item, {"_id": _id}, _desc)
188 _desc.clear()
189 # except DbException as e:
190 # self.logger.error("Updating {} _id={} with '{}'. Error: {}".format(item, _id, _desc, e))
191
192 def check_charm_hash_changed(
193 self, current_charm_path: str, target_charm_path: str
194 ) -> bool:
195 """Find the target charm has changed or not by checking the hash of
196 old and new charm packages
197
198 Args:
199 current_charm_path (str): Existing charm package artifact path
200 target_charm_path (str): Target charm package artifact path
201
202 Returns:
203 True/False (bool): if charm has changed it returns True
204
205 """
206 # Check if the charm artifacts are available
207 if os.path.exists(self.fs.path + current_charm_path) and os.path.exists(
208 self.fs.path + target_charm_path
209 ):
210 # Compare the hash of charm folders
211 if checksumdir.dirhash(
212 self.fs.path + current_charm_path
213 ) != checksumdir.dirhash(self.fs.path + target_charm_path):
214
215 return True
216
217 return False
218
219 else:
220 raise LcmException(
221 "Charm artifact {} does not exist in the VNF Package".format(
222 self.fs.path + target_charm_path
223 )
224 )
225
226 @staticmethod
227 def get_charm_name(charm_metadata_file: str) -> str:
228 """Get the charm name from metadata file.
229
230 Args:
231 charm_metadata_file (str): charm metadata file full path
232
233 Returns:
234 charm_name (str): charm name
235
236 """
237 # Read charm metadata.yaml to get the charm name
238 with open(charm_metadata_file, "r") as metadata_file:
239 content = yaml.safe_load(metadata_file)
240 charm_name = content["name"]
241 return str(charm_name)
242
243 def _get_charm_path(
244 self, nsd_package_path: str, nsd_package_name: str, charm_folder_name: str
245 ) -> str:
246 """Get the full path of charm folder.
247
248 Args:
249 nsd_package_path (str): NSD package full path
250 nsd_package_name (str): NSD package name
251 charm_folder_name (str): folder name
252
253 Returns:
254 charm_path (str): charm folder full path
255 """
256 charm_path = (
257 self.fs.path
258 + nsd_package_path
259 + "/"
260 + nsd_package_name
261 + "/charms/"
262 + charm_folder_name
263 )
264 return charm_path
265
266 def _get_charm_metadata_file(
267 self,
268 charm_folder_name: str,
269 nsd_package_path: str,
270 nsd_package_name: str,
271 charm_path: str = None,
272 ) -> str:
273 """Get the path of charm metadata file.
274
275 Args:
276 charm_folder_name (str): folder name
277 nsd_package_path (str): NSD package full path
278 nsd_package_name (str): NSD package name
279 charm_path (str): Charm full path
280
281 Returns:
282 charm_metadata_file_path (str): charm metadata file full path
283
284 """
285 # Locate the charm metadata.yaml
286 if charm_folder_name.endswith(".charm"):
287 extract_path = (
288 self.fs.path
289 + nsd_package_path
290 + "/"
291 + nsd_package_name
292 + "/charms/"
293 + charm_folder_name.split(".")[0]
294 )
295 # Extract .charm to extract path
296 with ZipFile(charm_path, "r") as zipfile:
297 zipfile.extractall(extract_path)
298 return extract_path + "/metadata.yaml"
299 else:
300 return charm_path + "/metadata.yaml"
301
302 def find_charm_name(self, db_nsr: dict, charm_folder_name: str) -> str:
303 """Get the charm name from metadata.yaml of charm package.
304
305 Args:
306 db_nsr (dict): NS record as a dictionary
307 charm_folder_name (str): charm folder name
308
309 Returns:
310 charm_name (str): charm name
311 """
312 try:
313 if not charm_folder_name:
314 raise LcmException("charm_folder_name should be provided.")
315
316 # Find nsd_package details: path, name
317 revision = db_nsr.get("revision", "")
318 nsd_package_path = (
319 db_nsr["nsd-id"] + ":" + str(revision) if revision else db_nsr["nsd-id"]
320 )
321 nsd_package_name = os.listdir(self.fs.path + nsd_package_path)[0]
322
323 # Remove the existing nsd package and sync from FsMongo
324 shutil.rmtree(self.fs.path + nsd_package_path, ignore_errors=True)
325 self.fs.sync(from_path=nsd_package_path)
326
327 # Get the charm path
328 charm_path = self._get_charm_path(
329 nsd_package_path, nsd_package_name, charm_folder_name
330 )
331
332 # Find charm metadata file full path
333 charm_metadata_file = self._get_charm_metadata_file(
334 charm_folder_name, nsd_package_path, nsd_package_name, charm_path
335 )
336
337 # Return charm name
338 return self.get_charm_name(charm_metadata_file)
339
340 except (
341 yaml.YAMLError,
342 IOError,
343 FsException,
344 KeyError,
345 TypeError,
346 FileNotFoundError,
347 BadZipfile,
348 ) as error:
349 self.logger.debug(traceback.format_exc())
350 self.logger.error(f"{error} occured while getting the charm name")
351 raise LcmException(error)
352
353
354 class TaskRegistry(LcmBase):
355 """
356 Implements a registry of task needed for later cancelation, look for related tasks that must be completed before
357 etc. It stores a four level dict
358 First level is the topic, ns, vim_account, sdn
359 Second level is the _id
360 Third level is the operation id
361 Fourth level is a descriptive name, the value is the task class
362
363 The HA (High-Availability) methods are used when more than one LCM instance is running.
364 To register the current task in the external DB, use LcmBase as base class, to be able
365 to reuse LcmBase.update_db_2()
366 The DB registry uses the following fields to distinguish a task:
367 - op_type: operation type ("nslcmops" or "nsilcmops")
368 - op_id: operation ID
369 - worker: the worker ID for this process
370 """
371
372 # NS/NSI: "services" VIM/WIM/SDN: "accounts"
373 topic_service_list = ["ns", "nsi"]
374 topic_account_list = ["vim", "wim", "sdn", "k8scluster", "vca", "k8srepo"]
375
376 # Map topic to InstanceID
377 topic2instid_dict = {"ns": "nsInstanceId", "nsi": "netsliceInstanceId"}
378
379 # Map topic to DB table name
380 topic2dbtable_dict = {
381 "ns": "nslcmops",
382 "nsi": "nsilcmops",
383 "vim": "vim_accounts",
384 "wim": "wim_accounts",
385 "sdn": "sdns",
386 "k8scluster": "k8sclusters",
387 "vca": "vca",
388 "k8srepo": "k8srepos",
389 }
390
391 def __init__(self, worker_id=None, logger=None):
392 self.task_registry = {
393 "ns": {},
394 "nsi": {},
395 "vim_account": {},
396 "wim_account": {},
397 "sdn": {},
398 "k8scluster": {},
399 "vca": {},
400 "k8srepo": {},
401 }
402 self.worker_id = worker_id
403 self.db = Database().instance.db
404 self.logger = logger
405
406 def register(self, topic, _id, op_id, task_name, task):
407 """
408 Register a new task
409 :param topic: Can be "ns", "nsi", "vim_account", "sdn"
410 :param _id: _id of the related item
411 :param op_id: id of the operation of the related item
412 :param task_name: Task descriptive name, as create, instantiate, terminate. Must be unique in this op_id
413 :param task: Task class
414 :return: none
415 """
416 if _id not in self.task_registry[topic]:
417 self.task_registry[topic][_id] = OrderedDict()
418 if op_id not in self.task_registry[topic][_id]:
419 self.task_registry[topic][_id][op_id] = {task_name: task}
420 else:
421 self.task_registry[topic][_id][op_id][task_name] = task
422 # print("registering task", topic, _id, op_id, task_name, task)
423
424 def remove(self, topic, _id, op_id, task_name=None):
425 """
426 When task is ended, it should be removed. It ignores missing tasks. It also removes tasks done with this _id
427 :param topic: Can be "ns", "nsi", "vim_account", "sdn"
428 :param _id: _id of the related item
429 :param op_id: id of the operation of the related item
430 :param task_name: Task descriptive name. If none it deletes all tasks with same _id and op_id
431 :return: None
432 """
433 if not self.task_registry[topic].get(_id):
434 return
435 if not task_name:
436 self.task_registry[topic][_id].pop(op_id, None)
437 elif self.task_registry[topic][_id].get(op_id):
438 self.task_registry[topic][_id][op_id].pop(task_name, None)
439
440 # delete done tasks
441 for op_id_ in list(self.task_registry[topic][_id]):
442 for name, task in self.task_registry[topic][_id][op_id_].items():
443 if not task.done():
444 break
445 else:
446 del self.task_registry[topic][_id][op_id_]
447 if not self.task_registry[topic][_id]:
448 del self.task_registry[topic][_id]
449
450 def lookfor_related(self, topic, _id, my_op_id=None):
451 task_list = []
452 task_name_list = []
453 if _id not in self.task_registry[topic]:
454 return "", task_name_list
455 for op_id in reversed(self.task_registry[topic][_id]):
456 if my_op_id:
457 if my_op_id == op_id:
458 my_op_id = None # so that the next task is taken
459 continue
460
461 for task_name, task in self.task_registry[topic][_id][op_id].items():
462 if not task.done():
463 task_list.append(task)
464 task_name_list.append(task_name)
465 break
466 return ", ".join(task_name_list), task_list
467
468 def cancel(self, topic, _id, target_op_id=None, target_task_name=None):
469 """
470 Cancel all active tasks of a concrete ns, nsi, vim_account, sdn identified for _id. If op_id is supplied only
471 this is cancelled, and the same with task_name
472 """
473 if not self.task_registry[topic].get(_id):
474 return
475 for op_id in reversed(self.task_registry[topic][_id]):
476 if target_op_id and target_op_id != op_id:
477 continue
478 for task_name, task in self.task_registry[topic][_id][op_id].items():
479 if target_task_name and target_task_name != task_name:
480 continue
481 # result =
482 task.cancel()
483 # if result:
484 # self.logger.debug("{} _id={} order_id={} task={} cancelled".format(topic, _id, op_id, task_name))
485
486 # Is topic NS/NSI?
487 def _is_service_type_HA(self, topic):
488 return topic in self.topic_service_list
489
490 # Is topic VIM/WIM/SDN?
491 def _is_account_type_HA(self, topic):
492 return topic in self.topic_account_list
493
494 # Input: op_id, example: 'abc123def:3' Output: account_id='abc123def', op_index=3
495 def _get_account_and_op_HA(self, op_id):
496 if not op_id:
497 return None, None
498 account_id, _, op_index = op_id.rpartition(":")
499 if not account_id or not op_index.isdigit():
500 return None, None
501 return account_id, op_index
502
503 # Get '_id' for any topic and operation
504 def _get_instance_id_HA(self, topic, op_type, op_id):
505 _id = None
506 # Special operation 'ANY', for SDN account associated to a VIM account: op_id as '_id'
507 if op_type == "ANY":
508 _id = op_id
509 # NS/NSI: Use op_id as '_id'
510 elif self._is_service_type_HA(topic):
511 _id = op_id
512 # VIM/SDN/WIM/K8SCLUSTER: Split op_id to get Account ID and Operation Index, use Account ID as '_id'
513 elif self._is_account_type_HA(topic):
514 _id, _ = self._get_account_and_op_HA(op_id)
515 return _id
516
517 # Set DB _filter for querying any related process state
518 def _get_waitfor_filter_HA(self, db_lcmop, topic, op_type, op_id):
519 _filter = {}
520 # Special operation 'ANY', for SDN account associated to a VIM account: op_id as '_id'
521 # In this special case, the timestamp is ignored
522 if op_type == "ANY":
523 _filter = {"operationState": "PROCESSING"}
524 # Otherwise, get 'startTime' timestamp for this operation
525 else:
526 # NS/NSI
527 if self._is_service_type_HA(topic):
528 now = time()
529 starttime_this_op = db_lcmop.get("startTime")
530 instance_id_label = self.topic2instid_dict.get(topic)
531 instance_id = db_lcmop.get(instance_id_label)
532 _filter = {
533 instance_id_label: instance_id,
534 "operationState": "PROCESSING",
535 "startTime.lt": starttime_this_op,
536 "_admin.modified.gt": now
537 - 2 * 3600, # ignore if tow hours of inactivity
538 }
539 # VIM/WIM/SDN/K8scluster
540 elif self._is_account_type_HA(topic):
541 _, op_index = self._get_account_and_op_HA(op_id)
542 _ops = db_lcmop["_admin"]["operations"]
543 _this_op = _ops[int(op_index)]
544 starttime_this_op = _this_op.get("startTime", None)
545 _filter = {
546 "operationState": "PROCESSING",
547 "startTime.lt": starttime_this_op,
548 }
549 return _filter
550
551 # Get DB params for any topic and operation
552 def _get_dbparams_for_lock_HA(self, topic, op_type, op_id):
553 q_filter = {}
554 update_dict = {}
555 # NS/NSI
556 if self._is_service_type_HA(topic):
557 q_filter = {"_id": op_id, "_admin.worker": None}
558 update_dict = {"_admin.worker": self.worker_id}
559 # VIM/WIM/SDN
560 elif self._is_account_type_HA(topic):
561 account_id, op_index = self._get_account_and_op_HA(op_id)
562 if not account_id:
563 return None, None
564 if op_type == "create":
565 # Creating a VIM/WIM/SDN account implies setting '_admin.current_operation' = 0
566 op_index = 0
567 q_filter = {
568 "_id": account_id,
569 "_admin.operations.{}.worker".format(op_index): None,
570 }
571 update_dict = {
572 "_admin.operations.{}.worker".format(op_index): self.worker_id,
573 "_admin.current_operation": op_index,
574 }
575 return q_filter, update_dict
576
577 def lock_HA(self, topic, op_type, op_id):
578 """
579 Lock a task, if possible, to indicate to the HA system that
580 the task will be executed in this LCM instance.
581 :param topic: Can be "ns", "nsi", "vim", "wim", or "sdn"
582 :param op_type: Operation type, can be "nslcmops", "nsilcmops", "create", "edit", "delete"
583 :param op_id: NS, NSI: Operation ID VIM,WIM,SDN: Account ID + ':' + Operation Index
584 :return:
585 True=lock was successful => execute the task (not registered by any other LCM instance)
586 False=lock failed => do NOT execute the task (already registered by another LCM instance)
587
588 HA tasks and backward compatibility:
589 If topic is "account type" (VIM/WIM/SDN) and op_id is None, 'op_id' was not provided by NBI.
590 This means that the running NBI instance does not support HA.
591 In such a case this method should always return True, to always execute
592 the task in this instance of LCM, without querying the DB.
593 """
594
595 # Backward compatibility for VIM/WIM/SDN/k8scluster without op_id
596 if self._is_account_type_HA(topic) and op_id is None:
597 return True
598
599 # Try to lock this task
600 db_table_name = self.topic2dbtable_dict[topic]
601 q_filter, update_dict = self._get_dbparams_for_lock_HA(topic, op_type, op_id)
602 db_lock_task = self.db.set_one(
603 db_table_name,
604 q_filter=q_filter,
605 update_dict=update_dict,
606 fail_on_empty=False,
607 )
608 if db_lock_task is None:
609 self.logger.debug(
610 "Task {} operation={} already locked by another worker".format(
611 topic, op_id
612 )
613 )
614 return False
615 else:
616 # Set 'detailed-status' to 'In progress' for VIM/WIM/SDN operations
617 if self._is_account_type_HA(topic):
618 detailed_status = "In progress"
619 account_id, op_index = self._get_account_and_op_HA(op_id)
620 q_filter = {"_id": account_id}
621 update_dict = {
622 "_admin.operations.{}.detailed-status".format(
623 op_index
624 ): detailed_status
625 }
626 self.db.set_one(
627 db_table_name,
628 q_filter=q_filter,
629 update_dict=update_dict,
630 fail_on_empty=False,
631 )
632 return True
633
634 def unlock_HA(self, topic, op_type, op_id, operationState, detailed_status):
635 """
636 Register a task, done when finished a VIM/WIM/SDN 'create' operation.
637 :param topic: Can be "vim", "wim", or "sdn"
638 :param op_type: Operation type, can be "create", "edit", "delete"
639 :param op_id: Account ID + ':' + Operation Index
640 :return: nothing
641 """
642
643 # Backward compatibility
644 if not self._is_account_type_HA(topic) or not op_id:
645 return
646
647 # Get Account ID and Operation Index
648 account_id, op_index = self._get_account_and_op_HA(op_id)
649 db_table_name = self.topic2dbtable_dict[topic]
650
651 # If this is a 'delete' operation, the account may have been deleted (SUCCESS) or may still exist (FAILED)
652 # If the account exist, register the HA task.
653 # Update DB for HA tasks
654 q_filter = {"_id": account_id}
655 update_dict = {
656 "_admin.operations.{}.operationState".format(op_index): operationState,
657 "_admin.operations.{}.detailed-status".format(op_index): detailed_status,
658 "_admin.operations.{}.worker".format(op_index): None,
659 "_admin.current_operation": None,
660 }
661 self.db.set_one(
662 db_table_name,
663 q_filter=q_filter,
664 update_dict=update_dict,
665 fail_on_empty=False,
666 )
667 return
668
669 async def waitfor_related_HA(self, topic, op_type, op_id=None):
670 """
671 Wait for any pending related HA tasks
672 """
673
674 # Backward compatibility
675 if not (
676 self._is_service_type_HA(topic) or self._is_account_type_HA(topic)
677 ) and (op_id is None):
678 return
679
680 # Get DB table name
681 db_table_name = self.topic2dbtable_dict.get(topic)
682
683 # Get instance ID
684 _id = self._get_instance_id_HA(topic, op_type, op_id)
685 _filter = {"_id": _id}
686 db_lcmop = self.db.get_one(db_table_name, _filter, fail_on_empty=False)
687 if not db_lcmop:
688 return
689
690 # Set DB _filter for querying any related process state
691 _filter = self._get_waitfor_filter_HA(db_lcmop, topic, op_type, op_id)
692
693 # For HA, get list of tasks from DB instead of from dictionary (in-memory) variable.
694 timeout_wait_for_task = (
695 3600 # Max time (seconds) to wait for a related task to finish
696 )
697 # interval_wait_for_task = 30 # A too long polling interval slows things down considerably
698 interval_wait_for_task = 10 # Interval in seconds for polling related tasks
699 time_left = timeout_wait_for_task
700 old_num_related_tasks = 0
701 while True:
702 # Get related tasks (operations within the same instance as this) which are
703 # still running (operationState='PROCESSING') and which were started before this task.
704 # In the case of op_type='ANY', get any related tasks with operationState='PROCESSING', ignore timestamps.
705 db_waitfor_related_task = self.db.get_list(db_table_name, q_filter=_filter)
706 new_num_related_tasks = len(db_waitfor_related_task)
707 # If there are no related tasks, there is nothing to wait for, so return.
708 if not new_num_related_tasks:
709 return
710 # If number of pending related tasks have changed,
711 # update the 'detailed-status' field and log the change.
712 # Do NOT update the 'detailed-status' for SDNC-associated-to-VIM operations ('ANY').
713 if (op_type != "ANY") and (new_num_related_tasks != old_num_related_tasks):
714 step = "Waiting for {} related tasks to be completed.".format(
715 new_num_related_tasks
716 )
717 update_dict = {}
718 q_filter = {"_id": _id}
719 # NS/NSI
720 if self._is_service_type_HA(topic):
721 update_dict = {
722 "detailed-status": step,
723 "queuePosition": new_num_related_tasks,
724 }
725 # VIM/WIM/SDN
726 elif self._is_account_type_HA(topic):
727 _, op_index = self._get_account_and_op_HA(op_id)
728 update_dict = {
729 "_admin.operations.{}.detailed-status".format(op_index): step
730 }
731 self.logger.debug("Task {} operation={} {}".format(topic, _id, step))
732 self.db.set_one(
733 db_table_name,
734 q_filter=q_filter,
735 update_dict=update_dict,
736 fail_on_empty=False,
737 )
738 old_num_related_tasks = new_num_related_tasks
739 time_left -= interval_wait_for_task
740 if time_left < 0:
741 raise LcmException(
742 "Timeout ({}) when waiting for related tasks to be completed".format(
743 timeout_wait_for_task
744 )
745 )
746 await asyncio.sleep(interval_wait_for_task)
747
748 return