blob: 568168301c77bd4198de5765ca08afd701e1caec [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
tiernoc0e42e22018-05-11 11:36:10 +020020import asyncio
21import yaml
tierno275411e2018-05-16 14:33:32 +020022import logging
23import logging.handlers
24import getopt
tierno275411e2018-05-16 14:33:32 +020025import sys
tiernobce32152018-07-23 16:18:59 +020026import ROclient
tierno59d22d22018-09-25 18:10:19 +020027import ns
28import vim_sdn
Felipe Vicensc2033f22018-11-15 15:09:58 +010029import netslice
tierno59d22d22018-09-25 18:10:19 +020030from lcm_utils import versiontuple, LcmException, TaskRegistry
31
tiernobce32152018-07-23 16:18:59 +020032# from osm_lcm import version as lcm_version, version_date as lcm_version_date, ROclient
tierno98768132018-09-11 12:07:21 +020033from osm_common import dbmemory, dbmongo, fslocal, msglocal, msgkafka
34from osm_common import version as common_version
tierno59d22d22018-09-25 18:10:19 +020035from osm_common.dbbase import DbException
tiernoc0e42e22018-05-11 11:36:10 +020036from osm_common.fsbase import FsException
37from osm_common.msgbase import MsgException
tierno275411e2018-05-16 14:33:32 +020038from os import environ, path
tierno59d22d22018-09-25 18:10:19 +020039from n2vc import version as n2vc_version
tiernoc0e42e22018-05-11 11:36:10 +020040
41
tierno275411e2018-05-16 14:33:32 +020042__author__ = "Alfonso Tierno"
tiernoe37b57d2018-12-11 17:22:51 +000043min_RO_version = [0, 6, 0]
tierno6e9d2eb2018-09-12 17:47:18 +020044min_n2vc_version = "0.0.2"
tierno17a612f2018-10-23 11:30:42 +020045min_common_version = "0.1.11"
tierno86aa62f2018-08-20 11:57:04 +000046# uncomment if LCM is installed as library and installed, and get them from __init__.py
tiernoeb55b012018-11-29 08:10:04 +000047lcm_version = '0.1.28'
48lcm_version_date = '2018-11-29'
tierno275411e2018-05-16 14:33:32 +020049
50
tiernoc0e42e22018-05-11 11:36:10 +020051class Lcm:
52
tiernoa9843d82018-10-24 10:44:20 +020053 ping_interval_pace = 120 # how many time ping is send once is confirmed all is running
tiernof578e552018-11-08 19:07:20 +010054 ping_interval_boot = 5 # how many time ping is sent when booting
tiernoa9843d82018-10-24 10:44:20 +020055
tierno59d22d22018-09-25 18:10:19 +020056 def __init__(self, config_file, loop=None):
tiernoc0e42e22018-05-11 11:36:10 +020057 """
58 Init, Connect to database, filesystem storage, and messaging
59 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
60 :return: None
61 """
62
63 self.db = None
64 self.msg = None
65 self.fs = None
66 self.pings_not_received = 1
67
68 # contains created tasks/futures to be able to cancel
tiernoca2e16a2018-06-29 15:25:24 +020069 self.lcm_tasks = TaskRegistry()
tiernoc0e42e22018-05-11 11:36:10 +020070 # logging
71 self.logger = logging.getLogger('lcm')
72 # load configuration
73 config = self.read_config_file(config_file)
74 self.config = config
tierno750b2452018-05-17 16:39:29 +020075 self.ro_config = {
tiernoc0e42e22018-05-11 11:36:10 +020076 "endpoint_url": "http://{}:{}/openmano".format(config["RO"]["host"], config["RO"]["port"]),
tierno750b2452018-05-17 16:39:29 +020077 "tenant": config.get("tenant", "osm"),
tiernoc0e42e22018-05-11 11:36:10 +020078 "logger_name": "lcm.ROclient",
79 "loglevel": "ERROR",
80 }
81
tierno59d22d22018-09-25 18:10:19 +020082 self.vca_config = config["VCA"]
83
84 self.loop = loop or asyncio.get_event_loop()
tiernoc0e42e22018-05-11 11:36:10 +020085
86 # logging
87 log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
88 log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
89 config["database"]["logger_name"] = "lcm.db"
90 config["storage"]["logger_name"] = "lcm.fs"
91 config["message"]["logger_name"] = "lcm.msg"
tierno86aa62f2018-08-20 11:57:04 +000092 if config["global"].get("logfile"):
tiernoc0e42e22018-05-11 11:36:10 +020093 file_handler = logging.handlers.RotatingFileHandler(config["global"]["logfile"],
94 maxBytes=100e6, backupCount=9, delay=0)
95 file_handler.setFormatter(log_formatter_simple)
96 self.logger.addHandler(file_handler)
tierno86aa62f2018-08-20 11:57:04 +000097 if not config["global"].get("nologging"):
tiernoc0e42e22018-05-11 11:36:10 +020098 str_handler = logging.StreamHandler()
99 str_handler.setFormatter(log_formatter_simple)
100 self.logger.addHandler(str_handler)
101
102 if config["global"].get("loglevel"):
103 self.logger.setLevel(config["global"]["loglevel"])
104
105 # logging other modules
106 for k1, logname in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
107 config[k1]["logger_name"] = logname
108 logger_module = logging.getLogger(logname)
tierno86aa62f2018-08-20 11:57:04 +0000109 if config[k1].get("logfile"):
tiernoc0e42e22018-05-11 11:36:10 +0200110 file_handler = logging.handlers.RotatingFileHandler(config[k1]["logfile"],
111 maxBytes=100e6, backupCount=9, delay=0)
112 file_handler.setFormatter(log_formatter_simple)
113 logger_module.addHandler(file_handler)
tierno86aa62f2018-08-20 11:57:04 +0000114 if config[k1].get("loglevel"):
tiernoc0e42e22018-05-11 11:36:10 +0200115 logger_module.setLevel(config[k1]["loglevel"])
tierno86aa62f2018-08-20 11:57:04 +0000116 self.logger.critical("starting osm/lcm version {} {}".format(lcm_version, lcm_version_date))
tierno59d22d22018-09-25 18:10:19 +0200117
tiernoc0e42e22018-05-11 11:36:10 +0200118 # check version of N2VC
119 # TODO enhance with int conversion or from distutils.version import LooseVersion
120 # or with list(map(int, version.split(".")))
tierno59d22d22018-09-25 18:10:19 +0200121 if versiontuple(n2vc_version) < versiontuple(min_n2vc_version):
tierno6e9d2eb2018-09-12 17:47:18 +0200122 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
tierno59d22d22018-09-25 18:10:19 +0200123 n2vc_version, min_n2vc_version))
124 # check version of common
tierno27246d82018-09-27 15:59:09 +0200125 if versiontuple(common_version) < versiontuple(min_common_version):
tierno6e9d2eb2018-09-12 17:47:18 +0200126 raise LcmException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
127 common_version, min_common_version))
tierno22f4f9c2018-06-11 18:53:39 +0200128
tiernoc0e42e22018-05-11 11:36:10 +0200129 try:
tierno22f4f9c2018-06-11 18:53:39 +0200130 # TODO check database version
tiernoc0e42e22018-05-11 11:36:10 +0200131 if config["database"]["driver"] == "mongo":
132 self.db = dbmongo.DbMongo()
133 self.db.db_connect(config["database"])
134 elif config["database"]["driver"] == "memory":
135 self.db = dbmemory.DbMemory()
136 self.db.db_connect(config["database"])
137 else:
138 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
139 config["database"]["driver"]))
140
141 if config["storage"]["driver"] == "local":
142 self.fs = fslocal.FsLocal()
143 self.fs.fs_connect(config["storage"])
144 else:
145 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
146 config["storage"]["driver"]))
147
148 if config["message"]["driver"] == "local":
149 self.msg = msglocal.MsgLocal()
150 self.msg.connect(config["message"])
151 elif config["message"]["driver"] == "kafka":
152 self.msg = msgkafka.MsgKafka()
153 self.msg.connect(config["message"])
154 else:
155 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
156 config["storage"]["driver"]))
157 except (DbException, FsException, MsgException) as e:
158 self.logger.critical(str(e), exc_info=True)
159 raise LcmException(str(e))
160
tierno59d22d22018-09-25 18:10:19 +0200161 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 +0100162 self.netslice = netslice.NetsliceLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config,
163 self.vca_config, self.loop)
tierno59d22d22018-09-25 18:10:19 +0200164 self.vim = vim_sdn.VimLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config, self.loop)
tiernoe37b57d2018-12-11 17:22:51 +0000165 self.wim = vim_sdn.WimLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config, self.loop)
tierno59d22d22018-09-25 18:10:19 +0200166 self.sdn = vim_sdn.SdnLcm(self.db, self.msg, self.fs, self.lcm_tasks, self.ro_config, self.loop)
167
tierno22f4f9c2018-06-11 18:53:39 +0200168 async def check_RO_version(self):
169 try:
170 RO = ROclient.ROClient(self.loop, **self.ro_config)
171 RO_version = await RO.get_version()
172 if RO_version < min_RO_version:
173 raise LcmException("Not compatible osm/RO version '{}.{}.{}'. Needed '{}.{}.{}' or higher".format(
174 *RO_version, *min_RO_version
175 ))
176 except ROclient.ROClientException as e:
tierno59d22d22018-09-25 18:10:19 +0200177 error_text = "Error while conneting to osm/RO " + str(e)
178 self.logger.critical(error_text, exc_info=True)
179 raise LcmException(error_text)
tierno22f4f9c2018-06-11 18:53:39 +0200180
tiernoc0e42e22018-05-11 11:36:10 +0200181 async def test(self, param=None):
182 self.logger.debug("Starting/Ending test task: {}".format(param))
183
tiernoc0e42e22018-05-11 11:36:10 +0200184 async def kafka_ping(self):
185 self.logger.debug("Task kafka_ping Enter")
186 consecutive_errors = 0
187 first_start = True
188 kafka_has_received = False
189 self.pings_not_received = 1
190 while True:
191 try:
tierno750b2452018-05-17 16:39:29 +0200192 await self.msg.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self.loop)
tiernoc0e42e22018-05-11 11:36:10 +0200193 # time between pings are low when it is not received and at starting
tiernoa9843d82018-10-24 10:44:20 +0200194 wait_time = self.ping_interval_boot if not kafka_has_received else self.ping_interval_pace
tiernoc0e42e22018-05-11 11:36:10 +0200195 if not self.pings_not_received:
196 kafka_has_received = True
197 self.pings_not_received += 1
198 await asyncio.sleep(wait_time, loop=self.loop)
199 if self.pings_not_received > 10:
200 raise LcmException("It is not receiving pings from Kafka bus")
201 consecutive_errors = 0
202 first_start = False
203 except LcmException:
204 raise
205 except Exception as e:
206 # if not first_start is the first time after starting. So leave more time and wait
207 # to allow kafka starts
208 if consecutive_errors == 8 if not first_start else 30:
209 self.logger.error("Task kafka_read task exit error too many errors. Exception: {}".format(e))
210 raise
211 consecutive_errors += 1
212 self.logger.error("Task kafka_read retrying after Exception {}".format(e))
213 wait_time = 1 if not first_start else 5
214 await asyncio.sleep(wait_time, loop=self.loop)
215
216 async def kafka_read(self):
217 self.logger.debug("Task kafka_read Enter")
218 order_id = 1
219 # future = asyncio.Future()
220 consecutive_errors = 0
221 first_start = True
222 while consecutive_errors < 10:
223 try:
tiernoe37b57d2018-12-11 17:22:51 +0000224 topics = ("admin", "ns", "vim_account", "wim_account", "sdn", "nsi")
tiernoc0e42e22018-05-11 11:36:10 +0200225 topic, command, params = await self.msg.aioread(topics, self.loop)
tierno35b0be72018-05-21 15:13:44 +0200226 if topic != "admin" and command != "ping":
227 self.logger.debug("Task kafka_read receives {} {}: {}".format(topic, command, params))
tiernoc0e42e22018-05-11 11:36:10 +0200228 consecutive_errors = 0
229 first_start = False
230 order_id += 1
231 if command == "exit":
232 print("Bye!")
233 break
234 elif command.startswith("#"):
235 continue
236 elif command == "echo":
237 # just for test
238 print(params)
239 sys.stdout.flush()
240 continue
241 elif command == "test":
242 asyncio.Task(self.test(params), loop=self.loop)
243 continue
244
245 if topic == "admin":
246 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
247 self.pings_not_received = 0
248 continue
249 elif topic == "ns":
250 if command == "instantiate":
251 # self.logger.debug("Deploying 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.instantiate(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +0200256 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
tiernoc0e42e22018-05-11 11:36:10 +0200257 continue
258 elif command == "terminate":
259 # self.logger.debug("Deleting NS {}".format(nsr_id))
260 nslcmop = params
261 nslcmop_id = nslcmop["_id"]
262 nsr_id = nslcmop["nsInstanceId"]
tiernoca2e16a2018-06-29 15:25:24 +0200263 self.lcm_tasks.cancel(topic, nsr_id)
tierno59d22d22018-09-25 18:10:19 +0200264 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +0200265 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
tiernoc0e42e22018-05-11 11:36:10 +0200266 continue
267 elif command == "action":
268 # self.logger.debug("Update NS {}".format(nsr_id))
269 nslcmop = params
270 nslcmop_id = nslcmop["_id"]
271 nsr_id = nslcmop["nsInstanceId"]
tierno59d22d22018-09-25 18:10:19 +0200272 task = asyncio.ensure_future(self.ns.action(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +0200273 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
tiernoc0e42e22018-05-11 11:36:10 +0200274 continue
tierno22f4f9c2018-06-11 18:53:39 +0200275 elif command == "scale":
276 # self.logger.debug("Update NS {}".format(nsr_id))
277 nslcmop = params
278 nslcmop_id = nslcmop["_id"]
279 nsr_id = nslcmop["nsInstanceId"]
tierno59d22d22018-09-25 18:10:19 +0200280 task = asyncio.ensure_future(self.ns.scale(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +0200281 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
tierno22f4f9c2018-06-11 18:53:39 +0200282 continue
tiernoc0e42e22018-05-11 11:36:10 +0200283 elif command == "show":
284 try:
285 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tierno750b2452018-05-17 16:39:29 +0200286 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
287 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
288 "".format(nsr_id, db_nsr["operational-status"], db_nsr["config-status"],
289 db_nsr["detailed-status"],
290 db_nsr["_admin"]["deployed"], self.lcm_ns_tasks.get(nsr_id)))
tiernoc0e42e22018-05-11 11:36:10 +0200291 except Exception as e:
292 print("nsr {} not found: {}".format(nsr_id, e))
293 sys.stdout.flush()
294 continue
295 elif command == "deleted":
296 continue # TODO cleaning of task just in case should be done
tiernoca2e16a2018-06-29 15:25:24 +0200297 elif command in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
298 continue
Felipe Vicensc2033f22018-11-15 15:09:58 +0100299 elif topic == "nsi": # netslice LCM processes (instantiate, terminate, etc)
300 if command == "instantiate":
301 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
302 nsilcmop = params
303 nsilcmop_id = nsilcmop["_id"] # slice operation id
304 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
305 task = asyncio.ensure_future(self.netslice.instantiate(nsir_id, nsilcmop_id))
306 self.lcm_tasks.register("nsi", nsir_id, nsilcmop_id, "nsi_instantiate", task)
307 continue
308 elif command == "terminate":
309 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
310 nsilcmop = params
311 nsilcmop_id = nsilcmop["_id"] # slice operation id
312 nsir_id = nsilcmop["netsliceInstanceId"] # slice record id
313 self.lcm_tasks.cancel(topic, nsir_id)
314 task = asyncio.ensure_future(self.netslice.terminate(nsir_id, nsilcmop_id))
315 self.lcm_tasks.register("nsi", nsir_id, nsilcmop_id, "nsi_terminate", task)
316 continue
317 elif command == "show":
318 try:
319 db_nsir = self.db.get_one("nsirs", {"_id": nsir_id})
320 print("nsir:\n _id={}\n operational-status: {}\n config-status: {}"
321 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
322 "".format(nsir_id, db_nsir["operational-status"], db_nsir["config-status"],
323 db_nsir["detailed-status"],
324 db_nsir["_admin"]["deployed"], self.lcm_netslice_tasks.get(nsir_id)))
325 except Exception as e:
326 print("nsir {} not found: {}".format(nsir_id, e))
327 sys.stdout.flush()
328 continue
329 elif command == "deleted":
330 continue # TODO cleaning of task just in case should be done
331 elif command in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
332 continue
tiernoc0e42e22018-05-11 11:36:10 +0200333 elif topic == "vim_account":
334 vim_id = params["_id"]
335 if command == "create":
tierno59d22d22018-09-25 18:10:19 +0200336 task = asyncio.ensure_future(self.vim.create(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200337 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_create", task)
tiernoc0e42e22018-05-11 11:36:10 +0200338 continue
339 elif command == "delete":
tiernoca2e16a2018-06-29 15:25:24 +0200340 self.lcm_tasks.cancel(topic, vim_id)
tierno59d22d22018-09-25 18:10:19 +0200341 task = asyncio.ensure_future(self.vim.delete(vim_id, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200342 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_delete", task)
tiernoc0e42e22018-05-11 11:36:10 +0200343 continue
344 elif command == "show":
345 print("not implemented show with vim_account")
346 sys.stdout.flush()
347 continue
348 elif command == "edit":
tierno59d22d22018-09-25 18:10:19 +0200349 task = asyncio.ensure_future(self.vim.edit(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200350 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_edit", task)
tiernoc0e42e22018-05-11 11:36:10 +0200351 continue
tiernoe37b57d2018-12-11 17:22:51 +0000352 elif topic == "wim_account":
353 wim_id = params["_id"]
354 if command == "create":
355 task = asyncio.ensure_future(self.wim.create(params, order_id))
356 self.lcm_tasks.register("wim_account", wim_id, order_id, "wim_create", task)
357 continue
358 elif command == "delete":
359 self.lcm_tasks.cancel(topic, wim_id)
360 task = asyncio.ensure_future(self.wim.delete(wim_id, order_id))
361 self.lcm_tasks.register("wim_account", wim_id, order_id, "wim_delete", task)
362 continue
363 elif command == "show":
364 print("not implemented show with wim_account")
365 sys.stdout.flush()
366 continue
367 elif command == "edit":
368 task = asyncio.ensure_future(self.wim.edit(params, order_id))
369 self.lcm_tasks.register("wim_account", wim_id, order_id, "wim_edit", task)
370 continue
tiernoc0e42e22018-05-11 11:36:10 +0200371 elif topic == "sdn":
372 _sdn_id = params["_id"]
373 if command == "create":
tierno59d22d22018-09-25 18:10:19 +0200374 task = asyncio.ensure_future(self.sdn.create(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200375 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_create", task)
tiernoc0e42e22018-05-11 11:36:10 +0200376 continue
377 elif command == "delete":
tiernoca2e16a2018-06-29 15:25:24 +0200378 self.lcm_tasks.cancel(topic, _sdn_id)
tierno59d22d22018-09-25 18:10:19 +0200379 task = asyncio.ensure_future(self.sdn.delete(_sdn_id, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200380 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
tiernoc0e42e22018-05-11 11:36:10 +0200381 continue
382 elif command == "edit":
tierno59d22d22018-09-25 18:10:19 +0200383 task = asyncio.ensure_future(self.sdn.edit(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +0200384 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
tiernoc0e42e22018-05-11 11:36:10 +0200385 continue
386 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
387 except Exception as e:
388 # if not first_start is the first time after starting. So leave more time and wait
389 # to allow kafka starts
390 if consecutive_errors == 8 if not first_start else 30:
391 self.logger.error("Task kafka_read task exit error too many errors. Exception: {}".format(e))
392 raise
393 consecutive_errors += 1
394 self.logger.error("Task kafka_read retrying after Exception {}".format(e))
395 wait_time = 2 if not first_start else 5
396 await asyncio.sleep(wait_time, loop=self.loop)
397
398 # self.logger.debug("Task kafka_read terminating")
399 self.logger.debug("Task kafka_read exit")
400
tiernoa9843d82018-10-24 10:44:20 +0200401 def health_check(self):
402
403 global exit_code
404 task = None
405 exit_code = 1
406
407 def health_check_callback(topic, command, params):
408 global exit_code
409 print("receiving callback {} {} {}".format(topic, command, params))
410 if topic == "admin" and command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
411 # print("received LCM ping")
412 exit_code = 0
413 task.cancel()
414
415 try:
416 task = asyncio.ensure_future(self.msg.aioread(("admin",), self.loop, health_check_callback))
417 self.loop.run_until_complete(task)
418 except Exception:
419 pass
420 exit(exit_code)
421
tiernoc0e42e22018-05-11 11:36:10 +0200422 def start(self):
tierno22f4f9c2018-06-11 18:53:39 +0200423
424 # check RO version
425 self.loop.run_until_complete(self.check_RO_version())
426
tiernoc0e42e22018-05-11 11:36:10 +0200427 self.loop.run_until_complete(asyncio.gather(
428 self.kafka_read(),
429 self.kafka_ping()
430 ))
431 # TODO
432 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +0200433 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +0200434 # timeout = 200
435 # while self.is_pending_tasks():
436 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
437 # await asyncio.sleep(2, loop=self.loop)
438 # timeout -= 2
439 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +0200440 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +0200441 self.loop.close()
442 self.loop = None
443 if self.db:
444 self.db.db_disconnect()
445 if self.msg:
446 self.msg.disconnect()
447 if self.fs:
448 self.fs.fs_disconnect()
449
tiernoc0e42e22018-05-11 11:36:10 +0200450 def read_config_file(self, config_file):
451 # TODO make a [ini] + yaml inside parser
452 # the configparser library is not suitable, because it does not admit comments at the end of line,
453 # and not parse integer or boolean
454 try:
455 with open(config_file) as f:
456 conf = yaml.load(f)
457 for k, v in environ.items():
458 if not k.startswith("OSMLCM_"):
459 continue
460 k_items = k.lower().split("_")
tierno17a612f2018-10-23 11:30:42 +0200461 if len(k_items) < 3:
462 continue
463 if k_items[1] in ("ro", "vca"):
464 # put in capital letter
465 k_items[1] = k_items[1].upper()
tiernoc0e42e22018-05-11 11:36:10 +0200466 c = conf
467 try:
468 for k_item in k_items[1:-1]:
tiernoc0e42e22018-05-11 11:36:10 +0200469 c = c[k_item]
470 if k_items[-1] == "port":
471 c[k_items[-1]] = int(v)
472 else:
473 c[k_items[-1]] = v
474 except Exception as e:
475 self.logger.warn("skipping environ '{}' on exception '{}'".format(k, e))
476
477 return conf
478 except Exception as e:
479 self.logger.critical("At config file '{}': {}".format(config_file, e))
480 exit(1)
481
482
tierno275411e2018-05-16 14:33:32 +0200483def usage():
484 print("""Usage: {} [options]
485 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
tiernoa9843d82018-10-24 10:44:20 +0200486 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
tierno275411e2018-05-16 14:33:32 +0200487 -h|--help: shows this help
488 """.format(sys.argv[0]))
tierno750b2452018-05-17 16:39:29 +0200489 # --log-socket-host HOST: send logs to this host")
490 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +0200491
492
tiernoc0e42e22018-05-11 11:36:10 +0200493if __name__ == '__main__':
tierno275411e2018-05-16 14:33:32 +0200494 try:
495 # load parameters and configuration
tiernoa9843d82018-10-24 10:44:20 +0200496 opts, args = getopt.getopt(sys.argv[1:], "hc:", ["config=", "help", "health-check"])
tierno275411e2018-05-16 14:33:32 +0200497 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
498 config_file = None
tiernoa9843d82018-10-24 10:44:20 +0200499 health_check = None
tierno275411e2018-05-16 14:33:32 +0200500 for o, a in opts:
501 if o in ("-h", "--help"):
502 usage()
503 sys.exit()
504 elif o in ("-c", "--config"):
505 config_file = a
tiernoa9843d82018-10-24 10:44:20 +0200506 elif o == "--health-check":
507 health_check = True
tierno275411e2018-05-16 14:33:32 +0200508 # elif o == "--log-socket-port":
509 # log_socket_port = a
510 # elif o == "--log-socket-host":
511 # log_socket_host = a
512 # elif o == "--log-file":
513 # log_file = a
514 else:
515 assert False, "Unhandled option"
516 if config_file:
517 if not path.isfile(config_file):
tierno17a612f2018-10-23 11:30:42 +0200518 print("configuration file '{}' not exist".format(config_file), file=sys.stderr)
tierno275411e2018-05-16 14:33:32 +0200519 exit(1)
520 else:
521 for config_file in (__file__[:__file__.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
522 if path.isfile(config_file):
523 break
524 else:
tierno17a612f2018-10-23 11:30:42 +0200525 print("No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/", file=sys.stderr)
tierno275411e2018-05-16 14:33:32 +0200526 exit(1)
527 lcm = Lcm(config_file)
tiernoa9843d82018-10-24 10:44:20 +0200528 if health_check:
529 lcm.health_check()
530 else:
531 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +0200532 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +0200533 print(str(e), file=sys.stderr)
534 # usage()
535 exit(1)