44f2b2ed0c757553d47a8e21b043678ab7a6a0d1
2 # -*- coding: utf-8 -*-
5 # Copyright 2018 Telefonica S.A.
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
11 # http://www.apache.org/licenses/LICENSE-2.0
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
23 import logging
.handlers
30 from lcm_utils
import versiontuple
, LcmException
, TaskRegistry
, LcmExceptionExit
32 # from osm_lcm import version as lcm_version, version_date as lcm_version_date, ROclient
33 from osm_common
import dbmemory
, dbmongo
, fslocal
, msglocal
, msgkafka
34 from osm_common
import version
as common_version
35 from osm_common
.dbbase
import DbException
36 from osm_common
.fsbase
import FsException
37 from osm_common
.msgbase
import MsgException
38 from os
import environ
, path
39 from n2vc
import version
as n2vc_version
42 __author__
= "Alfonso Tierno"
43 min_RO_version
= [0, 6, 3]
44 min_n2vc_version
= "0.0.2"
45 min_common_version
= "0.1.11"
46 # uncomment if LCM is installed as library and installed, and get them from __init__.py
47 lcm_version
= '0.1.32'
48 lcm_version_date
= '2019-01-28'
53 ping_interval_pace
= 120 # how many time ping is send once is confirmed all is running
54 ping_interval_boot
= 5 # how many time ping is sent when booting
56 def __init__(self
, config_file
, loop
=None):
58 Init, Connect to database, filesystem storage, and messaging
59 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
66 self
.pings_not_received
= 1
67 self
.consecutive_errors
= 0
68 self
.first_start
= False
70 # contains created tasks/futures to be able to cancel
71 self
.lcm_tasks
= TaskRegistry()
73 self
.logger
= logging
.getLogger('lcm')
75 config
= self
.read_config_file(config_file
)
78 "endpoint_url": "http://{}:{}/openmano".format(config
["RO"]["host"], config
["RO"]["port"]),
79 "tenant": config
.get("tenant", "osm"),
80 "logger_name": "lcm.ROclient",
84 self
.vca_config
= config
["VCA"]
86 self
.loop
= loop
or asyncio
.get_event_loop()
89 log_format_simple
= "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
90 log_formatter_simple
= logging
.Formatter(log_format_simple
, datefmt
='%Y-%m-%dT%H:%M:%S')
91 config
["database"]["logger_name"] = "lcm.db"
92 config
["storage"]["logger_name"] = "lcm.fs"
93 config
["message"]["logger_name"] = "lcm.msg"
94 if config
["global"].get("logfile"):
95 file_handler
= logging
.handlers
.RotatingFileHandler(config
["global"]["logfile"],
96 maxBytes
=100e6
, backupCount
=9, delay
=0)
97 file_handler
.setFormatter(log_formatter_simple
)
98 self
.logger
.addHandler(file_handler
)
99 if not config
["global"].get("nologging"):
100 str_handler
= logging
.StreamHandler()
101 str_handler
.setFormatter(log_formatter_simple
)
102 self
.logger
.addHandler(str_handler
)
104 if config
["global"].get("loglevel"):
105 self
.logger
.setLevel(config
["global"]["loglevel"])
107 # logging other modules
108 for k1
, logname
in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
109 config
[k1
]["logger_name"] = logname
110 logger_module
= logging
.getLogger(logname
)
111 if config
[k1
].get("logfile"):
112 file_handler
= logging
.handlers
.RotatingFileHandler(config
[k1
]["logfile"],
113 maxBytes
=100e6
, backupCount
=9, delay
=0)
114 file_handler
.setFormatter(log_formatter_simple
)
115 logger_module
.addHandler(file_handler
)
116 if config
[k1
].get("loglevel"):
117 logger_module
.setLevel(config
[k1
]["loglevel"])
118 self
.logger
.critical("starting osm/lcm version {} {}".format(lcm_version
, lcm_version_date
))
120 # check version of N2VC
121 # TODO enhance with int conversion or from distutils.version import LooseVersion
122 # or with list(map(int, version.split(".")))
123 if versiontuple(n2vc_version
) < versiontuple(min_n2vc_version
):
124 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
125 n2vc_version
, min_n2vc_version
))
126 # check version of common
127 if versiontuple(common_version
) < versiontuple(min_common_version
):
128 raise LcmException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
129 common_version
, min_common_version
))
132 # TODO check database version
133 if config
["database"]["driver"] == "mongo":
134 self
.db
= dbmongo
.DbMongo()
135 self
.db
.db_connect(config
["database"])
136 elif config
["database"]["driver"] == "memory":
137 self
.db
= dbmemory
.DbMemory()
138 self
.db
.db_connect(config
["database"])
140 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
141 config
["database"]["driver"]))
143 if config
["storage"]["driver"] == "local":
144 self
.fs
= fslocal
.FsLocal()
145 self
.fs
.fs_connect(config
["storage"])
147 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
148 config
["storage"]["driver"]))
150 config_message
= config
["message"].copy()
151 config_message
["loop"] = self
.loop
152 if config_message
["driver"] == "local":
153 self
.msg
= msglocal
.MsgLocal()
154 self
.msg
.connect(config_message
)
155 elif config_message
["driver"] == "kafka":
156 self
.msg
= msgkafka
.MsgKafka()
157 self
.msg
.connect(config_message
)
159 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
160 config
["message"]["driver"]))
161 except (DbException
, FsException
, MsgException
) as e
:
162 self
.logger
.critical(str(e
), exc_info
=True)
163 raise LcmException(str(e
))
165 self
.ns
= ns
.NsLcm(self
.db
, self
.msg
, self
.fs
, self
.lcm_tasks
, self
.ro_config
, self
.vca_config
, self
.loop
)
166 self
.netslice
= netslice
.NetsliceLcm(self
.db
, self
.msg
, self
.fs
, self
.lcm_tasks
, self
.ro_config
,
167 self
.vca_config
, self
.loop
)
168 self
.vim
= vim_sdn
.VimLcm(self
.db
, self
.msg
, self
.fs
, self
.lcm_tasks
, self
.ro_config
, self
.loop
)
169 self
.wim
= vim_sdn
.WimLcm(self
.db
, self
.msg
, self
.fs
, self
.lcm_tasks
, self
.ro_config
, self
.loop
)
170 self
.sdn
= vim_sdn
.SdnLcm(self
.db
, self
.msg
, self
.fs
, self
.lcm_tasks
, self
.ro_config
, self
.loop
)
172 async def check_RO_version(self
):
174 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
175 RO_version
= await RO
.get_version()
176 if RO_version
< min_RO_version
:
177 raise LcmException("Not compatible osm/RO version '{}.{}.{}'. Needed '{}.{}.{}' or higher".format(
178 *RO_version
, *min_RO_version
180 except ROclient
.ROClientException
as e
:
181 error_text
= "Error while conneting to osm/RO " + str(e
)
182 self
.logger
.critical(error_text
, exc_info
=True)
183 raise LcmException(error_text
)
185 async def test(self
, param
=None):
186 self
.logger
.debug("Starting/Ending test task: {}".format(param
))
188 async def kafka_ping(self
):
189 self
.logger
.debug("Task kafka_ping Enter")
190 consecutive_errors
= 0
192 kafka_has_received
= False
193 self
.pings_not_received
= 1
196 await self
.msg
.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self
.loop
)
197 # time between pings are low when it is not received and at starting
198 wait_time
= self
.ping_interval_boot
if not kafka_has_received
else self
.ping_interval_pace
199 if not self
.pings_not_received
:
200 kafka_has_received
= True
201 self
.pings_not_received
+= 1
202 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
203 if self
.pings_not_received
> 10:
204 raise LcmException("It is not receiving pings from Kafka bus")
205 consecutive_errors
= 0
209 except Exception as e
:
210 # if not first_start is the first time after starting. So leave more time and wait
211 # to allow kafka starts
212 if consecutive_errors
== 8 if not first_start
else 30:
213 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
215 consecutive_errors
+= 1
216 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
217 wait_time
= 1 if not first_start
else 5
218 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
220 def kafka_read_callback(self
, topic
, command
, params
):
223 if topic
!= "admin" and command
!= "ping":
224 self
.logger
.debug("Task kafka_read receives {} {}: {}".format(topic
, command
, params
))
225 self
.consecutive_errors
= 0
226 self
.first_start
= False
228 if command
== "exit":
229 raise LcmExceptionExit
230 elif command
.startswith("#"):
232 elif command
== "echo":
237 elif command
== "test":
238 asyncio
.Task(self
.test(params
), loop
=self
.loop
)
242 if command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
243 self
.pings_not_received
= 0
246 if command
== "instantiate":
247 # self.logger.debug("Deploying NS {}".format(nsr_id))
249 nslcmop_id
= nslcmop
["_id"]
250 nsr_id
= nslcmop
["nsInstanceId"]
251 task
= asyncio
.ensure_future(self
.ns
.instantiate(nsr_id
, nslcmop_id
))
252 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_instantiate", task
)
254 elif command
== "terminate":
255 # self.logger.debug("Deleting NS {}".format(nsr_id))
257 nslcmop_id
= nslcmop
["_id"]
258 nsr_id
= nslcmop
["nsInstanceId"]
259 self
.lcm_tasks
.cancel(topic
, nsr_id
)
260 task
= asyncio
.ensure_future(self
.ns
.terminate(nsr_id
, nslcmop_id
))
261 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_terminate", task
)
263 elif command
== "action":
264 # self.logger.debug("Update NS {}".format(nsr_id))
266 nslcmop_id
= nslcmop
["_id"]
267 nsr_id
= nslcmop
["nsInstanceId"]
268 task
= asyncio
.ensure_future(self
.ns
.action(nsr_id
, nslcmop_id
))
269 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_action", task
)
271 elif command
== "scale":
272 # self.logger.debug("Update NS {}".format(nsr_id))
274 nslcmop_id
= nslcmop
["_id"]
275 nsr_id
= nslcmop
["nsInstanceId"]
276 task
= asyncio
.ensure_future(self
.ns
.scale(nsr_id
, nslcmop_id
))
277 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_scale", task
)
279 elif command
== "show":
282 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
283 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
284 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
285 "".format(nsr_id
, db_nsr
["operational-status"], db_nsr
["config-status"],
286 db_nsr
["detailed-status"],
287 db_nsr
["_admin"]["deployed"], self
.lcm_ns_tasks
.get(nsr_id
)))
288 except Exception as e
:
289 print("nsr {} not found: {}".format(nsr_id
, e
))
292 elif command
== "deleted":
293 return # TODO cleaning of task just in case should be done
294 elif command
in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
296 elif topic
== "nsi": # netslice LCM processes (instantiate, terminate, etc)
297 if command
== "instantiate":
298 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
300 nsilcmop_id
= nsilcmop
["_id"] # slice operation id
301 nsir_id
= nsilcmop
["netsliceInstanceId"] # slice record id
302 task
= asyncio
.ensure_future(self
.netslice
.instantiate(nsir_id
, nsilcmop_id
))
303 self
.lcm_tasks
.register("nsi", nsir_id
, nsilcmop_id
, "nsi_instantiate", task
)
305 elif command
== "terminate":
306 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
308 nsilcmop_id
= nsilcmop
["_id"] # slice operation id
309 nsir_id
= nsilcmop
["netsliceInstanceId"] # slice record id
310 self
.lcm_tasks
.cancel(topic
, nsir_id
)
311 task
= asyncio
.ensure_future(self
.netslice
.terminate(nsir_id
, nsilcmop_id
))
312 self
.lcm_tasks
.register("nsi", nsir_id
, nsilcmop_id
, "nsi_terminate", task
)
314 elif command
== "show":
317 db_nsir
= self
.db
.get_one("nsirs", {"_id": nsir_id
})
318 print("nsir:\n _id={}\n operational-status: {}\n config-status: {}"
319 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
320 "".format(nsir_id
, db_nsir
["operational-status"], db_nsir
["config-status"],
321 db_nsir
["detailed-status"],
322 db_nsir
["_admin"]["deployed"], self
.lcm_netslice_tasks
.get(nsir_id
)))
323 except Exception as e
:
324 print("nsir {} not found: {}".format(nsir_id
, e
))
327 elif command
== "deleted":
328 return # TODO cleaning of task just in case should be done
329 elif command
in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
331 elif topic
== "vim_account":
332 vim_id
= params
["_id"]
333 if command
== "create":
334 task
= asyncio
.ensure_future(self
.vim
.create(params
, order_id
))
335 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_create", task
)
337 elif command
== "delete":
338 self
.lcm_tasks
.cancel(topic
, vim_id
)
339 task
= asyncio
.ensure_future(self
.vim
.delete(vim_id
, order_id
))
340 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_delete", task
)
342 elif command
== "show":
343 print("not implemented show with vim_account")
346 elif command
== "edit":
347 task
= asyncio
.ensure_future(self
.vim
.edit(params
, order_id
))
348 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_edit", task
)
350 elif topic
== "wim_account":
351 wim_id
= params
["_id"]
352 if command
== "create":
353 task
= asyncio
.ensure_future(self
.wim
.create(params
, order_id
))
354 self
.lcm_tasks
.register("wim_account", wim_id
, order_id
, "wim_create", task
)
356 elif command
== "delete":
357 self
.lcm_tasks
.cancel(topic
, wim_id
)
358 task
= asyncio
.ensure_future(self
.wim
.delete(wim_id
, order_id
))
359 self
.lcm_tasks
.register("wim_account", wim_id
, order_id
, "wim_delete", task
)
361 elif command
== "show":
362 print("not implemented show with wim_account")
365 elif command
== "edit":
366 task
= asyncio
.ensure_future(self
.wim
.edit(params
, order_id
))
367 self
.lcm_tasks
.register("wim_account", wim_id
, order_id
, "wim_edit", task
)
370 _sdn_id
= params
["_id"]
371 if command
== "create":
372 task
= asyncio
.ensure_future(self
.sdn
.create(params
, order_id
))
373 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_create", task
)
375 elif command
== "delete":
376 self
.lcm_tasks
.cancel(topic
, _sdn_id
)
377 task
= asyncio
.ensure_future(self
.sdn
.delete(_sdn_id
, order_id
))
378 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_delete", task
)
380 elif command
== "edit":
381 task
= asyncio
.ensure_future(self
.sdn
.edit(params
, order_id
))
382 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_edit", task
)
384 self
.logger
.critical("unknown topic {} and command '{}'".format(topic
, command
))
386 async def kafka_read(self
):
387 self
.logger
.debug("Task kafka_read Enter")
388 # future = asyncio.Future()
389 self
.consecutive_errors
= 0
390 self
.first_start
= True
391 while self
.consecutive_errors
< 10:
393 topics
= ("admin", "ns", "vim_account", "wim_account", "sdn", "nsi")
394 await self
.msg
.aioread(topics
, self
.loop
, self
.kafka_read_callback
)
396 except LcmExceptionExit
:
397 self
.logger
.debug("Bye!")
399 except Exception as e
:
400 # if not first_start is the first time after starting. So leave more time and wait
401 # to allow kafka starts
402 if self
.consecutive_errors
== 8 if not self
.first_start
else 30:
403 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
405 self
.consecutive_errors
+= 1
406 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
407 wait_time
= 2 if not self
.first_start
else 5
408 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
410 # self.logger.debug("Task kafka_read terminating")
411 self
.logger
.debug("Task kafka_read exit")
413 def health_check(self
):
419 def health_check_callback(topic
, command
, params
):
421 print("receiving callback {} {} {}".format(topic
, command
, params
))
422 if topic
== "admin" and command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
423 # print("received LCM ping")
428 task
= asyncio
.ensure_future(self
.msg
.aioread(("admin",), self
.loop
, health_check_callback
))
429 self
.loop
.run_until_complete(task
)
437 self
.loop
.run_until_complete(self
.check_RO_version())
439 self
.loop
.run_until_complete(asyncio
.gather(
444 # self.logger.debug("Terminating cancelling creation tasks")
445 # self.lcm_tasks.cancel("ALL", "create")
447 # while self.is_pending_tasks():
448 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
449 # await asyncio.sleep(2, loop=self.loop)
452 # self.lcm_tasks.cancel("ALL", "ALL")
456 self
.db
.db_disconnect()
458 self
.msg
.disconnect()
460 self
.fs
.fs_disconnect()
462 def read_config_file(self
, config_file
):
463 # TODO make a [ini] + yaml inside parser
464 # the configparser library is not suitable, because it does not admit comments at the end of line,
465 # and not parse integer or boolean
467 with
open(config_file
) as f
:
469 for k
, v
in environ
.items():
470 if not k
.startswith("OSMLCM_"):
472 k_items
= k
.lower().split("_")
475 if k_items
[1] in ("ro", "vca"):
476 # put in capital letter
477 k_items
[1] = k_items
[1].upper()
480 for k_item
in k_items
[1:-1]:
482 if k_items
[-1] == "port":
483 c
[k_items
[-1]] = int(v
)
486 except Exception as e
:
487 self
.logger
.warn("skipping environ '{}' on exception '{}'".format(k
, e
))
490 except Exception as e
:
491 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
496 print("""Usage: {} [options]
497 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
498 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
499 -h|--help: shows this help
500 """.format(sys
.argv
[0]))
501 # --log-socket-host HOST: send logs to this host")
502 # --log-socket-port PORT: send logs using this port (default: 9022)")
505 if __name__
== '__main__':
507 # load parameters and configuration
508 opts
, args
= getopt
.getopt(sys
.argv
[1:], "hc:", ["config=", "help", "health-check"])
509 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
513 if o
in ("-h", "--help"):
516 elif o
in ("-c", "--config"):
518 elif o
== "--health-check":
520 # elif o == "--log-socket-port":
521 # log_socket_port = a
522 # elif o == "--log-socket-host":
523 # log_socket_host = a
524 # elif o == "--log-file":
527 assert False, "Unhandled option"
529 if not path
.isfile(config_file
):
530 print("configuration file '{}' not exist".format(config_file
), file=sys
.stderr
)
533 for config_file
in (__file__
[:__file__
.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
534 if path
.isfile(config_file
):
537 print("No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/", file=sys
.stderr
)
539 lcm
= Lcm(config_file
)
544 except (LcmException
, getopt
.GetoptError
) as e
:
545 print(str(e
), file=sys
.stderr
)