blob: 6da333ca8ef980ff711338e1ba8bcce6842b02e6 [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:
66
garciadeblas5697b8b2021-03-24 09:17:02 +010067 ping_interval_pace = (
68 120 # how many time ping is send once is confirmed all is running
69 )
70 ping_interval_boot = 5 # how many time ping is sent when booting
Luis Vegaa27dc532022-11-11 20:10:49 +000071
72 main_config = LcmCfg()
tiernoa9843d82018-10-24 10:44:20 +020073
tierno59d22d22018-09-25 18:10:19 +020074 def __init__(self, config_file, loop=None):
tiernoc0e42e22018-05-11 11:36:10 +020075 """
76 Init, Connect to database, filesystem storage, and messaging
77 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
78 :return: None
79 """
tiernoc0e42e22018-05-11 11:36:10 +020080 self.db = None
81 self.msg = None
tierno16427352019-04-22 11:37:36 +000082 self.msg_admin = None
tiernoc0e42e22018-05-11 11:36:10 +020083 self.fs = None
84 self.pings_not_received = 1
tiernoc2564fe2019-01-28 16:18:56 +000085 self.consecutive_errors = 0
86 self.first_start = False
tiernoc0e42e22018-05-11 11:36:10 +020087
tiernoc0e42e22018-05-11 11:36:10 +020088 # logging
garciadeblas5697b8b2021-03-24 09:17:02 +010089 self.logger = logging.getLogger("lcm")
tierno16427352019-04-22 11:37:36 +000090 # get id
91 self.worker_id = self.get_process_id()
tiernoc0e42e22018-05-11 11:36:10 +020092 # load configuration
93 config = self.read_config_file(config_file)
Luis Vegaa27dc532022-11-11 20:10:49 +000094 self.main_config.set_from_dict(config)
95 self.main_config.transform()
96 self.main_config.load_from_env()
97 self.logger.critical("Loaded configuration:" + str(self.main_config.to_dict()))
98 # TODO: check if lcm_hc.py is necessary
99 self.health_check_file = get_health_check_file(self.main_config.to_dict())
tierno59d22d22018-09-25 18:10:19 +0200100 self.loop = loop or asyncio.get_event_loop()
garciadeblas5697b8b2021-03-24 09:17:02 +0100101 self.ns = (
102 self.netslice
103 ) = (
104 self.vim
105 ) = self.wim = self.sdn = self.k8scluster = self.vca = self.k8srepo = None
tiernoc0e42e22018-05-11 11:36:10 +0200106
107 # logging
garciadeblas5697b8b2021-03-24 09:17:02 +0100108 log_format_simple = (
109 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
110 )
111 log_formatter_simple = logging.Formatter(
112 log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S"
113 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000114 if self.main_config.globalConfig.logfile:
garciadeblas5697b8b2021-03-24 09:17:02 +0100115 file_handler = logging.handlers.RotatingFileHandler(
Luis Vegaa27dc532022-11-11 20:10:49 +0000116 self.main_config.globalConfig.logfile,
117 maxBytes=100e6,
118 backupCount=9,
119 delay=0,
garciadeblas5697b8b2021-03-24 09:17:02 +0100120 )
tiernoc0e42e22018-05-11 11:36:10 +0200121 file_handler.setFormatter(log_formatter_simple)
122 self.logger.addHandler(file_handler)
Luis Vegaa27dc532022-11-11 20:10:49 +0000123 if not self.main_config.globalConfig.to_dict()["nologging"]:
tiernoc0e42e22018-05-11 11:36:10 +0200124 str_handler = logging.StreamHandler()
125 str_handler.setFormatter(log_formatter_simple)
126 self.logger.addHandler(str_handler)
127
Luis Vegaa27dc532022-11-11 20:10:49 +0000128 if self.main_config.globalConfig.to_dict()["loglevel"]:
129 self.logger.setLevel(self.main_config.globalConfig.loglevel)
tiernoc0e42e22018-05-11 11:36:10 +0200130
131 # logging other modules
Luis Vegaa27dc532022-11-11 20:10:49 +0000132 for logger in ("message", "database", "storage", "tsdb"):
133 logger_config = self.main_config.to_dict()[logger]
134 logger_module = logging.getLogger(logger_config["logger_name"])
135 if logger_config["logfile"]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100136 file_handler = logging.handlers.RotatingFileHandler(
Luis Vegaa27dc532022-11-11 20:10:49 +0000137 logger_config["logfile"], maxBytes=100e6, backupCount=9, delay=0
garciadeblas5697b8b2021-03-24 09:17:02 +0100138 )
tiernoc0e42e22018-05-11 11:36:10 +0200139 file_handler.setFormatter(log_formatter_simple)
140 logger_module.addHandler(file_handler)
Luis Vegaa27dc532022-11-11 20:10:49 +0000141 if logger_config["loglevel"]:
142 logger_module.setLevel(logger_config["loglevel"])
garciadeblas5697b8b2021-03-24 09:17:02 +0100143 self.logger.critical(
144 "starting osm/lcm version {} {}".format(lcm_version, lcm_version_date)
145 )
tierno59d22d22018-09-25 18:10:19 +0200146
tiernoc0e42e22018-05-11 11:36:10 +0200147 # check version of N2VC
148 # TODO enhance with int conversion or from distutils.version import LooseVersion
149 # or with list(map(int, version.split(".")))
tierno59d22d22018-09-25 18:10:19 +0200150 if versiontuple(n2vc_version) < versiontuple(min_n2vc_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100151 raise LcmException(
152 "Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
153 n2vc_version, min_n2vc_version
154 )
155 )
tierno59d22d22018-09-25 18:10:19 +0200156 # check version of common
tierno27246d82018-09-27 15:59:09 +0200157 if versiontuple(common_version) < versiontuple(min_common_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100158 raise LcmException(
159 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
160 common_version, min_common_version
161 )
162 )
tierno22f4f9c2018-06-11 18:53:39 +0200163
tiernoc0e42e22018-05-11 11:36:10 +0200164 try:
Luis Vegaa27dc532022-11-11 20:10:49 +0000165 self.db = Database(self.main_config.to_dict()).instance.db
tiernoc0e42e22018-05-11 11:36:10 +0200166
Luis Vegaa27dc532022-11-11 20:10:49 +0000167 self.fs = Filesystem(self.main_config.to_dict()).instance.fs
sousaedu40365e82021-07-26 15:24:21 +0200168 self.fs.sync()
tiernoc0e42e22018-05-11 11:36:10 +0200169
quilesj7e13aeb2019-10-08 13:34:55 +0200170 # copy message configuration in order to remove 'group_id' for msg_admin
Luis Vegaa27dc532022-11-11 20:10:49 +0000171 config_message = self.main_config.message.to_dict()
tiernoc2564fe2019-01-28 16:18:56 +0000172 config_message["loop"] = self.loop
173 if config_message["driver"] == "local":
tiernoc0e42e22018-05-11 11:36:10 +0200174 self.msg = msglocal.MsgLocal()
tiernoc2564fe2019-01-28 16:18:56 +0000175 self.msg.connect(config_message)
tierno16427352019-04-22 11:37:36 +0000176 self.msg_admin = msglocal.MsgLocal()
177 config_message.pop("group_id", None)
178 self.msg_admin.connect(config_message)
tiernoc2564fe2019-01-28 16:18:56 +0000179 elif config_message["driver"] == "kafka":
tiernoc0e42e22018-05-11 11:36:10 +0200180 self.msg = msgkafka.MsgKafka()
tiernoc2564fe2019-01-28 16:18:56 +0000181 self.msg.connect(config_message)
tierno16427352019-04-22 11:37:36 +0000182 self.msg_admin = msgkafka.MsgKafka()
183 config_message.pop("group_id", None)
184 self.msg_admin.connect(config_message)
tiernoc0e42e22018-05-11 11:36:10 +0200185 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100186 raise LcmException(
187 "Invalid configuration param '{}' at '[message]':'driver'".format(
Luis Vegaa27dc532022-11-11 20:10:49 +0000188 self.main_config.message.driver
garciadeblas5697b8b2021-03-24 09:17:02 +0100189 )
190 )
tiernoc0e42e22018-05-11 11:36:10 +0200191 except (DbException, FsException, MsgException) as e:
192 self.logger.critical(str(e), exc_info=True)
193 raise LcmException(str(e))
194
kuused124bfe2019-06-18 12:09:24 +0200195 # contains created tasks/futures to be able to cancel
bravof922c4172020-11-24 21:21:43 -0300196 self.lcm_tasks = TaskRegistry(self.worker_id, self.logger)
kuused124bfe2019-06-18 12:09:24 +0200197
tierno22f4f9c2018-06-11 18:53:39 +0200198 async def check_RO_version(self):
tiernoe64f7fb2019-09-11 08:55:52 +0000199 tries = 14
200 last_error = None
201 while True:
Luis Vegaa27dc532022-11-11 20:10:49 +0000202 ro_uri = self.main_config.RO.uri
203 if not ro_uri:
204 ro_uri = ""
tiernoe64f7fb2019-09-11 08:55:52 +0000205 try:
tierno2357f4e2020-10-19 16:38:59 +0000206 # try new RO, if fail old RO
207 try:
Luis Vegaa27dc532022-11-11 20:10:49 +0000208 self.main_config.RO.uri = ro_uri + "ro"
209 ro_server = NgRoClient(self.loop, **self.main_config.RO.to_dict())
tierno2357f4e2020-10-19 16:38:59 +0000210 ro_version = await ro_server.get_version()
Luis Vegaa27dc532022-11-11 20:10:49 +0000211 self.main_config.RO.ng = True
tierno2357f4e2020-10-19 16:38:59 +0000212 except Exception:
Luis Vegaa27dc532022-11-11 20:10:49 +0000213 self.main_config.RO.uri = ro_uri + "openmano"
214 ro_server = ROClient(self.loop, **self.main_config.RO.to_dict())
tierno2357f4e2020-10-19 16:38:59 +0000215 ro_version = await ro_server.get_version()
Luis Vegaa27dc532022-11-11 20:10:49 +0000216 self.main_config.RO.ng = False
tiernoe64f7fb2019-09-11 08:55:52 +0000217 if versiontuple(ro_version) < versiontuple(min_RO_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100218 raise LcmException(
219 "Not compatible osm/RO version '{}'. Needed '{}' or higher".format(
220 ro_version, min_RO_version
221 )
222 )
223 self.logger.info(
224 "Connected to RO version {} new-generation version {}".format(
Luis Vegaa27dc532022-11-11 20:10:49 +0000225 ro_version, self.main_config.RO.ng
garciadeblas5697b8b2021-03-24 09:17:02 +0100226 )
227 )
tiernoe64f7fb2019-09-11 08:55:52 +0000228 return
tierno69f0d382020-05-07 13:08:09 +0000229 except (ROClientException, NgRoException) as e:
Luis Vegaa27dc532022-11-11 20:10:49 +0000230 self.main_config.RO.uri = ro_uri
tiernoe64f7fb2019-09-11 08:55:52 +0000231 tries -= 1
bravof922c4172020-11-24 21:21:43 -0300232 traceback.print_tb(e.__traceback__)
garciadeblas5697b8b2021-03-24 09:17:02 +0100233 error_text = "Error while connecting to RO on {}: {}".format(
Luis Vegaa27dc532022-11-11 20:10:49 +0000234 self.main_config.RO.uri, e
garciadeblas5697b8b2021-03-24 09:17:02 +0100235 )
tiernoe64f7fb2019-09-11 08:55:52 +0000236 if tries <= 0:
237 self.logger.critical(error_text)
238 raise LcmException(error_text)
239 if last_error != error_text:
240 last_error = error_text
garciadeblas5697b8b2021-03-24 09:17:02 +0100241 self.logger.error(
242 error_text + ". Waiting until {} seconds".format(5 * tries)
243 )
tiernoe64f7fb2019-09-11 08:55:52 +0000244 await asyncio.sleep(5)
tierno22f4f9c2018-06-11 18:53:39 +0200245
tiernoc0e42e22018-05-11 11:36:10 +0200246 async def test(self, param=None):
247 self.logger.debug("Starting/Ending test task: {}".format(param))
248
tiernoc0e42e22018-05-11 11:36:10 +0200249 async def kafka_ping(self):
250 self.logger.debug("Task kafka_ping Enter")
251 consecutive_errors = 0
252 first_start = True
253 kafka_has_received = False
254 self.pings_not_received = 1
255 while True:
256 try:
tierno16427352019-04-22 11:37:36 +0000257 await self.msg_admin.aiowrite(
garciadeblas5697b8b2021-03-24 09:17:02 +0100258 "admin",
259 "ping",
260 {
261 "from": "lcm",
262 "to": "lcm",
263 "worker_id": self.worker_id,
264 "version": lcm_version,
265 },
266 self.loop,
267 )
tiernoc0e42e22018-05-11 11:36:10 +0200268 # time between pings are low when it is not received and at starting
garciadeblas5697b8b2021-03-24 09:17:02 +0100269 wait_time = (
270 self.ping_interval_boot
271 if not kafka_has_received
272 else self.ping_interval_pace
273 )
tiernoc0e42e22018-05-11 11:36:10 +0200274 if not self.pings_not_received:
275 kafka_has_received = True
276 self.pings_not_received += 1
277 await asyncio.sleep(wait_time, loop=self.loop)
278 if self.pings_not_received > 10:
279 raise LcmException("It is not receiving pings from Kafka bus")
280 consecutive_errors = 0
281 first_start = False
282 except LcmException:
283 raise
284 except Exception as e:
285 # if not first_start is the first time after starting. So leave more time and wait
286 # to allow kafka starts
287 if consecutive_errors == 8 if not first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100288 self.logger.error(
289 "Task kafka_read task exit error too many errors. Exception: {}".format(
290 e
291 )
292 )
tiernoc0e42e22018-05-11 11:36:10 +0200293 raise
294 consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100295 self.logger.error(
296 "Task kafka_read retrying after Exception {}".format(e)
297 )
tierno16427352019-04-22 11:37:36 +0000298 wait_time = 2 if not first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200299 await asyncio.sleep(wait_time, loop=self.loop)
300
gcalvinoed7f6d42018-12-14 14:44:56 +0100301 def kafka_read_callback(self, topic, command, params):
302 order_id = 1
303
304 if topic != "admin" and command != "ping":
garciadeblas5697b8b2021-03-24 09:17:02 +0100305 self.logger.debug(
306 "Task kafka_read receives {} {}: {}".format(topic, command, params)
307 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100308 self.consecutive_errors = 0
309 self.first_start = False
310 order_id += 1
311 if command == "exit":
312 raise LcmExceptionExit
313 elif command.startswith("#"):
314 return
315 elif command == "echo":
316 # just for test
317 print(params)
318 sys.stdout.flush()
319 return
320 elif command == "test":
321 asyncio.Task(self.test(params), loop=self.loop)
322 return
323
324 if topic == "admin":
325 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
tierno16427352019-04-22 11:37:36 +0000326 if params.get("worker_id") != self.worker_id:
327 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100328 self.pings_not_received = 0
tierno3e359b12019-02-03 02:29:13 +0100329 try:
aticig56b86c22022-06-29 10:43:05 +0300330 with open(self.health_check_file, "w") as f:
tierno3e359b12019-02-03 02:29:13 +0100331 f.write(str(time()))
332 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100333 self.logger.error(
334 "Cannot write into '{}' for healthcheck: {}".format(
aticig56b86c22022-06-29 10:43:05 +0300335 self.health_check_file, e
garciadeblas5697b8b2021-03-24 09:17:02 +0100336 )
337 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100338 return
magnussonle9198bb2020-01-21 13:00:51 +0100339 elif topic == "pla":
340 if command == "placement":
341 self.ns.update_nsrs_with_pla_result(params)
342 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100343 elif topic == "k8scluster":
344 if command == "create" or command == "created":
345 k8scluster_id = params.get("_id")
346 task = asyncio.ensure_future(self.k8scluster.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100347 self.lcm_tasks.register(
348 "k8scluster", k8scluster_id, order_id, "k8scluster_create", task
349 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100350 return
351 elif command == "delete" or command == "deleted":
352 k8scluster_id = params.get("_id")
353 task = asyncio.ensure_future(self.k8scluster.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100354 self.lcm_tasks.register(
355 "k8scluster", k8scluster_id, order_id, "k8scluster_delete", task
356 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100357 return
David Garciac1fe90a2021-03-31 19:12:02 +0200358 elif topic == "vca":
359 if command == "create" or command == "created":
360 vca_id = params.get("_id")
361 task = asyncio.ensure_future(self.vca.create(params, order_id))
362 self.lcm_tasks.register("vca", vca_id, order_id, "vca_create", task)
363 return
Dario Faccin8e53c6d2023-01-10 10:38:41 +0000364 elif command == "edit" or command == "edited":
365 vca_id = params.get("_id")
366 task = asyncio.ensure_future(self.vca.edit(params, order_id))
367 self.lcm_tasks.register("vca", vca_id, order_id, "vca_edit", task)
368 return
David Garciac1fe90a2021-03-31 19:12:02 +0200369 elif command == "delete" or command == "deleted":
370 vca_id = params.get("_id")
371 task = asyncio.ensure_future(self.vca.delete(params, order_id))
372 self.lcm_tasks.register("vca", vca_id, order_id, "vca_delete", task)
373 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100374 elif topic == "k8srepo":
375 if command == "create" or command == "created":
376 k8srepo_id = params.get("_id")
377 self.logger.debug("k8srepo_id = {}".format(k8srepo_id))
378 task = asyncio.ensure_future(self.k8srepo.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100379 self.lcm_tasks.register(
380 "k8srepo", k8srepo_id, order_id, "k8srepo_create", task
381 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100382 return
383 elif command == "delete" or command == "deleted":
384 k8srepo_id = params.get("_id")
385 task = asyncio.ensure_future(self.k8srepo.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100386 self.lcm_tasks.register(
387 "k8srepo", k8srepo_id, order_id, "k8srepo_delete", task
388 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100389 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100390 elif topic == "ns":
tierno307425f2020-01-26 23:35:59 +0000391 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100392 # self.logger.debug("Deploying NS {}".format(nsr_id))
393 nslcmop = params
394 nslcmop_id = nslcmop["_id"]
395 nsr_id = nslcmop["nsInstanceId"]
396 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100397 self.lcm_tasks.register(
398 "ns", nsr_id, nslcmop_id, "ns_instantiate", task
399 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100400 return
tierno307425f2020-01-26 23:35:59 +0000401 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100402 # self.logger.debug("Deleting NS {}".format(nsr_id))
403 nslcmop = params
404 nslcmop_id = nslcmop["_id"]
405 nsr_id = nslcmop["nsInstanceId"]
406 self.lcm_tasks.cancel(topic, nsr_id)
407 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
408 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
409 return
ksaikiranr3fde2c72021-03-15 10:39:06 +0530410 elif command == "vca_status_refresh":
411 nslcmop = params
412 nslcmop_id = nslcmop["_id"]
413 nsr_id = nslcmop["nsInstanceId"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100414 task = asyncio.ensure_future(
415 self.ns.vca_status_refresh(nsr_id, nslcmop_id)
416 )
417 self.lcm_tasks.register(
418 "ns", nsr_id, nslcmop_id, "ns_vca_status_refresh", task
419 )
ksaikiranr3fde2c72021-03-15 10:39:06 +0530420 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100421 elif command == "action":
422 # self.logger.debug("Update NS {}".format(nsr_id))
423 nslcmop = params
424 nslcmop_id = nslcmop["_id"]
425 nsr_id = nslcmop["nsInstanceId"]
426 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
427 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
428 return
aticigdffa6212022-04-12 15:27:53 +0300429 elif command == "update":
430 # self.logger.debug("Update NS {}".format(nsr_id))
431 nslcmop = params
432 nslcmop_id = nslcmop["_id"]
433 nsr_id = nslcmop["nsInstanceId"]
434 task = asyncio.ensure_future(self.ns.update(nsr_id, nslcmop_id))
435 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_update", task)
436 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100437 elif command == "scale":
438 # self.logger.debug("Update NS {}".format(nsr_id))
439 nslcmop = params
440 nslcmop_id = nslcmop["_id"]
441 nsr_id = nslcmop["nsInstanceId"]
442 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
443 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
444 return
garciadeblas07f4e4c2022-06-09 09:42:58 +0200445 elif command == "heal":
446 # self.logger.debug("Healing NS {}".format(nsr_id))
447 nslcmop = params
448 nslcmop_id = nslcmop["_id"]
449 nsr_id = nslcmop["nsInstanceId"]
450 task = asyncio.ensure_future(self.ns.heal(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000451 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_heal", task)
garciadeblas07f4e4c2022-06-09 09:42:58 +0200452 return
elumalai80bcf1c2022-04-28 18:05:01 +0530453 elif command == "migrate":
454 nslcmop = params
455 nslcmop_id = nslcmop["_id"]
456 nsr_id = nslcmop["nsInstanceId"]
457 task = asyncio.ensure_future(self.ns.migrate(nsr_id, nslcmop_id))
458 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_migrate", task)
459 return
govindarajul4ff4b512022-05-02 20:02:41 +0530460 elif command == "verticalscale":
461 nslcmop = params
462 nslcmop_id = nslcmop["_id"]
463 nsr_id = nslcmop["nsInstanceId"]
464 task = asyncio.ensure_future(self.ns.vertical_scale(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000465 self.logger.debug(
466 "nsr_id,nslcmop_id,task {},{},{}".format(nsr_id, nslcmop_id, task)
467 )
468 self.lcm_tasks.register(
469 "ns", nsr_id, nslcmop_id, "ns_verticalscale", task
470 )
471 self.logger.debug(
472 "LCM task registered {},{},{} ".format(nsr_id, nslcmop_id, task)
473 )
govindarajul4ff4b512022-05-02 20:02:41 +0530474 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100475 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000476 nsr_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100477 try:
478 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100479 print(
480 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
481 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
482 "".format(
483 nsr_id,
484 db_nsr["operational-status"],
485 db_nsr["config-status"],
486 db_nsr["detailed-status"],
487 db_nsr["_admin"]["deployed"],
Gabriel Cuba411af2e2023-01-06 17:23:22 -0500488 self.lcm_tasks.task_registry["ns"].get(nsr_id, ""),
garciadeblas5697b8b2021-03-24 09:17:02 +0100489 )
490 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100491 except Exception as e:
492 print("nsr {} not found: {}".format(nsr_id, e))
493 sys.stdout.flush()
494 return
495 elif command == "deleted":
496 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100497 elif command in (
elumalaica7ece02022-04-12 12:47:32 +0530498 "vnf_terminated",
elumalaib9e357c2022-04-27 09:58:38 +0530499 "policy_updated",
garciadeblas5697b8b2021-03-24 09:17:02 +0100500 "terminated",
501 "instantiated",
502 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200503 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100504 "actioned",
aticigdffa6212022-04-12 15:27:53 +0300505 "updated",
elumalai80bcf1c2022-04-28 18:05:01 +0530506 "migrated",
govindarajul4ff4b512022-05-02 20:02:41 +0530507 "verticalscaled",
garciadeblas5697b8b2021-03-24 09:17:02 +0100508 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100509 return
elumalaica7ece02022-04-12 12:47:32 +0530510
gcalvinoed7f6d42018-12-14 14:44:56 +0100511 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
tierno307425f2020-01-26 23:35:59 +0000512 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100513 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
514 nsilcmop = params
515 nsilcmop_id = nsilcmop["_id"] # slice operation id
516 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
garciadeblas5697b8b2021-03-24 09:17:02 +0100517 task = asyncio.ensure_future(
518 self.netslice.instantiate(nsir_id, nsilcmop_id)
519 )
520 self.lcm_tasks.register(
521 "nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task
522 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100523 return
tierno307425f2020-01-26 23:35:59 +0000524 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100525 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
526 nsilcmop = params
527 nsilcmop_id = nsilcmop["_id"] # slice operation id
528 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
529 self.lcm_tasks.cancel(topic, nsir_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100530 task = asyncio.ensure_future(
531 self.netslice.terminate(nsir_id, nsilcmop_id)
532 )
533 self.lcm_tasks.register(
534 "nsi", nsir_id, nsilcmop_id, "nsi_terminate", task
535 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100536 return
537 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000538 nsir_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100539 try:
540 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100541 print(
542 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
543 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
544 "".format(
545 nsir_id,
546 db_nsir["operational-status"],
547 db_nsir["config-status"],
548 db_nsir["detailed-status"],
549 db_nsir["_admin"]["deployed"],
Gabriel Cuba411af2e2023-01-06 17:23:22 -0500550 self.lcm_tasks.task_registry["nsi"].get(nsir_id, ""),
garciadeblas5697b8b2021-03-24 09:17:02 +0100551 )
552 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100553 except Exception as e:
554 print("nsir {} not found: {}".format(nsir_id, e))
555 sys.stdout.flush()
556 return
557 elif command == "deleted":
558 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100559 elif command in (
560 "terminated",
561 "instantiated",
562 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200563 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100564 "actioned",
565 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100566 return
567 elif topic == "vim_account":
568 vim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000569 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000570 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000571 task = asyncio.ensure_future(self.vim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100572 self.lcm_tasks.register(
573 "vim_account", vim_id, order_id, "vim_create", task
574 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100575 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100576 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100577 self.lcm_tasks.cancel(topic, vim_id)
kuuse6a470c62019-07-10 13:52:45 +0200578 task = asyncio.ensure_future(self.vim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100579 self.lcm_tasks.register(
580 "vim_account", vim_id, order_id, "vim_delete", task
581 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100582 return
583 elif command == "show":
584 print("not implemented show with vim_account")
585 sys.stdout.flush()
586 return
tiernof210c1c2019-10-16 09:09:58 +0000587 elif command in ("edit", "edited"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000588 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000589 task = asyncio.ensure_future(self.vim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100590 self.lcm_tasks.register(
591 "vim_account", vim_id, order_id, "vim_edit", task
592 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100593 return
tiernof210c1c2019-10-16 09:09:58 +0000594 elif command == "deleted":
595 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100596 elif topic == "wim_account":
597 wim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000598 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000599 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000600 task = asyncio.ensure_future(self.wim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100601 self.lcm_tasks.register(
602 "wim_account", wim_id, order_id, "wim_create", task
603 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100604 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100605 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100606 self.lcm_tasks.cancel(topic, wim_id)
kuuse6a470c62019-07-10 13:52:45 +0200607 task = asyncio.ensure_future(self.wim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100608 self.lcm_tasks.register(
609 "wim_account", wim_id, order_id, "wim_delete", task
610 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100611 return
612 elif command == "show":
613 print("not implemented show with wim_account")
614 sys.stdout.flush()
615 return
tiernof210c1c2019-10-16 09:09:58 +0000616 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100617 task = asyncio.ensure_future(self.wim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100618 self.lcm_tasks.register(
619 "wim_account", wim_id, order_id, "wim_edit", task
620 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100621 return
tiernof210c1c2019-10-16 09:09:58 +0000622 elif command == "deleted":
623 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100624 elif topic == "sdn":
625 _sdn_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000626 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000627 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000628 task = asyncio.ensure_future(self.sdn.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100629 self.lcm_tasks.register(
630 "sdn", _sdn_id, order_id, "sdn_create", task
631 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100632 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100633 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100634 self.lcm_tasks.cancel(topic, _sdn_id)
kuuse6a470c62019-07-10 13:52:45 +0200635 task = asyncio.ensure_future(self.sdn.delete(params, order_id))
gcalvinoed7f6d42018-12-14 14:44:56 +0100636 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
637 return
tiernof210c1c2019-10-16 09:09:58 +0000638 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100639 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
640 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
641 return
tiernof210c1c2019-10-16 09:09:58 +0000642 elif command == "deleted":
643 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100644 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
645
tiernoc0e42e22018-05-11 11:36:10 +0200646 async def kafka_read(self):
garciadeblas5697b8b2021-03-24 09:17:02 +0100647 self.logger.debug(
648 "Task kafka_read Enter with worker_id={}".format(self.worker_id)
649 )
tiernoc0e42e22018-05-11 11:36:10 +0200650 # future = asyncio.Future()
gcalvinoed7f6d42018-12-14 14:44:56 +0100651 self.consecutive_errors = 0
652 self.first_start = True
653 while self.consecutive_errors < 10:
tiernoc0e42e22018-05-11 11:36:10 +0200654 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100655 topics = (
656 "ns",
657 "vim_account",
658 "wim_account",
659 "sdn",
660 "nsi",
661 "k8scluster",
662 "vca",
663 "k8srepo",
664 "pla",
665 )
666 topics_admin = ("admin",)
tierno16427352019-04-22 11:37:36 +0000667 await asyncio.gather(
garciadeblas5697b8b2021-03-24 09:17:02 +0100668 self.msg.aioread(
669 topics, self.loop, self.kafka_read_callback, from_beginning=True
670 ),
671 self.msg_admin.aioread(
672 topics_admin,
673 self.loop,
674 self.kafka_read_callback,
675 group_id=False,
676 ),
tierno16427352019-04-22 11:37:36 +0000677 )
tiernoc0e42e22018-05-11 11:36:10 +0200678
gcalvinoed7f6d42018-12-14 14:44:56 +0100679 except LcmExceptionExit:
680 self.logger.debug("Bye!")
681 break
tiernoc0e42e22018-05-11 11:36:10 +0200682 except Exception as e:
683 # if not first_start is the first time after starting. So leave more time and wait
684 # to allow kafka starts
gcalvinoed7f6d42018-12-14 14:44:56 +0100685 if self.consecutive_errors == 8 if not self.first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100686 self.logger.error(
687 "Task kafka_read task exit error too many errors. Exception: {}".format(
688 e
689 )
690 )
tiernoc0e42e22018-05-11 11:36:10 +0200691 raise
gcalvinoed7f6d42018-12-14 14:44:56 +0100692 self.consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100693 self.logger.error(
694 "Task kafka_read retrying after Exception {}".format(e)
695 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100696 wait_time = 2 if not self.first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200697 await asyncio.sleep(wait_time, loop=self.loop)
698
699 # self.logger.debug("Task kafka_read terminating")
700 self.logger.debug("Task kafka_read exit")
701
702 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200703
704 # check RO version
705 self.loop.run_until_complete(self.check_RO_version())
706
Luis Vegaa27dc532022-11-11 20:10:49 +0000707 self.ns = ns.NsLcm(self.msg, self.lcm_tasks, self.main_config, self.loop)
708 # TODO: modify the rest of classes to use the LcmCfg object instead of dicts
garciadeblas5697b8b2021-03-24 09:17:02 +0100709 self.netslice = netslice.NetsliceLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000710 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop, self.ns
garciadeblas5697b8b2021-03-24 09:17:02 +0100711 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000712 self.vim = vim_sdn.VimLcm(
713 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
714 )
715 self.wim = vim_sdn.WimLcm(
716 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
717 )
718 self.sdn = vim_sdn.SdnLcm(
719 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
720 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100721 self.k8scluster = vim_sdn.K8sClusterLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000722 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100723 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000724 self.vca = vim_sdn.VcaLcm(
725 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
726 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100727 self.k8srepo = vim_sdn.K8sRepoLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000728 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100729 )
tierno2357f4e2020-10-19 16:38:59 +0000730
garciadeblas5697b8b2021-03-24 09:17:02 +0100731 self.loop.run_until_complete(
732 asyncio.gather(self.kafka_read(), self.kafka_ping())
733 )
bravof73bac502021-05-11 07:38:47 -0400734
tiernoc0e42e22018-05-11 11:36:10 +0200735 # TODO
736 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200737 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200738 # timeout = 200
739 # while self.is_pending_tasks():
740 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
741 # await asyncio.sleep(2, loop=self.loop)
742 # timeout -= 2
743 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200744 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200745 self.loop.close()
746 self.loop = None
747 if self.db:
748 self.db.db_disconnect()
749 if self.msg:
750 self.msg.disconnect()
tierno16427352019-04-22 11:37:36 +0000751 if self.msg_admin:
752 self.msg_admin.disconnect()
tiernoc0e42e22018-05-11 11:36:10 +0200753 if self.fs:
754 self.fs.fs_disconnect()
755
tiernoc0e42e22018-05-11 11:36:10 +0200756 def read_config_file(self, config_file):
tiernoc0e42e22018-05-11 11:36:10 +0200757 try:
Gabriel Cubaa89a5a72022-11-26 18:55:15 -0500758 with open(config_file) as f:
759 return yaml.safe_load(f)
tiernoc0e42e22018-05-11 11:36:10 +0200760 except Exception as e:
761 self.logger.critical("At config file '{}': {}".format(config_file, e))
Gabriel Cubaa89a5a72022-11-26 18:55:15 -0500762 exit(1)
tiernoc0e42e22018-05-11 11:36:10 +0200763
tierno16427352019-04-22 11:37:36 +0000764 @staticmethod
765 def get_process_id():
766 """
767 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
768 will provide a random one
769 :return: Obtained ID
770 """
771 # Try getting docker id. If fails, get pid
772 try:
773 with open("/proc/self/cgroup", "r") as f:
774 text_id_ = f.readline()
775 _, _, text_id = text_id_.rpartition("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100776 text_id = text_id.replace("\n", "")[:12]
tierno16427352019-04-22 11:37:36 +0000777 if text_id:
778 return text_id
779 except Exception:
780 pass
781 # Return a random id
garciadeblas5697b8b2021-03-24 09:17:02 +0100782 return "".join(random_choice("0123456789abcdef") for _ in range(12))
tierno16427352019-04-22 11:37:36 +0000783
tiernoc0e42e22018-05-11 11:36:10 +0200784
tierno275411e2018-05-16 14:33:32 +0200785def usage():
garciadeblas5697b8b2021-03-24 09:17:02 +0100786 print(
787 """Usage: {} [options]
quilesj7e13aeb2019-10-08 13:34:55 +0200788 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200789 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200790 -h|--help: shows this help
garciadeblas5697b8b2021-03-24 09:17:02 +0100791 """.format(
792 sys.argv[0]
793 )
794 )
tierno750b2452018-05-17 16:39:29 +0200795 # --log-socket-host HOST: send logs to this host")
796 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200797
798
garciadeblas5697b8b2021-03-24 09:17:02 +0100799if __name__ == "__main__":
quilesj7e13aeb2019-10-08 13:34:55 +0200800
tierno275411e2018-05-16 14:33:32 +0200801 try:
tierno8c16b052020-02-05 15:08:32 +0000802 # print("SYS.PATH='{}'".format(sys.path))
tierno275411e2018-05-16 14:33:32 +0200803 # load parameters and configuration
quilesj7e13aeb2019-10-08 13:34:55 +0200804 # -h
805 # -c value
806 # --config value
807 # --help
808 # --health-check
garciadeblas5697b8b2021-03-24 09:17:02 +0100809 opts, args = getopt.getopt(
810 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
811 )
tierno275411e2018-05-16 14:33:32 +0200812 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
813 config_file = None
814 for o, a in opts:
815 if o in ("-h", "--help"):
816 usage()
817 sys.exit()
818 elif o in ("-c", "--config"):
819 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200820 elif o == "--health-check":
tierno94f06112020-02-11 12:38:19 +0000821 from osm_lcm.lcm_hc import health_check
garciadeblas5697b8b2021-03-24 09:17:02 +0100822
aticig56b86c22022-06-29 10:43:05 +0300823 health_check(config_file, Lcm.ping_interval_pace)
tierno275411e2018-05-16 14:33:32 +0200824 # elif o == "--log-socket-port":
825 # log_socket_port = a
826 # elif o == "--log-socket-host":
827 # log_socket_host = a
828 # elif o == "--log-file":
829 # log_file = a
830 else:
831 assert False, "Unhandled option"
quilesj7e13aeb2019-10-08 13:34:55 +0200832
tierno275411e2018-05-16 14:33:32 +0200833 if config_file:
834 if not path.isfile(config_file):
garciadeblas5697b8b2021-03-24 09:17:02 +0100835 print(
836 "configuration file '{}' does not exist".format(config_file),
837 file=sys.stderr,
838 )
tierno275411e2018-05-16 14:33:32 +0200839 exit(1)
840 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100841 for config_file in (
842 __file__[: __file__.rfind(".")] + ".cfg",
843 "./lcm.cfg",
844 "/etc/osm/lcm.cfg",
845 ):
tierno275411e2018-05-16 14:33:32 +0200846 if path.isfile(config_file):
847 break
848 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100849 print(
850 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
851 file=sys.stderr,
852 )
tierno275411e2018-05-16 14:33:32 +0200853 exit(1)
854 lcm = Lcm(config_file)
tierno3e359b12019-02-03 02:29:13 +0100855 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200856 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200857 print(str(e), file=sys.stderr)
858 # usage()
859 exit(1)