blob: 851ba090c2831d5ce2f4498e4a9b7d0e65e60e31 [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
tiernob996d942020-07-03 14:52:28 +000032from osm_lcm import ns, prometheus, 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
tiernoc0e42e22018-05-11 11:36:10 +0200188
quilesj7e13aeb2019-10-08 13:34:55 +0200189 # copy message configuration in order to remove 'group_id' for msg_admin
tiernoc2564fe2019-01-28 16:18:56 +0000190 config_message = config["message"].copy()
191 config_message["loop"] = self.loop
192 if config_message["driver"] == "local":
tiernoc0e42e22018-05-11 11:36:10 +0200193 self.msg = msglocal.MsgLocal()
tiernoc2564fe2019-01-28 16:18:56 +0000194 self.msg.connect(config_message)
tierno16427352019-04-22 11:37:36 +0000195 self.msg_admin = msglocal.MsgLocal()
196 config_message.pop("group_id", None)
197 self.msg_admin.connect(config_message)
tiernoc2564fe2019-01-28 16:18:56 +0000198 elif config_message["driver"] == "kafka":
tiernoc0e42e22018-05-11 11:36:10 +0200199 self.msg = msgkafka.MsgKafka()
tiernoc2564fe2019-01-28 16:18:56 +0000200 self.msg.connect(config_message)
tierno16427352019-04-22 11:37:36 +0000201 self.msg_admin = msgkafka.MsgKafka()
202 config_message.pop("group_id", None)
203 self.msg_admin.connect(config_message)
tiernoc0e42e22018-05-11 11:36:10 +0200204 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100205 raise LcmException(
206 "Invalid configuration param '{}' at '[message]':'driver'".format(
207 config["message"]["driver"]
208 )
209 )
tiernoc0e42e22018-05-11 11:36:10 +0200210 except (DbException, FsException, MsgException) as e:
211 self.logger.critical(str(e), exc_info=True)
212 raise LcmException(str(e))
213
kuused124bfe2019-06-18 12:09:24 +0200214 # contains created tasks/futures to be able to cancel
bravof922c4172020-11-24 21:21:43 -0300215 self.lcm_tasks = TaskRegistry(self.worker_id, self.logger)
kuused124bfe2019-06-18 12:09:24 +0200216
tierno991e95d2020-07-21 12:41:25 +0000217 if self.config.get("tsdb") and self.config["tsdb"].get("driver"):
218 if self.config["tsdb"]["driver"] == "prometheus":
garciadeblas5697b8b2021-03-24 09:17:02 +0100219 self.prometheus = prometheus.Prometheus(
220 self.config["tsdb"], self.worker_id, self.loop
221 )
tierno991e95d2020-07-21 12:41:25 +0000222 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100223 raise LcmException(
224 "Invalid configuration param '{}' at '[tsdb]':'driver'".format(
225 config["tsdb"]["driver"]
226 )
227 )
tiernob996d942020-07-03 14:52:28 +0000228 else:
229 self.prometheus = None
tierno59d22d22018-09-25 18:10:19 +0200230
tierno22f4f9c2018-06-11 18:53:39 +0200231 async def check_RO_version(self):
tiernoe64f7fb2019-09-11 08:55:52 +0000232 tries = 14
233 last_error = None
234 while True:
tierno2357f4e2020-10-19 16:38:59 +0000235 ro_uri = self.config["ro_config"]["uri"]
tiernoe64f7fb2019-09-11 08:55:52 +0000236 try:
tierno2357f4e2020-10-19 16:38:59 +0000237 # try new RO, if fail old RO
238 try:
239 self.config["ro_config"]["uri"] = ro_uri + "ro"
tierno69f0d382020-05-07 13:08:09 +0000240 ro_server = NgRoClient(self.loop, **self.config["ro_config"])
tierno2357f4e2020-10-19 16:38:59 +0000241 ro_version = await ro_server.get_version()
242 self.config["ro_config"]["ng"] = True
243 except Exception:
244 self.config["ro_config"]["uri"] = ro_uri + "openmano"
tierno69f0d382020-05-07 13:08:09 +0000245 ro_server = ROClient(self.loop, **self.config["ro_config"])
tierno2357f4e2020-10-19 16:38:59 +0000246 ro_version = await ro_server.get_version()
247 self.config["ro_config"]["ng"] = False
tiernoe64f7fb2019-09-11 08:55:52 +0000248 if versiontuple(ro_version) < versiontuple(min_RO_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100249 raise LcmException(
250 "Not compatible osm/RO version '{}'. Needed '{}' or higher".format(
251 ro_version, min_RO_version
252 )
253 )
254 self.logger.info(
255 "Connected to RO version {} new-generation version {}".format(
256 ro_version, self.config["ro_config"]["ng"]
257 )
258 )
tiernoe64f7fb2019-09-11 08:55:52 +0000259 return
tierno69f0d382020-05-07 13:08:09 +0000260 except (ROClientException, NgRoException) as e:
tierno2357f4e2020-10-19 16:38:59 +0000261 self.config["ro_config"]["uri"] = ro_uri
tiernoe64f7fb2019-09-11 08:55:52 +0000262 tries -= 1
bravof922c4172020-11-24 21:21:43 -0300263 traceback.print_tb(e.__traceback__)
garciadeblas5697b8b2021-03-24 09:17:02 +0100264 error_text = "Error while connecting to RO on {}: {}".format(
265 self.config["ro_config"]["uri"], e
266 )
tiernoe64f7fb2019-09-11 08:55:52 +0000267 if tries <= 0:
268 self.logger.critical(error_text)
269 raise LcmException(error_text)
270 if last_error != error_text:
271 last_error = error_text
garciadeblas5697b8b2021-03-24 09:17:02 +0100272 self.logger.error(
273 error_text + ". Waiting until {} seconds".format(5 * tries)
274 )
tiernoe64f7fb2019-09-11 08:55:52 +0000275 await asyncio.sleep(5)
tierno22f4f9c2018-06-11 18:53:39 +0200276
tiernoc0e42e22018-05-11 11:36:10 +0200277 async def test(self, param=None):
278 self.logger.debug("Starting/Ending test task: {}".format(param))
279
tiernoc0e42e22018-05-11 11:36:10 +0200280 async def kafka_ping(self):
281 self.logger.debug("Task kafka_ping Enter")
282 consecutive_errors = 0
283 first_start = True
284 kafka_has_received = False
285 self.pings_not_received = 1
286 while True:
287 try:
tierno16427352019-04-22 11:37:36 +0000288 await self.msg_admin.aiowrite(
garciadeblas5697b8b2021-03-24 09:17:02 +0100289 "admin",
290 "ping",
291 {
292 "from": "lcm",
293 "to": "lcm",
294 "worker_id": self.worker_id,
295 "version": lcm_version,
296 },
297 self.loop,
298 )
tiernoc0e42e22018-05-11 11:36:10 +0200299 # time between pings are low when it is not received and at starting
garciadeblas5697b8b2021-03-24 09:17:02 +0100300 wait_time = (
301 self.ping_interval_boot
302 if not kafka_has_received
303 else self.ping_interval_pace
304 )
tiernoc0e42e22018-05-11 11:36:10 +0200305 if not self.pings_not_received:
306 kafka_has_received = True
307 self.pings_not_received += 1
308 await asyncio.sleep(wait_time, loop=self.loop)
309 if self.pings_not_received > 10:
310 raise LcmException("It is not receiving pings from Kafka bus")
311 consecutive_errors = 0
312 first_start = False
313 except LcmException:
314 raise
315 except Exception as e:
316 # if not first_start is the first time after starting. So leave more time and wait
317 # to allow kafka starts
318 if consecutive_errors == 8 if not first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100319 self.logger.error(
320 "Task kafka_read task exit error too many errors. Exception: {}".format(
321 e
322 )
323 )
tiernoc0e42e22018-05-11 11:36:10 +0200324 raise
325 consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100326 self.logger.error(
327 "Task kafka_read retrying after Exception {}".format(e)
328 )
tierno16427352019-04-22 11:37:36 +0000329 wait_time = 2 if not first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200330 await asyncio.sleep(wait_time, loop=self.loop)
331
gcalvinoed7f6d42018-12-14 14:44:56 +0100332 def kafka_read_callback(self, topic, command, params):
333 order_id = 1
334
335 if topic != "admin" and command != "ping":
garciadeblas5697b8b2021-03-24 09:17:02 +0100336 self.logger.debug(
337 "Task kafka_read receives {} {}: {}".format(topic, command, params)
338 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100339 self.consecutive_errors = 0
340 self.first_start = False
341 order_id += 1
342 if command == "exit":
343 raise LcmExceptionExit
344 elif command.startswith("#"):
345 return
346 elif command == "echo":
347 # just for test
348 print(params)
349 sys.stdout.flush()
350 return
351 elif command == "test":
352 asyncio.Task(self.test(params), loop=self.loop)
353 return
354
355 if topic == "admin":
356 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
tierno16427352019-04-22 11:37:36 +0000357 if params.get("worker_id") != self.worker_id:
358 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100359 self.pings_not_received = 0
tierno3e359b12019-02-03 02:29:13 +0100360 try:
361 with open(health_check_file, "w") as f:
362 f.write(str(time()))
363 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100364 self.logger.error(
365 "Cannot write into '{}' for healthcheck: {}".format(
366 health_check_file, e
367 )
368 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100369 return
magnussonle9198bb2020-01-21 13:00:51 +0100370 elif topic == "pla":
371 if command == "placement":
372 self.ns.update_nsrs_with_pla_result(params)
373 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100374 elif topic == "k8scluster":
375 if command == "create" or command == "created":
376 k8scluster_id = params.get("_id")
377 task = asyncio.ensure_future(self.k8scluster.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100378 self.lcm_tasks.register(
379 "k8scluster", k8scluster_id, order_id, "k8scluster_create", task
380 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100381 return
382 elif command == "delete" or command == "deleted":
383 k8scluster_id = params.get("_id")
384 task = asyncio.ensure_future(self.k8scluster.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100385 self.lcm_tasks.register(
386 "k8scluster", k8scluster_id, order_id, "k8scluster_delete", task
387 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100388 return
David Garciac1fe90a2021-03-31 19:12:02 +0200389 elif topic == "vca":
390 if command == "create" or command == "created":
391 vca_id = params.get("_id")
392 task = asyncio.ensure_future(self.vca.create(params, order_id))
393 self.lcm_tasks.register("vca", vca_id, order_id, "vca_create", task)
394 return
395 elif command == "delete" or command == "deleted":
396 vca_id = params.get("_id")
397 task = asyncio.ensure_future(self.vca.delete(params, order_id))
398 self.lcm_tasks.register("vca", vca_id, order_id, "vca_delete", task)
399 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100400 elif topic == "k8srepo":
401 if command == "create" or command == "created":
402 k8srepo_id = params.get("_id")
403 self.logger.debug("k8srepo_id = {}".format(k8srepo_id))
404 task = asyncio.ensure_future(self.k8srepo.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100405 self.lcm_tasks.register(
406 "k8srepo", k8srepo_id, order_id, "k8srepo_create", task
407 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100408 return
409 elif command == "delete" or command == "deleted":
410 k8srepo_id = params.get("_id")
411 task = asyncio.ensure_future(self.k8srepo.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100412 self.lcm_tasks.register(
413 "k8srepo", k8srepo_id, order_id, "k8srepo_delete", task
414 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100415 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100416 elif topic == "ns":
tierno307425f2020-01-26 23:35:59 +0000417 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100418 # self.logger.debug("Deploying NS {}".format(nsr_id))
419 nslcmop = params
420 nslcmop_id = nslcmop["_id"]
421 nsr_id = nslcmop["nsInstanceId"]
422 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100423 self.lcm_tasks.register(
424 "ns", nsr_id, nslcmop_id, "ns_instantiate", task
425 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100426 return
tierno307425f2020-01-26 23:35:59 +0000427 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100428 # self.logger.debug("Deleting NS {}".format(nsr_id))
429 nslcmop = params
430 nslcmop_id = nslcmop["_id"]
431 nsr_id = nslcmop["nsInstanceId"]
432 self.lcm_tasks.cancel(topic, nsr_id)
433 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
434 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
435 return
ksaikiranr3fde2c72021-03-15 10:39:06 +0530436 elif command == "vca_status_refresh":
437 nslcmop = params
438 nslcmop_id = nslcmop["_id"]
439 nsr_id = nslcmop["nsInstanceId"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100440 task = asyncio.ensure_future(
441 self.ns.vca_status_refresh(nsr_id, nslcmop_id)
442 )
443 self.lcm_tasks.register(
444 "ns", nsr_id, nslcmop_id, "ns_vca_status_refresh", task
445 )
ksaikiranr3fde2c72021-03-15 10:39:06 +0530446 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100447 elif command == "action":
448 # self.logger.debug("Update NS {}".format(nsr_id))
449 nslcmop = params
450 nslcmop_id = nslcmop["_id"]
451 nsr_id = nslcmop["nsInstanceId"]
452 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
453 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
454 return
455 elif command == "scale":
456 # self.logger.debug("Update NS {}".format(nsr_id))
457 nslcmop = params
458 nslcmop_id = nslcmop["_id"]
459 nsr_id = nslcmop["nsInstanceId"]
460 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
461 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
462 return
463 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000464 nsr_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100465 try:
466 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100467 print(
468 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
469 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
470 "".format(
471 nsr_id,
472 db_nsr["operational-status"],
473 db_nsr["config-status"],
474 db_nsr["detailed-status"],
475 db_nsr["_admin"]["deployed"],
476 self.lcm_ns_tasks.get(nsr_id),
477 )
478 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100479 except Exception as e:
480 print("nsr {} not found: {}".format(nsr_id, e))
481 sys.stdout.flush()
482 return
483 elif command == "deleted":
484 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100485 elif command in (
486 "terminated",
487 "instantiated",
488 "scaled",
489 "actioned",
490 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100491 return
492 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
tierno307425f2020-01-26 23:35:59 +0000493 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100494 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
495 nsilcmop = params
496 nsilcmop_id = nsilcmop["_id"] # slice operation id
497 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
garciadeblas5697b8b2021-03-24 09:17:02 +0100498 task = asyncio.ensure_future(
499 self.netslice.instantiate(nsir_id, nsilcmop_id)
500 )
501 self.lcm_tasks.register(
502 "nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task
503 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100504 return
tierno307425f2020-01-26 23:35:59 +0000505 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100506 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
507 nsilcmop = params
508 nsilcmop_id = nsilcmop["_id"] # slice operation id
509 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
510 self.lcm_tasks.cancel(topic, nsir_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100511 task = asyncio.ensure_future(
512 self.netslice.terminate(nsir_id, nsilcmop_id)
513 )
514 self.lcm_tasks.register(
515 "nsi", nsir_id, nsilcmop_id, "nsi_terminate", task
516 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100517 return
518 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000519 nsir_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100520 try:
521 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100522 print(
523 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
524 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
525 "".format(
526 nsir_id,
527 db_nsir["operational-status"],
528 db_nsir["config-status"],
529 db_nsir["detailed-status"],
530 db_nsir["_admin"]["deployed"],
531 self.lcm_netslice_tasks.get(nsir_id),
532 )
533 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100534 except Exception as e:
535 print("nsir {} not found: {}".format(nsir_id, e))
536 sys.stdout.flush()
537 return
538 elif command == "deleted":
539 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100540 elif command in (
541 "terminated",
542 "instantiated",
543 "scaled",
544 "actioned",
545 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100546 return
547 elif topic == "vim_account":
548 vim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000549 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000550 if not self.config["ro_config"].get("ng"):
551 task = asyncio.ensure_future(self.vim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100552 self.lcm_tasks.register(
553 "vim_account", vim_id, order_id, "vim_create", task
554 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100555 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100556 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100557 self.lcm_tasks.cancel(topic, vim_id)
kuuse6a470c62019-07-10 13:52:45 +0200558 task = asyncio.ensure_future(self.vim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100559 self.lcm_tasks.register(
560 "vim_account", vim_id, order_id, "vim_delete", task
561 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100562 return
563 elif command == "show":
564 print("not implemented show with vim_account")
565 sys.stdout.flush()
566 return
tiernof210c1c2019-10-16 09:09:58 +0000567 elif command in ("edit", "edited"):
tierno2357f4e2020-10-19 16:38:59 +0000568 if not self.config["ro_config"].get("ng"):
569 task = asyncio.ensure_future(self.vim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100570 self.lcm_tasks.register(
571 "vim_account", vim_id, order_id, "vim_edit", task
572 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100573 return
tiernof210c1c2019-10-16 09:09:58 +0000574 elif command == "deleted":
575 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100576 elif topic == "wim_account":
577 wim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000578 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000579 if not self.config["ro_config"].get("ng"):
580 task = asyncio.ensure_future(self.wim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100581 self.lcm_tasks.register(
582 "wim_account", wim_id, order_id, "wim_create", task
583 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100584 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100585 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100586 self.lcm_tasks.cancel(topic, wim_id)
kuuse6a470c62019-07-10 13:52:45 +0200587 task = asyncio.ensure_future(self.wim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100588 self.lcm_tasks.register(
589 "wim_account", wim_id, order_id, "wim_delete", task
590 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100591 return
592 elif command == "show":
593 print("not implemented show with wim_account")
594 sys.stdout.flush()
595 return
tiernof210c1c2019-10-16 09:09:58 +0000596 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100597 task = asyncio.ensure_future(self.wim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100598 self.lcm_tasks.register(
599 "wim_account", wim_id, order_id, "wim_edit", task
600 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100601 return
tiernof210c1c2019-10-16 09:09:58 +0000602 elif command == "deleted":
603 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100604 elif topic == "sdn":
605 _sdn_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000606 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000607 if not self.config["ro_config"].get("ng"):
608 task = asyncio.ensure_future(self.sdn.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100609 self.lcm_tasks.register(
610 "sdn", _sdn_id, order_id, "sdn_create", task
611 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100612 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100613 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100614 self.lcm_tasks.cancel(topic, _sdn_id)
kuuse6a470c62019-07-10 13:52:45 +0200615 task = asyncio.ensure_future(self.sdn.delete(params, order_id))
gcalvinoed7f6d42018-12-14 14:44:56 +0100616 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
617 return
tiernof210c1c2019-10-16 09:09:58 +0000618 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100619 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
620 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
621 return
tiernof210c1c2019-10-16 09:09:58 +0000622 elif command == "deleted":
623 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100624 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
625
tiernoc0e42e22018-05-11 11:36:10 +0200626 async def kafka_read(self):
garciadeblas5697b8b2021-03-24 09:17:02 +0100627 self.logger.debug(
628 "Task kafka_read Enter with worker_id={}".format(self.worker_id)
629 )
tiernoc0e42e22018-05-11 11:36:10 +0200630 # future = asyncio.Future()
gcalvinoed7f6d42018-12-14 14:44:56 +0100631 self.consecutive_errors = 0
632 self.first_start = True
633 while self.consecutive_errors < 10:
tiernoc0e42e22018-05-11 11:36:10 +0200634 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100635 topics = (
636 "ns",
637 "vim_account",
638 "wim_account",
639 "sdn",
640 "nsi",
641 "k8scluster",
642 "vca",
643 "k8srepo",
644 "pla",
645 )
646 topics_admin = ("admin",)
tierno16427352019-04-22 11:37:36 +0000647 await asyncio.gather(
garciadeblas5697b8b2021-03-24 09:17:02 +0100648 self.msg.aioread(
649 topics, self.loop, self.kafka_read_callback, from_beginning=True
650 ),
651 self.msg_admin.aioread(
652 topics_admin,
653 self.loop,
654 self.kafka_read_callback,
655 group_id=False,
656 ),
tierno16427352019-04-22 11:37:36 +0000657 )
tiernoc0e42e22018-05-11 11:36:10 +0200658
gcalvinoed7f6d42018-12-14 14:44:56 +0100659 except LcmExceptionExit:
660 self.logger.debug("Bye!")
661 break
tiernoc0e42e22018-05-11 11:36:10 +0200662 except Exception as e:
663 # if not first_start is the first time after starting. So leave more time and wait
664 # to allow kafka starts
gcalvinoed7f6d42018-12-14 14:44:56 +0100665 if self.consecutive_errors == 8 if not self.first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100666 self.logger.error(
667 "Task kafka_read task exit error too many errors. Exception: {}".format(
668 e
669 )
670 )
tiernoc0e42e22018-05-11 11:36:10 +0200671 raise
gcalvinoed7f6d42018-12-14 14:44:56 +0100672 self.consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100673 self.logger.error(
674 "Task kafka_read retrying after Exception {}".format(e)
675 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100676 wait_time = 2 if not self.first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200677 await asyncio.sleep(wait_time, loop=self.loop)
678
679 # self.logger.debug("Task kafka_read terminating")
680 self.logger.debug("Task kafka_read exit")
681
682 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200683
684 # check RO version
685 self.loop.run_until_complete(self.check_RO_version())
686
garciadeblas5697b8b2021-03-24 09:17:02 +0100687 self.ns = ns.NsLcm(
688 self.msg, self.lcm_tasks, self.config, self.loop, self.prometheus
689 )
690 self.netslice = netslice.NetsliceLcm(
691 self.msg, self.lcm_tasks, self.config, self.loop, self.ns
692 )
bravof922c4172020-11-24 21:21:43 -0300693 self.vim = vim_sdn.VimLcm(self.msg, self.lcm_tasks, self.config, self.loop)
694 self.wim = vim_sdn.WimLcm(self.msg, self.lcm_tasks, self.config, self.loop)
695 self.sdn = vim_sdn.SdnLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100696 self.k8scluster = vim_sdn.K8sClusterLcm(
697 self.msg, self.lcm_tasks, self.config, self.loop
698 )
David Garciac1fe90a2021-03-31 19:12:02 +0200699 self.vca = vim_sdn.VcaLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100700 self.k8srepo = vim_sdn.K8sRepoLcm(
701 self.msg, self.lcm_tasks, self.config, self.loop
702 )
tierno2357f4e2020-10-19 16:38:59 +0000703
tierno991e95d2020-07-21 12:41:25 +0000704 # configure tsdb prometheus
tiernob996d942020-07-03 14:52:28 +0000705 if self.prometheus:
706 self.loop.run_until_complete(self.prometheus.start())
707
garciadeblas5697b8b2021-03-24 09:17:02 +0100708 self.loop.run_until_complete(
709 asyncio.gather(self.kafka_read(), self.kafka_ping())
710 )
tiernoc0e42e22018-05-11 11:36:10 +0200711 # TODO
712 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200713 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200714 # timeout = 200
715 # while self.is_pending_tasks():
716 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
717 # await asyncio.sleep(2, loop=self.loop)
718 # timeout -= 2
719 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200720 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200721 self.loop.close()
722 self.loop = None
723 if self.db:
724 self.db.db_disconnect()
725 if self.msg:
726 self.msg.disconnect()
tierno16427352019-04-22 11:37:36 +0000727 if self.msg_admin:
728 self.msg_admin.disconnect()
tiernoc0e42e22018-05-11 11:36:10 +0200729 if self.fs:
730 self.fs.fs_disconnect()
731
tiernoc0e42e22018-05-11 11:36:10 +0200732 def read_config_file(self, config_file):
733 # TODO make a [ini] + yaml inside parser
734 # the configparser library is not suitable, because it does not admit comments at the end of line,
735 # and not parse integer or boolean
736 try:
tierno744303e2020-01-13 16:46:31 +0000737 # read file as yaml format
tiernoc0e42e22018-05-11 11:36:10 +0200738 with open(config_file) as f:
tiernoda6fb102019-11-23 00:36:52 +0000739 conf = yaml.load(f, Loader=yaml.Loader)
tierno744303e2020-01-13 16:46:31 +0000740 # Ensure all sections are not empty
garciadeblas5697b8b2021-03-24 09:17:02 +0100741 for k in (
742 "global",
743 "timeout",
744 "RO",
745 "VCA",
746 "database",
747 "storage",
748 "message",
749 ):
tierno744303e2020-01-13 16:46:31 +0000750 if not conf.get(k):
751 conf[k] = {}
752
753 # read all environ that starts with OSMLCM_
tiernoc0e42e22018-05-11 11:36:10 +0200754 for k, v in environ.items():
755 if not k.startswith("OSMLCM_"):
756 continue
tierno744303e2020-01-13 16:46:31 +0000757 subject, _, item = k[7:].lower().partition("_")
758 if not item:
tierno17a612f2018-10-23 11:30:42 +0200759 continue
tierno744303e2020-01-13 16:46:31 +0000760 if subject in ("ro", "vca"):
tierno17a612f2018-10-23 11:30:42 +0200761 # put in capital letter
tierno744303e2020-01-13 16:46:31 +0000762 subject = subject.upper()
tiernoc0e42e22018-05-11 11:36:10 +0200763 try:
tierno744303e2020-01-13 16:46:31 +0000764 if item == "port" or subject == "timeout":
765 conf[subject][item] = int(v)
tiernoc0e42e22018-05-11 11:36:10 +0200766 else:
tierno744303e2020-01-13 16:46:31 +0000767 conf[subject][item] = v
tiernoc0e42e22018-05-11 11:36:10 +0200768 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100769 self.logger.warning(
770 "skipping environ '{}' on exception '{}'".format(k, e)
771 )
tierno744303e2020-01-13 16:46:31 +0000772
773 # backward compatibility of VCA parameters
774
garciadeblas5697b8b2021-03-24 09:17:02 +0100775 if "pubkey" in conf["VCA"]:
776 conf["VCA"]["public_key"] = conf["VCA"].pop("pubkey")
777 if "cacert" in conf["VCA"]:
778 conf["VCA"]["ca_cert"] = conf["VCA"].pop("cacert")
779 if "apiproxy" in conf["VCA"]:
780 conf["VCA"]["api_proxy"] = conf["VCA"].pop("apiproxy")
tierno744303e2020-01-13 16:46:31 +0000781
garciadeblas5697b8b2021-03-24 09:17:02 +0100782 if "enableosupgrade" in conf["VCA"]:
783 conf["VCA"]["enable_os_upgrade"] = conf["VCA"].pop("enableosupgrade")
784 if isinstance(conf["VCA"].get("enable_os_upgrade"), str):
785 if conf["VCA"]["enable_os_upgrade"].lower() == "false":
786 conf["VCA"]["enable_os_upgrade"] = False
787 elif conf["VCA"]["enable_os_upgrade"].lower() == "true":
788 conf["VCA"]["enable_os_upgrade"] = True
tierno744303e2020-01-13 16:46:31 +0000789
garciadeblas5697b8b2021-03-24 09:17:02 +0100790 if "aptmirror" in conf["VCA"]:
791 conf["VCA"]["apt_mirror"] = conf["VCA"].pop("aptmirror")
tiernoc0e42e22018-05-11 11:36:10 +0200792
793 return conf
794 except Exception as e:
795 self.logger.critical("At config file '{}': {}".format(config_file, e))
796 exit(1)
797
tierno16427352019-04-22 11:37:36 +0000798 @staticmethod
799 def get_process_id():
800 """
801 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
802 will provide a random one
803 :return: Obtained ID
804 """
805 # Try getting docker id. If fails, get pid
806 try:
807 with open("/proc/self/cgroup", "r") as f:
808 text_id_ = f.readline()
809 _, _, text_id = text_id_.rpartition("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100810 text_id = text_id.replace("\n", "")[:12]
tierno16427352019-04-22 11:37:36 +0000811 if text_id:
812 return text_id
813 except Exception:
814 pass
815 # Return a random id
garciadeblas5697b8b2021-03-24 09:17:02 +0100816 return "".join(random_choice("0123456789abcdef") for _ in range(12))
tierno16427352019-04-22 11:37:36 +0000817
tiernoc0e42e22018-05-11 11:36:10 +0200818
tierno275411e2018-05-16 14:33:32 +0200819def usage():
garciadeblas5697b8b2021-03-24 09:17:02 +0100820 print(
821 """Usage: {} [options]
quilesj7e13aeb2019-10-08 13:34:55 +0200822 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200823 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200824 -h|--help: shows this help
garciadeblas5697b8b2021-03-24 09:17:02 +0100825 """.format(
826 sys.argv[0]
827 )
828 )
tierno750b2452018-05-17 16:39:29 +0200829 # --log-socket-host HOST: send logs to this host")
830 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200831
832
garciadeblas5697b8b2021-03-24 09:17:02 +0100833if __name__ == "__main__":
quilesj7e13aeb2019-10-08 13:34:55 +0200834
tierno275411e2018-05-16 14:33:32 +0200835 try:
tierno8c16b052020-02-05 15:08:32 +0000836 # print("SYS.PATH='{}'".format(sys.path))
tierno275411e2018-05-16 14:33:32 +0200837 # load parameters and configuration
quilesj7e13aeb2019-10-08 13:34:55 +0200838 # -h
839 # -c value
840 # --config value
841 # --help
842 # --health-check
garciadeblas5697b8b2021-03-24 09:17:02 +0100843 opts, args = getopt.getopt(
844 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
845 )
tierno275411e2018-05-16 14:33:32 +0200846 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
847 config_file = None
848 for o, a in opts:
849 if o in ("-h", "--help"):
850 usage()
851 sys.exit()
852 elif o in ("-c", "--config"):
853 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200854 elif o == "--health-check":
tierno94f06112020-02-11 12:38:19 +0000855 from osm_lcm.lcm_hc import health_check
garciadeblas5697b8b2021-03-24 09:17:02 +0100856
tierno94f06112020-02-11 12:38:19 +0000857 health_check(health_check_file, Lcm.ping_interval_pace)
tierno275411e2018-05-16 14:33:32 +0200858 # elif o == "--log-socket-port":
859 # log_socket_port = a
860 # elif o == "--log-socket-host":
861 # log_socket_host = a
862 # elif o == "--log-file":
863 # log_file = a
864 else:
865 assert False, "Unhandled option"
quilesj7e13aeb2019-10-08 13:34:55 +0200866
tierno275411e2018-05-16 14:33:32 +0200867 if config_file:
868 if not path.isfile(config_file):
garciadeblas5697b8b2021-03-24 09:17:02 +0100869 print(
870 "configuration file '{}' does not exist".format(config_file),
871 file=sys.stderr,
872 )
tierno275411e2018-05-16 14:33:32 +0200873 exit(1)
874 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100875 for config_file in (
876 __file__[: __file__.rfind(".")] + ".cfg",
877 "./lcm.cfg",
878 "/etc/osm/lcm.cfg",
879 ):
tierno275411e2018-05-16 14:33:32 +0200880 if path.isfile(config_file):
881 break
882 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100883 print(
884 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
885 file=sys.stderr,
886 )
tierno275411e2018-05-16 14:33:32 +0200887 exit(1)
888 lcm = Lcm(config_file)
tierno3e359b12019-02-03 02:29:13 +0100889 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200890 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200891 print(str(e), file=sys.stderr)
892 # usage()
893 exit(1)