blob: 6202b328b2f977dc0b8676e80647605ac9c499c4 [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
sousaedub1e07452021-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
tierno991e95d2020-07-21 12:41:25 +0000218 if self.config.get("tsdb") and self.config["tsdb"].get("driver"):
219 if self.config["tsdb"]["driver"] == "prometheus":
garciadeblas5697b8b2021-03-24 09:17:02 +0100220 self.prometheus = prometheus.Prometheus(
221 self.config["tsdb"], self.worker_id, self.loop
222 )
tierno991e95d2020-07-21 12:41:25 +0000223 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100224 raise LcmException(
225 "Invalid configuration param '{}' at '[tsdb]':'driver'".format(
226 config["tsdb"]["driver"]
227 )
228 )
tiernob996d942020-07-03 14:52:28 +0000229 else:
230 self.prometheus = None
tierno59d22d22018-09-25 18:10:19 +0200231
tierno22f4f9c2018-06-11 18:53:39 +0200232 async def check_RO_version(self):
tiernoe64f7fb2019-09-11 08:55:52 +0000233 tries = 14
234 last_error = None
235 while True:
tierno2357f4e2020-10-19 16:38:59 +0000236 ro_uri = self.config["ro_config"]["uri"]
tiernoe64f7fb2019-09-11 08:55:52 +0000237 try:
tierno2357f4e2020-10-19 16:38:59 +0000238 # try new RO, if fail old RO
239 try:
240 self.config["ro_config"]["uri"] = ro_uri + "ro"
tierno69f0d382020-05-07 13:08:09 +0000241 ro_server = NgRoClient(self.loop, **self.config["ro_config"])
tierno2357f4e2020-10-19 16:38:59 +0000242 ro_version = await ro_server.get_version()
243 self.config["ro_config"]["ng"] = True
244 except Exception:
245 self.config["ro_config"]["uri"] = ro_uri + "openmano"
tierno69f0d382020-05-07 13:08:09 +0000246 ro_server = ROClient(self.loop, **self.config["ro_config"])
tierno2357f4e2020-10-19 16:38:59 +0000247 ro_version = await ro_server.get_version()
248 self.config["ro_config"]["ng"] = False
tiernoe64f7fb2019-09-11 08:55:52 +0000249 if versiontuple(ro_version) < versiontuple(min_RO_version):
garciadeblas5697b8b2021-03-24 09:17:02 +0100250 raise LcmException(
251 "Not compatible osm/RO version '{}'. Needed '{}' or higher".format(
252 ro_version, min_RO_version
253 )
254 )
255 self.logger.info(
256 "Connected to RO version {} new-generation version {}".format(
257 ro_version, self.config["ro_config"]["ng"]
258 )
259 )
tiernoe64f7fb2019-09-11 08:55:52 +0000260 return
tierno69f0d382020-05-07 13:08:09 +0000261 except (ROClientException, NgRoException) as e:
tierno2357f4e2020-10-19 16:38:59 +0000262 self.config["ro_config"]["uri"] = ro_uri
tiernoe64f7fb2019-09-11 08:55:52 +0000263 tries -= 1
bravof922c4172020-11-24 21:21:43 -0300264 traceback.print_tb(e.__traceback__)
garciadeblas5697b8b2021-03-24 09:17:02 +0100265 error_text = "Error while connecting to RO on {}: {}".format(
266 self.config["ro_config"]["uri"], e
267 )
tiernoe64f7fb2019-09-11 08:55:52 +0000268 if tries <= 0:
269 self.logger.critical(error_text)
270 raise LcmException(error_text)
271 if last_error != error_text:
272 last_error = error_text
garciadeblas5697b8b2021-03-24 09:17:02 +0100273 self.logger.error(
274 error_text + ". Waiting until {} seconds".format(5 * tries)
275 )
tiernoe64f7fb2019-09-11 08:55:52 +0000276 await asyncio.sleep(5)
tierno22f4f9c2018-06-11 18:53:39 +0200277
tiernoc0e42e22018-05-11 11:36:10 +0200278 async def test(self, param=None):
279 self.logger.debug("Starting/Ending test task: {}".format(param))
280
tiernoc0e42e22018-05-11 11:36:10 +0200281 async def kafka_ping(self):
282 self.logger.debug("Task kafka_ping Enter")
283 consecutive_errors = 0
284 first_start = True
285 kafka_has_received = False
286 self.pings_not_received = 1
287 while True:
288 try:
tierno16427352019-04-22 11:37:36 +0000289 await self.msg_admin.aiowrite(
garciadeblas5697b8b2021-03-24 09:17:02 +0100290 "admin",
291 "ping",
292 {
293 "from": "lcm",
294 "to": "lcm",
295 "worker_id": self.worker_id,
296 "version": lcm_version,
297 },
298 self.loop,
299 )
tiernoc0e42e22018-05-11 11:36:10 +0200300 # time between pings are low when it is not received and at starting
garciadeblas5697b8b2021-03-24 09:17:02 +0100301 wait_time = (
302 self.ping_interval_boot
303 if not kafka_has_received
304 else self.ping_interval_pace
305 )
tiernoc0e42e22018-05-11 11:36:10 +0200306 if not self.pings_not_received:
307 kafka_has_received = True
308 self.pings_not_received += 1
309 await asyncio.sleep(wait_time, loop=self.loop)
310 if self.pings_not_received > 10:
311 raise LcmException("It is not receiving pings from Kafka bus")
312 consecutive_errors = 0
313 first_start = False
314 except LcmException:
315 raise
316 except Exception as e:
317 # if not first_start is the first time after starting. So leave more time and wait
318 # to allow kafka starts
319 if consecutive_errors == 8 if not first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100320 self.logger.error(
321 "Task kafka_read task exit error too many errors. Exception: {}".format(
322 e
323 )
324 )
tiernoc0e42e22018-05-11 11:36:10 +0200325 raise
326 consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100327 self.logger.error(
328 "Task kafka_read retrying after Exception {}".format(e)
329 )
tierno16427352019-04-22 11:37:36 +0000330 wait_time = 2 if not first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200331 await asyncio.sleep(wait_time, loop=self.loop)
332
gcalvinoed7f6d42018-12-14 14:44:56 +0100333 def kafka_read_callback(self, topic, command, params):
334 order_id = 1
335
336 if topic != "admin" and command != "ping":
garciadeblas5697b8b2021-03-24 09:17:02 +0100337 self.logger.debug(
338 "Task kafka_read receives {} {}: {}".format(topic, command, params)
339 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100340 self.consecutive_errors = 0
341 self.first_start = False
342 order_id += 1
343 if command == "exit":
344 raise LcmExceptionExit
345 elif command.startswith("#"):
346 return
347 elif command == "echo":
348 # just for test
349 print(params)
350 sys.stdout.flush()
351 return
352 elif command == "test":
353 asyncio.Task(self.test(params), loop=self.loop)
354 return
355
356 if topic == "admin":
357 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
tierno16427352019-04-22 11:37:36 +0000358 if params.get("worker_id") != self.worker_id:
359 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100360 self.pings_not_received = 0
tierno3e359b12019-02-03 02:29:13 +0100361 try:
362 with open(health_check_file, "w") as f:
363 f.write(str(time()))
364 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100365 self.logger.error(
366 "Cannot write into '{}' for healthcheck: {}".format(
367 health_check_file, e
368 )
369 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100370 return
magnussonle9198bb2020-01-21 13:00:51 +0100371 elif topic == "pla":
372 if command == "placement":
373 self.ns.update_nsrs_with_pla_result(params)
374 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100375 elif topic == "k8scluster":
376 if command == "create" or command == "created":
377 k8scluster_id = params.get("_id")
378 task = asyncio.ensure_future(self.k8scluster.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100379 self.lcm_tasks.register(
380 "k8scluster", k8scluster_id, order_id, "k8scluster_create", task
381 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100382 return
383 elif command == "delete" or command == "deleted":
384 k8scluster_id = params.get("_id")
385 task = asyncio.ensure_future(self.k8scluster.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100386 self.lcm_tasks.register(
387 "k8scluster", k8scluster_id, order_id, "k8scluster_delete", task
388 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100389 return
David Garciac1fe90a2021-03-31 19:12:02 +0200390 elif topic == "vca":
391 if command == "create" or command == "created":
392 vca_id = params.get("_id")
393 task = asyncio.ensure_future(self.vca.create(params, order_id))
394 self.lcm_tasks.register("vca", vca_id, order_id, "vca_create", task)
395 return
396 elif command == "delete" or command == "deleted":
397 vca_id = params.get("_id")
398 task = asyncio.ensure_future(self.vca.delete(params, order_id))
399 self.lcm_tasks.register("vca", vca_id, order_id, "vca_delete", task)
400 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100401 elif topic == "k8srepo":
402 if command == "create" or command == "created":
403 k8srepo_id = params.get("_id")
404 self.logger.debug("k8srepo_id = {}".format(k8srepo_id))
405 task = asyncio.ensure_future(self.k8srepo.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100406 self.lcm_tasks.register(
407 "k8srepo", k8srepo_id, order_id, "k8srepo_create", task
408 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100409 return
410 elif command == "delete" or command == "deleted":
411 k8srepo_id = params.get("_id")
412 task = asyncio.ensure_future(self.k8srepo.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100413 self.lcm_tasks.register(
414 "k8srepo", k8srepo_id, order_id, "k8srepo_delete", task
415 )
calvinosanch9f9c6f22019-11-04 13:37:39 +0100416 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100417 elif topic == "ns":
tierno307425f2020-01-26 23:35:59 +0000418 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100419 # self.logger.debug("Deploying NS {}".format(nsr_id))
420 nslcmop = params
421 nslcmop_id = nslcmop["_id"]
422 nsr_id = nslcmop["nsInstanceId"]
423 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100424 self.lcm_tasks.register(
425 "ns", nsr_id, nslcmop_id, "ns_instantiate", task
426 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100427 return
tierno307425f2020-01-26 23:35:59 +0000428 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100429 # self.logger.debug("Deleting NS {}".format(nsr_id))
430 nslcmop = params
431 nslcmop_id = nslcmop["_id"]
432 nsr_id = nslcmop["nsInstanceId"]
433 self.lcm_tasks.cancel(topic, nsr_id)
434 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
435 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
436 return
ksaikiranr3fde2c72021-03-15 10:39:06 +0530437 elif command == "vca_status_refresh":
438 nslcmop = params
439 nslcmop_id = nslcmop["_id"]
440 nsr_id = nslcmop["nsInstanceId"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100441 task = asyncio.ensure_future(
442 self.ns.vca_status_refresh(nsr_id, nslcmop_id)
443 )
444 self.lcm_tasks.register(
445 "ns", nsr_id, nslcmop_id, "ns_vca_status_refresh", task
446 )
ksaikiranr3fde2c72021-03-15 10:39:06 +0530447 return
gcalvinoed7f6d42018-12-14 14:44:56 +0100448 elif command == "action":
449 # self.logger.debug("Update NS {}".format(nsr_id))
450 nslcmop = params
451 nslcmop_id = nslcmop["_id"]
452 nsr_id = nslcmop["nsInstanceId"]
453 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
454 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
455 return
456 elif command == "scale":
457 # self.logger.debug("Update NS {}".format(nsr_id))
458 nslcmop = params
459 nslcmop_id = nslcmop["_id"]
460 nsr_id = nslcmop["nsInstanceId"]
461 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
462 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
463 return
464 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000465 nsr_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100466 try:
467 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100468 print(
469 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
470 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
471 "".format(
472 nsr_id,
473 db_nsr["operational-status"],
474 db_nsr["config-status"],
475 db_nsr["detailed-status"],
476 db_nsr["_admin"]["deployed"],
477 self.lcm_ns_tasks.get(nsr_id),
478 )
479 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100480 except Exception as e:
481 print("nsr {} not found: {}".format(nsr_id, e))
482 sys.stdout.flush()
483 return
484 elif command == "deleted":
485 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100486 elif command in (
487 "terminated",
488 "instantiated",
489 "scaled",
490 "actioned",
491 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100492 return
493 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
tierno307425f2020-01-26 23:35:59 +0000494 if command == "instantiate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100495 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
496 nsilcmop = params
497 nsilcmop_id = nsilcmop["_id"] # slice operation id
498 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
garciadeblas5697b8b2021-03-24 09:17:02 +0100499 task = asyncio.ensure_future(
500 self.netslice.instantiate(nsir_id, nsilcmop_id)
501 )
502 self.lcm_tasks.register(
503 "nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task
504 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100505 return
tierno307425f2020-01-26 23:35:59 +0000506 elif command == "terminate":
gcalvinoed7f6d42018-12-14 14:44:56 +0100507 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
508 nsilcmop = params
509 nsilcmop_id = nsilcmop["_id"] # slice operation id
510 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
511 self.lcm_tasks.cancel(topic, nsir_id)
garciadeblas5697b8b2021-03-24 09:17:02 +0100512 task = asyncio.ensure_future(
513 self.netslice.terminate(nsir_id, nsilcmop_id)
514 )
515 self.lcm_tasks.register(
516 "nsi", nsir_id, nsilcmop_id, "nsi_terminate", task
517 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100518 return
519 elif command == "show":
tiernoc2564fe2019-01-28 16:18:56 +0000520 nsir_id = params
gcalvinoed7f6d42018-12-14 14:44:56 +0100521 try:
522 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100523 print(
524 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
525 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
526 "".format(
527 nsir_id,
528 db_nsir["operational-status"],
529 db_nsir["config-status"],
530 db_nsir["detailed-status"],
531 db_nsir["_admin"]["deployed"],
532 self.lcm_netslice_tasks.get(nsir_id),
533 )
534 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100535 except Exception as e:
536 print("nsir {} not found: {}".format(nsir_id, e))
537 sys.stdout.flush()
538 return
539 elif command == "deleted":
540 return # TODO cleaning of task just in case should be done
garciadeblas5697b8b2021-03-24 09:17:02 +0100541 elif command in (
542 "terminated",
543 "instantiated",
544 "scaled",
545 "actioned",
546 ): # "scaled-cooldown-time"
gcalvinoed7f6d42018-12-14 14:44:56 +0100547 return
548 elif topic == "vim_account":
549 vim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000550 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000551 if not self.config["ro_config"].get("ng"):
552 task = asyncio.ensure_future(self.vim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100553 self.lcm_tasks.register(
554 "vim_account", vim_id, order_id, "vim_create", task
555 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100556 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100557 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100558 self.lcm_tasks.cancel(topic, vim_id)
kuuse6a470c62019-07-10 13:52:45 +0200559 task = asyncio.ensure_future(self.vim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100560 self.lcm_tasks.register(
561 "vim_account", vim_id, order_id, "vim_delete", task
562 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100563 return
564 elif command == "show":
565 print("not implemented show with vim_account")
566 sys.stdout.flush()
567 return
tiernof210c1c2019-10-16 09:09:58 +0000568 elif command in ("edit", "edited"):
tierno2357f4e2020-10-19 16:38:59 +0000569 if not self.config["ro_config"].get("ng"):
570 task = asyncio.ensure_future(self.vim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100571 self.lcm_tasks.register(
572 "vim_account", vim_id, order_id, "vim_edit", task
573 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100574 return
tiernof210c1c2019-10-16 09:09:58 +0000575 elif command == "deleted":
576 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100577 elif topic == "wim_account":
578 wim_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000579 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000580 if not self.config["ro_config"].get("ng"):
581 task = asyncio.ensure_future(self.wim.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100582 self.lcm_tasks.register(
583 "wim_account", wim_id, order_id, "wim_create", task
584 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100585 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100586 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100587 self.lcm_tasks.cancel(topic, wim_id)
kuuse6a470c62019-07-10 13:52:45 +0200588 task = asyncio.ensure_future(self.wim.delete(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100589 self.lcm_tasks.register(
590 "wim_account", wim_id, order_id, "wim_delete", task
591 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100592 return
593 elif command == "show":
594 print("not implemented show with wim_account")
595 sys.stdout.flush()
596 return
tiernof210c1c2019-10-16 09:09:58 +0000597 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100598 task = asyncio.ensure_future(self.wim.edit(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100599 self.lcm_tasks.register(
600 "wim_account", wim_id, order_id, "wim_edit", task
601 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100602 return
tiernof210c1c2019-10-16 09:09:58 +0000603 elif command == "deleted":
604 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100605 elif topic == "sdn":
606 _sdn_id = params["_id"]
tiernof210c1c2019-10-16 09:09:58 +0000607 if command in ("create", "created"):
tierno2357f4e2020-10-19 16:38:59 +0000608 if not self.config["ro_config"].get("ng"):
609 task = asyncio.ensure_future(self.sdn.create(params, order_id))
garciadeblas5697b8b2021-03-24 09:17:02 +0100610 self.lcm_tasks.register(
611 "sdn", _sdn_id, order_id, "sdn_create", task
612 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100613 return
calvinosanch9f9c6f22019-11-04 13:37:39 +0100614 elif command == "delete" or command == "deleted":
gcalvinoed7f6d42018-12-14 14:44:56 +0100615 self.lcm_tasks.cancel(topic, _sdn_id)
kuuse6a470c62019-07-10 13:52:45 +0200616 task = asyncio.ensure_future(self.sdn.delete(params, order_id))
gcalvinoed7f6d42018-12-14 14:44:56 +0100617 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
618 return
tiernof210c1c2019-10-16 09:09:58 +0000619 elif command in ("edit", "edited"):
gcalvinoed7f6d42018-12-14 14:44:56 +0100620 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
621 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
622 return
tiernof210c1c2019-10-16 09:09:58 +0000623 elif command == "deleted":
624 return # TODO cleaning of task just in case should be done
gcalvinoed7f6d42018-12-14 14:44:56 +0100625 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
626
tiernoc0e42e22018-05-11 11:36:10 +0200627 async def kafka_read(self):
garciadeblas5697b8b2021-03-24 09:17:02 +0100628 self.logger.debug(
629 "Task kafka_read Enter with worker_id={}".format(self.worker_id)
630 )
tiernoc0e42e22018-05-11 11:36:10 +0200631 # future = asyncio.Future()
gcalvinoed7f6d42018-12-14 14:44:56 +0100632 self.consecutive_errors = 0
633 self.first_start = True
634 while self.consecutive_errors < 10:
tiernoc0e42e22018-05-11 11:36:10 +0200635 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100636 topics = (
637 "ns",
638 "vim_account",
639 "wim_account",
640 "sdn",
641 "nsi",
642 "k8scluster",
643 "vca",
644 "k8srepo",
645 "pla",
646 )
647 topics_admin = ("admin",)
tierno16427352019-04-22 11:37:36 +0000648 await asyncio.gather(
garciadeblas5697b8b2021-03-24 09:17:02 +0100649 self.msg.aioread(
650 topics, self.loop, self.kafka_read_callback, from_beginning=True
651 ),
652 self.msg_admin.aioread(
653 topics_admin,
654 self.loop,
655 self.kafka_read_callback,
656 group_id=False,
657 ),
tierno16427352019-04-22 11:37:36 +0000658 )
tiernoc0e42e22018-05-11 11:36:10 +0200659
gcalvinoed7f6d42018-12-14 14:44:56 +0100660 except LcmExceptionExit:
661 self.logger.debug("Bye!")
662 break
tiernoc0e42e22018-05-11 11:36:10 +0200663 except Exception as e:
664 # if not first_start is the first time after starting. So leave more time and wait
665 # to allow kafka starts
gcalvinoed7f6d42018-12-14 14:44:56 +0100666 if self.consecutive_errors == 8 if not self.first_start else 30:
garciadeblas5697b8b2021-03-24 09:17:02 +0100667 self.logger.error(
668 "Task kafka_read task exit error too many errors. Exception: {}".format(
669 e
670 )
671 )
tiernoc0e42e22018-05-11 11:36:10 +0200672 raise
gcalvinoed7f6d42018-12-14 14:44:56 +0100673 self.consecutive_errors += 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100674 self.logger.error(
675 "Task kafka_read retrying after Exception {}".format(e)
676 )
gcalvinoed7f6d42018-12-14 14:44:56 +0100677 wait_time = 2 if not self.first_start else 5
tiernoc0e42e22018-05-11 11:36:10 +0200678 await asyncio.sleep(wait_time, loop=self.loop)
679
680 # self.logger.debug("Task kafka_read terminating")
681 self.logger.debug("Task kafka_read exit")
682
683 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200684
685 # check RO version
686 self.loop.run_until_complete(self.check_RO_version())
687
garciadeblas5697b8b2021-03-24 09:17:02 +0100688 self.ns = ns.NsLcm(
689 self.msg, self.lcm_tasks, self.config, self.loop, self.prometheus
690 )
691 self.netslice = netslice.NetsliceLcm(
692 self.msg, self.lcm_tasks, self.config, self.loop, self.ns
693 )
bravof922c4172020-11-24 21:21:43 -0300694 self.vim = vim_sdn.VimLcm(self.msg, self.lcm_tasks, self.config, self.loop)
695 self.wim = vim_sdn.WimLcm(self.msg, self.lcm_tasks, self.config, self.loop)
696 self.sdn = vim_sdn.SdnLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100697 self.k8scluster = vim_sdn.K8sClusterLcm(
698 self.msg, self.lcm_tasks, self.config, self.loop
699 )
David Garciac1fe90a2021-03-31 19:12:02 +0200700 self.vca = vim_sdn.VcaLcm(self.msg, self.lcm_tasks, self.config, self.loop)
garciadeblas5697b8b2021-03-24 09:17:02 +0100701 self.k8srepo = vim_sdn.K8sRepoLcm(
702 self.msg, self.lcm_tasks, self.config, self.loop
703 )
tierno2357f4e2020-10-19 16:38:59 +0000704
tierno991e95d2020-07-21 12:41:25 +0000705 # configure tsdb prometheus
tiernob996d942020-07-03 14:52:28 +0000706 if self.prometheus:
707 self.loop.run_until_complete(self.prometheus.start())
708
garciadeblas5697b8b2021-03-24 09:17:02 +0100709 self.loop.run_until_complete(
710 asyncio.gather(self.kafka_read(), self.kafka_ping())
711 )
tiernoc0e42e22018-05-11 11:36:10 +0200712 # TODO
713 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200714 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200715 # timeout = 200
716 # while self.is_pending_tasks():
717 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
718 # await asyncio.sleep(2, loop=self.loop)
719 # timeout -= 2
720 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200721 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200722 self.loop.close()
723 self.loop = None
724 if self.db:
725 self.db.db_disconnect()
726 if self.msg:
727 self.msg.disconnect()
tierno16427352019-04-22 11:37:36 +0000728 if self.msg_admin:
729 self.msg_admin.disconnect()
tiernoc0e42e22018-05-11 11:36:10 +0200730 if self.fs:
731 self.fs.fs_disconnect()
732
tiernoc0e42e22018-05-11 11:36:10 +0200733 def read_config_file(self, config_file):
734 # TODO make a [ini] + yaml inside parser
735 # the configparser library is not suitable, because it does not admit comments at the end of line,
736 # and not parse integer or boolean
737 try:
tierno744303e2020-01-13 16:46:31 +0000738 # read file as yaml format
tiernoc0e42e22018-05-11 11:36:10 +0200739 with open(config_file) as f:
tiernoda6fb102019-11-23 00:36:52 +0000740 conf = yaml.load(f, Loader=yaml.Loader)
tierno744303e2020-01-13 16:46:31 +0000741 # Ensure all sections are not empty
garciadeblas5697b8b2021-03-24 09:17:02 +0100742 for k in (
743 "global",
744 "timeout",
745 "RO",
746 "VCA",
747 "database",
748 "storage",
749 "message",
750 ):
tierno744303e2020-01-13 16:46:31 +0000751 if not conf.get(k):
752 conf[k] = {}
753
754 # read all environ that starts with OSMLCM_
tiernoc0e42e22018-05-11 11:36:10 +0200755 for k, v in environ.items():
756 if not k.startswith("OSMLCM_"):
757 continue
tierno744303e2020-01-13 16:46:31 +0000758 subject, _, item = k[7:].lower().partition("_")
759 if not item:
tierno17a612f2018-10-23 11:30:42 +0200760 continue
tierno744303e2020-01-13 16:46:31 +0000761 if subject in ("ro", "vca"):
tierno17a612f2018-10-23 11:30:42 +0200762 # put in capital letter
tierno744303e2020-01-13 16:46:31 +0000763 subject = subject.upper()
tiernoc0e42e22018-05-11 11:36:10 +0200764 try:
tierno744303e2020-01-13 16:46:31 +0000765 if item == "port" or subject == "timeout":
766 conf[subject][item] = int(v)
tiernoc0e42e22018-05-11 11:36:10 +0200767 else:
tierno744303e2020-01-13 16:46:31 +0000768 conf[subject][item] = v
tiernoc0e42e22018-05-11 11:36:10 +0200769 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100770 self.logger.warning(
771 "skipping environ '{}' on exception '{}'".format(k, e)
772 )
tierno744303e2020-01-13 16:46:31 +0000773
774 # backward compatibility of VCA parameters
775
garciadeblas5697b8b2021-03-24 09:17:02 +0100776 if "pubkey" in conf["VCA"]:
777 conf["VCA"]["public_key"] = conf["VCA"].pop("pubkey")
778 if "cacert" in conf["VCA"]:
779 conf["VCA"]["ca_cert"] = conf["VCA"].pop("cacert")
780 if "apiproxy" in conf["VCA"]:
781 conf["VCA"]["api_proxy"] = conf["VCA"].pop("apiproxy")
tierno744303e2020-01-13 16:46:31 +0000782
garciadeblas5697b8b2021-03-24 09:17:02 +0100783 if "enableosupgrade" in conf["VCA"]:
784 conf["VCA"]["enable_os_upgrade"] = conf["VCA"].pop("enableosupgrade")
785 if isinstance(conf["VCA"].get("enable_os_upgrade"), str):
786 if conf["VCA"]["enable_os_upgrade"].lower() == "false":
787 conf["VCA"]["enable_os_upgrade"] = False
788 elif conf["VCA"]["enable_os_upgrade"].lower() == "true":
789 conf["VCA"]["enable_os_upgrade"] = True
tierno744303e2020-01-13 16:46:31 +0000790
garciadeblas5697b8b2021-03-24 09:17:02 +0100791 if "aptmirror" in conf["VCA"]:
792 conf["VCA"]["apt_mirror"] = conf["VCA"].pop("aptmirror")
tiernoc0e42e22018-05-11 11:36:10 +0200793
794 return conf
795 except Exception as e:
796 self.logger.critical("At config file '{}': {}".format(config_file, e))
797 exit(1)
798
tierno16427352019-04-22 11:37:36 +0000799 @staticmethod
800 def get_process_id():
801 """
802 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
803 will provide a random one
804 :return: Obtained ID
805 """
806 # Try getting docker id. If fails, get pid
807 try:
808 with open("/proc/self/cgroup", "r") as f:
809 text_id_ = f.readline()
810 _, _, text_id = text_id_.rpartition("/")
garciadeblas5697b8b2021-03-24 09:17:02 +0100811 text_id = text_id.replace("\n", "")[:12]
tierno16427352019-04-22 11:37:36 +0000812 if text_id:
813 return text_id
814 except Exception:
815 pass
816 # Return a random id
garciadeblas5697b8b2021-03-24 09:17:02 +0100817 return "".join(random_choice("0123456789abcdef") for _ in range(12))
tierno16427352019-04-22 11:37:36 +0000818
tiernoc0e42e22018-05-11 11:36:10 +0200819
tierno275411e2018-05-16 14:33:32 +0200820def usage():
garciadeblas5697b8b2021-03-24 09:17:02 +0100821 print(
822 """Usage: {} [options]
quilesj7e13aeb2019-10-08 13:34:55 +0200823 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200824 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200825 -h|--help: shows this help
garciadeblas5697b8b2021-03-24 09:17:02 +0100826 """.format(
827 sys.argv[0]
828 )
829 )
tierno750b2452018-05-17 16:39:29 +0200830 # --log-socket-host HOST: send logs to this host")
831 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200832
833
garciadeblas5697b8b2021-03-24 09:17:02 +0100834if __name__ == "__main__":
quilesj7e13aeb2019-10-08 13:34:55 +0200835
tierno275411e2018-05-16 14:33:32 +0200836 try:
tierno8c16b052020-02-05 15:08:32 +0000837 # print("SYS.PATH='{}'".format(sys.path))
tierno275411e2018-05-16 14:33:32 +0200838 # load parameters and configuration
quilesj7e13aeb2019-10-08 13:34:55 +0200839 # -h
840 # -c value
841 # --config value
842 # --help
843 # --health-check
garciadeblas5697b8b2021-03-24 09:17:02 +0100844 opts, args = getopt.getopt(
845 sys.argv[1:], "hc:", ["config=", "help", "health-check"]
846 )
tierno275411e2018-05-16 14:33:32 +0200847 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
848 config_file = None
849 for o, a in opts:
850 if o in ("-h", "--help"):
851 usage()
852 sys.exit()
853 elif o in ("-c", "--config"):
854 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200855 elif o == "--health-check":
tierno94f06112020-02-11 12:38:19 +0000856 from osm_lcm.lcm_hc import health_check
garciadeblas5697b8b2021-03-24 09:17:02 +0100857
tierno94f06112020-02-11 12:38:19 +0000858 health_check(health_check_file, Lcm.ping_interval_pace)
tierno275411e2018-05-16 14:33:32 +0200859 # elif o == "--log-socket-port":
860 # log_socket_port = a
861 # elif o == "--log-socket-host":
862 # log_socket_host = a
863 # elif o == "--log-file":
864 # log_file = a
865 else:
866 assert False, "Unhandled option"
quilesj7e13aeb2019-10-08 13:34:55 +0200867
tierno275411e2018-05-16 14:33:32 +0200868 if config_file:
869 if not path.isfile(config_file):
garciadeblas5697b8b2021-03-24 09:17:02 +0100870 print(
871 "configuration file '{}' does not exist".format(config_file),
872 file=sys.stderr,
873 )
tierno275411e2018-05-16 14:33:32 +0200874 exit(1)
875 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100876 for config_file in (
877 __file__[: __file__.rfind(".")] + ".cfg",
878 "./lcm.cfg",
879 "/etc/osm/lcm.cfg",
880 ):
tierno275411e2018-05-16 14:33:32 +0200881 if path.isfile(config_file):
882 break
883 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100884 print(
885 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
886 file=sys.stderr,
887 )
tierno275411e2018-05-16 14:33:32 +0200888 exit(1)
889 lcm = Lcm(config_file)
tierno3e359b12019-02-03 02:29:13 +0100890 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200891 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200892 print(str(e), file=sys.stderr)
893 # usage()
894 exit(1)