2 # -*- coding: utf-8 -*-
7 import logging
.handlers
13 from lcm_utils
import versiontuple
, LcmException
, TaskRegistry
15 # from osm_lcm import version as lcm_version, version_date as lcm_version_date, ROclient
16 from osm_common
import dbmemory
, dbmongo
, fslocal
, msglocal
, msgkafka
17 from osm_common
import version
as common_version
18 from osm_common
.dbbase
import DbException
19 from osm_common
.fsbase
import FsException
20 from osm_common
.msgbase
import MsgException
21 from os
import environ
, path
22 from n2vc
import version
as n2vc_version
25 __author__
= "Alfonso Tierno"
26 min_RO_version
= [0, 5, 72]
27 min_n2vc_version
= "0.0.2"
28 min_common_version
= "0.1.11"
29 # uncomment if LCM is installed as library and installed, and get them from __init__.py
30 lcm_version
= '0.1.22'
31 lcm_version_date
= '2018-10-31'
36 ping_interval_pace
= 120 # how many time ping is send once is confirmed all is running
37 ping_interval_boot
= 5 # how mnay time ping is sent when booting
39 def __init__(self
, config_file
, loop
=None):
41 Init, Connect to database, filesystem storage, and messaging
42 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
49 self
.pings_not_received
= 1
51 # contains created tasks/futures to be able to cancel
52 self
.lcm_tasks
= TaskRegistry()
54 self
.logger
= logging
.getLogger('lcm')
56 config
= self
.read_config_file(config_file
)
59 "endpoint_url": "http://{}:{}/openmano".format(config
["RO"]["host"], config
["RO"]["port"]),
60 "tenant": config
.get("tenant", "osm"),
61 "logger_name": "lcm.ROclient",
65 self
.vca_config
= config
["VCA"]
67 self
.loop
= loop
or asyncio
.get_event_loop()
70 log_format_simple
= "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
71 log_formatter_simple
= logging
.Formatter(log_format_simple
, datefmt
='%Y-%m-%dT%H:%M:%S')
72 config
["database"]["logger_name"] = "lcm.db"
73 config
["storage"]["logger_name"] = "lcm.fs"
74 config
["message"]["logger_name"] = "lcm.msg"
75 if config
["global"].get("logfile"):
76 file_handler
= logging
.handlers
.RotatingFileHandler(config
["global"]["logfile"],
77 maxBytes
=100e6
, backupCount
=9, delay
=0)
78 file_handler
.setFormatter(log_formatter_simple
)
79 self
.logger
.addHandler(file_handler
)
80 if not config
["global"].get("nologging"):
81 str_handler
= logging
.StreamHandler()
82 str_handler
.setFormatter(log_formatter_simple
)
83 self
.logger
.addHandler(str_handler
)
85 if config
["global"].get("loglevel"):
86 self
.logger
.setLevel(config
["global"]["loglevel"])
88 # logging other modules
89 for k1
, logname
in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
90 config
[k1
]["logger_name"] = logname
91 logger_module
= logging
.getLogger(logname
)
92 if config
[k1
].get("logfile"):
93 file_handler
= logging
.handlers
.RotatingFileHandler(config
[k1
]["logfile"],
94 maxBytes
=100e6
, backupCount
=9, delay
=0)
95 file_handler
.setFormatter(log_formatter_simple
)
96 logger_module
.addHandler(file_handler
)
97 if config
[k1
].get("loglevel"):
98 logger_module
.setLevel(config
[k1
]["loglevel"])
99 self
.logger
.critical("starting osm/lcm version {} {}".format(lcm_version
, lcm_version_date
))
101 # check version of N2VC
102 # TODO enhance with int conversion or from distutils.version import LooseVersion
103 # or with list(map(int, version.split(".")))
104 if versiontuple(n2vc_version
) < versiontuple(min_n2vc_version
):
105 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
106 n2vc_version
, min_n2vc_version
))
107 # check version of common
108 if versiontuple(common_version
) < versiontuple(min_common_version
):
109 raise LcmException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
110 common_version
, min_common_version
))
113 # TODO check database version
114 if config
["database"]["driver"] == "mongo":
115 self
.db
= dbmongo
.DbMongo()
116 self
.db
.db_connect(config
["database"])
117 elif config
["database"]["driver"] == "memory":
118 self
.db
= dbmemory
.DbMemory()
119 self
.db
.db_connect(config
["database"])
121 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
122 config
["database"]["driver"]))
124 if config
["storage"]["driver"] == "local":
125 self
.fs
= fslocal
.FsLocal()
126 self
.fs
.fs_connect(config
["storage"])
128 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
129 config
["storage"]["driver"]))
131 if config
["message"]["driver"] == "local":
132 self
.msg
= msglocal
.MsgLocal()
133 self
.msg
.connect(config
["message"])
134 elif config
["message"]["driver"] == "kafka":
135 self
.msg
= msgkafka
.MsgKafka()
136 self
.msg
.connect(config
["message"])
138 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
139 config
["storage"]["driver"]))
140 except (DbException
, FsException
, MsgException
) as e
:
141 self
.logger
.critical(str(e
), exc_info
=True)
142 raise LcmException(str(e
))
144 self
.ns
= ns
.NsLcm(self
.db
, self
.msg
, self
.fs
, self
.lcm_tasks
, self
.ro_config
, self
.vca_config
, self
.loop
)
145 self
.vim
= vim_sdn
.VimLcm(self
.db
, self
.msg
, self
.fs
, self
.lcm_tasks
, self
.ro_config
, self
.loop
)
146 self
.sdn
= vim_sdn
.SdnLcm(self
.db
, self
.msg
, self
.fs
, self
.lcm_tasks
, self
.ro_config
, self
.loop
)
148 async def check_RO_version(self
):
150 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
151 RO_version
= await RO
.get_version()
152 if RO_version
< min_RO_version
:
153 raise LcmException("Not compatible osm/RO version '{}.{}.{}'. Needed '{}.{}.{}' or higher".format(
154 *RO_version
, *min_RO_version
156 except ROclient
.ROClientException
as e
:
157 error_text
= "Error while conneting to osm/RO " + str(e
)
158 self
.logger
.critical(error_text
, exc_info
=True)
159 raise LcmException(error_text
)
161 async def test(self
, param
=None):
162 self
.logger
.debug("Starting/Ending test task: {}".format(param
))
164 async def kafka_ping(self
):
165 self
.logger
.debug("Task kafka_ping Enter")
166 consecutive_errors
= 0
168 kafka_has_received
= False
169 self
.pings_not_received
= 1
172 await self
.msg
.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self
.loop
)
173 # time between pings are low when it is not received and at starting
174 wait_time
= self
.ping_interval_boot
if not kafka_has_received
else self
.ping_interval_pace
175 if not self
.pings_not_received
:
176 kafka_has_received
= True
177 self
.pings_not_received
+= 1
178 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
179 if self
.pings_not_received
> 10:
180 raise LcmException("It is not receiving pings from Kafka bus")
181 consecutive_errors
= 0
185 except Exception as e
:
186 # if not first_start is the first time after starting. So leave more time and wait
187 # to allow kafka starts
188 if consecutive_errors
== 8 if not first_start
else 30:
189 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
191 consecutive_errors
+= 1
192 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
193 wait_time
= 1 if not first_start
else 5
194 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
196 async def kafka_read(self
):
197 self
.logger
.debug("Task kafka_read Enter")
199 # future = asyncio.Future()
200 consecutive_errors
= 0
202 while consecutive_errors
< 10:
204 topics
= ("admin", "ns", "vim_account", "sdn")
205 topic
, command
, params
= await self
.msg
.aioread(topics
, self
.loop
)
206 if topic
!= "admin" and command
!= "ping":
207 self
.logger
.debug("Task kafka_read receives {} {}: {}".format(topic
, command
, params
))
208 consecutive_errors
= 0
211 if command
== "exit":
214 elif command
.startswith("#"):
216 elif command
== "echo":
221 elif command
== "test":
222 asyncio
.Task(self
.test(params
), loop
=self
.loop
)
226 if command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
227 self
.pings_not_received
= 0
230 if command
== "instantiate":
231 # self.logger.debug("Deploying NS {}".format(nsr_id))
233 nslcmop_id
= nslcmop
["_id"]
234 nsr_id
= nslcmop
["nsInstanceId"]
235 task
= asyncio
.ensure_future(self
.ns
.instantiate(nsr_id
, nslcmop_id
))
236 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_instantiate", task
)
238 elif command
== "terminate":
239 # self.logger.debug("Deleting NS {}".format(nsr_id))
241 nslcmop_id
= nslcmop
["_id"]
242 nsr_id
= nslcmop
["nsInstanceId"]
243 self
.lcm_tasks
.cancel(topic
, nsr_id
)
244 task
= asyncio
.ensure_future(self
.ns
.terminate(nsr_id
, nslcmop_id
))
245 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_terminate", task
)
247 elif command
== "action":
248 # self.logger.debug("Update NS {}".format(nsr_id))
250 nslcmop_id
= nslcmop
["_id"]
251 nsr_id
= nslcmop
["nsInstanceId"]
252 task
= asyncio
.ensure_future(self
.ns
.action(nsr_id
, nslcmop_id
))
253 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_action", task
)
255 elif command
== "scale":
256 # self.logger.debug("Update NS {}".format(nsr_id))
258 nslcmop_id
= nslcmop
["_id"]
259 nsr_id
= nslcmop
["nsInstanceId"]
260 task
= asyncio
.ensure_future(self
.ns
.scale(nsr_id
, nslcmop_id
))
261 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_scale", task
)
263 elif command
== "show":
265 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
266 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
267 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
268 "".format(nsr_id
, db_nsr
["operational-status"], db_nsr
["config-status"],
269 db_nsr
["detailed-status"],
270 db_nsr
["_admin"]["deployed"], self
.lcm_ns_tasks
.get(nsr_id
)))
271 except Exception as e
:
272 print("nsr {} not found: {}".format(nsr_id
, e
))
275 elif command
== "deleted":
276 continue # TODO cleaning of task just in case should be done
277 elif command
in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
279 elif topic
== "vim_account":
280 vim_id
= params
["_id"]
281 if command
== "create":
282 task
= asyncio
.ensure_future(self
.vim
.create(params
, order_id
))
283 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_create", task
)
285 elif command
== "delete":
286 self
.lcm_tasks
.cancel(topic
, vim_id
)
287 task
= asyncio
.ensure_future(self
.vim
.delete(vim_id
, order_id
))
288 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_delete", task
)
290 elif command
== "show":
291 print("not implemented show with vim_account")
294 elif command
== "edit":
295 task
= asyncio
.ensure_future(self
.vim
.edit(params
, order_id
))
296 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_edit", task
)
299 _sdn_id
= params
["_id"]
300 if command
== "create":
301 task
= asyncio
.ensure_future(self
.sdn
.create(params
, order_id
))
302 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_create", task
)
304 elif command
== "delete":
305 self
.lcm_tasks
.cancel(topic
, _sdn_id
)
306 task
= asyncio
.ensure_future(self
.sdn
.delete(_sdn_id
, order_id
))
307 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_delete", task
)
309 elif command
== "edit":
310 task
= asyncio
.ensure_future(self
.sdn
.edit(params
, order_id
))
311 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_edit", task
)
313 self
.logger
.critical("unknown topic {} and command '{}'".format(topic
, command
))
314 except Exception as e
:
315 # if not first_start is the first time after starting. So leave more time and wait
316 # to allow kafka starts
317 if consecutive_errors
== 8 if not first_start
else 30:
318 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
320 consecutive_errors
+= 1
321 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
322 wait_time
= 2 if not first_start
else 5
323 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
325 # self.logger.debug("Task kafka_read terminating")
326 self
.logger
.debug("Task kafka_read exit")
328 def health_check(self
):
334 def health_check_callback(topic
, command
, params
):
336 print("receiving callback {} {} {}".format(topic
, command
, params
))
337 if topic
== "admin" and command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
338 # print("received LCM ping")
343 task
= asyncio
.ensure_future(self
.msg
.aioread(("admin",), self
.loop
, health_check_callback
))
344 self
.loop
.run_until_complete(task
)
352 self
.loop
.run_until_complete(self
.check_RO_version())
354 self
.loop
.run_until_complete(asyncio
.gather(
359 # self.logger.debug("Terminating cancelling creation tasks")
360 # self.lcm_tasks.cancel("ALL", "create")
362 # while self.is_pending_tasks():
363 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
364 # await asyncio.sleep(2, loop=self.loop)
367 # self.lcm_tasks.cancel("ALL", "ALL")
371 self
.db
.db_disconnect()
373 self
.msg
.disconnect()
375 self
.fs
.fs_disconnect()
377 def read_config_file(self
, config_file
):
378 # TODO make a [ini] + yaml inside parser
379 # the configparser library is not suitable, because it does not admit comments at the end of line,
380 # and not parse integer or boolean
382 with
open(config_file
) as f
:
384 for k
, v
in environ
.items():
385 if not k
.startswith("OSMLCM_"):
387 k_items
= k
.lower().split("_")
390 if k_items
[1] in ("ro", "vca"):
391 # put in capital letter
392 k_items
[1] = k_items
[1].upper()
395 for k_item
in k_items
[1:-1]:
397 if k_items
[-1] == "port":
398 c
[k_items
[-1]] = int(v
)
401 except Exception as e
:
402 self
.logger
.warn("skipping environ '{}' on exception '{}'".format(k
, e
))
405 except Exception as e
:
406 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
411 print("""Usage: {} [options]
412 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
413 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
414 -h|--help: shows this help
415 """.format(sys
.argv
[0]))
416 # --log-socket-host HOST: send logs to this host")
417 # --log-socket-port PORT: send logs using this port (default: 9022)")
420 if __name__
== '__main__':
422 # load parameters and configuration
423 opts
, args
= getopt
.getopt(sys
.argv
[1:], "hc:", ["config=", "help", "health-check"])
424 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
428 if o
in ("-h", "--help"):
431 elif o
in ("-c", "--config"):
433 elif o
== "--health-check":
435 # elif o == "--log-socket-port":
436 # log_socket_port = a
437 # elif o == "--log-socket-host":
438 # log_socket_host = a
439 # elif o == "--log-file":
442 assert False, "Unhandled option"
444 if not path
.isfile(config_file
):
445 print("configuration file '{}' not exist".format(config_file
), file=sys
.stderr
)
448 for config_file
in (__file__
[:__file__
.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
449 if path
.isfile(config_file
):
452 print("No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/", file=sys
.stderr
)
454 lcm
= Lcm(config_file
)
459 except (LcmException
, getopt
.GetoptError
) as e
:
460 print(str(e
), file=sys
.stderr
)