blob: 7f3342d84d1fd71d1965db1546fc4714a5497999 [file] [log] [blame]
tiernoc0e42e22018-05-11 11:36:10 +02001#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3
4import asyncio
5import yaml
tierno275411e2018-05-16 14:33:32 +02006import logging
7import logging.handlers
8import getopt
tierno275411e2018-05-16 14:33:32 +02009import sys
tiernobce32152018-07-23 16:18:59 +020010import ROclient
tierno59d22d22018-09-25 18:10:19 +020011import ns
12import vim_sdn
Felipe Vicensc2033f22018-11-15 15:09:58 +010013import netslice
tierno59d22d22018-09-25 18:10:19 +020014from lcm_utils import versiontuple, LcmException, TaskRegistry
15
tiernobce32152018-07-23 16:18:59 +020016# from osm_lcm import version as lcm_version, version_date as lcm_version_date, ROclient
tierno98768132018-09-11 12:07:21 +020017from osm_common import dbmemory, dbmongo, fslocal, msglocal, msgkafka
18from osm_common import version as common_version
tierno59d22d22018-09-25 18:10:19 +020019from osm_common.dbbase import DbException
tiernoc0e42e22018-05-11 11:36:10 +020020from osm_common.fsbase import FsException
21from osm_common.msgbase import MsgException
tierno275411e2018-05-16 14:33:32 +020022from os import environ, path
tierno59d22d22018-09-25 18:10:19 +020023from n2vc import version as n2vc_version
tiernoc0e42e22018-05-11 11:36:10 +020024
25
tierno275411e2018-05-16 14:33:32 +020026__author__ = "Alfonso Tierno"
tierno053422d2018-07-10 12:56:43 +020027min_RO_version = [0, 5, 72]
tierno6e9d2eb2018-09-12 17:47:18 +020028min_n2vc_version = "0.0.2"
tierno17a612f2018-10-23 11:30:42 +020029min_common_version = "0.1.11"
tierno86aa62f2018-08-20 11:57:04 +000030# uncomment if LCM is installed as library and installed, and get them from __init__.py
tierno4fa22b02018-11-20 14:56:26 +000031lcm_version = '0.1.25'
32lcm_version_date = '2018-11-20'
tierno275411e2018-05-16 14:33:32 +020033
34
tiernoc0e42e22018-05-11 11:36:10 +020035class Lcm:
36
tiernoa9843d82018-10-24 10:44:20 +020037 ping_interval_pace = 120 # how many time ping is send once is confirmed all is running
tiernof578e552018-11-08 19:07:20 +010038 ping_interval_boot = 5 # how many time ping is sent when booting
tiernoa9843d82018-10-24 10:44:20 +020039
tierno59d22d22018-09-25 18:10:19 +020040 def __init__(self, config_file, loop=None):
tiernoc0e42e22018-05-11 11:36:10 +020041 """
42 Init, Connect to database, filesystem storage, and messaging
43 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
44 :return: None
45 """
46
47 self.db = None
48 self.msg = None
49 self.fs = None
50 self.pings_not_received = 1
51
52 # contains created tasks/futures to be able to cancel
tiernoca2e16a2018-06-29 15:25:24 +020053 self.lcm_tasks = TaskRegistry()
tiernoc0e42e22018-05-11 11:36:10 +020054 # logging
55 self.logger = logging.getLogger('lcm')
56 # load configuration
57 config = self.read_config_file(config_file)
58 self.config = config
tierno750b2452018-05-17 16:39:29 +020059 self.ro_config = {
tiernoc0e42e22018-05-11 11:36:10 +020060 "endpoint_url": "http://{}:{}/openmano".format(config["RO"]["host"], config["RO"]["port"]),
tierno750b2452018-05-17 16:39:29 +020061 "tenant": config.get("tenant", "osm"),
tiernoc0e42e22018-05-11 11:36:10 +020062 "logger_name": "lcm.ROclient",
63 "loglevel": "ERROR",
64 }
65
tierno59d22d22018-09-25 18:10:19 +020066 self.vca_config = config["VCA"]
67
68 self.loop = loop or asyncio.get_event_loop()
tiernoc0e42e22018-05-11 11:36:10 +020069
70 # logging
71 log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
72 log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
73 config["database"]["logger_name"] = "lcm.db"
74 config["storage"]["logger_name"] = "lcm.fs"
75 config["message"]["logger_name"] = "lcm.msg"
tierno86aa62f2018-08-20 11:57:04 +000076 if config["global"].get("logfile"):
tiernoc0e42e22018-05-11 11:36:10 +020077 file_handler = logging.handlers.RotatingFileHandler(config["global"]["logfile"],
78 maxBytes=100e6, backupCount=9, delay=0)
79 file_handler.setFormatter(log_formatter_simple)
80 self.logger.addHandler(file_handler)
tierno86aa62f2018-08-20 11:57:04 +000081 if not config["global"].get("nologging"):
tiernoc0e42e22018-05-11 11:36:10 +020082 str_handler = logging.StreamHandler()
83 str_handler.setFormatter(log_formatter_simple)
84 self.logger.addHandler(str_handler)
85
86 if config["global"].get("loglevel"):
87 self.logger.setLevel(config["global"]["loglevel"])
88
89 # logging other modules
90 for k1, logname in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
91 config[k1]["logger_name"] = logname
92 logger_module = logging.getLogger(logname)
tierno86aa62f2018-08-20 11:57:04 +000093 if config[k1].get("logfile"):
tiernoc0e42e22018-05-11 11:36:10 +020094 file_handler = logging.handlers.RotatingFileHandler(config[k1]["logfile"],
95 maxBytes=100e6, backupCount=9, delay=0)
96 file_handler.setFormatter(log_formatter_simple)
97 logger_module.addHandler(file_handler)
tierno86aa62f2018-08-20 11:57:04 +000098 if config[k1].get("loglevel"):
tiernoc0e42e22018-05-11 11:36:10 +020099 logger_module.setLevel(config[k1]["loglevel"])
tierno86aa62f2018-08-20 11:57:04 +0000100 self.logger.critical("starting osm/lcm version {} {}".format(lcm_version, lcm_version_date))
tierno59d22d22018-09-25 18:10:19 +0200101
tiernoc0e42e22018-05-11 11:36:10 +0200102 # check version of N2VC
103 # TODO enhance with int conversion or from distutils.version import LooseVersion
104 # or with list(map(int, version.split(".")))
tierno59d22d22018-09-25 18:10:19 +0200105 if versiontuple(n2vc_version) < versiontuple(min_n2vc_version):
tierno6e9d2eb2018-09-12 17:47:18 +0200106 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
tierno59d22d22018-09-25 18:10:19 +0200107 n2vc_version, min_n2vc_version))
108 # check version of common
tierno27246d82018-09-27 15:59:09 +0200109 if versiontuple(common_version) < versiontuple(min_common_version):
tierno6e9d2eb2018-09-12 17:47:18 +0200110 raise LcmException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
111 common_version, min_common_version))
tierno22f4f9c2018-06-11 18:53:39 +0200112
tiernoc0e42e22018-05-11 11:36:10 +0200113 try:
tierno22f4f9c2018-06-11 18:53:39 +0200114 # TODO check database version
tiernoc0e42e22018-05-11 11:36:10 +0200115 if config["database"]["driver"] == "mongo":
116 self.db = dbmongo.DbMongo()
117 self.db.db_connect(config["database"])
118 elif config["database"]["driver"] == "memory":
119 self.db = dbmemory.DbMemory()
120 self.db.db_connect(config["database"])
121 else:
122 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
123 config["database"]["driver"]))
124
125 if config["storage"]["driver"] == "local":
126 self.fs = fslocal.FsLocal()
127 self.fs.fs_connect(config["storage"])
128 else:
129 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
130 config["storage"]["driver"]))
131
132 if config["message"]["driver"] == "local":
133 self.msg = msglocal.MsgLocal()
134 self.msg.connect(config["message"])
135 elif config["message"]["driver"] == "kafka":
136 self.msg = msgkafka.MsgKafka()
137 self.msg.connect(config["message"])
138 else:
139 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
140 config["storage"]["driver"]))
141 except (DbException, FsException, MsgException) as e:
142 self.logger.critical(str(e), exc_info=True)
143 raise LcmException(str(e))
144
tierno59d22d22018-09-25 18:10:19 +0200145 self.ns = ns.NsLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config, self.vca_config, self.loop)
Felipe Vicensc2033f22018-11-15 15:09:58 +0100146 self.netslice = netslice.NetsliceLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config,
147 self.vca_config, self.loop)
tierno59d22d22018-09-25 18:10:19 +0200148 self.vim = vim_sdn.VimLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config, self.loop)
149 self.sdn = vim_sdn.SdnLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config, self.loop)
150
tierno22f4f9c2018-06-11 18:53:39 +0200151 async def check_RO_version(self):
152 try:
153 RO = ROclient.ROClient(self.loop, **self.ro_config)
154 RO_version = await RO.get_version()
155 if RO_version < min_RO_version:
156 raise LcmException("Not compatible osm/RO version '{}.{}.{}'. Needed '{}.{}.{}' or higher".format(
157 *RO_version, *min_RO_version
158 ))
159 except ROclient.ROClientException as e:
tierno59d22d22018-09-25 18:10:19 +0200160 error_text = "Error while conneting to osm/RO " + str(e)
161 self.logger.critical(error_text, exc_info=True)
162 raise LcmException(error_text)
tierno22f4f9c2018-06-11 18:53:39 +0200163
tiernoc0e42e22018-05-11 11:36:10 +0200164 async def test(self, param=None):
165 self.logger.debug("Starting/Ending test task: {}".format(param))
166
tiernoc0e42e22018-05-11 11:36:10 +0200167 async def kafka_ping(self):
168 self.logger.debug("Task kafka_ping Enter")
169 consecutive_errors = 0
170 first_start = True
171 kafka_has_received = False
172 self.pings_not_received = 1
173 while True:
174 try:
tierno750b2452018-05-17 16:39:29 +0200175 await self.msg.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self.loop)
tiernoc0e42e22018-05-11 11:36:10 +0200176 # time between pings are low when it is not received and at starting
tiernoa9843d82018-10-24 10:44:20 +0200177 wait_time = self.ping_interval_boot if not kafka_has_received else self.ping_interval_pace
tiernoc0e42e22018-05-11 11:36:10 +0200178 if not self.pings_not_received:
179 kafka_has_received = True
180 self.pings_not_received += 1
181 await asyncio.sleep(wait_time, loop=self.loop)
182 if self.pings_not_received > 10:
183 raise LcmException("It is not receiving pings from Kafka bus")
184 consecutive_errors = 0
185 first_start = False
186 except LcmException:
187 raise
188 except Exception as e:
189 # if not first_start is the first time after starting. So leave more time and wait
190 # to allow kafka starts
191 if consecutive_errors == 8 if not first_start else 30:
192 self.logger.error("Task kafka_read task exit error too many errors. Exception: {}".format(e))
193 raise
194 consecutive_errors += 1
195 self.logger.error("Task kafka_read retrying after Exception {}".format(e))
196 wait_time = 1 if not first_start else 5
197 await asyncio.sleep(wait_time, loop=self.loop)
198
199 async def kafka_read(self):
200 self.logger.debug("Task kafka_read Enter")
201 order_id = 1
202 # future = asyncio.Future()
203 consecutive_errors = 0
204 first_start = True
205 while consecutive_errors < 10:
206 try:
Felipe Vicensc2033f22018-11-15 15:09:58 +0100207 topics = ("admin", "ns", "vim_account", "sdn", "nsi")
tiernoc0e42e22018-05-11 11:36:10 +0200208 topic, command, params = await self.msg.aioread(topics, self.loop)
tierno35b0be72018-05-21 15:13:44 +0200209 if topic != "admin" and command != "ping":
210 self.logger.debug("Task kafka_read receives {} {}: {}".format(topic, command, params))
tiernoc0e42e22018-05-11 11:36:10 +0200211 consecutive_errors = 0
212 first_start = False
213 order_id += 1
214 if command == "exit":
215 print("Bye!")
216 break
217 elif command.startswith("#"):
218 continue
219 elif command == "echo":
220 # just for test
221 print(params)
222 sys.stdout.flush()
223 continue
224 elif command == "test":
225 asyncio.Task(self.test(params), loop=self.loop)
226 continue
227
228 if topic == "admin":
229 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
230 self.pings_not_received = 0
231 continue
232 elif topic == "ns":
233 if command == "instantiate":
234 # self.logger.debug("Deploying NS {}".format(nsr_id))
235 nslcmop = params
236 nslcmop_id = nslcmop["_id"]
237 nsr_id = nslcmop["nsInstanceId"]
tierno59d22d22018-09-25 18:10:19 +0200238 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +0200239 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
tiernoc0e42e22018-05-11 11:36:10 +0200240 continue
241 elif command == "terminate":
242 # self.logger.debug("Deleting NS {}".format(nsr_id))
243 nslcmop = params
244 nslcmop_id = nslcmop["_id"]
245 nsr_id = nslcmop["nsInstanceId"]
tiernoca2e16a2018-06-29 15:25:24 +0200246 self.lcm_tasks.cancel(topic, nsr_id)
tierno59d22d22018-09-25 18:10:19 +0200247 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +0200248 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
tiernoc0e42e22018-05-11 11:36:10 +0200249 continue
250 elif command == "action":
251 # self.logger.debug("Update NS {}".format(nsr_id))
252 nslcmop = params
253 nslcmop_id = nslcmop["_id"]
254 nsr_id = nslcmop["nsInstanceId"]
tierno59d22d22018-09-25 18:10:19 +0200255 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +0200256 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
tiernoc0e42e22018-05-11 11:36:10 +0200257 continue
tierno22f4f9c2018-06-11 18:53:39 +0200258 elif command == "scale":
259 # self.logger.debug("Update NS {}".format(nsr_id))
260 nslcmop = params
261 nslcmop_id = nslcmop["_id"]
262 nsr_id = nslcmop["nsInstanceId"]
tierno59d22d22018-09-25 18:10:19 +0200263 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +0200264 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
tierno22f4f9c2018-06-11 18:53:39 +0200265 continue
tiernoc0e42e22018-05-11 11:36:10 +0200266 elif command == "show":
267 try:
268 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tierno750b2452018-05-17 16:39:29 +0200269 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
270 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
271 "".format(nsr_id, db_nsr["operational-status"], db_nsr["config-status"],
272 db_nsr["detailed-status"],
273 db_nsr["_admin"]["deployed"], self.lcm_ns_tasks.get(nsr_id)))
tiernoc0e42e22018-05-11 11:36:10 +0200274 except Exception as e:
275 print("nsr {} not found: {}".format(nsr_id, e))
276 sys.stdout.flush()
277 continue
278 elif command == "deleted":
279 continue # TODO cleaning of task just in case should be done
tiernoca2e16a2018-06-29 15:25:24 +0200280 elif command in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
281 continue
Felipe Vicensc2033f22018-11-15 15:09:58 +0100282 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
283 if command == "instantiate":
284 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
285 nsilcmop = params
286 nsilcmop_id = nsilcmop["_id"] # slice operation id
287 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
288 task = asyncio.ensure_future(self.netslice.instantiate(nsir_id, nsilcmop_id))
289 self.lcm_tasks.register("nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task)
290 continue
291 elif command == "terminate":
292 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
293 nsilcmop = params
294 nsilcmop_id = nsilcmop["_id"] # slice operation id
295 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
296 self.lcm_tasks.cancel(topic, nsir_id)
297 task = asyncio.ensure_future(self.netslice.terminate(nsir_id, nsilcmop_id))
298 self.lcm_tasks.register("nsi", nsir_id, nsilcmop_id, "nsi_terminate", task)
299 continue
300 elif command == "show":
301 try:
302 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
303 print("nsir:\n _id={}\n operational-status: {}\n config-status: {}"
304 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
305 "".format(nsir_id, db_nsir["operational-status"], db_nsir["config-status"],
306 db_nsir["detailed-status"],
307 db_nsir["_admin"]["deployed"], self.lcm_netslice_tasks.get(nsir_id)))
308 except Exception as e:
309 print("nsir {} not found: {}".format(nsir_id, e))
310 sys.stdout.flush()
311 continue
312 elif command == "deleted":
313 continue # TODO cleaning of task just in case should be done
314 elif command in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
315 continue
tiernoc0e42e22018-05-11 11:36:10 +0200316 elif topic == "vim_account":
317 vim_id = params["_id"]
318 if command == "create":
tierno59d22d22018-09-25 18:10:19 +0200319 task = asyncio.ensure_future(self.vim.create(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200320 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_create", task)
tiernoc0e42e22018-05-11 11:36:10 +0200321 continue
322 elif command == "delete":
tiernoca2e16a2018-06-29 15:25:24 +0200323 self.lcm_tasks.cancel(topic, vim_id)
tierno59d22d22018-09-25 18:10:19 +0200324 task = asyncio.ensure_future(self.vim.delete(vim_id, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200325 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_delete", task)
tiernoc0e42e22018-05-11 11:36:10 +0200326 continue
327 elif command == "show":
328 print("not implemented show with vim_account")
329 sys.stdout.flush()
330 continue
331 elif command == "edit":
tierno59d22d22018-09-25 18:10:19 +0200332 task = asyncio.ensure_future(self.vim.edit(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200333 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_edit", task)
tiernoc0e42e22018-05-11 11:36:10 +0200334 continue
335 elif topic == "sdn":
336 _sdn_id = params["_id"]
337 if command == "create":
tierno59d22d22018-09-25 18:10:19 +0200338 task = asyncio.ensure_future(self.sdn.create(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200339 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_create", task)
tiernoc0e42e22018-05-11 11:36:10 +0200340 continue
341 elif command == "delete":
tiernoca2e16a2018-06-29 15:25:24 +0200342 self.lcm_tasks.cancel(topic, _sdn_id)
tierno59d22d22018-09-25 18:10:19 +0200343 task = asyncio.ensure_future(self.sdn.delete(_sdn_id, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200344 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
tiernoc0e42e22018-05-11 11:36:10 +0200345 continue
346 elif command == "edit":
tierno59d22d22018-09-25 18:10:19 +0200347 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200348 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
tiernoc0e42e22018-05-11 11:36:10 +0200349 continue
350 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
351 except Exception as e:
352 # if not first_start is the first time after starting. So leave more time and wait
353 # to allow kafka starts
354 if consecutive_errors == 8 if not first_start else 30:
355 self.logger.error("Task kafka_read task exit error too many errors. Exception: {}".format(e))
356 raise
357 consecutive_errors += 1
358 self.logger.error("Task kafka_read retrying after Exception {}".format(e))
359 wait_time = 2 if not first_start else 5
360 await asyncio.sleep(wait_time, loop=self.loop)
361
362 # self.logger.debug("Task kafka_read terminating")
363 self.logger.debug("Task kafka_read exit")
364
tiernoa9843d82018-10-24 10:44:20 +0200365 def health_check(self):
366
367 global exit_code
368 task = None
369 exit_code = 1
370
371 def health_check_callback(topic, command, params):
372 global exit_code
373 print("receiving callback {} {} {}".format(topic, command, params))
374 if topic == "admin" and command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
375 # print("received LCM ping")
376 exit_code = 0
377 task.cancel()
378
379 try:
380 task = asyncio.ensure_future(self.msg.aioread(("admin",), self.loop, health_check_callback))
381 self.loop.run_until_complete(task)
382 except Exception:
383 pass
384 exit(exit_code)
385
tiernoc0e42e22018-05-11 11:36:10 +0200386 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200387
388 # check RO version
389 self.loop.run_until_complete(self.check_RO_version())
390
tiernoc0e42e22018-05-11 11:36:10 +0200391 self.loop.run_until_complete(asyncio.gather(
392 self.kafka_read(),
393 self.kafka_ping()
394 ))
395 # TODO
396 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200397 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200398 # timeout = 200
399 # while self.is_pending_tasks():
400 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
401 # await asyncio.sleep(2, loop=self.loop)
402 # timeout -= 2
403 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200404 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200405 self.loop.close()
406 self.loop = None
407 if self.db:
408 self.db.db_disconnect()
409 if self.msg:
410 self.msg.disconnect()
411 if self.fs:
412 self.fs.fs_disconnect()
413
tiernoc0e42e22018-05-11 11:36:10 +0200414 def read_config_file(self, config_file):
415 # TODO make a [ini] + yaml inside parser
416 # the configparser library is not suitable, because it does not admit comments at the end of line,
417 # and not parse integer or boolean
418 try:
419 with open(config_file) as f:
420 conf = yaml.load(f)
421 for k, v in environ.items():
422 if not k.startswith("OSMLCM_"):
423 continue
424 k_items = k.lower().split("_")
tierno17a612f2018-10-23 11:30:42 +0200425 if len(k_items) < 3:
426 continue
427 if k_items[1] in ("ro", "vca"):
428 # put in capital letter
429 k_items[1] = k_items[1].upper()
tiernoc0e42e22018-05-11 11:36:10 +0200430 c = conf
431 try:
432 for k_item in k_items[1:-1]:
tiernoc0e42e22018-05-11 11:36:10 +0200433 c = c[k_item]
434 if k_items[-1] == "port":
435 c[k_items[-1]] = int(v)
436 else:
437 c[k_items[-1]] = v
438 except Exception as e:
439 self.logger.warn("skipping environ '{}' on exception '{}'".format(k, e))
440
441 return conf
442 except Exception as e:
443 self.logger.critical("At config file '{}': {}".format(config_file, e))
444 exit(1)
445
446
tierno275411e2018-05-16 14:33:32 +0200447def usage():
448 print("""Usage: {} [options]
449 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200450 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200451 -h|--help: shows this help
452 """.format(sys.argv[0]))
tierno750b2452018-05-17 16:39:29 +0200453 # --log-socket-host HOST: send logs to this host")
454 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200455
456
tiernoc0e42e22018-05-11 11:36:10 +0200457if __name__ == '__main__':
tierno275411e2018-05-16 14:33:32 +0200458 try:
459 # load parameters and configuration
tiernoa9843d82018-10-24 10:44:20 +0200460 opts, args = getopt.getopt(sys.argv[1:], "hc:", ["config=", "help", "health-check"])
tierno275411e2018-05-16 14:33:32 +0200461 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
462 config_file = None
tiernoa9843d82018-10-24 10:44:20 +0200463 health_check = None
tierno275411e2018-05-16 14:33:32 +0200464 for o, a in opts:
465 if o in ("-h", "--help"):
466 usage()
467 sys.exit()
468 elif o in ("-c", "--config"):
469 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200470 elif o == "--health-check":
471 health_check = True
tierno275411e2018-05-16 14:33:32 +0200472 # elif o == "--log-socket-port":
473 # log_socket_port = a
474 # elif o == "--log-socket-host":
475 # log_socket_host = a
476 # elif o == "--log-file":
477 # log_file = a
478 else:
479 assert False, "Unhandled option"
480 if config_file:
481 if not path.isfile(config_file):
tierno17a612f2018-10-23 11:30:42 +0200482 print("configuration file '{}' not exist".format(config_file), file=sys.stderr)
tierno275411e2018-05-16 14:33:32 +0200483 exit(1)
484 else:
485 for config_file in (__file__[:__file__.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
486 if path.isfile(config_file):
487 break
488 else:
tierno17a612f2018-10-23 11:30:42 +0200489 print("No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/", file=sys.stderr)
tierno275411e2018-05-16 14:33:32 +0200490 exit(1)
491 lcm = Lcm(config_file)
tiernoa9843d82018-10-24 10:44:20 +0200492 if health_check:
493 lcm.health_check()
494 else:
495 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200496 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200497 print(str(e), file=sys.stderr)
498 # usage()
499 exit(1)