blob: 723ca7ac2610b84c83b73b5fcad82b51ab2ab57b [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
bravof73bac502021-05-11 07:38:47 -040032from osm_lcm import ns, 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
tierno8069ce52019-08-28 15:34:33 +000037from osm_lcm.lcm_utils import versiontuple, LcmException, TaskRegistry, LcmExceptionExit
tiernoa4dea5a2020-01-05 16:29:30 +000038from osm_lcm import version as lcm_version, version_date as lcm_version_date
tierno8069ce52019-08-28 15:34:33 +000039
bravof922c4172020-11-24 21:21:43 -030040from osm_common import msglocal, msgkafka
tierno98768132018-09-11 12:07:21 +020041from osm_common import version as common_version
tierno59d22d22018-09-25 18:10:19 +020042from osm_common.dbbase import DbException
tiernoc0e42e22018-05-11 11:36:10 +020043from osm_common.fsbase import FsException
44from osm_common.msgbase import MsgException
bravof922c4172020-11-24 21:21:43 -030045from osm_lcm.data_utils.database.database import Database
46from osm_lcm.data_utils.filesystem.filesystem import Filesystem
Luis Vegaa27dc532022-11-11 20:10:49 +000047from osm_lcm.data_utils.lcm_config import LcmCfg
aticig56b86c22022-06-29 10:43:05 +030048from osm_lcm.lcm_hc import get_health_check_file
Luis Vegaa27dc532022-11-11 20:10:49 +000049from os import path
tierno16427352019-04-22 11:37:36 +000050from random import choice as random_choice
tierno59d22d22018-09-25 18:10:19 +020051from n2vc import version as n2vc_version
bravof922c4172020-11-24 21:21:43 -030052import traceback
tiernoc0e42e22018-05-11 11:36:10 +020053
garciadeblas5697b8b2021-03-24 09:17:02 +010054if os.getenv("OSMLCM_PDB_DEBUG", None) is not None:
quilesj7e13aeb2019-10-08 13:34:55 +020055 pdb.set_trace()
56
tiernoc0e42e22018-05-11 11:36:10 +020057
tierno275411e2018-05-16 14:33:32 +020058__author__ = "Alfonso Tierno"
tiernoe64f7fb2019-09-11 08:55:52 +000059min_RO_version = "6.0.2"
tierno6e9d2eb2018-09-12 17:47:18 +020060min_n2vc_version = "0.0.2"
quilesj7e13aeb2019-10-08 13:34:55 +020061
tierno16427352019-04-22 11:37:36 +000062min_common_version = "0.1.19"
tierno275411e2018-05-16 14:33:32 +020063
64
tiernoc0e42e22018-05-11 11:36:10 +020065class Lcm:
garciadeblas5697b8b2021-03-24 09:17:02 +010066 ping_interval_pace = (
67 120 # how many time ping is send once is confirmed all is running
68 )
69 ping_interval_boot = 5 # how many time ping is sent when booting
Luis Vegaa27dc532022-11-11 20:10:49 +000070
71 main_config = LcmCfg()
tiernoa9843d82018-10-24 10:44:20 +020072
tierno59d22d22018-09-25 18:10:19 +020073 def __init__(self, config_file, loop=None):
tiernoc0e42e22018-05-11 11:36:10 +020074 """
75 Init, Connect to database, filesystem storage, and messaging
76 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
77 :return: None
78 """
tiernoc0e42e22018-05-11 11:36:10 +020079 self.db = None
80 self.msg = None
tierno16427352019-04-22 11:37:36 +000081 self.msg_admin = None
tiernoc0e42e22018-05-11 11:36:10 +020082 self.fs = None
83 self.pings_not_received = 1
tiernoc2564fe2019-01-28 16:18:56 +000084 self.consecutive_errors = 0
85 self.first_start = False
tiernoc0e42e22018-05-11 11:36:10 +020086
tiernoc0e42e22018-05-11 11:36:10 +020087 # logging
garciadeblas5697b8b2021-03-24 09:17:02 +010088 self.logger = logging.getLogger("lcm")
tierno16427352019-04-22 11:37:36 +000089 # get id
90 self.worker_id = self.get_process_id()
tiernoc0e42e22018-05-11 11:36:10 +020091 # load configuration
92 config = self.read_config_file(config_file)
Luis Vegaa27dc532022-11-11 20:10:49 +000093 self.main_config.set_from_dict(config)
94 self.main_config.transform()
95 self.main_config.load_from_env()
96 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
97 # TODO: check if lcm_hc.py is necessary
98 self.health_check_file = get_health_check_file(self.main_config.to_dict())
tierno59d22d22018-09-25 18:10:19 +020099 self.loop = loop or asyncio.get_event_loop()
garciadeblas5697b8b2021-03-24 09:17:02 +0100100 self.ns = (
101 self.netslice
102 ) = (
103 self.vim
104 ) = self.wim = self.sdn = self.k8scluster = self.vca = self.k8srepo = None
tiernoc0e42e22018-05-11 11:36:10 +0200105
106 # logging
garciadeblas5697b8b2021-03-24 09:17:02 +0100107 log_format_simple = (
108 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
109 )
110 log_formatter_simple = logging.Formatter(
111 log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S"
112 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000113 if self.main_config.globalConfig.logfile:
garciadeblas5697b8b2021-03-24 09:17:02 +0100114 file_handler = logging.handlers.RotatingFileHandler(
Luis Vegaa27dc532022-11-11 20:10:49 +0000115 self.main_config.globalConfig.logfile,
116 maxBytes=100e6,
117 backupCount=9,
118 delay=0,
garciadeblas5697b8b2021-03-24 09:17:02 +0100119 )
tiernoc0e42e22018-05-11 11:36:10 +0200120 file_handler.setFormatter(log_formatter_simple)
121 self.logger.addHandler(file_handler)
Luis Vegaa27dc532022-11-11 20:10:49 +0000122 if not self.main_config.globalConfig.to_dict()["nologging"]:
tiernoc0e42e22018-05-11 11:36:10 +0200123 str_handler = logging.StreamHandler()
124 str_handler.setFormatter(log_formatter_simple)
125 self.logger.addHandler(str_handler)
126
Luis Vegaa27dc532022-11-11 20:10:49 +0000127 if self.main_config.globalConfig.to_dict()["loglevel"]:
128 self.logger.setLevel(self.main_config.globalConfig.loglevel)
tiernoc0e42e22018-05-11 11:36:10 +0200129
130 # logging other modules
Luis Vegaa27dc532022-11-11 20:10:49 +0000131 for logger in ("message", "database", "storage", "tsdb"):
132 logger_config = self.main_config.to_dict()[logger]
133 logger_module = logging.getLogger(logger_config["logger_name"])
134 if logger_config["logfile"]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100135 file_handler = logging.handlers.RotatingFileHandler(
Luis Vegaa27dc532022-11-11 20:10:49 +0000136 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
garciadeblas5697b8b2021-03-24 09:17:02 +0100137 )
tiernoc0e42e22018-05-11 11:36:10 +0200138 file_handler.setFormatter(log_formatter_simple)
139 logger_module.addHandler(file_handler)
Luis Vegaa27dc532022-11-11 20:10:49 +0000140 if logger_config["loglevel"]:
141 logger_module.setLevel(logger_config["loglevel"])
garciadeblas5697b8b2021-03-24 09:17:02 +0100142 self.logger.critical(
143 "starting osm/lcm version {} {}".format(lcm_version, lcm_version_date)
144 )
tierno59d22d22018-09-25 18:10:19 +0200145
tiernoc0e42e22018-05-11 11:36:10 +0200146 # check version of N2VC
147 # TODO enhance with int conversion or from distutils.version import LooseVersion
148 # or with list(map(int, version.split(".")))
tierno59d22d22018-09-25 18:10:19 +0200149 if versiontuple(n2vc_version) < versiontuple(min_n2vc_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100150 raise LcmException(
151 "Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
152 n2vc_version, min_n2vc_version
153 )
154 )
tierno59d22d22018-09-25 18:10:19 +0200155 # check version of common
tierno27246d82018-09-27 15:59:09 +0200156 if versiontuple(common_version) < versiontuple(min_common_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100157 raise LcmException(
158 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
159 common_version, min_common_version
160 )
161 )
tierno22f4f9c2018-06-11 18:53:39 +0200162
tiernoc0e42e22018-05-11 11:36:10 +0200163 try:
Luis Vegaa27dc532022-11-11 20:10:49 +0000164 self.db = Database(self.main_config.to_dict()).instance.db
tiernoc0e42e22018-05-11 11:36:10 +0200165
Luis Vegaa27dc532022-11-11 20:10:49 +0000166 self.fs = Filesystem(self.main_config.to_dict()).instance.fs
sousaedu40365e82021-07-26 15:24:21 +0200167 self.fs.sync()
tiernoc0e42e22018-05-11 11:36:10 +0200168
quilesj7e13aeb2019-10-08 13:34:55 +0200169 # copy message configuration in order to remove 'group_id' for msg_admin
Luis Vegaa27dc532022-11-11 20:10:49 +0000170 config_message = self.main_config.message.to_dict()
tiernoc2564fe2019-01-28 16:18:56 +0000171 config_message["loop"] = self.loop
172 if config_message["driver"] == "local":
tiernoc0e42e22018-05-11 11:36:10 +0200173 self.msg = msglocal.MsgLocal()
tiernoc2564fe2019-01-28 16:18:56 +0000174 self.msg.connect(config_message)
tierno16427352019-04-22 11:37:36 +0000175 self.msg_admin = msglocal.MsgLocal()
176 config_message.pop("group_id", None)
177 self.msg_admin.connect(config_message)
tiernoc2564fe2019-01-28 16:18:56 +0000178 elif config_message["driver"] == "kafka":
tiernoc0e42e22018-05-11 11:36:10 +0200179 self.msg = msgkafka.MsgKafka()
tiernoc2564fe2019-01-28 16:18:56 +0000180 self.msg.connect(config_message)
tierno16427352019-04-22 11:37:36 +0000181 self.msg_admin = msgkafka.MsgKafka()
182 config_message.pop("group_id", None)
183 self.msg_admin.connect(config_message)
tiernoc0e42e22018-05-11 11:36:10 +0200184 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100185 raise LcmException(
186 "Invalid configuration param '{}' at '[message]':'driver'".format(
Luis Vegaa27dc532022-11-11 20:10:49 +0000187 self.main_config.message.driver
garciadeblas5697b8b2021-03-24 09:17:02 +0100188 )
189 )
tiernoc0e42e22018-05-11 11:36:10 +0200190 except (DbException, FsException, MsgException) as e:
191 self.logger.critical(str(e), exc_info=True)
192 raise LcmException(str(e))
193
kuused124bfe2019-06-18 12:09:24 +0200194 # contains created tasks/futures to be able to cancel
bravof922c4172020-11-24 21:21:43 -0300195 self.lcm_tasks = TaskRegistry(self.worker_id, self.logger)
kuused124bfe2019-06-18 12:09:24 +0200196
tierno22f4f9c2018-06-11 18:53:39 +0200197 async def check_RO_version(self):
tiernoe64f7fb2019-09-11 08:55:52 +0000198 tries = 14
199 last_error = None
200 while True:
Luis Vegaa27dc532022-11-11 20:10:49 +0000201 ro_uri = self.main_config.RO.uri
202 if not ro_uri:
203 ro_uri = ""
tiernoe64f7fb2019-09-11 08:55:52 +0000204 try:
tierno2357f4e2020-10-19 16:38:59 +0000205 # try new RO, if fail old RO
206 try:
Luis Vegaa27dc532022-11-11 20:10:49 +0000207 self.main_config.RO.uri = ro_uri + "ro"
208 ro_server = NgRoClient(self.loop, **self.main_config.RO.to_dict())
tierno2357f4e2020-10-19 16:38:59 +0000209 ro_version = await ro_server.get_version()
Luis Vegaa27dc532022-11-11 20:10:49 +0000210 self.main_config.RO.ng = True
tierno2357f4e2020-10-19 16:38:59 +0000211 except Exception:
Luis Vegaa27dc532022-11-11 20:10:49 +0000212 self.main_config.RO.uri = ro_uri + "openmano"
213 ro_server = ROClient(self.loop, **self.main_config.RO.to_dict())
tierno2357f4e2020-10-19 16:38:59 +0000214 ro_version = await ro_server.get_version()
Luis Vegaa27dc532022-11-11 20:10:49 +0000215 self.main_config.RO.ng = False
tiernoe64f7fb2019-09-11 08:55:52 +0000216 if versiontuple(ro_version) < versiontuple(min_RO_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100217 raise LcmException(
218 "Not compatible osm/RO version '{}'. Needed '{}' or higher".format(
219 ro_version, min_RO_version
220 )
221 )
222 self.logger.info(
223 "Connected to RO version {} new-generation version {}".format(
Luis Vegaa27dc532022-11-11 20:10:49 +0000224 ro_version, self.main_config.RO.ng
garciadeblas5697b8b2021-03-24 09:17:02 +0100225 )
226 )
tiernoe64f7fb2019-09-11 08:55:52 +0000227 return
tierno69f0d382020-05-07 13:08:09 +0000228 except (ROClientException, NgRoException) as e:
Luis Vegaa27dc532022-11-11 20:10:49 +0000229 self.main_config.RO.uri = ro_uri
tiernoe64f7fb2019-09-11 08:55:52 +0000230 tries -= 1
bravof922c4172020-11-24 21:21:43 -0300231 traceback.print_tb(e.__traceback__)
garciadeblas5697b8b2021-03-24 09:17:02 +0100232 error_text = "Error while connecting to RO on {}: {}".format(
Luis Vegaa27dc532022-11-11 20:10:49 +0000233 self.main_config.RO.uri, e
garciadeblas5697b8b2021-03-24 09:17:02 +0100234 )
tiernoe64f7fb2019-09-11 08:55:52 +0000235 if tries <= 0:
236 self.logger.critical(error_text)
237 raise LcmException(error_text)
238 if last_error != error_text:
239 last_error = error_text
garciadeblas5697b8b2021-03-24 09:17:02 +0100240 self.logger.error(
241 error_text + ". Waiting until {} seconds".format(5 * tries)
242 )
tiernoe64f7fb2019-09-11 08:55:52 +0000243 await asyncio.sleep(5)
tierno22f4f9c2018-06-11 18:53:39 +0200244
tiernoc0e42e22018-05-11 11:36:10 +0200245 async def test(self, param=None):
246 self.logger.debug("Starting/Ending test task: {}".format(param))
247
tiernoc0e42e22018-05-11 11:36:10 +0200248 async def kafka_ping(self):
249 self.logger.debug("Task kafka_ping Enter")
250 consecutive_errors = 0
251 first_start = True
252 kafka_has_received = False
253 self.pings_not_received = 1
254 while True:
255 try:
tierno16427352019-04-22 11:37:36 +0000256 await self.msg_admin.aiowrite(
garciadeblas5697b8b2021-03-24 09:17:02 +0100257 "admin",
258 "ping",
259 {
260 "from": "lcm",
261 "to": "lcm",
262 "worker_id": self.worker_id,
263 "version": lcm_version,
264 },
265 self.loop,
266 )
tiernoc0e42e22018-05-11 11:36:10 +0200267 # time between pings are low when it is not received and at starting
garciadeblas5697b8b2021-03-24 09:17:02 +0100268 wait_time = (
269 self.ping_interval_boot
270 if not kafka_has_received
271 else self.ping_interval_pace
272 )
tiernoc0e42e22018-05-11 11:36:10 +0200273 if not self.pings_not_received:
274 kafka_has_received = True
275 self.pings_not_received += 1
276 await asyncio.sleep(wait_time, loop=self.loop)
277 if self.pings_not_received > 10:
278 raise LcmException("It is not receiving pings from Kafka bus")
279 consecutive_errors = 0
280 first_start = False
281 except LcmException:
282 raise
283 except Exception as e:
284 # if not first_start is the first time after starting. So leave more time and wait
285 # to allow kafka starts
286 if consecutive_errors == 8 if not first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100287 self.logger.error(
288 "Task kafka_read task exit error too many errors. Exception: {}".format(
289 e
290 )
291 )
tiernoc0e42e22018-05-11 11:36:10 +0200292 raise
293 consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100294 self.logger.error(
295 "Task kafka_read retrying after Exception {}".format(e)
296 )
tierno16427352019-04-22 11:37:36 +0000297 wait_time = 2 if not first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200298 await asyncio.sleep(wait_time, loop=self.loop)
299
gcalvinoed7f6d42018-12-14 14:44:56 +0100300 def kafka_read_callback(self, topic, command, params):
301 order_id = 1
302
303 if topic != "admin" and command != "ping":
garciadeblas5697b8b2021-03-24 09:17:02 +0100304 self.logger.debug(
305 "Task kafka_read receives {} {}: {}".format(topic, command, params)
306 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100307 self.consecutive_errors = 0
308 self.first_start = False
309 order_id += 1
310 if command == "exit":
311 raise LcmExceptionExit
312 elif command.startswith("#"):
313 return
314 elif command == "echo":
315 # just for test
316 print(params)
317 sys.stdout.flush()
318 return
319 elif command == "test":
320 asyncio.Task(self.test(params), loop=self.loop)
321 return
322
323 if topic == "admin":
324 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
tierno16427352019-04-22 11:37:36 +0000325 if params.get("worker_id") != self.worker_id:
326 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100327 self.pings_not_received = 0
tierno3e359b12019-02-03 02:29:13 +0100328 try:
aticig56b86c22022-06-29 10:43:05 +0300329 with open(self.health_check_file, "w") as f:
tierno3e359b12019-02-03 02:29:13 +0100330 f.write(str(time()))
331 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100332 self.logger.error(
333 "Cannot write into '{}' for healthcheck: {}".format(
aticig56b86c22022-06-29 10:43:05 +0300334 self.health_check_file, e
garciadeblas5697b8b2021-03-24 09:17:02 +0100335 )
336 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100337 return
magnussonle9198bb2020-01-21 13:00:51 +0100338 elif topic == "pla":
339 if command == "placement":
340 self.ns.update_nsrs_with_pla_result(params)
341 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100342 elif topic == "k8scluster":
343 if command == "create" or command == "created":
344 k8scluster_id = params.get("_id")
345 task = asyncio.ensure_future(self.k8scluster.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100346 self.lcm_tasks.register(
347 "k8scluster", k8scluster_id, order_id, "k8scluster_create", task
348 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100349 return
dariofaccin8bbeeb02023-01-23 18:13:27 +0100350 elif command == "edit" or command == "edited":
351 k8scluster_id = params.get("_id")
352 task = asyncio.ensure_future(self.k8scluster.edit(params, order_id))
353 self.lcm_tasks.register(
354 "k8scluster", k8scluster_id, order_id, "k8scluster_edit", task
355 )
356 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100357 elif command == "delete" or command == "deleted":
358 k8scluster_id = params.get("_id")
359 task = asyncio.ensure_future(self.k8scluster.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100360 self.lcm_tasks.register(
361 "k8scluster", k8scluster_id, order_id, "k8scluster_delete", task
362 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100363 return
David Garciac1fe90a2021-03-31 19:12:02 +0200364 elif topic == "vca":
365 if command == "create" or command == "created":
366 vca_id = params.get("_id")
367 task = asyncio.ensure_future(self.vca.create(params, order_id))
368 self.lcm_tasks.register("vca", vca_id, order_id, "vca_create", task)
369 return
Dario Faccin8e53c6d2023-01-10 10:38:41 +0000370 elif command == "edit" or command == "edited":
371 vca_id = params.get("_id")
372 task = asyncio.ensure_future(self.vca.edit(params, order_id))
373 self.lcm_tasks.register("vca", vca_id, order_id, "vca_edit", task)
374 return
David Garciac1fe90a2021-03-31 19:12:02 +0200375 elif command == "delete" or command == "deleted":
376 vca_id = params.get("_id")
377 task = asyncio.ensure_future(self.vca.delete(params, order_id))
378 self.lcm_tasks.register("vca", vca_id, order_id, "vca_delete", task)
379 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100380 elif topic == "k8srepo":
381 if command == "create" or command == "created":
382 k8srepo_id = params.get("_id")
383 self.logger.debug("k8srepo_id = {}".format(k8srepo_id))
384 task = asyncio.ensure_future(self.k8srepo.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100385 self.lcm_tasks.register(
386 "k8srepo", k8srepo_id, order_id, "k8srepo_create", task
387 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100388 return
389 elif command == "delete" or command == "deleted":
390 k8srepo_id = params.get("_id")
391 task = asyncio.ensure_future(self.k8srepo.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100392 self.lcm_tasks.register(
393 "k8srepo", k8srepo_id, order_id, "k8srepo_delete", task
394 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100395 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100396 elif topic == "ns":
tierno307425f2020-01-26 23:35:59 +0000397 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100398 # self.logger.debug("Deploying NS {}".format(nsr_id))
399 nslcmop = params
400 nslcmop_id = nslcmop["_id"]
401 nsr_id = nslcmop["nsInstanceId"]
402 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100403 self.lcm_tasks.register(
404 "ns", nsr_id, nslcmop_id, "ns_instantiate", task
405 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100406 return
tierno307425f2020-01-26 23:35:59 +0000407 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100408 # self.logger.debug("Deleting NS {}".format(nsr_id))
409 nslcmop = params
410 nslcmop_id = nslcmop["_id"]
411 nsr_id = nslcmop["nsInstanceId"]
412 self.lcm_tasks.cancel(topic, nsr_id)
413 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
414 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
415 return
ksaikiranr3fde2c72021-03-15 10:39:06 +0530416 elif command == "vca_status_refresh":
417 nslcmop = params
418 nslcmop_id = nslcmop["_id"]
419 nsr_id = nslcmop["nsInstanceId"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100420 task = asyncio.ensure_future(
421 self.ns.vca_status_refresh(nsr_id, nslcmop_id)
422 )
423 self.lcm_tasks.register(
424 "ns", nsr_id, nslcmop_id, "ns_vca_status_refresh", task
425 )
ksaikiranr3fde2c72021-03-15 10:39:06 +0530426 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100427 elif command == "action":
428 # self.logger.debug("Update NS {}".format(nsr_id))
429 nslcmop = params
430 nslcmop_id = nslcmop["_id"]
431 nsr_id = nslcmop["nsInstanceId"]
432 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
433 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
434 return
aticigdffa6212022-04-12 15:27:53 +0300435 elif command == "update":
436 # self.logger.debug("Update NS {}".format(nsr_id))
437 nslcmop = params
438 nslcmop_id = nslcmop["_id"]
439 nsr_id = nslcmop["nsInstanceId"]
440 task = asyncio.ensure_future(self.ns.update(nsr_id, nslcmop_id))
441 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_update", task)
442 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100443 elif command == "scale":
444 # self.logger.debug("Update NS {}".format(nsr_id))
445 nslcmop = params
446 nslcmop_id = nslcmop["_id"]
447 nsr_id = nslcmop["nsInstanceId"]
448 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
449 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
450 return
garciadeblas07f4e4c2022-06-09 09:42:58 +0200451 elif command == "heal":
452 # self.logger.debug("Healing NS {}".format(nsr_id))
453 nslcmop = params
454 nslcmop_id = nslcmop["_id"]
455 nsr_id = nslcmop["nsInstanceId"]
456 task = asyncio.ensure_future(self.ns.heal(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000457 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_heal", task)
garciadeblas07f4e4c2022-06-09 09:42:58 +0200458 return
elumalai80bcf1c2022-04-28 18:05:01 +0530459 elif command == "migrate":
460 nslcmop = params
461 nslcmop_id = nslcmop["_id"]
462 nsr_id = nslcmop["nsInstanceId"]
463 task = asyncio.ensure_future(self.ns.migrate(nsr_id, nslcmop_id))
464 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_migrate", task)
465 return
govindarajul4ff4b512022-05-02 20:02:41 +0530466 elif command == "verticalscale":
467 nslcmop = params
468 nslcmop_id = nslcmop["_id"]
469 nsr_id = nslcmop["nsInstanceId"]
470 task = asyncio.ensure_future(self.ns.vertical_scale(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000471 self.logger.debug(
472 "nsr_id,nslcmop_id,task {},{},{}".format(nsr_id, nslcmop_id, task)
473 )
474 self.lcm_tasks.register(
475 "ns", nsr_id, nslcmop_id, "ns_verticalscale", task
476 )
477 self.logger.debug(
478 "LCM task registered {},{},{} ".format(nsr_id, nslcmop_id, task)
479 )
govindarajul4ff4b512022-05-02 20:02:41 +0530480 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100481 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000482 nsr_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100483 try:
484 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100485 print(
486 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
487 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
488 "".format(
489 nsr_id,
490 db_nsr["operational-status"],
491 db_nsr["config-status"],
492 db_nsr["detailed-status"],
493 db_nsr["_admin"]["deployed"],
Gabriel Cuba411af2e2023-01-06 17:23:22 -0500494 self.lcm_tasks.task_registry["ns"].get(nsr_id, ""),
garciadeblas5697b8b2021-03-24 09:17:02 +0100495 )
496 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100497 except Exception as e:
498 print("nsr {} not found: {}".format(nsr_id, e))
499 sys.stdout.flush()
500 return
501 elif command == "deleted":
502 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100503 elif command in (
elumalaica7ece02022-04-12 12:47:32 +0530504 "vnf_terminated",
elumalaib9e357c2022-04-27 09:58:38 +0530505 "policy_updated",
garciadeblas5697b8b2021-03-24 09:17:02 +0100506 "terminated",
507 "instantiated",
508 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200509 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100510 "actioned",
aticigdffa6212022-04-12 15:27:53 +0300511 "updated",
elumalai80bcf1c2022-04-28 18:05:01 +0530512 "migrated",
govindarajul4ff4b512022-05-02 20:02:41 +0530513 "verticalscaled",
garciadeblas5697b8b2021-03-24 09:17:02 +0100514 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100515 return
elumalaica7ece02022-04-12 12:47:32 +0530516
gcalvinoed7f6d42018-12-14 14:44:56 +0100517 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
tierno307425f2020-01-26 23:35:59 +0000518 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100519 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
520 nsilcmop = params
521 nsilcmop_id = nsilcmop["_id"] # slice operation id
522 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
garciadeblas5697b8b2021-03-24 09:17:02 +0100523 task = asyncio.ensure_future(
524 self.netslice.instantiate(nsir_id, nsilcmop_id)
525 )
526 self.lcm_tasks.register(
527 "nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task
528 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100529 return
tierno307425f2020-01-26 23:35:59 +0000530 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100531 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
532 nsilcmop = params
533 nsilcmop_id = nsilcmop["_id"] # slice operation id
534 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
535 self.lcm_tasks.cancel(topic, nsir_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100536 task = asyncio.ensure_future(
537 self.netslice.terminate(nsir_id, nsilcmop_id)
538 )
539 self.lcm_tasks.register(
540 "nsi", nsir_id, nsilcmop_id, "nsi_terminate", task
541 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100542 return
543 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000544 nsir_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100545 try:
546 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100547 print(
548 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
549 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
550 "".format(
551 nsir_id,
552 db_nsir["operational-status"],
553 db_nsir["config-status"],
554 db_nsir["detailed-status"],
555 db_nsir["_admin"]["deployed"],
Gabriel Cuba411af2e2023-01-06 17:23:22 -0500556 self.lcm_tasks.task_registry["nsi"].get(nsir_id, ""),
garciadeblas5697b8b2021-03-24 09:17:02 +0100557 )
558 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100559 except Exception as e:
560 print("nsir {} not found: {}".format(nsir_id, e))
561 sys.stdout.flush()
562 return
563 elif command == "deleted":
564 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100565 elif command in (
566 "terminated",
567 "instantiated",
568 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200569 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100570 "actioned",
571 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100572 return
573 elif topic == "vim_account":
574 vim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000575 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000576 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000577 task = asyncio.ensure_future(self.vim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100578 self.lcm_tasks.register(
579 "vim_account", vim_id, order_id, "vim_create", task
580 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100581 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100582 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100583 self.lcm_tasks.cancel(topic, vim_id)
kuuse6a470c62019-07-10 13:52:45 +0200584 task = asyncio.ensure_future(self.vim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100585 self.lcm_tasks.register(
586 "vim_account", vim_id, order_id, "vim_delete", task
587 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100588 return
589 elif command == "show":
590 print("not implemented show with vim_account")
591 sys.stdout.flush()
592 return
tiernof210c1c2019-10-16 09:09:58 +0000593 elif command in ("edit", "edited"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000594 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000595 task = asyncio.ensure_future(self.vim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100596 self.lcm_tasks.register(
597 "vim_account", vim_id, order_id, "vim_edit", task
598 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100599 return
tiernof210c1c2019-10-16 09:09:58 +0000600 elif command == "deleted":
601 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100602 elif topic == "wim_account":
603 wim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000604 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000605 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000606 task = asyncio.ensure_future(self.wim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100607 self.lcm_tasks.register(
608 "wim_account", wim_id, order_id, "wim_create", task
609 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100610 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100611 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100612 self.lcm_tasks.cancel(topic, wim_id)
kuuse6a470c62019-07-10 13:52:45 +0200613 task = asyncio.ensure_future(self.wim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100614 self.lcm_tasks.register(
615 "wim_account", wim_id, order_id, "wim_delete", task
616 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100617 return
618 elif command == "show":
619 print("not implemented show with wim_account")
620 sys.stdout.flush()
621 return
tiernof210c1c2019-10-16 09:09:58 +0000622 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100623 task = asyncio.ensure_future(self.wim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100624 self.lcm_tasks.register(
625 "wim_account", wim_id, order_id, "wim_edit", task
626 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100627 return
tiernof210c1c2019-10-16 09:09:58 +0000628 elif command == "deleted":
629 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100630 elif topic == "sdn":
631 _sdn_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000632 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000633 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000634 task = asyncio.ensure_future(self.sdn.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100635 self.lcm_tasks.register(
636 "sdn", _sdn_id, order_id, "sdn_create", task
637 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100638 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100639 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100640 self.lcm_tasks.cancel(topic, _sdn_id)
kuuse6a470c62019-07-10 13:52:45 +0200641 task = asyncio.ensure_future(self.sdn.delete(params, order_id))
gcalvinoed7f6d42018-12-14 14:44:56 +0100642 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
643 return
tiernof210c1c2019-10-16 09:09:58 +0000644 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100645 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
646 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
647 return
tiernof210c1c2019-10-16 09:09:58 +0000648 elif command == "deleted":
649 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100650 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
651
tiernoc0e42e22018-05-11 11:36:10 +0200652 async def kafka_read(self):
garciadeblas5697b8b2021-03-24 09:17:02 +0100653 self.logger.debug(
654 "Task kafka_read Enter with worker_id={}".format(self.worker_id)
655 )
tiernoc0e42e22018-05-11 11:36:10 +0200656 # future = asyncio.Future()
gcalvinoed7f6d42018-12-14 14:44:56 +0100657 self.consecutive_errors = 0
658 self.first_start = True
659 while self.consecutive_errors < 10:
tiernoc0e42e22018-05-11 11:36:10 +0200660 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100661 topics = (
662 "ns",
663 "vim_account",
664 "wim_account",
665 "sdn",
666 "nsi",
667 "k8scluster",
668 "vca",
669 "k8srepo",
670 "pla",
671 )
672 topics_admin = ("admin",)
tierno16427352019-04-22 11:37:36 +0000673 await asyncio.gather(
garciadeblas5697b8b2021-03-24 09:17:02 +0100674 self.msg.aioread(
675 topics, self.loop, self.kafka_read_callback, from_beginning=True
676 ),
677 self.msg_admin.aioread(
678 topics_admin,
679 self.loop,
680 self.kafka_read_callback,
681 group_id=False,
682 ),
tierno16427352019-04-22 11:37:36 +0000683 )
tiernoc0e42e22018-05-11 11:36:10 +0200684
gcalvinoed7f6d42018-12-14 14:44:56 +0100685 except LcmExceptionExit:
686 self.logger.debug("Bye!")
687 break
tiernoc0e42e22018-05-11 11:36:10 +0200688 except Exception as e:
689 # if not first_start is the first time after starting. So leave more time and wait
690 # to allow kafka starts
gcalvinoed7f6d42018-12-14 14:44:56 +0100691 if self.consecutive_errors == 8 if not self.first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100692 self.logger.error(
693 "Task kafka_read task exit error too many errors. Exception: {}".format(
694 e
695 )
696 )
tiernoc0e42e22018-05-11 11:36:10 +0200697 raise
gcalvinoed7f6d42018-12-14 14:44:56 +0100698 self.consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100699 self.logger.error(
700 "Task kafka_read retrying after Exception {}".format(e)
701 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100702 wait_time = 2 if not self.first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200703 await asyncio.sleep(wait_time, loop=self.loop)
704
705 # self.logger.debug("Task kafka_read terminating")
706 self.logger.debug("Task kafka_read exit")
707
708 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200709 # check RO version
710 self.loop.run_until_complete(self.check_RO_version())
711
Luis Vegaa27dc532022-11-11 20:10:49 +0000712 self.ns = ns.NsLcm(self.msg, self.lcm_tasks, self.main_config, self.loop)
713 # TODO: modify the rest of classes to use the LcmCfg object instead of dicts
garciadeblas5697b8b2021-03-24 09:17:02 +0100714 self.netslice = netslice.NetsliceLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000715 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop, self.ns
garciadeblas5697b8b2021-03-24 09:17:02 +0100716 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000717 self.vim = vim_sdn.VimLcm(
718 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
719 )
720 self.wim = vim_sdn.WimLcm(
721 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
722 )
723 self.sdn = vim_sdn.SdnLcm(
724 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
725 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100726 self.k8scluster = vim_sdn.K8sClusterLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000727 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100728 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000729 self.vca = vim_sdn.VcaLcm(
730 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
731 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100732 self.k8srepo = vim_sdn.K8sRepoLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000733 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100734 )
tierno2357f4e2020-10-19 16:38:59 +0000735
garciadeblas5697b8b2021-03-24 09:17:02 +0100736 self.loop.run_until_complete(
737 asyncio.gather(self.kafka_read(), self.kafka_ping())
738 )
bravof73bac502021-05-11 07:38:47 -0400739
tiernoc0e42e22018-05-11 11:36:10 +0200740 # TODO
741 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200742 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200743 # timeout = 200
744 # while self.is_pending_tasks():
745 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
746 # await asyncio.sleep(2, loop=self.loop)
747 # timeout -= 2
748 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200749 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200750 self.loop.close()
751 self.loop = None
752 if self.db:
753 self.db.db_disconnect()
754 if self.msg:
755 self.msg.disconnect()
tierno16427352019-04-22 11:37:36 +0000756 if self.msg_admin:
757 self.msg_admin.disconnect()
tiernoc0e42e22018-05-11 11:36:10 +0200758 if self.fs:
759 self.fs.fs_disconnect()
760
tiernoc0e42e22018-05-11 11:36:10 +0200761 def read_config_file(self, config_file):
tiernoc0e42e22018-05-11 11:36:10 +0200762 try:
Gabriel Cubaa89a5a72022-11-26 18:55:15 -0500763 with open(config_file) as f:
764 return yaml.safe_load(f)
tiernoc0e42e22018-05-11 11:36:10 +0200765 except Exception as e:
766 self.logger.critical("At config file '{}': {}".format(config_file, e))
Gabriel Cubaa89a5a72022-11-26 18:55:15 -0500767 exit(1)
tiernoc0e42e22018-05-11 11:36:10 +0200768
tierno16427352019-04-22 11:37:36 +0000769 @staticmethod
770 def get_process_id():
771 """
772 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
773 will provide a random one
774 :return: Obtained ID
775 """
776 # Try getting docker id. If fails, get pid
777 try:
778 with open("/proc/self/cgroup", "r") as f:
779 text_id_ = f.readline()
780 _, _, text_id = text_id_.rpartition("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100781 text_id = text_id.replace("\n", "")[:12]
tierno16427352019-04-22 11:37:36 +0000782 if text_id:
783 return text_id
784 except Exception:
785 pass
786 # Return a random id
garciadeblas5697b8b2021-03-24 09:17:02 +0100787 return "".join(random_choice("0123456789abcdef") for _ in range(12))
tierno16427352019-04-22 11:37:36 +0000788
tiernoc0e42e22018-05-11 11:36:10 +0200789
tierno275411e2018-05-16 14:33:32 +0200790def usage():
garciadeblas5697b8b2021-03-24 09:17:02 +0100791 print(
792 """Usage: {} [options]
quilesj7e13aeb2019-10-08 13:34:55 +0200793 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200794 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200795 -h|--help: shows this help
garciadeblas5697b8b2021-03-24 09:17:02 +0100796 """.format(
797 sys.argv[0]
798 )
799 )
tierno750b2452018-05-17 16:39:29 +0200800 # --log-socket-host HOST: send logs to this host")
801 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200802
803
garciadeblas5697b8b2021-03-24 09:17:02 +0100804if __name__ == "__main__":
tierno275411e2018-05-16 14:33:32 +0200805 try:
tierno8c16b052020-02-05 15:08:32 +0000806 # print("SYS.PATH='{}'".format(sys.path))
tierno275411e2018-05-16 14:33:32 +0200807 # load parameters and configuration
quilesj7e13aeb2019-10-08 13:34:55 +0200808 # -h
809 # -c value
810 # --config value
811 # --help
812 # --health-check
garciadeblas5697b8b2021-03-24 09:17:02 +0100813 opts, args = getopt.getopt(
814 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
815 )
tierno275411e2018-05-16 14:33:32 +0200816 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
817 config_file = None
818 for o, a in opts:
819 if o in ("-h", "--help"):
820 usage()
821 sys.exit()
822 elif o in ("-c", "--config"):
823 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200824 elif o == "--health-check":
tierno94f06112020-02-11 12:38:19 +0000825 from osm_lcm.lcm_hc import health_check
garciadeblas5697b8b2021-03-24 09:17:02 +0100826
aticig56b86c22022-06-29 10:43:05 +0300827 health_check(config_file, Lcm.ping_interval_pace)
tierno275411e2018-05-16 14:33:32 +0200828 # elif o == "--log-socket-port":
829 # log_socket_port = a
830 # elif o == "--log-socket-host":
831 # log_socket_host = a
832 # elif o == "--log-file":
833 # log_file = a
834 else:
835 assert False, "Unhandled option"
quilesj7e13aeb2019-10-08 13:34:55 +0200836
tierno275411e2018-05-16 14:33:32 +0200837 if config_file:
838 if not path.isfile(config_file):
garciadeblas5697b8b2021-03-24 09:17:02 +0100839 print(
840 "configuration file '{}' does not exist".format(config_file),
841 file=sys.stderr,
842 )
tierno275411e2018-05-16 14:33:32 +0200843 exit(1)
844 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100845 for config_file in (
846 __file__[: __file__.rfind(".")] + ".cfg",
847 "./lcm.cfg",
848 "/etc/osm/lcm.cfg",
849 ):
tierno275411e2018-05-16 14:33:32 +0200850 if path.isfile(config_file):
851 break
852 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100853 print(
854 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
855 file=sys.stderr,
856 )
tierno275411e2018-05-16 14:33:32 +0200857 exit(1)
858 lcm = Lcm(config_file)
tierno3e359b12019-02-03 02:29:13 +0100859 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200860 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200861 print(str(e), file=sys.stderr)
862 # usage()
863 exit(1)