blob: 4f6f3a1ca5e8c91984fb08e48ccf837f9fc9c5f1 [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
350 elif command == "delete" or command == "deleted":
351 k8scluster_id = params.get("_id")
352 task = asyncio.ensure_future(self.k8scluster.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100353 self.lcm_tasks.register(
354 "k8scluster", k8scluster_id, order_id, "k8scluster_delete", task
355 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100356 return
David Garciac1fe90a2021-03-31 19:12:02 +0200357 elif topic == "vca":
358 if command == "create" or command == "created":
359 vca_id = params.get("_id")
360 task = asyncio.ensure_future(self.vca.create(params, order_id))
361 self.lcm_tasks.register("vca", vca_id, order_id, "vca_create", task)
362 return
363 elif command == "delete" or command == "deleted":
364 vca_id = params.get("_id")
365 task = asyncio.ensure_future(self.vca.delete(params, order_id))
366 self.lcm_tasks.register("vca", vca_id, order_id, "vca_delete", task)
367 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100368 elif topic == "k8srepo":
369 if command == "create" or command == "created":
370 k8srepo_id = params.get("_id")
371 self.logger.debug("k8srepo_id = {}".format(k8srepo_id))
372 task = asyncio.ensure_future(self.k8srepo.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100373 self.lcm_tasks.register(
374 "k8srepo", k8srepo_id, order_id, "k8srepo_create", task
375 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100376 return
377 elif command == "delete" or command == "deleted":
378 k8srepo_id = params.get("_id")
379 task = asyncio.ensure_future(self.k8srepo.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100380 self.lcm_tasks.register(
381 "k8srepo", k8srepo_id, order_id, "k8srepo_delete", task
382 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100383 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100384 elif topic == "ns":
tierno307425f2020-01-26 23:35:59 +0000385 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100386 # self.logger.debug("Deploying NS {}".format(nsr_id))
387 nslcmop = params
388 nslcmop_id = nslcmop["_id"]
389 nsr_id = nslcmop["nsInstanceId"]
390 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100391 self.lcm_tasks.register(
392 "ns", nsr_id, nslcmop_id, "ns_instantiate", task
393 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100394 return
tierno307425f2020-01-26 23:35:59 +0000395 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100396 # self.logger.debug("Deleting NS {}".format(nsr_id))
397 nslcmop = params
398 nslcmop_id = nslcmop["_id"]
399 nsr_id = nslcmop["nsInstanceId"]
400 self.lcm_tasks.cancel(topic, nsr_id)
401 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
402 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
403 return
ksaikiranr3fde2c72021-03-15 10:39:06 +0530404 elif command == "vca_status_refresh":
405 nslcmop = params
406 nslcmop_id = nslcmop["_id"]
407 nsr_id = nslcmop["nsInstanceId"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100408 task = asyncio.ensure_future(
409 self.ns.vca_status_refresh(nsr_id, nslcmop_id)
410 )
411 self.lcm_tasks.register(
412 "ns", nsr_id, nslcmop_id, "ns_vca_status_refresh", task
413 )
ksaikiranr3fde2c72021-03-15 10:39:06 +0530414 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100415 elif command == "action":
416 # self.logger.debug("Update NS {}".format(nsr_id))
417 nslcmop = params
418 nslcmop_id = nslcmop["_id"]
419 nsr_id = nslcmop["nsInstanceId"]
420 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
421 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
422 return
aticigdffa6212022-04-12 15:27:53 +0300423 elif command == "update":
424 # self.logger.debug("Update NS {}".format(nsr_id))
425 nslcmop = params
426 nslcmop_id = nslcmop["_id"]
427 nsr_id = nslcmop["nsInstanceId"]
428 task = asyncio.ensure_future(self.ns.update(nsr_id, nslcmop_id))
429 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_update", task)
430 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100431 elif command == "scale":
432 # self.logger.debug("Update NS {}".format(nsr_id))
433 nslcmop = params
434 nslcmop_id = nslcmop["_id"]
435 nsr_id = nslcmop["nsInstanceId"]
436 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
437 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
438 return
garciadeblas07f4e4c2022-06-09 09:42:58 +0200439 elif command == "heal":
440 # self.logger.debug("Healing NS {}".format(nsr_id))
441 nslcmop = params
442 nslcmop_id = nslcmop["_id"]
443 nsr_id = nslcmop["nsInstanceId"]
444 task = asyncio.ensure_future(self.ns.heal(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000445 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_heal", task)
garciadeblas07f4e4c2022-06-09 09:42:58 +0200446 return
elumalai80bcf1c2022-04-28 18:05:01 +0530447 elif command == "migrate":
448 nslcmop = params
449 nslcmop_id = nslcmop["_id"]
450 nsr_id = nslcmop["nsInstanceId"]
451 task = asyncio.ensure_future(self.ns.migrate(nsr_id, nslcmop_id))
452 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_migrate", task)
453 return
govindarajul4ff4b512022-05-02 20:02:41 +0530454 elif command == "verticalscale":
455 nslcmop = params
456 nslcmop_id = nslcmop["_id"]
457 nsr_id = nslcmop["nsInstanceId"]
458 task = asyncio.ensure_future(self.ns.vertical_scale(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000459 self.logger.debug(
460 "nsr_id,nslcmop_id,task {},{},{}".format(nsr_id, nslcmop_id, task)
461 )
462 self.lcm_tasks.register(
463 "ns", nsr_id, nslcmop_id, "ns_verticalscale", task
464 )
465 self.logger.debug(
466 "LCM task registered {},{},{} ".format(nsr_id, nslcmop_id, task)
467 )
govindarajul4ff4b512022-05-02 20:02:41 +0530468 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100469 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000470 nsr_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100471 try:
472 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100473 print(
474 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
475 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
476 "".format(
477 nsr_id,
478 db_nsr["operational-status"],
479 db_nsr["config-status"],
480 db_nsr["detailed-status"],
481 db_nsr["_admin"]["deployed"],
482 self.lcm_ns_tasks.get(nsr_id),
483 )
484 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100485 except Exception as e:
486 print("nsr {} not found: {}".format(nsr_id, e))
487 sys.stdout.flush()
488 return
489 elif command == "deleted":
490 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100491 elif command in (
elumalaica7ece02022-04-12 12:47:32 +0530492 "vnf_terminated",
elumalaib9e357c2022-04-27 09:58:38 +0530493 "policy_updated",
garciadeblas5697b8b2021-03-24 09:17:02 +0100494 "terminated",
495 "instantiated",
496 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200497 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100498 "actioned",
aticigdffa6212022-04-12 15:27:53 +0300499 "updated",
elumalai80bcf1c2022-04-28 18:05:01 +0530500 "migrated",
govindarajul4ff4b512022-05-02 20:02:41 +0530501 "verticalscaled",
garciadeblas5697b8b2021-03-24 09:17:02 +0100502 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100503 return
elumalaica7ece02022-04-12 12:47:32 +0530504
gcalvinoed7f6d42018-12-14 14:44:56 +0100505 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
tierno307425f2020-01-26 23:35:59 +0000506 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100507 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
508 nsilcmop = params
509 nsilcmop_id = nsilcmop["_id"] # slice operation id
510 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
garciadeblas5697b8b2021-03-24 09:17:02 +0100511 task = asyncio.ensure_future(
512 self.netslice.instantiate(nsir_id, nsilcmop_id)
513 )
514 self.lcm_tasks.register(
515 "nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task
516 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100517 return
tierno307425f2020-01-26 23:35:59 +0000518 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100519 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
520 nsilcmop = params
521 nsilcmop_id = nsilcmop["_id"] # slice operation id
522 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
523 self.lcm_tasks.cancel(topic, nsir_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100524 task = asyncio.ensure_future(
525 self.netslice.terminate(nsir_id, nsilcmop_id)
526 )
527 self.lcm_tasks.register(
528 "nsi", nsir_id, nsilcmop_id, "nsi_terminate", task
529 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100530 return
531 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000532 nsir_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100533 try:
534 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100535 print(
536 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
537 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
538 "".format(
539 nsir_id,
540 db_nsir["operational-status"],
541 db_nsir["config-status"],
542 db_nsir["detailed-status"],
543 db_nsir["_admin"]["deployed"],
544 self.lcm_netslice_tasks.get(nsir_id),
545 )
546 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100547 except Exception as e:
548 print("nsir {} not found: {}".format(nsir_id, e))
549 sys.stdout.flush()
550 return
551 elif command == "deleted":
552 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100553 elif command in (
554 "terminated",
555 "instantiated",
556 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200557 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100558 "actioned",
559 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100560 return
561 elif topic == "vim_account":
562 vim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000563 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000564 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000565 task = asyncio.ensure_future(self.vim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100566 self.lcm_tasks.register(
567 "vim_account", vim_id, order_id, "vim_create", task
568 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100569 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100570 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100571 self.lcm_tasks.cancel(topic, vim_id)
kuuse6a470c62019-07-10 13:52:45 +0200572 task = asyncio.ensure_future(self.vim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100573 self.lcm_tasks.register(
574 "vim_account", vim_id, order_id, "vim_delete", task
575 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100576 return
577 elif command == "show":
578 print("not implemented show with vim_account")
579 sys.stdout.flush()
580 return
tiernof210c1c2019-10-16 09:09:58 +0000581 elif command in ("edit", "edited"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000582 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000583 task = asyncio.ensure_future(self.vim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100584 self.lcm_tasks.register(
585 "vim_account", vim_id, order_id, "vim_edit", task
586 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100587 return
tiernof210c1c2019-10-16 09:09:58 +0000588 elif command == "deleted":
589 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100590 elif topic == "wim_account":
591 wim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000592 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000593 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000594 task = asyncio.ensure_future(self.wim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100595 self.lcm_tasks.register(
596 "wim_account", wim_id, order_id, "wim_create", task
597 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100598 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100599 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100600 self.lcm_tasks.cancel(topic, wim_id)
kuuse6a470c62019-07-10 13:52:45 +0200601 task = asyncio.ensure_future(self.wim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100602 self.lcm_tasks.register(
603 "wim_account", wim_id, order_id, "wim_delete", task
604 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100605 return
606 elif command == "show":
607 print("not implemented show with wim_account")
608 sys.stdout.flush()
609 return
tiernof210c1c2019-10-16 09:09:58 +0000610 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100611 task = asyncio.ensure_future(self.wim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100612 self.lcm_tasks.register(
613 "wim_account", wim_id, order_id, "wim_edit", task
614 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100615 return
tiernof210c1c2019-10-16 09:09:58 +0000616 elif command == "deleted":
617 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100618 elif topic == "sdn":
619 _sdn_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000620 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000621 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000622 task = asyncio.ensure_future(self.sdn.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100623 self.lcm_tasks.register(
624 "sdn", _sdn_id, order_id, "sdn_create", task
625 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100626 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100627 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100628 self.lcm_tasks.cancel(topic, _sdn_id)
kuuse6a470c62019-07-10 13:52:45 +0200629 task = asyncio.ensure_future(self.sdn.delete(params, order_id))
gcalvinoed7f6d42018-12-14 14:44:56 +0100630 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
631 return
tiernof210c1c2019-10-16 09:09:58 +0000632 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100633 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
634 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
635 return
tiernof210c1c2019-10-16 09:09:58 +0000636 elif command == "deleted":
637 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100638 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
639
tiernoc0e42e22018-05-11 11:36:10 +0200640 async def kafka_read(self):
garciadeblas5697b8b2021-03-24 09:17:02 +0100641 self.logger.debug(
642 "Task kafka_read Enter with worker_id={}".format(self.worker_id)
643 )
tiernoc0e42e22018-05-11 11:36:10 +0200644 # future = asyncio.Future()
gcalvinoed7f6d42018-12-14 14:44:56 +0100645 self.consecutive_errors = 0
646 self.first_start = True
647 while self.consecutive_errors < 10:
tiernoc0e42e22018-05-11 11:36:10 +0200648 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100649 topics = (
650 "ns",
651 "vim_account",
652 "wim_account",
653 "sdn",
654 "nsi",
655 "k8scluster",
656 "vca",
657 "k8srepo",
658 "pla",
659 )
660 topics_admin = ("admin",)
tierno16427352019-04-22 11:37:36 +0000661 await asyncio.gather(
garciadeblas5697b8b2021-03-24 09:17:02 +0100662 self.msg.aioread(
663 topics, self.loop, self.kafka_read_callback, from_beginning=True
664 ),
665 self.msg_admin.aioread(
666 topics_admin,
667 self.loop,
668 self.kafka_read_callback,
669 group_id=False,
670 ),
tierno16427352019-04-22 11:37:36 +0000671 )
tiernoc0e42e22018-05-11 11:36:10 +0200672
gcalvinoed7f6d42018-12-14 14:44:56 +0100673 except LcmExceptionExit:
674 self.logger.debug("Bye!")
675 break
tiernoc0e42e22018-05-11 11:36:10 +0200676 except Exception as e:
677 # if not first_start is the first time after starting. So leave more time and wait
678 # to allow kafka starts
gcalvinoed7f6d42018-12-14 14:44:56 +0100679 if self.consecutive_errors == 8 if not self.first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100680 self.logger.error(
681 "Task kafka_read task exit error too many errors. Exception: {}".format(
682 e
683 )
684 )
tiernoc0e42e22018-05-11 11:36:10 +0200685 raise
gcalvinoed7f6d42018-12-14 14:44:56 +0100686 self.consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100687 self.logger.error(
688 "Task kafka_read retrying after Exception {}".format(e)
689 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100690 wait_time = 2 if not self.first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200691 await asyncio.sleep(wait_time, loop=self.loop)
692
693 # self.logger.debug("Task kafka_read terminating")
694 self.logger.debug("Task kafka_read exit")
695
696 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200697 # check RO version
698 self.loop.run_until_complete(self.check_RO_version())
699
Luis Vegaa27dc532022-11-11 20:10:49 +0000700 self.ns = ns.NsLcm(self.msg, self.lcm_tasks, self.main_config, self.loop)
701 # TODO: modify the rest of classes to use the LcmCfg object instead of dicts
garciadeblas5697b8b2021-03-24 09:17:02 +0100702 self.netslice = netslice.NetsliceLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000703 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop, self.ns
garciadeblas5697b8b2021-03-24 09:17:02 +0100704 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000705 self.vim = vim_sdn.VimLcm(
706 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
707 )
708 self.wim = vim_sdn.WimLcm(
709 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
710 )
711 self.sdn = vim_sdn.SdnLcm(
712 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
713 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100714 self.k8scluster = vim_sdn.K8sClusterLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000715 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100716 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000717 self.vca = vim_sdn.VcaLcm(
718 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
719 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100720 self.k8srepo = vim_sdn.K8sRepoLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000721 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100722 )
tierno2357f4e2020-10-19 16:38:59 +0000723
garciadeblas5697b8b2021-03-24 09:17:02 +0100724 self.loop.run_until_complete(
725 asyncio.gather(self.kafka_read(), self.kafka_ping())
726 )
bravof73bac502021-05-11 07:38:47 -0400727
tiernoc0e42e22018-05-11 11:36:10 +0200728 # TODO
729 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200730 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200731 # timeout = 200
732 # while self.is_pending_tasks():
733 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
734 # await asyncio.sleep(2, loop=self.loop)
735 # timeout -= 2
736 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200737 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200738 self.loop.close()
739 self.loop = None
740 if self.db:
741 self.db.db_disconnect()
742 if self.msg:
743 self.msg.disconnect()
tierno16427352019-04-22 11:37:36 +0000744 if self.msg_admin:
745 self.msg_admin.disconnect()
tiernoc0e42e22018-05-11 11:36:10 +0200746 if self.fs:
747 self.fs.fs_disconnect()
748
tiernoc0e42e22018-05-11 11:36:10 +0200749 def read_config_file(self, config_file):
tiernoc0e42e22018-05-11 11:36:10 +0200750 try:
Gabriel Cuba53dee6b2022-11-26 18:55:15 -0500751 with open(config_file) as f:
752 return yaml.safe_load(f)
tiernoc0e42e22018-05-11 11:36:10 +0200753 except Exception as e:
754 self.logger.critical("At config file '{}': {}".format(config_file, e))
Gabriel Cuba53dee6b2022-11-26 18:55:15 -0500755 exit(1)
tiernoc0e42e22018-05-11 11:36:10 +0200756
tierno16427352019-04-22 11:37:36 +0000757 @staticmethod
758 def get_process_id():
759 """
760 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
761 will provide a random one
762 :return: Obtained ID
763 """
764 # Try getting docker id. If fails, get pid
765 try:
766 with open("/proc/self/cgroup", "r") as f:
767 text_id_ = f.readline()
768 _, _, text_id = text_id_.rpartition("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100769 text_id = text_id.replace("\n", "")[:12]
tierno16427352019-04-22 11:37:36 +0000770 if text_id:
771 return text_id
772 except Exception:
773 pass
774 # Return a random id
garciadeblas5697b8b2021-03-24 09:17:02 +0100775 return "".join(random_choice("0123456789abcdef") for _ in range(12))
tierno16427352019-04-22 11:37:36 +0000776
tiernoc0e42e22018-05-11 11:36:10 +0200777
tierno275411e2018-05-16 14:33:32 +0200778def usage():
garciadeblas5697b8b2021-03-24 09:17:02 +0100779 print(
780 """Usage: {} [options]
quilesj7e13aeb2019-10-08 13:34:55 +0200781 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200782 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200783 -h|--help: shows this help
garciadeblas5697b8b2021-03-24 09:17:02 +0100784 """.format(
785 sys.argv[0]
786 )
787 )
tierno750b2452018-05-17 16:39:29 +0200788 # --log-socket-host HOST: send logs to this host")
789 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200790
791
garciadeblas5697b8b2021-03-24 09:17:02 +0100792if __name__ == "__main__":
tierno275411e2018-05-16 14:33:32 +0200793 try:
tierno8c16b052020-02-05 15:08:32 +0000794 # print("SYS.PATH='{}'".format(sys.path))
tierno275411e2018-05-16 14:33:32 +0200795 # load parameters and configuration
quilesj7e13aeb2019-10-08 13:34:55 +0200796 # -h
797 # -c value
798 # --config value
799 # --help
800 # --health-check
garciadeblas5697b8b2021-03-24 09:17:02 +0100801 opts, args = getopt.getopt(
802 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
803 )
tierno275411e2018-05-16 14:33:32 +0200804 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
805 config_file = None
806 for o, a in opts:
807 if o in ("-h", "--help"):
808 usage()
809 sys.exit()
810 elif o in ("-c", "--config"):
811 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200812 elif o == "--health-check":
tierno94f06112020-02-11 12:38:19 +0000813 from osm_lcm.lcm_hc import health_check
garciadeblas5697b8b2021-03-24 09:17:02 +0100814
aticig56b86c22022-06-29 10:43:05 +0300815 health_check(config_file, Lcm.ping_interval_pace)
tierno275411e2018-05-16 14:33:32 +0200816 # elif o == "--log-socket-port":
817 # log_socket_port = a
818 # elif o == "--log-socket-host":
819 # log_socket_host = a
820 # elif o == "--log-file":
821 # log_file = a
822 else:
823 assert False, "Unhandled option"
quilesj7e13aeb2019-10-08 13:34:55 +0200824
tierno275411e2018-05-16 14:33:32 +0200825 if config_file:
826 if not path.isfile(config_file):
garciadeblas5697b8b2021-03-24 09:17:02 +0100827 print(
828 "configuration file '{}' does not exist".format(config_file),
829 file=sys.stderr,
830 )
tierno275411e2018-05-16 14:33:32 +0200831 exit(1)
832 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100833 for config_file in (
834 __file__[: __file__.rfind(".")] + ".cfg",
835 "./lcm.cfg",
836 "/etc/osm/lcm.cfg",
837 ):
tierno275411e2018-05-16 14:33:32 +0200838 if path.isfile(config_file):
839 break
840 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100841 print(
842 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
843 file=sys.stderr,
844 )
tierno275411e2018-05-16 14:33:32 +0200845 exit(1)
846 lcm = Lcm(config_file)
tierno3e359b12019-02-03 02:29:13 +0100847 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200848 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200849 print(str(e), file=sys.stderr)
850 # usage()
851 exit(1)