blob: e6c4e19761db3138966409d9f6f33fff68061a10 [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
364 elif command == "delete" or command == "deleted":
365 vca_id = params.get("_id")
366 task = asyncio.ensure_future(self.vca.delete(params, order_id))
367 self.lcm_tasks.register("vca", vca_id, order_id, "vca_delete", task)
368 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100369 elif topic == "k8srepo":
370 if command == "create" or command == "created":
371 k8srepo_id = params.get("_id")
372 self.logger.debug("k8srepo_id = {}".format(k8srepo_id))
373 task = asyncio.ensure_future(self.k8srepo.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100374 self.lcm_tasks.register(
375 "k8srepo", k8srepo_id, order_id, "k8srepo_create", task
376 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100377 return
378 elif command == "delete" or command == "deleted":
379 k8srepo_id = params.get("_id")
380 task = asyncio.ensure_future(self.k8srepo.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100381 self.lcm_tasks.register(
382 "k8srepo", k8srepo_id, order_id, "k8srepo_delete", task
383 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100384 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100385 elif topic == "ns":
tierno307425f2020-01-26 23:35:59 +0000386 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100387 # self.logger.debug("Deploying NS {}".format(nsr_id))
388 nslcmop = params
389 nslcmop_id = nslcmop["_id"]
390 nsr_id = nslcmop["nsInstanceId"]
391 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100392 self.lcm_tasks.register(
393 "ns", nsr_id, nslcmop_id, "ns_instantiate", task
394 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100395 return
tierno307425f2020-01-26 23:35:59 +0000396 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100397 # self.logger.debug("Deleting NS {}".format(nsr_id))
398 nslcmop = params
399 nslcmop_id = nslcmop["_id"]
400 nsr_id = nslcmop["nsInstanceId"]
401 self.lcm_tasks.cancel(topic, nsr_id)
402 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
403 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
404 return
ksaikiranr3fde2c72021-03-15 10:39:06 +0530405 elif command == "vca_status_refresh":
406 nslcmop = params
407 nslcmop_id = nslcmop["_id"]
408 nsr_id = nslcmop["nsInstanceId"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100409 task = asyncio.ensure_future(
410 self.ns.vca_status_refresh(nsr_id, nslcmop_id)
411 )
412 self.lcm_tasks.register(
413 "ns", nsr_id, nslcmop_id, "ns_vca_status_refresh", task
414 )
ksaikiranr3fde2c72021-03-15 10:39:06 +0530415 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100416 elif command == "action":
417 # self.logger.debug("Update NS {}".format(nsr_id))
418 nslcmop = params
419 nslcmop_id = nslcmop["_id"]
420 nsr_id = nslcmop["nsInstanceId"]
421 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
422 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
423 return
aticigdffa6212022-04-12 15:27:53 +0300424 elif command == "update":
425 # self.logger.debug("Update NS {}".format(nsr_id))
426 nslcmop = params
427 nslcmop_id = nslcmop["_id"]
428 nsr_id = nslcmop["nsInstanceId"]
429 task = asyncio.ensure_future(self.ns.update(nsr_id, nslcmop_id))
430 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_update", task)
431 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100432 elif command == "scale":
433 # self.logger.debug("Update NS {}".format(nsr_id))
434 nslcmop = params
435 nslcmop_id = nslcmop["_id"]
436 nsr_id = nslcmop["nsInstanceId"]
437 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
438 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
439 return
garciadeblas07f4e4c2022-06-09 09:42:58 +0200440 elif command == "heal":
441 # self.logger.debug("Healing NS {}".format(nsr_id))
442 nslcmop = params
443 nslcmop_id = nslcmop["_id"]
444 nsr_id = nslcmop["nsInstanceId"]
445 task = asyncio.ensure_future(self.ns.heal(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000446 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_heal", task)
garciadeblas07f4e4c2022-06-09 09:42:58 +0200447 return
elumalai80bcf1c2022-04-28 18:05:01 +0530448 elif command == "migrate":
449 nslcmop = params
450 nslcmop_id = nslcmop["_id"]
451 nsr_id = nslcmop["nsInstanceId"]
452 task = asyncio.ensure_future(self.ns.migrate(nsr_id, nslcmop_id))
453 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_migrate", task)
454 return
govindarajul4ff4b512022-05-02 20:02:41 +0530455 elif command == "verticalscale":
456 nslcmop = params
457 nslcmop_id = nslcmop["_id"]
458 nsr_id = nslcmop["nsInstanceId"]
459 task = asyncio.ensure_future(self.ns.vertical_scale(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000460 self.logger.debug(
461 "nsr_id,nslcmop_id,task {},{},{}".format(nsr_id, nslcmop_id, task)
462 )
463 self.lcm_tasks.register(
464 "ns", nsr_id, nslcmop_id, "ns_verticalscale", task
465 )
466 self.logger.debug(
467 "LCM task registered {},{},{} ".format(nsr_id, nslcmop_id, task)
468 )
govindarajul4ff4b512022-05-02 20:02:41 +0530469 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100470 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000471 nsr_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100472 try:
473 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100474 print(
475 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
476 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
477 "".format(
478 nsr_id,
479 db_nsr["operational-status"],
480 db_nsr["config-status"],
481 db_nsr["detailed-status"],
482 db_nsr["_admin"]["deployed"],
Gabriel Cuba411af2e2023-01-06 17:23:22 -0500483 self.lcm_tasks.task_registry["ns"].get(nsr_id, ""),
garciadeblas5697b8b2021-03-24 09:17:02 +0100484 )
485 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100486 except Exception as e:
487 print("nsr {} not found: {}".format(nsr_id, e))
488 sys.stdout.flush()
489 return
490 elif command == "deleted":
491 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100492 elif command in (
elumalaica7ece02022-04-12 12:47:32 +0530493 "vnf_terminated",
elumalaib9e357c2022-04-27 09:58:38 +0530494 "policy_updated",
garciadeblas5697b8b2021-03-24 09:17:02 +0100495 "terminated",
496 "instantiated",
497 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200498 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100499 "actioned",
aticigdffa6212022-04-12 15:27:53 +0300500 "updated",
elumalai80bcf1c2022-04-28 18:05:01 +0530501 "migrated",
govindarajul4ff4b512022-05-02 20:02:41 +0530502 "verticalscaled",
garciadeblas5697b8b2021-03-24 09:17:02 +0100503 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100504 return
elumalaica7ece02022-04-12 12:47:32 +0530505
gcalvinoed7f6d42018-12-14 14:44:56 +0100506 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
tierno307425f2020-01-26 23:35:59 +0000507 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100508 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
509 nsilcmop = params
510 nsilcmop_id = nsilcmop["_id"] # slice operation id
511 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
garciadeblas5697b8b2021-03-24 09:17:02 +0100512 task = asyncio.ensure_future(
513 self.netslice.instantiate(nsir_id, nsilcmop_id)
514 )
515 self.lcm_tasks.register(
516 "nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task
517 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100518 return
tierno307425f2020-01-26 23:35:59 +0000519 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100520 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
521 nsilcmop = params
522 nsilcmop_id = nsilcmop["_id"] # slice operation id
523 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
524 self.lcm_tasks.cancel(topic, nsir_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100525 task = asyncio.ensure_future(
526 self.netslice.terminate(nsir_id, nsilcmop_id)
527 )
528 self.lcm_tasks.register(
529 "nsi", nsir_id, nsilcmop_id, "nsi_terminate", task
530 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100531 return
532 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000533 nsir_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100534 try:
535 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100536 print(
537 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
538 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
539 "".format(
540 nsir_id,
541 db_nsir["operational-status"],
542 db_nsir["config-status"],
543 db_nsir["detailed-status"],
544 db_nsir["_admin"]["deployed"],
Gabriel Cuba411af2e2023-01-06 17:23:22 -0500545 self.lcm_tasks.task_registry["nsi"].get(nsir_id, ""),
garciadeblas5697b8b2021-03-24 09:17:02 +0100546 )
547 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100548 except Exception as e:
549 print("nsir {} not found: {}".format(nsir_id, e))
550 sys.stdout.flush()
551 return
552 elif command == "deleted":
553 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100554 elif command in (
555 "terminated",
556 "instantiated",
557 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200558 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100559 "actioned",
560 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100561 return
562 elif topic == "vim_account":
563 vim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000564 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000565 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000566 task = asyncio.ensure_future(self.vim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100567 self.lcm_tasks.register(
568 "vim_account", vim_id, order_id, "vim_create", task
569 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100570 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100571 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100572 self.lcm_tasks.cancel(topic, vim_id)
kuuse6a470c62019-07-10 13:52:45 +0200573 task = asyncio.ensure_future(self.vim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100574 self.lcm_tasks.register(
575 "vim_account", vim_id, order_id, "vim_delete", task
576 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100577 return
578 elif command == "show":
579 print("not implemented show with vim_account")
580 sys.stdout.flush()
581 return
tiernof210c1c2019-10-16 09:09:58 +0000582 elif command in ("edit", "edited"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000583 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000584 task = asyncio.ensure_future(self.vim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100585 self.lcm_tasks.register(
586 "vim_account", vim_id, order_id, "vim_edit", task
587 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100588 return
tiernof210c1c2019-10-16 09:09:58 +0000589 elif command == "deleted":
590 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100591 elif topic == "wim_account":
592 wim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000593 if command in ("create", "created"):
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.wim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100596 self.lcm_tasks.register(
597 "wim_account", wim_id, order_id, "wim_create", task
598 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100599 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100600 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100601 self.lcm_tasks.cancel(topic, wim_id)
kuuse6a470c62019-07-10 13:52:45 +0200602 task = asyncio.ensure_future(self.wim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100603 self.lcm_tasks.register(
604 "wim_account", wim_id, order_id, "wim_delete", task
605 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100606 return
607 elif command == "show":
608 print("not implemented show with wim_account")
609 sys.stdout.flush()
610 return
tiernof210c1c2019-10-16 09:09:58 +0000611 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100612 task = asyncio.ensure_future(self.wim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100613 self.lcm_tasks.register(
614 "wim_account", wim_id, order_id, "wim_edit", task
615 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100616 return
tiernof210c1c2019-10-16 09:09:58 +0000617 elif command == "deleted":
618 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100619 elif topic == "sdn":
620 _sdn_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000621 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000622 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000623 task = asyncio.ensure_future(self.sdn.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100624 self.lcm_tasks.register(
625 "sdn", _sdn_id, order_id, "sdn_create", task
626 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100627 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100628 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100629 self.lcm_tasks.cancel(topic, _sdn_id)
kuuse6a470c62019-07-10 13:52:45 +0200630 task = asyncio.ensure_future(self.sdn.delete(params, order_id))
gcalvinoed7f6d42018-12-14 14:44:56 +0100631 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
632 return
tiernof210c1c2019-10-16 09:09:58 +0000633 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100634 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
635 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
636 return
tiernof210c1c2019-10-16 09:09:58 +0000637 elif command == "deleted":
638 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100639 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
640
tiernoc0e42e22018-05-11 11:36:10 +0200641 async def kafka_read(self):
garciadeblas5697b8b2021-03-24 09:17:02 +0100642 self.logger.debug(
643 "Task kafka_read Enter with worker_id={}".format(self.worker_id)
644 )
tiernoc0e42e22018-05-11 11:36:10 +0200645 # future = asyncio.Future()
gcalvinoed7f6d42018-12-14 14:44:56 +0100646 self.consecutive_errors = 0
647 self.first_start = True
648 while self.consecutive_errors < 10:
tiernoc0e42e22018-05-11 11:36:10 +0200649 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100650 topics = (
651 "ns",
652 "vim_account",
653 "wim_account",
654 "sdn",
655 "nsi",
656 "k8scluster",
657 "vca",
658 "k8srepo",
659 "pla",
660 )
661 topics_admin = ("admin",)
tierno16427352019-04-22 11:37:36 +0000662 await asyncio.gather(
garciadeblas5697b8b2021-03-24 09:17:02 +0100663 self.msg.aioread(
664 topics, self.loop, self.kafka_read_callback, from_beginning=True
665 ),
666 self.msg_admin.aioread(
667 topics_admin,
668 self.loop,
669 self.kafka_read_callback,
670 group_id=False,
671 ),
tierno16427352019-04-22 11:37:36 +0000672 )
tiernoc0e42e22018-05-11 11:36:10 +0200673
gcalvinoed7f6d42018-12-14 14:44:56 +0100674 except LcmExceptionExit:
675 self.logger.debug("Bye!")
676 break
tiernoc0e42e22018-05-11 11:36:10 +0200677 except Exception as e:
678 # if not first_start is the first time after starting. So leave more time and wait
679 # to allow kafka starts
gcalvinoed7f6d42018-12-14 14:44:56 +0100680 if self.consecutive_errors == 8 if not self.first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100681 self.logger.error(
682 "Task kafka_read task exit error too many errors. Exception: {}".format(
683 e
684 )
685 )
tiernoc0e42e22018-05-11 11:36:10 +0200686 raise
gcalvinoed7f6d42018-12-14 14:44:56 +0100687 self.consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100688 self.logger.error(
689 "Task kafka_read retrying after Exception {}".format(e)
690 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100691 wait_time = 2 if not self.first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200692 await asyncio.sleep(wait_time, loop=self.loop)
693
694 # self.logger.debug("Task kafka_read terminating")
695 self.logger.debug("Task kafka_read exit")
696
697 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200698
699 # check RO version
700 self.loop.run_until_complete(self.check_RO_version())
701
Luis Vegaa27dc532022-11-11 20:10:49 +0000702 self.ns = ns.NsLcm(self.msg, self.lcm_tasks, self.main_config, self.loop)
703 # TODO: modify the rest of classes to use the LcmCfg object instead of dicts
garciadeblas5697b8b2021-03-24 09:17:02 +0100704 self.netslice = netslice.NetsliceLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000705 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop, self.ns
garciadeblas5697b8b2021-03-24 09:17:02 +0100706 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000707 self.vim = vim_sdn.VimLcm(
708 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
709 )
710 self.wim = vim_sdn.WimLcm(
711 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
712 )
713 self.sdn = vim_sdn.SdnLcm(
714 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
715 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100716 self.k8scluster = vim_sdn.K8sClusterLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000717 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100718 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000719 self.vca = vim_sdn.VcaLcm(
720 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
721 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100722 self.k8srepo = vim_sdn.K8sRepoLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000723 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100724 )
tierno2357f4e2020-10-19 16:38:59 +0000725
garciadeblas5697b8b2021-03-24 09:17:02 +0100726 self.loop.run_until_complete(
727 asyncio.gather(self.kafka_read(), self.kafka_ping())
728 )
bravof73bac502021-05-11 07:38:47 -0400729
tiernoc0e42e22018-05-11 11:36:10 +0200730 # TODO
731 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200732 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200733 # timeout = 200
734 # while self.is_pending_tasks():
735 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
736 # await asyncio.sleep(2, loop=self.loop)
737 # timeout -= 2
738 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200739 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200740 self.loop.close()
741 self.loop = None
742 if self.db:
743 self.db.db_disconnect()
744 if self.msg:
745 self.msg.disconnect()
tierno16427352019-04-22 11:37:36 +0000746 if self.msg_admin:
747 self.msg_admin.disconnect()
tiernoc0e42e22018-05-11 11:36:10 +0200748 if self.fs:
749 self.fs.fs_disconnect()
750
tiernoc0e42e22018-05-11 11:36:10 +0200751 def read_config_file(self, config_file):
tiernoc0e42e22018-05-11 11:36:10 +0200752 try:
Gabriel Cubaa89a5a72022-11-26 18:55:15 -0500753 with open(config_file) as f:
754 return yaml.safe_load(f)
tiernoc0e42e22018-05-11 11:36:10 +0200755 except Exception as e:
756 self.logger.critical("At config file '{}': {}".format(config_file, e))
Gabriel Cubaa89a5a72022-11-26 18:55:15 -0500757 exit(1)
tiernoc0e42e22018-05-11 11:36:10 +0200758
tierno16427352019-04-22 11:37:36 +0000759 @staticmethod
760 def get_process_id():
761 """
762 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
763 will provide a random one
764 :return: Obtained ID
765 """
766 # Try getting docker id. If fails, get pid
767 try:
768 with open("/proc/self/cgroup", "r") as f:
769 text_id_ = f.readline()
770 _, _, text_id = text_id_.rpartition("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100771 text_id = text_id.replace("\n", "")[:12]
tierno16427352019-04-22 11:37:36 +0000772 if text_id:
773 return text_id
774 except Exception:
775 pass
776 # Return a random id
garciadeblas5697b8b2021-03-24 09:17:02 +0100777 return "".join(random_choice("0123456789abcdef") for _ in range(12))
tierno16427352019-04-22 11:37:36 +0000778
tiernoc0e42e22018-05-11 11:36:10 +0200779
tierno275411e2018-05-16 14:33:32 +0200780def usage():
garciadeblas5697b8b2021-03-24 09:17:02 +0100781 print(
782 """Usage: {} [options]
quilesj7e13aeb2019-10-08 13:34:55 +0200783 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200784 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200785 -h|--help: shows this help
garciadeblas5697b8b2021-03-24 09:17:02 +0100786 """.format(
787 sys.argv[0]
788 )
789 )
tierno750b2452018-05-17 16:39:29 +0200790 # --log-socket-host HOST: send logs to this host")
791 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200792
793
garciadeblas5697b8b2021-03-24 09:17:02 +0100794if __name__ == "__main__":
quilesj7e13aeb2019-10-08 13:34:55 +0200795
tierno275411e2018-05-16 14:33:32 +0200796 try:
tierno8c16b052020-02-05 15:08:32 +0000797 # print("SYS.PATH='{}'".format(sys.path))
tierno275411e2018-05-16 14:33:32 +0200798 # load parameters and configuration
quilesj7e13aeb2019-10-08 13:34:55 +0200799 # -h
800 # -c value
801 # --config value
802 # --help
803 # --health-check
garciadeblas5697b8b2021-03-24 09:17:02 +0100804 opts, args = getopt.getopt(
805 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
806 )
tierno275411e2018-05-16 14:33:32 +0200807 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
808 config_file = None
809 for o, a in opts:
810 if o in ("-h", "--help"):
811 usage()
812 sys.exit()
813 elif o in ("-c", "--config"):
814 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200815 elif o == "--health-check":
tierno94f06112020-02-11 12:38:19 +0000816 from osm_lcm.lcm_hc import health_check
garciadeblas5697b8b2021-03-24 09:17:02 +0100817
aticig56b86c22022-06-29 10:43:05 +0300818 health_check(config_file, Lcm.ping_interval_pace)
tierno275411e2018-05-16 14:33:32 +0200819 # elif o == "--log-socket-port":
820 # log_socket_port = a
821 # elif o == "--log-socket-host":
822 # log_socket_host = a
823 # elif o == "--log-file":
824 # log_file = a
825 else:
826 assert False, "Unhandled option"
quilesj7e13aeb2019-10-08 13:34:55 +0200827
tierno275411e2018-05-16 14:33:32 +0200828 if config_file:
829 if not path.isfile(config_file):
garciadeblas5697b8b2021-03-24 09:17:02 +0100830 print(
831 "configuration file '{}' does not exist".format(config_file),
832 file=sys.stderr,
833 )
tierno275411e2018-05-16 14:33:32 +0200834 exit(1)
835 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100836 for config_file in (
837 __file__[: __file__.rfind(".")] + ".cfg",
838 "./lcm.cfg",
839 "/etc/osm/lcm.cfg",
840 ):
tierno275411e2018-05-16 14:33:32 +0200841 if path.isfile(config_file):
842 break
843 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100844 print(
845 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
846 file=sys.stderr,
847 )
tierno275411e2018-05-16 14:33:32 +0200848 exit(1)
849 lcm = Lcm(config_file)
tierno3e359b12019-02-03 02:29:13 +0100850 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200851 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200852 print(str(e), file=sys.stderr)
853 # usage()
854 exit(1)