blob: 060aa07d59ca968e0b0aadbdaa61f145dc4d55c5 [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
bravof569d8882021-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
442 elif command == "scale":
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.scale(nsr_id, nslcmop_id))
448 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
449 return
450 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000451 nsr_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100452 try:
453 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100454 print(
455 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
456 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
457 "".format(
458 nsr_id,
459 db_nsr["operational-status"],
460 db_nsr["config-status"],
461 db_nsr["detailed-status"],
462 db_nsr["_admin"]["deployed"],
463 self.lcm_ns_tasks.get(nsr_id),
464 )
465 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100466 except Exception as e:
467 print("nsr {} not found: {}".format(nsr_id, e))
468 sys.stdout.flush()
469 return
470 elif command == "deleted":
471 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100472 elif command in (
473 "terminated",
474 "instantiated",
475 "scaled",
476 "actioned",
477 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100478 return
479 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
tierno307425f2020-01-26 23:35:59 +0000480 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100481 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
482 nsilcmop = params
483 nsilcmop_id = nsilcmop["_id"] # slice operation id
484 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
garciadeblas5697b8b2021-03-24 09:17:02 +0100485 task = asyncio.ensure_future(
486 self.netslice.instantiate(nsir_id, nsilcmop_id)
487 )
488 self.lcm_tasks.register(
489 "nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task
490 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100491 return
tierno307425f2020-01-26 23:35:59 +0000492 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100493 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
494 nsilcmop = params
495 nsilcmop_id = nsilcmop["_id"] # slice operation id
496 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
497 self.lcm_tasks.cancel(topic, nsir_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100498 task = asyncio.ensure_future(
499 self.netslice.terminate(nsir_id, nsilcmop_id)
500 )
501 self.lcm_tasks.register(
502 "nsi", nsir_id, nsilcmop_id, "nsi_terminate", task
503 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100504 return
505 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000506 nsir_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100507 try:
508 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100509 print(
510 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
511 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
512 "".format(
513 nsir_id,
514 db_nsir["operational-status"],
515 db_nsir["config-status"],
516 db_nsir["detailed-status"],
517 db_nsir["_admin"]["deployed"],
518 self.lcm_netslice_tasks.get(nsir_id),
519 )
520 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100521 except Exception as e:
522 print("nsir {} not found: {}".format(nsir_id, e))
523 sys.stdout.flush()
524 return
525 elif command == "deleted":
526 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100527 elif command in (
528 "terminated",
529 "instantiated",
530 "scaled",
531 "actioned",
532 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100533 return
534 elif topic == "vim_account":
535 vim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000536 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000537 if not self.config["ro_config"].get("ng"):
538 task = asyncio.ensure_future(self.vim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100539 self.lcm_tasks.register(
540 "vim_account", vim_id, order_id, "vim_create", task
541 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100542 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100543 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100544 self.lcm_tasks.cancel(topic, vim_id)
kuuse6a470c62019-07-10 13:52:45 +0200545 task = asyncio.ensure_future(self.vim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100546 self.lcm_tasks.register(
547 "vim_account", vim_id, order_id, "vim_delete", task
548 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100549 return
550 elif command == "show":
551 print("not implemented show with vim_account")
552 sys.stdout.flush()
553 return
tiernof210c1c2019-10-16 09:09:58 +0000554 elif command in ("edit", "edited"):
tierno2357f4e2020-10-19 16:38:59 +0000555 if not self.config["ro_config"].get("ng"):
556 task = asyncio.ensure_future(self.vim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100557 self.lcm_tasks.register(
558 "vim_account", vim_id, order_id, "vim_edit", task
559 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100560 return
tiernof210c1c2019-10-16 09:09:58 +0000561 elif command == "deleted":
562 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100563 elif topic == "wim_account":
564 wim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000565 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000566 if not self.config["ro_config"].get("ng"):
567 task = asyncio.ensure_future(self.wim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100568 self.lcm_tasks.register(
569 "wim_account", wim_id, order_id, "wim_create", task
570 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100571 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100572 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100573 self.lcm_tasks.cancel(topic, wim_id)
kuuse6a470c62019-07-10 13:52:45 +0200574 task = asyncio.ensure_future(self.wim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100575 self.lcm_tasks.register(
576 "wim_account", wim_id, order_id, "wim_delete", task
577 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100578 return
579 elif command == "show":
580 print("not implemented show with wim_account")
581 sys.stdout.flush()
582 return
tiernof210c1c2019-10-16 09:09:58 +0000583 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100584 task = asyncio.ensure_future(self.wim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100585 self.lcm_tasks.register(
586 "wim_account", wim_id, order_id, "wim_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 == "sdn":
592 _sdn_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000593 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000594 if not self.config["ro_config"].get("ng"):
595 task = asyncio.ensure_future(self.sdn.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100596 self.lcm_tasks.register(
597 "sdn", _sdn_id, order_id, "sdn_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, _sdn_id)
kuuse6a470c62019-07-10 13:52:45 +0200602 task = asyncio.ensure_future(self.sdn.delete(params, order_id))
gcalvinoed7f6d42018-12-14 14:44:56 +0100603 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
604 return
tiernof210c1c2019-10-16 09:09:58 +0000605 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100606 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
607 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
608 return
tiernof210c1c2019-10-16 09:09:58 +0000609 elif command == "deleted":
610 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100611 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
612
tiernoc0e42e22018-05-11 11:36:10 +0200613 async def kafka_read(self):
garciadeblas5697b8b2021-03-24 09:17:02 +0100614 self.logger.debug(
615 "Task kafka_read Enter with worker_id={}".format(self.worker_id)
616 )
tiernoc0e42e22018-05-11 11:36:10 +0200617 # future = asyncio.Future()
gcalvinoed7f6d42018-12-14 14:44:56 +0100618 self.consecutive_errors = 0
619 self.first_start = True
620 while self.consecutive_errors < 10:
tiernoc0e42e22018-05-11 11:36:10 +0200621 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100622 topics = (
623 "ns",
624 "vim_account",
625 "wim_account",
626 "sdn",
627 "nsi",
628 "k8scluster",
629 "vca",
630 "k8srepo",
631 "pla",
632 )
633 topics_admin = ("admin",)
tierno16427352019-04-22 11:37:36 +0000634 await asyncio.gather(
garciadeblas5697b8b2021-03-24 09:17:02 +0100635 self.msg.aioread(
636 topics, self.loop, self.kafka_read_callback, from_beginning=True
637 ),
638 self.msg_admin.aioread(
639 topics_admin,
640 self.loop,
641 self.kafka_read_callback,
642 group_id=False,
643 ),
tierno16427352019-04-22 11:37:36 +0000644 )
tiernoc0e42e22018-05-11 11:36:10 +0200645
gcalvinoed7f6d42018-12-14 14:44:56 +0100646 except LcmExceptionExit:
647 self.logger.debug("Bye!")
648 break
tiernoc0e42e22018-05-11 11:36:10 +0200649 except Exception as e:
650 # if not first_start is the first time after starting. So leave more time and wait
651 # to allow kafka starts
gcalvinoed7f6d42018-12-14 14:44:56 +0100652 if self.consecutive_errors == 8 if not self.first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100653 self.logger.error(
654 "Task kafka_read task exit error too many errors. Exception: {}".format(
655 e
656 )
657 )
tiernoc0e42e22018-05-11 11:36:10 +0200658 raise
gcalvinoed7f6d42018-12-14 14:44:56 +0100659 self.consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100660 self.logger.error(
661 "Task kafka_read retrying after Exception {}".format(e)
662 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100663 wait_time = 2 if not self.first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200664 await asyncio.sleep(wait_time, loop=self.loop)
665
666 # self.logger.debug("Task kafka_read terminating")
667 self.logger.debug("Task kafka_read exit")
668
669 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200670
671 # check RO version
672 self.loop.run_until_complete(self.check_RO_version())
673
garciadeblas5697b8b2021-03-24 09:17:02 +0100674 self.ns = ns.NsLcm(
bravof569d8882021-05-11 07:38:47 -0400675 self.msg, self.lcm_tasks, self.config, self.loop
garciadeblas5697b8b2021-03-24 09:17:02 +0100676 )
677 self.netslice = netslice.NetsliceLcm(
678 self.msg, self.lcm_tasks, self.config, self.loop, self.ns
679 )
bravof922c4172020-11-24 21:21:43 -0300680 self.vim = vim_sdn.VimLcm(self.msg, self.lcm_tasks, self.config, self.loop)
681 self.wim = vim_sdn.WimLcm(self.msg, self.lcm_tasks, self.config, self.loop)
682 self.sdn = vim_sdn.SdnLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100683 self.k8scluster = vim_sdn.K8sClusterLcm(
684 self.msg, self.lcm_tasks, self.config, self.loop
685 )
David Garciac1fe90a2021-03-31 19:12:02 +0200686 self.vca = vim_sdn.VcaLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100687 self.k8srepo = vim_sdn.K8sRepoLcm(
688 self.msg, self.lcm_tasks, self.config, self.loop
689 )
tierno2357f4e2020-10-19 16:38:59 +0000690
garciadeblas5697b8b2021-03-24 09:17:02 +0100691 self.loop.run_until_complete(
692 asyncio.gather(self.kafka_read(), self.kafka_ping())
693 )
bravof569d8882021-05-11 07:38:47 -0400694
tiernoc0e42e22018-05-11 11:36:10 +0200695 # TODO
696 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200697 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200698 # timeout = 200
699 # while self.is_pending_tasks():
700 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
701 # await asyncio.sleep(2, loop=self.loop)
702 # timeout -= 2
703 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200704 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200705 self.loop.close()
706 self.loop = None
707 if self.db:
708 self.db.db_disconnect()
709 if self.msg:
710 self.msg.disconnect()
tierno16427352019-04-22 11:37:36 +0000711 if self.msg_admin:
712 self.msg_admin.disconnect()
tiernoc0e42e22018-05-11 11:36:10 +0200713 if self.fs:
714 self.fs.fs_disconnect()
715
tiernoc0e42e22018-05-11 11:36:10 +0200716 def read_config_file(self, config_file):
717 # TODO make a [ini] + yaml inside parser
718 # the configparser library is not suitable, because it does not admit comments at the end of line,
719 # and not parse integer or boolean
720 try:
tierno744303e2020-01-13 16:46:31 +0000721 # read file as yaml format
tiernoc0e42e22018-05-11 11:36:10 +0200722 with open(config_file) as f:
tiernoda6fb102019-11-23 00:36:52 +0000723 conf = yaml.load(f, Loader=yaml.Loader)
tierno744303e2020-01-13 16:46:31 +0000724 # Ensure all sections are not empty
garciadeblas5697b8b2021-03-24 09:17:02 +0100725 for k in (
726 "global",
727 "timeout",
728 "RO",
729 "VCA",
730 "database",
731 "storage",
732 "message",
733 ):
tierno744303e2020-01-13 16:46:31 +0000734 if not conf.get(k):
735 conf[k] = {}
736
737 # read all environ that starts with OSMLCM_
tiernoc0e42e22018-05-11 11:36:10 +0200738 for k, v in environ.items():
739 if not k.startswith("OSMLCM_"):
740 continue
tierno744303e2020-01-13 16:46:31 +0000741 subject, _, item = k[7:].lower().partition("_")
742 if not item:
tierno17a612f2018-10-23 11:30:42 +0200743 continue
tierno744303e2020-01-13 16:46:31 +0000744 if subject in ("ro", "vca"):
tierno17a612f2018-10-23 11:30:42 +0200745 # put in capital letter
tierno744303e2020-01-13 16:46:31 +0000746 subject = subject.upper()
tiernoc0e42e22018-05-11 11:36:10 +0200747 try:
tierno744303e2020-01-13 16:46:31 +0000748 if item == "port" or subject == "timeout":
749 conf[subject][item] = int(v)
tiernoc0e42e22018-05-11 11:36:10 +0200750 else:
tierno744303e2020-01-13 16:46:31 +0000751 conf[subject][item] = v
tiernoc0e42e22018-05-11 11:36:10 +0200752 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100753 self.logger.warning(
754 "skipping environ '{}' on exception '{}'".format(k, e)
755 )
tierno744303e2020-01-13 16:46:31 +0000756
757 # backward compatibility of VCA parameters
758
garciadeblas5697b8b2021-03-24 09:17:02 +0100759 if "pubkey" in conf["VCA"]:
760 conf["VCA"]["public_key"] = conf["VCA"].pop("pubkey")
761 if "cacert" in conf["VCA"]:
762 conf["VCA"]["ca_cert"] = conf["VCA"].pop("cacert")
763 if "apiproxy" in conf["VCA"]:
764 conf["VCA"]["api_proxy"] = conf["VCA"].pop("apiproxy")
tierno744303e2020-01-13 16:46:31 +0000765
garciadeblas5697b8b2021-03-24 09:17:02 +0100766 if "enableosupgrade" in conf["VCA"]:
767 conf["VCA"]["enable_os_upgrade"] = conf["VCA"].pop("enableosupgrade")
768 if isinstance(conf["VCA"].get("enable_os_upgrade"), str):
769 if conf["VCA"]["enable_os_upgrade"].lower() == "false":
770 conf["VCA"]["enable_os_upgrade"] = False
771 elif conf["VCA"]["enable_os_upgrade"].lower() == "true":
772 conf["VCA"]["enable_os_upgrade"] = True
tierno744303e2020-01-13 16:46:31 +0000773
garciadeblas5697b8b2021-03-24 09:17:02 +0100774 if "aptmirror" in conf["VCA"]:
775 conf["VCA"]["apt_mirror"] = conf["VCA"].pop("aptmirror")
tiernoc0e42e22018-05-11 11:36:10 +0200776
777 return conf
778 except Exception as e:
779 self.logger.critical("At config file '{}': {}".format(config_file, e))
780 exit(1)
781
tierno16427352019-04-22 11:37:36 +0000782 @staticmethod
783 def get_process_id():
784 """
785 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
786 will provide a random one
787 :return: Obtained ID
788 """
789 # Try getting docker id. If fails, get pid
790 try:
791 with open("/proc/self/cgroup", "r") as f:
792 text_id_ = f.readline()
793 _, _, text_id = text_id_.rpartition("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100794 text_id = text_id.replace("\n", "")[:12]
tierno16427352019-04-22 11:37:36 +0000795 if text_id:
796 return text_id
797 except Exception:
798 pass
799 # Return a random id
garciadeblas5697b8b2021-03-24 09:17:02 +0100800 return "".join(random_choice("0123456789abcdef") for _ in range(12))
tierno16427352019-04-22 11:37:36 +0000801
tiernoc0e42e22018-05-11 11:36:10 +0200802
tierno275411e2018-05-16 14:33:32 +0200803def usage():
garciadeblas5697b8b2021-03-24 09:17:02 +0100804 print(
805 """Usage: {} [options]
quilesj7e13aeb2019-10-08 13:34:55 +0200806 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200807 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200808 -h|--help: shows this help
garciadeblas5697b8b2021-03-24 09:17:02 +0100809 """.format(
810 sys.argv[0]
811 )
812 )
tierno750b2452018-05-17 16:39:29 +0200813 # --log-socket-host HOST: send logs to this host")
814 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200815
816
garciadeblas5697b8b2021-03-24 09:17:02 +0100817if __name__ == "__main__":
quilesj7e13aeb2019-10-08 13:34:55 +0200818
tierno275411e2018-05-16 14:33:32 +0200819 try:
tierno8c16b052020-02-05 15:08:32 +0000820 # print("SYS.PATH='{}'".format(sys.path))
tierno275411e2018-05-16 14:33:32 +0200821 # load parameters and configuration
quilesj7e13aeb2019-10-08 13:34:55 +0200822 # -h
823 # -c value
824 # --config value
825 # --help
826 # --health-check
garciadeblas5697b8b2021-03-24 09:17:02 +0100827 opts, args = getopt.getopt(
828 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
829 )
tierno275411e2018-05-16 14:33:32 +0200830 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
831 config_file = None
832 for o, a in opts:
833 if o in ("-h", "--help"):
834 usage()
835 sys.exit()
836 elif o in ("-c", "--config"):
837 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200838 elif o == "--health-check":
tierno94f06112020-02-11 12:38:19 +0000839 from osm_lcm.lcm_hc import health_check
garciadeblas5697b8b2021-03-24 09:17:02 +0100840
tierno94f06112020-02-11 12:38:19 +0000841 health_check(health_check_file, Lcm.ping_interval_pace)
tierno275411e2018-05-16 14:33:32 +0200842 # elif o == "--log-socket-port":
843 # log_socket_port = a
844 # elif o == "--log-socket-host":
845 # log_socket_host = a
846 # elif o == "--log-file":
847 # log_file = a
848 else:
849 assert False, "Unhandled option"
quilesj7e13aeb2019-10-08 13:34:55 +0200850
tierno275411e2018-05-16 14:33:32 +0200851 if config_file:
852 if not path.isfile(config_file):
garciadeblas5697b8b2021-03-24 09:17:02 +0100853 print(
854 "configuration file '{}' does not exist".format(config_file),
855 file=sys.stderr,
856 )
tierno275411e2018-05-16 14:33:32 +0200857 exit(1)
858 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100859 for config_file in (
860 __file__[: __file__.rfind(".")] + ".cfg",
861 "./lcm.cfg",
862 "/etc/osm/lcm.cfg",
863 ):
tierno275411e2018-05-16 14:33:32 +0200864 if path.isfile(config_file):
865 break
866 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100867 print(
868 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
869 file=sys.stderr,
870 )
tierno275411e2018-05-16 14:33:32 +0200871 exit(1)
872 lcm = Lcm(config_file)
tierno3e359b12019-02-03 02:29:13 +0100873 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200874 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200875 print(str(e), file=sys.stderr)
876 # usage()
877 exit(1)