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
32 from osm_lcm
import ns
, vim_sdn
, netslice
33 from osm_lcm
.ng_ro
import NgRoException
, NgRoClient
34 from osm_lcm
.ROclient
import ROClient
, ROClientException
37 from osm_lcm
.lcm_utils
import versiontuple
, LcmException
, TaskRegistry
, LcmExceptionExit
38 from osm_lcm
import version
as lcm_version
, version_date
as lcm_version_date
40 from osm_common
import msglocal
, msgkafka
41 from osm_common
import version
as common_version
42 from osm_common
.dbbase
import DbException
43 from osm_common
.fsbase
import FsException
44 from osm_common
.msgbase
import MsgException
45 from osm_lcm
.data_utils
.database
.database
import Database
46 from osm_lcm
.data_utils
.filesystem
.filesystem
import Filesystem
47 from os
import environ
, path
48 from random
import choice
as random_choice
49 from n2vc
import version
as n2vc_version
52 if os
.getenv("OSMLCM_PDB_DEBUG", None) is not None:
56 __author__
= "Alfonso Tierno"
57 min_RO_version
= "6.0.2"
58 min_n2vc_version
= "0.0.2"
60 min_common_version
= "0.1.19"
62 path
.expanduser("~") + "/time_last_ping"
63 ) # TODO find better location for this file
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
76 "tsdb": "lcm.prometheus",
78 # ^ contains for each section at lcm.cfg the used logger name
80 def __init__(self
, config_file
, loop
=None):
82 Init, Connect to database, filesystem storage, and messaging
83 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
90 self
.pings_not_received
= 1
91 self
.consecutive_errors
= 0
92 self
.first_start
= False
95 self
.logger
= logging
.getLogger("lcm")
97 self
.worker_id
= self
.get_process_id()
99 config
= self
.read_config_file(config_file
)
101 self
.config
["ro_config"] = {
102 "ng": config
["RO"].get("ng", False),
103 "uri": config
["RO"].get("uri"),
104 "tenant": config
.get("tenant", "osm"),
105 "logger_name": "lcm.roclient",
106 "loglevel": config
["RO"].get("loglevel", "ERROR"),
108 if not self
.config
["ro_config"]["uri"]:
109 self
.config
["ro_config"]["uri"] = "http://{}:{}/".format(
110 config
["RO"]["host"], config
["RO"]["port"]
113 "/ro" in self
.config
["ro_config"]["uri"][-4:]
114 or "/openmano" in self
.config
["ro_config"]["uri"][-10:]
116 # uri ends with '/ro', '/ro/', '/openmano', '/openmano/'
117 index
= self
.config
["ro_config"]["uri"][-1].rfind("/")
118 self
.config
["ro_config"]["uri"] = self
.config
["ro_config"]["uri"][index
+ 1]
120 self
.loop
= loop
or asyncio
.get_event_loop()
125 ) = self
.wim
= self
.sdn
= self
.k8scluster
= self
.vca
= self
.k8srepo
= None
128 log_format_simple
= (
129 "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
131 log_formatter_simple
= logging
.Formatter(
132 log_format_simple
, datefmt
="%Y-%m-%dT%H:%M:%S"
134 config
["database"]["logger_name"] = "lcm.db"
135 config
["storage"]["logger_name"] = "lcm.fs"
136 config
["message"]["logger_name"] = "lcm.msg"
137 if config
["global"].get("logfile"):
138 file_handler
= logging
.handlers
.RotatingFileHandler(
139 config
["global"]["logfile"], maxBytes
=100e6
, backupCount
=9, delay
=0
141 file_handler
.setFormatter(log_formatter_simple
)
142 self
.logger
.addHandler(file_handler
)
143 if not config
["global"].get("nologging"):
144 str_handler
= logging
.StreamHandler()
145 str_handler
.setFormatter(log_formatter_simple
)
146 self
.logger
.addHandler(str_handler
)
148 if config
["global"].get("loglevel"):
149 self
.logger
.setLevel(config
["global"]["loglevel"])
151 # logging other modules
152 for k1
, logname
in self
.cfg_logger_name
.items():
153 config
[k1
]["logger_name"] = logname
154 logger_module
= logging
.getLogger(logname
)
155 if config
[k1
].get("logfile"):
156 file_handler
= logging
.handlers
.RotatingFileHandler(
157 config
[k1
]["logfile"], maxBytes
=100e6
, backupCount
=9, delay
=0
159 file_handler
.setFormatter(log_formatter_simple
)
160 logger_module
.addHandler(file_handler
)
161 if config
[k1
].get("loglevel"):
162 logger_module
.setLevel(config
[k1
]["loglevel"])
163 self
.logger
.critical(
164 "starting osm/lcm version {} {}".format(lcm_version
, lcm_version_date
)
167 # check version of N2VC
168 # TODO enhance with int conversion or from distutils.version import LooseVersion
169 # or with list(map(int, version.split(".")))
170 if versiontuple(n2vc_version
) < versiontuple(min_n2vc_version
):
172 "Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
173 n2vc_version
, min_n2vc_version
176 # check version of common
177 if versiontuple(common_version
) < versiontuple(min_common_version
):
179 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
180 common_version
, min_common_version
185 self
.db
= Database(config
).instance
.db
187 self
.fs
= Filesystem(config
).instance
.fs
190 # copy message configuration in order to remove 'group_id' for msg_admin
191 config_message
= config
["message"].copy()
192 config_message
["loop"] = self
.loop
193 if config_message
["driver"] == "local":
194 self
.msg
= msglocal
.MsgLocal()
195 self
.msg
.connect(config_message
)
196 self
.msg_admin
= msglocal
.MsgLocal()
197 config_message
.pop("group_id", None)
198 self
.msg_admin
.connect(config_message
)
199 elif config_message
["driver"] == "kafka":
200 self
.msg
= msgkafka
.MsgKafka()
201 self
.msg
.connect(config_message
)
202 self
.msg_admin
= msgkafka
.MsgKafka()
203 config_message
.pop("group_id", None)
204 self
.msg_admin
.connect(config_message
)
207 "Invalid configuration param '{}' at '[message]':'driver'".format(
208 config
["message"]["driver"]
211 except (DbException
, FsException
, MsgException
) as e
:
212 self
.logger
.critical(str(e
), exc_info
=True)
213 raise LcmException(str(e
))
215 # contains created tasks/futures to be able to cancel
216 self
.lcm_tasks
= TaskRegistry(self
.worker_id
, self
.logger
)
218 async def check_RO_version(self
):
222 ro_uri
= self
.config
["ro_config"]["uri"]
224 # try new RO, if fail old RO
226 self
.config
["ro_config"]["uri"] = ro_uri
+ "ro"
227 ro_server
= NgRoClient(self
.loop
, **self
.config
["ro_config"])
228 ro_version
= await ro_server
.get_version()
229 self
.config
["ro_config"]["ng"] = True
231 self
.config
["ro_config"]["uri"] = ro_uri
+ "openmano"
232 ro_server
= ROClient(self
.loop
, **self
.config
["ro_config"])
233 ro_version
= await ro_server
.get_version()
234 self
.config
["ro_config"]["ng"] = False
235 if versiontuple(ro_version
) < versiontuple(min_RO_version
):
237 "Not compatible osm/RO version '{}'. Needed '{}' or higher".format(
238 ro_version
, min_RO_version
242 "Connected to RO version {} new-generation version {}".format(
243 ro_version
, self
.config
["ro_config"]["ng"]
247 except (ROClientException
, NgRoException
) as e
:
248 self
.config
["ro_config"]["uri"] = ro_uri
250 traceback
.print_tb(e
.__traceback
__)
251 error_text
= "Error while connecting to RO on {}: {}".format(
252 self
.config
["ro_config"]["uri"], e
255 self
.logger
.critical(error_text
)
256 raise LcmException(error_text
)
257 if last_error
!= error_text
:
258 last_error
= error_text
260 error_text
+ ". Waiting until {} seconds".format(5 * tries
)
262 await asyncio
.sleep(5)
264 async def test(self
, param
=None):
265 self
.logger
.debug("Starting/Ending test task: {}".format(param
))
267 async def kafka_ping(self
):
268 self
.logger
.debug("Task kafka_ping Enter")
269 consecutive_errors
= 0
271 kafka_has_received
= False
272 self
.pings_not_received
= 1
275 await self
.msg_admin
.aiowrite(
281 "worker_id": self
.worker_id
,
282 "version": lcm_version
,
286 # time between pings are low when it is not received and at starting
288 self
.ping_interval_boot
289 if not kafka_has_received
290 else self
.ping_interval_pace
292 if not self
.pings_not_received
:
293 kafka_has_received
= True
294 self
.pings_not_received
+= 1
295 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
296 if self
.pings_not_received
> 10:
297 raise LcmException("It is not receiving pings from Kafka bus")
298 consecutive_errors
= 0
302 except Exception as e
:
303 # if not first_start is the first time after starting. So leave more time and wait
304 # to allow kafka starts
305 if consecutive_errors
== 8 if not first_start
else 30:
307 "Task kafka_read task exit error too many errors. Exception: {}".format(
312 consecutive_errors
+= 1
314 "Task kafka_read retrying after Exception {}".format(e
)
316 wait_time
= 2 if not first_start
else 5
317 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
319 def kafka_read_callback(self
, topic
, command
, params
):
322 if topic
!= "admin" and command
!= "ping":
324 "Task kafka_read receives {} {}: {}".format(topic
, command
, params
)
326 self
.consecutive_errors
= 0
327 self
.first_start
= False
329 if command
== "exit":
330 raise LcmExceptionExit
331 elif command
.startswith("#"):
333 elif command
== "echo":
338 elif command
== "test":
339 asyncio
.Task(self
.test(params
), loop
=self
.loop
)
343 if command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
344 if params
.get("worker_id") != self
.worker_id
:
346 self
.pings_not_received
= 0
348 with
open(health_check_file
, "w") as f
:
350 except Exception as e
:
352 "Cannot write into '{}' for healthcheck: {}".format(
358 if command
== "placement":
359 self
.ns
.update_nsrs_with_pla_result(params
)
361 elif topic
== "k8scluster":
362 if command
== "create" or command
== "created":
363 k8scluster_id
= params
.get("_id")
364 task
= asyncio
.ensure_future(self
.k8scluster
.create(params
, order_id
))
365 self
.lcm_tasks
.register(
366 "k8scluster", k8scluster_id
, order_id
, "k8scluster_create", task
369 elif command
== "delete" or command
== "deleted":
370 k8scluster_id
= params
.get("_id")
371 task
= asyncio
.ensure_future(self
.k8scluster
.delete(params
, order_id
))
372 self
.lcm_tasks
.register(
373 "k8scluster", k8scluster_id
, order_id
, "k8scluster_delete", task
377 if command
== "create" or command
== "created":
378 vca_id
= params
.get("_id")
379 task
= asyncio
.ensure_future(self
.vca
.create(params
, order_id
))
380 self
.lcm_tasks
.register("vca", vca_id
, order_id
, "vca_create", task
)
382 elif command
== "delete" or command
== "deleted":
383 vca_id
= params
.get("_id")
384 task
= asyncio
.ensure_future(self
.vca
.delete(params
, order_id
))
385 self
.lcm_tasks
.register("vca", vca_id
, order_id
, "vca_delete", task
)
387 elif topic
== "k8srepo":
388 if command
== "create" or command
== "created":
389 k8srepo_id
= params
.get("_id")
390 self
.logger
.debug("k8srepo_id = {}".format(k8srepo_id
))
391 task
= asyncio
.ensure_future(self
.k8srepo
.create(params
, order_id
))
392 self
.lcm_tasks
.register(
393 "k8srepo", k8srepo_id
, order_id
, "k8srepo_create", task
396 elif command
== "delete" or command
== "deleted":
397 k8srepo_id
= params
.get("_id")
398 task
= asyncio
.ensure_future(self
.k8srepo
.delete(params
, order_id
))
399 self
.lcm_tasks
.register(
400 "k8srepo", k8srepo_id
, order_id
, "k8srepo_delete", task
404 if command
== "instantiate":
405 # self.logger.debug("Deploying NS {}".format(nsr_id))
407 nslcmop_id
= nslcmop
["_id"]
408 nsr_id
= nslcmop
["nsInstanceId"]
409 task
= asyncio
.ensure_future(self
.ns
.instantiate(nsr_id
, nslcmop_id
))
410 self
.lcm_tasks
.register(
411 "ns", nsr_id
, nslcmop_id
, "ns_instantiate", task
414 elif command
== "terminate":
415 # self.logger.debug("Deleting NS {}".format(nsr_id))
417 nslcmop_id
= nslcmop
["_id"]
418 nsr_id
= nslcmop
["nsInstanceId"]
419 self
.lcm_tasks
.cancel(topic
, nsr_id
)
420 task
= asyncio
.ensure_future(self
.ns
.terminate(nsr_id
, nslcmop_id
))
421 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_terminate", task
)
423 elif command
== "vca_status_refresh":
425 nslcmop_id
= nslcmop
["_id"]
426 nsr_id
= nslcmop
["nsInstanceId"]
427 task
= asyncio
.ensure_future(
428 self
.ns
.vca_status_refresh(nsr_id
, nslcmop_id
)
430 self
.lcm_tasks
.register(
431 "ns", nsr_id
, nslcmop_id
, "ns_vca_status_refresh", task
434 elif command
== "action":
435 # self.logger.debug("Update NS {}".format(nsr_id))
437 nslcmop_id
= nslcmop
["_id"]
438 nsr_id
= nslcmop
["nsInstanceId"]
439 task
= asyncio
.ensure_future(self
.ns
.action(nsr_id
, nslcmop_id
))
440 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_action", task
)
442 elif command
== "update":
443 # self.logger.debug("Update NS {}".format(nsr_id))
445 nslcmop_id
= nslcmop
["_id"]
446 nsr_id
= nslcmop
["nsInstanceId"]
447 task
= asyncio
.ensure_future(self
.ns
.update(nsr_id
, nslcmop_id
))
448 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_update", task
)
450 elif command
== "scale":
451 # self.logger.debug("Update NS {}".format(nsr_id))
453 nslcmop_id
= nslcmop
["_id"]
454 nsr_id
= nslcmop
["nsInstanceId"]
455 task
= asyncio
.ensure_future(self
.ns
.scale(nsr_id
, nslcmop_id
))
456 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_scale", task
)
458 elif command
== "migrate":
460 nslcmop_id
= nslcmop
["_id"]
461 nsr_id
= nslcmop
["nsInstanceId"]
462 task
= asyncio
.ensure_future(self
.ns
.migrate(nsr_id
, nslcmop_id
))
463 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_migrate", task
)
465 elif command
== "show":
468 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
470 "nsr:\n _id={}\n operational-status: {}\n config-status: {}"
471 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
474 db_nsr
["operational-status"],
475 db_nsr
["config-status"],
476 db_nsr
["detailed-status"],
477 db_nsr
["_admin"]["deployed"],
478 self
.lcm_ns_tasks
.get(nsr_id
),
481 except Exception as e
:
482 print("nsr {} not found: {}".format(nsr_id
, e
))
485 elif command
== "deleted":
486 return # TODO cleaning of task just in case should be done
496 ): # "scaled-cooldown-time"
499 elif topic
== "nsi": # netslice LCM processes (instantiate, terminate, etc)
500 if command
== "instantiate":
501 # self.logger.debug("Instantiating Network Slice {}".format(nsilcmop["netsliceInstanceId"]))
503 nsilcmop_id
= nsilcmop
["_id"] # slice operation id
504 nsir_id
= nsilcmop
["netsliceInstanceId"] # slice record id
505 task
= asyncio
.ensure_future(
506 self
.netslice
.instantiate(nsir_id
, nsilcmop_id
)
508 self
.lcm_tasks
.register(
509 "nsi", nsir_id
, nsilcmop_id
, "nsi_instantiate", task
512 elif command
== "terminate":
513 # self.logger.debug("Terminating Network Slice NS {}".format(nsilcmop["netsliceInstanceId"]))
515 nsilcmop_id
= nsilcmop
["_id"] # slice operation id
516 nsir_id
= nsilcmop
["netsliceInstanceId"] # slice record id
517 self
.lcm_tasks
.cancel(topic
, nsir_id
)
518 task
= asyncio
.ensure_future(
519 self
.netslice
.terminate(nsir_id
, nsilcmop_id
)
521 self
.lcm_tasks
.register(
522 "nsi", nsir_id
, nsilcmop_id
, "nsi_terminate", task
525 elif command
== "show":
528 db_nsir
= self
.db
.get_one("nsirs", {"_id": nsir_id
})
530 "nsir:\n _id={}\n operational-status: {}\n config-status: {}"
531 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
534 db_nsir
["operational-status"],
535 db_nsir
["config-status"],
536 db_nsir
["detailed-status"],
537 db_nsir
["_admin"]["deployed"],
538 self
.lcm_netslice_tasks
.get(nsir_id
),
541 except Exception as e
:
542 print("nsir {} not found: {}".format(nsir_id
, e
))
545 elif command
== "deleted":
546 return # TODO cleaning of task just in case should be done
552 ): # "scaled-cooldown-time"
554 elif topic
== "vim_account":
555 vim_id
= params
["_id"]
556 if command
in ("create", "created"):
557 if not self
.config
["ro_config"].get("ng"):
558 task
= asyncio
.ensure_future(self
.vim
.create(params
, order_id
))
559 self
.lcm_tasks
.register(
560 "vim_account", vim_id
, order_id
, "vim_create", task
563 elif command
== "delete" or command
== "deleted":
564 self
.lcm_tasks
.cancel(topic
, vim_id
)
565 task
= asyncio
.ensure_future(self
.vim
.delete(params
, order_id
))
566 self
.lcm_tasks
.register(
567 "vim_account", vim_id
, order_id
, "vim_delete", task
570 elif command
== "show":
571 print("not implemented show with vim_account")
574 elif command
in ("edit", "edited"):
575 if not self
.config
["ro_config"].get("ng"):
576 task
= asyncio
.ensure_future(self
.vim
.edit(params
, order_id
))
577 self
.lcm_tasks
.register(
578 "vim_account", vim_id
, order_id
, "vim_edit", task
581 elif command
== "deleted":
582 return # TODO cleaning of task just in case should be done
583 elif topic
== "wim_account":
584 wim_id
= params
["_id"]
585 if command
in ("create", "created"):
586 if not self
.config
["ro_config"].get("ng"):
587 task
= asyncio
.ensure_future(self
.wim
.create(params
, order_id
))
588 self
.lcm_tasks
.register(
589 "wim_account", wim_id
, order_id
, "wim_create", task
592 elif command
== "delete" or command
== "deleted":
593 self
.lcm_tasks
.cancel(topic
, wim_id
)
594 task
= asyncio
.ensure_future(self
.wim
.delete(params
, order_id
))
595 self
.lcm_tasks
.register(
596 "wim_account", wim_id
, order_id
, "wim_delete", task
599 elif command
== "show":
600 print("not implemented show with wim_account")
603 elif command
in ("edit", "edited"):
604 task
= asyncio
.ensure_future(self
.wim
.edit(params
, order_id
))
605 self
.lcm_tasks
.register(
606 "wim_account", wim_id
, order_id
, "wim_edit", task
609 elif command
== "deleted":
610 return # TODO cleaning of task just in case should be done
612 _sdn_id
= params
["_id"]
613 if command
in ("create", "created"):
614 if not self
.config
["ro_config"].get("ng"):
615 task
= asyncio
.ensure_future(self
.sdn
.create(params
, order_id
))
616 self
.lcm_tasks
.register(
617 "sdn", _sdn_id
, order_id
, "sdn_create", task
620 elif command
== "delete" or command
== "deleted":
621 self
.lcm_tasks
.cancel(topic
, _sdn_id
)
622 task
= asyncio
.ensure_future(self
.sdn
.delete(params
, order_id
))
623 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_delete", task
)
625 elif command
in ("edit", "edited"):
626 task
= asyncio
.ensure_future(self
.sdn
.edit(params
, order_id
))
627 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_edit", task
)
629 elif command
== "deleted":
630 return # TODO cleaning of task just in case should be done
631 self
.logger
.critical("unknown topic {} and command '{}'".format(topic
, command
))
633 async def kafka_read(self
):
635 "Task kafka_read Enter with worker_id={}".format(self
.worker_id
)
637 # future = asyncio.Future()
638 self
.consecutive_errors
= 0
639 self
.first_start
= True
640 while self
.consecutive_errors
< 10:
653 topics_admin
= ("admin",)
654 await asyncio
.gather(
656 topics
, self
.loop
, self
.kafka_read_callback
, from_beginning
=True
658 self
.msg_admin
.aioread(
661 self
.kafka_read_callback
,
666 except LcmExceptionExit
:
667 self
.logger
.debug("Bye!")
669 except Exception as e
:
670 # if not first_start is the first time after starting. So leave more time and wait
671 # to allow kafka starts
672 if self
.consecutive_errors
== 8 if not self
.first_start
else 30:
674 "Task kafka_read task exit error too many errors. Exception: {}".format(
679 self
.consecutive_errors
+= 1
681 "Task kafka_read retrying after Exception {}".format(e
)
683 wait_time
= 2 if not self
.first_start
else 5
684 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
686 # self.logger.debug("Task kafka_read terminating")
687 self
.logger
.debug("Task kafka_read exit")
692 self
.loop
.run_until_complete(self
.check_RO_version())
694 self
.ns
= ns
.NsLcm(self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
)
695 self
.netslice
= netslice
.NetsliceLcm(
696 self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
, self
.ns
698 self
.vim
= vim_sdn
.VimLcm(self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
)
699 self
.wim
= vim_sdn
.WimLcm(self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
)
700 self
.sdn
= vim_sdn
.SdnLcm(self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
)
701 self
.k8scluster
= vim_sdn
.K8sClusterLcm(
702 self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
704 self
.vca
= vim_sdn
.VcaLcm(self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
)
705 self
.k8srepo
= vim_sdn
.K8sRepoLcm(
706 self
.msg
, self
.lcm_tasks
, self
.config
, self
.loop
709 self
.loop
.run_until_complete(
710 asyncio
.gather(self
.kafka_read(), self
.kafka_ping())
714 # self.logger.debug("Terminating cancelling creation tasks")
715 # self.lcm_tasks.cancel("ALL", "create")
717 # while self.is_pending_tasks():
718 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
719 # await asyncio.sleep(2, loop=self.loop)
722 # self.lcm_tasks.cancel("ALL", "ALL")
726 self
.db
.db_disconnect()
728 self
.msg
.disconnect()
730 self
.msg_admin
.disconnect()
732 self
.fs
.fs_disconnect()
734 def read_config_file(self
, config_file
):
735 # TODO make a [ini] + yaml inside parser
736 # the configparser library is not suitable, because it does not admit comments at the end of line,
737 # and not parse integer or boolean
739 # read file as yaml format
740 with
open(config_file
) as f
:
741 conf
= yaml
.load(f
, Loader
=yaml
.Loader
)
742 # Ensure all sections are not empty
755 # read all environ that starts with OSMLCM_
756 for k
, v
in environ
.items():
757 if not k
.startswith("OSMLCM_"):
759 subject
, _
, item
= k
[7:].lower().partition("_")
762 if subject
in ("ro", "vca"):
763 # put in capital letter
764 subject
= subject
.upper()
766 if item
== "port" or subject
== "timeout":
767 conf
[subject
][item
] = int(v
)
769 conf
[subject
][item
] = v
770 except Exception as e
:
772 "skipping environ '{}' on exception '{}'".format(k
, e
)
775 # backward compatibility of VCA parameters
777 if "pubkey" in conf
["VCA"]:
778 conf
["VCA"]["public_key"] = conf
["VCA"].pop("pubkey")
779 if "cacert" in conf
["VCA"]:
780 conf
["VCA"]["ca_cert"] = conf
["VCA"].pop("cacert")
781 if "apiproxy" in conf
["VCA"]:
782 conf
["VCA"]["api_proxy"] = conf
["VCA"].pop("apiproxy")
784 if "enableosupgrade" in conf
["VCA"]:
785 conf
["VCA"]["enable_os_upgrade"] = conf
["VCA"].pop("enableosupgrade")
786 if isinstance(conf
["VCA"].get("enable_os_upgrade"), str):
787 if conf
["VCA"]["enable_os_upgrade"].lower() == "false":
788 conf
["VCA"]["enable_os_upgrade"] = False
789 elif conf
["VCA"]["enable_os_upgrade"].lower() == "true":
790 conf
["VCA"]["enable_os_upgrade"] = True
792 if "aptmirror" in conf
["VCA"]:
793 conf
["VCA"]["apt_mirror"] = conf
["VCA"].pop("aptmirror")
796 except Exception as e
:
797 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
801 def get_process_id():
803 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
804 will provide a random one
807 # Try getting docker id. If fails, get pid
809 with
open("/proc/self/cgroup", "r") as f
:
810 text_id_
= f
.readline()
811 _
, _
, text_id
= text_id_
.rpartition("/")
812 text_id
= text_id
.replace("\n", "")[:12]
818 return "".join(random_choice("0123456789abcdef") for _
in range(12))
823 """Usage: {} [options]
824 -c|--config [configuration_file]: loads the configuration file (default: ./lcm.cfg)
825 --health-check: do not run lcm, but inspect kafka bus to determine if lcm is healthy
826 -h|--help: shows this help
831 # --log-socket-host HOST: send logs to this host")
832 # --log-socket-port PORT: send logs using this port (default: 9022)")
835 if __name__
== "__main__":
838 # print("SYS.PATH='{}'".format(sys.path))
839 # load parameters and configuration
845 opts
, args
= getopt
.getopt(
846 sys
.argv
[1:], "hc:", ["config=", "help", "health-check"]
848 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
851 if o
in ("-h", "--help"):
854 elif o
in ("-c", "--config"):
856 elif o
== "--health-check":
857 from osm_lcm
.lcm_hc
import health_check
859 health_check(health_check_file
, Lcm
.ping_interval_pace
)
860 # elif o == "--log-socket-port":
861 # log_socket_port = a
862 # elif o == "--log-socket-host":
863 # log_socket_host = a
864 # elif o == "--log-file":
867 assert False, "Unhandled option"
870 if not path
.isfile(config_file
):
872 "configuration file '{}' does not exist".format(config_file
),
878 __file__
[: __file__
.rfind(".")] + ".cfg",
882 if path
.isfile(config_file
):
886 "No configuration file 'lcm.cfg' found neither at local folder nor at /etc/osm/",
890 lcm
= Lcm(config_file
)
892 except (LcmException
, getopt
.GetoptError
) as e
:
893 print(str(e
), file=sys
.stderr
)