blob: 9378b1d6b28663cdd7e5458b8be612d6af4e7222 [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
tierno275411e2018-05-16 14:33:32 +020047from os import environ, path
tierno16427352019-04-22 11:37:36 +000048from random import choice as random_choice
tierno59d22d22018-09-25 18:10:19 +020049from n2vc import version as n2vc_version
bravof922c4172020-11-24 21:21:43 -030050import traceback
tiernoc0e42e22018-05-11 11:36:10 +020051
garciadeblas5697b8b2021-03-24 09:17:02 +010052if os.getenv("OSMLCM_PDB_DEBUG", None) is not None:
quilesj7e13aeb2019-10-08 13:34:55 +020053 pdb.set_trace()
54
tiernoc0e42e22018-05-11 11:36:10 +020055
tierno275411e2018-05-16 14:33:32 +020056__author__ = "Alfonso Tierno"
tiernoe64f7fb2019-09-11 08:55:52 +000057min_RO_version = "6.0.2"
tierno6e9d2eb2018-09-12 17:47:18 +020058min_n2vc_version = "0.0.2"
quilesj7e13aeb2019-10-08 13:34:55 +020059
tierno16427352019-04-22 11:37:36 +000060min_common_version = "0.1.19"
garciadeblas5697b8b2021-03-24 09:17:02 +010061health_check_file = (
62 path.expanduser("~") + "/time_last_ping"
63) # TODO find better location for this file
tierno275411e2018-05-16 14:33:32 +020064
65
tiernoc0e42e22018-05-11 11:36:10 +020066class Lcm:
67
garciadeblas5697b8b2021-03-24 09:17:02 +010068 ping_interval_pace = (
69 120 # how many time ping is send once is confirmed all is running
70 )
71 ping_interval_boot = 5 # how many time ping is sent when booting
72 cfg_logger_name = {
73 "message": "lcm.msg",
74 "database": "lcm.db",
75 "storage": "lcm.fs",
76 "tsdb": "lcm.prometheus",
77 }
tierno991e95d2020-07-21 12:41:25 +000078 # ^ contains for each section at lcm.cfg the used logger name
tiernoa9843d82018-10-24 10:44:20 +020079
tierno59d22d22018-09-25 18:10:19 +020080 def __init__(self, config_file, loop=None):
tiernoc0e42e22018-05-11 11:36:10 +020081 """
82 Init, Connect to database, filesystem storage, and messaging
83 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
84 :return: None
85 """
tiernoc0e42e22018-05-11 11:36:10 +020086 self.db = None
87 self.msg = None
tierno16427352019-04-22 11:37:36 +000088 self.msg_admin = None
tiernoc0e42e22018-05-11 11:36:10 +020089 self.fs = None
90 self.pings_not_received = 1
tiernoc2564fe2019-01-28 16:18:56 +000091 self.consecutive_errors = 0
92 self.first_start = False
tiernoc0e42e22018-05-11 11:36:10 +020093
tiernoc0e42e22018-05-11 11:36:10 +020094 # logging
garciadeblas5697b8b2021-03-24 09:17:02 +010095 self.logger = logging.getLogger("lcm")
tierno16427352019-04-22 11:37:36 +000096 # get id
97 self.worker_id = self.get_process_id()
tiernoc0e42e22018-05-11 11:36:10 +020098 # load configuration
99 config = self.read_config_file(config_file)
100 self.config = config
tierno744303e2020-01-13 16:46:31 +0000101 self.config["ro_config"] = {
tierno69f0d382020-05-07 13:08:09 +0000102 "ng": config["RO"].get("ng", False),
103 "uri": config["RO"].get("uri"),
tierno750b2452018-05-17 16:39:29 +0200104 "tenant": config.get("tenant", "osm"),
tierno69f0d382020-05-07 13:08:09 +0000105 "logger_name": "lcm.roclient",
106 "loglevel": config["RO"].get("loglevel", "ERROR"),
tiernoc0e42e22018-05-11 11:36:10 +0200107 }
tierno69f0d382020-05-07 13:08:09 +0000108 if not self.config["ro_config"]["uri"]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100109 self.config["ro_config"]["uri"] = "http://{}:{}/".format(
110 config["RO"]["host"], config["RO"]["port"]
111 )
112 elif (
113 "/ro" in self.config["ro_config"]["uri"][-4:]
114 or "/openmano" in self.config["ro_config"]["uri"][-10:]
115 ):
tierno2357f4e2020-10-19 16:38:59 +0000116 # uri ends with '/ro', '/ro/', '/openmano', '/openmano/'
117 index = self.config["ro_config"]["uri"][-1].rfind("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100118 self.config["ro_config"]["uri"] = self.config["ro_config"]["uri"][index + 1]
tiernoc0e42e22018-05-11 11:36:10 +0200119
tierno59d22d22018-09-25 18:10:19 +0200120 self.loop = loop or asyncio.get_event_loop()
garciadeblas5697b8b2021-03-24 09:17:02 +0100121 self.ns = (
122 self.netslice
123 ) = (
124 self.vim
125 ) = self.wim = self.sdn = self.k8scluster = self.vca = self.k8srepo = None
tiernoc0e42e22018-05-11 11:36:10 +0200126
127 # logging
garciadeblas5697b8b2021-03-24 09:17:02 +0100128 log_format_simple = (
129 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
130 )
131 log_formatter_simple = logging.Formatter(
132 log_format_simple, datefmt="%Y-%m-%dT%H:%M:%S"
133 )
tiernoc0e42e22018-05-11 11:36:10 +0200134 config["database"]["logger_name"] = "lcm.db"
135 config["storage"]["logger_name"] = "lcm.fs"
136 config["message"]["logger_name"] = "lcm.msg"
tierno86aa62f2018-08-20 11:57:04 +0000137 if config["global"].get("logfile"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100138 file_handler = logging.handlers.RotatingFileHandler(
139 config["global"]["logfile"], maxBytes=100e6, backupCount=9, delay=0
140 )
tiernoc0e42e22018-05-11 11:36:10 +0200141 file_handler.setFormatter(log_formatter_simple)
142 self.logger.addHandler(file_handler)
tierno86aa62f2018-08-20 11:57:04 +0000143 if not config["global"].get("nologging"):
tiernoc0e42e22018-05-11 11:36:10 +0200144 str_handler = logging.StreamHandler()
145 str_handler.setFormatter(log_formatter_simple)
146 self.logger.addHandler(str_handler)
147
148 if config["global"].get("loglevel"):
149 self.logger.setLevel(config["global"]["loglevel"])
150
151 # logging other modules
tierno991e95d2020-07-21 12:41:25 +0000152 for k1, logname in self.cfg_logger_name.items():
tiernoc0e42e22018-05-11 11:36:10 +0200153 config[k1]["logger_name"] = logname
154 logger_module = logging.getLogger(logname)
tierno86aa62f2018-08-20 11:57:04 +0000155 if config[k1].get("logfile"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100156 file_handler = logging.handlers.RotatingFileHandler(
157 config[k1]["logfile"], maxBytes=100e6, backupCount=9, delay=0
158 )
tiernoc0e42e22018-05-11 11:36:10 +0200159 file_handler.setFormatter(log_formatter_simple)
160 logger_module.addHandler(file_handler)
tierno86aa62f2018-08-20 11:57:04 +0000161 if config[k1].get("loglevel"):
tiernoc0e42e22018-05-11 11:36:10 +0200162 logger_module.setLevel(config[k1]["loglevel"])
garciadeblas5697b8b2021-03-24 09:17:02 +0100163 self.logger.critical(
164 "starting osm/lcm version {} {}".format(lcm_version, lcm_version_date)
165 )
tierno59d22d22018-09-25 18:10:19 +0200166
tiernoc0e42e22018-05-11 11:36:10 +0200167 # check version of N2VC
168 # TODO enhance with int conversion or from distutils.version import LooseVersion
169 # or with list(map(int, version.split(".")))
tierno59d22d22018-09-25 18:10:19 +0200170 if versiontuple(n2vc_version) < versiontuple(min_n2vc_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100171 raise LcmException(
172 "Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
173 n2vc_version, min_n2vc_version
174 )
175 )
tierno59d22d22018-09-25 18:10:19 +0200176 # check version of common
tierno27246d82018-09-27 15:59:09 +0200177 if versiontuple(common_version) < versiontuple(min_common_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100178 raise LcmException(
179 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
180 common_version, min_common_version
181 )
182 )
tierno22f4f9c2018-06-11 18:53:39 +0200183
tiernoc0e42e22018-05-11 11:36:10 +0200184 try:
bravof922c4172020-11-24 21:21:43 -0300185 self.db = Database(config).instance.db
tiernoc0e42e22018-05-11 11:36:10 +0200186
bravof922c4172020-11-24 21:21:43 -0300187 self.fs = Filesystem(config).instance.fs
sousaedu40365e82021-07-26 15:24:21 +0200188 self.fs.sync()
tiernoc0e42e22018-05-11 11:36:10 +0200189
quilesj7e13aeb2019-10-08 13:34:55 +0200190 # copy message configuration in order to remove 'group_id' for msg_admin
tiernoc2564fe2019-01-28 16:18:56 +0000191 config_message = config["message"].copy()
192 config_message["loop"] = self.loop
193 if config_message["driver"] == "local":
tiernoc0e42e22018-05-11 11:36:10 +0200194 self.msg = msglocal.MsgLocal()
tiernoc2564fe2019-01-28 16:18:56 +0000195 self.msg.connect(config_message)
tierno16427352019-04-22 11:37:36 +0000196 self.msg_admin = msglocal.MsgLocal()
197 config_message.pop("group_id", None)
198 self.msg_admin.connect(config_message)
tiernoc2564fe2019-01-28 16:18:56 +0000199 elif config_message["driver"] == "kafka":
tiernoc0e42e22018-05-11 11:36:10 +0200200 self.msg = msgkafka.MsgKafka()
tiernoc2564fe2019-01-28 16:18:56 +0000201 self.msg.connect(config_message)
tierno16427352019-04-22 11:37:36 +0000202 self.msg_admin = msgkafka.MsgKafka()
203 config_message.pop("group_id", None)
204 self.msg_admin.connect(config_message)
tiernoc0e42e22018-05-11 11:36:10 +0200205 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100206 raise LcmException(
207 "Invalid configuration param '{}' at '[message]':'driver'".format(
208 config["message"]["driver"]
209 )
210 )
tiernoc0e42e22018-05-11 11:36:10 +0200211 except (DbException, FsException, MsgException) as e:
212 self.logger.critical(str(e), exc_info=True)
213 raise LcmException(str(e))
214
kuused124bfe2019-06-18 12:09:24 +0200215 # contains created tasks/futures to be able to cancel
bravof922c4172020-11-24 21:21:43 -0300216 self.lcm_tasks = TaskRegistry(self.worker_id, self.logger)
kuused124bfe2019-06-18 12:09:24 +0200217
tierno22f4f9c2018-06-11 18:53:39 +0200218 async def check_RO_version(self):
tiernoe64f7fb2019-09-11 08:55:52 +0000219 tries = 14
220 last_error = None
221 while True:
tierno2357f4e2020-10-19 16:38:59 +0000222 ro_uri = self.config["ro_config"]["uri"]
tiernoe64f7fb2019-09-11 08:55:52 +0000223 try:
tierno2357f4e2020-10-19 16:38:59 +0000224 # try new RO, if fail old RO
225 try:
226 self.config["ro_config"]["uri"] = ro_uri + "ro"
tierno69f0d382020-05-07 13:08:09 +0000227 ro_server = NgRoClient(self.loop, **self.config["ro_config"])
tierno2357f4e2020-10-19 16:38:59 +0000228 ro_version = await ro_server.get_version()
229 self.config["ro_config"]["ng"] = True
230 except Exception:
231 self.config["ro_config"]["uri"] = ro_uri + "openmano"
tierno69f0d382020-05-07 13:08:09 +0000232 ro_server = ROClient(self.loop, **self.config["ro_config"])
tierno2357f4e2020-10-19 16:38:59 +0000233 ro_version = await ro_server.get_version()
234 self.config["ro_config"]["ng"] = False
tiernoe64f7fb2019-09-11 08:55:52 +0000235 if versiontuple(ro_version) < versiontuple(min_RO_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100236 raise LcmException(
237 "Not compatible osm/RO version '{}'. Needed '{}' or higher".format(
238 ro_version, min_RO_version
239 )
240 )
241 self.logger.info(
242 "Connected to RO version {} new-generation version {}".format(
243 ro_version, self.config["ro_config"]["ng"]
244 )
245 )
tiernoe64f7fb2019-09-11 08:55:52 +0000246 return
tierno69f0d382020-05-07 13:08:09 +0000247 except (ROClientException, NgRoException) as e:
tierno2357f4e2020-10-19 16:38:59 +0000248 self.config["ro_config"]["uri"] = ro_uri
tiernoe64f7fb2019-09-11 08:55:52 +0000249 tries -= 1
bravof922c4172020-11-24 21:21:43 -0300250 traceback.print_tb(e.__traceback__)
garciadeblas5697b8b2021-03-24 09:17:02 +0100251 error_text = "Error while connecting to RO on {}: {}".format(
252 self.config["ro_config"]["uri"], e
253 )
tiernoe64f7fb2019-09-11 08:55:52 +0000254 if tries <= 0:
255 self.logger.critical(error_text)
256 raise LcmException(error_text)
257 if last_error != error_text:
258 last_error = error_text
garciadeblas5697b8b2021-03-24 09:17:02 +0100259 self.logger.error(
260 error_text + ". Waiting until {} seconds".format(5 * tries)
261 )
tiernoe64f7fb2019-09-11 08:55:52 +0000262 await asyncio.sleep(5)
tierno22f4f9c2018-06-11 18:53:39 +0200263
tiernoc0e42e22018-05-11 11:36:10 +0200264 async def test(self, param=None):
265 self.logger.debug("Starting/Ending test task: {}".format(param))
266
tiernoc0e42e22018-05-11 11:36:10 +0200267 async def kafka_ping(self):
268 self.logger.debug("Task kafka_ping Enter")
269 consecutive_errors = 0
270 first_start = True
271 kafka_has_received = False
272 self.pings_not_received = 1
273 while True:
274 try:
tierno16427352019-04-22 11:37:36 +0000275 await self.msg_admin.aiowrite(
garciadeblas5697b8b2021-03-24 09:17:02 +0100276 "admin",
277 "ping",
278 {
279 "from": "lcm",
280 "to": "lcm",
281 "worker_id": self.worker_id,
282 "version": lcm_version,
283 },
284 self.loop,
285 )
tiernoc0e42e22018-05-11 11:36:10 +0200286 # time between pings are low when it is not received and at starting
garciadeblas5697b8b2021-03-24 09:17:02 +0100287 wait_time = (
288 self.ping_interval_boot
289 if not kafka_has_received
290 else self.ping_interval_pace
291 )
tiernoc0e42e22018-05-11 11:36:10 +0200292 if not self.pings_not_received:
293 kafka_has_received = True
294 self.pings_not_received += 1
295 await asyncio.sleep(wait_time, loop=self.loop)
296 if self.pings_not_received > 10:
297 raise LcmException("It is not receiving pings from Kafka bus")
298 consecutive_errors = 0
299 first_start = False
300 except LcmException:
301 raise
302 except Exception as e:
303 # if not first_start is the first time after starting. So leave more time and wait
304 # to allow kafka starts
305 if consecutive_errors == 8 if not first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100306 self.logger.error(
307 "Task kafka_read task exit error too many errors. Exception: {}".format(
308 e
309 )
310 )
tiernoc0e42e22018-05-11 11:36:10 +0200311 raise
312 consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100313 self.logger.error(
314 "Task kafka_read retrying after Exception {}".format(e)
315 )
tierno16427352019-04-22 11:37:36 +0000316 wait_time = 2 if not first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200317 await asyncio.sleep(wait_time, loop=self.loop)
318
gcalvinoed7f6d42018-12-14 14:44:56 +0100319 def kafka_read_callback(self, topic, command, params):
320 order_id = 1
321
322 if topic != "admin" and command != "ping":
garciadeblas5697b8b2021-03-24 09:17:02 +0100323 self.logger.debug(
324 "Task kafka_read receives {} {}: {}".format(topic, command, params)
325 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100326 self.consecutive_errors = 0
327 self.first_start = False
328 order_id += 1
329 if command == "exit":
330 raise LcmExceptionExit
331 elif command.startswith("#"):
332 return
333 elif command == "echo":
334 # just for test
335 print(params)
336 sys.stdout.flush()
337 return
338 elif command == "test":
339 asyncio.Task(self.test(params), loop=self.loop)
340 return
341
342 if topic == "admin":
343 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
tierno16427352019-04-22 11:37:36 +0000344 if params.get("worker_id") != self.worker_id:
345 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100346 self.pings_not_received = 0
tierno3e359b12019-02-03 02:29:13 +0100347 try:
348 with open(health_check_file, "w") as f:
349 f.write(str(time()))
350 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100351 self.logger.error(
352 "Cannot write into '{}' for healthcheck: {}".format(
353 health_check_file, e
354 )
355 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100356 return
magnussonle9198bb2020-01-21 13:00:51 +0100357 elif topic == "pla":
358 if command == "placement":
359 self.ns.update_nsrs_with_pla_result(params)
360 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100361 elif topic == "k8scluster":
362 if command == "create" or command == "created":
363 k8scluster_id = params.get("_id")
364 task = asyncio.ensure_future(self.k8scluster.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100365 self.lcm_tasks.register(
366 "k8scluster", k8scluster_id, order_id, "k8scluster_create", task
367 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100368 return
369 elif command == "delete" or command == "deleted":
370 k8scluster_id = params.get("_id")
371 task = asyncio.ensure_future(self.k8scluster.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100372 self.lcm_tasks.register(
373 "k8scluster", k8scluster_id, order_id, "k8scluster_delete", task
374 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100375 return
David Garciac1fe90a2021-03-31 19:12:02 +0200376 elif topic == "vca":
377 if command == "create" or command == "created":
378 vca_id = params.get("_id")
379 task = asyncio.ensure_future(self.vca.create(params, order_id))
380 self.lcm_tasks.register("vca", vca_id, order_id, "vca_create", task)
381 return
382 elif command == "delete" or command == "deleted":
383 vca_id = params.get("_id")
384 task = asyncio.ensure_future(self.vca.delete(params, order_id))
385 self.lcm_tasks.register("vca", vca_id, order_id, "vca_delete", task)
386 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100387 elif topic == "k8srepo":
388 if command == "create" or command == "created":
389 k8srepo_id = params.get("_id")
390 self.logger.debug("k8srepo_id = {}".format(k8srepo_id))
391 task = asyncio.ensure_future(self.k8srepo.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100392 self.lcm_tasks.register(
393 "k8srepo", k8srepo_id, order_id, "k8srepo_create", task
394 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100395 return
396 elif command == "delete" or command == "deleted":
397 k8srepo_id = params.get("_id")
398 task = asyncio.ensure_future(self.k8srepo.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100399 self.lcm_tasks.register(
400 "k8srepo", k8srepo_id, order_id, "k8srepo_delete", task
401 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100402 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100403 elif topic == "ns":
tierno307425f2020-01-26 23:35:59 +0000404 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100405 # self.logger.debug("Deploying NS {}".format(nsr_id))
406 nslcmop = params
407 nslcmop_id = nslcmop["_id"]
408 nsr_id = nslcmop["nsInstanceId"]
409 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100410 self.lcm_tasks.register(
411 "ns", nsr_id, nslcmop_id, "ns_instantiate", task
412 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100413 return
tierno307425f2020-01-26 23:35:59 +0000414 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100415 # self.logger.debug("Deleting NS {}".format(nsr_id))
416 nslcmop = params
417 nslcmop_id = nslcmop["_id"]
418 nsr_id = nslcmop["nsInstanceId"]
419 self.lcm_tasks.cancel(topic, nsr_id)
420 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
421 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
422 return
ksaikiranr3fde2c72021-03-15 10:39:06 +0530423 elif command == "vca_status_refresh":
424 nslcmop = params
425 nslcmop_id = nslcmop["_id"]
426 nsr_id = nslcmop["nsInstanceId"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100427 task = asyncio.ensure_future(
428 self.ns.vca_status_refresh(nsr_id, nslcmop_id)
429 )
430 self.lcm_tasks.register(
431 "ns", nsr_id, nslcmop_id, "ns_vca_status_refresh", task
432 )
ksaikiranr3fde2c72021-03-15 10:39:06 +0530433 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100434 elif command == "action":
435 # self.logger.debug("Update NS {}".format(nsr_id))
436 nslcmop = params
437 nslcmop_id = nslcmop["_id"]
438 nsr_id = nslcmop["nsInstanceId"]
439 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
440 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
441 return
aticigdffa6212022-04-12 15:27:53 +0300442 elif command == "update":
443 # self.logger.debug("Update NS {}".format(nsr_id))
444 nslcmop = params
445 nslcmop_id = nslcmop["_id"]
446 nsr_id = nslcmop["nsInstanceId"]
447 task = asyncio.ensure_future(self.ns.update(nsr_id, nslcmop_id))
448 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_update", task)
449 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100450 elif command == "scale":
451 # self.logger.debug("Update NS {}".format(nsr_id))
452 nslcmop = params
453 nslcmop_id = nslcmop["_id"]
454 nsr_id = nslcmop["nsInstanceId"]
455 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
456 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
457 return
garciadeblas07f4e4c2022-06-09 09:42:58 +0200458 elif command == "heal":
459 # self.logger.debug("Healing NS {}".format(nsr_id))
460 nslcmop = params
461 nslcmop_id = nslcmop["_id"]
462 nsr_id = nslcmop["nsInstanceId"]
463 task = asyncio.ensure_future(self.ns.heal(nsr_id, nslcmop_id))
464 self.lcm_tasks.register(
465 "ns", nsr_id, nslcmop_id, "ns_heal", task
466 )
467 return
elumalai80bcf1c2022-04-28 18:05:01 +0530468 elif command == "migrate":
469 nslcmop = params
470 nslcmop_id = nslcmop["_id"]
471 nsr_id = nslcmop["nsInstanceId"]
472 task = asyncio.ensure_future(self.ns.migrate(nsr_id, nslcmop_id))
473 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_migrate", task)
474 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100475 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000476 nsr_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100477 try:
478 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100479 print(
480 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
481 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
482 "".format(
483 nsr_id,
484 db_nsr["operational-status"],
485 db_nsr["config-status"],
486 db_nsr["detailed-status"],
487 db_nsr["_admin"]["deployed"],
488 self.lcm_ns_tasks.get(nsr_id),
489 )
490 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100491 except Exception as e:
492 print("nsr {} not found: {}".format(nsr_id, e))
493 sys.stdout.flush()
494 return
495 elif command == "deleted":
496 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100497 elif command in (
elumalaica7ece02022-04-12 12:47:32 +0530498 "vnf_terminated",
elumalaib9e357c2022-04-27 09:58:38 +0530499 "policy_updated",
garciadeblas5697b8b2021-03-24 09:17:02 +0100500 "terminated",
501 "instantiated",
502 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200503 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100504 "actioned",
aticigdffa6212022-04-12 15:27:53 +0300505 "updated",
elumalai80bcf1c2022-04-28 18:05:01 +0530506 "migrated",
garciadeblas5697b8b2021-03-24 09:17:02 +0100507 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100508 return
elumalaica7ece02022-04-12 12:47:32 +0530509
gcalvinoed7f6d42018-12-14 14:44:56 +0100510 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
tierno307425f2020-01-26 23:35:59 +0000511 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100512 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
513 nsilcmop = params
514 nsilcmop_id = nsilcmop["_id"] # slice operation id
515 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
garciadeblas5697b8b2021-03-24 09:17:02 +0100516 task = asyncio.ensure_future(
517 self.netslice.instantiate(nsir_id, nsilcmop_id)
518 )
519 self.lcm_tasks.register(
520 "nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task
521 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100522 return
tierno307425f2020-01-26 23:35:59 +0000523 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100524 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
525 nsilcmop = params
526 nsilcmop_id = nsilcmop["_id"] # slice operation id
527 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
528 self.lcm_tasks.cancel(topic, nsir_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100529 task = asyncio.ensure_future(
530 self.netslice.terminate(nsir_id, nsilcmop_id)
531 )
532 self.lcm_tasks.register(
533 "nsi", nsir_id, nsilcmop_id, "nsi_terminate", task
534 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100535 return
536 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000537 nsir_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100538 try:
539 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100540 print(
541 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
542 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
543 "".format(
544 nsir_id,
545 db_nsir["operational-status"],
546 db_nsir["config-status"],
547 db_nsir["detailed-status"],
548 db_nsir["_admin"]["deployed"],
549 self.lcm_netslice_tasks.get(nsir_id),
550 )
551 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100552 except Exception as e:
553 print("nsir {} not found: {}".format(nsir_id, e))
554 sys.stdout.flush()
555 return
556 elif command == "deleted":
557 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100558 elif command in (
559 "terminated",
560 "instantiated",
561 "scaled",
garciadeblas07f4e4c2022-06-09 09:42:58 +0200562 "healed",
garciadeblas5697b8b2021-03-24 09:17:02 +0100563 "actioned",
564 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100565 return
566 elif topic == "vim_account":
567 vim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000568 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000569 if not self.config["ro_config"].get("ng"):
570 task = asyncio.ensure_future(self.vim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100571 self.lcm_tasks.register(
572 "vim_account", vim_id, order_id, "vim_create", task
573 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100574 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100575 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100576 self.lcm_tasks.cancel(topic, vim_id)
kuuse6a470c62019-07-10 13:52:45 +0200577 task = asyncio.ensure_future(self.vim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100578 self.lcm_tasks.register(
579 "vim_account", vim_id, order_id, "vim_delete", task
580 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100581 return
582 elif command == "show":
583 print("not implemented show with vim_account")
584 sys.stdout.flush()
585 return
tiernof210c1c2019-10-16 09:09:58 +0000586 elif command in ("edit", "edited"):
tierno2357f4e2020-10-19 16:38:59 +0000587 if not self.config["ro_config"].get("ng"):
588 task = asyncio.ensure_future(self.vim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100589 self.lcm_tasks.register(
590 "vim_account", vim_id, order_id, "vim_edit", task
591 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100592 return
tiernof210c1c2019-10-16 09:09:58 +0000593 elif command == "deleted":
594 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100595 elif topic == "wim_account":
596 wim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000597 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000598 if not self.config["ro_config"].get("ng"):
599 task = asyncio.ensure_future(self.wim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100600 self.lcm_tasks.register(
601 "wim_account", wim_id, order_id, "wim_create", task
602 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100603 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100604 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100605 self.lcm_tasks.cancel(topic, wim_id)
kuuse6a470c62019-07-10 13:52:45 +0200606 task = asyncio.ensure_future(self.wim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100607 self.lcm_tasks.register(
608 "wim_account", wim_id, order_id, "wim_delete", task
609 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100610 return
611 elif command == "show":
612 print("not implemented show with wim_account")
613 sys.stdout.flush()
614 return
tiernof210c1c2019-10-16 09:09:58 +0000615 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100616 task = asyncio.ensure_future(self.wim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100617 self.lcm_tasks.register(
618 "wim_account", wim_id, order_id, "wim_edit", task
619 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100620 return
tiernof210c1c2019-10-16 09:09:58 +0000621 elif command == "deleted":
622 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100623 elif topic == "sdn":
624 _sdn_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000625 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000626 if not self.config["ro_config"].get("ng"):
627 task = asyncio.ensure_future(self.sdn.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100628 self.lcm_tasks.register(
629 "sdn", _sdn_id, order_id, "sdn_create", task
630 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100631 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100632 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100633 self.lcm_tasks.cancel(topic, _sdn_id)
kuuse6a470c62019-07-10 13:52:45 +0200634 task = asyncio.ensure_future(self.sdn.delete(params, order_id))
gcalvinoed7f6d42018-12-14 14:44:56 +0100635 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
636 return
tiernof210c1c2019-10-16 09:09:58 +0000637 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100638 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
639 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
640 return
tiernof210c1c2019-10-16 09:09:58 +0000641 elif command == "deleted":
642 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100643 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
644
tiernoc0e42e22018-05-11 11:36:10 +0200645 async def kafka_read(self):
garciadeblas5697b8b2021-03-24 09:17:02 +0100646 self.logger.debug(
647 "Task kafka_read Enter with worker_id={}".format(self.worker_id)
648 )
tiernoc0e42e22018-05-11 11:36:10 +0200649 # future = asyncio.Future()
gcalvinoed7f6d42018-12-14 14:44:56 +0100650 self.consecutive_errors = 0
651 self.first_start = True
652 while self.consecutive_errors < 10:
tiernoc0e42e22018-05-11 11:36:10 +0200653 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100654 topics = (
655 "ns",
656 "vim_account",
657 "wim_account",
658 "sdn",
659 "nsi",
660 "k8scluster",
661 "vca",
662 "k8srepo",
663 "pla",
664 )
665 topics_admin = ("admin",)
tierno16427352019-04-22 11:37:36 +0000666 await asyncio.gather(
garciadeblas5697b8b2021-03-24 09:17:02 +0100667 self.msg.aioread(
668 topics, self.loop, self.kafka_read_callback, from_beginning=True
669 ),
670 self.msg_admin.aioread(
671 topics_admin,
672 self.loop,
673 self.kafka_read_callback,
674 group_id=False,
675 ),
tierno16427352019-04-22 11:37:36 +0000676 )
tiernoc0e42e22018-05-11 11:36:10 +0200677
gcalvinoed7f6d42018-12-14 14:44:56 +0100678 except LcmExceptionExit:
679 self.logger.debug("Bye!")
680 break
tiernoc0e42e22018-05-11 11:36:10 +0200681 except Exception as e:
682 # if not first_start is the first time after starting. So leave more time and wait
683 # to allow kafka starts
gcalvinoed7f6d42018-12-14 14:44:56 +0100684 if self.consecutive_errors == 8 if not self.first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100685 self.logger.error(
686 "Task kafka_read task exit error too many errors. Exception: {}".format(
687 e
688 )
689 )
tiernoc0e42e22018-05-11 11:36:10 +0200690 raise
gcalvinoed7f6d42018-12-14 14:44:56 +0100691 self.consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100692 self.logger.error(
693 "Task kafka_read retrying after Exception {}".format(e)
694 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100695 wait_time = 2 if not self.first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200696 await asyncio.sleep(wait_time, loop=self.loop)
697
698 # self.logger.debug("Task kafka_read terminating")
699 self.logger.debug("Task kafka_read exit")
700
701 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200702
703 # check RO version
704 self.loop.run_until_complete(self.check_RO_version())
705
aticig15db6142022-01-24 12:51:26 +0300706 self.ns = ns.NsLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100707 self.netslice = netslice.NetsliceLcm(
708 self.msg, self.lcm_tasks, self.config, self.loop, self.ns
709 )
bravof922c4172020-11-24 21:21:43 -0300710 self.vim = vim_sdn.VimLcm(self.msg, self.lcm_tasks, self.config, self.loop)
711 self.wim = vim_sdn.WimLcm(self.msg, self.lcm_tasks, self.config, self.loop)
712 self.sdn = vim_sdn.SdnLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100713 self.k8scluster = vim_sdn.K8sClusterLcm(
714 self.msg, self.lcm_tasks, self.config, self.loop
715 )
David Garciac1fe90a2021-03-31 19:12:02 +0200716 self.vca = vim_sdn.VcaLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100717 self.k8srepo = vim_sdn.K8sRepoLcm(
718 self.msg, self.lcm_tasks, self.config, self.loop
719 )
tierno2357f4e2020-10-19 16:38:59 +0000720
garciadeblas5697b8b2021-03-24 09:17:02 +0100721 self.loop.run_until_complete(
722 asyncio.gather(self.kafka_read(), self.kafka_ping())
723 )
bravof73bac502021-05-11 07:38:47 -0400724
tiernoc0e42e22018-05-11 11:36:10 +0200725 # TODO
726 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200727 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200728 # timeout = 200
729 # while self.is_pending_tasks():
730 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
731 # await asyncio.sleep(2, loop=self.loop)
732 # timeout -= 2
733 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200734 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200735 self.loop.close()
736 self.loop = None
737 if self.db:
738 self.db.db_disconnect()
739 if self.msg:
740 self.msg.disconnect()
tierno16427352019-04-22 11:37:36 +0000741 if self.msg_admin:
742 self.msg_admin.disconnect()
tiernoc0e42e22018-05-11 11:36:10 +0200743 if self.fs:
744 self.fs.fs_disconnect()
745
tiernoc0e42e22018-05-11 11:36:10 +0200746 def read_config_file(self, config_file):
747 # TODO make a [ini] + yaml inside parser
748 # the configparser library is not suitable, because it does not admit comments at the end of line,
749 # and not parse integer or boolean
750 try:
tierno744303e2020-01-13 16:46:31 +0000751 # read file as yaml format
tiernoc0e42e22018-05-11 11:36:10 +0200752 with open(config_file) as f:
tiernoda6fb102019-11-23 00:36:52 +0000753 conf = yaml.load(f, Loader=yaml.Loader)
tierno744303e2020-01-13 16:46:31 +0000754 # Ensure all sections are not empty
garciadeblas5697b8b2021-03-24 09:17:02 +0100755 for k in (
756 "global",
757 "timeout",
758 "RO",
759 "VCA",
760 "database",
761 "storage",
762 "message",
763 ):
tierno744303e2020-01-13 16:46:31 +0000764 if not conf.get(k):
765 conf[k] = {}
766
767 # read all environ that starts with OSMLCM_
tiernoc0e42e22018-05-11 11:36:10 +0200768 for k, v in environ.items():
769 if not k.startswith("OSMLCM_"):
770 continue
tierno744303e2020-01-13 16:46:31 +0000771 subject, _, item = k[7:].lower().partition("_")
772 if not item:
tierno17a612f2018-10-23 11:30:42 +0200773 continue
tierno744303e2020-01-13 16:46:31 +0000774 if subject in ("ro", "vca"):
tierno17a612f2018-10-23 11:30:42 +0200775 # put in capital letter
tierno744303e2020-01-13 16:46:31 +0000776 subject = subject.upper()
tiernoc0e42e22018-05-11 11:36:10 +0200777 try:
tierno744303e2020-01-13 16:46:31 +0000778 if item == "port" or subject == "timeout":
779 conf[subject][item] = int(v)
tiernoc0e42e22018-05-11 11:36:10 +0200780 else:
tierno744303e2020-01-13 16:46:31 +0000781 conf[subject][item] = v
tiernoc0e42e22018-05-11 11:36:10 +0200782 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100783 self.logger.warning(
784 "skipping environ '{}' on exception '{}'".format(k, e)
785 )
tierno744303e2020-01-13 16:46:31 +0000786
787 # backward compatibility of VCA parameters
788
garciadeblas5697b8b2021-03-24 09:17:02 +0100789 if "pubkey" in conf["VCA"]:
790 conf["VCA"]["public_key"] = conf["VCA"].pop("pubkey")
791 if "cacert" in conf["VCA"]:
792 conf["VCA"]["ca_cert"] = conf["VCA"].pop("cacert")
793 if "apiproxy" in conf["VCA"]:
794 conf["VCA"]["api_proxy"] = conf["VCA"].pop("apiproxy")
tierno744303e2020-01-13 16:46:31 +0000795
garciadeblas5697b8b2021-03-24 09:17:02 +0100796 if "enableosupgrade" in conf["VCA"]:
797 conf["VCA"]["enable_os_upgrade"] = conf["VCA"].pop("enableosupgrade")
798 if isinstance(conf["VCA"].get("enable_os_upgrade"), str):
799 if conf["VCA"]["enable_os_upgrade"].lower() == "false":
800 conf["VCA"]["enable_os_upgrade"] = False
801 elif conf["VCA"]["enable_os_upgrade"].lower() == "true":
802 conf["VCA"]["enable_os_upgrade"] = True
tierno744303e2020-01-13 16:46:31 +0000803
garciadeblas5697b8b2021-03-24 09:17:02 +0100804 if "aptmirror" in conf["VCA"]:
805 conf["VCA"]["apt_mirror"] = conf["VCA"].pop("aptmirror")
tiernoc0e42e22018-05-11 11:36:10 +0200806
807 return conf
808 except Exception as e:
809 self.logger.critical("At config file '{}': {}".format(config_file, e))
810 exit(1)
811
tierno16427352019-04-22 11:37:36 +0000812 @staticmethod
813 def get_process_id():
814 """
815 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
816 will provide a random one
817 :return: Obtained ID
818 """
819 # Try getting docker id. If fails, get pid
820 try:
821 with open("/proc/self/cgroup", "r") as f:
822 text_id_ = f.readline()
823 _, _, text_id = text_id_.rpartition("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100824 text_id = text_id.replace("\n", "")[:12]
tierno16427352019-04-22 11:37:36 +0000825 if text_id:
826 return text_id
827 except Exception:
828 pass
829 # Return a random id
garciadeblas5697b8b2021-03-24 09:17:02 +0100830 return "".join(random_choice("0123456789abcdef") for _ in range(12))
tierno16427352019-04-22 11:37:36 +0000831
tiernoc0e42e22018-05-11 11:36:10 +0200832
tierno275411e2018-05-16 14:33:32 +0200833def usage():
garciadeblas5697b8b2021-03-24 09:17:02 +0100834 print(
835 """Usage: {} [options]
quilesj7e13aeb2019-10-08 13:34:55 +0200836 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200837 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200838 -h|--help: shows this help
garciadeblas5697b8b2021-03-24 09:17:02 +0100839 """.format(
840 sys.argv[0]
841 )
842 )
tierno750b2452018-05-17 16:39:29 +0200843 # --log-socket-host HOST: send logs to this host")
844 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200845
846
garciadeblas5697b8b2021-03-24 09:17:02 +0100847if __name__ == "__main__":
quilesj7e13aeb2019-10-08 13:34:55 +0200848
tierno275411e2018-05-16 14:33:32 +0200849 try:
tierno8c16b052020-02-05 15:08:32 +0000850 # print("SYS.PATH='{}'".format(sys.path))
tierno275411e2018-05-16 14:33:32 +0200851 # load parameters and configuration
quilesj7e13aeb2019-10-08 13:34:55 +0200852 # -h
853 # -c value
854 # --config value
855 # --help
856 # --health-check
garciadeblas5697b8b2021-03-24 09:17:02 +0100857 opts, args = getopt.getopt(
858 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
859 )
tierno275411e2018-05-16 14:33:32 +0200860 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
861 config_file = None
862 for o, a in opts:
863 if o in ("-h", "--help"):
864 usage()
865 sys.exit()
866 elif o in ("-c", "--config"):
867 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200868 elif o == "--health-check":
tierno94f06112020-02-11 12:38:19 +0000869 from osm_lcm.lcm_hc import health_check
garciadeblas5697b8b2021-03-24 09:17:02 +0100870
tierno94f06112020-02-11 12:38:19 +0000871 health_check(health_check_file, Lcm.ping_interval_pace)
tierno275411e2018-05-16 14:33:32 +0200872 # elif o == "--log-socket-port":
873 # log_socket_port = a
874 # elif o == "--log-socket-host":
875 # log_socket_host = a
876 # elif o == "--log-file":
877 # log_file = a
878 else:
879 assert False, "Unhandled option"
quilesj7e13aeb2019-10-08 13:34:55 +0200880
tierno275411e2018-05-16 14:33:32 +0200881 if config_file:
882 if not path.isfile(config_file):
garciadeblas5697b8b2021-03-24 09:17:02 +0100883 print(
884 "configuration file '{}' does not exist".format(config_file),
885 file=sys.stderr,
886 )
tierno275411e2018-05-16 14:33:32 +0200887 exit(1)
888 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100889 for config_file in (
890 __file__[: __file__.rfind(".")] + ".cfg",
891 "./lcm.cfg",
892 "/etc/osm/lcm.cfg",
893 ):
tierno275411e2018-05-16 14:33:32 +0200894 if path.isfile(config_file):
895 break
896 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100897 print(
898 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
899 file=sys.stderr,
900 )
tierno275411e2018-05-16 14:33:32 +0200901 exit(1)
902 lcm = Lcm(config_file)
tierno3e359b12019-02-03 02:29:13 +0100903 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200904 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200905 print(str(e), file=sys.stderr)
906 # usage()
907 exit(1)