blob: 5f34280ad7c1d27b26353cf8fb652adf57b11091 [file] [log] [blame]
tiernoc0e42e22018-05-11 11:36:10 +02001#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3
tierno2e215512018-11-28 09:37:52 +00004##
5# Copyright 2018 Telefonica S.A.
6#
7# Licensed under the Apache License, Version 2.0 (the "License"); you may
8# not use this file except in compliance with the License. You may obtain
9# a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16# License for the specific language governing permissions and limitations
17# under the License.
18##
19
quilesj7e13aeb2019-10-08 13:34:55 +020020
21# DEBUG WITH PDB
22import os
23import pdb
24
tiernoc0e42e22018-05-11 11:36:10 +020025import asyncio
26import yaml
tierno275411e2018-05-16 14:33:32 +020027import logging
28import logging.handlers
29import getopt
tierno275411e2018-05-16 14:33:32 +020030import sys
tierno59d22d22018-09-25 18:10:19 +020031
Patricia Reinoso15ce47b2022-10-26 08:58:39 +000032from osm_lcm import ns, paas, vim_sdn, netslice
tierno69f0d382020-05-07 13:08:09 +000033from osm_lcm.ng_ro import NgRoException, NgRoClient
34from osm_lcm.ROclient import ROClient, ROClientException
quilesj7e13aeb2019-10-08 13:34:55 +020035
tierno94f06112020-02-11 12:38:19 +000036from time import time
Gulsum Aticie7e0b752022-09-30 14:31:26 +030037from osm_lcm.lcm_utils import (
38 get_paas_id_by_nsr_id,
39 get_paas_type_by_paas_id,
40 LcmException,
41 LcmExceptionExit,
42 TaskRegistry,
43 versiontuple,
44)
tiernoa4dea5a2020-01-05 16:29:30 +000045from osm_lcm import version as lcm_version, version_date as lcm_version_date
tierno8069ce52019-08-28 15:34:33 +000046
bravof922c4172020-11-24 21:21:43 -030047from osm_common import msglocal, msgkafka
tierno98768132018-09-11 12:07:21 +020048from osm_common import version as common_version
tierno59d22d22018-09-25 18:10:19 +020049from osm_common.dbbase import DbException
tiernoc0e42e22018-05-11 11:36:10 +020050from osm_common.fsbase import FsException
51from osm_common.msgbase import MsgException
bravof922c4172020-11-24 21:21:43 -030052from osm_lcm.data_utils.database.database import Database
53from osm_lcm.data_utils.filesystem.filesystem import Filesystem
aticig56b86c22022-06-29 10:43:05 +030054from osm_lcm.lcm_hc import get_health_check_file
Gulsum Aticie7e0b752022-09-30 14:31:26 +030055from osm_lcm.paas_service import paas_service_factory
tierno275411e2018-05-16 14:33:32 +020056from os import environ, path
tierno16427352019-04-22 11:37:36 +000057from random import choice as random_choice
tierno59d22d22018-09-25 18:10:19 +020058from n2vc import version as n2vc_version
bravof922c4172020-11-24 21:21:43 -030059import traceback
tiernoc0e42e22018-05-11 11:36:10 +020060
garciadeblas5697b8b2021-03-24 09:17:02 +010061if os.getenv("OSMLCM_PDB_DEBUG", None) is not None:
quilesj7e13aeb2019-10-08 13:34:55 +020062 pdb.set_trace()
63
tiernoc0e42e22018-05-11 11:36:10 +020064
tierno275411e2018-05-16 14:33:32 +020065__author__ = "Alfonso Tierno"
tiernoe64f7fb2019-09-11 08:55:52 +000066min_RO_version = "6.0.2"
tierno6e9d2eb2018-09-12 17:47:18 +020067min_n2vc_version = "0.0.2"
quilesj7e13aeb2019-10-08 13:34:55 +020068
tierno16427352019-04-22 11:37:36 +000069min_common_version = "0.1.19"
tierno275411e2018-05-16 14:33:32 +020070
71
tiernoc0e42e22018-05-11 11:36:10 +020072class Lcm:
73
garciadeblas5697b8b2021-03-24 09:17:02 +010074 ping_interval_pace = (
75 120 # how many time ping is send once is confirmed all is running
76 )
77 ping_interval_boot = 5 # how many time ping is sent when booting
78 cfg_logger_name = {
79 "message": "lcm.msg",
80 "database": "lcm.db",
81 "storage": "lcm.fs",
82 "tsdb": "lcm.prometheus",
83 }
tierno991e95d2020-07-21 12:41:25 +000084 # ^ contains for each section at lcm.cfg the used logger name
tiernoa9843d82018-10-24 10:44:20 +020085
tierno59d22d22018-09-25 18:10:19 +020086 def __init__(self, config_file, loop=None):
tiernoc0e42e22018-05-11 11:36:10 +020087 """
88 Init, Connect to database, filesystem storage, and messaging
Gulsum Aticie7e0b752022-09-30 14:31:26 +030089 :param config_file: two level dictionary with configuration. Top level should contain 'database', 'storage',
tiernoc0e42e22018-05-11 11:36:10 +020090 :return: None
91 """
tiernoc0e42e22018-05-11 11:36:10 +020092 self.db = None
93 self.msg = None
tierno16427352019-04-22 11:37:36 +000094 self.msg_admin = None
tiernoc0e42e22018-05-11 11:36:10 +020095 self.fs = None
96 self.pings_not_received = 1
tiernoc2564fe2019-01-28 16:18:56 +000097 self.consecutive_errors = 0
98 self.first_start = False
tiernoc0e42e22018-05-11 11:36:10 +020099
tiernoc0e42e22018-05-11 11:36:10 +0200100 # logging
garciadeblas5697b8b2021-03-24 09:17:02 +0100101 self.logger = logging.getLogger("lcm")
tierno16427352019-04-22 11:37:36 +0000102 # get id
103 self.worker_id = self.get_process_id()
tiernoc0e42e22018-05-11 11:36:10 +0200104 # load configuration
105 config = self.read_config_file(config_file)
106 self.config = config
aticig56b86c22022-06-29 10:43:05 +0300107 self.health_check_file = get_health_check_file(self.config)
tierno744303e2020-01-13 16:46:31 +0000108 self.config["ro_config"] = {
tierno69f0d382020-05-07 13:08:09 +0000109 "ng": config["RO"].get("ng", False),
110 "uri": config["RO"].get("uri"),
tierno750b2452018-05-17 16:39:29 +0200111 "tenant": config.get("tenant", "osm"),
tierno69f0d382020-05-07 13:08:09 +0000112 "logger_name": "lcm.roclient",
113 "loglevel": config["RO"].get("loglevel", "ERROR"),
tiernoc0e42e22018-05-11 11:36:10 +0200114 }
tierno69f0d382020-05-07 13:08:09 +0000115 if not self.config["ro_config"]["uri"]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100116 self.config["ro_config"]["uri"] = "http://{}:{}/".format(
117 config["RO"]["host"], config["RO"]["port"]
118 )
119 elif (
120 "/ro" in self.config["ro_config"]["uri"][-4:]
121 or "/openmano" in self.config["ro_config"]["uri"][-10:]
122 ):
tierno2357f4e2020-10-19 16:38:59 +0000123 # uri ends with '/ro', '/ro/', '/openmano', '/openmano/'
124 index = self.config["ro_config"]["uri"][-1].rfind("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100125 self.config["ro_config"]["uri"] = self.config["ro_config"]["uri"][index + 1]
tiernoc0e42e22018-05-11 11:36:10 +0200126
tierno59d22d22018-09-25 18:10:19 +0200127 self.loop = loop or asyncio.get_event_loop()
garciadeblas5697b8b2021-03-24 09:17:02 +0100128 self.ns = (
129 self.netslice
130 ) = (
131 self.vim
Patricia Reinoso15ce47b2022-10-26 08:58:39 +0000132 ) = (
133 self.wim
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300134 ) = (
135 self.sdn
136 ) = (
137 self.k8scluster
138 ) = (
139 self.vca
140 ) = self.k8srepo = self.paas = self.paas_service = self.juju_paas = None
tiernoc0e42e22018-05-11 11:36:10 +0200141 # logging
garciadeblas5697b8b2021-03-24 09:17:02 +0100142 log_format_simple = (
143 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
144 )
145 log_formatter_simple = logging.Formatter(
146 log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S"
147 )
tiernoc0e42e22018-05-11 11:36:10 +0200148 config["database"]["logger_name"] = "lcm.db"
149 config["storage"]["logger_name"] = "lcm.fs"
150 config["message"]["logger_name"] = "lcm.msg"
tierno86aa62f2018-08-20 11:57:04 +0000151 if config["global"].get("logfile"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100152 file_handler = logging.handlers.RotatingFileHandler(
153 config["global"]["logfile"], maxBytes=100e6, backupCount=9, delay=0
154 )
tiernoc0e42e22018-05-11 11:36:10 +0200155 file_handler.setFormatter(log_formatter_simple)
156 self.logger.addHandler(file_handler)
tierno86aa62f2018-08-20 11:57:04 +0000157 if not config["global"].get("nologging"):
tiernoc0e42e22018-05-11 11:36:10 +0200158 str_handler = logging.StreamHandler()
159 str_handler.setFormatter(log_formatter_simple)
160 self.logger.addHandler(str_handler)
161
162 if config["global"].get("loglevel"):
163 self.logger.setLevel(config["global"]["loglevel"])
164
165 # logging other modules
tierno991e95d2020-07-21 12:41:25 +0000166 for k1, logname in self.cfg_logger_name.items():
tiernoc0e42e22018-05-11 11:36:10 +0200167 config[k1]["logger_name"] = logname
168 logger_module = logging.getLogger(logname)
tierno86aa62f2018-08-20 11:57:04 +0000169 if config[k1].get("logfile"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100170 file_handler = logging.handlers.RotatingFileHandler(
171 config[k1]["logfile"], maxBytes=100e6, backupCount=9, delay=0
172 )
tiernoc0e42e22018-05-11 11:36:10 +0200173 file_handler.setFormatter(log_formatter_simple)
174 logger_module.addHandler(file_handler)
tierno86aa62f2018-08-20 11:57:04 +0000175 if config[k1].get("loglevel"):
tiernoc0e42e22018-05-11 11:36:10 +0200176 logger_module.setLevel(config[k1]["loglevel"])
garciadeblas5697b8b2021-03-24 09:17:02 +0100177 self.logger.critical(
178 "starting osm/lcm version {} {}".format(lcm_version, lcm_version_date)
179 )
tierno59d22d22018-09-25 18:10:19 +0200180
tiernoc0e42e22018-05-11 11:36:10 +0200181 # check version of N2VC
182 # TODO enhance with int conversion or from distutils.version import LooseVersion
183 # or with list(map(int, version.split(".")))
tierno59d22d22018-09-25 18:10:19 +0200184 if versiontuple(n2vc_version) < versiontuple(min_n2vc_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100185 raise LcmException(
186 "Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
187 n2vc_version, min_n2vc_version
188 )
189 )
tierno59d22d22018-09-25 18:10:19 +0200190 # check version of common
tierno27246d82018-09-27 15:59:09 +0200191 if versiontuple(common_version) < versiontuple(min_common_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100192 raise LcmException(
193 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
194 common_version, min_common_version
195 )
196 )
tierno22f4f9c2018-06-11 18:53:39 +0200197
tiernoc0e42e22018-05-11 11:36:10 +0200198 try:
bravof922c4172020-11-24 21:21:43 -0300199 self.db = Database(config).instance.db
tiernoc0e42e22018-05-11 11:36:10 +0200200
bravof922c4172020-11-24 21:21:43 -0300201 self.fs = Filesystem(config).instance.fs
sousaedu40365e82021-07-26 15:24:21 +0200202 self.fs.sync()
tiernoc0e42e22018-05-11 11:36:10 +0200203
quilesj7e13aeb2019-10-08 13:34:55 +0200204 # copy message configuration in order to remove 'group_id' for msg_admin
tiernoc2564fe2019-01-28 16:18:56 +0000205 config_message = config["message"].copy()
206 config_message["loop"] = self.loop
207 if config_message["driver"] == "local":
tiernoc0e42e22018-05-11 11:36:10 +0200208 self.msg = msglocal.MsgLocal()
tiernoc2564fe2019-01-28 16:18:56 +0000209 self.msg.connect(config_message)
tierno16427352019-04-22 11:37:36 +0000210 self.msg_admin = msglocal.MsgLocal()
211 config_message.pop("group_id", None)
212 self.msg_admin.connect(config_message)
tiernoc2564fe2019-01-28 16:18:56 +0000213 elif config_message["driver"] == "kafka":
tiernoc0e42e22018-05-11 11:36:10 +0200214 self.msg = msgkafka.MsgKafka()
tiernoc2564fe2019-01-28 16:18:56 +0000215 self.msg.connect(config_message)
tierno16427352019-04-22 11:37:36 +0000216 self.msg_admin = msgkafka.MsgKafka()
217 config_message.pop("group_id", None)
218 self.msg_admin.connect(config_message)
tiernoc0e42e22018-05-11 11:36:10 +0200219 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100220 raise LcmException(
221 "Invalid configuration param '{}' at '[message]':'driver'".format(
222 config["message"]["driver"]
223 )
224 )
tiernoc0e42e22018-05-11 11:36:10 +0200225 except (DbException, FsException, MsgException) as e:
226 self.logger.critical(str(e), exc_info=True)
227 raise LcmException(str(e))
228
kuused124bfe2019-06-18 12:09:24 +0200229 # contains created tasks/futures to be able to cancel
bravof922c4172020-11-24 21:21:43 -0300230 self.lcm_tasks = TaskRegistry(self.worker_id, self.logger)
kuused124bfe2019-06-18 12:09:24 +0200231
tierno22f4f9c2018-06-11 18:53:39 +0200232 async def check_RO_version(self):
tiernoe64f7fb2019-09-11 08:55:52 +0000233 tries = 14
234 last_error = None
235 while True:
tierno2357f4e2020-10-19 16:38:59 +0000236 ro_uri = self.config["ro_config"]["uri"]
tiernoe64f7fb2019-09-11 08:55:52 +0000237 try:
tierno2357f4e2020-10-19 16:38:59 +0000238 # try new RO, if fail old RO
239 try:
240 self.config["ro_config"]["uri"] = ro_uri + "ro"
tierno69f0d382020-05-07 13:08:09 +0000241 ro_server = NgRoClient(self.loop, **self.config["ro_config"])
tierno2357f4e2020-10-19 16:38:59 +0000242 ro_version = await ro_server.get_version()
243 self.config["ro_config"]["ng"] = True
244 except Exception:
245 self.config["ro_config"]["uri"] = ro_uri + "openmano"
tierno69f0d382020-05-07 13:08:09 +0000246 ro_server = ROClient(self.loop, **self.config["ro_config"])
tierno2357f4e2020-10-19 16:38:59 +0000247 ro_version = await ro_server.get_version()
248 self.config["ro_config"]["ng"] = False
tiernoe64f7fb2019-09-11 08:55:52 +0000249 if versiontuple(ro_version) < versiontuple(min_RO_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100250 raise LcmException(
251 "Not compatible osm/RO version '{}'. Needed '{}' or higher".format(
252 ro_version, min_RO_version
253 )
254 )
255 self.logger.info(
256 "Connected to RO version {} new-generation version {}".format(
257 ro_version, self.config["ro_config"]["ng"]
258 )
259 )
tiernoe64f7fb2019-09-11 08:55:52 +0000260 return
tierno69f0d382020-05-07 13:08:09 +0000261 except (ROClientException, NgRoException) as e:
tierno2357f4e2020-10-19 16:38:59 +0000262 self.config["ro_config"]["uri"] = ro_uri
tiernoe64f7fb2019-09-11 08:55:52 +0000263 tries -= 1
bravof922c4172020-11-24 21:21:43 -0300264 traceback.print_tb(e.__traceback__)
garciadeblas5697b8b2021-03-24 09:17:02 +0100265 error_text = "Error while connecting to RO on {}: {}".format(
266 self.config["ro_config"]["uri"], e
267 )
tiernoe64f7fb2019-09-11 08:55:52 +0000268 if tries <= 0:
269 self.logger.critical(error_text)
270 raise LcmException(error_text)
271 if last_error != error_text:
272 last_error = error_text
garciadeblas5697b8b2021-03-24 09:17:02 +0100273 self.logger.error(
274 error_text + ". Waiting until {} seconds".format(5 * tries)
275 )
tiernoe64f7fb2019-09-11 08:55:52 +0000276 await asyncio.sleep(5)
tierno22f4f9c2018-06-11 18:53:39 +0200277
tiernoc0e42e22018-05-11 11:36:10 +0200278 async def test(self, param=None):
279 self.logger.debug("Starting/Ending test task: {}".format(param))
280
tiernoc0e42e22018-05-11 11:36:10 +0200281 async def kafka_ping(self):
282 self.logger.debug("Task kafka_ping Enter")
283 consecutive_errors = 0
284 first_start = True
285 kafka_has_received = False
286 self.pings_not_received = 1
287 while True:
288 try:
tierno16427352019-04-22 11:37:36 +0000289 await self.msg_admin.aiowrite(
garciadeblas5697b8b2021-03-24 09:17:02 +0100290 "admin",
291 "ping",
292 {
293 "from": "lcm",
294 "to": "lcm",
295 "worker_id": self.worker_id,
296 "version": lcm_version,
297 },
298 self.loop,
299 )
tiernoc0e42e22018-05-11 11:36:10 +0200300 # time between pings are low when it is not received and at starting
garciadeblas5697b8b2021-03-24 09:17:02 +0100301 wait_time = (
302 self.ping_interval_boot
303 if not kafka_has_received
304 else self.ping_interval_pace
305 )
tiernoc0e42e22018-05-11 11:36:10 +0200306 if not self.pings_not_received:
307 kafka_has_received = True
308 self.pings_not_received += 1
309 await asyncio.sleep(wait_time, loop=self.loop)
310 if self.pings_not_received > 10:
311 raise LcmException("It is not receiving pings from Kafka bus")
312 consecutive_errors = 0
313 first_start = False
314 except LcmException:
315 raise
316 except Exception as e:
317 # if not first_start is the first time after starting. So leave more time and wait
318 # to allow kafka starts
319 if consecutive_errors == 8 if not first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100320 self.logger.error(
321 "Task kafka_read task exit error too many errors. Exception: {}".format(
322 e
323 )
324 )
tiernoc0e42e22018-05-11 11:36:10 +0200325 raise
326 consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100327 self.logger.error(
328 "Task kafka_read retrying after Exception {}".format(e)
329 )
tierno16427352019-04-22 11:37:36 +0000330 wait_time = 2 if not first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200331 await asyncio.sleep(wait_time, loop=self.loop)
332
Patricia Reinoso15ce47b2022-10-26 08:58:39 +0000333 def _kafka_read_paas(self, command, params, order_id):
334 paas_id = params.get("_id")
335
336 if command == "created":
337 task = asyncio.ensure_future(self.paas.create(params, order_id))
338 self.lcm_tasks.register("paas", paas_id, order_id, "paas_create", task)
339 elif command == "edited":
340 task = asyncio.ensure_future(self.paas.edit(params, order_id))
341 self.lcm_tasks.register("paas", paas_id, order_id, "paas_edit", task)
342 elif command == "delete":
343 task = asyncio.ensure_future(self.paas.delete(params, order_id))
344 self.lcm_tasks.register("paas", paas_id, order_id, "paas_delete", task)
345 elif command == "deleted":
346 self.logger.debug("PaaS {} already deleted from DB".format(paas_id))
347 else:
348 self.logger.error("Invalid command {} for PaaS topic".format(command))
349
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300350 def _kafka_read_ns_instantiate(self, params: dict) -> None:
351 """Operations to be performed if the topic is ns and command is instantiate.
352 Args:
353 params (dict): Dictionary including NS related parameters
354 """
355 nsr_id, nslcmop_id = params["nsInstanceId"], params["_id"]
356 paas_id = params["operationParams"].get("paasAccountId")
357
358 if paas_id:
359 paas_type = get_paas_type_by_paas_id(paas_id, self.db)
360 task = asyncio.ensure_future(
361 self.paas_service[paas_type].instantiate(nsr_id, nslcmop_id)
362 )
363 self.logger.debug(
364 "Deploying NS {} using PaaS account {}".format(nsr_id, paas_id)
365 )
366
367 else:
368 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
369 self.logger.debug("Deploying NS {}".format(nsr_id))
370
371 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
372
373 def _kafka_read_ns_terminate(self, params: dict, topic: str) -> None:
374 """Operations to be performed if the topic is ns and command is terminate.
375 Args:
376 params (dict): Dictionary including NS related parameters
377 topic (str): Name of Kafka topic
378 """
379 nsr_id, nslcmop_id = params["nsInstanceId"], params["_id"]
380 paas_id = get_paas_id_by_nsr_id(nsr_id, self.db)
381
382 if paas_id:
383 paas_type = get_paas_type_by_paas_id(paas_id, self.db)
384 task = asyncio.ensure_future(
385 self.paas_service[paas_type].terminate(nsr_id, nslcmop_id)
386 )
387 self.logger.debug(
388 "Terminating NS {} using PaaS account {}".format(nsr_id, paas_id)
389 )
390
391 else:
392 self.lcm_tasks.cancel(topic, nsr_id)
393 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
394 self.logger.debug("Terminating NS {}".format(nsr_id))
395
396 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
397
398 def _kafka_read_ns_action(self, params: dict) -> None:
399 """Operations to be performed if the topic is ns and command is action.
400 Args:
401 params (dict): Dictionary including NS related parameters
402 """
403 nsr_id, nslcmop_id = params["nsInstanceId"], params["_id"]
404 paas_id = get_paas_id_by_nsr_id(nsr_id, self.db)
405
406 if paas_id:
407 paas_type = get_paas_type_by_paas_id(paas_id, self.db)
408 task = asyncio.ensure_future(
409 self.paas_service[paas_type].action(nsr_id, nslcmop_id)
410 )
411 self.logger.debug(
412 "Running action on NS {} using PaaS account {}".format(nsr_id, paas_id)
413 )
414
415 else:
416 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
417 self.logger.debug("Running action on NS {}".format(nsr_id))
418
419 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
420
gcalvinoed7f6d42018-12-14 14:44:56 +0100421 def kafka_read_callback(self, topic, command, params):
422 order_id = 1
423
424 if topic != "admin" and command != "ping":
garciadeblas5697b8b2021-03-24 09:17:02 +0100425 self.logger.debug(
426 "Task kafka_read receives {} {}: {}".format(topic, command, params)
427 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100428 self.consecutive_errors = 0
429 self.first_start = False
430 order_id += 1
431 if command == "exit":
432 raise LcmExceptionExit
433 elif command.startswith("#"):
434 return
435 elif command == "echo":
436 # just for test
437 print(params)
438 sys.stdout.flush()
439 return
440 elif command == "test":
441 asyncio.Task(self.test(params), loop=self.loop)
442 return
443
444 if topic == "admin":
445 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
tierno16427352019-04-22 11:37:36 +0000446 if params.get("worker_id") != self.worker_id:
447 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100448 self.pings_not_received = 0
tierno3e359b12019-02-03 02:29:13 +0100449 try:
aticig56b86c22022-06-29 10:43:05 +0300450 with open(self.health_check_file, "w") as f:
tierno3e359b12019-02-03 02:29:13 +0100451 f.write(str(time()))
452 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100453 self.logger.error(
454 "Cannot write into '{}' for healthcheck: {}".format(
aticig56b86c22022-06-29 10:43:05 +0300455 self.health_check_file, e
garciadeblas5697b8b2021-03-24 09:17:02 +0100456 )
457 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100458 return
magnussonle9198bb2020-01-21 13:00:51 +0100459 elif topic == "pla":
460 if command == "placement":
461 self.ns.update_nsrs_with_pla_result(params)
462 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100463 elif topic == "k8scluster":
464 if command == "create" or command == "created":
465 k8scluster_id = params.get("_id")
466 task = asyncio.ensure_future(self.k8scluster.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100467 self.lcm_tasks.register(
468 "k8scluster", k8scluster_id, order_id, "k8scluster_create", task
469 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100470 return
471 elif command == "delete" or command == "deleted":
472 k8scluster_id = params.get("_id")
473 task = asyncio.ensure_future(self.k8scluster.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100474 self.lcm_tasks.register(
475 "k8scluster", k8scluster_id, order_id, "k8scluster_delete", task
476 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100477 return
David Garciac1fe90a2021-03-31 19:12:02 +0200478 elif topic == "vca":
479 if command == "create" or command == "created":
480 vca_id = params.get("_id")
481 task = asyncio.ensure_future(self.vca.create(params, order_id))
482 self.lcm_tasks.register("vca", vca_id, order_id, "vca_create", task)
483 return
484 elif command == "delete" or command == "deleted":
485 vca_id = params.get("_id")
486 task = asyncio.ensure_future(self.vca.delete(params, order_id))
487 self.lcm_tasks.register("vca", vca_id, order_id, "vca_delete", task)
488 return
Patricia Reinoso15ce47b2022-10-26 08:58:39 +0000489 elif topic == "paas":
490 self._kafka_read_paas(command, params, order_id)
491 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100492 elif topic == "k8srepo":
493 if command == "create" or command == "created":
494 k8srepo_id = params.get("_id")
495 self.logger.debug("k8srepo_id = {}".format(k8srepo_id))
496 task = asyncio.ensure_future(self.k8srepo.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100497 self.lcm_tasks.register(
498 "k8srepo", k8srepo_id, order_id, "k8srepo_create", task
499 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100500 return
501 elif command == "delete" or command == "deleted":
502 k8srepo_id = params.get("_id")
503 task = asyncio.ensure_future(self.k8srepo.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100504 self.lcm_tasks.register(
505 "k8srepo", k8srepo_id, order_id, "k8srepo_delete", task
506 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100507 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100508 elif topic == "ns":
tierno307425f2020-01-26 23:35:59 +0000509 if command == "instantiate":
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300510 self._kafka_read_ns_instantiate(params)
gcalvinoed7f6d42018-12-14 14:44:56 +0100511 return
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300512
tierno307425f2020-01-26 23:35:59 +0000513 elif command == "terminate":
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300514 self._kafka_read_ns_terminate(params, topic)
gcalvinoed7f6d42018-12-14 14:44:56 +0100515 return
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300516
ksaikiranr3fde2c72021-03-15 10:39:06 +0530517 elif command == "vca_status_refresh":
518 nslcmop = params
519 nslcmop_id = nslcmop["_id"]
520 nsr_id = nslcmop["nsInstanceId"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100521 task = asyncio.ensure_future(
522 self.ns.vca_status_refresh(nsr_id, nslcmop_id)
523 )
524 self.lcm_tasks.register(
525 "ns", nsr_id, nslcmop_id, "ns_vca_status_refresh", task
526 )
ksaikiranr3fde2c72021-03-15 10:39:06 +0530527 return
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300528
gcalvinoed7f6d42018-12-14 14:44:56 +0100529 elif command == "action":
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300530 self._kafka_read_ns_action(params)
gcalvinoed7f6d42018-12-14 14:44:56 +0100531 return
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300532
aticigdffa6212022-04-12 15:27:53 +0300533 elif command == "update":
534 # self.logger.debug("Update NS {}".format(nsr_id))
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300535 nsr_id, nslcmop_id = params["nsInstanceId"], params["_id"]
aticigdffa6212022-04-12 15:27:53 +0300536 task = asyncio.ensure_future(self.ns.update(nsr_id, nslcmop_id))
537 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_update", task)
538 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100539 elif command == "scale":
540 # self.logger.debug("Update NS {}".format(nsr_id))
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300541 nsr_id, nslcmop_id = params["nsInstanceId"], params["_id"]
gcalvinoed7f6d42018-12-14 14:44:56 +0100542 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
543 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
544 return
garciadeblas07f4e4c2022-06-09 09:42:58 +0200545 elif command == "heal":
546 # self.logger.debug("Healing NS {}".format(nsr_id))
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300547 nsr_id, nslcmop_id = params["nsInstanceId"], params["_id"]
garciadeblas07f4e4c2022-06-09 09:42:58 +0200548 task = asyncio.ensure_future(self.ns.heal(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000549 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_heal", task)
garciadeblas07f4e4c2022-06-09 09:42:58 +0200550 return
elumalai80bcf1c2022-04-28 18:05:01 +0530551 elif command == "migrate":
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300552 nsr_id, nslcmop_id = params["nsInstanceId"], params["_id"]
elumalai80bcf1c2022-04-28 18:05:01 +0530553 task = asyncio.ensure_future(self.ns.migrate(nsr_id, nslcmop_id))
554 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_migrate", task)
555 return
govindarajul4ff4b512022-05-02 20:02:41 +0530556 elif command == "verticalscale":
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300557 nsr_id, nslcmop_id = params["nsInstanceId"], params["_id"]
govindarajul4ff4b512022-05-02 20:02:41 +0530558 task = asyncio.ensure_future(self.ns.vertical_scale(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000559 self.logger.debug(
560 "nsr_id,nslcmop_id,task {},{},{}".format(nsr_id, nslcmop_id, task)
561 )
562 self.lcm_tasks.register(
563 "ns", nsr_id, nslcmop_id, "ns_verticalscale", task
564 )
565 self.logger.debug(
566 "LCM task registered {},{},{} ".format(nsr_id, nslcmop_id, task)
567 )
govindarajul4ff4b512022-05-02 20:02:41 +0530568 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100569 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000570 nsr_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100571 try:
572 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100573 print(
574 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
575 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
576 "".format(
577 nsr_id,
578 db_nsr["operational-status"],
579 db_nsr["config-status"],
580 db_nsr["detailed-status"],
581 db_nsr["_admin"]["deployed"],
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300582 self.lcm_tasks.task_registry["ns"][nsr_id],
garciadeblas5697b8b2021-03-24 09:17:02 +0100583 )
584 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100585 except Exception as e:
586 print("nsr {} not found: {}".format(nsr_id, e))
587 sys.stdout.flush()
588 return
589 elif command == "deleted":
590 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100591 elif command in (
elumalaica7ece02022-04-12 12:47:32 +0530592 "vnf_terminated",
elumalaib9e357c2022-04-27 09:58:38 +0530593 "policy_updated",
garciadeblas5697b8b2021-03-24 09:17:02 +0100594 "terminated",
595 "instantiated",
596 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200597 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100598 "actioned",
aticigdffa6212022-04-12 15:27:53 +0300599 "updated",
elumalai80bcf1c2022-04-28 18:05:01 +0530600 "migrated",
govindarajul4ff4b512022-05-02 20:02:41 +0530601 "verticalscaled",
garciadeblas5697b8b2021-03-24 09:17:02 +0100602 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100603 return
elumalaica7ece02022-04-12 12:47:32 +0530604
gcalvinoed7f6d42018-12-14 14:44:56 +0100605 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
tierno307425f2020-01-26 23:35:59 +0000606 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100607 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
608 nsilcmop = params
609 nsilcmop_id = nsilcmop["_id"] # slice operation id
610 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
garciadeblas5697b8b2021-03-24 09:17:02 +0100611 task = asyncio.ensure_future(
612 self.netslice.instantiate(nsir_id, nsilcmop_id)
613 )
614 self.lcm_tasks.register(
615 "nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task
616 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100617 return
tierno307425f2020-01-26 23:35:59 +0000618 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100619 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
620 nsilcmop = params
621 nsilcmop_id = nsilcmop["_id"] # slice operation id
622 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
623 self.lcm_tasks.cancel(topic, nsir_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100624 task = asyncio.ensure_future(
625 self.netslice.terminate(nsir_id, nsilcmop_id)
626 )
627 self.lcm_tasks.register(
628 "nsi", nsir_id, nsilcmop_id, "nsi_terminate", task
629 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100630 return
631 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000632 nsir_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100633 try:
634 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100635 print(
636 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
637 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
638 "".format(
639 nsir_id,
640 db_nsir["operational-status"],
641 db_nsir["config-status"],
642 db_nsir["detailed-status"],
643 db_nsir["_admin"]["deployed"],
644 self.lcm_netslice_tasks.get(nsir_id),
645 )
646 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100647 except Exception as e:
648 print("nsir {} not found: {}".format(nsir_id, e))
649 sys.stdout.flush()
650 return
651 elif command == "deleted":
652 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100653 elif command in (
654 "terminated",
655 "instantiated",
656 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200657 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100658 "actioned",
659 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100660 return
661 elif topic == "vim_account":
662 vim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000663 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000664 if not self.config["ro_config"].get("ng"):
665 task = asyncio.ensure_future(self.vim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100666 self.lcm_tasks.register(
667 "vim_account", vim_id, order_id, "vim_create", task
668 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100669 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100670 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100671 self.lcm_tasks.cancel(topic, vim_id)
kuuse6a470c62019-07-10 13:52:45 +0200672 task = asyncio.ensure_future(self.vim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100673 self.lcm_tasks.register(
674 "vim_account", vim_id, order_id, "vim_delete", task
675 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100676 return
677 elif command == "show":
678 print("not implemented show with vim_account")
679 sys.stdout.flush()
680 return
tiernof210c1c2019-10-16 09:09:58 +0000681 elif command in ("edit", "edited"):
tierno2357f4e2020-10-19 16:38:59 +0000682 if not self.config["ro_config"].get("ng"):
683 task = asyncio.ensure_future(self.vim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100684 self.lcm_tasks.register(
685 "vim_account", vim_id, order_id, "vim_edit", task
686 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100687 return
tiernof210c1c2019-10-16 09:09:58 +0000688 elif command == "deleted":
689 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100690 elif topic == "wim_account":
691 wim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000692 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000693 if not self.config["ro_config"].get("ng"):
694 task = asyncio.ensure_future(self.wim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100695 self.lcm_tasks.register(
696 "wim_account", wim_id, order_id, "wim_create", task
697 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100698 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100699 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100700 self.lcm_tasks.cancel(topic, wim_id)
kuuse6a470c62019-07-10 13:52:45 +0200701 task = asyncio.ensure_future(self.wim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100702 self.lcm_tasks.register(
703 "wim_account", wim_id, order_id, "wim_delete", task
704 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100705 return
706 elif command == "show":
707 print("not implemented show with wim_account")
708 sys.stdout.flush()
709 return
tiernof210c1c2019-10-16 09:09:58 +0000710 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100711 task = asyncio.ensure_future(self.wim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100712 self.lcm_tasks.register(
713 "wim_account", wim_id, order_id, "wim_edit", task
714 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100715 return
tiernof210c1c2019-10-16 09:09:58 +0000716 elif command == "deleted":
717 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100718 elif topic == "sdn":
719 _sdn_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000720 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000721 if not self.config["ro_config"].get("ng"):
722 task = asyncio.ensure_future(self.sdn.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100723 self.lcm_tasks.register(
724 "sdn", _sdn_id, order_id, "sdn_create", task
725 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100726 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100727 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100728 self.lcm_tasks.cancel(topic, _sdn_id)
kuuse6a470c62019-07-10 13:52:45 +0200729 task = asyncio.ensure_future(self.sdn.delete(params, order_id))
gcalvinoed7f6d42018-12-14 14:44:56 +0100730 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
731 return
tiernof210c1c2019-10-16 09:09:58 +0000732 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100733 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
734 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
735 return
tiernof210c1c2019-10-16 09:09:58 +0000736 elif command == "deleted":
737 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100738 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
739
tiernoc0e42e22018-05-11 11:36:10 +0200740 async def kafka_read(self):
garciadeblas5697b8b2021-03-24 09:17:02 +0100741 self.logger.debug(
742 "Task kafka_read Enter with worker_id={}".format(self.worker_id)
743 )
tiernoc0e42e22018-05-11 11:36:10 +0200744 # future = asyncio.Future()
gcalvinoed7f6d42018-12-14 14:44:56 +0100745 self.consecutive_errors = 0
746 self.first_start = True
747 while self.consecutive_errors < 10:
tiernoc0e42e22018-05-11 11:36:10 +0200748 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100749 topics = (
750 "ns",
751 "vim_account",
752 "wim_account",
753 "sdn",
754 "nsi",
755 "k8scluster",
756 "vca",
Patricia Reinoso15ce47b2022-10-26 08:58:39 +0000757 "paas",
garciadeblas5697b8b2021-03-24 09:17:02 +0100758 "k8srepo",
759 "pla",
760 )
761 topics_admin = ("admin",)
tierno16427352019-04-22 11:37:36 +0000762 await asyncio.gather(
garciadeblas5697b8b2021-03-24 09:17:02 +0100763 self.msg.aioread(
764 topics, self.loop, self.kafka_read_callback, from_beginning=True
765 ),
766 self.msg_admin.aioread(
767 topics_admin,
768 self.loop,
769 self.kafka_read_callback,
770 group_id=False,
771 ),
tierno16427352019-04-22 11:37:36 +0000772 )
tiernoc0e42e22018-05-11 11:36:10 +0200773
gcalvinoed7f6d42018-12-14 14:44:56 +0100774 except LcmExceptionExit:
775 self.logger.debug("Bye!")
776 break
tiernoc0e42e22018-05-11 11:36:10 +0200777 except Exception as e:
778 # if not first_start is the first time after starting. So leave more time and wait
779 # to allow kafka starts
gcalvinoed7f6d42018-12-14 14:44:56 +0100780 if self.consecutive_errors == 8 if not self.first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100781 self.logger.error(
782 "Task kafka_read task exit error too many errors. Exception: {}".format(
783 e
784 )
785 )
tiernoc0e42e22018-05-11 11:36:10 +0200786 raise
gcalvinoed7f6d42018-12-14 14:44:56 +0100787 self.consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100788 self.logger.error(
789 "Task kafka_read retrying after Exception {}".format(e)
790 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100791 wait_time = 2 if not self.first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200792 await asyncio.sleep(wait_time, loop=self.loop)
793
794 # self.logger.debug("Task kafka_read terminating")
795 self.logger.debug("Task kafka_read exit")
796
797 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200798
799 # check RO version
800 self.loop.run_until_complete(self.check_RO_version())
801
aticig15db6142022-01-24 12:51:26 +0300802 self.ns = ns.NsLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100803 self.netslice = netslice.NetsliceLcm(
804 self.msg, self.lcm_tasks, self.config, self.loop, self.ns
805 )
bravof922c4172020-11-24 21:21:43 -0300806 self.vim = vim_sdn.VimLcm(self.msg, self.lcm_tasks, self.config, self.loop)
807 self.wim = vim_sdn.WimLcm(self.msg, self.lcm_tasks, self.config, self.loop)
808 self.sdn = vim_sdn.SdnLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100809 self.k8scluster = vim_sdn.K8sClusterLcm(
810 self.msg, self.lcm_tasks, self.config, self.loop
811 )
David Garciac1fe90a2021-03-31 19:12:02 +0200812 self.vca = vim_sdn.VcaLcm(self.msg, self.lcm_tasks, self.config, self.loop)
Patricia Reinoso15ce47b2022-10-26 08:58:39 +0000813 self.paas = paas.PaasLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100814 self.k8srepo = vim_sdn.K8sRepoLcm(
815 self.msg, self.lcm_tasks, self.config, self.loop
816 )
tierno2357f4e2020-10-19 16:38:59 +0000817
Gulsum Aticie7e0b752022-09-30 14:31:26 +0300818 # Specific PaaS Service Object for "Juju" PaaS Orchestrator type
819 self.juju_paas = paas_service_factory(
820 self.msg,
821 self.lcm_tasks,
822 self.db,
823 self.fs,
824 self.logger,
825 self.loop,
826 self.config,
827 "juju",
828 )
829 # Mapping between paas_type and PaaS service object
830 self.paas_service = {
831 "juju": self.juju_paas,
832 }
garciadeblas5697b8b2021-03-24 09:17:02 +0100833 self.loop.run_until_complete(
834 asyncio.gather(self.kafka_read(), self.kafka_ping())
835 )
bravof73bac502021-05-11 07:38:47 -0400836
tiernoc0e42e22018-05-11 11:36:10 +0200837 # TODO
838 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200839 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200840 # timeout = 200
841 # while self.is_pending_tasks():
842 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
843 # await asyncio.sleep(2, loop=self.loop)
844 # timeout -= 2
845 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200846 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200847 self.loop.close()
848 self.loop = None
849 if self.db:
850 self.db.db_disconnect()
851 if self.msg:
852 self.msg.disconnect()
tierno16427352019-04-22 11:37:36 +0000853 if self.msg_admin:
854 self.msg_admin.disconnect()
tiernoc0e42e22018-05-11 11:36:10 +0200855 if self.fs:
856 self.fs.fs_disconnect()
857
tiernoc0e42e22018-05-11 11:36:10 +0200858 def read_config_file(self, config_file):
859 # TODO make a [ini] + yaml inside parser
860 # the configparser library is not suitable, because it does not admit comments at the end of line,
861 # and not parse integer or boolean
862 try:
tierno744303e2020-01-13 16:46:31 +0000863 # read file as yaml format
tiernoc0e42e22018-05-11 11:36:10 +0200864 with open(config_file) as f:
Luisccdc2162022-07-01 14:35:49 +0000865 conf = yaml.safe_load(f)
tierno744303e2020-01-13 16:46:31 +0000866 # Ensure all sections are not empty
garciadeblas5697b8b2021-03-24 09:17:02 +0100867 for k in (
868 "global",
869 "timeout",
870 "RO",
871 "VCA",
872 "database",
873 "storage",
874 "message",
875 ):
tierno744303e2020-01-13 16:46:31 +0000876 if not conf.get(k):
877 conf[k] = {}
878
879 # read all environ that starts with OSMLCM_
tiernoc0e42e22018-05-11 11:36:10 +0200880 for k, v in environ.items():
881 if not k.startswith("OSMLCM_"):
882 continue
tierno744303e2020-01-13 16:46:31 +0000883 subject, _, item = k[7:].lower().partition("_")
884 if not item:
tierno17a612f2018-10-23 11:30:42 +0200885 continue
tierno744303e2020-01-13 16:46:31 +0000886 if subject in ("ro", "vca"):
tierno17a612f2018-10-23 11:30:42 +0200887 # put in capital letter
tierno744303e2020-01-13 16:46:31 +0000888 subject = subject.upper()
tiernoc0e42e22018-05-11 11:36:10 +0200889 try:
tierno744303e2020-01-13 16:46:31 +0000890 if item == "port" or subject == "timeout":
891 conf[subject][item] = int(v)
tiernoc0e42e22018-05-11 11:36:10 +0200892 else:
tierno744303e2020-01-13 16:46:31 +0000893 conf[subject][item] = v
tiernoc0e42e22018-05-11 11:36:10 +0200894 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100895 self.logger.warning(
896 "skipping environ '{}' on exception '{}'".format(k, e)
897 )
tierno744303e2020-01-13 16:46:31 +0000898
899 # backward compatibility of VCA parameters
900
garciadeblas5697b8b2021-03-24 09:17:02 +0100901 if "pubkey" in conf["VCA"]:
902 conf["VCA"]["public_key"] = conf["VCA"].pop("pubkey")
903 if "cacert" in conf["VCA"]:
904 conf["VCA"]["ca_cert"] = conf["VCA"].pop("cacert")
905 if "apiproxy" in conf["VCA"]:
906 conf["VCA"]["api_proxy"] = conf["VCA"].pop("apiproxy")
tierno744303e2020-01-13 16:46:31 +0000907
garciadeblas5697b8b2021-03-24 09:17:02 +0100908 if "enableosupgrade" in conf["VCA"]:
909 conf["VCA"]["enable_os_upgrade"] = conf["VCA"].pop("enableosupgrade")
910 if isinstance(conf["VCA"].get("enable_os_upgrade"), str):
911 if conf["VCA"]["enable_os_upgrade"].lower() == "false":
912 conf["VCA"]["enable_os_upgrade"] = False
913 elif conf["VCA"]["enable_os_upgrade"].lower() == "true":
914 conf["VCA"]["enable_os_upgrade"] = True
tierno744303e2020-01-13 16:46:31 +0000915
garciadeblas5697b8b2021-03-24 09:17:02 +0100916 if "aptmirror" in conf["VCA"]:
917 conf["VCA"]["apt_mirror"] = conf["VCA"].pop("aptmirror")
tiernoc0e42e22018-05-11 11:36:10 +0200918
919 return conf
920 except Exception as e:
921 self.logger.critical("At config file '{}': {}".format(config_file, e))
922 exit(1)
923
tierno16427352019-04-22 11:37:36 +0000924 @staticmethod
925 def get_process_id():
926 """
927 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
928 will provide a random one
929 :return: Obtained ID
930 """
931 # Try getting docker id. If fails, get pid
932 try:
933 with open("/proc/self/cgroup", "r") as f:
934 text_id_ = f.readline()
935 _, _, text_id = text_id_.rpartition("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100936 text_id = text_id.replace("\n", "")[:12]
tierno16427352019-04-22 11:37:36 +0000937 if text_id:
938 return text_id
939 except Exception:
940 pass
941 # Return a random id
garciadeblas5697b8b2021-03-24 09:17:02 +0100942 return "".join(random_choice("0123456789abcdef") for _ in range(12))
tierno16427352019-04-22 11:37:36 +0000943
tiernoc0e42e22018-05-11 11:36:10 +0200944
tierno275411e2018-05-16 14:33:32 +0200945def usage():
garciadeblas5697b8b2021-03-24 09:17:02 +0100946 print(
947 """Usage: {} [options]
quilesj7e13aeb2019-10-08 13:34:55 +0200948 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200949 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200950 -h|--help: shows this help
garciadeblas5697b8b2021-03-24 09:17:02 +0100951 """.format(
952 sys.argv[0]
953 )
954 )
tierno750b2452018-05-17 16:39:29 +0200955 # --log-socket-host HOST: send logs to this host")
956 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200957
958
garciadeblas5697b8b2021-03-24 09:17:02 +0100959if __name__ == "__main__":
quilesj7e13aeb2019-10-08 13:34:55 +0200960
tierno275411e2018-05-16 14:33:32 +0200961 try:
tierno8c16b052020-02-05 15:08:32 +0000962 # print("SYS.PATH='{}'".format(sys.path))
tierno275411e2018-05-16 14:33:32 +0200963 # load parameters and configuration
quilesj7e13aeb2019-10-08 13:34:55 +0200964 # -h
965 # -c value
966 # --config value
967 # --help
968 # --health-check
garciadeblas5697b8b2021-03-24 09:17:02 +0100969 opts, args = getopt.getopt(
970 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
971 )
tierno275411e2018-05-16 14:33:32 +0200972 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
973 config_file = None
974 for o, a in opts:
975 if o in ("-h", "--help"):
976 usage()
977 sys.exit()
978 elif o in ("-c", "--config"):
979 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200980 elif o == "--health-check":
tierno94f06112020-02-11 12:38:19 +0000981 from osm_lcm.lcm_hc import health_check
garciadeblas5697b8b2021-03-24 09:17:02 +0100982
aticig56b86c22022-06-29 10:43:05 +0300983 health_check(config_file, Lcm.ping_interval_pace)
tierno275411e2018-05-16 14:33:32 +0200984 # elif o == "--log-socket-port":
985 # log_socket_port = a
986 # elif o == "--log-socket-host":
987 # log_socket_host = a
988 # elif o == "--log-file":
989 # log_file = a
990 else:
991 assert False, "Unhandled option"
quilesj7e13aeb2019-10-08 13:34:55 +0200992
tierno275411e2018-05-16 14:33:32 +0200993 if config_file:
994 if not path.isfile(config_file):
garciadeblas5697b8b2021-03-24 09:17:02 +0100995 print(
996 "configuration file '{}' does not exist".format(config_file),
997 file=sys.stderr,
998 )
tierno275411e2018-05-16 14:33:32 +0200999 exit(1)
1000 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001001 for config_file in (
1002 __file__[: __file__.rfind(".")] + ".cfg",
1003 "./lcm.cfg",
1004 "/etc/osm/lcm.cfg",
1005 ):
tierno275411e2018-05-16 14:33:32 +02001006 if path.isfile(config_file):
1007 break
1008 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001009 print(
1010 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
1011 file=sys.stderr,
1012 )
tierno275411e2018-05-16 14:33:32 +02001013 exit(1)
1014 lcm = Lcm(config_file)
tierno3e359b12019-02-03 02:29:13 +01001015 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +02001016 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +02001017 print(str(e), file=sys.stderr)
1018 # usage()
1019 exit(1)