blob: 4bffba9396193c1fc641409e6645025ccec90608 [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
dariofaccin8bbeeb02023-01-23 18:13:27 +0100351 elif command == "edit" or command == "edited":
352 k8scluster_id = params.get("_id")
353 task = asyncio.ensure_future(self.k8scluster.edit(params, order_id))
354 self.lcm_tasks.register(
355 "k8scluster", k8scluster_id, order_id, "k8scluster_edit", task
356 )
357 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100358 elif command == "delete" or command == "deleted":
359 k8scluster_id = params.get("_id")
360 task = asyncio.ensure_future(self.k8scluster.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100361 self.lcm_tasks.register(
362 "k8scluster", k8scluster_id, order_id, "k8scluster_delete", task
363 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100364 return
David Garciac1fe90a2021-03-31 19:12:02 +0200365 elif topic == "vca":
366 if command == "create" or command == "created":
367 vca_id = params.get("_id")
368 task = asyncio.ensure_future(self.vca.create(params, order_id))
369 self.lcm_tasks.register("vca", vca_id, order_id, "vca_create", task)
370 return
Dario Faccin8e53c6d2023-01-10 10:38:41 +0000371 elif command == "edit" or command == "edited":
372 vca_id = params.get("_id")
373 task = asyncio.ensure_future(self.vca.edit(params, order_id))
374 self.lcm_tasks.register("vca", vca_id, order_id, "vca_edit", task)
375 return
David Garciac1fe90a2021-03-31 19:12:02 +0200376 elif command == "delete" or command == "deleted":
377 vca_id = params.get("_id")
378 task = asyncio.ensure_future(self.vca.delete(params, order_id))
379 self.lcm_tasks.register("vca", vca_id, order_id, "vca_delete", task)
380 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100381 elif topic == "k8srepo":
382 if command == "create" or command == "created":
383 k8srepo_id = params.get("_id")
384 self.logger.debug("k8srepo_id = {}".format(k8srepo_id))
385 task = asyncio.ensure_future(self.k8srepo.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100386 self.lcm_tasks.register(
387 "k8srepo", k8srepo_id, order_id, "k8srepo_create", task
388 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100389 return
390 elif command == "delete" or command == "deleted":
391 k8srepo_id = params.get("_id")
392 task = asyncio.ensure_future(self.k8srepo.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100393 self.lcm_tasks.register(
394 "k8srepo", k8srepo_id, order_id, "k8srepo_delete", task
395 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100396 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100397 elif topic == "ns":
tierno307425f2020-01-26 23:35:59 +0000398 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100399 # self.logger.debug("Deploying NS {}".format(nsr_id))
400 nslcmop = params
401 nslcmop_id = nslcmop["_id"]
402 nsr_id = nslcmop["nsInstanceId"]
403 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100404 self.lcm_tasks.register(
405 "ns", nsr_id, nslcmop_id, "ns_instantiate", task
406 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100407 return
tierno307425f2020-01-26 23:35:59 +0000408 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100409 # self.logger.debug("Deleting NS {}".format(nsr_id))
410 nslcmop = params
411 nslcmop_id = nslcmop["_id"]
412 nsr_id = nslcmop["nsInstanceId"]
413 self.lcm_tasks.cancel(topic, nsr_id)
414 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
415 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
416 return
ksaikiranr3fde2c72021-03-15 10:39:06 +0530417 elif command == "vca_status_refresh":
418 nslcmop = params
419 nslcmop_id = nslcmop["_id"]
420 nsr_id = nslcmop["nsInstanceId"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100421 task = asyncio.ensure_future(
422 self.ns.vca_status_refresh(nsr_id, nslcmop_id)
423 )
424 self.lcm_tasks.register(
425 "ns", nsr_id, nslcmop_id, "ns_vca_status_refresh", task
426 )
ksaikiranr3fde2c72021-03-15 10:39:06 +0530427 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100428 elif command == "action":
429 # self.logger.debug("Update NS {}".format(nsr_id))
430 nslcmop = params
431 nslcmop_id = nslcmop["_id"]
432 nsr_id = nslcmop["nsInstanceId"]
433 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
434 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
435 return
aticigdffa6212022-04-12 15:27:53 +0300436 elif command == "update":
437 # self.logger.debug("Update NS {}".format(nsr_id))
438 nslcmop = params
439 nslcmop_id = nslcmop["_id"]
440 nsr_id = nslcmop["nsInstanceId"]
441 task = asyncio.ensure_future(self.ns.update(nsr_id, nslcmop_id))
442 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_update", task)
443 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100444 elif command == "scale":
445 # self.logger.debug("Update NS {}".format(nsr_id))
446 nslcmop = params
447 nslcmop_id = nslcmop["_id"]
448 nsr_id = nslcmop["nsInstanceId"]
449 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
450 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
451 return
garciadeblas07f4e4c2022-06-09 09:42:58 +0200452 elif command == "heal":
453 # self.logger.debug("Healing NS {}".format(nsr_id))
454 nslcmop = params
455 nslcmop_id = nslcmop["_id"]
456 nsr_id = nslcmop["nsInstanceId"]
457 task = asyncio.ensure_future(self.ns.heal(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000458 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_heal", task)
garciadeblas07f4e4c2022-06-09 09:42:58 +0200459 return
elumalai80bcf1c2022-04-28 18:05:01 +0530460 elif command == "migrate":
461 nslcmop = params
462 nslcmop_id = nslcmop["_id"]
463 nsr_id = nslcmop["nsInstanceId"]
464 task = asyncio.ensure_future(self.ns.migrate(nsr_id, nslcmop_id))
465 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_migrate", task)
466 return
govindarajul4ff4b512022-05-02 20:02:41 +0530467 elif command == "verticalscale":
468 nslcmop = params
469 nslcmop_id = nslcmop["_id"]
470 nsr_id = nslcmop["nsInstanceId"]
471 task = asyncio.ensure_future(self.ns.vertical_scale(nsr_id, nslcmop_id))
preethika.p28b0bf82022-09-23 07:36:28 +0000472 self.logger.debug(
473 "nsr_id,nslcmop_id,task {},{},{}".format(nsr_id, nslcmop_id, task)
474 )
475 self.lcm_tasks.register(
476 "ns", nsr_id, nslcmop_id, "ns_verticalscale", task
477 )
478 self.logger.debug(
479 "LCM task registered {},{},{} ".format(nsr_id, nslcmop_id, task)
480 )
govindarajul4ff4b512022-05-02 20:02:41 +0530481 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100482 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000483 nsr_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100484 try:
485 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100486 print(
487 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
488 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
489 "".format(
490 nsr_id,
491 db_nsr["operational-status"],
492 db_nsr["config-status"],
493 db_nsr["detailed-status"],
494 db_nsr["_admin"]["deployed"],
Gabriel Cuba411af2e2023-01-06 17:23:22 -0500495 self.lcm_tasks.task_registry["ns"].get(nsr_id, ""),
garciadeblas5697b8b2021-03-24 09:17:02 +0100496 )
497 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100498 except Exception as e:
499 print("nsr {} not found: {}".format(nsr_id, e))
500 sys.stdout.flush()
501 return
502 elif command == "deleted":
503 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100504 elif command in (
elumalaica7ece02022-04-12 12:47:32 +0530505 "vnf_terminated",
elumalaib9e357c2022-04-27 09:58:38 +0530506 "policy_updated",
garciadeblas5697b8b2021-03-24 09:17:02 +0100507 "terminated",
508 "instantiated",
509 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200510 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100511 "actioned",
aticigdffa6212022-04-12 15:27:53 +0300512 "updated",
elumalai80bcf1c2022-04-28 18:05:01 +0530513 "migrated",
govindarajul4ff4b512022-05-02 20:02:41 +0530514 "verticalscaled",
garciadeblas5697b8b2021-03-24 09:17:02 +0100515 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100516 return
elumalaica7ece02022-04-12 12:47:32 +0530517
gcalvinoed7f6d42018-12-14 14:44:56 +0100518 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
tierno307425f2020-01-26 23:35:59 +0000519 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100520 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
521 nsilcmop = params
522 nsilcmop_id = nsilcmop["_id"] # slice operation id
523 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
garciadeblas5697b8b2021-03-24 09:17:02 +0100524 task = asyncio.ensure_future(
525 self.netslice.instantiate(nsir_id, nsilcmop_id)
526 )
527 self.lcm_tasks.register(
528 "nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task
529 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100530 return
tierno307425f2020-01-26 23:35:59 +0000531 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100532 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
533 nsilcmop = params
534 nsilcmop_id = nsilcmop["_id"] # slice operation id
535 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
536 self.lcm_tasks.cancel(topic, nsir_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100537 task = asyncio.ensure_future(
538 self.netslice.terminate(nsir_id, nsilcmop_id)
539 )
540 self.lcm_tasks.register(
541 "nsi", nsir_id, nsilcmop_id, "nsi_terminate", task
542 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100543 return
544 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000545 nsir_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100546 try:
547 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100548 print(
549 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
550 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
551 "".format(
552 nsir_id,
553 db_nsir["operational-status"],
554 db_nsir["config-status"],
555 db_nsir["detailed-status"],
556 db_nsir["_admin"]["deployed"],
Gabriel Cuba411af2e2023-01-06 17:23:22 -0500557 self.lcm_tasks.task_registry["nsi"].get(nsir_id, ""),
garciadeblas5697b8b2021-03-24 09:17:02 +0100558 )
559 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100560 except Exception as e:
561 print("nsir {} not found: {}".format(nsir_id, e))
562 sys.stdout.flush()
563 return
564 elif command == "deleted":
565 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100566 elif command in (
567 "terminated",
568 "instantiated",
569 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200570 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100571 "actioned",
572 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100573 return
574 elif topic == "vim_account":
575 vim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000576 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000577 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000578 task = asyncio.ensure_future(self.vim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100579 self.lcm_tasks.register(
580 "vim_account", vim_id, order_id, "vim_create", task
581 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100582 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100583 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100584 self.lcm_tasks.cancel(topic, vim_id)
kuuse6a470c62019-07-10 13:52:45 +0200585 task = asyncio.ensure_future(self.vim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100586 self.lcm_tasks.register(
587 "vim_account", vim_id, order_id, "vim_delete", task
588 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100589 return
590 elif command == "show":
591 print("not implemented show with vim_account")
592 sys.stdout.flush()
593 return
tiernof210c1c2019-10-16 09:09:58 +0000594 elif command in ("edit", "edited"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000595 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000596 task = asyncio.ensure_future(self.vim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100597 self.lcm_tasks.register(
598 "vim_account", vim_id, order_id, "vim_edit", task
599 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100600 return
tiernof210c1c2019-10-16 09:09:58 +0000601 elif command == "deleted":
602 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100603 elif topic == "wim_account":
604 wim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000605 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000606 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000607 task = asyncio.ensure_future(self.wim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100608 self.lcm_tasks.register(
609 "wim_account", wim_id, order_id, "wim_create", task
610 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100611 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100612 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100613 self.lcm_tasks.cancel(topic, wim_id)
kuuse6a470c62019-07-10 13:52:45 +0200614 task = asyncio.ensure_future(self.wim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100615 self.lcm_tasks.register(
616 "wim_account", wim_id, order_id, "wim_delete", task
617 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100618 return
619 elif command == "show":
620 print("not implemented show with wim_account")
621 sys.stdout.flush()
622 return
tiernof210c1c2019-10-16 09:09:58 +0000623 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100624 task = asyncio.ensure_future(self.wim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100625 self.lcm_tasks.register(
626 "wim_account", wim_id, order_id, "wim_edit", task
627 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100628 return
tiernof210c1c2019-10-16 09:09:58 +0000629 elif command == "deleted":
630 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100631 elif topic == "sdn":
632 _sdn_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000633 if command in ("create", "created"):
Luis Vegaa27dc532022-11-11 20:10:49 +0000634 if not self.main_config.RO.ng:
tierno2357f4e2020-10-19 16:38:59 +0000635 task = asyncio.ensure_future(self.sdn.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100636 self.lcm_tasks.register(
637 "sdn", _sdn_id, order_id, "sdn_create", task
638 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100639 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100640 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100641 self.lcm_tasks.cancel(topic, _sdn_id)
kuuse6a470c62019-07-10 13:52:45 +0200642 task = asyncio.ensure_future(self.sdn.delete(params, order_id))
gcalvinoed7f6d42018-12-14 14:44:56 +0100643 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
644 return
tiernof210c1c2019-10-16 09:09:58 +0000645 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100646 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
647 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
648 return
tiernof210c1c2019-10-16 09:09:58 +0000649 elif command == "deleted":
650 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100651 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
652
tiernoc0e42e22018-05-11 11:36:10 +0200653 async def kafka_read(self):
garciadeblas5697b8b2021-03-24 09:17:02 +0100654 self.logger.debug(
655 "Task kafka_read Enter with worker_id={}".format(self.worker_id)
656 )
tiernoc0e42e22018-05-11 11:36:10 +0200657 # future = asyncio.Future()
gcalvinoed7f6d42018-12-14 14:44:56 +0100658 self.consecutive_errors = 0
659 self.first_start = True
660 while self.consecutive_errors < 10:
tiernoc0e42e22018-05-11 11:36:10 +0200661 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100662 topics = (
663 "ns",
664 "vim_account",
665 "wim_account",
666 "sdn",
667 "nsi",
668 "k8scluster",
669 "vca",
670 "k8srepo",
671 "pla",
672 )
673 topics_admin = ("admin",)
tierno16427352019-04-22 11:37:36 +0000674 await asyncio.gather(
garciadeblas5697b8b2021-03-24 09:17:02 +0100675 self.msg.aioread(
676 topics, self.loop, self.kafka_read_callback, from_beginning=True
677 ),
678 self.msg_admin.aioread(
679 topics_admin,
680 self.loop,
681 self.kafka_read_callback,
682 group_id=False,
683 ),
tierno16427352019-04-22 11:37:36 +0000684 )
tiernoc0e42e22018-05-11 11:36:10 +0200685
gcalvinoed7f6d42018-12-14 14:44:56 +0100686 except LcmExceptionExit:
687 self.logger.debug("Bye!")
688 break
tiernoc0e42e22018-05-11 11:36:10 +0200689 except Exception as e:
690 # if not first_start is the first time after starting. So leave more time and wait
691 # to allow kafka starts
gcalvinoed7f6d42018-12-14 14:44:56 +0100692 if self.consecutive_errors == 8 if not self.first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100693 self.logger.error(
694 "Task kafka_read task exit error too many errors. Exception: {}".format(
695 e
696 )
697 )
tiernoc0e42e22018-05-11 11:36:10 +0200698 raise
gcalvinoed7f6d42018-12-14 14:44:56 +0100699 self.consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100700 self.logger.error(
701 "Task kafka_read retrying after Exception {}".format(e)
702 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100703 wait_time = 2 if not self.first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200704 await asyncio.sleep(wait_time, loop=self.loop)
705
706 # self.logger.debug("Task kafka_read terminating")
707 self.logger.debug("Task kafka_read exit")
708
709 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200710
711 # check RO version
712 self.loop.run_until_complete(self.check_RO_version())
713
Luis Vegaa27dc532022-11-11 20:10:49 +0000714 self.ns = ns.NsLcm(self.msg, self.lcm_tasks, self.main_config, self.loop)
715 # TODO: modify the rest of classes to use the LcmCfg object instead of dicts
garciadeblas5697b8b2021-03-24 09:17:02 +0100716 self.netslice = netslice.NetsliceLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000717 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop, self.ns
garciadeblas5697b8b2021-03-24 09:17:02 +0100718 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000719 self.vim = vim_sdn.VimLcm(
720 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
721 )
722 self.wim = vim_sdn.WimLcm(
723 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
724 )
725 self.sdn = vim_sdn.SdnLcm(
726 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
727 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100728 self.k8scluster = vim_sdn.K8sClusterLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000729 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100730 )
Luis Vegaa27dc532022-11-11 20:10:49 +0000731 self.vca = vim_sdn.VcaLcm(
732 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
733 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100734 self.k8srepo = vim_sdn.K8sRepoLcm(
Luis Vegaa27dc532022-11-11 20:10:49 +0000735 self.msg, self.lcm_tasks, self.main_config.to_dict(), self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100736 )
tierno2357f4e2020-10-19 16:38:59 +0000737
garciadeblas5697b8b2021-03-24 09:17:02 +0100738 self.loop.run_until_complete(
739 asyncio.gather(self.kafka_read(), self.kafka_ping())
740 )
bravof73bac502021-05-11 07:38:47 -0400741
tiernoc0e42e22018-05-11 11:36:10 +0200742 # TODO
743 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200744 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200745 # timeout = 200
746 # while self.is_pending_tasks():
747 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
748 # await asyncio.sleep(2, loop=self.loop)
749 # timeout -= 2
750 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200751 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200752 self.loop.close()
753 self.loop = None
754 if self.db:
755 self.db.db_disconnect()
756 if self.msg:
757 self.msg.disconnect()
tierno16427352019-04-22 11:37:36 +0000758 if self.msg_admin:
759 self.msg_admin.disconnect()
tiernoc0e42e22018-05-11 11:36:10 +0200760 if self.fs:
761 self.fs.fs_disconnect()
762
tiernoc0e42e22018-05-11 11:36:10 +0200763 def read_config_file(self, config_file):
tiernoc0e42e22018-05-11 11:36:10 +0200764 try:
Gabriel Cubaa89a5a72022-11-26 18:55:15 -0500765 with open(config_file) as f:
766 return yaml.safe_load(f)
tiernoc0e42e22018-05-11 11:36:10 +0200767 except Exception as e:
768 self.logger.critical("At config file '{}': {}".format(config_file, e))
Gabriel Cubaa89a5a72022-11-26 18:55:15 -0500769 exit(1)
tiernoc0e42e22018-05-11 11:36:10 +0200770
tierno16427352019-04-22 11:37:36 +0000771 @staticmethod
772 def get_process_id():
773 """
774 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
775 will provide a random one
776 :return: Obtained ID
777 """
778 # Try getting docker id. If fails, get pid
779 try:
780 with open("/proc/self/cgroup", "r") as f:
781 text_id_ = f.readline()
782 _, _, text_id = text_id_.rpartition("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100783 text_id = text_id.replace("\n", "")[:12]
tierno16427352019-04-22 11:37:36 +0000784 if text_id:
785 return text_id
786 except Exception:
787 pass
788 # Return a random id
garciadeblas5697b8b2021-03-24 09:17:02 +0100789 return "".join(random_choice("0123456789abcdef") for _ in range(12))
tierno16427352019-04-22 11:37:36 +0000790
tiernoc0e42e22018-05-11 11:36:10 +0200791
tierno275411e2018-05-16 14:33:32 +0200792def usage():
garciadeblas5697b8b2021-03-24 09:17:02 +0100793 print(
794 """Usage: {} [options]
quilesj7e13aeb2019-10-08 13:34:55 +0200795 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200796 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200797 -h|--help: shows this help
garciadeblas5697b8b2021-03-24 09:17:02 +0100798 """.format(
799 sys.argv[0]
800 )
801 )
tierno750b2452018-05-17 16:39:29 +0200802 # --log-socket-host HOST: send logs to this host")
803 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200804
805
garciadeblas5697b8b2021-03-24 09:17:02 +0100806if __name__ == "__main__":
quilesj7e13aeb2019-10-08 13:34:55 +0200807
tierno275411e2018-05-16 14:33:32 +0200808 try:
tierno8c16b052020-02-05 15:08:32 +0000809 # print("SYS.PATH='{}'".format(sys.path))
tierno275411e2018-05-16 14:33:32 +0200810 # load parameters and configuration
quilesj7e13aeb2019-10-08 13:34:55 +0200811 # -h
812 # -c value
813 # --config value
814 # --help
815 # --health-check
garciadeblas5697b8b2021-03-24 09:17:02 +0100816 opts, args = getopt.getopt(
817 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
818 )
tierno275411e2018-05-16 14:33:32 +0200819 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
820 config_file = None
821 for o, a in opts:
822 if o in ("-h", "--help"):
823 usage()
824 sys.exit()
825 elif o in ("-c", "--config"):
826 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200827 elif o == "--health-check":
tierno94f06112020-02-11 12:38:19 +0000828 from osm_lcm.lcm_hc import health_check
garciadeblas5697b8b2021-03-24 09:17:02 +0100829
aticig56b86c22022-06-29 10:43:05 +0300830 health_check(config_file, Lcm.ping_interval_pace)
tierno275411e2018-05-16 14:33:32 +0200831 # elif o == "--log-socket-port":
832 # log_socket_port = a
833 # elif o == "--log-socket-host":
834 # log_socket_host = a
835 # elif o == "--log-file":
836 # log_file = a
837 else:
838 assert False, "Unhandled option"
quilesj7e13aeb2019-10-08 13:34:55 +0200839
tierno275411e2018-05-16 14:33:32 +0200840 if config_file:
841 if not path.isfile(config_file):
garciadeblas5697b8b2021-03-24 09:17:02 +0100842 print(
843 "configuration file '{}' does not exist".format(config_file),
844 file=sys.stderr,
845 )
tierno275411e2018-05-16 14:33:32 +0200846 exit(1)
847 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100848 for config_file in (
849 __file__[: __file__.rfind(".")] + ".cfg",
850 "./lcm.cfg",
851 "/etc/osm/lcm.cfg",
852 ):
tierno275411e2018-05-16 14:33:32 +0200853 if path.isfile(config_file):
854 break
855 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100856 print(
857 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
858 file=sys.stderr,
859 )
tierno275411e2018-05-16 14:33:32 +0200860 exit(1)
861 lcm = Lcm(config_file)
tierno3e359b12019-02-03 02:29:13 +0100862 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200863 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200864 print(str(e), file=sys.stderr)
865 # usage()
866 exit(1)