9f0e31061a7a36c1e91ceedeb2cd80c0a35cb0bb
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
28 import logging
.handlers
33 from osm_lcm
import ns
, vim_sdn
, netslice
34 from osm_lcm
.ng_ro
import NgRoException
, NgRoClient
35 from osm_lcm
.ROclient
import ROClient
, ROClientException
38 from osm_lcm
.lcm_utils
import versiontuple
, LcmException
, TaskRegistry
, LcmExceptionExit
39 from osm_lcm
import version
as lcm_version
, version_date
as lcm_version_date
41 from osm_common
import msglocal
, msgkafka
42 from osm_common
import version
as common_version
43 from osm_common
.dbbase
import DbException
44 from osm_common
.fsbase
import FsException
45 from osm_common
.msgbase
import MsgException
46 from osm_lcm
.data_utils
.database
.database
import Database
47 from osm_lcm
.data_utils
.filesystem
.filesystem
import Filesystem
48 from osm_lcm
.data_utils
.lcm_config
import LcmCfg
49 from osm_lcm
.lcm_hc
import get_health_check_file
51 from random
import choice
as random_choice
52 from n2vc
import version
as n2vc_version
55 if os
.getenv("OSMLCM_PDB_DEBUG", None) is not None:
59 __author__
= "Alfonso Tierno"
60 min_RO_version
= "6.0.2"
61 min_n2vc_version
= "0.0.2"
63 min_common_version
= "0.1.19"
68 ping_interval_pace
= (
69 120 # how many time ping is send once is confirmed all is running
71 ping_interval_boot
= 5 # how many time ping is sent when booting
73 main_config
= LcmCfg()
75 def __init__(self
, config_file
, loop
=None):
77 Init, Connect to database, filesystem storage, and messaging
78 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
85 self
.pings_not_received
= 1
86 self
.consecutive_errors
= 0
87 self
.first_start
= False
90 self
.logger
= logging
.getLogger("lcm")
92 self
.worker_id
= self
.get_process_id()
94 config
= self
.read_config_file(config_file
)
95 self
.main_config
.set_from_dict(config
)
96 self
.main_config
.transform()
97 self
.main_config
.load_from_env()
98 self
.logger
.critical("Loaded configuration:" + str(self
.main_config
.to_dict()))
99 # TODO: check if lcm_hc.py is necessary
100 self
.health_check_file
= get_health_check_file(self
.main_config
.to_dict())
101 self
.loop
= loop
or asyncio
.get_event_loop()
106 ) = self
.wim
= self
.sdn
= self
.k8scluster
= self
.vca
= self
.k8srepo
= None
109 log_format_simple
= (
110 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
112 log_formatter_simple
= logging
.Formatter(
113 log_format_simple
, datefmt
="%Y-%m-%dT%H:%M:%S"
115 if self
.main_config
.globalConfig
.logfile
:
116 file_handler
= logging
.handlers
.RotatingFileHandler(
117 self
.main_config
.globalConfig
.logfile
,
122 file_handler
.setFormatter(log_formatter_simple
)
123 self
.logger
.addHandler(file_handler
)
124 if not self
.main_config
.globalConfig
.to_dict()["nologging"]:
125 str_handler
= logging
.StreamHandler()
126 str_handler
.setFormatter(log_formatter_simple
)
127 self
.logger
.addHandler(str_handler
)
129 if self
.main_config
.globalConfig
.to_dict()["loglevel"]:
130 self
.logger
.setLevel(self
.main_config
.globalConfig
.loglevel
)
132 # logging other modules
133 for logger
in ("message", "database", "storage", "tsdb"):
134 logger_config
= self
.main_config
.to_dict()[logger
]
135 logger_module
= logging
.getLogger(logger_config
["logger_name"])
136 if logger_config
["logfile"]:
137 file_handler
= logging
.handlers
.RotatingFileHandler(
138 logger_config
["logfile"], maxBytes
=100e6
, backupCount
=9, delay
=0
140 file_handler
.setFormatter(log_formatter_simple
)
141 logger_module
.addHandler(file_handler
)
142 if logger_config
["loglevel"]:
143 logger_module
.setLevel(logger_config
["loglevel"])
144 self
.logger
.critical(
145 "starting osm/lcm version {} {}".format(lcm_version
, lcm_version_date
)
148 # check version of N2VC
149 # TODO enhance with int conversion or from distutils.version import LooseVersion
150 # or with list(map(int, version.split(".")))
151 if versiontuple(n2vc_version
) < versiontuple(min_n2vc_version
):
153 "Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
154 n2vc_version
, min_n2vc_version
157 # check version of common
158 if versiontuple(common_version
) < versiontuple(min_common_version
):
160 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
161 common_version
, min_common_version
166 self
.db
= Database(self
.main_config
.to_dict()).instance
.db
168 self
.fs
= Filesystem(self
.main_config
.to_dict()).instance
.fs
171 # copy message configuration in order to remove 'group_id' for msg_admin
172 config_message
= self
.main_config
.message
.to_dict()
173 config_message
["loop"] = self
.loop
174 if config_message
["driver"] == "local":
175 self
.msg
= msglocal
.MsgLocal()
176 self
.msg
.connect(config_message
)
177 self
.msg_admin
= msglocal
.MsgLocal()
178 config_message
.pop("group_id", None)
179 self
.msg_admin
.connect(config_message
)
180 elif config_message
["driver"] == "kafka":
181 self
.msg
= msgkafka
.MsgKafka()
182 self
.msg
.connect(config_message
)
183 self
.msg_admin
= msgkafka
.MsgKafka()
184 config_message
.pop("group_id", None)
185 self
.msg_admin
.connect(config_message
)
188 "Invalid configuration param '{}' at '[message]':'driver'".format(
189 self
.main_config
.message
.driver
192 except (DbException
, FsException
, MsgException
) as e
:
193 self
.logger
.critical(str(e
), exc_info
=True)
194 raise LcmException(str(e
))
196 # contains created tasks/futures to be able to cancel
197 self
.lcm_tasks
= TaskRegistry(self
.worker_id
, self
.logger
)
199 async def check_RO_version(self
):
203 ro_uri
= self
.main_config
.RO
.uri
207 # try new RO, if fail old RO
209 self
.main_config
.RO
.uri
= ro_uri
+ "ro"
210 ro_server
= NgRoClient(self
.loop
, **self
.main_config
.RO
.to_dict())
211 ro_version
= await ro_server
.get_version()
212 self
.main_config
.RO
.ng
= True
214 self
.main_config
.RO
.uri
= ro_uri
+ "openmano"
215 ro_server
= ROClient(self
.loop
, **self
.main_config
.RO
.to_dict())
216 ro_version
= await ro_server
.get_version()
217 self
.main_config
.RO
.ng
= False
218 if versiontuple(ro_version
) < versiontuple(min_RO_version
):
220 "Not compatible osm/RO version '{}'. Needed '{}' or higher".format(
221 ro_version
, min_RO_version
225 "Connected to RO version {} new-generation version {}".format(
226 ro_version
, self
.main_config
.RO
.ng
230 except (ROClientException
, NgRoException
) as e
:
231 self
.main_config
.RO
.uri
= ro_uri
233 traceback
.print_tb(e
.__traceback
__)
234 error_text
= "Error while connecting to RO on {}: {}".format(
235 self
.main_config
.RO
.uri
, e
238 self
.logger
.critical(error_text
)
239 raise LcmException(error_text
)
240 if last_error
!= error_text
:
241 last_error
= error_text
243 error_text
+ ". Waiting until {} seconds".format(5 * tries
)
245 await asyncio
.sleep(5)
247 async def test(self
, param
=None):
248 self
.logger
.debug("Starting/Ending test task: {}".format(param
))
250 async def kafka_ping(self
):
251 self
.logger
.debug("Task kafka_ping Enter")
252 consecutive_errors
= 0
254 kafka_has_received
= False
255 self
.pings_not_received
= 1
258 await self
.msg_admin
.aiowrite(
264 "worker_id": self
.worker_id
,
265 "version": lcm_version
,
269 # time between pings are low when it is not received and at starting
271 self
.ping_interval_boot
272 if not kafka_has_received
273 else self
.ping_interval_pace
275 if not self
.pings_not_received
:
276 kafka_has_received
= True
277 self
.pings_not_received
+= 1
278 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
279 if self
.pings_not_received
> 10:
280 raise LcmException("It is not receiving pings from Kafka bus")
281 consecutive_errors
= 0
285 except Exception as e
:
286 # if not first_start is the first time after starting. So leave more time and wait
287 # to allow kafka starts
288 if consecutive_errors
== 8 if not first_start
else 30:
290 "Task kafka_read task exit error too many errors. Exception: {}".format(
295 consecutive_errors
+= 1
297 "Task kafka_read retrying after Exception {}".format(e
)
299 wait_time
= 2 if not first_start
else 5
300 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
302 def kafka_read_callback(self
, topic
, command
, params
):
305 if topic
!= "admin" and command
!= "ping":
307 "Task kafka_read receives {} {}: {}".format(topic
, command
, params
)
309 self
.consecutive_errors
= 0
310 self
.first_start
= False
312 if command
== "exit":
313 raise LcmExceptionExit
314 elif command
.startswith("#"):
316 elif command
== "echo":
321 elif command
== "test":
322 asyncio
.Task(self
.test(params
), loop
=self
.loop
)
326 if command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
327 if params
.get("worker_id") != self
.worker_id
:
329 self
.pings_not_received
= 0
331 with
open(self
.health_check_file
, "w") as f
:
333 except Exception as e
:
335 "Cannot write into '{}' for healthcheck: {}".format(
336 self
.health_check_file
, e
341 if command
== "placement":
342 self
.ns
.update_nsrs_with_pla_result(params
)
344 elif topic
== "k8scluster":
345 if command
== "create" or command
== "created":
346 k8scluster_id
= params
.get("_id")
347 task
= asyncio
.ensure_future(self
.k8scluster
.create(params
, order_id
))
348 self
.lcm_tasks
.register(
349 "k8scluster", k8scluster_id
, order_id
, "k8scluster_create", task
352 elif command
== "delete" or command
== "deleted":
353 k8scluster_id
= params
.get("_id")
354 task
= asyncio
.ensure_future(self
.k8scluster
.delete(params
, order_id
))
355 self
.lcm_tasks
.register(
356 "k8scluster", k8scluster_id
, order_id
, "k8scluster_delete", task
360 if command
== "create" or command
== "created":
361 vca_id
= params
.get("_id")
362 task
= asyncio
.ensure_future(self
.vca
.create(params
, order_id
))
363 self
.lcm_tasks
.register("vca", vca_id
, order_id
, "vca_create", task
)
365 elif command
== "delete" or command
== "deleted":
366 vca_id
= params
.get("_id")
367 task
= asyncio
.ensure_future(self
.vca
.delete(params
, order_id
))
368 self
.lcm_tasks
.register("vca", vca_id
, order_id
, "vca_delete", task
)
370 elif topic
== "k8srepo":
371 if command
== "create" or command
== "created":
372 k8srepo_id
= params
.get("_id")
373 self
.logger
.debug("k8srepo_id = {}".format(k8srepo_id
))
374 task
= asyncio
.ensure_future(self
.k8srepo
.create(params
, order_id
))
375 self
.lcm_tasks
.register(
376 "k8srepo", k8srepo_id
, order_id
, "k8srepo_create", task
379 elif command
== "delete" or command
== "deleted":
380 k8srepo_id
= params
.get("_id")
381 task
= asyncio
.ensure_future(self
.k8srepo
.delete(params
, order_id
))
382 self
.lcm_tasks
.register(
383 "k8srepo", k8srepo_id
, order_id
, "k8srepo_delete", task
387 if command
== "instantiate":
388 # self.logger.debug("Deploying NS {}".format(nsr_id))
390 nslcmop_id
= nslcmop
["_id"]
391 nsr_id
= nslcmop
["nsInstanceId"]
392 task
= asyncio
.ensure_future(self
.ns
.instantiate(nsr_id
, nslcmop_id
))
393 self
.lcm_tasks
.register(
394 "ns", nsr_id
, nslcmop_id
, "ns_instantiate", task
397 elif command
== "terminate":
398 # self.logger.debug("Deleting NS {}".format(nsr_id))
400 nslcmop_id
= nslcmop
["_id"]
401 nsr_id
= nslcmop
["nsInstanceId"]
402 self
.lcm_tasks
.cancel(topic
, nsr_id
)
403 task
= asyncio
.ensure_future(self
.ns
.terminate(nsr_id
, nslcmop_id
))
404 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_terminate", task
)
406 elif command
== "vca_status_refresh":
408 nslcmop_id
= nslcmop
["_id"]
409 nsr_id
= nslcmop
["nsInstanceId"]
410 task
= asyncio
.ensure_future(
411 self
.ns
.vca_status_refresh(nsr_id
, nslcmop_id
)
413 self
.lcm_tasks
.register(
414 "ns", nsr_id
, nslcmop_id
, "ns_vca_status_refresh", task
417 elif command
== "action":
418 # self.logger.debug("Update NS {}".format(nsr_id))
420 nslcmop_id
= nslcmop
["_id"]
421 nsr_id
= nslcmop
["nsInstanceId"]
422 task
= asyncio
.ensure_future(self
.ns
.action(nsr_id
, nslcmop_id
))
423 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_action", task
)
425 elif command
== "update":
426 # self.logger.debug("Update NS {}".format(nsr_id))
428 nslcmop_id
= nslcmop
["_id"]
429 nsr_id
= nslcmop
["nsInstanceId"]
430 task
= asyncio
.ensure_future(self
.ns
.update(nsr_id
, nslcmop_id
))
431 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_update", task
)
433 elif command
== "scale":
434 # self.logger.debug("Update NS {}".format(nsr_id))
436 nslcmop_id
= nslcmop
["_id"]
437 nsr_id
= nslcmop
["nsInstanceId"]
438 task
= asyncio
.ensure_future(self
.ns
.scale(nsr_id
, nslcmop_id
))
439 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_scale", task
)
441 elif command
== "heal":
442 # self.logger.debug("Healing NS {}".format(nsr_id))
444 nslcmop_id
= nslcmop
["_id"]
445 nsr_id
= nslcmop
["nsInstanceId"]
446 task
= asyncio
.ensure_future(self
.ns
.heal(nsr_id
, nslcmop_id
))
447 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_heal", task
)
449 elif command
== "migrate":
451 nslcmop_id
= nslcmop
["_id"]
452 nsr_id
= nslcmop
["nsInstanceId"]
453 task
= asyncio
.ensure_future(self
.ns
.migrate(nsr_id
, nslcmop_id
))
454 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_migrate", task
)
456 elif command
== "verticalscale":
458 nslcmop_id
= nslcmop
["_id"]
459 nsr_id
= nslcmop
["nsInstanceId"]
460 task
= asyncio
.ensure_future(self
.ns
.vertical_scale(nsr_id
, nslcmop_id
))
462 "nsr_id,nslcmop_id,task {},{},{}".format(nsr_id
, nslcmop_id
, task
)
464 self
.lcm_tasks
.register(
465 "ns", nsr_id
, nslcmop_id
, "ns_verticalscale", task
468 "LCM task registered {},{},{} ".format(nsr_id
, nslcmop_id
, task
)
471 elif command
== "show":
474 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
476 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
477 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
480 db_nsr
["operational-status"],
481 db_nsr
["config-status"],
482 db_nsr
["detailed-status"],
483 db_nsr
["_admin"]["deployed"],
484 self
.lcm_ns_tasks
.get(nsr_id
),
487 except Exception as e
:
488 print("nsr {} not found: {}".format(nsr_id
, e
))
491 elif command
== "deleted":
492 return # TODO cleaning of task just in case should be done
504 ): # "scaled-cooldown-time"
507 elif topic
== "nsi": # netslice LCM processes (instantiate, terminate, etc)
508 if command
== "instantiate":
509 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
511 nsilcmop_id
= nsilcmop
["_id"] # slice operation id
512 nsir_id
= nsilcmop
["netsliceInstanceId"] # slice record id
513 task
= asyncio
.ensure_future(
514 self
.netslice
.instantiate(nsir_id
, nsilcmop_id
)
516 self
.lcm_tasks
.register(
517 "nsi", nsir_id
, nsilcmop_id
, "nsi_instantiate", task
520 elif command
== "terminate":
521 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
523 nsilcmop_id
= nsilcmop
["_id"] # slice operation id
524 nsir_id
= nsilcmop
["netsliceInstanceId"] # slice record id
525 self
.lcm_tasks
.cancel(topic
, nsir_id
)
526 task
= asyncio
.ensure_future(
527 self
.netslice
.terminate(nsir_id
, nsilcmop_id
)
529 self
.lcm_tasks
.register(
530 "nsi", nsir_id
, nsilcmop_id
, "nsi_terminate", task
533 elif command
== "show":
536 db_nsir
= self
.db
.get_one("nsirs", {"_id": nsir_id
})
538 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
539 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
542 db_nsir
["operational-status"],
543 db_nsir
["config-status"],
544 db_nsir
["detailed-status"],
545 db_nsir
["_admin"]["deployed"],
546 self
.lcm_netslice_tasks
.get(nsir_id
),
549 except Exception as e
:
550 print("nsir {} not found: {}".format(nsir_id
, e
))
553 elif command
== "deleted":
554 return # TODO cleaning of task just in case should be done
561 ): # "scaled-cooldown-time"
563 elif topic
== "vim_account":
564 vim_id
= params
["_id"]
565 if command
in ("create", "created"):
566 if not self
.main_config
.RO
.ng
:
567 task
= asyncio
.ensure_future(self
.vim
.create(params
, order_id
))
568 self
.lcm_tasks
.register(
569 "vim_account", vim_id
, order_id
, "vim_create", task
572 elif command
== "delete" or command
== "deleted":
573 self
.lcm_tasks
.cancel(topic
, vim_id
)
574 task
= asyncio
.ensure_future(self
.vim
.delete(params
, order_id
))
575 self
.lcm_tasks
.register(
576 "vim_account", vim_id
, order_id
, "vim_delete", task
579 elif command
== "show":
580 print("not implemented show with vim_account")
583 elif command
in ("edit", "edited"):
584 if not self
.main_config
.RO
.ng
:
585 task
= asyncio
.ensure_future(self
.vim
.edit(params
, order_id
))
586 self
.lcm_tasks
.register(
587 "vim_account", vim_id
, order_id
, "vim_edit", task
590 elif command
== "deleted":
591 return # TODO cleaning of task just in case should be done
592 elif topic
== "wim_account":
593 wim_id
= params
["_id"]
594 if command
in ("create", "created"):
595 if not self
.main_config
.RO
.ng
:
596 task
= asyncio
.ensure_future(self
.wim
.create(params
, order_id
))
597 self
.lcm_tasks
.register(
598 "wim_account", wim_id
, order_id
, "wim_create", task
601 elif command
== "delete" or command
== "deleted":
602 self
.lcm_tasks
.cancel(topic
, wim_id
)
603 task
= asyncio
.ensure_future(self
.wim
.delete(params
, order_id
))
604 self
.lcm_tasks
.register(
605 "wim_account", wim_id
, order_id
, "wim_delete", task
608 elif command
== "show":
609 print("not implemented show with wim_account")
612 elif command
in ("edit", "edited"):
613 task
= asyncio
.ensure_future(self
.wim
.edit(params
, order_id
))
614 self
.lcm_tasks
.register(
615 "wim_account", wim_id
, order_id
, "wim_edit", task
618 elif command
== "deleted":
619 return # TODO cleaning of task just in case should be done
621 _sdn_id
= params
["_id"]
622 if command
in ("create", "created"):
623 if not self
.main_config
.RO
.ng
:
624 task
= asyncio
.ensure_future(self
.sdn
.create(params
, order_id
))
625 self
.lcm_tasks
.register(
626 "sdn", _sdn_id
, order_id
, "sdn_create", task
629 elif command
== "delete" or command
== "deleted":
630 self
.lcm_tasks
.cancel(topic
, _sdn_id
)
631 task
= asyncio
.ensure_future(self
.sdn
.delete(params
, order_id
))
632 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_delete", task
)
634 elif command
in ("edit", "edited"):
635 task
= asyncio
.ensure_future(self
.sdn
.edit(params
, order_id
))
636 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_edit", task
)
638 elif command
== "deleted":
639 return # TODO cleaning of task just in case should be done
640 self
.logger
.critical("unknown topic {} and command '{}'".format(topic
, command
))
642 async def kafka_read(self
):
644 "Task kafka_read Enter with worker_id={}".format(self
.worker_id
)
646 # future = asyncio.Future()
647 self
.consecutive_errors
= 0
648 self
.first_start
= True
649 while self
.consecutive_errors
< 10:
662 topics_admin
= ("admin",)
663 await asyncio
.gather(
665 topics
, self
.loop
, self
.kafka_read_callback
, from_beginning
=True
667 self
.msg_admin
.aioread(
670 self
.kafka_read_callback
,
675 except LcmExceptionExit
:
676 self
.logger
.debug("Bye!")
678 except Exception as e
:
679 # if not first_start is the first time after starting. So leave more time and wait
680 # to allow kafka starts
681 if self
.consecutive_errors
== 8 if not self
.first_start
else 30:
683 "Task kafka_read task exit error too many errors. Exception: {}".format(
688 self
.consecutive_errors
+= 1
690 "Task kafka_read retrying after Exception {}".format(e
)
692 wait_time
= 2 if not self
.first_start
else 5
693 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
695 # self.logger.debug("Task kafka_read terminating")
696 self
.logger
.debug("Task kafka_read exit")
701 self
.loop
.run_until_complete(self
.check_RO_version())
703 self
.ns
= ns
.NsLcm(self
.msg
, self
.lcm_tasks
, self
.main_config
, self
.loop
)
704 # TODO: modify the rest of classes to use the LcmCfg object instead of dicts
705 self
.netslice
= netslice
.NetsliceLcm(
706 self
.msg
, self
.lcm_tasks
, self
.main_config
.to_dict(), self
.loop
, self
.ns
708 self
.vim
= vim_sdn
.VimLcm(
709 self
.msg
, self
.lcm_tasks
, self
.main_config
.to_dict(), self
.loop
711 self
.wim
= vim_sdn
.WimLcm(
712 self
.msg
, self
.lcm_tasks
, self
.main_config
.to_dict(), self
.loop
714 self
.sdn
= vim_sdn
.SdnLcm(
715 self
.msg
, self
.lcm_tasks
, self
.main_config
.to_dict(), self
.loop
717 self
.k8scluster
= vim_sdn
.K8sClusterLcm(
718 self
.msg
, self
.lcm_tasks
, self
.main_config
.to_dict(), self
.loop
720 self
.vca
= vim_sdn
.VcaLcm(
721 self
.msg
, self
.lcm_tasks
, self
.main_config
.to_dict(), self
.loop
723 self
.k8srepo
= vim_sdn
.K8sRepoLcm(
724 self
.msg
, self
.lcm_tasks
, self
.main_config
.to_dict(), self
.loop
727 self
.loop
.run_until_complete(
728 asyncio
.gather(self
.kafka_read(), self
.kafka_ping())
732 # self.logger.debug("Terminating cancelling creation tasks")
733 # self.lcm_tasks.cancel("ALL", "create")
735 # while self.is_pending_tasks():
736 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
737 # await asyncio.sleep(2, loop=self.loop)
740 # self.lcm_tasks.cancel("ALL", "ALL")
744 self
.db
.db_disconnect()
746 self
.msg
.disconnect()
748 self
.msg_admin
.disconnect()
750 self
.fs
.fs_disconnect()
752 def read_config_file(self
, config_file
):
753 # TODO make a [ini] + yaml inside parser
754 # the configparser library is not suitable, because it does not admit comments at the end of line,
755 # and not parse integer or boolean
758 # read file as yaml format
759 config
= configparser
.ConfigParser(inline_comment_prefixes
="#")
760 config
.read(config_file
)
761 conf
= {s
: dict(config
.items(s
)) for s
in config
.sections()}
762 except Exception as e
:
763 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
764 self
.logger
.critical("Trying to load config as legacy mode")
766 with
open(config_file
) as f
:
767 conf
= yaml
.safe_load(f
)
768 # Ensure all sections are not empty
780 except Exception as e
:
781 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
786 def get_process_id():
788 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
789 will provide a random one
792 # Try getting docker id. If fails, get pid
794 with
open("/proc/self/cgroup", "r") as f
:
795 text_id_
= f
.readline()
796 _
, _
, text_id
= text_id_
.rpartition("/")
797 text_id
= text_id
.replace("\n", "")[:12]
803 return "".join(random_choice("0123456789abcdef") for _
in range(12))
808 """Usage: {} [options]
809 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
810 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
811 -h|--help: shows this help
816 # --log-socket-host HOST: send logs to this host")
817 # --log-socket-port PORT: send logs using this port (default: 9022)")
820 if __name__
== "__main__":
823 # print("SYS.PATH='{}'".format(sys.path))
824 # load parameters and configuration
830 opts
, args
= getopt
.getopt(
831 sys
.argv
[1:], "hc:", ["config=", "help", "health-check"]
833 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
836 if o
in ("-h", "--help"):
839 elif o
in ("-c", "--config"):
841 elif o
== "--health-check":
842 from osm_lcm
.lcm_hc
import health_check
844 health_check(config_file
, Lcm
.ping_interval_pace
)
845 # elif o == "--log-socket-port":
846 # log_socket_port = a
847 # elif o == "--log-socket-host":
848 # log_socket_host = a
849 # elif o == "--log-file":
852 assert False, "Unhandled option"
855 if not path
.isfile(config_file
):
857 "configuration file '{}' does not exist".format(config_file
),
863 __file__
[: __file__
.rfind(".")] + ".cfg",
867 if path
.isfile(config_file
):
871 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
875 lcm
= Lcm(config_file
)
877 except (LcmException
, getopt
.GetoptError
) as e
:
878 print(str(e
), file=sys
.stderr
)